repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
amirgeva/commit
mainwindow.py
Python
gpl-2.0
3,793
0.001318
from PyQt5 import QtCore, QtGui, QtWidgets import os import scanner import utils class MainWindow(QtWidgets.QMainWindow): def __init__(self, root, parent=None): super(MainWindow, self).__init__(parent) datadir = os.path.dirname(os.path.abspath(__file__)) self.setWindowIcon(QtGui.QIcon(os.p...
newSize.setWidth(s.width()) self.fileTable.resize(newSize) def update(self): self.updating = True newRows = scanner.scan(self.root, self.dataDict) modified = False if len(newRows) < len(self.dataDict): modified = True else: for row
in newRows: if row[0] in self.dataDict: if row != self.dataDict.get(row[0]): modified = True break else: modified = True break if modified: self.dataDict = {} ...
FedericoMuciaccia/SistemiComplessi
html/altro/output html.py
Python
mit
710
0.014085
from IPython.core.display import HTML styles = open("./styles/custom.css", "r").read() HTML(styles) from IPython.core.display import HTML import urllib2 HTML(urllib2.urlopen("http://nbviewer.jupyter.org/github/CamDavidson
Pilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/styles/custom.css").read())
from IPython.display import HTML table = "<table><tr><th>bar</th><th>bar</th></tr><tr><td>foo</td><td>foo</td></tr></table>" HTML(table) from IPython.core.display import HTML import urllib2 HTML(urllib2.urlopen('http://bit.ly/1Bf5Hft').read()) # http://nbviewer.jupyter.org/ # This web site does not host notebooks, it...
e-koch/VLA_Lband
CASA_functions/imaging_utils.py
Python
mit
13,393
0.000075
''' Scripts for automatically setting clean parameters ''' import numpy as np from warnings import warn import os from taskinit import tb from cleanhelper import cleanhelper def set_imagermode(vis, source): tb.open(os.path.join(vis, 'FIELD')) names = tb.getcol('NAME') tb.close() moscount = 0 ...
lengths.append(length) all_lengths = np.array(all_lengths) return all_lengths def get_mosaic_info(vis, spw, sourceid=None, intent='TARGET', pblevel=0.1): ''' Return image size based on mosaic fields Parameters ---------- vis : str MS Name ...
str, optional The field names used will contain sourceid. intent : str, optional Use every field with the given intent (wildcards used by default). pblevel : float between 0 and 1 PB level that defines the edges of the mosaic. ''' mytb = au.createCas...
warmsea/tc-srm
srm147/CCipher.py
Python
mit
389
0.002571
""" http://community.topcoder.com/stat?c=pro
blem_statement&pm=1667 Single Round Match 147 Round 1 - Division II, Level One """ class CCipher: def decode(self, cipherText, shift): a = ord('A
') decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)] plain = [chr(decoder[ord(c) - a]) for c in cipherText] return ''.join(plain)
ziirish/burp-ui
burpui/api/misc.py
Python
bsd-3-clause
35,390
0.000961
# -*- coding: utf8 -*- """ .. module:: burpui.api.misc :platform: Unix :synopsis: Burp-UI misc api module. .. moduleauthor:: Ziirish <hi+burpui@ziirish.me> """ from . import api, cache_key, force_refresh from ..engines.server import BUIServer # noqa from .custom import fields, Resource from .client import Cl...
ng() if isinstance(running, dict): if server and client not in running[server]: self.abort( 404, "'{}' not found in the list of running clients for '{}'".format( client, server
), ) else: found = False for (_, cls) in running.items(): if client in cls: found = True break if not found: api.bort(404, "'{}' not fou...
sveetch/Sveetoy
project/pages.py
Python
mit
1,627
0.004302
# -*- coding: utf-8 -*- """ The project pages map for project """ import io import os from optimus.builder.pages import PageViewBase from optimus.conf import settings from project import __version__ as sveetoy_version from project.sitemap import PageSitemap, tree_from_directory_structure from py_css_styleguide.model...
return context class PageWithSitemap(BasicPage): """ Page view aware of sitemap """
sitemap = {} def get_context(self): context = super(PageWithSitemap, self).get_context() context.update({ 'site_sitemap': self.sitemap, }) return context # Enabled pages to build #PAGES = PageSitemap(sitemap_tree, PageWithSitemap).ressources PAGES = [ BasicPage(...
DiCarloLab-Delft/PycQED_py3
pycqed/measurement/distortions_models.py
Python
mit
507
0.003945
import numpy as np import lmfit class SinglePoleStep: def __init__(self, amp, tau): self.amp_s = amp self.tau_s = tau self.amp_k = self.amp_s/(self.amp_s-1.) self.tau_k = (1.-self.amp_s)*self.tau_s self.step_func = lambda t: 1.-self.amp_s*np.exp(-t/self.tau_s) self...
l_step_func = lambda t: 1.+self.amp_k*np.exp(-t/self.tau_k) self.step_model = lmfit.Model(self.step_func
) self.kernel_step_model = lmfit.Model(self.kernel_step_func)
pra85/calibre
src/calibre/gui2/init.py
Python
gpl-3.0
14,621
0.003967
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import functools from PyQt4.Qt import (Qt, QApplication, QStackedWidget, QMenu, QTimer, QSize, QSizePolicy, QStatu...
ow(0) if v is self.library_view and v.row_count() == 0: self.book_details.reset_info() # }}} class LibraryWi
dget(Splitter): # {{{ def __init__(self, parent): orientation = Qt.Vertical if config['gui_layout'] == 'narrow': orientation = Qt.Horizontal if is_widescreen() else Qt.Vertical idx = 0 if orientation == Qt.Vertical else 1 size = 300 if orientation == Qt.Vertical else 55...
secworks/aes
src/model/python/aes_key_gen.py
Python
bsd-2-clause
22,825
0.003374
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #======================================================================= # # aes_key_gen.py # ------------- # Simple, pure Python test model of the AES key generation. # This one is operating on 32 bit words. The key generation # supports 128 and 256 bit keys. # # # Author...
d4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3...
xoolive/facile
examples/xkcd.py
Python
lgpl-3.0
1,013
0
from facile import constraint, solve_all, sum, variable # http://xkcd.com/287/ # Some amount (or none) of each dish should be ordered to give a total of # exactly 15.05 price = [215, 275, 335, 355, 420, 580] total = 1505 products = [ "mixed fruit", "french fries", "side salad", "host wings", "mo...
antity = [variable(range(10)) for p in price] constraint(sum(q * p for q, p in zip(quantity, price)) == total) def print_current(sol): print("Solution after {} backtracks:".format(sol.backtrack)) for i, x in enumerate(sol.solution): if x == 0: continue print(" {} × {:<20} : {:>5}...
: {:>5}".format(total)) res = solve_all(quantity, backtrack=True, on_solution=print_current) print("Total of {} backtracks".format(res[-1].backtrack))
SCPR/accountability-tracker
bakery/management/commands/publish.py
Python
gpl-2.0
10,130
0
import os import boto import time import hashlib import logging import mimetypes from django.conf import settings from optparse import make_option from multiprocessing.pool import ThreadPool from django.core.urlresolvers import get_callable from django.core.management.base import BaseCommand, CommandError logger = logg...
ey_dict(self): """ Retrieves and returns a dictionary of keys in our s3 bucket. The keys will be the name (or path) of the key and the value will be
the Key object from boto. """ return dict((key.name, key) for key in self.bucket.list()) def get_local_file_list(self): """ Walk the local build directory and create a list of relative and absolute paths to files. """ file_list = [] for (dirpath, dir...
elebihan/qemu-tools-elb
qemu_tools_elb/utils.py
Python
gpl-3.0
1,838
0.001088
# -*- coding: utf-8 -*- # # This file is part of qemu-tools-elb # # Copyright (C) 2014 Eric Le Bihan <eric.le.bihan.dev@free.fr> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version ...
14 Eric Le Bihan <eric.le.bihan.dev@free.fr> :license: GPLv3+ """ import os from gettext import bindtextdomain, textdomain def get_data_dir(): """Returns the data directory. rtype: str """ root_dir = os.path.dirname(os.path.abspath(__file__)) root_dir = os.path.join(root_dir, '..') if os....
h.join(root_dir, 'data') else: upper, lower = root_dir.split('lib') data_dir = os.path.join(upper, 'share', 'qemu-tools-elb') return os.path.normpath(data_dir) def setup_i18n(): """Set up internationalization.""" root_dir = os.path.dirname(os.path.abspath(__file__)) if 'lib' not in...
ativelkov/murano-api
murano/packages/mpl_package.py
Python
apache-2.0
3,570
0
# Copyright (c) 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this fil
e except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr
iting, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import sys import yaml import mura...
XeCycle/indico
indico/web/flask/blueprints/category_management.py
Python
gpl-3.0
3,446
0.006094
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
categoryMod.RHCategoryCreation, methods=('GET', 'POST')) category_mgmt.add_url_rule('!/category/<categId>/create/subcategory/save', 'categoryCreation-create', categoryMod.RHCategoryPerformCreation, methods=('POST',)) # Event creation is in event.creation # General...
ryMod.RHCategoryModification) category_mgmt.add_url_rule('/data', 'categoryDataModification', categoryMod.RHCategoryDataModif, methods=('GET', 'POST')) category_mgmt.add_url_rule('/data/save', 'categoryDataModification-modify', categoryMod.RHCategoryPerformModification, ...
girardinsamuel/minierp-django
setup.py
Python
gpl-3.0
841
0
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-minierp', ve...
amuel Girardin', author_email='samuelgirardin@gmail.com', classifiers=[ 'Env
ironment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.10', # replace "X.Y" as appropriate 'Programming Language :: Python 2', ], )
movsesyan1970/pg_repo
db_update.py
Python
bsd-3-clause
5,556
0.049136
#!/usr/bin/env python import argparse import sys import re import settings import psycopg2 import imp ######################################################################################## class UpdSource(): def __init__(self,in_source,last_update): self.upd_dict=dict() self.source=in_source self.src_handl...
d" else: print "Last applied update: upd_{0}".format(last_applied) conn.close() sys.exit() us=UpdSource(args.source,last_applied) upd_dict=us.get_upd_dict() ap=Apply(conn) ap.iterate_over(upd_di
ct,args.dry_run) if not args.dry_run: print "Applied {0} updates out of {1}".format(ap.get_num_applied(),us.get_total_updates())
openstack/tripleo-common
releasenotes/source/conf.py
Python
apache-2.0
8,655
0
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
tion', u'2016, TripleO Developers', 'tripleo-commonReleaseNotes', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domai
n_i
LyuGGang/Flask-BotoSQS
flask_boto_sqs.py
Python
mit
1,590
0.002516
# -*- coding: utf-8 -*- """ Boto3 SQS integration for Flask by LyuGGang (https://github.com/LyuGGang/Flask-BotoSQS) """ import flask from boto3.session import Session class FlaskBotoSQS(object): def __init__(self, app=None, conf_key=None): """ :type app: flask.Flask :parm str conf_key: Key...
pp is not None: self.init_app(app, conf_key) def init_app(self, app, c
onf_key=None): """ :type app: flask.Flask :parm str conf_key: Key of flask config. """ conf_key = conf_key or self.conf_key or 'FLASK_BOTO_SQS' self.conf_key = conf_key conf = app.config[conf_key] if not isinstance(conf, dict): raise TypeError(...
annavonzansen/exams
exams/management/commands/importcandidates.py
Python
gpl-2.0
931
0.003222
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import ugettext as _ from exams.models import import_candidates class Command(BaseCommand): args = '<candidates.xml>' help = _('Imports candidates from XML file') def handle(self, *args, **options):
filename = args[0] print _("Importing candidates from %(filename)s") % { 'filename': filename, } imported = import_candidates(filename=filename) if type(imported) == dict: if len(imported['messages']) > 0: for m in imported['messages']:...
kkuunnddaannkk/vispy
vispy/geometry/meshdata.py
Python
bsd-3-clause
22,746
0.000176
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from ..ext.six.moves import xrange def _fix_colors(colors): colors = np.asarray(colors) if colors.ndim not in (2, 3): raise ValueError('c...
vertex_colors, indexed='faces') if face_colors is not None: self.set_face_colors(face_colors, indexed='faces') else: self.set_vertices(vertices) self.set_faces(faces) if vertex_colors is not None: self.se...
def get_faces(self): """Array (Nf, 3) of vertex indices, three per triangular face. If faces have not been computed for this mesh, returns None. """ return self._faces def get_edges(self, indexed=None): """Edges of the mesh Parameters ----------...
ptt/pttbbs
daemon/commentd/commentd.py
Python
gpl-2.0
6,640
0.003313
#!/usr/bin/env python from builtins import zip, map import struct import collections import sys import logging import os from gevent import monkey; monkey.patch_all() import gevent import gevent.server import leveldb # Ref: ../../include/pttstruct.h IDLEN = 12 FNLEN = 28 COMMENTLEN = 80 # Ref: ../../include/daemon...
'#%08d' % (query.start + 1) data = g_db.get(key) logging.debug(" => %r", UnpackComment(data)) return UnpackComment(data) def LoadCommentCount(query): key = '%s/%s' % (query.board, query.file) num = int(g
_db.get(key) or '0') logging.debug('LoadCommentCount: key: %s, value: %r', key, g_db.get(key)) return num def MarkCommentDeleted(query): logging.debug("MarkCommentDeleted: %r", query) key = '%s/%s' % (query.board, query.file) num = int(g_db.get(key) or '0') if query.start >= num: return...
mvantellingen/django-healthchecks
src/django_healthchecks/checker.py
Python
mit
3,175
0.000315
import base64 import functools import inspect import requests from django.conf import settings from django.utils.encoding import force_str from django.utils.module_loading import import_string class PermissionDenied(Exception): pass def create_report(request=None): """Run all checks and return a tuple cont...
has_error = True return report, not has_error def create_service_result(servic
e, request=None): functions = list(_get_check_functions(name=service, request=request)) if not functions: return check_func = functions[0][1] result = check_func() or False return result def _get_check_functions(name=None, request=None): checks = _get_registered_health_checks() if...
Astroxslurg/interlecture
interlecture/interauth/migrations/0001_initial.py
Python
mit
905
0.00221
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-25 18:48 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migratio...
able_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserActivation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('activation_key', models.CharFi...
imeField()), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ]
thisisshi/cloud-custodian
c7n/ctx.py
Python
apache-2.0
4,915
0.000407
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import time import uuid import os from c7n.output import ( api_stats_outputs, blob_outputs, log_outputs, metrics_outputs, sys_stats_outputs, tracer_outputs) from c7n.utils import reset_session_cache, dumps, local_s...
self.execution_id = str(uuid.uuid4()) @property def log_dir(self): return self.output.root_dir def __enter__(self): self.initialize() self.session_factory.pol
icy_name = self.policy.name self.sys_stats.__enter__() self.output.__enter__() self.logs.__enter__() if self.output_logs: self.output_logs.__enter__() self.api_stats.__enter__() self.tracer.__enter__() # Api stats and user agent modification by polic...
dannytpeck/python-arcade-game
pygame_base_template.py
Python
gpl-2.0
1,492
0.018767
""" Show how to use a sprite backed by a graphic. Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc """ import pygame # Define some colors BLACK = ( 0, 0, 0) WHITE = ...
ge how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): # User d
id something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop # --- Game logic should go here # --- Drawing code should go here # First, clear the screen to white. Don't put other drawing commands # above this, or th...
arve0/example_lessons
src/python/lessons/Turtle Power/Club Leader Resources/DrawingShapes-triangle.py
Python
cc0-1.0
128
0
from turtle import * shape("turtle")
forward(100) left(120) forward(100) left(
120) forward(100) left(120) done()
ruchikd/Algorithms
Python/findEndianness/findEndianness.py
Python
gpl-3.0
111
0.063063
import sys def main(): print sys.b
yteorder print hex(42) print bin(42) if __name__ == '__main__'
: main()
bhzunami/Immo
immo/scikit/scripts/Overfit_underfit.py
Python
mit
1,611
0.002483
import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score np.random.seed(0) n_samples = 30 degrees = [1, 4, 15] true_fun = lambda X...
polynomial_features = PolynomialFeatures(degree=degrees[i], i
nclude_bias=False) linear_regression = LinearRegression() pipeline = Pipeline([("polynomial_features", polynomial_features), ("linear_regression", linear_regression)]) pipeline.fit(X[:, np.newaxis], y) # Evaluate the models using crossvalidation scores = cross_val_score(pip...
dhermes/google-cloud-python
vision/google/cloud/vision_v1/__init__.py
Python
apache-2.0
1,393
0
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
RRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers im...
t as iac from google.cloud.vision_v1.gapic import product_search_client class ProductSearchClient(product_search_client.ProductSearchClient): __doc__ = product_search_client.ProductSearchClient.__doc__ enums = enums @add_single_feature_methods class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClie...
lmregus/Portfolio
python/exercism/allergies/allergies.py
Python
mit
766
0.001305
######################### # # # Developer: Luis Regus # # Date: 11/23/15 # # # ######################### class Allergies: ''' Custom object used to represent a list of allergies ''' allergies = {'eggs': 1, 'peanuts': 2, ...
': 16, 'chocolate': 32, 'pol
len': 64, 'cats': 128} def __init__(self, val): self.lst = list() for k, v in self.allergies.items(): if v & val: self.lst.append(k) def is_allergic_to(self, k_allergy): return k_allergy in self.lst
LandRegistry/lc-public-api
application/routes.py
Python
mit
8,175
0.002324
from application import app from flask import Response, request import json import logging import requests import traceback import kombu import re import uuid import getpass from datetime import datetime from jsonschema import Draft4Validator name_schema = { "type": "object", "properties": { "forename...
n(json_data['residence']) > 0: errors.append({ 'location': '', 'error_message': "'residence' may not be supplied when 'address_withheld' is true" }) if len(errors) > 0: data = { 'errors': errors, } if 'application_ref' in json_data: ...
logging.info("T:{} Invalid submission: {}".format(transaction_id, body)) return Response(body, status=400, mimetype='application/json') url = app.config['B2B_PROCESSOR_URL'] + '/bankruptcies' headers = { 'Content-Type': 'application/json', 'X-Transaction-ID': transaction_id, '...
uwescience/pulse2percept
examples/stimuli/plot_video_stim.py
Python
bsd-3-clause
5,013
0.000199
# -*- coding: utf-8 -*- """ =============================================================================== Generating a stimulus from a video =============================================================================== *This example shows how to use videos as input stimuli for a retinal implant.* Loading a video ...
tim = p2p.stimuli.videos.VideoStimulus("path-to-video.mp4") There is an example video that is pre-installed with pulse2percept. You can load it like this. """ # sphinx_gallery_thumbnail_number = 1 impo
rt pulse2percept as p2p import numpy as np video = p2p.stimuli.BostonTrain(as_gray=True) print(video) ############################################################################## # There is a lot of useful information in this output. # # Firstly, note that ``vid_shape`` gives the dimension of the original video in ...
synappio/swagger-pyramid
swagger/lib.py
Python
apache-2.0
1,633
0.001225
from formencode import validators as fev from dateutil import parser class DateTime(fev.FancyValidator): def _to_python(self, value, state=None): return parser.parse(value) def _from_python(self, value, state=None): return value.isoformat() class Object(fev.FancyValidator): '''Basic do...
-time', 'object' ]) model_deps = {} for key, model in models.items(): assert model['id'] == key, 'Model name/id mismatch: %s != %s' % ( model['id'], key) model_deps[key] = set(model_depends(model)) while model_deps: len_yielded = len(yielded) for key...
model_deps.items(): if not deps - yielded: yielded.add(key) yield models[key] model_deps.pop(key) if len(yielded) == len_yielded: import ipdb; ipdb.set_trace(); assert len(yielded) > len_yielded, \ "Can't make forward p...
DLRSP/django-sp
src/socialprofile/decorators.py
Python
mit
465
0
from functools import wraps from django.shortcuts import render from django.template import RequestContext # ToDo: not needed !? def r
ender_to(tpl): def decorator(func): @wraps
(func) def wrapper(request, *args, **kwargs): out = func(request, *args, **kwargs) if isinstance(out, dict): out = render(tpl, out, RequestContext(request)) return out return wrapper return decorator
OCA/maintainer-tools
tests/test_update_pre_commit_excluded_addons.py
Python
agpl-3.0
3,933
0.001271
from __future__ import unicode_literals import subprocess import textwrap def test_update_pre_commit_excluded_addons(tmp_path): pre_commit = tmp_path / ".pre-commit-config.yaml" pre_commit.write_text( textwrap.dedent( """\ exclude: | (?x) ...
le and addon2, addon3 not installable m3.write_text("{'installable': False}") subprocess.check_call(["oca-update-pre-commit-excluded-addons"], cwd=str(tmp_path)) assert pre_commit.read_text() == textwrap.dedent( """\ exclude: | (?x) # NOT INSTALLABLE ADDONS ...
xclude default_language_version: python: python3 """ ) def test_update_pre_commit_excluded_addons_subdir(tmp_path): pre_commit = tmp_path / ".pre-commit-config.yaml" pre_commit.write_text( textwrap.dedent( """\ exclude: | ...
appleseedhq/gaffer
python/GafferTest/BlockedConnectionTest.py
Python
bsd-3-clause
2,869
0.032067
########################################################################## # # Copyright (c) 2012, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
sertEqual( self.numCalls, 1 ) with Gaffer.BlockedConnection( c ) : s() self.assertEqual( self.numCalls, 1 ) s() self.assertEqual( self.numCalls, 2 ) def testReentrant( self ) : self.numCalls = 0 def f() : self.numCalls += 1 s = Gaffer.Signal0() c = s.connect( f ) s() self.assertEqual( ...
lf.assertEqual( self.numCalls, 1 ) with Gaffer.BlockedConnection( c ) : s() self.assertEqual( self.numCalls, 1 ) s() self.assertEqual( self.numCalls, 2 ) with Gaffer.BlockedConnection( c ) : s() self.assertEqual( self.numCalls, 2 ) with Gaffer.BlockedConnection( c ) : s() self.assertEq...
antivirtel/Flexget
flexget/plugins/api/series.py
Python
mit
36,378
0.002309
from __future__ import unicode_literals, division, absolute_import import copy import datetime from math import ceil from flask import jsonify from flask import request from flask_restplus import inputs from sqlalchemy.orm.exc import NoResultFound from flexget.api import api, APIResource, ApiClient from flexget.even...
schema = { 'type': 'object', 'properties': { 'shows': { 'type': 'array', 'items': show_object }, 'number_of_shows': {'type': 'integer'} } } def get_release_details(release): release_item = { 'release_id': release.id, 'release_title': rele...
e.downloaded, 'release_quality': release.quality.name, 'release_proper_count': release.proper_count, 'release_first_seen': release.first_seen, 'release_episode_id': release.episode_id, } return release_item def get_episode_details(episode): episode_item = { 'episode...
dustywind/bachelor-thesis
impl/recommender/vector/idf/inversedocumentfrequencyvectorcreator.py
Python
mit
2,882
0.00347
import math from ..df import DocumentFrequencyVectorCreator from . import InverseDocumentFrequencyVector class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator): """Creates inverse-document-frequency vectors Inherits from :class:`recommender.vector.abstractvector.VectorCreator` :par...
_create_log_function(conn) values = self._get_vector_values_from_db(cursor) for value in [] if values is None else values: vector.add_to_vector(value) return vector def _get_vector_values_from_db(self, c): c.execute( ''' SELECT ...
ncy] ; ''') vector_values = [] for result in c.fetchall(): vector_values.append((result[0], result[1], result[2])) pass return None if not vector_values else vector_values def _create_log_function(self, conn): conn.create_function(...
simbtrix/mxnix
project/materialLawEditor/logarithmInformation.py
Python
gpl-3.0
3,830
0.0047
''' Created on 13.09.2016 @author: mkennert ''' from kivy.properties import StringProperty from materialLawEditor.ainformation import AInformation from ownComponents.design import Design from ownComponents.numpad import Numpad from ownComponents.ownButton import OwnButton from ownComponents.ownLabel import...
pupNumpad = OwnPopup(content=self.numpad) ''' create the gui of the information, where you can change the properties of the quadratic-function ''' def create_information(self): self.create_btns()
self.add_widget(OwnLabel(text=self.functionStr)) self.add_widget(self.btnExponential) self.add_widget(OwnLabel(text=self.aStr)) self.add_widget(self.aBtn) self.add_widget(OwnLabel(text=self.bStr)) self.add_widget(self.bBtn) self.add_base_btns() ...
carlos-ferras/Sequence-ToolKit
controller/gensec/dialogs/processes/posl.py
Python
gpl-3.0
6,732
0.001931
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from functools import partial from PyQt5 import QtWidgets, QtCore from controller.gensec.dialogs.processes.information import Information from view.dialogs.base_dialog import BaseDialog from view.gensec.dialogs.processes.ui_posl ...
n == 2: self.during_stimulation.setValue(during - 1) else: self.after_stimulation.setValue(after - 1) else: self.channels_calculation = before + during + after self.channels.setText(str(self.channels_calculation)) self.updateTimePer...
(self): data = "POSL, " + \ str(self.ligth_source.currentText()) + ", " + \ str(self.optical_power.value()) + "%" all_ = { "id": self.id, "light_source": str(self.ligth_source.currentText()), "start_optical_power": self.optical_power.val...
Ultimaker/Uranium
tests/Settings/TestContainerQuery.py
Python
lgpl-3.0
1,534
0
# Copyright (c) 2018 Ultimaker B.V. # Uranium is released under the terms of the LGPLv3 or higher. import pytest from UM.Settings.ContainerQuery import ContainerQuery def test_matchMultipleTokens(): cq = ContainerQuery(None) # Test #1: if property_name doesn't exist, it will return False result = cq._m...
token, match "property_name": "name", "value": "[abc|123|test|456]", }, "match": True, }, {"input": {"metadata": {"name": "test"}, # Multiple token, no match "property_name": "name"
, "value": "[abc|_test_|test2|tst]", }, "match": False, }, ] for test_case in test_cases: result = cq._matchRegMultipleTokens(**test_case["input"]) if test_case["match"]: assert result is not None else: asse...
dtaylor84/pysnapsync
pysnapsync/tests/test_dummy.py
Python
gpl-3.0
370
0
# co
ding=utf-8 """Dummy test. Pointless dummy test. """ from __future__ import absolute_import from __future__ import print_function from __future__ import division # import pysnapsync.server # import pysnapsync.client def inc(arg): """Return arg incremented by one."""
return arg + 1 def test_answer(): """Assert 3+1 == 4.""" assert inc(3) == 4
agdsn/pycroft
pycroft/lib/finance.py
Python
apache-2.0
41,063
0.002752
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import csv import difflib import logging import operator import re from datetime import datetime, date, timedelt...
sqlalchemy import func, between, cast from sqlalchemy import or_, and_, literal, select, exists, not_, \ text, future from sqlalchemy.orm import aliased, contains_eager, joinedload, Session from sqlalchemy.orm.exc import NoResultFound from pycroft import config from pycroft.helpers.d
ate import diff_month, last_day_of_month from pycroft.helpers.i18n import deferred_gettext, gettext from pycroft.helpers.interval import ( closed, Bound, Interval, IntervalSet, UnboundedInterval, closedopen) from pycroft.helpers.utc import with_min_time, with_max_time from pycroft.lib.exc import PycroftLibException...
plotly/python-api
packages/python/plotly/plotly/validators/histogram/marker/colorbar/tickfont/_size.py
Python
mit
541
0
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="histogram.marker.colorbar.tickfo
nt", **kwargs
): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 1), role=kwargs.pop("role", "style"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/graph_objs/layout/template/data/_heatmapgl.py
Python
mit
40
0
from p
lotly.graph_objs import Heatmapg
l
gwr/samba
source4/scripting/python/samba/samdb.py
Python
gpl-3.0
28,037
0.002853
#!/usr/bin/env python # Unix SMB/CIFS implementation. # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010 # Copyrig
ht (C) Matthias Dieter Wallnoefer 2009 # # Based on the original in EJS: # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version ...
ersion. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public Licens...
dmuhamedagic/crmsh
crmsh/lock.py
Python
gpl-2.0
5,141
0.00214
# Copyright (C) 2020 Xin Liang <XLiang@suse.com> # See COPYING for license information. import re import time from contextlib import contextmanager from . import utils from . import config from .msg import common_warn class SSHError(Exception): """ Custom exception for ssh error """ class ClaimLockEr...
directory" MKDIR_CMD = "mkdir {}".format(LOCK_DIR) RM_CMD = "rm -rf {}".form
at(LOCK_DIR) def __init__(self): """ Init function """ # only the lock owner can unlock self.lock_owner = False def _run(self, cmd): """ Run command on local """ return utils.get_stdout_stderr(cmd) def _create_lock_dir(self): ...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/cliff/tests/test_formatters_yaml.py
Python
mit
1,048
0
#!/usr/bin/env python from six import StringIO import yaml from cliff.formatters import yaml_format import mock def test_yaml_format_one(): sf = yaml_format.YAMLFormatter() c = ('a', 'b', 'c', 'd') d = ('A', 'B', 'C', '"escape me"') expected = { 'a': 'A', 'b': 'B', 'c': 'C', ...
al = yaml.safe_load(output.getvalue()) assert expected == actual def test_yaml_format_list(): s
f = yaml_format.YAMLFormatter() c = ('a', 'b', 'c') d = ( ('A1', 'B1', 'C1'), ('A2', 'B2', 'C2'), ('A3', 'B3', 'C3') ) expected = [ {'a': 'A1', 'b': 'B1', 'c': 'C1'}, {'a': 'A2', 'b': 'B2', 'c': 'C2'}, {'a': 'A3', 'b': 'B3', 'c': 'C3'} ] output = S...
mozilla/spark
apps/users/models.py
Python
bsd-3-clause
13,725
0.009253
import datetime from django.db import models, IntegrityError from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.urlresolvers import reverse as django_reverse from django.utils.http import urlquote from django.conf import settings from tower import ugettext as _, ...
letion information. Used to render both desktop and mobile collapsing challenge lists. """ return utils.get_profile_levels(self) @property def new_challenge_count(self): """Returns the number of newly available challenges in the user's current level.""" if self.new_c...
_count = utils.CHALLENGE_COUNT_PER_LVL[self.level-1] completed_challenge_count = len(CompletedChallenge.objects.filter(profile=self, challenge__level=self.level)) return challenge_count - completed_challenge_count ...
wawiesel/BootsOnTheGround
external/TriBITS/tribits/python_utils/CMakeBinaries.py
Python
mit
4,584
0.010253
# @HEADER # ************************************************************************ # # TriBITS: Tribal Build, Integrate, and Test System # Copyright 2013 Sandia Corporation # # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains certain ri...
c + "-Linux-i386.tar.gz"),\ ('darwin', cmake_baseurl + "/v2.8/cmake-" + cmake_version_rc + "-Darwin-universal.tar.gz"),\ ('win32', cmake_baseurl + "/v2.8/cmake-" + cmake_version_rc + "-win32-x86.zip"),\ ) # Latest verified build for vdir "vCVS" -- detected automatically # cmake_dev_binaries = (\ ('linux2', c...
ake-" + cmake_version_dev + "-Linux-i386.tar.gz"),\ ('darwin', cmake_baseurl + "/vCVS/cmake-" + cmake_version_dev + "-Darwin-universal.tar.gz"),\ ('win32', cmake_baseurl + "/vCVS/cmake-" + cmake_version_dev + "-win32-x86.zip"),\ )
chipaca/snapcraft
snapcraft/internal/db/migration.py
Python
gpl-3.0
3,728
0.000536
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2020 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
'migration' table.""" migration_table = self.db.table("migration") migration_table.insert( { "schema_version": self.SCHEMA_VERSION, "snapcraft_version": self._snapcraft_version, "timestamp": datetime.utcnow().isoformat() + "Z", } ...
method def _migrate(self) -> None: """Per-migration implementation.""" ... def apply(self) -> int: """Apply migration, if determined to be necessary. Returns current schema version.""" control_record = self._query_control_record() current_schema_version = contro...
nashby/sublime_config
new_file_syntax.py
Python
mit
1,254
0
''' Stores syntax file from last activated view and reuses this for a new view. @author: Oktay Acikalin <ok@ryotic.de> @license: MIT (http://www.opensource.org/licenses/mit-license.php) @since: 2011-03-05 @todo: Remove odd workaround below when/if "on_deactivated", "on_new" and "on_activated" events get fire...
buffer_id() self.new_buffers.append(view.buffer_id()) def on_activated(self, view): # print 'on_activated', self.last_syntax, view.buffer_id() if view.buffer_id() in self.new_buffers: if self.last_syntax: view.set_syntax_file(self.last_syntax) self.ne...
if view.buffer_id() not in self.new_buffers: self.last_syntax = view.settings().get('syntax')
mitsei/dlkit
dlkit/records/assessment/analytic/irt.py
Python
mit
7,495
0.001868
""" Basic IRT support for assessment items """ from dlkit.json_.osid.metadata import Metadata from dlkit.abstract_osid.assessment import record_templates as abc_assessment_records from dlkit.abstract_osid.osid.errors import IllegalState, InvalidArgument from ...osid.base_records import DecimalValuesRecord,\ Deci...
value,
match) def clear_maximum_difficulty_terms(self): """stub""" self._my_osid_query._clear_maximum_terms('decimalValues.difficulty') def match_minimum_discrimination(self, value, match): """stub""" self._my_osid_query._match_minimum_decimal('decimalValues.discrimin...
luckydonald/python-utils
luckydonaldUtils/logger/__init__.py
Python
gpl-2.0
17,417
0.002813
# -*- coding: utf-8 -*- import logging as _logging import sys __author__ = 'luckydonald' __all__ = ["logging", "ColoredFormatter", "ColoredStreamHandler", "LevelByNameFilter"] DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" class ColoredFormatter(_logging.Formatter): class Color(object): """ utility...
append( "{color_on}{inverse_on}{level_filler}{inverse_off}{color_off} {color_on}{message}{color_off}{background_off}{all_off}".format( level_filler=level_filler, message=line, date=timestamp, date_filler=timestamp_filler, process_thread_part=process_th...
lse # end for return "\n".join(lines) # end def def __init__(self, date_formatter=None): super(ColoredFormatter, self).__init__(datefmt=date_formatter) self.color_instance = self.Color(self) def colored(self, record): return self.color_instance.color...
beckenkamp/weatherbot
index.py
Python
gpl-3.0
7,204
0.001944
import os import traceback import json import requests from flask import Flask, request from cities_list import CITIES from messages import get_message, search_keyword token = os.environ.get('FB_ACCESS_TOKEN') api_key = os.environ.get('WEATHER_API_KEY') app = Flask(__name__) def location_quick_reply(sender, text=N...
et_message('error')) send_message(message) # Send location button payload = location_quick_reply(sender) send_message(payload) return 'Ok' # If text not in city list...
essage = search_keyword(text) if chat_message: # if found keyword, reply with chat stuff message = send_text(sender, chat_message) send_message(message) else: message = send_text(sender, get_message('not-a-c...
eplanet/diffbuilder
test/__init__.py
Python
gpl-2.0
25
0
__author__ = 'donstrat
a'
Georacer/last_letter
documentation/source/conf.py
Python
gpl-3.0
11,461
0.005933
# -*- coding: utf-8 -*- # # MAVProxy documentation build configuration file, created by # sphinx-quickstart on Wed Aug 19 05:17:36 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
ies to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be ...
will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in th...
GoogleCloudPlatform/training-data-analyst
quests/dei/census/custom_transforms.py
Python
apache-2.0
1,287
0.003108
from sklearn.base import BaseEstimator, TransformerMixin import numpy as np class PositionalSelector(BaseEstimator, TransformerMixin): def __init__(self, positions): self.positions = positions de
f fit(self, X, y=None): return self def transform(self, X): return np.array(X)[:, self.positions] class StripString(BaseEstimator, TransformerMixin): def fit(self, X, y=None): return self def transform(self, X): strip = np.vectorize(str.strip) return strip(np.arra...
seEstimator, TransformerMixin): def fit(self, X, y=None): self.values = [] for c in range(X.shape[1]): Y = X[:, c] values = {v: i for i, v in enumerate(np.unique(Y))} self.values.append(values) return self def transform(self, X): X = np.array(...
blueprinthealth/gargoyle
gargoyle/apps.py
Python
apache-2.0
417
0
try: from django.apps import AppConfig except ImportError: pass else: class GargoyleAppConfig(AppConfig): name = 'gargoyle' def ready(self): try: import nex
us except ImportError: pass else: from gargoyle.nexus_modules import GargoyleMod
ule nexus.site.register(GargoyleModule, 'gargoyle')
HEPData/hepdata-validator
testsuite/test_full_submission_validator.py
Python
gpl-2.0
18,250
0.005973
import os import pytest from hepdata_validator.full_submission_validator import FullSubmissionValidator, SchemaType @pytest.fixture(scope="module") def data_path(): base_dir = os.path.dirname(os.path.realpath(__file__)) return os.path.join(base_dir, 'test_data') @pytest.fixture() def validator_v0(): r...
== {} validator_v1.print_errors('notanarchive') out, err = capsys.readouterr() lines = out.splitlines() assert lines[0].strip() == "error - File notanarchive does not exist." # Invalid zip (not a zip) file = os.path.join(data_path, 'valid_submission.yaml') is_valid = validator_v1.validate(...
assert not is_valid assert validator_v1.valid_files == {} validator_v1.print_errors(file) out, err = capsys.readouterr() lines = out.splitlines() assert lines[0].strip() == f"error - Unable to extract file {file}. Error was: Unknown archive format '{file}'" def test_missing_submission(validator_...
stuart-knock/tvb-library
tvb/tests/library/simulator/history_test.py
Python
gpl-2.0
4,478
0.00268
# -*- coding: utf-8 -*- # # # TheVirtualBrain-Scientific Package. This package holds all simulators, and # analysers necessary to run brain-simulations. You can use it stand alone or # in conjunction with TheVirtualBrain-Framework Package. See content of the # documentation-folder for more details. See also http://www....
e details. You should have received a copy of the GNU General # Public License along with this program; if not, you can download it here # http://www.gnu.org/licenses/old-licenses/gpl-2.0 # # # CITATION: # When using The Virtual Brain for scientific publications, please cite i
t as follows: # # Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide, # Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013) # The Virtual Brain: a simulator of primate brain network dynamics. # Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010) # # """ Test history in...
jbasko/configmanager
configmanager/schema_parser.py
Python
mit
2,942
0.002039
import collections.abc import inspect import six from .base import BaseItem, BaseSection def parse_config_schema(schema, parent_section=None, root=None): if root: parent_section = root is_valid_config_root_schema = ( inspect.ismodule(schema) or ( ...
tion=parent_section, root=root) if isinstance(schema, collections.abc.Sequence) and not isinstance(schema, six.string_types): if len(schema) == 0 or not isinstance(schema[0], tuple): #
Declaration of an item return parent_section.create_item(default=schema) # Pre-process all keys and discard private parts and separate out meta parts clean_schema = [] meta = {} for k, v in schema: if k.startswith('_'): continue elif...
Shinichi-Nakagawa/pitchpx
tests/pitchpx/test_mlbam_util.py
Python
mit
3,194
0.003444
#!/usr/bin/env python # -*- coding: utf-8 -*- from unittest import TestCase, main from pitchpx.mlbam_util import MlbamUtil, MlbAmHttpNotFound
__author__ = 'Shinichi Nakagawa' class TestMlbamUtil(TestCase): """ MLBAM Util Class Test """ def setUp(self): pass def tearDown(self): pass def test_get_content_200(self): """ Get html content(status:200, head:default) """ req = MlbamUtil._ge...
e, 200) self.assertEqual(req.request.headers['Accept'], 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') self.assertEqual(req.request.headers['User-Agent'], ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) ' ...
zenodo/invenio
invenio/legacy/websubmit/functions/Export_Via_SWORD.py
Python
gpl-2.0
8,575
0.010612
# This file is part of Invenio. # Copyright (C) 2010, 2011 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Inveni...
server specified in parameters. The user can specify the ## the remote collection and the cat
egories where he wants ## to put the record. ## ## Author: M. Barras ## ## PARAMETERS: - the database id of the remote server (in swrREMOTESERVER) ## - the id of the record to export ## - the remote collection url ## - t...
hrishioa/Aviato
app/views.py
Python
gpl-2.0
5,183
0.006753
from app import application from flask import render_template, flash, redirect, url_for, request, Response from datetime import datetime from kartograph import Kartograph from .forms import SearchForm import json import os import httplib2 import pycountry from aviato import * #Used as the filtering function def southe...
.join(script_dir, rel_path) with open(abs_file_path, "rb") as fp:
data = json.load(fp) fp.close() if iso_code in data: data[iso_code]["popularity"] += 100 else: data[iso_code] = {"popularity": 100} jsonFile=open(abs_file_path, "w+") jsonFile.write(json.dumps(data)) jsonFile.close() return True def get_from_json(token): #Usin...
openzim/gutenberg
gutenbergtozim/iso639.py
Python
gpl-3.0
4,373
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu import babel def language_name(code): try: return babel.Locale(code).get_language_name(code).title() except Exception: return other_language_names.get(code, code) # Autonyms unknown by babel # collected from CLDR,...
"yi": "ייִדיש", "ale": "Unangam Tunuu / Унáҥам Тунý", "ang": "Ænglisc", "arp": "Hinónoʼeitíít", "bgi": "Giangan", "ceb": "Cebuano", "csb": "kaszëbsczi", "enm": "
Middle English", "fur": "furlan", "gla": "Gàidhlig", "grc": "Ἀρχαία ἑλληνικὴ", "ilo": "Ilokano", "kha": "Khasi", "kld": "Gamilaraay", "myn": "Maya", "nah": "Nāhuatl", "nai": "Amérindien", "nap": "Napulitano", "nav": "Diné bizaad", "oji": "Ojibwe", "rmr": "Caló", } #...
sonofatailor/django-oscar
src/oscar/apps/voucher/abstract_models.py
Python
bsd-3-clause
6,712
0
from decimal import Decimal from django.core import exceptions from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from oscar.core.compat import AUTH_USER_MODEL, user_is_authenticated @py...
(c) Once per customer Oscar enforces those modes by creating VoucherApplication instances when a voucher is used for an order. """ name = models.CharField(_("Name"), max_length=
128, help_text=_("This will be shown in the checkout" " and basket once the voucher is" " entered")) code = models.CharField(_("Code"), max_length=128, db_index=True, unique=True, ...
mathstuf/sprokit
tests/bindings/python/modules/sprokit/schedulers/__init__.py
Python
bsd-3-clause
1,615
0.001238
#ckwg +28 # Copyright 2012 by Kitware, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditio...
T NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GO...
UPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from pkgutil import extend_path __path__ = extend_path(__path__, __name...
jpgerke/bds-files
chapter-10-sequence/readfq.py
Python
mit
1,633
0.014085
def readfq(fp): # this is a generator function last = None # this is a buffer keeping the last unprocessed line while True: # mimic closure; is it a bad idea? if not last: # the first record or a record following a fastq for l in fp: # search for the start of the next record ...
import sys n, slen, qlen = 0, 0, 0 fo
r name, seq, qual in readfq(sys.stdin): n += 1 slen += len(seq) qlen += qual and len(qual) or 0 print n, '\t', slen, '\t', qlen
GreenJoey/My-Simple-Programs
python/pull.py
Python
gpl-2.0
440
0.002273
from selenium.webdriver import Firefox import subprocess from json import loads import time video_list = loads(open("/home/stux/vids.json").read()) driver = Firefox() for video in video_list: print(video["video_id"]) driver.get(video['url']) url = driver.find_element_by_xpath("//video").get_attrib
ute("src") print(url) subprocess.run(["wget", "-O", video["
video_id"]+".mp4", url]) time.sleep(5) driver.close()
oshtaier/robottelo
tests/foreman/cli/test_medium.py
Python
gpl-3.0
6,174
0
# -*- encoding: utf-8 -*- # vim: ts=4 sw=4 expandtab ai """Test class for Medium CLI""" from ddt import ddt from fauxfactory import gen_string, gen_alphanumeric from robottelo.cli.factory import CLIFactoryError from robottelo.test import CLITestCase from robottelo.common.decorators import data, run_only_on from robot...
{'name': gen_string("utf8", 10)}, {'name': gen_string("alpha", 10)}, {'name': gen_string("alphanumeric", 10)}, {'name': gen_string("numeric", 10)}, {'name': gen_string("html", 10)}) def test_positive_create_1(self, test_data):
"""@Test: Check if Medium can be created @Feature: Medium - Positive Create @Assert: Medium is created """ new_obj = make_medium(test_data) # Can we find the new object? result = Medium.info({'id': new_obj['id']}) self.assertEqual(result.return_code, 0, "F...
anthraxx/pwndbg
pwndbg/strings.py
Python
mit
1,182
0.00423
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Functionality for resolving ASCII printable strings within the debuggee's address space. """ import
string import gdb import pwndbg.events import pwndbg.memory import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show pr
int elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') if message == 'unlimited': ...
myth/trashcan
it3105/project1/gui/widgets.py
Python
gpl-2.0
6,474
0.002935
# -*- coding: utf8 -*- # # Created by 'myth' on 8/26/15 from tkinter import * from algorithms import ASTAR_OPTIONS, ASTAR_HEURISTIC, GAC_DEFAULT_K, GAC_DEFAULT_CONSTRAINT from common import * def generate_menus(window): """ Takes in the window main menu bar and registers the submenus and their commands ...
e2/graphs/') ])), (u'Nonograms', sorted([ (os.path.basename(board), lambda fp=board: window.control
ler.load_nonogram(file_path=fp)) for board in fetch_files_from_dir(rootdir='module3/nonograms/') ])), (u'Run', [ (u'GO!', window.controller.solve), ]), ] # Iterate over the main menu components and their actions for name, actions in menus: menu = Menu...
foohooboo/graphql-cookiecutter
graphql_cookiecutter/buildings/migrations/0001_initial.py
Python
mit
1,612
0.003102
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-14 02:26 from __future__ import unicode_literals from django.db import migrations, mo
dels import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Building', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fals...
d(max_length=255)), ('size', models.PositiveSmallIntegerField()), ], ), migrations.CreateModel( name='Floor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('...
stettberger/metagit
setup.py
Python
gpl-3.0
1,094
0.021938
#!/usr/bin/env python3 # The version is the latest git tag import subprocess from manpage import build_manpage from setuptools import setup a = subprocess.Popen("git tag | grep '^v' | tail -n 1", shell = True, stdout = subprocess.PIPE) version = a.stdout.readline().decode().strip().replace("v", "") a.wait() setup( ...
Dietrich", author_email = "stettberger@dokucode.de", description='managing big amount of git repositories', long_description = """With metagit you can define either scm
repositories manually by setting their clone url and where to put them or you can use a repository lister, which searches on a remote site for repositories and adds them to the list. You can select some of the listed repos and execute various scm commands on the in a single step.""", license = "GPLv3", url='http:/...
CMUSV-VisTrails/WorkflowRecommendation
vistrails/db/versions/v0_3_1/__init__.py
Python
bsd-3-clause
1,861
0.022569
############################################################################### ## ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, ...
TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF TH
E USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### version = '0.3.1'
Makohoek/parameter-framework
test/functional-tests/PfwTestCase/Domains/tDomain_Elements.py
Python
bsd-3-clause
16,700
0.007365
# -*-coding:utf-8 -* # Copyright (c) 2011-2015, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, thi...
while removing domain element %s" % (self.elem_2_path) def test_addElement_Error(self): """ Testing addElement error ------------------------ Test case d
escription : ~~~~~~~~~~~~~~~~~~~~
henrysky/astroNN
astroNN/datasets/apogee.py
Python
mit
6,265
0.002235
import numpy as np from astropy import units as u from astropy.io import fits from astroNN.apogee import allstar from astroNN.apogee.downloader import apogee_distances, apogee_rc from astroNN.gaia import mag_to_absmag, mag_to_fakemag, extinction_correction from astroquery.vizier import Vizier def load_apogee_distanc...
t :param unit: which unit you want to get back - "absmag" for absolute magnitude - "fakemag" for fake magnitude - "distance" for distance in parsec :type unit: string :param cuts: Whether to cut bad data (negative parallax and percentage error more t...
: Whether to take extinction into account, only affect when unit is NOT 'distance' :type extinction: bool :param keepdims: Whether to preserve indices the same as APOGEE allstar DR14, no effect when cuts=False, set to -9999 for bad indices when cuts=True keepdims=True :type keepdims: boolean :return: nu...
Br3nda/docvert
core/document_type.py
Python
gpl-3.0
1,545
0.004531
# -*- coding: utf-8 -*- import zipfile class types(object): oasis_open_document = "oasis_open_document (any
version)" pdf = "portable document format (any version)" xml = "xml" unknown_type = "unknown file type" def detect_document_t
ype(data): data.seek(0) try: # 1. Try OpenDocument magic_bytes_open_document = 'PK' first_bytes = data.read(len(magic_bytes_open_document)) if first_bytes.decode("utf-8") == magic_bytes_open_document: # 1.1 Ok it's a ZIP but... archive = zipfile.ZipFile(data) ...
pasupulaphani/spacy-nlp-docker
thrift/spacyThrift/service.py
Python
mit
1,083
0.00277
from spacyThrift import SpacyThrift from spacyThrift.ttypes import Token from spacy.en import English from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer import loggi
ng class Handler: def __i
nit__(self, nlp): self.nlp = nlp def tag(self, sentence): document = nlp(sentence, parse=False, entity=False) return [Token(element.orth_, element.tag_, element.lemma_) for element in document] if __name__ == '__main__': logging.basicConfig() logger = logging.getLog...
samth/pycket
pycket/vector.py
Python
mit
19,695
0.00198
from pycket.values import W_MVector, W_VectorSuper, W_Fixnum, W_Flonum, W_Character, UNROLLING_CUTOFF, wrap from pycket.base import W_Object, SingletonMeta, UnhashableType from pycket import config from rpython.rlib import debug, jit, objectmodel, rerased from rpython.rlib.longlong2float import ( can_encode_int32...
ngleton if immutable: strategy = strategy.immutable_variant() storage = strategy.create_storage_for_element(elem, times) return W_Vector(strategy, storage, times) def tostring(self): l = self.strategy.ref_all(self) return "#(%s)" % " ".join([obj.tostring() for ob...
UnhashableType # def hash_equal(self, info=None): # x = 0x456789 # for i in range(self.len): # hash = self.ref(i).hash_equal(info=info) # x = intmask((1000003 * x) ^ hash) # return x def equal(self, other): # XXX could be optimized using strategies ...
leifos/ifind
ifind/search/exceptions.py
Python
mit
2,524
0.001189
# TODO When raising an exception pass a lambda function, the function being the module/path/name thing ERROR = {'default': "Unknown engine error ({0})", 400: "Bad request sent to search API ({0})", 401: "Incorrect API Key ({0})", 403: "Correct API but request refused ({0})", 404: "B...
ly loaded. """ pass class EngineAPIKeyException(SearchException): """ Thrown when an Engine's API key hasn't been provided. """ pass class QueryParamException(SearchException): """ Thrown when a query parameters incompatible or missing. """ pass cla
ss CacheConnectionException(SearchException): """ Thrown when cache connectivity error occurs. """ pass class InvalidQueryException(SearchException): """ Thrown when an invalid query is passed to engine's search method. """ pass class RateLimitException(SearchException): """ ...
orezpraw/unnaturalcode
unnaturalcode/testdata/makehuman/makehuman/plugins/0_modeling_9_custom_targets.py
Python
agpl-3.0
7,637
0.002488
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ Plugin to apply custom targets. **Project Name:** MakeHuman **Product Home Page:** http://www.makehuman.org/ **Code Home Page:** https://bitbucket.org/MakeHuman/makehuman/ **Authors:** Eduardo Menezes de Morais, Jonas Hauquier **Copyright(c):** ...
folderGroup.targetCount = 0 self.folders.append(groupBox) for f in files: i
f f.endswith(".target"): self.createTargetControls(groupBox, os.path.join(root, f)) folderGroup.targetCount += 1 for folder in self.folders: for child in folder.children: child.update() if active is not None: for child in ...
plang85/rough_surfaces
rough_surfaces/__init__.py
Python
mit
129
0
from . import analy
se from . import ge
nerate from . import params from . import contact from . import surface from . import plot
openqt/algorithms
leetcode/python/lc962-maximum-width-ramp.py
Python
gpl-3.0
1,041
0.009606
# coding=utf-8 import unittest """962. Maximum Width Ramp https://leetcode.com/problems/maximum-width-ramp/description/ Given an array `A` of integers, a _ramp_ is a tuple `(i, j)` for which `i < j` and `A[i] <= A[j]`. The width of such a ramp is `j - i`. Find the maximum width of a ramp in `A`. If one doesn't ex...
**Example 1:** **Input:** [6,0,8,2,1,5] **Output:** 4 **Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5. **Example 2:** **Input:** [9,8,1,0,1,9,4,0,4,1]
**Output:** 7 **Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1. **Note:** 1. `2 <= A.length <= 50000` 2. `0 <= A[i] <= 50000` Similar Questions: """ class Solution(object): def maxWidthRamp(self, A): """ :type A: List[in...
gimli-org/gimli
pygimli/utils/utils.py
Python
apache-2.0
22,192
0.000315
#!/usr/bin/env python # -*- coding: utf-8 -*- """Collection of several utility functions.""" from __future__ import print_function import sys from math import floor, sqrt import numpy as np import pygimli as pg class ProgressBar(object): """Animated text-based progressbar. Animated text-based progressbar f...
(np.log10(vMin)) vMax = 10**np.ceil(np.log10(vMax)) if vMax == vMin: vMax *= 10 n = np.log10(vMax / vMin) * nDec + 1 q = 10.**(1. / nDec) return vMi
n * q**np.arange(n) def grange(start, end, dx=0, n
maxim5/time-series-machine-learning
predict/model_io.py
Python
apache-2.0
1,222
0.009002
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxim' import os # noinspection PyUnresolvedReferences from models import * from util import * class ModelInfo(object): def __init__(self, path, model_class, model_params, run_params): self.path = path self.model_class = model_class self.mod...
lobals()[model_class] if strict and resolved_class is None: raise ModelN
otAvailable(model_class) return ModelInfo(path, resolved_class, model_params, run_params) def _read_dict(path): with open(path, 'r') as file_: content = file_.read() return str_to_obj(content) class ModelNotAvailable(BaseException): def __init__(self, model_class, *args): super(ModelNotAvailable, ...
reviewboard/reviewboard
reviewboard/diffviewer/tests/test_filediff.py
Python
mit
15,804
0
"""Unit tests for reviewboard.diffviewer.models.filediff.""" from itertools import chain from reviewboard.diffviewer.models import DiffSet, FileDiff from reviewboard.diffviewer.tests.test_diffutils import \ BaseFileDiffAncestorTests from reviewboard.testing import TestCase class FileDiffTests(TestCase): """...
assertEqual(diff_hash.insert_count, 1) self.assertEqual(diff_hash.delete_count, 2) def test_long_filenames(self): """Testing FileDiff with long filenames (1024 characters)""" long_filename = 'x' * 1024 filediff = FileDiff.objects.create(source_file=long_filename,
dest_file='foo', diffset=self.diffset) self.assertEqual(filediff.source_file, long_filename) def test_diff_hashes(self): """Testing FileDiff with multiple entries and same diff data deduplicates data """ ...
JioCloud/horizon
openstack_dashboard/dashboards/admin/networks/ports/forms.py
Python
apache-2.0
5,334
0
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/license
s/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitatio...
port logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api from openstack_dashboard.dashboards.project.networks.ports \ import forms as ...
getninjas/adwords-client
adwords_client/adwords_api/batch_job_service.py
Python
apache-2.0
5,359
0.002426
import logging from collections import OrderedDict import googleads from . import common as cm from adwords_client.adwords_api.operations.utils import batch_job_operation from adwords_client.internal_api.builder import OperationsBuilder logger = logging.getLogger(__name__) class BatchJobHelper(googleads.adwords.Ba...
def add_operation(self, operation): if operation['xsi_type'] in self.operations: self.operations[operation['xsi_type']].append(operation) else: self.operations[operation['xsi_type']] = [operation] self.last_operation = operation def get_temporary_id(self): ...
ons are applied in the order they appear in your upload. Therefore, when using temporary IDs, make sure the operation that creates a parent object comes before the operations that create its child objects. See: https://developers.google.com/adwords/api/docs/guides/batch-jobs?#using_temporary_ids...
Smiter/voodoo
voodoo/admin_center/forms.py
Python
gpl-2.0
8,129
0.011181
# encoding: UTF-8 from django import forms from django.forms import * from voodoo.admin_center.models import * from datetime import date, timedelta, datetime import datetime import os.path class OrderForm(forms.ModelForm): required_css_class = 'required' order_status = ModelChoiceField(OrderStatus....
}), # 'city_recipient': TextInput(attrs={'size': '63', 'maxlength': '63'}), # 'name_recipient': TextInput(attrs={'size': '63', 'maxlength': '63'}), } exclude = ('creation_date', 'order_total_pri
ce1', 'order_total_price2') ORDER_PART_CHOICES = ( (u'Запчасти', u'Запчасти'), (u'Клиенте', u'Клиенте'), (u'Авто', u'Авто'), (u'Заказе', u'Заказе'), ) class OrdersManagementForm(forms.Form): # Фильтр required_css_class = 'required' o...
dsjoerg/ggpyjobs
sc2parse/plugins.py
Python
gpl-3.0
73,851
0.013378
import re, math, itertools from collections import defaultdict, deque from sc2reader.events import * from sc2reader.utils import DepotFile from sc2reader.factories.plugins.utils import plugin from pprint import pprint from xml.dom import minidom def framestr(frame): if frame is None: return 'None' retu...
festor', [100,150,2]), (True,'infestedterran', [0,0,0]), (True,'ultralisk', [300,200,6]), (False,'nydusworm', [100,100,0]), ]}, 'HotS': {'Protoss':[ (False,'probe', [50,0,1]), (True,'zealot', [100,0,2]), (True,'sentry', [50,100,2]), (True,'stalker', [125,50,2]), (True,'hightemplar', [...
the difference. (True,'observer', [25,75,1]), (True,'warpprism', [200,0,2]), #10 (True,'phoenix', [150,100,2]), (True,'voidray', [250,150,4]), (True,'carrier', [350,250,6]), (True,'mothership', [400,400,8]), # includes mothershipcore cost (True,'photoncannon', [150,0,0]), #15 (...
MerryMage/dynarmic
externals/vixl/vixl/tools/printer.py
Python
gpl-2.0
4,754
0.012831
#!/usr/bin/env python2.7 # Copyright 2014, VIXL authors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this l...
s) def Print(string, has_lock = False): if not has_lock: __print_lock__.acquire() if __last_line_type__.value != LINE_TYPE_NONE: sys.stdout.write('\n') PrintInternal(string) sys.stdout.write('\n') __last_overwritable_line_length__.value = 0 __last_line_type__.value = LINE_TYP
E_NONE if not has_lock: __print_lock__.release() # Lines of a specific type only overwrite and can only be overwritten by lines # of the same type. def PrintOverwritableLine(string, has_lock = False, type = LINE_TYPE_NONE): if not has_lock: __print_lock__.acquire() if (__last_line_type__.value != type) and \ ...
CalebBell/thermo
thermo/utils/t_dependent_property.py
Python
mit
202,501
0.007279
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t...
rom random import uniform except: # pragma: no cover pass from math import inf, exp, log from fluids.numerics import (quad, brenth, secant, linspace, newton, polyint, polyint_over_x, derivative, trunc_log, trunc_exp, polyder, h...
differential_evolution, fit_minimization_targets, leastsq, horner_backwards, exp_horner_backwards, exp_horner_backwards_ln_tau, exp_horner_backwards_ln_tau_and_der, exp_horner_backw...
gregreen/bayestar
scripts/plotpdf.py
Python
gpl-2.0
13,899
0.042161
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # # plotpdf.py # # Copyright 2012 Greg <greg@greg-G53JW> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Founda...
converged stars.') parser.add_argument('-fig', '--figsize', type=float, nargs=2, default=(7, 5.), help='Figure width and height in inches.') parser.add_argument('-y', '--EBV-max', type=float, default=None, help='Upper limit of E(B-V) for the y-axis.') if 'python...
0]: offset = 2 else: offset = 1 args = parser.parse_args(sys.argv[offset:]) if (args.output == None) and not args.show: print 'Either --output or --show must be given.' return 0 fname = abspath(expanduser(args.input)) group = 'pixel %d-%d' % (args.loc[0], args.loc[1]) # Load in pdfs x_min, x_max = ...
openmaraude/APITaxi
APITaxi2/commands/report.py
Python
agpl-3.0
4,872
0.001853
import datetime import click from flask import Blueprint from prettytable import PrettyTable from sqlalchemy.orm import joinedload from APITaxi_models2 import ADS, Departement, Driver, Hail, Taxi, User, VehicleDescription blueprint = Blueprint('commands_report', __name__, cli_group=None) TODAY = datetime.datetime...
t, ADS.id), [
('Création', lambda ads: ads.added_at), ('Id', lambda ads: ads.id), ('Numéro', lambda ads: ads.numero), ('INSEE', lambda ads: ads.insee), ('Propriétaire', lambda ads: ads.owner_name), ('Opérateur', lambda ads: ads.added_by.email), ] ) print(...
mnahm5/django-estore
Lib/site-packages/troposphere/__init__.py
Python
mit
18,785
0.000053
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. import collections import json import re import sys import types from . import validators __version__ = "1.9.0" # constants for DeletionPolicy Delete = 'Delete' Retain = 'Retain' Snapshot = 'Snapshot'...
= ['DependsOn', 'DeletionPolicy', 'Metadata', 'UpdatePolicy', 'Condition', 'CreationPolicy']
# try to validate the title if its there if self.title: self.validate_title() # Create the list of properties set on this object by the user self.properties = {} dictname = getattr(self, 'dictname', None) if dictname: self.resource = { ...
spudmind/parlparse
pyscraper/sp/common.py
Python
agpl-3.0
3,970
0.032242
# A few functions that turn out to be useful in ma
ny of the Scottish # Parliament scraping scripts. import sys import datetime sys.path.append('../') from BeautifulSoup import NavigableString from BeautifulSoup import Tag from BeautifulSoup import Comment import re # A number of SPIDs have a 0 (zero) in place of an O (letter O), and # this converts a string contain...
Carvuh/TerminalQuest
DataFiles.py
Python
mit
1,403
0.0335
import json ## Trying to keep this as abstract as possible. ## Abstract in terms of: nothing should have to be imported into this file besides bare necessities. class GlobalDatabase: ## This class is strictly for parsing the very large json file that will be procedurally generated. # FileHandler.parseGenericJSON(...
that will be passed as the global DB. global genericData def parseGenericJSON(filename): with open(filename) as data_file: genericData = json.load(data_file) ## This is particularly only for player stats, classes, races, etc. ##
player spells, anything related to the player itself, NOT THE WORLD. def parseCharacterSheetData(fileName): with open(filename) as data_file: parsedPlayerData = json.load(data_file) ## This is for every item that can currently load into the game. ## All stats, price, and bio of every item. def parseItemSheet...
wideioltd/mongoapi2sql
mongoapi2sql/mongo_db.py
Python
gpl-2.0
3,344
0
#!/usr/bin/env python from mongo_vars import MongoVars from mongo_error import MongoError class MongoDb(MongoVars): """ The db you want to use should inherit from this class """ def __init__(self): """ Init object """ raise MongoError("__init__ not yet implemented") ...
""" raise MongoError("connect not yet implemented") def close(self, *args, **kwargs): """ Close your db """ raise MongoError("close not yet implemented") def collection_names(self): """ Return a list of all collections """ raise MongoE...
<limit> documents of the collection <name> matching <filter> """ raise MongoError("all_element not yet implemented") def create_collection(self, name, fields): """ Create the collection named <name> with a set of field <fields> """ raise MongoError("create_table not ...