text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip acr...
[ "def", "flipcoords", "(", "xcoord", ",", "ycoord", ",", "axis", ")", ":", "axis", "=", "axis", ".", "lower", "(", ")", "if", "axis", "==", "'y'", ":", "if", "xcoord", ">", "0", ":", "return", "str", "(", "xcoord", "-", "xcoord", "-", "xcoord", ")...
34.085714
0.000815
def error(self, s, pos): """Show text and a caret under that. For example: x = 2y + z ^ """ print("Lexical error:") print("%s" % s[:pos+10]) # + 10 for trailing context print("%s^" % (" "*(pos-1))) for t in self.rv: print(t) raise SystemExit
[ "def", "error", "(", "self", ",", "s", ",", "pos", ")", ":", "print", "(", "\"Lexical error:\"", ")", "print", "(", "\"%s\"", "%", "s", "[", ":", "pos", "+", "10", "]", ")", "# + 10 for trailing context", "print", "(", "\"%s^\"", "%", "(", "\" \"", "...
28.6
0.010169
def query_raw(self, metric, **kwargs): # noqa: E501 """Perform a raw data query against Wavefront servers that returns second granularity points grouped by tags # noqa: E501 An API to check if ingested points are as expected. Points ingested within a single second are averaged when returned. # noqa...
[ "def", "query_raw", "(", "self", ",", "metric", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "query_raw_with...
65.8
0.001198
def run_cell(self, raw_cell, store_history=False, silent=False): """Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell ...
[ "def", "run_cell", "(", "self", ",", "raw_cell", ",", "store_history", "=", "False", ",", "silent", "=", "False", ")", ":", "if", "(", "not", "raw_cell", ")", "or", "raw_cell", ".", "isspace", "(", ")", ":", "return", "if", "silent", ":", "store_histor...
45.377358
0.002442
def keyword_search(rows, **kwargs): """ Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments. Keys in the row data have ' ' and '-' replaced with '_', so they can match the keyword argument parsing. For example, the keywor...
[ "def", "keyword_search", "(", "rows", ",", "*", "*", "kwargs", ")", ":", "results", "=", "[", "]", "if", "not", "kwargs", ":", "return", "results", "# Allows us to transform the key and do lookups like __contains and", "# __startswith", "matchers", "=", "{", "'defau...
41.846154
0.002095
def subscribe(self, handler, topic=None, options=None): """Subscribe to a topic for receiving events. Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe` """ def proxy_handler(*args, **kwargs): return self._callbacks_runner.put(partial(handler, *args, **kwa...
[ "def", "subscribe", "(", "self", ",", "handler", ",", "topic", "=", "None", ",", "options", "=", "None", ")", ":", "def", "proxy_handler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_callbacks_runner", ".", "put", "(...
51
0.009639
def set_pixel(self, x, y, color): """ Color may be: value, tuple, list etc. If the image is set to contain more color-channels than len(color), the remaining channels will be filled automatically. Example (channels = 4, i.e. RGBA output): color = 17 -> color = [...
[ "def", "set_pixel", "(", "self", ",", "x", ",", "y", ",", "color", ")", ":", "try", ":", "# these checks are for convenience, not for safety\r", "if", "len", "(", "color", ")", "<", "self", ".", "channels", ":", "# color is a a tuple (length >= 1)\r", "if", "len...
46.615385
0.001078
def get_remote_data(data, settings, mode, more_excluded_names=None): """ Return globals according to filter described in *settings*: * data: data to be filtered (dictionary) * settings: variable explorer settings (dictionary) * mode (string): 'editable' or 'picklable' * more_excl...
[ "def", "get_remote_data", "(", "data", ",", "settings", ",", "mode", ",", "more_excluded_names", "=", "None", ")", ":", "supported_types", "=", "get_supported_types", "(", ")", "assert", "mode", "in", "list", "(", "supported_types", ".", "keys", "(", ")", ")...
53.1
0.000925
def _get_ngrams(n, text): """Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add(tuple(t...
[ "def", "_get_ngrams", "(", "n", ",", "text", ")", ":", "ngram_set", "=", "set", "(", ")", "text_length", "=", "len", "(", "text", ")", "max_index_ngram_start", "=", "text_length", "-", "n", "for", "i", "in", "range", "(", "max_index_ngram_start", "+", "1...
21.125
0.01983
def get_pointing_chains(docgraph, layer=None): """ returns a list of chained pointing relations (e.g. coreference chains) found in the given document graph. Parameters ---------- docgraph : DiscourseDocumentGraph a text with annotations, represented by a document graph layer : str o...
[ "def", "get_pointing_chains", "(", "docgraph", ",", "layer", "=", "None", ")", ":", "pointing_relations", "=", "select_edges_by", "(", "docgraph", ",", "layer", "=", "layer", ",", "edge_type", "=", "EdgeTypes", ".", "pointing_relation", ")", "# a markable can poin...
38.769231
0.00129
def database_remove_types(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes """ return DXHTTPRequest('/%s/removeTypes...
[ "def", "database_remove_types", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/removeTypes'", "%", "object_id", ",", "input_params", ",", "always_...
54.142857
0.01039
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
[ "def", "finish", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Disconnecting from JLigier.\"", ")", "self", ".", "client", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "self", ".", "client", ".", "_disconnect", "(", ")" ]
41.6
0.009434
def reverse(array): """ returns a reversed numpy array """ l = list(array) l.reverse() return _n.array(l)
[ "def", "reverse", "(", "array", ")", ":", "l", "=", "list", "(", "array", ")", "l", ".", "reverse", "(", ")", "return", "_n", ".", "array", "(", "l", ")" ]
17.571429
0.015504
def CompressStream(in_stream, length=None, compresslevel=2, chunksize=16777216): """Compresses an input stream into a file-like buffer. This reads from the input stream until either we've stored at least length compressed bytes, or the input stream has been exhausted. This supports...
[ "def", "CompressStream", "(", "in_stream", ",", "length", "=", "None", ",", "compresslevel", "=", "2", ",", "chunksize", "=", "16777216", ")", ":", "in_read", "=", "0", "in_exhausted", "=", "False", "out_stream", "=", "StreamingBuffer", "(", ")", "with", "...
40.946429
0.000426
def preformat_cache(cache, start=None, end=None): """Preprocess a `list` of file paths for reading. - read the cache from the file (if necessary) - sieve the cache to only include data we need Parameters ---------- cache : `list`, `str` List of file paths, or path to a LAL-format cache...
[ "def", "preformat_cache", "(", "cache", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "# open cache file", "if", "isinstance", "(", "cache", ",", "FILE_LIKE", "+", "string_types", ")", ":", "return", "read_cache", "(", "cache", ",", "sort",...
34.340426
0.000602
def is_valid_solution(solution, events, slots): """Take a solution and return whether it is valid for the given constraints Parameters ---------- solution: list or tuple a schedule in solution form events : list or tuple of resources.Event instances slots...
[ "def", "is_valid_solution", "(", "solution", ",", "events", ",", "slots", ")", ":", "if", "len", "(", "solution", ")", "==", "0", ":", "return", "False", "array", "=", "converter", ".", "solution_to_array", "(", "solution", ",", "events", ",", "slots", "...
27.772727
0.001582
def rows_to_columns(data, schema=None): """ :param data: array of objects :param schema: Known schema, will be extended to include all properties found in data :return: Table """ if not schema: schema = SchemaTree() all_schema = schema all_leaves = schema.leaves values = {ful...
[ "def", "rows_to_columns", "(", "data", ",", "schema", "=", "None", ")", ":", "if", "not", "schema", ":", "schema", "=", "SchemaTree", "(", ")", "all_schema", "=", "schema", "all_leaves", "=", "schema", ".", "leaves", "values", "=", "{", "full_name", ":",...
44.309735
0.002149
def create_arg_parser(parent): """Create command subparsers. Parameters ---------- parent : `argparse.ArgumentParser` Command parser. """ arg1 = parent.add_subparsers(dest='command') arg2 = arg1.add_parser('create') arg2.add_argument('-P', '--progress', a...
[ "def", "create_arg_parser", "(", "parent", ")", ":", "arg1", "=", "parent", ".", "add_subparsers", "(", "dest", "=", "'command'", ")", "arg2", "=", "arg1", ".", "add_parser", "(", "'create'", ")", "arg2", ".", "add_argument", "(", "'-P'", ",", "'--progress...
40.580645
0.000259
def _generate_composite(self, comp_node, keepables): """Collect all composite prereqs and create the specified composite. Args: comp_node (Node): Composite Node to generate a Dataset for keepables (set): `set` to update if any datasets are needed whe...
[ "def", "_generate_composite", "(", "self", ",", "comp_node", ",", "keepables", ")", ":", "if", "comp_node", ".", "name", "in", "self", ".", "datasets", ":", "# already loaded", "return", "compositor", ",", "prereqs", ",", "optional_prereqs", "=", "comp_node", ...
38.145455
0.001394
def rename(self, names, prefix): """ Rename the Attributes' names, prefixes, or both. If names or prefix evaluates to None, the old version is used. Resulting names must be unambiguous. :param names: A list of new names for each attribute or an empty list. :param prefix: ...
[ "def", "rename", "(", "self", ",", "names", ",", "prefix", ")", ":", "if", "names", ":", "if", "len", "(", "names", ")", "!=", "len", "(", "self", ".", "_contents", ")", ":", "raise", "InputError", "(", "'Attribute count mismatch.'", ")", "if", "self",...
46
0.001638
def taskfileinfo_element_data(tfi, role): """Return the data for the element (e.g. the Asset or Shot) :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :param role: item data role :type role: QtCore.Qt.ItemDataRole :ret...
[ "def", "taskfileinfo_element_data", "(", "tfi", ",", "role", ")", ":", "task", "=", "tfi", ".", "task", "element", "=", "task", ".", "element", "if", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", "or", "role", "==", "QtCore", ".", "Qt", ".", ...
35.4
0.001835
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(GitTrackerSatchel, self).record_manifest() manifest[CURRENT_COMMIT] = self.get_current_commit() return manifest
[ "def", "record_manifest", "(", "self", ")", ":", "manifest", "=", "super", "(", "GitTrackerSatchel", ",", "self", ")", ".", "record_manifest", "(", ")", "manifest", "[", "CURRENT_COMMIT", "]", "=", "self", ".", "get_current_commit", "(", ")", "return", "mani...
38.75
0.009464
def delete(self, uri, logon_required=True): """ Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the oper...
[ "def", "delete", "(", "self", ",", "uri", ",", "logon_required", "=", "True", ")", ":", "if", "logon_required", ":", "self", ".", "logon", "(", ")", "url", "=", "self", ".", "base_url", "+", "uri", "self", ".", "_log_http_request", "(", "'DELETE'", ","...
38.957143
0.000715
def list_role_binding_for_all_namespaces(self, **kwargs): """ list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_role_binding_for_all_namespaces(...
[ "def", "list_role_binding_for_all_namespaces", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_role_binding_for_al...
169.222222
0.002394
def make_uniq_for_step(ctx, ukeys, step, stage, full_data, clean_missing_after_seconds, to_uniq): """initially just a copy from UNIQ_PULL""" # TODO: # this still seems to work ok for Storage types json/bubble, # for DS we need to reload de dumped step to uniqify if not ukeys: return to_uni...
[ "def", "make_uniq_for_step", "(", "ctx", ",", "ukeys", ",", "step", ",", "stage", ",", "full_data", ",", "clean_missing_after_seconds", ",", "to_uniq", ")", ":", "# TODO:", "# this still seems to work ok for Storage types json/bubble,", "# for DS we need to reload de dumped s...
41.625
0.001467
def parse_response(self, header_data, ignore_bad_cookies=False, ignore_bad_attributes=True): """Parse 'Set-Cookie' header data into Cookie objects, and add them to this Cookies object. :arg header_data: string containing only 'Set-Cookie:' request headers or their...
[ "def", "parse_response", "(", "self", ",", "header_data", ",", "ignore_bad_cookies", "=", "False", ",", "ignore_bad_attributes", "=", "True", ")", ":", "cookie_dicts", "=", "_parse_response", "(", "header_data", ",", "ignore_bad_cookies", "=", "ignore_bad_cookies", ...
50.837209
0.001346
def y_fit(self, test_length): """ Test to see if the page has enough space for the given text height. """ if (self.y + test_length) >= self.ymax: return False else: return True
[ "def", "y_fit", "(", "self", ",", "test_length", ")", ":", "if", "(", "self", ".", "y", "+", "test_length", ")", ">=", "self", ".", "ymax", ":", "return", "False", "else", ":", "return", "True" ]
37.333333
0.0131
def save_dispatcher(dsp, path): """ Write Dispatcher object in Python pickle format. Pickles are a serialized byte stream of a Python object. This format will preserve Python objects used as nodes or edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula...
[ "def", "save_dispatcher", "(", "dsp", ",", "path", ")", ":", "import", "dill", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "dill", ".", "dump", "(", "dsp", ",", "f", ")" ]
27.393939
0.001068
def bulk(self, request, *args, **kwargs): """ Update multiple preferences at once this is a long method because we ensure everything is valid before actually persisting the changes """ manager = self.get_manager() errors = {} preferences = [] payl...
[ "def", "bulk", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "manager", "=", "self", ".", "get_manager", "(", ")", "errors", "=", "{", "}", "preferences", "=", "[", "]", "payload", "=", "request", ".", "data", ...
31.984127
0.000963
def add_nations_field(authors_subfields): """Add correct nations field according to mapping in NATIONS_DEFAULT_MAP.""" from .config import NATIONS_DEFAULT_MAP result = [] for field in authors_subfields: if field[0] == 'v': values = [x.replace('.', '') for x in field[1].split(', ')] ...
[ "def", "add_nations_field", "(", "authors_subfields", ")", ":", "from", ".", "config", "import", "NATIONS_DEFAULT_MAP", "result", "=", "[", "]", "for", "field", "in", "authors_subfields", ":", "if", "field", "[", "0", "]", "==", "'v'", ":", "values", "=", ...
41.590909
0.002137
def get_public_ip(access_token, subscription_id, resource_group, ip_name): '''Get details about the named public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. ...
[ "def", "get_public_ip", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "ip_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourceGro...
42.736842
0.001205
def decayWeights(self, decayConst=60): """ Decay the network's weights. :param decayConst: The time constant (in seconds) to use for decay. Note: If applied, decay must be used extremely carefully, as it has a tendency to cause asymmetries in the network weights. """ self.we...
[ "def", "decayWeights", "(", "self", ",", "decayConst", "=", "60", ")", ":", "self", ".", "weightsII", "-=", "self", ".", "weightsII", "*", "self", ".", "dt", "/", "decayConst", "self", ".", "weightsELI", "-=", "self", ".", "weightsELI", "*", "self", "....
44.923077
0.001678
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: """ Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to ...
[ "def", "find_nth", "(", "s", ":", "str", ",", "x", ":", "str", ",", "n", ":", "int", "=", "0", ",", "overlap", ":", "bool", "=", "False", ")", "->", "int", ":", "# noqa", "length_of_fragment", "=", "1", "if", "overlap", "else", "len", "(", "x", ...
33.9
0.001435
def metadata(self): """Get metadata information in XML format.""" params = { self.PCTYPE: self.CTYPE_XML } response = self.call(self.CGI_BUG, params) return response
[ "def", "metadata", "(", "self", ")", ":", "params", "=", "{", "self", ".", "PCTYPE", ":", "self", ".", "CTYPE_XML", "}", "response", "=", "self", ".", "call", "(", "self", ".", "CGI_BUG", ",", "params", ")", "return", "response" ]
21.1
0.009091
def apply_K(df, k): """Apply the geometric factors to the dataset and compute (apparent) resistivities/conductivities """ if 'k' not in df.columns: df['k'] = k if 'rho_a' not in df.columns: df['rho_a'] = df['r'] * df['k'] if 'sigma_a' not in df.columns: df['sigma_a'] = ...
[ "def", "apply_K", "(", "df", ",", "k", ")", ":", "if", "'k'", "not", "in", "df", ".", "columns", ":", "df", "[", "'k'", "]", "=", "k", "if", "'rho_a'", "not", "in", "df", ".", "columns", ":", "df", "[", "'rho_a'", "]", "=", "df", "[", "'r'", ...
25.8125
0.002336
def log_write(self, data, kind='input'): """Write data to the log file, if active""" #print 'data: %r' % data # dbg if self.log_active and data: write = self.logfile.write if kind=='input': if self.timestamp: write(str_to_unicode(time....
[ "def", "log_write", "(", "self", ",", "data", ",", "kind", "=", "'input'", ")", ":", "#print 'data: %r' % data # dbg", "if", "self", ".", "log_active", "and", "data", ":", "write", "=", "self", ".", "logfile", ".", "write", "if", "kind", "==", "'input'", ...
42.0625
0.010174
def connect(url='https://github.com', token=None): """ Create a GitHub session for making requests """ gh_session = None if url == 'https://github.com': gh_session = create_session(token) else: gh_session = create_enterprise_session(url, token) if gh_session is None: ...
[ "def", "connect", "(", "url", "=", "'https://github.com'", ",", "token", "=", "None", ")", ":", "gh_session", "=", "None", "if", "url", "==", "'https://github.com'", ":", "gh_session", "=", "create_session", "(", "token", ")", "else", ":", "gh_session", "=",...
25.611111
0.002092
def channels_voice_greeting_recording(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/voice-api/greetings#get-greeting-audio-file" api_path = "/api/v2/channels/voice/greetings/{id}/recording.mp3" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "channels_voice_greeting_recording", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/channels/voice/greetings/{id}/recording.mp3\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "sel...
62.4
0.009494
def installed(name, updates=None): ''' Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ...
[ "def", "installed", "(", "name", ",", "updates", "=", "None", ")", ":", "if", "isinstance", "(", "updates", ",", "six", ".", "string_types", ")", ":", "updates", "=", "[", "updates", "]", "if", "not", "updates", ":", "updates", "=", "name", "ret", "=...
28.795455
0.000509
def from_dict(cls, d): """Extend Field.from_dict, set display/display_international attributes.""" phone = super(cls, cls).from_dict(d) phone.display = d.get('display', u'') phone.display_international = d.get('display_international', u'') return phone
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "phone", "=", "super", "(", "cls", ",", "cls", ")", ".", "from_dict", "(", "d", ")", "phone", ".", "display", "=", "d", ".", "get", "(", "'display'", ",", "u''", ")", "phone", ".", "display_inte...
43
0.009772
def _setTag(self, tag): ''' _setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict. If bool(#tag) is True, will set the weakref to that tag. Otherwise, will clear the reference @param tag <AdvancedTag...
[ "def", "_setTag", "(", "self", ",", "tag", ")", ":", "if", "tag", ":", "self", ".", "_tagRef", "=", "weakref", ".", "ref", "(", "tag", ")", "else", ":", "self", ".", "_tagRef", "=", "None" ]
36.214286
0.009615
def get_event_access_codes(self, id, **data): """ GET /events/:id/access_codes/ Returns a :ref:`paginated <pagination>` response with a key of ``access_codes``, containing a list of :format:`access_codes <access_code>` available on this event. """ return self.get("/event...
[ "def", "get_event_access_codes", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/access_codes/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
51
0.011019
def comparator(self, value): """sets the comparator (with validation of input)""" if not isinstance(value, RangeCheckComparatorType): raise AttributeError("%s comparator is invalid in RangeCheck." % (value,)) self._comparator = value
[ "def", "comparator", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "RangeCheckComparatorType", ")", ":", "raise", "AttributeError", "(", "\"%s comparator is invalid in RangeCheck.\"", "%", "(", "value", ",", ")", ")", "self",...
53
0.011152
def list2key(self, keyList): """ Convert a list of (``QtModifier``, ``QtCore.Qt.Key_*``) tuples into a key sequence. If no error is raised, then the list was accepted. |Args| * ``keyList`` (**list**): eg. (QtCore.Qt.ControlModifier, QtCore.Qt.Key_F). ...
[ "def", "list2key", "(", "self", ",", "keyList", ")", ":", "for", "keyCombo", "in", "keyList", ":", "if", "not", "(", "isinstance", "(", "keyCombo", ",", "list", ")", "or", "isinstance", "(", "keyCombo", ",", "tuple", ")", ")", ":", "msg", "=", "(", ...
40.017544
0.000856
def strftime(self, date_format): """ Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in `python string for...
[ "def", "strftime", "(", "self", ",", "date_format", ")", ":", "from", "pandas", "import", "Index", "return", "Index", "(", "self", ".", "_format_native_types", "(", "date_format", "=", "date_format", ")", ")" ]
35.675676
0.001475
def send(self, obj): """Send object""" buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj) self.send_bytes(buf.getvalue())
[ "def", "send", "(", "self", ",", "obj", ")", ":", "buf", "=", "io", ".", "BytesIO", "(", ")", "ForkingPickler", "(", "buf", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", ".", "dump", "(", "obj", ")", "self", ".", "send_bytes", "(", "buf", ".", "getv...
34.4
0.011364
def generate_module_table_header(modules): """ Generate header with module table entries for builtin modules. :param List[(module_name, obj_module, enabled_define)] modules: module defs :return: None """ # Print header file for all external modules. mod_defs = [] print("// Automatically ge...
[ "def", "generate_module_table_header", "(", "modules", ")", ":", "# Print header file for all external modules.", "mod_defs", "=", "[", "]", "print", "(", "\"// Automatically generated by makemoduledefs.py.\\n\"", ")", "for", "module_name", ",", "obj_module", ",", "enabled_de...
37.366667
0.001739
def _maybe_download(self): """ Helper to downlaod the image if not in path """ if self.grid == 'WAC': urlpath = 'http://lroc.sese.asu.edu/data/LRO-L-LROC-5-RDR-V1.0/LROLRC_2001/DATA/BDR/WAC_GLOBAL/' r = requests.get(urlpath) # List file in the cloud images = [elt.spl...
[ "def", "_maybe_download", "(", "self", ")", ":", "if", "self", ".", "grid", "==", "'WAC'", ":", "urlpath", "=", "'http://lroc.sese.asu.edu/data/LRO-L-LROC-5-RDR-V1.0/LROLRC_2001/DATA/BDR/WAC_GLOBAL/'", "r", "=", "requests", ".", "get", "(", "urlpath", ")", "# List fil...
54.488372
0.002096
def get_named_arg(name, default_val=None, reqd=False): """ Extract the value after a command-line flag such as '-f' and return it. If the command-line flag is missing, return default_val. If reqd == True and the command-line flag is missing, throw an error. Parameters ---------- name : str ...
[ "def", "get_named_arg", "(", "name", ",", "default_val", "=", "None", ",", "reqd", "=", "False", ")", ":", "if", "name", "in", "sys", ".", "argv", ":", "# if the command line flag is found in sys.argv", "ind", "=", "sys", ".", "argv", ".", "index", "(", "n...
35.071429
0.000991
def get_action_by_id(self, action_id): """ Получение детального описания события """ parsed_json, raw_json = self._call('getactionbyid', element_id=action_id) action = Action.object_from_api(parsed_json, raw_json) return action
[ "def", "get_action_by_id", "(", "self", ",", "action_id", ")", ":", "parsed_json", ",", "raw_json", "=", "self", ".", "_call", "(", "'getactionbyid'", ",", "element_id", "=", "action_id", ")", "action", "=", "Action", ".", "object_from_api", "(", "parsed_json"...
43.666667
0.011236
def DownloadFile(ID, season=None, mission='k2', cadence='lc', filename=None, clobber=False): ''' Download a given :py:mod:`everest` file from MAST. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param str filename: The ...
[ "def", "DownloadFile", "(", "ID", ",", "season", "=", "None", ",", "mission", "=", "'k2'", ",", "cadence", "=", "'lc'", ",", "filename", "=", "None", ",", "clobber", "=", "False", ")", ":", "# Get season", "if", "season", "is", "None", ":", "season", ...
33.891304
0.000312
def _drawPoints(self, pen, **kwargs): """ Subclasses may override this method. """ # The try: ... except TypeError: ... # handles backwards compatibility with # point pens that have not been upgraded # to point pen protocol 2. try: pen.beginPat...
[ "def", "_drawPoints", "(", "self", ",", "pen", ",", "*", "*", "kwargs", ")", ":", "# The try: ... except TypeError: ...", "# handles backwards compatibility with", "# point pens that have not been upgraded", "# to point pen protocol 2.", "try", ":", "pen", ".", "beginPath", ...
37.166667
0.002186
def parse_member_from_rsvp(data): """ Parse a ``MeetupMember`` from the given RSVP response data. Returns ------- A ``pythonkc_meetups.types.MeetupMember``. """ return MeetupMember( id=data['member'].get('member_id', None), name=data['member'].get('name', None), pho...
[ "def", "parse_member_from_rsvp", "(", "data", ")", ":", "return", "MeetupMember", "(", "id", "=", "data", "[", "'member'", "]", ".", "get", "(", "'member_id'", ",", "None", ")", ",", "name", "=", "data", "[", "'member'", "]", ".", "get", "(", "'name'",...
26.733333
0.00241
def from_file(file=str): """ Creates new Generic model by loading existing embedded model into library, e.g. from H2O MOJO. The imported model must be supported by H2O. :param file: A string containing path to the file to create the model from :return: H2OGenericEstimator instanc...
[ "def", "from_file", "(", "file", "=", "str", ")", ":", "from", "h2o", "import", "lazy_import", ",", "get_frame", "model_key", "=", "lazy_import", "(", "file", ")", "model_bytes_frame", "=", "get_frame", "(", "model_key", "[", "0", "]", ")", "model", "=", ...
42.785714
0.009804
def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'): """ Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass ...
[ "def", "_", "(", "mcs", ",", "cls_name", "=", "'Object'", ",", "with_meta", "=", "None", ",", "hashattr", "=", "'_name'", ")", ":", "extype", "=", "super", "(", "ExtensibleByHashType", ",", "mcs", ")", ".", "_", "(", "cls_name", "=", "cls_name", ",", ...
38.483871
0.001635
def add(self, fact): """Create a VALID token and send it to all children.""" token = Token.valid(fact) MATCHER.debug("<BusNode> added %r", token) for child in self.children: child.callback(token)
[ "def", "add", "(", "self", ",", "fact", ")", ":", "token", "=", "Token", ".", "valid", "(", "fact", ")", "MATCHER", ".", "debug", "(", "\"<BusNode> added %r\"", ",", "token", ")", "for", "child", "in", "self", ".", "children", ":", "child", ".", "cal...
39
0.008368
def _load(self, exit_on_failure): """One you have added all your configuration data (Section, Element, ...) you need to load data from the config file.""" # pylint: disable-msg=W0621 log = logging.getLogger('argtoolbox') discoveredFileList = [] if self.config_file: ...
[ "def", "_load", "(", "self", ",", "exit_on_failure", ")", ":", "# pylint: disable-msg=W0621", "log", "=", "logging", ".", "getLogger", "(", "'argtoolbox'", ")", "discoveredFileList", "=", "[", "]", "if", "self", ".", "config_file", ":", "if", "isinstance", "("...
42.068182
0.001056
def parse_encoded_styles(text, normalize_key=None): """ Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a string). :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` and :data:`DEFAULT_LEVEL_STYLES` dictionaries...
[ "def", "parse_encoded_styles", "(", "text", ",", "normalize_key", "=", "None", ")", ":", "parsed_styles", "=", "{", "}", "for", "assignment", "in", "split", "(", "text", ",", "';'", ")", ":", "name", ",", "_", ",", "styles", "=", "assignment", ".", "pa...
42.511628
0.00107
def process_rawq(self): """Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ buf = b'' try: while self.rawq: # Handle non-IAC first (normal data). ...
[ "def", "process_rawq", "(", "self", ")", ":", "buf", "=", "b''", "try", ":", "while", "self", ".", "rawq", ":", "# Handle non-IAC first (normal data).", "char", "=", "self", ".", "rawq_getchar", "(", ")", "if", "char", "!=", "IAC", ":", "buf", "=", "buf"...
41.92
0.000699
def normalized_scalar_param_list(param, length, param_conv=None, keep_none=True, return_nonconv=False): """Return a list of given length from a scalar parameter. The typical use case is when a single value or a sequence of values is accepted as input. This function makes a ...
[ "def", "normalized_scalar_param_list", "(", "param", ",", "length", ",", "param_conv", "=", "None", ",", "keep_none", "=", "True", ",", "return_nonconv", "=", "False", ")", ":", "length", ",", "length_in", "=", "int", "(", "length", ")", ",", "length", "if...
35
0.000253
def define(self, *names, **kwargs): """Define a variable in the problem. Variables must be defined before they can be accessed by var() or set(). This function takes keyword arguments lower and upper to define the bounds of the variable (default: -inf to inf). The keyword argument ...
[ "def", "define", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "names", "=", "tuple", "(", "names", ")", "for", "name", "in", "names", ":", "if", "name", "in", "self", ".", "_variables", ":", "raise", "ValueError", "(", "'Varia...
39.969231
0.000751
def addl(self, value, start=0.0, end=float('inf')): """ Shortcut for ``add(Label(value, start, end))``. """ self.add(Label(value, start=start, end=end))
[ "def", "addl", "(", "self", ",", "value", ",", "start", "=", "0.0", ",", "end", "=", "float", "(", "'inf'", ")", ")", ":", "self", ".", "add", "(", "Label", "(", "value", ",", "start", "=", "start", ",", "end", "=", "end", ")", ")" ]
36
0.01087
def token(self): """ Returns a token from the current input. If tok is None from the current input, it means we are at end of current input (e.g. at end of include file). If so, closes the current input and discards it; then pops the previous input and lexer from the input stack,...
[ "def", "token", "(", "self", ")", ":", "tok", "=", "None", "if", "self", ".", "next_token", "is", "not", "None", ":", "tok", "=", "lex", ".", "LexToken", "(", ")", "tok", ".", "value", "=", "''", "tok", ".", "lineno", "=", "self", ".", "lex", "...
35.413793
0.001896
def retrieve_request(self, url): """Open the given url and decode and return the response url: The url to open. """ try: data = urlopen(url) except: print("Error Retrieving Data from Steam") sys.exit(2) return data.read().decode('utf-...
[ "def", "retrieve_request", "(", "self", ",", "url", ")", ":", "try", ":", "data", "=", "urlopen", "(", "url", ")", "except", ":", "print", "(", "\"Error Retrieving Data from Steam\"", ")", "sys", ".", "exit", "(", "2", ")", "return", "data", ".", "read",...
26
0.009288
def iter_poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Retrieve pages iteratively in a non-greedy manner. Automatically increments the sequenceNo as it continues to poll for results until the endpoint reports JOB_FINISHED or ...
[ "def", "iter_poll", "(", "self", ",", "query_id", "=", "None", ",", "sequence_no", "=", "None", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "while", "True", ":", "r", "=", "self", ".", "poll", "(", "query_id", ...
35.844444
0.002414
def list_nodes_full(conn=None, call=None): ''' Return a list of the VMs that are on the provider, with all fields ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or ' '--function.' ) if not conn: ...
[ "def", "list_nodes_full", "(", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_full function must be called with -f or '", "'--function.'", ")", "if", "not", "conn", ...
30.309524
0.000761
def _AddCredentialConfiguration( self, path_spec, credential_type, credential_data): """Adds a credential configuration. Args: path_spec (dfvfs.PathSpec): path specification. credential_type (str): credential type. credential_data (bytes): credential data. """ credential_configu...
[ "def", "_AddCredentialConfiguration", "(", "self", ",", "path_spec", ",", "credential_type", ",", "credential_data", ")", ":", "credential_configuration", "=", "configurations", ".", "CredentialConfiguration", "(", "credential_data", "=", "credential_data", ",", "credenti...
37.714286
0.001848
def output_mailbox(gandi, mailbox, output_keys, justify=16): """ Helper to output a mailbox information.""" quota = 'quota' in output_keys responder = 'responder' in output_keys if quota: output_keys.pop(output_keys.index('quota')) if responder: output_keys.pop(output_keys.index('r...
[ "def", "output_mailbox", "(", "gandi", ",", "mailbox", ",", "output_keys", ",", "justify", "=", "16", ")", ":", "quota", "=", "'quota'", "in", "output_keys", "responder", "=", "'responder'", "in", "output_keys", "if", "quota", ":", "output_keys", ".", "pop",...
34.575758
0.000853
def combine_argtype(observations): """Combines a list of Tuple types into one. Basically these are combined element wise into a Union with some additional unification effort (e.g. can apply PEP 484 style numeric tower). """ assert len(observations) > 0 assert is_Tuple(observations[0]) if len...
[ "def", "combine_argtype", "(", "observations", ")", ":", "assert", "len", "(", "observations", ")", ">", "0", "assert", "is_Tuple", "(", "observations", "[", "0", "]", ")", "if", "len", "(", "observations", ")", ">", "1", ":", "prms", "=", "[", "get_Tu...
36.428571
0.000955
def execute(query, data=None): """ Execute an arbitrary SQL query given by query, returning any results as a list of OrderedDicts. A list of values can be supplied as an, additional argument, which will be substituted into question marks in the query. """ connection = _State.connection() ...
[ "def", "execute", "(", "query", ",", "data", "=", "None", ")", ":", "connection", "=", "_State", ".", "connection", "(", ")", "_State", ".", "new_transaction", "(", ")", "if", "data", "is", "None", ":", "data", "=", "[", "]", "result", "=", "connecti...
26.384615
0.001406
def _dict_mapping_to_pb(mapping, proto_type): """ Convert a dict to protobuf. Args: mapping (dict): A dict that needs to be converted to protobuf. proto_type (str): The type of the Protobuf. Returns: An instance of the specified protobuf. """ converted_pb = getattr(trac...
[ "def", "_dict_mapping_to_pb", "(", "mapping", ",", "proto_type", ")", ":", "converted_pb", "=", "getattr", "(", "trace_pb2", ",", "proto_type", ")", "(", ")", "ParseDict", "(", "mapping", ",", "converted_pb", ")", "return", "converted_pb" ]
27.714286
0.002494
def get_section_marks(self): """For each section in AArtGeneProducts, return '*' or "" .""" return [abc if s in self.sec2chr else "." for s, abc in self.datobj.sec2chr.items()]
[ "def", "get_section_marks", "(", "self", ")", ":", "return", "[", "abc", "if", "s", "in", "self", ".", "sec2chr", "else", "\".\"", "for", "s", ",", "abc", "in", "self", ".", "datobj", ".", "sec2chr", ".", "items", "(", ")", "]" ]
63.333333
0.015625
def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False): "Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`." if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts)) return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts))
[ "def", "_do_perspective_warp", "(", "c", ":", "FlowField", ",", "targ_pts", ":", "Points", ",", "invert", "=", "False", ")", ":", "if", "invert", ":", "return", "_apply_perspective", "(", "c", ",", "_find_coeffs", "(", "targ_pts", ",", "_orig_pts", ")", ")...
70.25
0.014085
def AddInstanceTags(r, instance, tags, dry_run=False): """ Adds tags to an instance. @type instance: str @param instance: instance to add tags to @type tags: list of str @param tags: tags to add to the instance @type dry_run: bool @param dry_run: whether to perform a dry run @rtype...
[ "def", "AddInstanceTags", "(", "r", ",", "instance", ",", "tags", ",", "dry_run", "=", "False", ")", ":", "query", "=", "{", "\"tag\"", ":", "tags", ",", "\"dry-run\"", ":", "dry_run", ",", "}", "return", "r", ".", "request", "(", "\"put\"", ",", "\"...
22.857143
0.002
def _apex2qd_nonvectorized(self, alat, alon, height): """Convert from apex to quasi-dipole (not-vectorised) Parameters ----------- alat : (float) Apex latitude in degrees alon : (float) Apex longitude in degrees height : (float) Height...
[ "def", "_apex2qd_nonvectorized", "(", "self", ",", "alat", ",", "alon", ",", "height", ")", ":", "alat", "=", "helpers", ".", "checklat", "(", "alat", ",", "name", "=", "'alat'", ")", "# convert modified apex to quasi-dipole:", "qlon", "=", "alon", "# apex hei...
29.390244
0.00241
def emulate_mouse(self, key_code, x_val, y_val, data): """Emulate the ev codes using the data Windows has given us. Note that by default in Windows, to recognise a double click, you just notice two clicks in a row within a reasonablely short time period. However, if the applica...
[ "def", "emulate_mouse", "(", "self", ",", "key_code", ",", "x_val", ",", "y_val", ",", "data", ")", ":", "# Once again ignore Windows' relative time (since system", "# startup) and use the absolute time (since epoch i.e. 1st Jan", "# 1970).", "self", ".", "update_timeval", "(...
36.671429
0.000759
def compile(schema, pointer, context, scope=None): """ Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context .. _`...
[ "def", "compile", "(", "schema", ",", "pointer", ",", "context", ",", "scope", "=", "None", ")", ":", "schm", "=", "deepcopy", "(", "schema", ")", "scope", "=", "urljoin", "(", "scope", "or", "str", "(", "pointer", ")", ",", "schm", ".", "pop", "("...
44
0.000101
def fit(self, y, exogenous=None): """Fit the transformer Learns the value of ``lmbda``, if not specified in the constructor. If defined in the constructor, is not re-learned. Parameters ---------- y : array-like or None, shape=(n_samples,) The endogenous (ti...
[ "def", "fit", "(", "self", ",", "y", ",", "exogenous", "=", "None", ")", ":", "lam1", "=", "self", ".", "lmbda", "lam2", "=", "self", ".", "lmbda2", "if", "lam2", "<", "0", ":", "raise", "ValueError", "(", "\"lmbda2 must be a non-negative scalar value\"", ...
33
0.00203
def fin(self): '''Indicate that this message is finished processing''' self.connection.fin(self.id) self.processed = True
[ "def", "fin", "(", "self", ")", ":", "self", ".", "connection", ".", "fin", "(", "self", ".", "id", ")", "self", ".", "processed", "=", "True" ]
35.5
0.013793
def reference(self, referencing_path=None): """How to reference this address in a BUILD file. :API: public """ if referencing_path is not None and self._spec_path == referencing_path: return self.relative_spec elif os.path.basename(self._spec_path) != self._target_name: return self.spec...
[ "def", "reference", "(", "self", ",", "referencing_path", "=", "None", ")", ":", "if", "referencing_path", "is", "not", "None", "and", "self", ".", "_spec_path", "==", "referencing_path", ":", "return", "self", ".", "relative_spec", "elif", "os", ".", "path"...
31.727273
0.011142
def get_template_parameters_s3(template_key, s3_resource): """ Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found Args: template_key: S3 key for template file. omit bucket. s3_resource: a boto3 s3 resource Returns: filename of paramete...
[ "def", "get_template_parameters_s3", "(", "template_key", ",", "s3_resource", ")", ":", "for", "suffix", "in", "EFConfig", ".", "PARAMETER_FILE_SUFFIXES", ":", "parameters_key", "=", "template_key", ".", "replace", "(", "\"/templates\"", ",", "\"/parameters\"", ")", ...
35.5
0.01372
def set_colors(self,*args,**kw): """Shorthand access to the color table scheme selector method.""" # Set own color table self.color_scheme_table.set_active_scheme(*args,**kw) # for convenience, set Colors to the active scheme self.Colors = self.color_scheme_table.active_colors ...
[ "def", "set_colors", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# Set own color table", "self", ".", "color_scheme_table", ".", "set_active_scheme", "(", "*", "args", ",", "*", "*", "kw", ")", "# for convenience, set Colors to the active sche...
44.8
0.015317
def size(self, value): """gets/sets the size""" if self._size != value and \ isinstance(value, (int, float, long)): self._size = value
[ "def", "size", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_size", "!=", "value", "and", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "self", ".", "_size", "=", "value" ]
33.8
0.011561
def component_title(component): """ Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc. """ title = u'' label_text = u'' title_text = u'' if component.get('label'): label_text = component.get('label') if component.get...
[ "def", "component_title", "(", "component", ")", ":", "title", "=", "u''", "label_text", "=", "u''", "title_text", "=", "u''", "if", "component", ".", "get", "(", "'label'", ")", ":", "label_text", "=", "component", ".", "get", "(", "'label'", ")", "if",...
23.076923
0.0016
def output(self,pin,value): """Set the specified pin the provided high/low value. Value should be either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean. """ self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)
[ "def", "output", "(", "self", ",", "pin", ",", "value", ")", ":", "self", ".", "mraa_gpio", ".", "Gpio", ".", "write", "(", "self", ".", "mraa_gpio", ".", "Gpio", "(", "pin", ")", ",", "value", ")" ]
48.8
0.016129
def largest_graph(mol): """Return a molecule which has largest graph in the compound Passing single molecule object will results as same as molutil.clone """ mol.require("Valence") mol.require("Topology") m = clone(mol) # Avoid modification of original object if m.isolated: for k in...
[ "def", "largest_graph", "(", "mol", ")", ":", "mol", ".", "require", "(", "\"Valence\"", ")", "mol", ".", "require", "(", "\"Topology\"", ")", "m", "=", "clone", "(", "mol", ")", "# Avoid modification of original object", "if", "m", ".", "isolated", ":", "...
35.909091
0.002469
def add_pre(h,sec_list,section,order_list=None,branch_order=None): """ A helper function that traverses a neuron's morphology (or a sub-tree) of the morphology in pre-order. This is usually not necessary for the user to import. """ sec_list.append(section) sref = h.SectionRef(sec=section) ...
[ "def", "add_pre", "(", "h", ",", "sec_list", ",", "section", ",", "order_list", "=", "None", ",", "branch_order", "=", "None", ")", ":", "sec_list", ".", "append", "(", "section", ")", "sref", "=", "h", ".", "SectionRef", "(", "sec", "=", "section", ...
31.647059
0.018051
def remove_module_load(state_dict): """create new OrderedDict that does not contain `module.`""" new_state_dict = OrderedDict() for k, v in state_dict.items(): new_state_dict[k[7:]] = v return new_state_dict
[ "def", "remove_module_load", "(", "state_dict", ")", ":", "new_state_dict", "=", "OrderedDict", "(", ")", "for", "k", ",", "v", "in", "state_dict", ".", "items", "(", ")", ":", "new_state_dict", "[", "k", "[", "7", ":", "]", "]", "=", "v", "return", ...
43.8
0.008969
def timezone(zone): r''' Return a datetime.tzinfo implementation for the given timezone >>> from datetime import datetime, timedelta >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> timezone(u'US/Eastern') is eastern True >>> utc_dt = ...
[ "def", "timezone", "(", "zone", ")", ":", "if", "zone", ".", "upper", "(", ")", "==", "'UTC'", ":", "return", "utc", "try", ":", "zone", "=", "zone", ".", "encode", "(", "'US-ASCII'", ")", "except", "UnicodeEncodeError", ":", "# All valid timezones are ASC...
30.54902
0.000622
def closest_val(x, L): ''' Finds the index value in an iterable closest to a desired value. Parameters ---------- x : object The desired value. L : iterable The iterable in which to search for the desired value. Returns ------- index : int The index of the c...
[ "def", "closest_val", "(", "x", ",", "L", ")", ":", "# Make sure the iterable is nonempty", "if", "len", "(", "L", ")", "==", "0", ":", "raise", "ValueError", "(", "'L must not be empty'", ")", "if", "isinstance", "(", "L", ",", "np", ".", "ndarray", ")", ...
25.555556
0.000838
def common_req(self, execute, send_body=True): "Common code for GET and POST requests" self._SERVER = {'CLIENT_ADDR_HOST': self.client_address[0], 'CLIENT_ADDR_PORT': self.client_address[1]} self._to_log = True self._cmd ...
[ "def", "common_req", "(", "self", ",", "execute", ",", "send_body", "=", "True", ")", ":", "self", ".", "_SERVER", "=", "{", "'CLIENT_ADDR_HOST'", ":", "self", ".", "client_address", "[", "0", "]", ",", "'CLIENT_ADDR_PORT'", ":", "self", ".", "client_addre...
36.06383
0.010339
def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser: """ Creates an argument parser populated with the arg formats for the server command. """ parser = arg_parser or ArgumentParser() parser.description = 'Cauldron kernel server' parser.add_argument( '-p', '--port...
[ "def", "create_parser", "(", "arg_parser", ":", "ArgumentParser", "=", "None", ")", "->", "ArgumentParser", ":", "parser", "=", "arg_parser", "or", "ArgumentParser", "(", ")", "parser", ".", "description", "=", "'Cauldron kernel server'", "parser", ".", "add_argum...
19.377778
0.001092
def wait_for_ribcl_firmware_update_to_complete(ribcl_object): """Continuously checks for iLO firmware update to complete.""" def is_ilo_reset_initiated(): """Checks for initiation of iLO reset Invokes the ``get_product_name`` api and returns i) True, if exception gets raised as tha...
[ "def", "wait_for_ribcl_firmware_update_to_complete", "(", "ribcl_object", ")", ":", "def", "is_ilo_reset_initiated", "(", ")", ":", "\"\"\"Checks for initiation of iLO reset\n\n Invokes the ``get_product_name`` api and returns\n i) True, if exception gets raised as that marks...
39.741935
0.000792
def import_sbml(document): """ Import a model from a SBMLDocument. Parameters ---------- document : SBMLDocument Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume. """ from...
[ "def", "import_sbml", "(", "document", ")", ":", "from", "ecell4", ".", "util", ".", "decorator", "import", "generate_ratelaw", "m", "=", "document", ".", "getModel", "(", ")", "if", "m", ".", "getNumCompartments", "(", ")", "==", "0", ":", "raise", "Run...
30.540323
0.001535
def partition_found(partition, description): """ returns True, if the partition (--partition) is in the description we received from the host """ # if we want to have a linux partition (/) we use the full path (startswith "/" would result in / /var /dev etc). # if we start with something else, we u...
[ "def", "partition_found", "(", "partition", ",", "description", ")", ":", "# if we want to have a linux partition (/) we use the full path (startswith \"/\" would result in / /var /dev etc). ", "# if we start with something else, we use the startswith function", "if", "\"/\"", "in", "parti...
37.823529
0.009105
def _chain_future(source, dest): """Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future. """ i...
[ "def", "_chain_future", "(", "source", ",", "dest", ")", ":", "if", "not", "isinstance", "(", "source", ",", "(", "asyncio", ".", "Future", ",", "concurrent", ".", "futures", ".", "Future", ")", ")", ":", "raise", "TypeError", "(", "'A future is required f...
43.676471
0.000659
def _assign_uid(self, sid): """ Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object """ self._uid = ru.generate_id('stage.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid) for task in self._tasks: ...
[ "def", "_assign_uid", "(", "self", ",", "sid", ")", ":", "self", ".", "_uid", "=", "ru", ".", "generate_id", "(", "'stage.%(item_counter)04d'", ",", "ru", ".", "ID_CUSTOM", ",", "namespace", "=", "sid", ")", "for", "task", "in", "self", ".", "_tasks", ...
36.3
0.010753
def _get_section(name, source): # type: (str, str) -> Optional[str] """Extract the named section from the source. Args: name: The name of the section to extract (e.g. "Usage"). source: The usage string to parse. Returns: A string containing only the requested section. If the se...
[ "def", "_get_section", "(", "name", ",", "source", ")", ":", "# type: (str, str) -> Optional[str]", "pattern", "=", "re", ".", "compile", "(", "'^([^\\n]*{name}[^\\n]*\\n?(?:[ \\t].*?(?:\\n|$))*)'", ".", "format", "(", "name", "=", "name", ")", ",", "re", ".", "IG...
35.315789
0.001451
def get_user_roles(uid,**kwargs): """ Get the roles for a user. @param user_id """ try: user_roles = db.DBSession.query(Role).filter(Role.id==RoleUser.role_id, RoleUser.user_id==uid).all() return user_roles except NoResult...
[ "def", "get_user_roles", "(", "uid", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user_roles", "=", "db", ".", "DBSession", ".", "query", "(", "Role", ")", ".", "filter", "(", "Role", ".", "id", "==", "RoleUser", ".", "role_id", ",", "RoleUser", ...
35.818182
0.012376
def is_timeseries(nc, variable): ''' Returns true if the variable is a time series feature type. :param netCDF4.Dataset nc: An open netCDF dataset :param str variable: name of the variable to check ''' # x, y, z, t(t) # X(t) dims = nc.variables[variable].dimensions cmatrix = coordi...
[ "def", "is_timeseries", "(", "nc", ",", "variable", ")", ":", "# x, y, z, t(t)", "# X(t)", "dims", "=", "nc", ".", "variables", "[", "variable", "]", ".", "dimensions", "cmatrix", "=", "coordinate_dimension_matrix", "(", "nc", ")", "time_variables", "=", "get_...
25.451613
0.001221