text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_completed(self): """Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation. """ postgame = self.get_postgame() if postgame: return postgame.complete else: ...
[ "def", "get_completed", "(", "self", ")", ":", "postgame", "=", "self", ".", "get_postgame", "(", ")", "if", "postgame", ":", "return", "postgame", ".", "complete", "else", ":", "return", "True", "if", "self", ".", "_cache", "[", "'resigned'", "]", "else...
33.545455
15.363636
def close(self): """Close the connection.""" if self.sock: self.sock.close() self.sock = 0 self.eof = 1
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "0", "self", ".", "eof", "=", "1" ]
23.666667
15.5
def get_value_tuple(self): """ Returns a tuple of the color's values (in order). For example, an LabColor object will return (lab_l, lab_a, lab_b), where each member of the tuple is the float value for said variable. """ retval = tuple() for val in self.VALUES: ...
[ "def", "get_value_tuple", "(", "self", ")", ":", "retval", "=", "tuple", "(", ")", "for", "val", "in", "self", ".", "VALUES", ":", "retval", "+=", "(", "getattr", "(", "self", ",", "val", ")", ",", ")", "return", "retval" ]
37.4
14.8
def benchmark_command(cmd, progress): """Benchmark one command execution""" full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd) (_, err) = subprocess.Popen( ['/bin/sh', '-c', full_cmd], stdin=subprocess.PIPE, ...
[ "def", "benchmark_command", "(", "cmd", ",", "progress", ")", ":", "full_cmd", "=", "'/usr/bin/time --format=\"%U %M\" {0}'", ".", "format", "(", "cmd", ")", "print", "'{0:6.2f}% Running {1}'", ".", "format", "(", "100.0", "*", "progress", ",", "full_cmd", ")", ...
33.75
15.6
def p_classDeclaration(p): # pylint: disable=line-too-long """classDeclaration : CLASS className '{' classFeatureList '}' ';' | CLASS className superClass '{' classFeatureList '}' ';' | CLASS className alias '{' classFeatureList '}' ';' | C...
[ "def", "p_classDeclaration", "(", "p", ")", ":", "# pylint: disable=line-too-long", "# noqa: E501", "superclass", "=", "None", "alias", "=", "None", "quals", "=", "[", "]", "if", "isinstance", "(", "p", "[", "1", "]", ",", "six", ".", "string_types", ")", ...
39.12069
16.413793
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.noise_k.free_params = value[self.k.num_free_p...
[ "def", "free_params", "(", "self", ",", "value", ")", ":", "value", "=", "scipy", ".", "asarray", "(", "value", ",", "dtype", "=", "float", ")", "self", ".", "K_up_to_date", "=", "False", "self", ".", "k", ".", "free_params", "=", "value", "[", ":", ...
55.555556
20.888889
async def disconnect_message(self, message, context): """Handle a disconnect message. See :meth:`AbstractDeviceAdapter.disconnect`. """ conn_string = message.get('connection_string') client_id = context.user_data await self.disconnect(client_id, conn_string)
[ "async", "def", "disconnect_message", "(", "self", ",", "message", ",", "context", ")", ":", "conn_string", "=", "message", ".", "get", "(", "'connection_string'", ")", "client_id", "=", "context", ".", "user_data", "await", "self", ".", "disconnect", "(", "...
30
17.6
def read_config(ctx, param, config_path): """Callback that is used whenever --config is passed.""" if sys.argv[1] == 'init': return cfg = ctx.ensure_object(Config) if config_path is None: config_path = path.join(sys.path[0], 'v2ex_config.json') if not path.exists(config_path): ...
[ "def", "read_config", "(", "ctx", ",", "param", ",", "config_path", ")", ":", "if", "sys", ".", "argv", "[", "1", "]", "==", "'init'", ":", "return", "cfg", "=", "ctx", ".", "ensure_object", "(", "Config", ")", "if", "config_path", "is", "None", ":",...
42.076923
13.615385
def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) repo.ui.quiet = True cl, err = LoadCL(ui, repo, name, web=True) if err != "": raise hg_util....
[ "def", "upload", "(", "ui", ",", "repo", ",", "name", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "repo", ".", "ui", ".", "quiet", "=", "True", "cl", ",", "err"...
27.294118
16.823529
def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.format(output_path)) stash.export(output_path=output_path) click.echo('Export complete!') exc...
[ "def", "export_keys", "(", "output_path", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Exporting stash to {0}...'", ".", ...
32
15
def fetch(self, task_channel=values.unset): """ Fetch a WorkspaceRealTimeStatisticsInstance :param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel. :returns: Fetched WorkspaceRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace....
[ "def", "fetch", "(", "self", ",", "task_channel", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "fetch", "(", "task_channel", "=", "task_channel", ",", ")" ]
45.1
26.9
def get_family_search_session(self, proxy=None): """Gets the ``OsidSession`` associated with the family search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilySearchSession) - a ``FamilySearchSession`` raise: NullArgument - ``proxy`` ...
[ "def", "get_family_search_session", "(", "self", ",", "proxy", "=", "None", ")", ":", "if", "not", "self", ".", "supports_family_search", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError...
40.28
17.2
def install_board_with_programmer(mcu, programmer, f_cpu=16000000, core='arduino', replace_existing=False, ): """install board with programmer."""...
[ "def", "install_board_with_programmer", "(", "mcu", ",", "programmer", ",", "f_cpu", "=", "16000000", ",", "core", "=", "'arduino'", ",", "replace_existing", "=", "False", ",", ")", ":", "bunch", "=", "AutoBunch", "(", ")", "board_id", "=", "'{mcu}_{f_cpu}_{pr...
42.75
17.416667
def remove_images(): """Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used""" client = get_docker_client() removed = _remove_dangling_images() dusty_images = get_dusty_images() all_images = client.images(all=True) for image in all_images: ...
[ "def", "remove_images", "(", ")", ":", "client", "=", "get_docker_client", "(", ")", "removed", "=", "_remove_dangling_images", "(", ")", "dusty_images", "=", "get_dusty_images", "(", ")", "all_images", "=", "client", ".", "images", "(", "all", "=", "True", ...
43.75
14.25
def _parse_list(element, definition): """Parse xml element by definition given by list. Find all elements matched by the string given as the first value in the list (as XPath or @attribute). If there is a second argument it will be handled as a definitions for the elements matched or the text when...
[ "def", "_parse_list", "(", "element", ",", "definition", ")", ":", "if", "len", "(", "definition", ")", "==", "0", ":", "raise", "XmlToJsonException", "(", "'List definition needs some definition'", ")", "tag", "=", "definition", "[", "0", "]", "tag_def", "=",...
28.62963
20.259259
def make_password(length, chars=string.letters + string.digits + '#$%&!'): """ Generate and return a random password :param length: Desired length :param chars: Character set to use """ return get_random_string(length, chars)
[ "def", "make_password", "(", "length", ",", "chars", "=", "string", ".", "letters", "+", "string", ".", "digits", "+", "'#$%&!'", ")", ":", "return", "get_random_string", "(", "length", ",", "chars", ")" ]
30.375
10.875
def _resolve_attribute(self, attribute): """Recursively replaces references to other attributes with their value. Args: attribute (str): The name of the attribute to resolve. Returns: str: The resolved value of 'attribute'. """ value = self.attributes[a...
[ "def", "_resolve_attribute", "(", "self", ",", "attribute", ")", ":", "value", "=", "self", ".", "attributes", "[", "attribute", "]", "if", "not", "value", ":", "return", "None", "resolved_value", "=", "re", ".", "sub", "(", "'\\$\\((.*?)\\)'", ",", "self"...
31.666667
20
def run_step(context): """Write payload out to json file. Args: context: pypyr.context.Context. Mandatory. The following context keys expected: - fileWriteJson - path. mandatory. path-like. Write output file to here. Will create...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_child_key_has_value", "(", "'fileWriteJson'", ",", "'path'", ",", "__name__", ")", "out_path", "=", "context", ".", "get_formatted_string", "(",...
39.863636
25.886364
def iter_series(self, workbook, row, col): """ Yield series dictionaries with values resolved to the final excel formulas. """ for series in self.__series: series = dict(series) series["values"] = series["values"].get_formula(workbook, row, col) if "ca...
[ "def", "iter_series", "(", "self", ",", "workbook", ",", "row", ",", "col", ")", ":", "for", "series", "in", "self", ".", "__series", ":", "series", "=", "dict", "(", "series", ")", "series", "[", "\"values\"", "]", "=", "series", "[", "\"values\"", ...
44.8
16.4
def Upload(self,directory,filename): """Uploads/Updates/Replaces files""" db = self._loadDB(directory) logger.debug("wp: Attempting upload of %s"%(filename)) # See if this already exists in our DB if db.has_key(filename): pid=db[filename] logger.debug('...
[ "def", "Upload", "(", "self", ",", "directory", ",", "filename", ")", ":", "db", "=", "self", ".", "_loadDB", "(", "directory", ")", "logger", ".", "debug", "(", "\"wp: Attempting upload of %s\"", "%", "(", "filename", ")", ")", "# See if this already exists i...
29.644444
18.444444
def list_containers(self): '''return a list of containers, determined by finding the metadata field "type" with value "container." We alert the user to no containers if results is empty, and exit {'metadata': {'items': [ {'key': 't...
[ "def", "list_containers", "(", "self", ")", ":", "results", "=", "[", "]", "for", "image", "in", "self", ".", "_bucket", ".", "list_blobs", "(", ")", ":", "if", "image", ".", "metadata", "is", "not", "None", ":", "if", "\"type\"", "in", "image", ".",...
31.833333
21.25
def apply_t0(self, hits): """Apply only t0s""" if HAVE_NUMBA: apply_t0_nb( hits.time, hits.dom_id, hits.channel_id, self._lookup_tables ) else: n = len(hits) cal = np.empty(n) lookup = self._calib_by_dom_and_channel ...
[ "def", "apply_t0", "(", "self", ",", "hits", ")", ":", "if", "HAVE_NUMBA", ":", "apply_t0_nb", "(", "hits", ".", "time", ",", "hits", ".", "dom_id", ",", "hits", ".", "channel_id", ",", "self", ".", "_lookup_tables", ")", "else", ":", "n", "=", "len"...
32.533333
17.2
def get_or_add_childTnLst(self): """Return parent element for a new `p:video` child element. The `p:video` element causes play controls to appear under a video shape (pic shape containing video). There can be more than one video shape on a slide, which causes the precondition to vary. I...
[ "def", "get_or_add_childTnLst", "(", "self", ")", ":", "childTnLst", "=", "self", ".", "_childTnLst", "if", "childTnLst", "is", "None", ":", "childTnLst", "=", "self", ".", "_add_childTnLst", "(", ")", "return", "childTnLst" ]
50.529412
22.294118
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
[ "def", "_render_log", "(", ")", ":", "config", "=", "load_config", "(", "ROOT", ")", "definitions", "=", "config", "[", "'types'", "]", "fragments", ",", "fragment_filenames", "=", "find_fragments", "(", "pathlib", ".", "Path", "(", "config", "[", "'director...
30.789474
15.526316
def _insertBPoint(self, index, type, anchor, bcpIn, bcpOut, **kwargs): """ Subclasses may override this method. """ # insert a simple line segment at the given anchor # look it up as a bPoint and change the bcpIn and bcpOut there # this avoids code duplication sel...
[ "def", "_insertBPoint", "(", "self", ",", "index", ",", "type", ",", "anchor", ",", "bcpIn", ",", "bcpOut", ",", "*", "*", "kwargs", ")", ":", "# insert a simple line segment at the given anchor", "# look it up as a bPoint and change the bcpIn and bcpOut there", "# this a...
37.684211
12
def stop(self): """Synchronously stop the background loop from outside. This method will block until the background loop is completely stopped so it cannot be called from inside the loop itself. This method is safe to call multiple times. If the loop is not currently running i...
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "loop", ":", "return", "if", "self", ".", "inside_loop", "(", ")", ":", "raise", "InternalError", "(", "\"BackgroundEventLoop.stop() called from inside event loop; \"", "\"would have deadlocked.\"", ")"...
32.814815
23.703704
def credentials_required(view_func): """ This decorator should be used with views that need simple authentication against Django's authentication framework. """ @wraps(view_func, assigned=available_attrs(view_func)) def decorator(request, *args, **kwargs): if settings.LOCALSHOP_USE_PROXI...
[ "def", "credentials_required", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "decorator", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if",...
39.222222
19.388889
def get_user_details(user_id): """Get information about number of changesets, blocks and mapping days of a user, using both the OSM API and the Mapbox comments APIself. """ reasons = [] try: url = OSM_USERS_API.format(user_id=requests.compat.quote(user_id)) user_request = requests.ge...
[ "def", "get_user_details", "(", "user_id", ")", ":", "reasons", "=", "[", "]", "try", ":", "url", "=", "OSM_USERS_API", ".", "format", "(", "user_id", "=", "requests", ".", "compat", ".", "quote", "(", "user_id", ")", ")", "user_request", "=", "requests"...
46.90625
15.28125
def start(self, **kwargs): """ Start this container. Similar to the ``docker start`` command, but doesn't support attach options. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ return self.client.api.start(self....
[ "def", "start", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "client", ".", "api", ".", "start", "(", "self", ".", "id", ",", "*", "*", "kwargs", ")" ]
32.4
14.2
def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $...
[ "def", "set_password", "(", "name", ",", "password", ")", ":", "s_file", "=", "'/etc/shadow'", "ret", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", "(", "s_file", ")", ":", "return", "ret", "lines", "=", "[", "]", "with", "salt", "....
31.741935
18.645161
def local_time(unix_time, utc_offset, microseconds): """ Returns a UNIX time as a broken down time for a particular transition type. :type unix_time: int :type utc_offset: int :type microseconds: int :rtype: tuple """ year = EPOCH_YEAR seconds = int(math.floor(unix_time)) ...
[ "def", "local_time", "(", "unix_time", ",", "utc_offset", ",", "microseconds", ")", ":", "year", "=", "EPOCH_YEAR", "seconds", "=", "int", "(", "math", ".", "floor", "(", "unix_time", ")", ")", "# Shift to a base year that is 400-year aligned.", "if", "seconds", ...
28.219178
16.191781
def send_button(recipient): """ Shortcuts are supported page.send(recipient, Template.Buttons("hello", [ {'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'}, {'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'}, ...
[ "def", "send_button", "(", "recipient", ")", ":", "page", ".", "send", "(", "recipient", ",", "Template", ".", "Buttons", "(", "\"hello\"", ",", "[", "Template", ".", "ButtonWeb", "(", "\"Open Web URL\"", ",", "\"https://www.oculus.com/en-us/rift/\"", ")", ",", ...
50.142857
28
def validate_minimum(value, minimum, is_exclusive, **kwargs): """ Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`. """ if is_exclusive: comp...
[ "def", "validate_minimum", "(", "value", ",", "minimum", ",", "is_exclusive", ",", "*", "*", "kwargs", ")", ":", "if", "is_exclusive", ":", "comparison_text", "=", "\"greater than\"", "compare_fn", "=", "operator", ".", "gt", "else", ":", "comparison_text", "=...
36.823529
18.352941
def gen_triplets_master(wv_master, geometry=None, debugplot=0): """Compute information associated to triplets in master table. Determine all the possible triplets that can be generated from the array `wv_master`. In addition, the relative position of the central line of each triplet is also computed. ...
[ "def", "gen_triplets_master", "(", "wv_master", ",", "geometry", "=", "None", ",", "debugplot", "=", "0", ")", ":", "nlines_master", "=", "wv_master", ".", "size", "# Check that the wavelengths in the master table are sorted", "wv_previous", "=", "wv_master", "[", "0"...
41.607843
20.480392
def check_days(text): """Suggest the preferred forms.""" err = "MAU102" msg = "Days of the week should be capitalized. '{}' is the preferred form." list = [ ["Monday", ["monday"]], ["Tuesday", ["tuesday"]], ["Wednesday", ["wednesday"]], ["Thursday", ["...
[ "def", "check_days", "(", "text", ")", ":", "err", "=", "\"MAU102\"", "msg", "=", "\"Days of the week should be capitalized. '{}' is the preferred form.\"", "list", "=", "[", "[", "\"Monday\"", ",", "[", "\"monday\"", "]", "]", ",", "[", "\"Tuesday\"", ",", "[", ...
30.176471
18.176471
def get_symbols_list(self): '''Return a list of GdxSymb found in the GdxFile.''' slist = [] rc, nSymb, nElem = gdxcc.gdxSystemInfo(self.gdx_handle) assert rc, 'Unable to retrieve "%s" info' % self.filename self.number_symbols = nSymb self.number_elements = nElem s...
[ "def", "get_symbols_list", "(", "self", ")", ":", "slist", "=", "[", "]", "rc", ",", "nSymb", ",", "nElem", "=", "gdxcc", ".", "gdxSystemInfo", "(", "self", ".", "gdx_handle", ")", "assert", "rc", ",", "'Unable to retrieve \"%s\" info'", "%", "self", ".", ...
38.5
12.5
def consume(self, kind): """Consume one token and verify it is of the expected kind.""" next_token = self.stream.move() assert next_token.kind == kind
[ "def", "consume", "(", "self", ",", "kind", ")", ":", "next_token", "=", "self", ".", "stream", ".", "move", "(", ")", "assert", "next_token", ".", "kind", "==", "kind" ]
42.75
4.75
def database_set_properties(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/setProperties API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties """ return DXHTTPRequest('/%s/...
[ "def", "database_set_properties", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/setProperties'", "%", "object_id", ",", "input_params", ",", "alw...
56
36.857143
def start(self, stages=None): """ Makes the ``Piper`` ready to return results. This involves starting the the provided ``NuMap`` instance. If multiple ``Pipers`` share a ``NuMap`` instance the order in which these ``Pipers`` are started is important. The valid order is upstrea...
[ "def", "start", "(", "self", ",", "stages", "=", "None", ")", ":", "# defaults differ linear vs. parallel", "stages", "=", "stages", "or", "(", "(", "0", ",", ")", "if", "self", ".", "imap", "is", "imap", "else", "(", "0", ",", "1", ",", "2", ")", ...
46.68
23.32
def create_node(hostname, username, password, name, address): ''' Create a new node if it does not already exist. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the node to cr...
[ "def", "create_node", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "address", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", ...
27.019608
22.352941
def _cmd(self, cmd, *args, **kw): ''' write a single command, with variable number of arguments. after the command, the device must return ACK ''' ok = kw.setdefault('ok', False) self._wakeup() if args: cmd = "%s %s" % (cmd, ' '.join(str(a) for a in a...
[ "def", "_cmd", "(", "self", ",", "cmd", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "ok", "=", "kw", ".", "setdefault", "(", "'ok'", ",", "False", ")", "self", ".", "_wakeup", "(", ")", "if", "args", ":", "cmd", "=", "\"%s %s\"", "%", "(...
34.791667
16.291667
def new_text_cell(text=None): """Create a new text cell.""" cell = NotebookNode() if text is not None: cell.text = unicode(text) cell.cell_type = u'text' return cell
[ "def", "new_text_cell", "(", "text", "=", "None", ")", ":", "cell", "=", "NotebookNode", "(", ")", "if", "text", "is", "not", "None", ":", "cell", ".", "text", "=", "unicode", "(", "text", ")", "cell", ".", "cell_type", "=", "u'text'", "return", "cel...
26.714286
12.285714
def save(name, filter=False): ''' Save the register to <salt cachedir>/thorium/saves/<name>, or to an absolute path. If an absolute path is specified, then the directory will be created non-recursively if it doesn't exist. USAGE: .. code-block:: yaml foo: file.save ...
[ "def", "save", "(", "name", ",", "filter", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "True", "}", "if", "name", ".", "startswith", "(", "'/'...
26.277778
22.333333
def separate_operations(document_ast: DocumentNode) -> Dict[str, DocumentNode]: """Separate operations in a given AST document. This function accepts a single AST document which may contain many operations and fragments and returns a collection of AST documents each of which contains a single operation...
[ "def", "separate_operations", "(", "document_ast", ":", "DocumentNode", ")", "->", "Dict", "[", "str", ",", "DocumentNode", "]", ":", "# Populate metadata and build a dependency graph.", "visitor", "=", "SeparateOperations", "(", ")", "visit", "(", "document_ast", ","...
42.5
21.441176
def get(self, hostport): """Get a Peer for the given destination. A new Peer is added to the peer heap and returned if one does not already exist for the given host-port. Otherwise, the existing Peer is returned. """ assert hostport, "hostport is required" assert...
[ "def", "get", "(", "self", ",", "hostport", ")", ":", "assert", "hostport", ",", "\"hostport is required\"", "assert", "isinstance", "(", "hostport", ",", "basestring", ")", ",", "\"hostport must be a string\"", "if", "hostport", "not", "in", "self", ".", "_peer...
34.285714
18.071429
def with_metaclass(meta, *bases): """Python 2 and 3 compatible way to do meta classes""" class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, "temporary_class", (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "class", "metaclass", "(", "meta", ")", ":", "def", "__new__", "(", "cls", ",", "name", ",", "this_bases", ",", "d", ")", ":", "return", "meta", "(", "name", ",", "bases", ",", "d",...
32.875
16.125
def update(self, json_state): """Update the json data from a dictionary. Only updates if it already exists in the device. """ self._json_state.update( {k: json_state[k] for k in json_state if self._json_state.get(k)}) self._update_name()
[ "def", "update", "(", "self", ",", "json_state", ")", ":", "self", ".", "_json_state", ".", "update", "(", "{", "k", ":", "json_state", "[", "k", "]", "for", "k", "in", "json_state", "if", "self", ".", "_json_state", ".", "get", "(", "k", ")", "}",...
35.375
15.75
def create_table_level(self): """Create the QTableView that will hold the level model.""" self.table_level = QTableView() self.table_level.setEditTriggers(QTableWidget.NoEditTriggers) self.table_level.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_level.setVe...
[ "def", "create_table_level", "(", "self", ")", ":", "self", ".", "table_level", "=", "QTableView", "(", ")", "self", ".", "table_level", ".", "setEditTriggers", "(", "QTableWidget", ".", "NoEditTriggers", ")", "self", ".", "table_level", ".", "setHorizontalScrol...
63.4375
22.9375
def from_config_specs(cls, config_specs, prepare=True): """ Alternate constructor that merges config attributes from ``$HOME/.bangrc`` and :attr:`config_specs` into a single :class:`Config` object. The first (and potentially *only* spec) in :attr:`config_specs` should be...
[ "def", "from_config_specs", "(", "cls", ",", "config_specs", ",", "prepare", "=", "True", ")", ":", "bangrc", "=", "parse_bangrc", "(", ")", "config_dir", "=", "bangrc", ".", "get", "(", "A", ".", "CONFIG_DIR", ",", "DEFAULT_CONFIG_DIR", ")", "config_paths",...
37.923077
22.487179
def do_set(self, args: argparse.Namespace) -> None: """Set a settable parameter or show current settings of parameters""" # Check if param was passed in if not args.param: return self.show(args) param = utils.norm_fold(args.param.strip()) # Check if value was passed...
[ "def", "do_set", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# Check if param was passed in", "if", "not", "args", ".", "param", ":", "return", "self", ".", "show", "(", "args", ")", "param", "=", "utils", ".", ...
36.69697
16.787879
def _getScriptSettingsFromIniFile(policy_info): ''' helper function to parse/read a GPO Startup/Shutdown script file psscript.ini and script.ini file definitions are here https://msdn.microsoft.com/en-us/library/ff842529.aspx https://msdn.microsoft.com/en-us/library/dd303238.aspx ''' ...
[ "def", "_getScriptSettingsFromIniFile", "(", "policy_info", ")", ":", "_existingData", "=", "None", "if", "os", ".", "path", ".", "isfile", "(", "policy_info", "[", "'ScriptIni'", "]", "[", "'IniPath'", "]", ")", ":", "with", "salt", ".", "utils", ".", "fi...
53.78125
32.84375
def _prefer_package(self, package): """ Prefer a serializtion handler over other handlers. :param str package: The name of the package to use :raises ValueError: When the given package name is not one of the available supported serializtion packages for this handler :return:...
[ "def", "_prefer_package", "(", "self", ",", "package", ")", ":", "if", "isinstance", "(", "package", ",", "str", ")", "and", "package", "!=", "self", ".", "imported", ":", "if", "package", "not", "in", "self", ".", "packages", ":", "raise", "ValueError",...
43.130435
18.130435
def _get_team_abbreviation(self, team): """ Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. Parame...
[ "def", "_get_team_abbreviation", "(", "self", ",", "team", ")", ":", "name_tag", "=", "team", "(", "'th[data-stat=\"school_name\"] a'", ")", "team_abbreviation", "=", "re", ".", "sub", "(", "r'.*/cfb/schools/'", ",", "''", ",", "str", "(", "name_tag", ")", ")"...
35.565217
22
def props_to_image(regionprops, shape, prop): r""" Creates an image with each region colored according the specified ``prop``, as obtained by ``regionprops_3d``. Parameters ---------- regionprops : list This is a list of properties for each region that is computed by PoreSpy's `...
[ "def", "props_to_image", "(", "regionprops", ",", "shape", ",", "prop", ")", ":", "im", "=", "sp", ".", "zeros", "(", "shape", "=", "shape", ")", "for", "r", "in", "regionprops", ":", "if", "prop", "==", "'convex'", ":", "mask", "=", "r", ".", "con...
30.238095
23.928571
def monthly_build_list_regex(self): """Return the regex for the folder containing builds of a month.""" # Regex for possible builds for the given date return r'nightly/%(YEAR)s/%(MONTH)s/' % { 'YEAR': self.date.year, 'MONTH': str(self.date.month).zfill(2)}
[ "def", "monthly_build_list_regex", "(", "self", ")", ":", "# Regex for possible builds for the given date", "return", "r'nightly/%(YEAR)s/%(MONTH)s/'", "%", "{", "'YEAR'", ":", "self", ".", "date", ".", "year", ",", "'MONTH'", ":", "str", "(", "self", ".", "date", ...
49.833333
7.333333
async def do_run_task(context, run_cancellable, to_cancellable_process): """Run the task logic. Returns the integer status of the task. args: context (scriptworker.context.Context): the scriptworker context. run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker...
[ "async", "def", "do_run_task", "(", "context", ",", "run_cancellable", ",", "to_cancellable_process", ")", ":", "status", "=", "0", "try", ":", "if", "context", ".", "config", "[", "'verify_chain_of_trust'", "]", ":", "chain", "=", "ChainOfTrust", "(", "contex...
35.885714
24.142857
def doc_unwrap(raw_doc): """ Applies two transformations to raw_doc: 1. N consecutive newlines are converted into N-1 newlines. 2. A lone newline is converted to a space, which basically unwraps text. Returns a new string, or None if the input was None. """ if raw_doc is None: retur...
[ "def", "doc_unwrap", "(", "raw_doc", ")", ":", "if", "raw_doc", "is", "None", ":", "return", "None", "docstring", "=", "''", "consecutive_newlines", "=", "0", "# Remove all leading and trailing whitespace in the documentation block", "for", "c", "in", "raw_doc", ".", ...
31.791667
14.875
def colour_hsv(self): """Return colour as HSV value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_hsv(hexvalue)
[ "def", "colour_hsv", "(", "self", ")", ":", "hexvalue", "=", "self", ".", "status", "(", ")", "[", "self", ".", "DPS", "]", "[", "self", ".", "DPS_INDEX_COLOUR", "]", "return", "BulbDevice", ".", "_hexvalue_to_hsv", "(", "hexvalue", ")" ]
44.5
14
def ks_unif_durbin_matrix(samples, statistic): """ Calculates the probability that the statistic is less than the given value, using a fairly accurate implementation of the Durbin's matrix formula. Not an exact transliteration of the Marsaglia code, but using the same ideas. Assumes samples > 0. Se...
[ "def", "ks_unif_durbin_matrix", "(", "samples", ",", "statistic", ")", ":", "# Construct the Durbin matrix.", "h", ",", "k", "=", "modf", "(", "samples", "*", "statistic", ")", "k", "=", "int", "(", "k", ")", "h", "=", "1", "-", "h", "m", "=", "2", "...
28.191489
18.617021
def DEFINE_choice(self, name, default, choices, help, constant=False): """A helper for defining choice string options.""" self.AddOption( type_info.Choice( name=name, default=default, choices=choices, description=help), constant=constant)
[ "def", "DEFINE_choice", "(", "self", ",", "name", ",", "default", ",", "choices", ",", "help", ",", "constant", "=", "False", ")", ":", "self", ".", "AddOption", "(", "type_info", ".", "Choice", "(", "name", "=", "name", ",", "default", "=", "default",...
44.833333
19.166667
def configure(self, options, conf): """ Configure plugin. """ super(LeakDetectorPlugin, self).configure(options, conf) if options.leak_detector_level: self.reporting_level = int(options.leak_detector_level) self.report_delta = options.leak_detector_report_delt...
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "super", "(", "LeakDetectorPlugin", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "if", "options", ".", "leak_detector_level", ":", "self", ".", "reporting_leve...
49.833333
18.166667
def row(cls, pitch, pa, pitch_list, ball_tally, strike_tally): """ Pitching Result Pitch f/x fields: https://fastballs.wordpress.com/category/pitchfx-glossary/ :param pitch: pitch object(type:Beautifulsoup) :param pa: At bat data for pa(dict) :param pitch_list: Pitching ...
[ "def", "row", "(", "cls", ",", "pitch", ",", "pa", ",", "pitch_list", ",", "ball_tally", ",", "strike_tally", ")", ":", "pitch_res", "=", "MlbamUtil", ".", "get_attribute_stats", "(", "pitch", ",", "'type'", ",", "str", ",", "MlbamConst", ".", "UNKNOWN_FUL...
63.176471
25.8
def search_domain(self, searchterm): """Search for domains :type searchterm: str :rtype: list """ return self.__search(type_attribute=self.__mispdomaintypes(), value=searchterm)
[ "def", "search_domain", "(", "self", ",", "searchterm", ")", ":", "return", "self", ".", "__search", "(", "type_attribute", "=", "self", ".", "__mispdomaintypes", "(", ")", ",", "value", "=", "searchterm", ")" ]
31.428571
16.285714
def example_reading_spec(self): """Data fields to store on disk and their decoders.""" # Subclasses can override and/or extend. processed_reward_type = tf.float32 if self.is_processed_rewards_discrete: processed_reward_type = tf.int64 data_fields = { TIMESTEP_FIELD: tf.FixedLenFeatu...
[ "def", "example_reading_spec", "(", "self", ")", ":", "# Subclasses can override and/or extend.", "processed_reward_type", "=", "tf", ".", "float32", "if", "self", ".", "is_processed_rewards_discrete", ":", "processed_reward_type", "=", "tf", ".", "int64", "data_fields", ...
34.62963
21
def literalize(self): """ Return an expression where NOTs are only occurring as literals. Applied recursively to subexpressions. """ if self.isliteral: return self args = tuple(arg.literalize() for arg in self.args) if all(arg is self.args[i] for i, ar...
[ "def", "literalize", "(", "self", ")", ":", "if", "self", ".", "isliteral", ":", "return", "self", "args", "=", "tuple", "(", "arg", ".", "literalize", "(", ")", "for", "arg", "in", "self", ".", "args", ")", "if", "all", "(", "arg", "is", "self", ...
32.75
16.083333
def denorm(self,arr): """Reverse the normalization done to a batch of images. Arguments: arr: of shape/size (N,3,sz,sz) """ if type(arr) is not np.ndarray: arr = to_np(arr) if len(arr.shape)==3: arr = arr[None] return self.transform.denorm(np.rollaxis(arr,1,4...
[ "def", "denorm", "(", "self", ",", "arr", ")", ":", "if", "type", "(", "arr", ")", "is", "not", "np", ".", "ndarray", ":", "arr", "=", "to_np", "(", "arr", ")", "if", "len", "(", "arr", ".", "shape", ")", "==", "3", ":", "arr", "=", "arr", ...
34.888889
13.555556
def to_dict(self): """ Create a JSON-serializable representation of the ISA. The dictionary representation is of the form:: { "1Q": { "0": { "type": "Xhalves" }, "1": { ...
[ "def", "to_dict", "(", "self", ")", ":", "def", "_maybe_configure", "(", "o", ",", "t", ")", ":", "# type: (Union[Qubit,Edge], str) -> dict", "\"\"\"\n Exclude default values from generated dictionary.\n\n :param Union[Qubit,Edge] o: The object to serialize\n ...
28.388889
18.462963
def check_url_accessibility(url, timeout=10): ''' Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError ''' if(url=='localhost'): url = 'http://127.0.0.1' try: req = urllib2.urlopen(url, timeout=timeout) if (req.getcode()==20...
[ "def", "check_url_accessibility", "(", "url", ",", "timeout", "=", "10", ")", ":", "if", "(", "url", "==", "'localhost'", ")", ":", "url", "=", "'http://127.0.0.1'", "try", ":", "req", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "t...
30.857143
19.428571
def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0, period=None, subtract_mid=False): """Compute the windowed sum of the given arrays. This is a slow function, used primarily for testing and validation of the faster version of ``windowed_sum()`` Parameters --...
[ "def", "windowed_sum_slow", "(", "arrays", ",", "span", ",", "t", "=", "None", ",", "indices", "=", "None", ",", "tpowers", "=", "0", ",", "period", "=", "None", ",", "subtract_mid", "=", "False", ")", ":", "span", "=", "np", ".", "asarray", "(", "...
36.123457
19.493827
def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max(...
[ "def", "truncate_selection", "(", "self", ",", "position_from", ")", ":", "position_from", "=", "self", ".", "get_position", "(", "position_from", ")", "cursor", "=", "self", ".", "textCursor", "(", ")", "start", ",", "end", "=", "cursor", ".", "selectionSta...
43.4
11.1
def measured_current(self): """ The measured current that the battery is supplying (in microamps) """ self._measured_current, value = self.get_attr_int(self._measured_current, 'current_now') return value
[ "def", "measured_current", "(", "self", ")", ":", "self", ".", "_measured_current", ",", "value", "=", "self", ".", "get_attr_int", "(", "self", ".", "_measured_current", ",", "'current_now'", ")", "return", "value" ]
39.666667
20.333333
def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) """ assert self.cal1Dfn.is_file( ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'.format(self.cal1Dfn) ...
[ "def", "doorient", "(", "self", ")", ":", "assert", "self", ".", "cal1Dfn", ".", "is_file", "(", ")", ",", "'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'", ".", "format", "(", "self", ".", "cal1Dfn", ")", "with", "h5py", ".", "F...
32.9
17.34
def rel_path(self, other): """Return a path to "other" relative to this directory. """ # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths ...
[ "def", "rel_path", "(", "self", ",", "other", ")", ":", "# This complicated and expensive method, which constructs relative", "# paths between arbitrary Node.FS objects, is no longer used", "# by SCons itself. It was introduced to store dependency paths", "# in .sconsign files relative to the...
33.358491
19.396226
def update_all(self, rs=None, since=None): "Sync all objects for the relations rs (if None, sync all resources)" self._log.info("Updating resources: %s", ' '.join(r.tag for r in rs)) if rs is None: rs = resource.all_resources() ctx = self._ContextClass(self) for r in...
[ "def", "update_all", "(", "self", ",", "rs", "=", "None", ",", "since", "=", "None", ")", ":", "self", ".", "_log", ".", "info", "(", "\"Updating resources: %s\"", ",", "' '", ".", "join", "(", "r", ".", "tag", "for", "r", "in", "rs", ")", ")", "...
43.444444
21.222222
def validate_leafref_path(ctx, stmt, path_spec, path, accept_non_leaf_target=False, accept_non_config_target=False): """Return the leaf that the path points to and the expanded path arg, or None on error.""" pathpos = path.pos # Unprefixed paths in t...
[ "def", "validate_leafref_path", "(", "ctx", ",", "stmt", ",", "path_spec", ",", "path", ",", "accept_non_leaf_target", "=", "False", ",", "accept_non_config_target", "=", "False", ")", ":", "pathpos", "=", "path", ".", "pos", "# Unprefixed paths in typedefs in YANG ...
43.312253
16.146245
def add_tagged_report_number(reading_line, len_reportnum, reportnum, startpos, true_replacement_index, extras): """In rebuilding the line, add an identified institutional ...
[ "def", "add_tagged_report_number", "(", "reading_line", ",", "len_reportnum", ",", "reportnum", ",", "startpos", ",", "true_replacement_index", ",", "extras", ")", ":", "rebuilt_line", "=", "u\"\"", "# The segment of the line that's being rebuilt to", "# include the tagged & ...
48.807692
23.326923
def compute_venn3_colors(set_colors): ''' Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111). >>> compute_venn3_colors(['r', 'g', 'b']) (array([ 1.,...
[ "def", "compute_venn3_colors", "(", "set_colors", ")", ":", "ccv", "=", "ColorConverter", "(", ")", "base_colors", "=", "[", "np", ".", "array", "(", "ccv", ".", "to_rgb", "(", "c", ")", ")", "for", "c", "in", "set_colors", "]", "return", "(", "base_co...
59.583333
40.083333
async def get_departures( self, station_id: str, direction_id: Optional[str] = None, max_journeys: int = 20, products: Optional[List[str]] = None, ) -> Dict[str, Any]: """Fetch data from rmv.de.""" self.station_id: str = station_id self.direction_id: s...
[ "async", "def", "get_departures", "(", "self", ",", "station_id", ":", "str", ",", "direction_id", ":", "Optional", "[", "str", "]", "=", "None", ",", "max_journeys", ":", "int", "=", "20", ",", "products", ":", "Optional", "[", "List", "[", "str", "]"...
35.014706
17.264706
def ListChildren(self, urn, limit=None, age=NEWEST_TIME): """Lists bunch of directories efficiently. Args: urn: Urn to list children. limit: Max number of children to list. age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Returns: R...
[ "def", "ListChildren", "(", "self", ",", "urn", ",", "limit", "=", "None", ",", "age", "=", "NEWEST_TIME", ")", ":", "_", ",", "children_urns", "=", "list", "(", "self", ".", "MultiListChildren", "(", "[", "urn", "]", ",", "limit", "=", "limit", ",",...
30.866667
17.466667
def export_partlist_to_file(input, output, timeout=20, showgui=False): ''' call eagle and export sch or brd to partlist text file :param input: .sch or .brd file name :param output: text file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: None ''' ...
[ "def", "export_partlist_to_file", "(", "input", ",", "output", ",", "timeout", "=", "20", ",", "showgui", "=", "False", ")", ":", "input", "=", "norm_path", "(", "input", ")", "output", "=", "norm_path", "(", "output", ")", "commands", "=", "export_command...
32.875
22.625
def detect(): """Does this compiler support OpenMP parallelization?""" compiler = new_compiler() hasopenmp = hasfunction(compiler, 'omp_get_num_threads()') needs_gomp = hasopenmp if not hasopenmp: compiler.add_library('gomp') hasopenmp = hasfunction(compiler, 'omp_get_num_threads()') needs_gomp = hasopenmp re...
[ "def", "detect", "(", ")", ":", "compiler", "=", "new_compiler", "(", ")", "hasopenmp", "=", "hasfunction", "(", "compiler", ",", "'omp_get_num_threads()'", ")", "needs_gomp", "=", "hasopenmp", "if", "not", "hasopenmp", ":", "compiler", ".", "add_library", "("...
32.5
16.8
def to_params(self): """ Convert the instance dictionary into a sorted list of pairs (name, valrepr) where valrepr is the string representation of the underlying value. """ dic = self.__dict__ return [(k, repr(dic[k])) for k in sorted(dic) if not k...
[ "def", "to_params", "(", "self", ")", ":", "dic", "=", "self", ".", "__dict__", "return", "[", "(", "k", ",", "repr", "(", "dic", "[", "k", "]", ")", ")", "for", "k", "in", "sorted", "(", "dic", ")", "if", "not", "k", ".", "startswith", "(", ...
36.555556
12.777778
def check_statement(self, stmt, max_paths=1, max_path_length=5): """Check a single Statement against the model. Parameters ---------- stmt : indra.statements.Statement The Statement to check. max_paths : Optional[int] The maximum number of specific paths ...
[ "def", "check_statement", "(", "self", ",", "stmt", ",", "max_paths", "=", "1", ",", "max_path_length", "=", "5", ")", ":", "# Make sure the influence map is initialized", "self", ".", "get_im", "(", ")", "# Check if this is one of the statement types that we can check", ...
50.916667
21.625
def get_trace(self, trace_id, project_id=None): """ Gets a single trace by its ID. Args: trace_id (str): ID of the trace to return. project_id (str): Required. ID of the Cloud project where the trace data is stored. Returns: A Trace ...
[ "def", "get_trace", "(", "self", ",", "trace_id", ",", "project_id", "=", "None", ")", ":", "if", "project_id", "is", "None", ":", "project_id", "=", "self", ".", "project", "return", "self", ".", "trace_api", ".", "get_trace", "(", "project_id", "=", "p...
27.823529
20.647059
def register(self, url, doc): """Register a DOI via the DataCite API. :param url: Specify the URL for the API. :param doc: Set metadata for DOI. :returns: `True` if is registered successfully. """ try: self.pid.register() # Set metadata for DOI ...
[ "def", "register", "(", "self", ",", "url", ",", "doc", ")", ":", "try", ":", "self", ".", "pid", ".", "register", "(", ")", "# Set metadata for DOI", "self", ".", "api", ".", "metadata_post", "(", "doc", ")", "# Mint DOI", "self", ".", "api", ".", "...
36
12.8
async def close(self): """ Terminate the ICE agent, ending ICE processing and streams. """ if self.__isClosed: return self.__isClosed = True self.__setSignalingState('closed') # stop senders / receivers for transceiver in self.__transceivers: ...
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "__isClosed", ":", "return", "self", ".", "__isClosed", "=", "True", "self", ".", "__setSignalingState", "(", "'closed'", ")", "# stop senders / receivers", "for", "transceiver", "in", "self", ...
33.148148
13.888889
def WaitUntilComplete(self,poll_freq=2,timeout=None): """Poll until status is completed. If status is 'notStarted' or 'executing' continue polling. If status is 'succeeded' return Else raise exception poll_freq option is in seconds """ start_time = time.time() while not self.time_completed: status...
[ "def", "WaitUntilComplete", "(", "self", ",", "poll_freq", "=", "2", ",", "timeout", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "not", "self", ".", "time_completed", ":", "status", "=", "self", ".", "Status", "(",...
35.884615
21.538462
def update_metadata(session, path=DATA_PATH): """Update metadata files (only ladders right now).""" with open(os.path.join(path, 'games.json')) as handle: games = json.loads(handle.read()) for key, data in get_metadata(session, games).items(): with open(os.path.join(path, '{}.json'.for...
[ "def", "update_metadata", "(", "session", ",", "path", "=", "DATA_PATH", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'games.json'", ")", ")", "as", "handle", ":", "games", "=", "json", ".", "loads", "(", "handle"...
48.875
15.5
def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name """Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations ...
[ "def", "get_hyperparameter_configurations", "(", "self", ",", "num", ",", "r", ",", "searchspace_json", ",", "random_state", ")", ":", "# pylint: disable=invalid-name", "global", "_KEY", "# pylint: disable=global-statement", "assert", "self", ".", "i", "==", "0", "hyp...
42.130435
24
def highlight_text(self, text, start, end): """ Highlights given text. :param text: Text. :type text: QString :param start: Text start index. :type start: int :param end: Text end index. :type end: int :return: Method success. :rtype: bool...
[ "def", "highlight_text", "(", "self", ",", "text", ",", "start", ",", "end", ")", ":", "for", "rule", "in", "self", ".", "__rules", ":", "index", "=", "rule", ".", "pattern", ".", "indexIn", "(", "text", ",", "start", ")", "while", "index", ">=", "...
34.590909
16.590909
def adapter(data, headers, **kwargs): """Wrap the formatting inside a function for TabularOutputFormatter.""" for row in chain((headers,), data): yield "\t".join((replace(r, (('\n', r'\n'), ('\t', r'\t'))) for r in row))
[ "def", "adapter", "(", "data", ",", "headers", ",", "*", "*", "kwargs", ")", ":", "for", "row", "in", "chain", "(", "(", "headers", ",", ")", ",", "data", ")", ":", "yield", "\"\\t\"", ".", "join", "(", "(", "replace", "(", "r", ",", "(", "(", ...
58.25
11.5
def remove_child_vault(self, vault_id, child_id): """Removes a child from a vault. arg: vault_id (osid.id.Id): the ``Id`` of a vault arg: child_id (osid.id.Id): the ``Id`` of the child raise: NotFound - ``vault_id`` not parent of ``child_id`` raise: NullArgument - ``vaul...
[ "def", "remove_child_vault", "(", "self", ",", "vault_id", ",", "child_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchyDesignSession.remove_child_bin_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self",...
52.117647
23.352941
async def _loadNodeValu(self, full, valu): ''' Load a node from storage into the tree. ( used by initialization routines to build the tree) ''' node = self.root for path in iterpath(full): name = path[-1] step = node.kids.get(name) if...
[ "async", "def", "_loadNodeValu", "(", "self", ",", "full", ",", "valu", ")", ":", "node", "=", "self", ".", "root", "for", "path", "in", "iterpath", "(", "full", ")", ":", "name", "=", "path", "[", "-", "1", "]", "step", "=", "node", ".", "kids",...
25.222222
20.777778
def copy_default_data_file(filename, module=None): """Copies file from default data directory to local directory.""" if module is None: module = __get_filetypes_module() fullpath = get_default_data_path(filename, module=module) shutil.copy(fullpath, ".")
[ "def", "copy_default_data_file", "(", "filename", ",", "module", "=", "None", ")", ":", "if", "module", "is", "None", ":", "module", "=", "__get_filetypes_module", "(", ")", "fullpath", "=", "get_default_data_path", "(", "filename", ",", "module", "=", "module...
45.5
10
def _getSensorInputRecord(self, inputRecord): """ inputRecord - dict containing the input to the sensor Return a 'SensorInput' object, which represents the 'parsed' representation of the input record """ sensor = self._getSensorRegion() dataRow = copy.deepcopy(sensor.getSelf().getOutputValu...
[ "def", "_getSensorInputRecord", "(", "self", ",", "inputRecord", ")", ":", "sensor", "=", "self", ".", "_getSensorRegion", "(", ")", "dataRow", "=", "copy", ".", "deepcopy", "(", "sensor", ".", "getSelf", "(", ")", ".", "getOutputValues", "(", "'sourceOut'",...
42.210526
14.842105
def list(self, opts): """List all confs or if a conf is given, all the stanzas in it.""" argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # but all are optional cpres = True if count > 0 else False spres = True if cou...
[ "def", "list", "(", "self", ",", "opts", ")", ":", "argv", "=", "opts", ".", "args", "count", "=", "len", "(", "argv", ")", "# unflagged arguments are conf, stanza, key. In this order", "# but all are optional", "cpres", "=", "True", "if", "count", ">", "0", "...
37.724138
16.827586
def send_fetch_request(self, payloads=None, fail_on_error=True, callback=None, max_wait_time=DEFAULT_FETCH_SERVER_WAIT_MSECS, min_bytes=DEFAULT_FETCH_MIN_BYTES): """ Encode and send a FetchRequest Payloads are grou...
[ "def", "send_fetch_request", "(", "self", ",", "payloads", "=", "None", ",", "fail_on_error", "=", "True", ",", "callback", "=", "None", ",", "max_wait_time", "=", "DEFAULT_FETCH_SERVER_WAIT_MSECS", ",", "min_bytes", "=", "DEFAULT_FETCH_MIN_BYTES", ")", ":", "if",...
39.933333
22.133333
def add_flair_template(self, subreddit, text='', css_class='', text_editable=False, is_link=False): """Add a flair template to the given subreddit. :returns: The json response from the server. """ data = {'r': six.text_type(subreddit), 'text':...
[ "def", "add_flair_template", "(", "self", ",", "subreddit", ",", "text", "=", "''", ",", "css_class", "=", "''", ",", "text_editable", "=", "False", ",", "is_link", "=", "False", ")", ":", "data", "=", "{", "'r'", ":", "six", ".", "text_type", "(", "...
43.384615
18.615385
def reload(self, reload_timeout, save_config): """Reload the device.""" PROCEED = re.compile(re.escape("Proceed with reload? [confirm]")) CONTINUE = re.compile(re.escape("Do you wish to continue?[confirm(y/n)]")) DONE = re.compile(re.escape("[Done]")) CONFIGURATION_COMPLETED = re...
[ "def", "reload", "(", "self", ",", "reload_timeout", ",", "save_config", ")", ":", "PROCEED", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "\"Proceed with reload? [confirm]\"", ")", ")", "CONTINUE", "=", "re", ".", "compile", "(", "re", ".", ...
64.564516
33.693548
def create_memory_layer( layer_name, geometry, coordinate_reference_system=None, fields=None): """Create a vector memory layer. :param layer_name: The name of the layer. :type layer_name: str :param geometry: The geometry of the layer. :rtype geometry: QgsWkbTypes (note: ...
[ "def", "create_memory_layer", "(", "layer_name", ",", "geometry", ",", "coordinate_reference_system", "=", "None", ",", "fields", "=", "None", ")", ":", "if", "geometry", "==", "QgsWkbTypes", ".", "PointGeometry", ":", "wkb_type", "=", "QgsWkbTypes", ".", "Multi...
34
15.945455