text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def on_success(self, inv_plugin, emit_set_slot): """ Called when the click was successful and should be applied to the inventory. Args: inv_plugin (InventoryPlugin): inventory plugin instance emit_set_slot (func): function to signal a slot change, ...
[ "def", "on_success", "(", "self", ",", "inv_plugin", ",", "emit_set_slot", ")", ":", "self", ".", "dirty", "=", "set", "(", ")", "self", ".", "apply", "(", "inv_plugin", ")", "for", "changed_slot", "in", "self", ".", "dirty", ":", "emit_set_slot", "(", ...
35.642857
13.071429
def delete_consumer_group(self, project, logstore, consumer_group): """ Delete consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: ...
[ "def", "delete_consumer_group", "(", "self", ",", "project", ",", "logstore", ",", "consumer_group", ")", ":", "headers", "=", "{", "\"x-log-bodyrawsize\"", ":", "'0'", "}", "params", "=", "{", "}", "resource", "=", "\"/logstores/\"", "+", "logstore", "+", "...
31.333333
21.333333
def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None: """ Adds errors to the error store for the schema """ for error in errors: self._error_cache.add(error)
[ "def", "add_errors", "(", "self", ",", "*", "errors", ":", "Union", "[", "BaseSchemaError", ",", "SchemaErrorCollection", "]", ")", "->", "None", ":", "for", "error", "in", "errors", ":", "self", ".", "_error_cache", ".", "add", "(", "error", ")" ]
53.5
14.25
def _do_run(self, mode='1'): """workhorse for the self.do_run_xx methods.""" for a in range(len(self.particle_groups)): group = self.particle_groups[a] lp = LMParticles(self.state, group, **self._kwargs) if mode == 'internal': lp.J, lp.JTJ, lp._dif_til...
[ "def", "_do_run", "(", "self", ",", "mode", "=", "'1'", ")", ":", "for", "a", "in", "range", "(", "len", "(", "self", ".", "particle_groups", ")", ")", ":", "group", "=", "self", ".", "particle_groups", "[", "a", "]", "lp", "=", "LMParticles", "(",...
39.684211
15.315789
def pcap_name(self, devname): """Return pcap device name for given Windows device name.""" try: pcap_name = self.data[devname].pcap_name except KeyError: raise ValueError("Unknown network interface %r" % devname) else: return pcap_name
[ "def", "pcap_name", "(", "self", ",", "devname", ")", ":", "try", ":", "pcap_name", "=", "self", ".", "data", "[", "devname", "]", ".", "pcap_name", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Unknown network interface %r\"", "%", "devname", ")...
32.888889
19.555556
def close(self): """Commit changes and close the database.""" import sys, os for store in self.stores: if hasattr(store, 'save'): store.save(reimport=False) path, filename = os.path.split(store._filename) modname = filename[:-3] if ...
[ "def", "close", "(", "self", ")", ":", "import", "sys", ",", "os", "for", "store", "in", "self", ".", "stores", ":", "if", "hasattr", "(", "store", ",", "'save'", ")", ":", "store", ".", "save", "(", "reimport", "=", "False", ")", "path", ",", "f...
36.181818
8.727273
def _readFromUrl(cls, url, writable): """ Writes the contents of a file to a source (writes url to writable) using a ~10Mb buffer. :param str url: A path as a string of the file to be read from. :param object writable: An open file object to write to. """ # we us...
[ "def", "_readFromUrl", "(", "cls", ",", "url", ",", "writable", ")", ":", "# we use a ~10Mb buffer to improve speed", "with", "open", "(", "cls", ".", "_extractPathFromUrl", "(", "url", ")", ",", "'rb'", ")", "as", "readable", ":", "shutil", ".", "copyfileobj"...
44.090909
19.181818
def from_global_driver(self): """Connect to the global driver.""" address, _ = _read_driver() if address is None: raise DriverNotRunningError("No driver currently running") security = Security.from_default() return Client(address=address, security=security)
[ "def", "from_global_driver", "(", "self", ")", ":", "address", ",", "_", "=", "_read_driver", "(", ")", "if", "address", "is", "None", ":", "raise", "DriverNotRunningError", "(", "\"No driver currently running\"", ")", "security", "=", "Security", ".", "from_def...
33.666667
17.555556
def append_dict_values(list_of_dicts, keys=None): """ Return a dict of lists from a list of dicts with the same keys. For each dict in list_of_dicts with look for the values of the given keys and append it to the output dict. Parameters ---------- list_of_dicts: list of dicts keys: lis...
[ "def", "append_dict_values", "(", "list_of_dicts", ",", "keys", "=", "None", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "list", "(", "list_of_dicts", "[", "0", "]", ".", "keys", "(", ")", ")", "dict_of_lists", "=", "DefaultOrderedDict", "(",...
28.8
18.08
def _makedirs(self, path): """Make folders recursively for the given path and check read and write permission on the path Args: path -- path to the leaf folder """ try: oldmask = os.umask(0) os.makedirs(path, self._conf['dmode']) ...
[ "def", "_makedirs", "(", "self", ",", "path", ")", ":", "try", ":", "oldmask", "=", "os", ".", "umask", "(", "0", ")", "os", ".", "makedirs", "(", "path", ",", "self", ".", "_conf", "[", "'dmode'", "]", ")", "os", ".", "umask", "(", "oldmask", ...
45.666667
19.52381
def make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The client that holds configuration details. :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient` :returns: A datastore API insta...
[ "def", "make_datastore_api", "(", "client", ")", ":", "parse_result", "=", "six", ".", "moves", ".", "urllib_parse", ".", "urlparse", "(", "client", ".", "_base_url", ")", "host", "=", "parse_result", ".", "netloc", "if", "parse_result", ".", "scheme", "==",...
37.272727
21.181818
def get_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3): """ A filter that eliminates possibly repetitive responses to prevent a chat bot from repeating statements that it has recently said. """ from collections import Counter # Get the most recent statement...
[ "def", "get_recent_repeated_responses", "(", "chatbot", ",", "conversation", ",", "sample", "=", "10", ",", "threshold", "=", "3", ",", "quantity", "=", "3", ")", ":", "from", "collections", "import", "Counter", "# Get the most recent statements from the conversation"...
31.576923
21.807692
def process_reply(self, reply, status=None, description=None): """ Re-entry for processing a successful reply. Depending on how the ``retxml`` option is set, may return the SOAP reply XML or process it and return the Python object representing the returned value. @param...
[ "def", "process_reply", "(", "self", ",", "reply", ",", "status", "=", "None", ",", "description", "=", "None", ")", ":", "return", "self", ".", "__process_reply", "(", "reply", ",", "status", ",", "description", ")" ]
39
19.736842
def get_weather(self, time, max_hour=6): """Get the current weather data from met.no.""" if self.data is None: return {} ordered_entries = [] for time_entry in self.data['product']['time']: valid_from = parse_datetime(time_entry['@from']) valid_to = p...
[ "def", "get_weather", "(", "self", ",", "time", ",", "max_hour", "=", "6", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "{", "}", "ordered_entries", "=", "[", "]", "for", "time_entry", "in", "self", ".", "data", "[", "'product'",...
39.666667
21.212121
def paint( self, painter, option, index ): """ Overloads the paint method from Qt to perform some additional painting on items. :param painter | <QPainter> option | <QStyleOption> index | <QModelIndex> """ ...
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "index", ")", ":", "# draw the background", "edit", "=", "self", ".", "parent", "(", ")", "item", "=", "edit", ".", "item", "(", "index", ".", "row", "(", ")", ")", "if", "(", "not", ...
36.621622
12.405405
def override_spec(cls, **kwargs): """OVerride 'spec' and '_default_spec' with given values""" cls._default_spec.set(**kwargs) cls.spec.set(**kwargs)
[ "def", "override_spec", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "cls", ".", "_default_spec", ".", "set", "(", "*", "*", "kwargs", ")", "cls", ".", "spec", ".", "set", "(", "*", "*", "kwargs", ")" ]
42.25
4.5
def isRevoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and...
[ "def", "isRevoked", "(", "self", ",", "crl_list", ")", ":", "for", "c", "in", "crl_list", ":", "if", "(", "self", ".", "authorityKeyID", "is", "not", "None", "and", "c", ".", "authorityKeyID", "is", "not", "None", "and", "self", ".", "authorityKeyID", ...
47.291667
22.041667
def flush(self, log=False): # pylint:disable=too-many-branches, too-many-nested-blocks """Send inner stored metrics to the configured Graphite or InfluxDB Returns False if the sending failed with a warning log if log parameter is set :param log: to log information or not :type log: bo...
[ "def", "flush", "(", "self", ",", "log", "=", "False", ")", ":", "# pylint:disable=too-many-branches, too-many-nested-blocks", "if", "not", "self", ".", "my_metrics", ":", "logger", ".", "debug", "(", "\"Flushing - no metrics to send\"", ")", "return", "True", "now"...
47
23.932331
def delete_pipeline(self, pipeline_key): '''Deletes the pipeline specified by the key Args: returns (status code for the DELETE request, success message dict) expect (200 , {'success': 'true'}) for successful execution} ''' if pipeline_key: uri = '/'.join([ self.api_uri, self.pipeline...
[ "def", "delete_pipeline", "(", "self", ",", "pipeline_key", ")", ":", "if", "pipeline_key", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "api_uri", ",", "self", ".", "pipelines_suffix", ",", "pipeline_key", "]", ")", "return", "self", ".",...
28.733333
19.8
def disable_avatar(self): """ Temporarily disable the avatar. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled (even if disabling the PEP avatar fails). This is done by setting the avatar metadata node empty and if :attr:`synchronize_vcard` is true, do...
[ "def", "disable_avatar", "(", "self", ")", ":", "with", "(", "yield", "from", "self", ".", "_publish_lock", ")", ":", "todo", "=", "[", "]", "if", "self", ".", "_synchronize_vcard", ":", "todo", ".", "append", "(", "self", ".", "_disable_vcard_avatar", "...
34.862069
20.655172
def _sort_converters(cls, app_ready=False): '''Sorts the converter functions''' # app_ready is True when called from DMP's AppConfig.ready() # we can't sort before then because models aren't ready cls._sorting_enabled = cls._sorting_enabled or app_ready if cls._sorting_enabled: ...
[ "def", "_sort_converters", "(", "cls", ",", "app_ready", "=", "False", ")", ":", "# app_ready is True when called from DMP's AppConfig.ready()", "# we can't sort before then because models aren't ready", "cls", ".", "_sorting_enabled", "=", "cls", ".", "_sorting_enabled", "or",...
51.111111
12.888889
def unitResponse(self,band): """This is used internally for :ref:`pysynphot-formula-effstim` calculations.""" #sumfilt(wave,1,band) # SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ] wave=band.wave total = band.trapezoidIntegration(wave,band.throughput*wave) ...
[ "def", "unitResponse", "(", "self", ",", "band", ")", ":", "#sumfilt(wave,1,band)", "# SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ]", "wave", "=", "band", ".", "wave", "total", "=", "band", ".", "trapezoidIntegration", "(", "wave", ",", "band", ".", "throu...
42.222222
12.333333
def addKwdArgsToSig(sigStr, kwArgsDict): """ Alter the passed function signature string to add the given kewords """ retval = sigStr if len(kwArgsDict) > 0: retval = retval.strip(' ,)') # open up the r.h.s. for more args for k in kwArgsDict: if retval[-1] != '(': retval += ", " ...
[ "def", "addKwdArgsToSig", "(", "sigStr", ",", "kwArgsDict", ")", ":", "retval", "=", "sigStr", "if", "len", "(", "kwArgsDict", ")", ">", "0", ":", "retval", "=", "retval", ".", "strip", "(", "' ,)'", ")", "# open up the r.h.s. for more args", "for", "k", "...
38.181818
14.454545
async def _connect(self, host_loc): ''' Simple enough stuff to figure out where we should connect, and creates the appropriate connection. ''' scheme, host, path, parameters, query, fragment = urlparse( host_loc) if parameters or query or fragment: ...
[ "async", "def", "_connect", "(", "self", ",", "host_loc", ")", ":", "scheme", ",", "host", ",", "path", ",", "parameters", ",", "query", ",", "fragment", "=", "urlparse", "(", "host_loc", ")", "if", "parameters", "or", "query", "or", "fragment", ":", "...
37.578947
19.263158
def check_version(expected_version): """ Make sure the package version in setuptools matches what we expect it to be """ with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file: version = version_file.read().strip() if version != expected_version: raise EnvironmentError("Versi...
[ "def", "check_version", "(", "expected_version", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "root_folder", ",", "'VERSION'", ")", ",", "'r'", ")", "as", "version_file", ":", "version", "=", "version_file", ".", "read", "(", ")", ...
47.666667
22.222222
def get_groups_by_token(cls, username, token, request): """ Get user's groups if user with :username: exists and their api key token equals :token: Used by Token-based authentication as `check` kwarg. """ try: user = cls.get_item(username=username) except Exc...
[ "def", "get_groups_by_token", "(", "cls", ",", "username", ",", "token", ",", "request", ")", ":", "try", ":", "user", "=", "cls", ".", "get_item", "(", "username", "=", "username", ")", "except", "Exception", "as", "ex", ":", "log", ".", "error", "(",...
34.733333
15.6
def cluster_del_slots(self, slot, *slots): """Set hash slots as unbound in receiving node.""" slots = (slot,) + slots if not all(isinstance(s, int) for s in slots): raise TypeError("All parameters must be of type int") fut = self.execute(b'CLUSTER', b'DELSLOTS', *slots) ...
[ "def", "cluster_del_slots", "(", "self", ",", "slot", ",", "*", "slots", ")", ":", "slots", "=", "(", "slot", ",", ")", "+", "slots", "if", "not", "all", "(", "isinstance", "(", "s", ",", "int", ")", "for", "s", "in", "slots", ")", ":", "raise", ...
48
11.714286
def add_tag(self, name, value): """ :param name: Name of the tag :type name: string :param value: Value of the tag :type value: string """ self.tags.append(Tag(name, value))
[ "def", "add_tag", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "tags", ".", "append", "(", "Tag", "(", "name", ",", "value", ")", ")" ]
26.444444
8
def _choi_to_superop(data, input_dim, output_dim): """Transform Choi to SuperOp representation.""" shape = (input_dim, output_dim, input_dim, output_dim) return _reshuffle(data, shape)
[ "def", "_choi_to_superop", "(", "data", ",", "input_dim", ",", "output_dim", ")", ":", "shape", "=", "(", "input_dim", ",", "output_dim", ",", "input_dim", ",", "output_dim", ")", "return", "_reshuffle", "(", "data", ",", "shape", ")" ]
48.25
8.5
def resolve(self, component_type, **kwargs): """ Resolves an instance of the component type. :param component_type: The type of the component (e.g. a class). :param kwargs: Overriding arguments to use (by name) instead of resolving them. :return: An instance of the component. ...
[ "def", "resolve", "(", "self", ",", "component_type", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_resolve_lock", ":", "context", "=", "_ComponentContext", "(", "self", ")", "return", "context", ".", "resolve", "(", "component_type", ",", "*",...
45.9
13.3
def pint_multiply(da, q, out_units=None): """Multiply xarray.DataArray by pint.Quantity. Parameters ---------- da : xr.DataArray Input array. q : pint.Quantity Multiplicating factor. out_units : str Units the output array should be converted into. """ a = 1 * units2pin...
[ "def", "pint_multiply", "(", "da", ",", "q", ",", "out_units", "=", "None", ")", ":", "a", "=", "1", "*", "units2pint", "(", "da", ")", "f", "=", "a", "*", "q", ".", "to_base_units", "(", ")", "if", "out_units", ":", "f", "=", "f", ".", "to", ...
24.842105
16.157895
def get_choice_status(self): """ Returns a message field, which indicates whether choices statically or dynamically defined, and flag indicating whether a dynamic file selection loading error occurred. Throws an error if this is not a choice parameter. """ if 'ch...
[ "def", "get_choice_status", "(", "self", ")", ":", "if", "'choiceInfo'", "not", "in", "self", ".", "dto", "[", "self", ".", "name", "]", ":", "raise", "GPException", "(", "'not a choice parameter'", ")", "status", "=", "self", ".", "dto", "[", "self", "....
39.384615
18
def _align(self, axes, key_shape=None): """ Align local bolt array so that axes for iteration are in the keys. This operation is applied before most functional operators. It ensures that the specified axes are valid, and might transpose/reshape the underlying array so that the f...
[ "def", "_align", "(", "self", ",", "axes", ",", "key_shape", "=", "None", ")", ":", "# ensure that the key axes are valid for an ndarray of this shape", "inshape", "(", "self", ".", "shape", ",", "axes", ")", "# compute the set of dimensions/axes that will be used to reshap...
38.114286
27.2
def label(self, input_grid): """ Labels input grid using enhanced watershed algorithm. Args: input_grid (numpy.ndarray): Grid to be labeled. Returns: Array of labeled pixels """ marked = self.find_local_maxima(input_grid) marked = np.wher...
[ "def", "label", "(", "self", ",", "input_grid", ")", ":", "marked", "=", "self", ".", "find_local_maxima", "(", "input_grid", ")", "marked", "=", "np", ".", "where", "(", "marked", ">=", "0", ",", "1", ",", "0", ")", "# splabel returns two things in a tupl...
31.875
16.75
def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_key"]() ) exce...
[ "def", "decrypt", "(", "data", ",", "digest", "=", "True", ")", ":", "alg", ",", "_", ",", "data", "=", "data", ".", "rpartition", "(", "\"$\"", ")", "if", "not", "alg", ":", "return", "data", "data", "=", "_from_hex_digest", "(", "data", ")", "if"...
32.75
16.583333
def wwpn_alloc(self): """ Allocates a WWPN unique to this partition, in the range of 0xAFFEAFFE00008000 to 0xAFFEAFFE0000FFFF. Returns: string: The WWPN as 16 hexadecimal digits in upper case. Raises: ValueError: No more WWPNs available in that range. ...
[ "def", "wwpn_alloc", "(", "self", ")", ":", "wwpn_int", "=", "self", ".", "_wwpn_pool", ".", "alloc", "(", ")", "wwpn", "=", "\"AFFEAFFE0000\"", "+", "\"{:04X}\"", ".", "format", "(", "wwpn_int", ")", "return", "wwpn" ]
30.928571
19.214286
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' results = {} try: for entry in os.scandir(diskdir): target = normpath(join(diskdir, os.readlink(entry.path))) decoded_name = entry.name.encode('utf8').decode('unicode_escape') ...
[ "def", "get_label_map", "(", "opts", ")", ":", "results", "=", "{", "}", "try", ":", "for", "entry", "in", "os", ".", "scandir", "(", "diskdir", ")", ":", "target", "=", "normpath", "(", "join", "(", "diskdir", ",", "os", ".", "readlink", "(", "ent...
36.538462
19.769231
def update(self, hosted_number_order_sids=values.unset, address_sid=values.unset, email=values.unset, cc_emails=values.unset, status=values.unset, contact_title=values.unset, contact_phone_number=values.unset): """ Update the AuthorizationDocumentInstance ...
[ "def", "update", "(", "self", ",", "hosted_number_order_sids", "=", "values", ".", "unset", ",", "address_sid", "=", "values", ".", "unset", ",", "email", "=", "values", ".", "unset", ",", "cc_emails", "=", "values", ".", "unset", ",", "status", "=", "va...
47.851852
22.074074
def bp_rate_limit_heavy_bp_rate_limit_slot_bp_rate_limit_slot_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") bp_rate_limit = ET.SubElement(config, "bp-rate-limit", xmlns="urn:brocade.com:mgmt:brocade-bprate-limit") heavy = ET.SubElement(bp_rate_limi...
[ "def", "bp_rate_limit_heavy_bp_rate_limit_slot_bp_rate_limit_slot_num", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "bp_rate_limit", "=", "ET", ".", "SubElement", "(", "config", ",", "\"bp-rate-limit...
54.25
26.166667
def gdaArray(arry, dtype, numGhosts=1): """ ghosted distributed array constructor @param arry numpy-like array @param numGhosts the number of ghosts (>= 0) """ a = numpy.array(arry, dtype) res = GhostedDistArray(a.shape, a.dtype) res.setNumberOfGhosts(numGhosts) res[:] = a return...
[ "def", "gdaArray", "(", "arry", ",", "dtype", ",", "numGhosts", "=", "1", ")", ":", "a", "=", "numpy", ".", "array", "(", "arry", ",", "dtype", ")", "res", "=", "GhostedDistArray", "(", "a", ".", "shape", ",", "a", ".", "dtype", ")", "res", ".", ...
28.545455
7.818182
def _generatePayload(self, query): """Adds the following defaults to the payload: __rev, __user, __a, ttstamp, fb_dtsg, __req """ payload = self._payload_default.copy() if query: payload.update(query) payload["__req"] = str_base(self._req_counter, 36) ...
[ "def", "_generatePayload", "(", "self", ",", "query", ")", ":", "payload", "=", "self", ".", "_payload_default", ".", "copy", "(", ")", "if", "query", ":", "payload", ".", "update", "(", "query", ")", "payload", "[", "\"__req\"", "]", "=", "str_base", ...
35.636364
9.727273
def _clone(self): """Make a (shallow) copy of the set. There is a 'clone protocol' that subclasses of this class should use. To make a copy, first call your super's _clone() method, and use the object returned as the new instance. Then make shallow copies of the attributes def...
[ "def", "_clone", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "obj", "=", "cls", ".", "__new__", "(", "cls", ")", "obj", ".", "items", "=", "list", "(", "self", ".", "items", ")", "return", "obj" ]
35.941176
22.352941
def list_vars(script_path, ignore=IGNORE_DEFAULT): """ Given a shell script, returns a list of shell variable names. Note: this method executes the script, so beware if it contains side-effects. :param script_path: Path the a shell script :type script_path: str or unicode :param ignore: variable...
[ "def", "list_vars", "(", "script_path", ",", "ignore", "=", "IGNORE_DEFAULT", ")", ":", "if", "path", ".", "isfile", "(", "script_path", ")", ":", "input", "=", "(", "\"\"\". \"%s\"; env | awk -F = '/[a-zA-Z_][a-zA-Z_0-9]*=/ \"\"\"", "%", "script_path", "+", "\"\"\"...
43.678571
16.214286
def colgen(*lstcol,**kargs): """Returns a generator that mixes provided quantities forever trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default""" if len(lstcol) < 2: lstcol *= 2 trans = kargs.get("trans", lambda x,y,z: (x,y,z)) while 1: for ...
[ "def", "colgen", "(", "*", "lstcol", ",", "*", "*", "kargs", ")", ":", "if", "len", "(", "lstcol", ")", "<", "2", ":", "lstcol", "*=", "2", "trans", "=", "kargs", ".", "get", "(", "\"trans\"", ",", "lambda", "x", ",", "y", ",", "z", ":", "(",...
48.75
15.25
def _parse(jsonOutput): ''' Parses JSON response from Tika REST API server :param jsonOutput: JSON output from Tika Server :return: a dictionary having 'metadata' and 'content' values ''' parsed={} if not jsonOutput: return parsed parsed["status"] = jsonOutput[0] if json...
[ "def", "_parse", "(", "jsonOutput", ")", ":", "parsed", "=", "{", "}", "if", "not", "jsonOutput", ":", "return", "parsed", "parsed", "[", "\"status\"", "]", "=", "jsonOutput", "[", "0", "]", "if", "jsonOutput", "[", "1", "]", "==", "None", "or", "jso...
27.864865
19.972973
def drp(points, epsilon): """ Douglas ramer peucker Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm Args: points (:obj:`list` of :obj:`Point`) epsilon (float): drp threshold Returns: :obj:`list` of :obj:`Point` """ dmax = 0.0 i...
[ "def", "drp", "(", "points", ",", "epsilon", ")", ":", "dmax", "=", "0.0", "index", "=", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "points", ")", "-", "1", ")", ":", "dist", "=", "point_line_distance", "(", "points", "[", "i", ...
26.583333
21.833333
def discover(timeout=DISCOVERY_TIMEOUT): """ Discover devices on the local network. :param timeout: Optional timeout in seconds. :returns: Set of discovered host addresses. """ hosts = {} payload = MAGIC + DISCOVERY for _ in range(RETRIES): _SOCKET.sendto(bytearray(payload), ('255.2...
[ "def", "discover", "(", "timeout", "=", "DISCOVERY_TIMEOUT", ")", ":", "hosts", "=", "{", "}", "payload", "=", "MAGIC", "+", "DISCOVERY", "for", "_", "in", "range", "(", "RETRIES", ")", ":", "_SOCKET", ".", "sendto", "(", "bytearray", "(", "payload", "...
39.115385
11.923077
def get_users(self): """Return the configuration of the users.""" users = {} _JUNOS_CLASS_CISCO_PRIVILEGE_LEVEL_MAP = { "super-user": 15, "superuser": 15, "operator": 5, "read-only": 1, "unauthorized": 0, } _DEFAULT_US...
[ "def", "get_users", "(", "self", ")", ":", "users", "=", "{", "}", "_JUNOS_CLASS_CISCO_PRIVILEGE_LEVEL_MAP", "=", "{", "\"super-user\"", ":", "15", ",", "\"superuser\"", ":", "15", ",", "\"operator\"", ":", "5", ",", "\"read-only\"", ":", "1", ",", "\"unauth...
35.552632
17.184211
def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32): """ Smooth an image ANTsR function: `smoothImage` Arguments --------- image Image to smooth sigma Smoothing factor. Can be scalar, in which case the same sigma is...
[ "def", "smooth_image", "(", "image", ",", "sigma", ",", "sigma_in_physical_coordinates", "=", "True", ",", "FWHM", "=", "False", ",", "max_kernel_width", "=", "32", ")", ":", "if", "image", ".", "components", "==", "1", ":", "return", "_smooth_image_helper", ...
33.47619
29.47619
def clean_pid_file(pidfile): """clean pid file. """ if pidfile and os.path.exists(pidfile): os.unlink(pidfile)
[ "def", "clean_pid_file", "(", "pidfile", ")", ":", "if", "pidfile", "and", "os", ".", "path", ".", "exists", "(", "pidfile", ")", ":", "os", ".", "unlink", "(", "pidfile", ")" ]
25.2
5.8
def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } st...
[ "def", "get_redirect_args", "(", "self", ",", "request", ",", "callback", ")", ":", "callback", "=", "request", ".", "build_absolute_uri", "(", "callback", ")", "args", "=", "{", "'client_id'", ":", "self", ".", "provider", ".", "consumer_key", ",", "'redire...
38.230769
13.769231
def get_host(self): """ Gets the host name or IP address. :return: the host name or IP address. """ host = self.get_as_nullable_string("host") host = host if host != None else self.get_as_nullable_string("ip") return host
[ "def", "get_host", "(", "self", ")", ":", "host", "=", "self", ".", "get_as_nullable_string", "(", "\"host\"", ")", "host", "=", "host", "if", "host", "!=", "None", "else", "self", ".", "get_as_nullable_string", "(", "\"ip\"", ")", "return", "host" ]
30
14.666667
def alias(self): """ Returns the device's alias (name). """ try: return self._properties.Get('org.bluez.Device1', 'Alias') except dbus.exceptions.DBusException as e: if e.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownObject': # Blue...
[ "def", "alias", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_properties", ".", "Get", "(", "'org.bluez.Device1'", ",", "'Alias'", ")", "except", "dbus", ".", "exceptions", ".", "DBusException", "as", "e", ":", "if", "e", ".", "get_dbus_nam...
44.928571
21.642857
def yield_amd_require_string_arguments( node, pos, reserved_module=reserved_module, wrapped=define_wrapped): """ This yields only strings within the lists provided in the argument list at the specified position from a function call. Originally, this was implemented for yield a list of m...
[ "def", "yield_amd_require_string_arguments", "(", "node", ",", "pos", ",", "reserved_module", "=", "reserved_module", ",", "wrapped", "=", "define_wrapped", ")", ":", "for", "i", ",", "child", "in", "enumerate", "(", "node", ".", "args", ".", "items", "[", "...
38.555556
17.666667
def path(self, path): """ Creates a path based on the location attribute of the backend and the path argument of the function. If the path argument is an absolute path the path is returned. :param path: The path that should be joined with the backends location. """ if os...
[ "def", "path", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "return", "os", ".", "path", ".", "join", "(", "self", ".", "location", ",", "path", ")" ]
40.2
23
def send_media(self, media_id, user_ids, text='', thread_id=None): """ :param media_id: :param self: bot :param text: text of message :param user_ids: list of user_ids for creating group or one user_id for send to one person :param thread_id: thread_id """ user_ids = _get_user_ids(self, ...
[ "def", "send_media", "(", "self", ",", "media_id", ",", "user_ids", ",", "text", "=", "''", ",", "thread_id", "=", "None", ")", ":", "user_ids", "=", "_get_user_ids", "(", "self", ",", "user_ids", ")", "if", "not", "isinstance", "(", "text", ",", "str"...
32.969697
19.878788
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(descrip...
[ "def", "main", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.main'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'This Python module allows '", "'sending Slack messages.'", ")", "parser", ...
43.645833
27.145833
def loads(s, cls=BinaryQuadraticModel, vartype=None): """Load a COOrdinate formatted binary quadratic model from a string.""" return load(s.split('\n'), cls=cls, vartype=vartype)
[ "def", "loads", "(", "s", ",", "cls", "=", "BinaryQuadraticModel", ",", "vartype", "=", "None", ")", ":", "return", "load", "(", "s", ".", "split", "(", "'\\n'", ")", ",", "cls", "=", "cls", ",", "vartype", "=", "vartype", ")" ]
61.333333
9.666667
def _set_snps(self, snps, build=37): """ Set `_snps` and `_build` properties of this ``Individual``. Notes ----- Intended to be used internally to `lineage`. Parameters ---------- snps : pandas.DataFrame individual's genetic data normalized for use w...
[ "def", "_set_snps", "(", "self", ",", "snps", ",", "build", "=", "37", ")", ":", "self", ".", "_snps", "=", "snps", "self", ".", "_build", "=", "build" ]
28.25
18.125
def parse_frog(lines): """ Interpret the output of the frog parser. Input should be an iterable of lines (i.e. the output of call_frog) Result is a sequence of dicts representing the tokens """ sid = 0 for i, line in enumerate(lines): if not line: # end of sentence marker...
[ "def", "parse_frog", "(", "lines", ")", ":", "sid", "=", "0", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "not", "line", ":", "# end of sentence marker", "sid", "+=", "1", "else", ":", "parts", "=", "line", ".", "split",...
36.913043
15.26087
def trim_baseline_of_removed_secrets(results, baseline, filelist): """ NOTE: filelist is not a comprehensive list of all files in the repo (because we can't be sure whether --all-files is passed in as a parameter to pre-commit). :type results: SecretsCollection :type baseline: SecretsCollection...
[ "def", "trim_baseline_of_removed_secrets", "(", "results", ",", "baseline", ",", "filelist", ")", ":", "updated", "=", "False", "for", "filename", "in", "filelist", ":", "if", "filename", "not", "in", "baseline", ".", "data", ":", "# Nothing to modify, because not...
35.95082
17.491803
def update_vertices(self, vertices): """ Update the triangle vertices. """ vertices = np.array(vertices, dtype=np.float32) self._vbo_v.set_data(vertices)
[ "def", "update_vertices", "(", "self", ",", "vertices", ")", ":", "vertices", "=", "np", ".", "array", "(", "vertices", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "_vbo_v", ".", "set_data", "(", "vertices", ")" ]
26.857143
9.142857
def find_team(self, color: str = None): """Find the :class:`~.Team` with the given properties Returns the team whose attributes match the given properties, or ``None`` if no match is found. :param color: The :class:`~.Team.Color` of the Team """ if color != None: ...
[ "def", "find_team", "(", "self", ",", "color", ":", "str", "=", "None", ")", ":", "if", "color", "!=", "None", ":", "if", "color", "is", "Team", ".", "Color", ".", "BLUE", ":", "return", "self", ".", "blue_team", "else", ":", "return", "self", ".",...
31.6
14.666667
def _put_bucket_policy(self): """Attach a bucket policy to app bucket.""" if self.s3props['bucket_policy']: policy_str = json.dumps(self.s3props['bucket_policy']) _response = self.s3client.put_bucket_policy(Bucket=self.bucket, Policy=policy_str) else: _respons...
[ "def", "_put_bucket_policy", "(", "self", ")", ":", "if", "self", ".", "s3props", "[", "'bucket_policy'", "]", ":", "policy_str", "=", "json", ".", "dumps", "(", "self", ".", "s3props", "[", "'bucket_policy'", "]", ")", "_response", "=", "self", ".", "s3...
53.555556
20.777778
def list_semod(): ''' Return a structure listing all of the selinux modules on the system and what state they are in CLI Example: .. code-block:: bash salt '*' selinux.list_semod .. versionadded:: 2016.3.0 ''' helptext = __salt__['cmd.run']('semodule -h').splitlines() sem...
[ "def", "list_semod", "(", ")", ":", "helptext", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'semodule -h'", ")", ".", "splitlines", "(", ")", "semodule_version", "=", "''", "for", "line", "in", "helptext", ":", "if", "line", ".", "strip", "(", ")", "...
29.826087
18.521739
def add_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5): """ Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the the square root of the sum of squares of all elements of the input along C, H and W dimensions. Parameters ---------- ...
[ "def", "add_l2_normalize", "(", "self", ",", "name", ",", "input_name", ",", "output_name", ",", "epsilon", "=", "1e-5", ")", ":", "spec", "=", "self", ".", "spec", "nn_spec", "=", "self", ".", "nn_spec", "# Add a new layer", "spec_layer", "=", "nn_spec", ...
27.8
21.342857
def _cut_tree(tree, n_clusters, membs): """ Cut the tree to get desired number of clusters as n_clusters 2 <= n_desired <= n_clusters """ ## starting from root, ## a node is added to the cut_set or ## its children are added to node_set assert(n_clusters >= 2) assert(n_clusters <...
[ "def", "_cut_tree", "(", "tree", ",", "n_clusters", ",", "membs", ")", ":", "## starting from root,", "## a node is added to the cut_set or ", "## its children are added to node_set", "assert", "(", "n_clusters", ">=", "2", ")", "assert", "(", "n_clusters", "<=", "len",...
32.863636
13.477273
def get_article(doi, output_format='txt'): """Get the full body of an article from Elsevier. Parameters ---------- doi : str The doi for the desired article. output_format : 'txt' or 'xml' The desired format for the output. Selecting 'txt' (default) strips all xml tags and j...
[ "def", "get_article", "(", "doi", ",", "output_format", "=", "'txt'", ")", ":", "xml_string", "=", "download_article", "(", "doi", ")", "if", "output_format", "==", "'txt'", "and", "xml_string", "is", "not", "None", ":", "text", "=", "extract_text", "(", "...
35.25
20.25
def parse_properties(node): """ Parse a Tiled xml node and return a dict that represents a tiled "property" :param node: etree element :return: dict """ d = dict() for child in node.findall('properties'): for subnode in child.findall('property'): cls = None try: ...
[ "def", "parse_properties", "(", "node", ")", ":", "d", "=", "dict", "(", ")", "for", "child", "in", "node", ".", "findall", "(", "'properties'", ")", ":", "for", "subnode", "in", "child", ".", "findall", "(", "'property'", ")", ":", "cls", "=", "None...
39.888889
20.222222
def full_installation(self, location=None): """Return the full details of the installation.""" url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self._get_location(location)) response = r...
[ "def", "full_installation", "(", "self", ",", "location", "=", "None", ")", ":", "url", "=", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"", "\"/%s/installationInfo?includeTemperatureControlSystems=True\"", "%", "self", ".", "_get_location", "(", "location...
42
19.2
def _parse_bands(lines, n_start): """Parse band structure from cp2k output""" kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for...
[ "def", "_parse_bands", "(", "lines", ",", "n_start", ")", ":", "kpoints", "=", "[", "]", "labels", "=", "[", "]", "bands_s1", "=", "[", "]", "bands_s2", "=", "[", "]", "known_kpoints", "=", "{", "}", "pattern", "=", "re", ".", "compile", "(", "\".*...
42.514286
15.914286
def push_results(self): """Push the checks/actions results to our schedulers :return: None """ # For all schedulers, we check for wait_homerun # and we send back results for scheduler_link_uuid in self.schedulers: scheduler_link = self.schedulers[scheduler_li...
[ "def", "push_results", "(", "self", ")", ":", "# For all schedulers, we check for wait_homerun", "# and we send back results", "for", "scheduler_link_uuid", "in", "self", ".", "schedulers", ":", "scheduler_link", "=", "self", ".", "schedulers", "[", "scheduler_link_uuid", ...
46.2
23.257143
def tokenized_texts_to_sequences_generator(self, tok_texts): """Transforms tokenized text to a sequence of integers. Only top "num_words" most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments tokenized texts:...
[ "def", "tokenized_texts_to_sequences_generator", "(", "self", ",", "tok_texts", ")", ":", "for", "seq", "in", "tok_texts", ":", "vect", "=", "[", "]", "for", "w", "in", "seq", ":", "# if the word is missing you get oov_index", "i", "=", "self", ".", "word_index"...
39.3125
14.4375
def load_reference_data(name=None): """ Fetch LAtools reference data from online repository. Parameters ---------- name : str< Which data to download. Can be one of 'culture_reference', 'culture_test', 'downcore_reference', 'downcore_test', 'iolite_reference' or 'zircon_refe...
[ "def", "load_reference_data", "(", "name", "=", "None", ")", ":", "base_url", "=", "'https://docs.google.com/spreadsheets/d/e/2PACX-1vQJfCeuqrtFFMAeSpA9rguzLAo9OVuw50AHhAULuqjMJzbd3h46PK1KjF69YiJAeNAAjjMDkJK7wMpG/pub?gid={:}&single=true&output=csv'", "gids", "=", "{", "'culture_reference...
35.175
18.325
def main(): """ main method """ # initialize parser usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url" parser = OptionParser(usage, version="%prog "+instapaperlib.__version__) parser.add_option("-u", "--user", action="store", dest="user", m...
[ "def", "main", "(", ")", ":", "# initialize parser", "usage", "=", "\"usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url\"", "parser", "=", "OptionParser", "(", "usage", ",", "version", "=", "\"%prog \"", "+", "instapaperlib", ".", "__version__", ")", "p...
38.644444
21.222222
def merge_conf(to_hash, other_hash, path=[]): "merges other_hash into to_hash" for key in other_hash: if (key in to_hash and isinstance(to_hash[key], dict) and isinstance(other_hash[key], dict)): merge_conf(to_hash[key], other_hash[key], path + [str(key)]) else: ...
[ "def", "merge_conf", "(", "to_hash", ",", "other_hash", ",", "path", "=", "[", "]", ")", ":", "for", "key", "in", "other_hash", ":", "if", "(", "key", "in", "to_hash", "and", "isinstance", "(", "to_hash", "[", "key", "]", ",", "dict", ")", "and", "...
40.888889
15.777778
def __numero_tres_cifras(self, number, indice=None, sing=False): """Convierte a texto numeros de tres cifras""" number = int(number) if number < 30: if sing: return especiales_apocopado[number] else: return especiales_masculino[number] ...
[ "def", "__numero_tres_cifras", "(", "self", ",", "number", ",", "indice", "=", "None", ",", "sing", "=", "False", ")", ":", "number", "=", "int", "(", "number", ")", "if", "number", "<", "30", ":", "if", "sing", ":", "return", "especiales_apocopado", "...
31.192308
19.730769
def compose(*decorators): """Helper to compose decorators:: @a @b def f(): pass Is equivalent to:: @compose(a, b) def f(): ... """ def composed(f): for decor in reversed(decorators): f = decor(f) return f ...
[ "def", "compose", "(", "*", "decorators", ")", ":", "def", "composed", "(", "f", ")", ":", "for", "decor", "in", "reversed", "(", "decorators", ")", ":", "f", "=", "decor", "(", "f", ")", "return", "f", "return", "composed" ]
16.684211
21.631579
def job_success(self, job, queue, job_result): """ Called just after an execute call was successful. job_result is the value returned by the callback, if any. """ job.queued.delete() job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS) queue.success.rpus...
[ "def", "job_success", "(", "self", ",", "job", ",", "queue", ",", "job_result", ")", ":", "job", ".", "queued", ".", "delete", "(", ")", "job", ".", "hmset", "(", "end", "=", "str", "(", "datetime", ".", "utcnow", "(", ")", ")", ",", "status", "=...
43.090909
11.454545
def make_job_graph(infiles, fragfiles, blastcmds): """Return a job dependency graph, based on the passed input sequence files. - infiles - a list of paths to input FASTA files - fragfiles - a list of paths to fragmented input FASTA files By default, will run ANIb - it *is* possible to make a mess of p...
[ "def", "make_job_graph", "(", "infiles", ",", "fragfiles", ",", "blastcmds", ")", ":", "joblist", "=", "[", "]", "# Holds list of job dependency graphs", "# Get dictionary of database-building jobs", "dbjobdict", "=", "build_db_jobs", "(", "infiles", ",", "blastcmds", "...
42.195122
22.390244
def init_states(self, source_encoded: mx.sym.Symbol, source_encoded_lengths: mx.sym.Symbol, source_encoded_max_length: int) -> List[mx.sym.Symbol]: """ Returns a list of symbolic states that represent the initial states of this decoder. ...
[ "def", "init_states", "(", "self", ",", "source_encoded", ":", "mx", ".", "sym", ".", "Symbol", ",", "source_encoded_lengths", ":", "mx", ".", "sym", ".", "Symbol", ",", "source_encoded_max_length", ":", "int", ")", "->", "List", "[", "mx", ".", "sym", "...
48.928571
27.357143
def parse_table(document, tbl): "Parse table element." def _change(rows, pos_x): if len(rows) == 1: return rows count_x = 1 for x in rows[-1]: if count_x == pos_x: x.row_span += 1 count_x += x.grid_span return rows tab...
[ "def", "parse_table", "(", "document", ",", "tbl", ")", ":", "def", "_change", "(", "rows", ",", "pos_x", ")", ":", "if", "len", "(", "rows", ")", "==", "1", ":", "return", "rows", "count_x", "=", "1", "for", "x", "in", "rows", "[", "-", "1", "...
23.84
23.36
def skip_prepare(func): """ A convenience decorator for indicating the raw data should not be prepared. """ @wraps(func) def _wrapper(self, *args, **kwargs): value = func(self, *args, **kwargs) return Data(value, should_prepare=False) return _wrapper
[ "def", "skip_prepare", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")"...
31.333333
12.444444
def btc_bitcoind_tx_serialize( tx ): """ Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC) ...
[ "def", "btc_bitcoind_tx_serialize", "(", "tx", ")", ":", "tx_ins", "=", "[", "]", "tx_outs", "=", "[", "]", "try", ":", "for", "inp", "in", "tx", "[", "'vin'", "]", ":", "next_inp", "=", "{", "\"outpoint\"", ":", "{", "\"index\"", ":", "int", "(", ...
31.677419
21.129032
def search_and_extract_nucleotides_matching_nucleotide_database(self, unpack, euk_check, search_method, ...
[ "def", "search_and_extract_nucleotides_matching_nucleotide_database", "(", "self", ",", "unpack", ",", "euk_check", ",", "search_method", ",", "maximum_range", ",", "threads", ",", "evalue", ",", "hmmsearch_output_table", ",", "hit_reads_fasta", ")", ":", "if", "search_...
41.202128
21.989362
def set_split_extents_by_indices_per_axis(self): """ Sets split shape :attr:`split_shape` and split extents (:attr:`split_begs` and :attr:`split_ends`) from values in :attr:`indices_per_axis`. """ if self.indices_per_axis is None: raise ValueError("Got None fo...
[ "def", "set_split_extents_by_indices_per_axis", "(", "self", ")", ":", "if", "self", ".", "indices_per_axis", "is", "None", ":", "raise", "ValueError", "(", "\"Got None for self.indices_per_axis\"", ")", "self", ".", "logger", ".", "debug", "(", "\"self.array_shape=%s...
50.121212
20.969697
def get_stdout(self, workflow_id, task_id): """Get stdout for a particular task. Args: workflow_id (str): Workflow id. task_id (str): Task id. Returns: Stdout of the task (string). """ url = '%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout...
[ "def", "get_stdout", "(", "self", ",", "workflow_id", ",", "task_id", ")", ":", "url", "=", "'%(wf_url)s/%(wf_id)s/tasks/%(task_id)s/stdout'", "%", "{", "'wf_url'", ":", "self", ".", "workflows_url", ",", "'wf_id'", ":", "workflow_id", ",", "'task_id'", ":", "ta...
29.176471
18.294118
def add_channel(self, chname, workspace=None, num_images=None, settings=None, settings_template=None, settings_share=None, share_keylist=None): """Create a new Ginga channel. Parameters ---------- chname : str The n...
[ "def", "add_channel", "(", "self", ",", "chname", ",", "workspace", "=", "None", ",", "num_images", "=", "None", ",", "settings", "=", "None", ",", "settings_template", "=", "None", ",", "settings_share", "=", "None", ",", "share_keylist", "=", "None", ")"...
39.789916
21.07563
def to_dict(self): """ Return this ModuleDoc as a dict. In addition to `CommentDoc` defaults, this has: - **name**: The module name. - **dependencies**: A list of immediate dependencies. - **all_dependencies**: A list of all dependencies. """ ...
[ "def", "to_dict", "(", "self", ")", ":", "vars", "=", "super", "(", "ModuleDoc", ",", "self", ")", ".", "to_dict", "(", ")", "vars", "[", "'dependencies'", "]", "=", "self", ".", "dependencies", "vars", "[", "'name'", "]", "=", "self", ".", "name", ...
35.058824
16.352941
def known(self, object): """ get the type specified in the object's metadata """ try: md = object.__metadata__ known = md.sxtype return known except: pass
[ "def", "known", "(", "self", ",", "object", ")", ":", "try", ":", "md", "=", "object", ".", "__metadata__", "known", "=", "md", ".", "sxtype", "return", "known", "except", ":", "pass" ]
27.375
15.5
def get_distance(F, x): """Helper function for margin-based loss. Return a distance matrix given a matrix.""" n = x.shape[0] square = F.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose())) # Adding identity to make sqrt work. retu...
[ "def", "get_distance", "(", "F", ",", "x", ")", ":", "n", "=", "x", ".", "shape", "[", "0", "]", "square", "=", "F", ".", "sum", "(", "x", "**", "2.0", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "distance_square", "=", "square", ...
40.444444
21.444444
def decode(self, val): """Override of the default decode method that also uses decode_date.""" # First try the date decoder. new_val = self.decode_date(val) if val != new_val: return new_val # Fall back to the default decoder. return json.JSONDecoder.decode(self, val)
[ "def", "decode", "(", "self", ",", "val", ")", ":", "# First try the date decoder.", "new_val", "=", "self", ".", "decode_date", "(", "val", ")", "if", "val", "!=", "new_val", ":", "return", "new_val", "# Fall back to the default decoder.", "return", "json", "."...
36.375
9.25
def uninstall( ctx, state, all_dev=False, all=False, **kwargs ): """Un-installs a provided package and removes it from Pipfile.""" from ..core import do_uninstall retcode = do_uninstall( packages=state.installstate.packages, editable_packages=state.installstate.editables,...
[ "def", "uninstall", "(", "ctx", ",", "state", ",", "all_dev", "=", "False", ",", "all", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "core", "import", "do_uninstall", "retcode", "=", "do_uninstall", "(", "packages", "=", "state", ...
26.25
18.375
def render_image(self, rgbobj, dst_x, dst_y): """Render the image represented by (rgbobj) at dst_x, dst_y in the offscreen pixmap. """ self.logger.debug("redraw pixmap=%s" % (self.pixmap)) if self.pixmap is None: return self.logger.debug("drawing to pixmap") ...
[ "def", "render_image", "(", "self", ",", "rgbobj", ",", "dst_x", ",", "dst_y", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"redraw pixmap=%s\"", "%", "(", "self", ".", "pixmap", ")", ")", "if", "self", ".", "pixmap", "is", "None", ":", "ret...
38
14.533333
def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_de...
[ "def", "next_frame_basic_stochastic_discrete", "(", ")", ":", "hparams", "=", "basic_deterministic_params", ".", "next_frame_sampling", "(", ")", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "video_num_target_frames", "=", "6", "hparams", ".", "scheduled_sa...
44.785714
9.678571
def get_users(self): """ :return: list of User object """ self.read_sizes() if self.users == 0: self.next_uid = 1 self.next_user_id='1' return [] users = [] max_uid = 0 userdata, size = self.read_with_buffer(const.CMD_US...
[ "def", "get_users", "(", "self", ")", ":", "self", ".", "read_sizes", "(", ")", "if", "self", ".", "users", "==", "0", ":", "self", ".", "next_uid", "=", "1", "self", ".", "next_user_id", "=", "'1'", "return", "[", "]", "users", "=", "[", "]", "m...
48.559322
22.186441
def register(self, command: str, handler: Any): """ Register a new handler for a specific slash command Args: command: Slash command handler: Callback """ if not command.startswith("/"): command = f"/{command}" LOG.info("Registering ...
[ "def", "register", "(", "self", ",", "command", ":", "str", ",", "handler", ":", "Any", ")", ":", "if", "not", "command", ".", "startswith", "(", "\"/\"", ")", ":", "command", "=", "f\"/{command}\"", "LOG", ".", "info", "(", "\"Registering %s to %s\"", "...
27.214286
15.642857
def _find_orm(self, pnq): """Return a Partition object from the database based on a PartitionId. An ORM object is returned, so changes can be persisted. """ # import sqlalchemy.orm.exc from ambry.orm import Partition as OrmPartition # , Table from sqlalchemy.orm import...
[ "def", "_find_orm", "(", "self", ",", "pnq", ")", ":", "# import sqlalchemy.orm.exc", "from", "ambry", ".", "orm", "import", "Partition", "as", "OrmPartition", "# , Table", "from", "sqlalchemy", ".", "orm", "import", "joinedload", "# , joinedload_all", "assert", "...
34.693548
23.580645
def init_host(self): """ Initial host """ env.host_string = self.host_string env.user = self.host_user env.password = self.host_passwd env.key_filename = self.host_keyfile
[ "def", "init_host", "(", "self", ")", ":", "env", ".", "host_string", "=", "self", ".", "host_string", "env", ".", "user", "=", "self", ".", "host_user", "env", ".", "password", "=", "self", ".", "host_passwd", "env", ".", "key_filename", "=", "self", ...
28
6.25
def iter_compress(item_iter, flag_iter): """ iter_compress - like numpy compress Args: item_iter (list): flag_iter (list): of bools Returns: list: true_items Example: >>> # ENABLE_DOCTEST >>> from utool.util_iter import * # NOQA >>> item_iter = [1,...
[ "def", "iter_compress", "(", "item_iter", ",", "flag_iter", ")", ":", "# TODO: Just use it.compress", "true_items", "=", "(", "item", "for", "(", "item", ",", "flag", ")", "in", "zip", "(", "item_iter", ",", "flag_iter", ")", "if", "flag", ")", "return", "...
27.083333
17