code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return '/'.join(['images', str(instance.question_level), str(instance.question_level_id), binascii.b2a_hex(os.urandom(15)), filename])
def question_image_filepath(instance, filename)
Function DocString
4.486428
4.281595
1.04784
string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)]) string += '/'+datetime.datetime.now().strftime("%I:%M%p-%m-%d-%Y") string += filename return string
def submission_storage_path(instance, filename)
Function DocString
4.541359
4.41649
1.028274
if self.question_upload_type == STRING: return self.question_answer_string and True else: return self.question_upload_file and self.question_checker_script
def is_question_valid(self)
Function DocString
10.267942
8.851438
1.160031
if self.question_upload_type == STRING: return self.question_answer_string.lower().replace(' ', '') == submission_string.lower().replace(' ', '') else: raise Exception("Question not String Type.")
def check_submission(self, submission_string, submission_id)
Function DocString
8.349747
7.796119
1.071013
with script as dialogue: selection = dialogue.select(ensemble, roles=roles) if not any(selection.values()) or strict and not all(selection.values()): return try: model = dialogue.cast(selection).run() except (AttributeError, ValueError) as e: ...
def run_through(script, ensemble, roles=1, strict=False)
:py:class:`turberfield.dialogue.model.SceneScript`.
8.277582
5.373042
1.540576
if isinstance(folders, SceneScript.Folder): folders = [folders] yield from handler(references, loop=loop) matcher = Matcher(folders) performer = Performer(folders, references) while True: folder, index, script, selection, interlude = performer.next( folders, refere...
def rehearse( folders, references, handler, repeat=0, roles=1, strict=False, loop=None )
Cast a set of objects into a sequence of scene scripts. Deliver the performance. :param folders: A sequence of :py:class:`turberfield.dialogue.model.SceneScript.Folder` objects. :param references: A sequence of Python objects. :param handler: A callable object. This will be invoked with every event...
5.400499
5.349602
1.009514
return ((self._max_files_per_container == 0 or self._max_files_per_container > len(block.content_file_infos)) and (self.does_content_fit(file_info, block) or # check if we can fit some content by splitting the file # Note: i...
def can_add_new_content(self, block, file_info)
new content from file_info can be added into block iff - file count limit hasn't been reached for the block - there is enough space to completely fit the info into the block - OR the info can be split and some info can fit into the block
5.736526
5.091056
1.126785
fs_settings = deepcopy(fs_settings) # because we store some of the info, we need a deep copy ''' If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice ''' for sender_spec in fs_settings.sender_specs: r...
def do_init(self, fs_settings, global_quota)
If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice
5.386692
3.673066
1.466538
uk = ses.query(um.UserKey).filter(um.UserKey.key==key)\ .filter(um.UserKey.last_nonce<nonce * 1000).first() if not uk: return None lastnonce = copy.copy(uk.last_nonce) # TODO Update DB record in same query as above, if possible uk.last_nonce = nonce * 1000 try: s...
def get_last_nonce(app, key, nonce)
Get the last_nonce used by the given key from the SQLAlchemy database. Update the last_nonce to nonce at the same time. :param str key: the public key the nonce belongs to :param int nonce: the last nonce used by this key
4.593743
4.619761
0.994368
user = ses.query(um.User).join(um.UserKey).filter(um.UserKey.key==key).first() return user
def get_user_by_key(app, key)
An SQLAlchemy User getting function. Get a user by public key. :param str key: the public key the user belongs to
5.057042
6.516489
0.776038
balsq = ses.query(wm.Balance).filter(wm.Balance.user_id == current_user.id) if not balsq: return None bals = [json.loads(jsonify2(b, 'Balance')) for b in balsq] print "returning bals %s" % bals response = current_app.bitjws.create_response(bals) ses.close() return response
def get_balance()
Get the latest balance(s) for a single User. Currently no search parameters are supported. All balances returned. --- responses: '200': description: the User's balance(s) schema: items: $ref: '#/definitions/Balance' type: array default: des...
5.872385
7.189674
0.81678
currency = request.jws_payload['data'].get('currency') network = request.jws_payload['data'].get('network') state = 'active' if network.lower() in ps: try: addy = ps[network.lower()].get_new_address() except Exception as e: print type(e) print e ...
def create_address()
Create a new address owned by your user. --- parameters: - name: address in: body description: The pseudo-address you would like to create. i.e. currency and network required: true schema: $ref: '#/definitions/Address' responses: '200': descripti...
4.330147
4.474223
0.967799
address = request.jws_payload['data'].get('address') currency = request.jws_payload['data'].get('currency') network = request.jws_payload['data'].get('network') addysq = ses.query(wm.Address).filter(wm.Address.user_id == current_user.id) if address: addysq = addysq.filter(wm.Address.add...
def get_address()
Get one or more existing address(es) owned by your user. --- parameters: - name: address in: body description: The address you'd like to get info about. required: false schema: $ref: '#/definitions/Address' responses: '200': description: Your new...
3.161288
3.316562
0.953182
sid = request.jws_payload['data'].get('id') address = request.jws_payload['data'].get('address') currency = request.jws_payload['data'].get('currency') network = request.jws_payload['data'].get('network') #reference = request.jws_payload['data'].get('reference') ref_id = request.jws_payload...
def search_debit()
Get one to ten debit(s) for a single User. --- parameters: - name: searchcd in: body description: The Debit(s) you'd like to get. required: false schema: $ref: '#/definitions/SearchCD' responses: '200': description: the User's debit(s) sc...
2.134652
2.203431
0.968785
sid = request.jws_payload['data'].get('id') address = request.jws_payload['data'].get('address') currency = request.jws_payload['data'].get('currency') network = request.jws_payload['data'].get('network') #reference = request.jws_payload['data'].get('reference') ref_id = request.jws_payload...
def search_credit()
Get one to ten credit(s) for a single User. --- parameters: - name: searchcd in: body description: The Credit(s) you'd like to get. required: false schema: $ref: '#/definitions/SearchCD' responses: '200': description: the User's credit(s) ...
2.244813
2.31732
0.968711
lnet = network.lower() isenabled = lnet in ps fee = float(CFG.get(lnet, 'FEE')) roughAvail = str(int(ps[lnet].get_balance()['available'].to_double())) available = float(10 ** (len(roughAvail) - 1)) response = json.dumps({'isenabled': isenabled, 'fee': fee, 'availa...
def network_info(network)
Get information about the transaction network indicated. Returned info is: enabled/disabled, available hot wallet balance, & the transaction fee. --- description: Get information about the transaction network indicated. operationId: getinfo produces: - application/json parameters: ...
9.059236
9.67221
0.936625
currency = request.jws_payload['data'].get('currency') amount = Amount("%s %s" % (request.jws_payload['data'].get('amount'), currency)) address = request.jws_payload['data'].get('address') network = request.jws_payload['data'].get('network') reference = request.jw...
def create_debit()
Create a new debit, sending tokens out of your User's account. --- parameters: - name: debit in: body description: The debit you would like to create. required: true schema: $ref: '#/definitions/Debit' responses: '200': description: The Debit rec...
3.307225
3.416585
0.967991
userdict = json.loads(jsonify2(current_user.dbuser, 'User')) return current_app.bitjws.create_response(userdict)
def get_user()
Get your user object. Users may only get their own info, not others'. --- responses: '200': description: user response schema: $ref: '#/definitions/User' default: description: unexpected error schema: $ref: '#/definitions/errorModel' descr...
15.39933
26.194435
0.587886
load_jws_from_request(request) if not hasattr(request, 'jws_header') or request.jws_header is None: return "Invalid Payload", 401 username = request.jws_payload['data'].get('username') address = request.jws_header['kid'] last_nonce = request.jws_payload['iat']*1000 try: user...
def add_user()
Register a new User. Create a User and a UserKey based on the JWS header and payload. --- operationId: addUser parameters: - name: user in: body description: A new User to add required: true schema: $ref: '#/definitions/User' responses: '20...
5.088198
4.902287
1.037923
sum_ = sum(x) ratios = [] for i in x: ratio = i / sum_ ratios.append(ratio) return ratios
def compute_ratio(x)
计算每一类数据的占比
3.038171
2.819103
1.077708
from .tools.file import batch_rename_file batch_rename_file(path, f, t)
def brf(path, f, t)
batch_rename_file | 批量重命名文件
6.927365
3.92904
1.763119
proxy_type = widget_proxies.get(widget.__class__) if proxy_type is None: raise KeyError('There is no proxy type registered for %r' % widget) return proxy_type(widget)
def proxy_for(widget)
Create a proxy for a Widget :param widget: A gtk.Widget to proxy This will raise a KeyError if there is no proxy type registered for the widget type.
3.511054
3.141709
1.117562
self.update_internal(value) self.emit('changed', self.get_widget_value())
def update(self, value)
Update the widget's value
8.183062
7.563213
1.081956
self.block() self.set_widget_value(value) self.unblock()
def update_internal(self, value)
Update the widget's value without firing a changed signal
6.83342
4.94124
1.382936
if self.signal_name is not None: # None for read only widgets sid = self.widget.connect(self.signal_name, self.widget_changed) self.connections.append(sid)
def connect_widget(self)
Perform the initial connection of the widget the default implementation will connect to the widgets signal based on self.signal_name
7.361396
5.76634
1.276615
proxy = proxy_for(widget) self.add_proxy(name, proxy)
def add_proxy_for(self, name, widget)
Create a proxy for a widget and add it to this group :param name: The name or key of the proxy, which will be emitted with the changed signal :param widget: The widget to create a proxy for
5.321206
7.9198
0.671886
args, varargs, varkw, defaults = inspect.getargspec(func) f_name = func.__name__ arg2value = {} # The following closures are basically because of tuple parameter # unpacking. assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg...
def _getcallargs(func, positional, named)
Get the mapping of arguments to values. Generates a dict, with keys being the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'. A parameter for the request is injected. Returns a tuple of the dict,...
2.540208
2.435991
1.042782
# Handle the tricky case of right being a full URL tmp = urlparse.urlparse(right) if tmp.scheme or tmp.netloc: # Go ahead and use urlparse.urljoin() return urlparse.urljoin(left, right) # Check for slashes joincond = (left[-1:], right[:1]) if joincond == ('/', '/'): ...
def _urljoin(left, right)
Join two URLs. Takes URLs specified by left and right and joins them into a single URL. If right is an absolute URL, it is returned directly. This differs from urlparse.urljoin() in that the latter always chops off the left-most component of left unless it is trailed by '/', which is not the behav...
5.942855
5.189531
1.145162
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): # Process the arguments against the original function argmap, theSelf, req_name = _getcallargs(func, args, kwargs) # Build the URL url = _urljoin(theSelf._baseurl, reluri....
def restmethod(method, reluri, *qargs, **headers)
Decorate a method to inject an HTTPRequest. Generates an HTTPRequest using the given HTTP method and relative URI. If additional positional arguments are present, they are expected to be strings that name function arguments that should be included as the query parameters of the URL. If additional ...
3.58477
3.263564
1.098422
for addon_type in addon_types: addon_type(widget) for name, addon_type in named_addon_types.items(): addon_type(widget, addon_name=name)
def apply_addons(widget, *addon_types, **named_addon_types)
Apply some addons to a widget. :param widget: The widget to apply addons to. :param addon_types: A list of addon types, which will be instantiated and applied to the widget with the default name of the addon. :param named_addon_types: A named list of addons...
2.413531
2.455362
0.982964
config_dir = config.get("dp.config_dir") return os.path.join(config_dir, *endings)
def make_path(config, *endings)
Create a path based on component configuration. All paths are relative to the component's configuration directory; usually this will be the same for an entire session, but this function supuports component-specific configuration directories. Arguments: config - the configuration object for a compo...
4.627407
6.120698
0.756026
contact_item_number = len(payload) assert 2 <= contact_item_number <= 4, 'Invalid contact information format' is_primary = is_verified = None # Unpack the contact information to each component. if contact_item_number == 2: (name, value) = payload el...
def from_json(payload)
Convert the JSON expression of a contact information into an instance `Contact. @param payload: a JSON expression representing a contact information: [ type:ContactName, value:string, [is_primary:boolean, [is_verified:boolean]] ] @return: an instance `Contact`. @raise ...
3.680847
3.009939
1.222898
return obj if isinstance(obj, Contact) \ else Contact(cast.string_to_enum(obj.name, Contact.ContactName), obj.value, is_primary=obj.is_primary and cast.string_to_boolean(obj.is_primary, strict=True), is_verified=obj....
def from_object(obj)
Convert an object representing a contact information to an instance `Contact`. @param obj: an object containg the following attributes: * `name`: an item of the enumeration `ContactName` representing the type of this contact information. * `value`: value of this...
3.878683
3.263829
1.188384
user = User.objects.get(username=request.user.username) question = Question.objects.filter(question_level=question_level).filter(question_number=question_number) if int(user.profile.user_access_level) < int(question_level): content = {'user_nick':profile.user_nick, 'please ...
def post(self, request, question_level, question_number, format=None)
Use this Function to submit.
2.846714
2.842201
1.001588
user = User.objects.get(username=request.user.username) question = Question.objects.filter(question_level=question_level).filter(question_number=question_number) if int(user.profile.user_access_level) < int(question_level): content = {'user_nick':profile.user_nick, 'please m...
def post(self, request, question_level, question_number, format=None)
Use this Function to submit Comment.
3.089585
3.060526
1.009495
if args is None: args = sys.argv parser = ArgumentParser(description='Barcode scanner based on GStreamer, ' 'zbar, and gtk.') log_levels = ('critical', 'error', 'warning', 'info', 'debug', 'notset') parser.add_argument('-l', '--log-level', type=str, choices=lo...
def parse_args(args=None)
Parses arguments, returns (options, args).
2.829007
2.820279
1.003095
return ''.join([ chr(c) for c in list(itertools.chain.from_iterable( [ range(ord(x), ord(y) + 1) for (x, y) in base_offsets ])) ])
def calculate_base_sequence(base_offsets)
Return a sequence of characters corresponding to the specified base. Example:: >>> calculate_base_sequence([ ('0', '9'), ('A', 'F') ]) '0123456789ABCDEF' @param base_offsets: a list of character offsets in the form of tuples ``(x, y)`` where ``x`` corresponds to the first character...
4.142498
3.872596
1.069696
if not isinstance(value, (int, long)): raise ValueError() posix_time = int(time.mktime(datetime.datetime.now().timetuple())) nonce = hashlib.md5(str(posix_time)).hexdigest()[:nonce_length] key = int_to_key(value, base=base) return key, nonce, '%s%s%s' % (key, key_nonce_separator, nonce...
def generate_secured_key(value, key_nonce_separator='.', nonce_length=4, base=BASE62)
Generate a secured key composed of the integer value encoded in Base62 and a nonce. @param value: an integer value. @param key_nonce_separator: the character that is used to separate the key and the nonce to form the secured key. @param nonce_length: the number of characters to compose the no...
2.841692
3.018871
0.941309
def key_sequence_generator(value, base): base_length = len(base) while True: yield base[value % base_length] if value < base_length: break value /= base_length return ''.join([ c for c in key_sequence_generator(value, base) ])
def int_to_key(value, base=BASE62)
Convert the specified integer to a key using the given base. @param value: a positive integer. @param base: a sequence of characters that is used to encode the integer value. @return: a key expressed in the specified base.
3.630366
3.834809
0.946688
base_length = len(base) value = 0 for c in reversed(key): value = (value * base_length) + base.index(c) return value
def key_to_int(key, base=BASE62)
Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode the integer value. @return: the integer value corresponding to the given key. @raise ValueError: if one character of the specified key doesn't match any char...
2.727901
3.590942
0.759662
parts = secured_key.split(key_nonce_separator) if len(parts) != 2: raise ValueError('Invalid secured key format') (key, nonce) = parts if len(nonce) != nonce_length: raise ValueError('Invalid length of the key nonce') return key_to_int(key, base=base), key, nonce
def parse_secured_key(secured_key, key_nonce_separator='.', nonce_length=4, base=BASE62)
Parse a given secured key and return its associated integer, the key itself, and the embedded nonce. @param secured_key a string representation of a secured key composed of a key in Base62, a separator character, and a nonce. @param key_nonce_separator: the character that is used to separate th...
2.509841
2.412649
1.040284
def uuid4(): # Otherwise, get randomness from urandom or the 'random' module. try: import os return UUID(bytes=os.urandom(16), version=4) except Exception: import random bytes = [chr(random.randrange(256)) for i in range(16)] return UUID(bytes=bytes, ver...
Generate a random UUID.
null
null
null
def uuid5(namespace, name): from hashlib import sha1 hash = sha1(namespace.bytes + name).digest() return UUID(bytes=hash[:16], version=5)
Generate a UUID from the SHA-1 hash of a namespace UUID and a name.
null
null
null
m = TemplateManager(args.hosts) t = m.get(args.name) if t: print(json.dumps(t, indent=2)) else: sys.exit(1)
def get(args)
Get a template by name.
3.874649
3.074334
1.260321
m = TemplateManager(args.hosts) m.delete(args.name)
def delete(args)
Delete a template by name
11.043427
7.850587
1.406701
if __is_deleted(user): return deleted_parser(user) if user['id'] in item_types: raise Exception('Not a user name') if type(user['id']) == int: raise Exception('Not a user name') return User( user['id'], user['delay'], user['created'], user['...
def user_parser(user)
Parses a user object
6.079887
6.052805
1.004474
if __is_deleted(story): return deleted_parser(story) if story['type'] != 'story': return item_parser(story) return Story( __check_key('id', story), __check_key('by', story), __check_key('kids', story), __check_key('score', story), __check_key('tim...
def story_parser(story)
Parses a story object
2.545128
2.593122
0.981492
try: if comment['type'] != 'comment': return item_parser(comment) except KeyError: return deleted_parser(comment) return Comment( comment['id'], comment['by'], __check_key('kids', comment), # some comments do not have kids key comment['parent...
def comment_parser(comment)
Parses a comment object
5.367058
5.499269
0.975958
if __is_deleted(poll): return deleted_parser(poll) if poll['type'] not in poll_types: raise Exception('Not a poll type') return Poll( poll['id'], poll['by'], __check_key('kids', poll), # poll and pollopt differ this property __check_key('parts', poll), ...
def poll_parser(poll)
Parses a poll object
5.599597
5.548504
1.009208
if __is_deleted(item): return deleted_parser(item) return Item( __check_key('id', item), __check_key('deleted', item), __check_key('type', item), __check_key('by', item), __check_key('time', item), __check_key('text', item), __check_key('dead'...
def item_parser(item)
Parses a item object It gives None for the property not present Used when some item types do not get parsed easily when using gevent
2.570686
2.563974
1.002618
return null_string_repr if is_undefined(value) \ else obj.jsonify(value, trimable=trimable)
def json_to_string(value, null_string_repr='[]', trimable=False)
Return a string representation of the specified JSON object. @param value: a JSON object. @param null_string_rep: the string representation of the null object. @return: a string representation of the specified JSON object.
7.522786
15.635209
0.481144
if is_undefined(value) and default_value: return default_value if isinstance(value, bool): return value if isinstance(value, basestring) and value is not None: value = value.lower() is_true = value in ('yes', 'true', 't', '1') if not is_true and strict == True and \ ...
def string_to_boolean(value, strict=False, default_value=False)
Return a boolean with a value represented by the specified string. @param value: a string representation of a boolean. @param strict: indicate whether the specified string MUST be of a valid boolean representation. @return: the boolean value represented by the string. @raise ValueError: if t...
2.819132
2.968299
0.949747
if isinstance(value, datetime.date): return value return dateutil.parser.parse(value).date()
def string_to_date(value)
Return a Python date that corresponds to the specified string representation. @param value: string representation of a date. @return: an instance ``datetime.datetime`` represented by the string.
3.331177
5.966258
0.558336
if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None try: return float(value) except ValueError: raise ValueError( 'The specified string "%s" does not represent an integer' % value)
def string_to_decimal(value, strict=True)
Return a decimal corresponding to the string representation of a number. @param value: a string representation of an decimal number. @param strict: indicate whether the specified string MUST be of a valid decimal number representation. @return: the decimal value represented by the string. ...
4.190112
5.467473
0.766371
if not isinstance(enumeration, Enum): raise ValueError('The specified enumeration is not an instance of Enum') if is_undefined(value): if strict: raise ValueError('The value cannot be null') if default_value is not None and not default_value in enumeration: ...
def string_to_enum(value, enumeration, strict=True, default_value=None)
Return the item of an enumeration that corresponds to the specified string representation. @param value: string representation of an item of a Python enumeration. @param enumeration: a Python enumeration. @param strict: indicate whether the value must correspond to an item of the spec...
2.750728
2.597857
1.058845
if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None try: return int(value) except ValueError: raise ValueError('The specified string "%s" does not represent an integer' % value)
def string_to_integer(value, strict=False)
Return an integer corresponding to the string representation of a number. @param value: a string representation of an integer number. @param strict: indicate whether the specified string MUST be of a valid integer number representation. @return: the integer value represented by the string. ...
3.787418
4.696879
0.806369
if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None if not REGEX_IPV4.match(value): raise ValueError('The specified string "%s" does not represent a IPv4' % value) ipv4 = [ int(byte) for byte in value.split('.') if int(byte) ...
def string_to_ipv4(value, strict=False)
Return a tuple corresponding to the string representation of an IPv4 address. An IPv4 address is canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., ``172.16.254.1``. @param value: a dotted-decimal notation ...
3.245371
3.433766
0.945135
try: return None if is_undefined(value) else Locale.from_string(value, strict=strict) except Locale.MalformedLocaleException, exception: if strict: raise exception
def string_to_locale(value, strict=True)
Return an instance ``Locale`` corresponding to the string representation of a locale. @param value: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code. @param strict: indicate wh...
5.03678
5.807715
0.867257
if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None match = REGEX_MAC_ADDRESS.match(value.lower()) if match is None: raise ValueError('The specified string "%s" does not represent a MAC address' % value) return match.grou...
def string_to_macaddr(value, strict=False)
Return a tuple corresponding to the string representation of a Media Access Control address (MAC address) of a device, which is a unique identifier assigned to a network interface controller (NIC) for communications at the data link layer of a network segment. The standard (IEEE 802) format for printin...
3.723933
4.476207
0.831939
try: return datetime.datetime.strptime(value, '%H:%M:%S').time() except ValueError: return datetime.datetime.strptime(value, '%H:%M').time()
def string_to_time(value)
Return an instance ``datetime.time`` that corresponds to the specified string representation. @param value: a string representation of a time ``HH:MM[:SS]``, where: * ``HH``: hour (24-hour clock) as a zero-padded decimal number. * ``MM``: minute as a zero-padded decimal number. * ``S...
1.981849
2.371974
0.835527
if second_digits < 0 or second_digits > 6: raise ValueError('The number of second digits after the decimal point must be in 0..6') if not value: return None if isinstance(value, datetime.date): pydatetime = ISO8601DateTime.from_datetime(value) else: if default_utc...
def string_to_timestamp(value, second_digits=3, default_utc_offset=None, rounding_method=TimestampRoundingMethod.ceiling)
Return the ISO 8601 date time that corresponds to the specified string representation. When the required precision is lower than microsecond, the function rounds the sub-second time to the specified number of digits. By default, when possible, it returns the smallest value greater than or equal to...
2.396311
2.282434
1.049893
try: return None if is_undefined(value) else uuid.UUID(value) except ValueError, error: if strict: raise error
def string_to_uuid(value, strict=True)
Return a Universally Unique Identifier (UUID) object represented by the specified string. @param value: a string representation of a UUID. @param strict: indicate whether the specified string MUST be of a valid UUID representation. @return: a UUID object.
4.499964
5.821155
0.773036
app = Flask(__name__) app.secret_key = str(uuid.uuid4()) app.json_encoder = DateTimeEncoder app.register_blueprint(page) Bower(app) api = Api(app) api.add_resource( PluginListAPI, api_path + "plugins/", endpoint="APIPlugins" ) api.add_resource( Pl...
def create_app(debug=False)
Create the flask app :param debug: Use debug mode :type debug: bool :return: Created app :rtype: flask.Flask
3.087806
3.263546
0.946151
p = None if plugin_key: try: p = db_plugin_instance.plugin_get(plugin_key) except KeyError: logger.error(u"Plugin '{}' not found".format(plugin_key)) return render_template("plugin.html", title="Plugins", plugin=p)
def plugin(plugin_key=None)
Serve plugin page :param plugin_key: Which plugin page to server; if None -> landing page (default: None) :type plugin_key: None | unicode
3.789626
4.358751
0.869429
if (point_q.x <= max(point_p.x, point_r.x) and point_q.x >= min(point_p.x, point_r.x) and point_q.y <= max(point_p.y, point_r.y) and point_q.y >= min(point_p.y, point_r.y)): return True return False
def on_segment(point_p, point_q, point_r)
Given three colinear points p, q, r, the function checks if point q lies on line segment "pr" :param point_p: :type point_p: models.Point :param point_q: :type point_q: models.Point :param point_r: :type point_r: models.Point :return: if point r on line segment "pr" :rtype: bool
1.50235
1.455247
1.032368
# Set https://www.geeksforgeeks.org/orientation-3-ordered-points/ # for details of below formula. r = ((point_q.y - point_p.y) * (point_r.x - point_q.x) - (point_q.x - point_p.x) * (point_r.y - point_q.y)) if r == 0: return 0 return 1 if r > 0 else 2
def orientation(point_p, point_q, point_r)
To find orientation of ordered triplet (p, q, r). :param point_p: :type point_p: models.Point :param point_q: :type point_q: models.Point :param point_r: :type point_r: models.Point :return: 0: p, q and r are colinear 1: clockwise 2: counterclockwise :rtype: in...
2.196584
2.067448
1.062462
# Find the four orientations needed for general and special cases orientation_1 = orientation(line_a.endpoint_a, line_a.endpoint_b, line_b.endpoint_a) orientation_2 = orientation(line_a.endpoint_a, line_a.endpoint_b, line_b.endpoint_b) ...
def is_intersect(line_a, line_b)
Determine if lina_a intersect with line_b :param lina_a: :type lina_a: models.Line :param lina_b: :type line_b: models.Line :return: :rtype: bool
1.355927
1.385013
0.978999
points = region.vertices extrame = models.Point(x=1000000, y=point.y) points = points + [points[0]] intersect_count = 0 for i in range(len(points) - 1): if is_intersect(models.Line(point, extrame), models.Line(points[i], points[i+1])): intersect_coun...
def is_inside(point, region)
Detemine if point is in region :param point: :type point: models.Point :param region: :type region: Region
3.694266
4.160379
0.887964
if method == "edge": if model != "projection": raise ValueError("`method='edge'` requires `model='projection'`!") n, r, c = edgefit.analyze(qpi=qpi, r0=r0, edgekw=edgekw, ret_center...
def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False)
Determine refractive index and radius of a spherical object Parameters ---------- qpi: qpimage.QPImage Quantitative phase image data r0: float Approximate radius of the sphere [m] method: str The method used to determine the refractive index can either be "edge" (det...
2.299848
2.16489
1.06234
# Mask values around the object cx, cy = sim["sim center"] radius = sim["sim radius"] px_um = sim["pixel size"] x = np.arange(sim.shape[0]).reshape(-1, 1) y = np.arange(sim.shape[1]).reshape(1, -1) rsq = (x - cx)**2 + (y - cy)**2 mask = rsq > (radius/px_um * radial_clearance)**2 ...
def bg_phase_mask_from_sim(sim, radial_clearance=1.1)
Return the background phase mask of a qpsphere simulation Parameters ---------- sim: qpimage.QPImage Quantitative phase data simulated with qpsphere; The simulation keyword arguments "sim center", "sim radius", and "pixel size" must be present in `sim.meta`. radial_clearance: fl...
3.489498
2.919426
1.195268
# fit sphere _, _, sim = analyze(qpi=qpi, r0=r0, method=method, model=model, edgekw=edgekw, imagekw=imagekw, ret_qpi=True) # determine mask mask = bg_phase...
def bg_phase_mask_for_qpi(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={}, radial_clearance=1.1)
Determine the background phase mask for a spherical phase object The position and radius of the phase object are determined with :func:`analyze`, to which the corresponding keyword arguments are passed. A binary mask is created from the simulation results via :func:`bg_phase_mask_from_sim`. Parame...
3.485245
3.169638
1.099572
''' Returns ''' path = 'templates/{}'.format(filename) with open(path) as source: code = compile(source.read(), path, 'exec') global_vars = {'t': t, 'f': f, 'e': e, 'escape': html.escape, 'ctime': tim...
def template(filename, **locals)
Returns
4.101223
4.35058
0.942684
self._validate_subtype(subtype) self.subtype = subtype return self
def with_subtype(self, subtype)
Add a subtype segment Args: subtype (str): May be one of ``['a', 'c', 'r']``. See the `Reference Definition <https://elections.democracyclub.org.uk/reference_definition>`_. for valid election type/subtype combinations. Returns: IdBuilder ...
4.336552
9.109942
0.476024
if organisation is None: organisation = '' organisation = slugify(organisation) self._validate_organisation(organisation) self.organisation = organisation return self
def with_organisation(self, organisation)
Add an organisation segment. Args: organisation (str): Official name of an administrative body holding an election. Returns: IdBuilder Raises: ValueError
4.10465
7.075202
0.580146
if division is None: division = '' division = slugify(division) self._validate_division(division) self.division = division return self
def with_division(self, division)
Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError
4.500526
5.781981
0.778371
self._validate() # there are no additional validation checks for the top-level group id parts = [] parts.append(self.election_type) parts.append(self.date) return ".".join(parts)
def election_group_id(self)
str: Election Group ID
8.821179
7.750124
1.138199
self._validate() self._validate_for_subtype_group_id() parts = [] parts.append(self.election_type) parts.append(self.subtype) parts.append(self.date) return ".".join(parts)
def subtype_group_id(self)
str: Subtype Group ID
5.284371
4.815636
1.097336
self._validate() self._validate_for_organisation_group_id() parts = [] parts.append(self.election_type) if self.subtype: parts.append(self.subtype) parts.append(self.organisation) parts.append(self.date) return ".".join(parts)
def organisation_group_id(self)
str: Organisation Group ID
4.826623
4.414973
1.09324
self._validate() self._validate_division(self.division) self._validate_for_ballot_id() parts = [] parts.append(self.election_type) if self.subtype: parts.append(self.subtype) if self.organisation: parts.append(self.organisation) ...
def ballot_id(self)
str: Ballot ID
2.845392
2.788875
1.020265
ids = [] try: ids.append(self.election_group_id) except ValueError: pass if isinstance(self.spec.subtypes, tuple): try: ids.append(self.subtype_group_id) except ValueError: pass if self.sp...
def ids(self)
list[str]: All applicable IDs
3.512181
3.421733
1.026433
''' Call cmd and return output. return None if any exception occurs ''' try: return safely_decode(check_output(cmd)) except Exception as e: logger.warn(u'Couldnt execute cmd: %s.\nReason: %s' % (cmd, e)) return None
def execute(cmd)
Call cmd and return output. return None if any exception occurs
6.702899
4.596566
1.458241
ret = os.environ.copy() for env in component_config.get_list("dp.env_list"): real_env = env.upper() value = os.environ.get(real_env) value = _prepend_env(component_config, env, value) value = _append_env(component_config, env, value) _apply_change(ret, real_env, valu...
def create_environment(component_config)
Create a modified environment. Arguments component_config - The configuration for a component.
4.356199
4.517388
0.964318
''' Reset the contents of the tree view to show one row per surface, with a column containing the alpha multiplier for the corresponding surface (in the range [0, 1]), indexed by surface name. For example: | index | alpha | |--------|--------| ...
def set_surfaces(self, df_surfaces)
Reset the contents of the tree view to show one row per surface, with a column containing the alpha multiplier for the corresponding surface (in the range [0, 1]), indexed by surface name. For example: | index | alpha | |--------|--------| | layer1 | 1.00 ...
4.011425
2.866657
1.399339
''' Set scale marker to alpha for selected layer. ''' # 1. Look up selected layer. selection = self.treeview_layers.get_selection() list_store, selected_iter = selection.get_selected() # 2. Set adjustment to current alpha value for selected layer (if any). ...
def set_scale_alpha_from_selection(self)
Set scale marker to alpha for selected layer.
4.118643
3.634262
1.133282
''' Set alpha for selected layer. ''' # 1. Look up selected layer. selection = self.treeview_layers.get_selection() list_store, selected_iter = selection.get_selected() # 2. Set alpha value for layer (if selected). if selected_iter is None: #...
def set_alpha_for_selection(self, alpha)
Set alpha for selected layer.
5.68305
5.423385
1.047879
if hasattr(block, 'send_destinations') and block.send_destinations: self.fire(events.FileProcessed(block)) self._log_in_db(block) if self._sent_log_file: self._log_in_sent_log(block) self.log.info("Sent to '%s' file '%s' containing files: ...
def process_data(self, block)
expects Block from Compressor
5.282969
5.211396
1.013734
try: return session.query(UploadedFile).filter(UploadedFile.sha1 == file_info.sha1).one() except NoResultFound: new_instance = UploadedFile( sha1=file_info.sha1, file_name=file_info.upath, fragment_count=fragment_count ...
def _get_uploaded_file(session, file_info, fragment_count=0)
:param session: locked session (with self._session_resource as >> session <<) :param file_info: contains file information to save or query :param fragment_count: amount of fragments associated to the file :return: an UploadedFile associated to the file_info
2.375306
2.221964
1.069012
# FIXME all these should be done by the block itself self._sent_log_file.write("\n") sent_file_info = block.latest_file_info self._sent_log_file.write("|".join((sent_file_info.basename, sent_file_info.sha1))) if hasattr(block, 'cipher_key'): self._sent_log_fi...
def _log_in_sent_log(self, block)
Logs: block file | bfile (not encrypted) sha1 [| bfile encryption key | encrypted bfile sha1] <tab>content file | cfile sha1 | part of parts [| whole file sha1]
2.808125
2.613397
1.074512
if self.filters.get('whitelist', None): return request.tree.type in self.filters['whitelist'] elif self.filters.get('blacklist', None): return request.tree.type not in self.filters['blacklist'] else: return True
def should_send(self, request)
Returns whether or not the request should be sent to the modules, based on the filters.
3.02479
2.854995
1.059473
self.log.info('starting the ``get`` method') self._remove_processed_data() archivePath = self.settings["atlas archive path"] self._update_day_tracker_table() mjds = self._determine_mjds_to_download(days=days) if len(mjds) == 0: return dbCo...
def get( self, days)
*download a cache of ATLAS nights data* **Key Arguments:** - ``days`` -- the number of days data to cache locally **Return:** - None **Usage:** See class docstring
5.478868
5.100867
1.074105
self.log.info('starting the ``_determine_mjds_to_download`` method') # COUNT DOWNLOADED NIGHTS sqlQuery = u % locals() mjds = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.atlasMoversDBConn, quiet=False ) ...
def _determine_mjds_to_download( self, days)
*determine which ATLAS nights require to be cached locally* **Key Arguments:** - ``days`` -- the number of days data to cache locally **Return:** - ``mjds`` -- a list of the MJDs to be downloaded from the ATLAS datastore in hawaii
4.792439
4.24001
1.13029
self.log.info('starting the ``_remove_processed_data`` method') archivePath = self.settings["atlas archive path"] from fundamentals.mysql import readquery sqlQuery = u % locals() mjds = readquery( log=self.log, sqlQuery=sqlQuery, dbC...
def _remove_processed_data( self)
*remove processed data*
4.419942
4.310651
1.025354
self.log.info('starting the ``_update_day_tracker_table`` method') # YESTERDAY MJD mjd = now( log=self.log ).get_mjd() yesterday = int(math.floor(mjd - 1)) sqlQuery = u % locals() rows = readquery( log=self.log, sqlQu...
def _update_day_tracker_table( self)
* update day tracker table* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool for this method - ...
4.212895
4.111203
1.024736
response = requests.get(recipe_url, headers=get_header()) html = BeautifulSoup(response.text, 'lxml') # 获取菜名 name = html.find("div", {"class": "re-up"}).h1.text # 主图 img = html.find("div", {"class": "gallery"}).a['href'] img = urljoin(HOME_URL, img) all_info = html.find_all("div"...
def get_recipe_detail(recipe_url)
从url中获取菜谱详细信息 :param recipe_url: str 菜谱url,如:https://www.xinshipu.com/zuofa/598775; https://www.xinshipu.com//zuofa/749342 :return:dict
2.676036
2.669999
1.002261
url = "https://www.xinshipu.com/%E8%8F%9C%E8%B0%B1%E5%A4%A7%E5%85%A8.html" response = requests.get(url, headers=get_header()) html = BeautifulSoup(response.text, "lxml") all_a = html.find("div", {'class': "detail-cate-list clearfix mt20"}).find_all('a') classify = dict() for a in all_a: ...
def get_all_classify()
获取全部菜谱分类
3.29493
3.137538
1.050164
class_url = class_url + "?page={page}" recipes = dict() # 暴力爬取方案,每个菜谱分类请求100页 for page in range(1, max_page): time.sleep(sleep) url = class_url.format(page=page) print("current url: ", url) response = requests.get(url, headers=get_header()) html = BeautifulS...
def get_class_recipes(class_url, max_page=20, sleep=0.1)
获取某个菜谱分类url下的所有菜谱url
3.472685
3.2659
1.063317
m = RiverManager(args.hosts) r = m.get(args.name) if r: print(json.dumps(r, indent=2)) else: sys.exit(1)
def get(args)
Get a river by name.
3.940954
2.979458
1.322709
data = json.load(sys.stdin) m = RiverManager(args.hosts) m.create(args.name, data)
def create(args)
Create a river. This command expects to be fed a JSON document on STDIN.
7.786096
4.359758
1.785901
m = RiverManager(args.hosts) m.delete(args.name)
def delete(args)
Delete a river by name
12.323752
7.171952
1.718326
data = json.load(sys.stdin) m = RiverManager(args.hosts) if m.compare(args.name, data): sys.exit(0) else: sys.exit(1)
def compare(args)
Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is configured as specified, and 1 otherwise.
5.099798
3.308709
1.541326