text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def event_env_merge_info(app, env, _, other): """Called by Sphinx during phase 3 (resolving). * Combine child process' modified env with this one. Only changes should be new Imgur IDs since cache update is done in event_env_updated() after everything is merged and we're back to one process. :param s...
[ "def", "event_env_merge_info", "(", "app", ",", "env", ",", "_", ",", "other", ")", ":", "other_album_cache", "=", "getattr", "(", "other", ",", "'imgur_album_cache'", ",", "None", ")", "other_image_cache", "=", "getattr", "(", "other", ",", "'imgur_image_cach...
45.545455
24.636364
def build_on_entry(self, runnable, regime, on_entry): """ Build OnEntry start handler code. @param on_entry: OnEntry start handler object @type on_entry: lems.model.dynamics.OnEntry @return: Generated OnEntry code @rtype: list(string) """ on_entry_code ...
[ "def", "build_on_entry", "(", "self", ",", "runnable", ",", "regime", ",", "on_entry", ")", ":", "on_entry_code", "=", "[", "]", "on_entry_code", "+=", "[", "'if self.current_regime != self.last_regime:'", "]", "on_entry_code", "+=", "[", "' self.last_regime = self...
30.090909
19.181818
def run_thread(self): """Run the main thread.""" self._run_thread = True self._thread.setDaemon(True) self._thread.start()
[ "def", "run_thread", "(", "self", ")", ":", "self", ".", "_run_thread", "=", "True", "self", ".", "_thread", ".", "setDaemon", "(", "True", ")", "self", ".", "_thread", ".", "start", "(", ")" ]
30
8.8
def convertall(table, *args, **kwargs): """ Convenience function to convert all fields in the table using a common function or mapping. See also :func:`convert`. The ``where`` keyword argument can be given with a callable or expression which is evaluated on each row and which should return True if ...
[ "def", "convertall", "(", "table", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO don't read the data twice!", "return", "convert", "(", "table", ",", "header", "(", "table", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
36.538462
20.692308
def pos(self): """ Lazy-loads the part of speech tag for this word :getter: Returns the plain string value of the POS tag for the word :type: str """ if self._pos is None: poses = self._element.xpath('POS/text()') if len(poses) > 0: ...
[ "def", "pos", "(", "self", ")", ":", "if", "self", ".", "_pos", "is", "None", ":", "poses", "=", "self", ".", "_element", ".", "xpath", "(", "'POS/text()'", ")", "if", "len", "(", "poses", ")", ">", "0", ":", "self", ".", "_pos", "=", "poses", ...
27.384615
17.846154
def dot_eth_label(name): """ Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex' If name is already a label, this should be a noop, except for converting to a string and validating the name syntax. """ label = name_to_label(name, registrar='eth') if len(label) < MIN_ETH_LAB...
[ "def", "dot_eth_label", "(", "name", ")", ":", "label", "=", "name_to_label", "(", "name", ",", "registrar", "=", "'eth'", ")", "if", "len", "(", "label", ")", "<", "MIN_ETH_LABEL_LENGTH", ":", "raise", "InvalidLabel", "(", "'name %r is too short'", "%", "la...
37.272727
16.363636
def create(cls, bucket, key, value): """Create a new tag for bucket.""" with db.session.begin_nested(): obj = cls( bucket_id=as_bucket_id(bucket), key=key, value=value ) db.session.add(obj) return obj
[ "def", "create", "(", "cls", ",", "bucket", ",", "key", ",", "value", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", "=", "cls", "(", "bucket_id", "=", "as_bucket_id", "(", "bucket", ")", ",", "key", "=", "key", ...
29.9
11.7
def hpx_to_axes(h, npix): """ Generate a sequence of bin edge vectors corresponding to the axes of a HPX object.""" x = h.ebins z = np.arange(npix[-1] + 1) return x, z
[ "def", "hpx_to_axes", "(", "h", ",", "npix", ")", ":", "x", "=", "h", ".", "ebins", "z", "=", "np", ".", "arange", "(", "npix", "[", "-", "1", "]", "+", "1", ")", "return", "x", ",", "z" ]
26
16.285714
def dumps(self, script): "Return a compressed representation of script as a binary string." string = BytesIO() self._dump(script, string, self._protocol, self._version) return string.getvalue()
[ "def", "dumps", "(", "self", ",", "script", ")", ":", "string", "=", "BytesIO", "(", ")", "self", ".", "_dump", "(", "script", ",", "string", ",", "self", ".", "_protocol", ",", "self", ".", "_version", ")", "return", "string", ".", "getvalue", "(", ...
44.2
19.4
def virtual_interface_create(provider, names, **kwargs): ''' Attach private interfaces to a server CLI Example: .. code-block:: bash salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt' ''' client = _get_client() return client.extra_action(...
[ "def", "virtual_interface_create", "(", "provider", ",", "names", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_client", "(", ")", "return", "client", ".", "extra_action", "(", "provider", "=", "provider", ",", "names", "=", "names", ",", "action...
29.538462
32.615385
def delete_view(self, query_criteria=None, uid='_all_users'): ''' a method to delete a view associated with a user design doc :param query_criteria: [optional] dictionary with valid jsonmodel query criteria :param uid: [optional] string with uid of design document to up...
[ "def", "delete_view", "(", "self", ",", "query_criteria", "=", "None", ",", "uid", "=", "'_all_users'", ")", ":", "# https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/query/delete__db___design__ddoc_", "title", "=", "'%s.del...
40.94382
26.247191
def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None, region=None, profile=None, url=None, interface=None, **connection_args): ''' Create an endpoint for an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_create nova...
[ "def", "endpoint_create", "(", "service", ",", "publicurl", "=", "None", ",", "internalurl", "=", "None", ",", "adminurl", "=", "None", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "url", "=", "None", ",", "interface", "=", "None", ","...
45.16129
27.096774
def normal_print(raw): ''' no colorful text, for output.''' lines = raw.split('\n') for line in lines: if line: print(line + '\n')
[ "def", "normal_print", "(", "raw", ")", ":", "lines", "=", "raw", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "if", "line", ":", "print", "(", "line", "+", "'\\n'", ")" ]
26.166667
13.833333
def run(): """Fetches changes and applies them to VIFs periodically Process as of RM11449: * Get all groups from redis * Fetch ALL VIFs from Xen * Walk ALL VIFs and partition them into added, updated and removed * Walk the final "modified" VIFs list and apply flows to each """ groups_cl...
[ "def", "run", "(", ")", ":", "groups_client", "=", "sg_cli", ".", "SecurityGroupsClient", "(", ")", "xapi_client", "=", "xapi", ".", "XapiClient", "(", ")", "interfaces", "=", "set", "(", ")", "while", "True", ":", "try", ":", "interfaces", "=", "xapi_cl...
41.702128
24.702128
def repmc(instr, marker, value, lenout=None): """ Replace a marker with a character string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacemen...
[ "def", "repmc", "(", "instr", ",", "marker", ",", "value", ",", "lenout", "=", "None", ")", ":", "if", "lenout", "is", "None", ":", "lenout", "=", "ctypes", ".", "c_int", "(", "len", "(", "instr", ")", "+", "len", "(", "value", ")", "+", "len", ...
32.48
13.84
def post_object_async(self, path, **kwds): """POST to an object.""" return self.do_request_async(self.api_url + path, 'POST', **kwds)
[ "def", "post_object_async", "(", "self", ",", "path", ",", "*", "*", "kwds", ")", ":", "return", "self", ".", "do_request_async", "(", "self", ".", "api_url", "+", "path", ",", "'POST'", ",", "*", "*", "kwds", ")" ]
46.333333
10.333333
def get_network(self): """ Identify the connected network. This call returns a dictionary with keys chain_id, core_symbol and prefix """ props = self.get_chain_properties() chain_id = props["chain_id"] for k, v in known_chains.items(): if v["chain_id"] == ...
[ "def", "get_network", "(", "self", ")", ":", "props", "=", "self", ".", "get_chain_properties", "(", ")", "chain_id", "=", "props", "[", "\"chain_id\"", "]", "for", "k", ",", "v", "in", "known_chains", ".", "items", "(", ")", ":", "if", "v", "[", "\"...
40.75
12.75
def __cancel(self, checkout_id, cancel_reason, **kwargs): """Call documentation: `/checkout/cancel <https://www.wepay.com/developer/reference/checkout#cancel>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_toke...
[ "def", "__cancel", "(", "self", ",", "checkout_id", ",", "cancel_reason", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'checkout_id'", ":", "checkout_id", ",", "'cancel_reason'", ":", "cancel_reason", "}", "return", "self", ".", "make_call", "(", ...
36.916667
20.541667
def relation_clear(r_id=None): ''' Clears any relation data already set on relation r_id ''' settings = relation_get(rid=r_id, unit=local_unit()) for setting in settings: if setting not in ['public-address', 'private-address']: settings[setting] = None rel...
[ "def", "relation_clear", "(", "r_id", "=", "None", ")", ":", "settings", "=", "relation_get", "(", "rid", "=", "r_id", ",", "unit", "=", "local_unit", "(", ")", ")", "for", "setting", "in", "settings", ":", "if", "setting", "not", "in", "[", "'public-a...
40.888889
11.333333
def getMenu(self): """Get manager interface section list from Squid Proxy Server @return: List of tuples (section, description, type) """ data = self._retrieve('') info_list = [] for line in data.splitlines(): mobj = re.match('^\s*(\S.*\S...
[ "def", "getMenu", "(", "self", ")", ":", "data", "=", "self", ".", "_retrieve", "(", "''", ")", "info_list", "=", "[", "]", "for", "line", "in", "data", ".", "splitlines", "(", ")", ":", "mobj", "=", "re", ".", "match", "(", "'^\\s*(\\S.*\\S)\\s*\\t\...
34.153846
16.461538
def timestamp(x): """Get a timestamp from a date in python 3 and python 2""" if x.tzinfo is None: # Naive dates to utc x = x.replace(tzinfo=utc) if hasattr(x, 'timestamp'): return x.timestamp() else: return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
[ "def", "timestamp", "(", "x", ")", ":", "if", "x", ".", "tzinfo", "is", "None", ":", "# Naive dates to utc", "x", "=", "x", ".", "replace", "(", "tzinfo", "=", "utc", ")", "if", "hasattr", "(", "x", ",", "'timestamp'", ")", ":", "return", "x", ".",...
30.1
17.9
def pydict2xml(filename, metadata_dict, **kwargs): """Create an XML file. Takes a path to where the XML file should be created and a metadata dictionary. """ try: f = open(filename, 'w') f.write(pydict2xmlstring(metadata_dict, **kwargs).encode('utf-8')) f.close() except:...
[ "def", "pydict2xml", "(", "filename", ",", "metadata_dict", ",", "*", "*", "kwargs", ")", ":", "try", ":", "f", "=", "open", "(", "filename", ",", "'w'", ")", "f", ".", "write", "(", "pydict2xmlstring", "(", "metadata_dict", ",", "*", "*", "kwargs", ...
30.642857
18.857143
def rec_apply(func, n): """ Used to determine parent directory n levels up by repeatedly applying os.path.dirname """ if n > 1: rec_func = rec_apply(func, n - 1) return lambda x: func(rec_func(x)) return func
[ "def", "rec_apply", "(", "func", ",", "n", ")", ":", "if", "n", ">", "1", ":", "rec_func", "=", "rec_apply", "(", "func", ",", "n", "-", "1", ")", "return", "lambda", "x", ":", "func", "(", "rec_func", "(", "x", ")", ")", "return", "func" ]
26.666667
9.333333
def dump(stream=None): """ Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project. """ if stream: stream.write(dumps()) else: path = os.path.join(os.path.dirname(insights._...
[ "def", "dump", "(", "stream", "=", "None", ")", ":", "if", "stream", ":", "stream", ".", "write", "(", "dumps", "(", ")", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "insights", "....
32.833333
18.333333
def runprofilerandshow(funcname, profilepath, argv='', *args, **kwargs): ''' Run a functions profiler and show it in a GUI visualisation using RunSnakeRun Note: can also use calibration for more exact results ''' functionprofiler.runprofile(funcname+'(\''+argv+'\')', profilepath, *args, **kwargs) ...
[ "def", "runprofilerandshow", "(", "funcname", ",", "profilepath", ",", "argv", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "functionprofiler", ".", "runprofile", "(", "funcname", "+", "'(\\''", "+", "argv", "+", "'\\')'", ",", "profil...
56.25
32.75
def _set_esp(self, v, load=False): """ Setter method for esp, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp (algorithm-type-esp) If this variable is read-only (config: false) in the source YANG file, then _set_esp is considered...
[ "def", "_set_esp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "...
93.25
48.708333
def gen_timeout_resend(attempts): """Generate the time in seconds in which DHCPDISCOVER wil be retransmited. [:rfc:`2131#section-3.1`]:: might retransmit the DHCPREQUEST message four times, for a total delay of 60 seconds [:rfc:`2131#section-4.1`]:: For example, in a 10Mb/sec Eth...
[ "def", "gen_timeout_resend", "(", "attempts", ")", ":", "timeout", "=", "2", "**", "(", "attempts", "+", "1", ")", "+", "random", ".", "uniform", "(", "-", "1", ",", "+", "1", ")", "logger", ".", "debug", "(", "'next timeout resending will happen on %s'", ...
43.8
24.32
def choice_default_invalidator(self, obj): """Invalidated cached items when the Choice changes.""" invalid = [('Question', obj.question_id, True)] for pk in obj.voters.values_list('pk', flat=True): invalid.append(('User', pk, False)) return invalid
[ "def", "choice_default_invalidator", "(", "self", ",", "obj", ")", ":", "invalid", "=", "[", "(", "'Question'", ",", "obj", ".", "question_id", ",", "True", ")", "]", "for", "pk", "in", "obj", ".", "voters", ".", "values_list", "(", "'pk'", ",", "flat"...
47.833333
10
def search_user_directory(self, term: str) -> List[User]: """ Search user directory for a given term, returning a list of users Args: term: term to be searched for Returns: user_list: list of users returned by server-side search """ response = self...
[ "def", "search_user_directory", "(", "self", ",", "term", ":", "str", ")", "->", "List", "[", "User", "]", ":", "response", "=", "self", ".", "api", ".", "_send", "(", "'POST'", ",", "'/user_directory/search'", ",", "{", "'search_term'", ":", "term", ","...
30
18
def p_systemcall_signed(self, p): # for $signed system task 'systemcall : DOLLER SIGNED LPAREN sysargs RPAREN' p[0] = SystemCall(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_systemcall_signed", "(", "self", ",", "p", ")", ":", "# for $signed system task", "p", "[", "0", "]", "=", "SystemCall", "(", "p", "[", "2", "]", ",", "p", "[", "4", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ...
52.75
14.75
def prepare(doc): """Sets the caption_found and plot_found variables to False.""" doc.caption_found = False doc.plot_found = False doc.listings_counter = 0
[ "def", "prepare", "(", "doc", ")", ":", "doc", ".", "caption_found", "=", "False", "doc", ".", "plot_found", "=", "False", "doc", ".", "listings_counter", "=", "0" ]
33.4
12
def get_env_spec(self, filters=None): """ Get the spec of the current env. The spec will hold the info about all the domains and networks associated with this env. Args: filters (list): list of paths to keys that should be removed from the init file ...
[ "def", "get_env_spec", "(", "self", ",", "filters", "=", "None", ")", ":", "spec", "=", "{", "'domains'", ":", "{", "vm_name", ":", "deepcopy", "(", "vm_object", ".", "spec", ")", "for", "vm_name", ",", "vm_object", "in", "self", ".", "_vms", ".", "v...
30.142857
18.785714
def tdist_ci(x, df, stderr, level): """ Confidence Intervals using the t-distribution """ q = (1 + level)/2 delta = stats.t.ppf(q, df) * stderr return x - delta, x + delta
[ "def", "tdist_ci", "(", "x", ",", "df", ",", "stderr", ",", "level", ")", ":", "q", "=", "(", "1", "+", "level", ")", "/", "2", "delta", "=", "stats", ".", "t", ".", "ppf", "(", "q", ",", "df", ")", "*", "stderr", "return", "x", "-", "delta...
27
6.142857
def compute_inj_optimal_snr(workflow, inj_file, precalc_psd_files, out_dir, tags=None): "Set up a job for computing optimal SNRs of a sim_inspiral file." if tags is None: tags = [] node = Executable(workflow.cp, 'optimal_snr', ifos=workflow.ifos, ou...
[ "def", "compute_inj_optimal_snr", "(", "workflow", ",", "inj_file", ",", "precalc_psd_files", ",", "out_dir", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "node", "=", "Executable", "(", "workflow", ".", "cp...
45.923077
23.307692
def bytes2unicode(x, encoding='utf-8', errors='strict'): """ Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 's...
[ "def", "bytes2unicode", "(", "x", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "x", ",", "(", "text_type", ",", "type", "(", "None", ")", ")", ")", ":", "return", "x", "return", "text_type", "(",...
37.5
13.071429
def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-...
[ "def", "zone_get", "(", "name", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "dnsconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'dns'", ",", "*", "*", "kwargs", ")", "try", ":", "zone", "=", "dnsconn", ".", "zones", ".",...
24.290323
24.096774
def get_file(self, attr_name): '''Return absolute path to logging file for obj's attribute.''' return os.path.abspath(os.path.join(self.folder, "{}.log" .format(attr_name)))
[ "def", "get_file", "(", "self", ",", "attr_name", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "folder", ",", "\"{}.log\"", ".", "format", "(", "attr_name", ")", ")", ")" ]
57.5
22.5
def twostep(script, iterations=3, angle_threshold=60, normal_steps=20, fit_steps=20, selected=False): """ Two Step Smoothing, a feature preserving/enhancing fairing filter. It is based on a Normal Smoothing step where similar normals are averaged together and a step where the vertexes are fitte...
[ "def", "twostep", "(", "script", ",", "iterations", "=", "3", ",", "angle_threshold", "=", "60", ",", "normal_steps", "=", "20", ",", "fit_steps", "=", "20", ",", "selected", "=", "False", ")", ":", "filter_xml", "=", "''", ".", "join", "(", "[", "' ...
37.378788
18.333333
def tsave( text, font=DEFAULT_FONT, filename="art", chr_ignore=True, print_status=True): r""" Save ascii art (support \n). :param text: input text :param font: input font :type font:str :type text:str :param filename: output file name :type filena...
[ "def", "tsave", "(", "text", ",", "font", "=", "DEFAULT_FONT", ",", "filename", "=", "\"art\"", ",", "chr_ignore", "=", "True", ",", "print_status", "=", "True", ")", ":", "try", ":", "if", "isinstance", "(", "text", ",", "str", ")", "is", "False", "...
31.26
14.92
def create_media_service_rg(access_token, subscription_id, rgname, location, stoname, msname): '''Create a media service in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group na...
[ "def", "create_media_service_rg", "(", "access_token", ",", "subscription_id", ",", "rgname", ",", "location", ",", "stoname", ",", "msname", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", ...
43.724138
18.068966
def get_schema(self, filename): """ Guess schema using messytables """ table_set = self.read_file(filename) # Have I been able to read the filename if table_set is None: return [] # Get the first table as rowset row_set = table_...
[ "def", "get_schema", "(", "self", ",", "filename", ")", ":", "table_set", "=", "self", ".", "read_file", "(", "filename", ")", "# Have I been able to read the filename", "if", "table_set", "is", "None", ":", "return", "[", "]", "# Get the first table as rowset", "...
30.793103
15.827586
def gen_binder_rst(fpath, binder_conf, gallery_conf): """Generate the RST + link for the Binder badge. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None If a dictionary it must have the following keys: ...
[ "def", "gen_binder_rst", "(", "fpath", ",", "binder_conf", ",", "gallery_conf", ")", ":", "binder_conf", "=", "check_binder_conf", "(", "binder_conf", ")", "binder_url", "=", "gen_binder_url", "(", "fpath", ",", "binder_conf", ",", "gallery_conf", ")", "rst", "=...
34.416667
24.166667
def unique_values(func): """ Wrap a function returning an iterable such that the resulting iterable only ever yields unique items. """ @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper
[ "def", "unique_values", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "unique_everseen", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "...
24.181818
18.363636
def screeplot(self, type="barplot", **kwargs): """ Produce the scree plot. Library ``matplotlib`` is required for this function. :param str type: either ``"barplot"`` or ``"lines"``. """ # check for matplotlib. exit if absent. is_server = kwargs.pop("server") ...
[ "def", "screeplot", "(", "self", ",", "type", "=", "\"barplot\"", ",", "*", "*", "kwargs", ")", ":", "# check for matplotlib. exit if absent.", "is_server", "=", "kwargs", ".", "pop", "(", "\"server\"", ")", "if", "kwargs", ":", "raise", "ValueError", "(", "...
38.3
18.7
def deserialize_non_framed_values(stream, header, verifier=None): """Deserializes the IV and body length from a non-framed stream. :param stream: Source data stream :type stream: io.BytesIO :param header: Deserialized header :type header: aws_encryption_sdk.structures.MessageHeader :param verif...
[ "def", "deserialize_non_framed_values", "(", "stream", ",", "header", ",", "verifier", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"Starting non-framed body iv/tag deserialization\"", ")", "(", "data_iv", ",", "data_length", ")", "=", "unpack_values", "("...
47.066667
17
def script_status(self, script_id): """ Returns the run status of a stored script as well as the current values of parameters 0 to 9. script_id:= id of stored script. The run status may be . . PI_SCRIPT_INITING PI_SCRIPT_HALTED PI_SCRIPT_RUNNING...
[ "def", "script_status", "(", "self", ",", "script_id", ")", ":", "res", "=", "yield", "from", "self", ".", "_pigpio_aio_command", "(", "_PI_CMD_PROCP", ",", "script_id", ",", "0", ")", "bytes", "=", "u2i", "(", "res", ")", "if", "bytes", ">", "0", ":",...
28.159091
19.977273
def _get_spinner(self, spinner): """Extracts spinner value from options and returns value containing spinner frames and interval, defaults to 'dots' spinner. Parameters ---------- spinner : dict, str Contains spinner value or type of spinner to be used Returns...
[ "def", "_get_spinner", "(", "self", ",", "spinner", ")", ":", "default_spinner", "=", "Spinners", "[", "'dots'", "]", ".", "value", "if", "spinner", "and", "type", "(", "spinner", ")", "==", "dict", ":", "return", "spinner", "if", "is_supported", "(", ")...
32.708333
18.166667
def depricated_name(newmethod): """ Decorator for warning user of depricated functions before use. Args: newmethod (str): Name of method to use instead. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.simplefilter('always', Deprecatio...
[ "def", "depricated_name", "(", "newmethod", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "simplefilter", "(", "'always'", ...
34.894737
19.210526
def focus_cb(self, viewer, channel): """ Callback from the reference viewer shell when the focus changes between channels. """ chname = channel.name if self.active != chname: # focus has shifted to a different channel than our idea # of the active...
[ "def", "focus_cb", "(", "self", ",", "viewer", ",", "channel", ")", ":", "chname", "=", "channel", ".", "name", "if", "self", ".", "active", "!=", "chname", ":", "# focus has shifted to a different channel than our idea", "# of the active one", "self", ".", "activ...
32.5
14.642857
def is_async_call(func): '''inspect.iscoroutinefunction that looks through partials.''' while isinstance(func, partial): func = func.func return inspect.iscoroutinefunction(func)
[ "def", "is_async_call", "(", "func", ")", ":", "while", "isinstance", "(", "func", ",", "partial", ")", ":", "func", "=", "func", ".", "func", "return", "inspect", ".", "iscoroutinefunction", "(", "func", ")" ]
38.8
13.2
def generate_hash_comment(file_path): """ Read file with given file_path and return string of format # SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709 which is hex representation of SHA1 file content hash """ with open(file_path, 'rb') as fp: hexdigest = hashlib.sha1(fp.read().strip(...
[ "def", "generate_hash_comment", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "fp", ":", "hexdigest", "=", "hashlib", ".", "sha1", "(", "fp", ".", "read", "(", ")", ".", "strip", "(", ")", ")", ".", "hexdigest"...
33.454545
15.090909
def set_y2label(self, s, delay_draw=False): "set plot ylabel" self.conf.relabel(y2label=s, delay_draw=delay_draw)
[ "def", "set_y2label", "(", "self", ",", "s", ",", "delay_draw", "=", "False", ")", ":", "self", ".", "conf", ".", "relabel", "(", "y2label", "=", "s", ",", "delay_draw", "=", "delay_draw", ")" ]
42.333333
12.333333
def _create_intermediate_nodes(self, name): """Create intermediate nodes if hierarchy does not exist.""" hierarchy = self._split_node_name(name, self.root_name) node_tree = [ self.root_name + self._node_separator + self._node_separator.join(hierarchy[: num + 1...
[ "def", "_create_intermediate_nodes", "(", "self", ",", "name", ")", ":", "hierarchy", "=", "self", ".", "_split_node_name", "(", "name", ",", "self", ".", "root_name", ")", "node_tree", "=", "[", "self", ".", "root_name", "+", "self", ".", "_node_separator",...
39.684211
15.894737
def has_nans(obj): """Check if obj has any NaNs Compatible with different behavior of np.isnan, which sometimes applies over all axes (py35, py35) and sometimes does not (py34). """ nans = np.isnan(obj) while np.ndim(nans): nans = np.any(nans) return bool(nans)
[ "def", "has_nans", "(", "obj", ")", ":", "nans", "=", "np", ".", "isnan", "(", "obj", ")", "while", "np", ".", "ndim", "(", "nans", ")", ":", "nans", "=", "np", ".", "any", "(", "nans", ")", "return", "bool", "(", "nans", ")" ]
28.9
18.2
def tag_pivot(self, tag_resource): """Pivot point on tags for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided tag applied. **Example Endpoints URI's** +--------------+----------------------...
[ "def", "tag_pivot", "(", "self", ",", "tag_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "tag_resource", ".", "request_uri", ",", "resource", ".", "_request_uri", "...
59.333333
35
def team_stats(game_id): """Return team stats of a game with matching id. The additional pitching/batting is mostly the same stats. MLB decided to have two box score files, thus we return the data from both. """ # get data from data module box_score = mlbgame.data.get_box_score(game_id) raw...
[ "def", "team_stats", "(", "game_id", ")", ":", "# get data from data module", "box_score", "=", "mlbgame", ".", "data", ".", "get_box_score", "(", "game_id", ")", "raw_box_score", "=", "mlbgame", ".", "data", ".", "get_raw_box_score", "(", "game_id", ")", "# par...
41.095238
16.952381
def _forceInt(x,y,z,dens,b2,c2,i,glx=None,glw=None): """Integral that gives the force in x,y,z""" def integrand(s): t= 1/s**2.-1. return dens(numpy.sqrt(x**2./(1.+t)+y**2./(b2+t)+z**2./(c2+t)))\ *(x/(1.+t)*(i==0)+y/(b2+t)*(i==1)+z/(c2+t)*(i==2))\ /numpy.sqrt((1.+(b2-1.)*s...
[ "def", "_forceInt", "(", "x", ",", "y", ",", "z", ",", "dens", ",", "b2", ",", "c2", ",", "i", ",", "glx", "=", "None", ",", "glw", "=", "None", ")", ":", "def", "integrand", "(", "s", ")", ":", "t", "=", "1", "/", "s", "**", "2.", "-", ...
44.545455
20.181818
def import_end_event_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN end event. End event inherits sequence of eventDefinitionRef from Event type. Separate methods for each event type are required since each of them...
[ "def", "import_end_event_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "element", ")", ":", "end_event_definitions", "=", "{", "'messageEventDefinition'", ",", "'signalEventDefinition'", ",", "'escalationEventDefinition'", ",", "'errorE...
71.470588
40.882353
def maybe_timeout_options(self): """Implements the NailgunProtocol.TimeoutProvider interface.""" if self._exit_timeout_start_time: return NailgunProtocol.TimeoutOptions(self._exit_timeout_start_time, self._exit_timeout) else: return None
[ "def", "maybe_timeout_options", "(", "self", ")", ":", "if", "self", ".", "_exit_timeout_start_time", ":", "return", "NailgunProtocol", ".", "TimeoutOptions", "(", "self", ".", "_exit_timeout_start_time", ",", "self", ".", "_exit_timeout", ")", "else", ":", "retur...
42.666667
19.833333
def loadProfile(self, profile, inspectorFullName=None): """ Reads the persistent program settings for the current profile. If inspectorFullName is given, a window with this inspector will be created if it wasn't already created in the profile. All windows with this inspector will be rai...
[ "def", "loadProfile", "(", "self", ",", "profile", ",", "inspectorFullName", "=", "None", ")", ":", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "logger", ".", "info", "(", "\"Reading profile {!r} from: {}\"", ".", "format", "(", "profile", ",", "s...
43.682927
21.804878
def split_history_item(history): """ Return the log file and optional description for item. """ try: log_file, description = shlex.split(history) except ValueError: log_file = history.strip() description = None return log_file, description
[ "def", "split_history_item", "(", "history", ")", ":", "try", ":", "log_file", ",", "description", "=", "shlex", ".", "split", "(", "history", ")", "except", "ValueError", ":", "log_file", "=", "history", ".", "strip", "(", ")", "description", "=", "None",...
25.272727
14.181818
def to_xml(cls, enum_val): """ Return the XML value of the enumeration value *enum_val*. """ if enum_val not in cls._member_to_xml: raise ValueError( "value '%s' not in enumeration %s" % (enum_val, cls.__name__) ) return cls._member_to_xml[...
[ "def", "to_xml", "(", "cls", ",", "enum_val", ")", ":", "if", "enum_val", "not", "in", "cls", ".", "_member_to_xml", ":", "raise", "ValueError", "(", "\"value '%s' not in enumeration %s\"", "%", "(", "enum_val", ",", "cls", ".", "__name__", ")", ")", "return...
35.666667
13.666667
def set_default_symbols(self): """Set self.symbols based on self.numbers and the periodic table.""" self.symbols = tuple(periodic[n].symbol for n in self.numbers)
[ "def", "set_default_symbols", "(", "self", ")", ":", "self", ".", "symbols", "=", "tuple", "(", "periodic", "[", "n", "]", ".", "symbol", "for", "n", "in", "self", ".", "numbers", ")" ]
58.666667
13.333333
def _build_http_client(cls, session: AppSession): '''Create the HTTP client. Returns: Client: An instance of :class:`.http.Client`. ''' # TODO: # recorder = self._build_recorder() stream_factory = functools.partial( HTTPStream, ignore...
[ "def", "_build_http_client", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "# TODO:", "# recorder = self._build_recorder()", "stream_factory", "=", "functools", ".", "partial", "(", "HTTPStream", ",", "ignore_length", "=", "session", ".", "args", ".", "...
29.947368
18.473684
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG: """return the higher parent which is not an AssignName, Tuple or List node """ while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)): node = node.parent return node
[ "def", "assign_parent", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "astroid", ".", "node_classes", ".", "NodeNG", ":", "while", "node", "and", "isinstance", "(", "node", ",", "(", "astroid", ".", "AssignName", ",", "astroid...
49.5
21.666667
def _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """ for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
[ "def", "_iget", "(", "key", ",", "lookup_dict", ")", ":", "for", "k", ",", "v", "in", "lookup_dict", ".", "items", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ":", "return", "v", "return", "None" ]
27
11.5
def sas_logical_jbods(self): """ Gets the SAS Logical JBODs API client. Returns: SasLogicalJbod: """ if not self.__sas_logical_jbods: self.__sas_logical_jbods = SasLogicalJbods(self.__connection) return self.__sas_logical_jbods
[ "def", "sas_logical_jbods", "(", "self", ")", ":", "if", "not", "self", ".", "__sas_logical_jbods", ":", "self", ".", "__sas_logical_jbods", "=", "SasLogicalJbods", "(", "self", ".", "__connection", ")", "return", "self", ".", "__sas_logical_jbods" ]
29.1
12.9
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
[ "def", "get_cash_balance", "(", "self", ")", ":", "cash", "=", "False", "try", ":", "response", "=", "self", ".", "session", ".", "get", "(", "'/browse/cashBalanceAj.action'", ")", "json_response", "=", "response", ".", "json", "(", ")", "if", "self", ".",...
36.393939
23.787879
def read_sections(): """Read ini files and return list of pairs (name, options)""" config = configparser.ConfigParser() config.read(('requirements.ini', 'setup.cfg', 'tox.ini')) return [ ( name, { key: parse_value(key, config[name][key]) fo...
[ "def", "read_sections", "(", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "(", "'requirements.ini'", ",", "'setup.cfg'", ",", "'tox.ini'", ")", ")", "return", "[", "(", "name", ",", "{", "key", ":", ...
28.6
18
def enable_collection(f): """Call the wrapped function with a HistogramCollection as argument.""" @wraps(f) def new_f(h: AbstractHistogram1D, **kwargs): from physt.histogram_collection import HistogramCollection if isinstance(h, HistogramCollection): return f(h, **kwargs) ...
[ "def", "enable_collection", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "new_f", "(", "h", ":", "AbstractHistogram1D", ",", "*", "*", "kwargs", ")", ":", "from", "physt", ".", "histogram_collection", "import", "HistogramCollection", "if", "isin...
38.9
15.4
def by_organizations(self, field=None): """ Used to seggregate the data acording to organizations. This method pops the latest aggregation from the self.aggregations dict and adds it as a nested aggregation under itself :param field: the field to create the parent agg (optional)...
[ "def", "by_organizations", "(", "self", ",", "field", "=", "None", ")", ":", "# this functions is currently only for issues and PRs", "agg_field", "=", "field", "if", "field", "else", "\"author_org_name\"", "agg_key", "=", "\"terms_\"", "+", "agg_field", "if", "agg_ke...
42.884615
21.346154
def expand_tamil(start,end): """ expand uyir or mei-letter range etc. i.e. அ-ஔ gets converted to அ,ஆ,இ,ஈ,உ,ஊ,எ,ஏ,ஐ,ஒ,ஓ,ஔ etc. """ # few sequences for seq in [utf8.uyir_letters, utf8.grantha_mei_letters, \ utf8.grantha_agaram_letters]: if is_containing_seq(start,end,seq):...
[ "def", "expand_tamil", "(", "start", ",", "end", ")", ":", "# few sequences", "for", "seq", "in", "[", "utf8", ".", "uyir_letters", ",", "utf8", ".", "grantha_mei_letters", ",", "utf8", ".", "grantha_agaram_letters", "]", ":", "if", "is_containing_seq", "(", ...
38.733333
12.4
def UWRatio(s1, s2, full_process=True): """Return a measure of the sequences' similarity between 0 and 100, using different algorithms. Same as WRatio but preserving unicode. """ return WRatio(s1, s2, force_ascii=False, full_process=full_process)
[ "def", "UWRatio", "(", "s1", ",", "s2", ",", "full_process", "=", "True", ")", ":", "return", "WRatio", "(", "s1", ",", "s2", ",", "force_ascii", "=", "False", ",", "full_process", "=", "full_process", ")" ]
51.6
12.4
def get_parameter_p_value_too_high_warning( model_type, model_params, parameter, p_value, maximum_p_value ): """ Return an empty list or a single warning wrapped in a list indicating whether model parameter p-value is too high. Parameters ---------- model_type : :any:`str` Model type (e...
[ "def", "get_parameter_p_value_too_high_warning", "(", "model_type", ",", "model_params", ",", "parameter", ",", "p_value", ",", "maximum_p_value", ")", ":", "warnings", "=", "[", "]", "if", "p_value", ">", "maximum_p_value", ":", "data", "=", "{", "\"{}_p_value\""...
34.234043
19.808511
def compound_crossspec(a_data, tbin, Df=None, pointProcess=False): """ Calculate cross spectra of compound signals. a_data is a list of datasets (a_data = [data1,data2,...]). For each dataset in a_data, the compound signal is calculated and the crossspectra between these compound signals is computed...
[ "def", "compound_crossspec", "(", "a_data", ",", "tbin", ",", "Df", "=", "None", ",", "pointProcess", "=", "False", ")", ":", "a_mdata", "=", "[", "]", "for", "data", "in", "a_data", ":", "a_mdata", ".", "append", "(", "np", ".", "sum", "(", "data", ...
31.191489
23.404255
def _remote_file_size(url=None, file_name=None, pb_dir=None): """ Get the remote file size in bytes Parameters ---------- url : str, optional The full url of the file. Use this option to explicitly state the full url. file_name : str, optional The base file name. Use thi...
[ "def", "_remote_file_size", "(", "url", "=", "None", ",", "file_name", "=", "None", ",", "pb_dir", "=", "None", ")", ":", "# Option to construct the url", "if", "file_name", "and", "pb_dir", ":", "url", "=", "posixpath", ".", "join", "(", "config", ".", "d...
28.857143
20.628571
def load(self, filepath): """Load the track file""" with open(filepath, 'rb') as fd: num_keys = struct.unpack(">i", fd.read(4))[0] for i in range(num_keys): row, value, kind = struct.unpack('>ifb', fd.read(9)) self.keys.append(TrackKey(row, value, ...
[ "def", "load", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "fd", ":", "num_keys", "=", "struct", ".", "unpack", "(", "\">i\"", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "for"...
45.714286
11.857143
def apool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct an average pooling layer.""" return self._pool("apool", pooling_layers.average_p...
[ "def", "apool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "...
37
15.75
def html(self) -> str: """Generate a random HTML tag with text inside and some attrs set. :return: HTML. :Examples: '<span class="select" id="careers"> Ports are created with the built-in function open_port. </span>' """ tag_name = self.rando...
[ "def", "html", "(", "self", ")", "->", "str", ":", "tag_name", "=", "self", ".", "random", ".", "choice", "(", "list", "(", "HTML_CONTAINER_TAGS", ")", ")", "tag_attributes", "=", "list", "(", "HTML_CONTAINER_TAGS", "[", "tag_name", "]", ")", "# type: igno...
33.37037
20.074074
def tmp_file_path(self): """ :return: :rtype: str """ return os.path.normpath(os.path.join( TMP_DIR, self.filename ))
[ "def", "tmp_file_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "TMP_DIR", ",", "self", ".", "filename", ")", ")" ]
20.111111
14.555556
def mergecn(args): """ %prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another. """ p = OptionParser(mergecn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: ...
[ "def", "mergecn", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mergecn", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", ...
38.703704
15.296296
def run_putgist(filename, user, **kwargs): """Passes user inputs to GetGist() and calls put()""" assume_yes = kwargs.get("yes_to_all") private = kwargs.get("private") getgist = GetGist( user=user, filename=filename, assume_yes=assume_yes, create_private=private, a...
[ "def", "run_putgist", "(", "filename", ",", "user", ",", "*", "*", "kwargs", ")", ":", "assume_yes", "=", "kwargs", ".", "get", "(", "\"yes_to_all\"", ")", "private", "=", "kwargs", ".", "get", "(", "\"private\"", ")", "getgist", "=", "GetGist", "(", "...
29
12.916667
def battery_status_encode(self, id, battery_function, type, temperature, voltages, current_battery, current_consumed, energy_consumed, battery_remaining): ''' Battery information id : Battery ID (uint8_t) battery_function :...
[ "def", "battery_status_encode", "(", "self", ",", "id", ",", "battery_function", ",", "type", ",", "temperature", ",", "voltages", ",", "current_battery", ",", "current_consumed", ",", "energy_consumed", ",", "battery_remaining", ")", ":", "return", "MAVLink_battery...
100.875
76.75
def immediate_postdominators(self, end, target_graph=None): """ Get all immediate postdominators of sub graph from given node upwards. :param str start: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.grap...
[ "def", "immediate_postdominators", "(", "self", ",", "end", ",", "target_graph", "=", "None", ")", ":", "return", "self", ".", "_immediate_dominators", "(", "end", ",", "target_graph", "=", "target_graph", ",", "reverse_graph", "=", "True", ")" ]
49.818182
33.272727
def limit_exceed(to_validate, constraint, violation_cfg): """ Compares 2 values and returns violation message if validated value bigger than constraint :param to_validate: :param constraint: :param violation_cfg: :return: """ if to_validate > constraint: violation_cfg[Check.CFG_K...
[ "def", "limit_exceed", "(", "to_validate", ",", "constraint", ",", "violation_cfg", ")", ":", "if", "to_validate", ">", "constraint", ":", "violation_cfg", "[", "Check", ".", "CFG_KEY_VIOLATION_MSG", "]", "=", "violation_cfg", "[", "Check", ".", "CFG_KEY_VIOLATION...
34.461538
22.615385
def visit_Return(self, node): """ Add edge from all possible callee to current function. Gather all the function call that led to the creation of the returned expression and add an edge to each of this function. When visiting an expression, one returns a list of frozensets. Eac...
[ "def", "visit_Return", "(", "self", ",", "node", ")", ":", "if", "not", "node", ".", "value", ":", "# Yielding function can't return values", "return", "for", "dep_set", "in", "self", ".", "visit", "(", "node", ".", "value", ")", ":", "if", "dep_set", ":",...
40.380952
19.52381
def start_fetching_next_page(self): """ If there are more pages left in the query result, this asynchronously starts fetching the next page. If there are no pages left, :exc:`.QueryExhausted` is raised. Also see :attr:`.has_more_pages`. This should only be called after the fir...
[ "def", "start_fetching_next_page", "(", "self", ")", ":", "if", "not", "self", ".", "_paging_state", ":", "raise", "QueryExhausted", "(", ")", "self", ".", "_make_query_plan", "(", ")", "self", ".", "message", ".", "paging_state", "=", "self", ".", "_paging_...
34.45
17.45
def _root_mean_square_error(y, y_pred, w): """Calculate the root mean square error.""" return np.sqrt(np.average(((y_pred - y) ** 2), weights=w))
[ "def", "_root_mean_square_error", "(", "y", ",", "y_pred", ",", "w", ")", ":", "return", "np", ".", "sqrt", "(", "np", ".", "average", "(", "(", "(", "y_pred", "-", "y", ")", "**", "2", ")", ",", "weights", "=", "w", ")", ")" ]
50.333333
8
def update_iteration_num_suggestions(self, num_suggestions): """Update iteration's num_suggestions.""" iteration_config = self.experiment_group.iteration_config iteration_config.num_suggestions = num_suggestions self._update_config(iteration_config)
[ "def", "update_iteration_num_suggestions", "(", "self", ",", "num_suggestions", ")", ":", "iteration_config", "=", "self", ".", "experiment_group", ".", "iteration_config", "iteration_config", ".", "num_suggestions", "=", "num_suggestions", "self", ".", "_update_config", ...
46.166667
18
def visit_classdef(self, node): """visit an astroid.Class node add this class to the class diagram definition """ anc_level, association_level = self._get_levels() self.extract_classes(node, anc_level, association_level)
[ "def", "visit_classdef", "(", "self", ",", "node", ")", ":", "anc_level", ",", "association_level", "=", "self", ".", "_get_levels", "(", ")", "self", ".", "extract_classes", "(", "node", ",", "anc_level", ",", "association_level", ")" ]
36.428571
14.857143
def storeTopAnnotations(self, service_name, annotations): """ Aggregates methods Parameters: - service_name - annotations """ self.send_storeTopAnnotations(service_name, annotations) self.recv_storeTopAnnotations()
[ "def", "storeTopAnnotations", "(", "self", ",", "service_name", ",", "annotations", ")", ":", "self", ".", "send_storeTopAnnotations", "(", "service_name", ",", "annotations", ")", "self", ".", "recv_storeTopAnnotations", "(", ")" ]
24
16.8
def _inputhook_tk(inputhook_context): """ Inputhook for Tk. Run the Tk eventloop until prompt-toolkit needs to process the next input. """ # Get the current TK application. import _tkinter # Keep this imports inline! from six.moves import tkinter root = tkinter._default_root def wa...
[ "def", "_inputhook_tk", "(", "inputhook_context", ")", ":", "# Get the current TK application.", "import", "_tkinter", "# Keep this imports inline!", "from", "six", ".", "moves", "import", "tkinter", "root", "=", "tkinter", ".", "_default_root", "def", "wait_using_filehan...
32.659574
18.021277
def backend(): """ :return: A unicode string of the backend being used: "openssl", "osx", "win", "winlegacy" """ if _module_values['backend'] is not None: return _module_values['backend'] with _backend_lock: if _module_values['backend'] is not None: retu...
[ "def", "backend", "(", ")", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", ":", "return", "_module_values", "[", "'backend'", "]", "with", "_backend_lock", ":", "if", "_module_values", "[", "'backend'", "]", "is", "not", "None", "...
30
16.307692
def get_levels_and_coordinates_names(self): """ Get the current level of the high level mean plot and the name of the corrisponding site, study, etc. As well as the code for the current coordinate system. Returns ------- (high_level_type,high_level_name,coordinat...
[ "def", "get_levels_and_coordinates_names", "(", "self", ")", ":", "if", "self", ".", "COORDINATE_SYSTEM", "==", "\"geographic\"", ":", "dirtype", "=", "'DA-DIR-GEO'", "elif", "self", ".", "COORDINATE_SYSTEM", "==", "\"tilt-corrected\"", ":", "dirtype", "=", "'DA-DIR...
39
15.137931
def save_waypoints(self, filename): '''save waypoints to a file''' try: #need to remove the leading and trailing quotes in filename self.wploader.save(filename.strip('"')) except Exception as msg: print("Failed to save %s - %s" % (filename, msg)) r...
[ "def", "save_waypoints", "(", "self", ",", "filename", ")", ":", "try", ":", "#need to remove the leading and trailing quotes in filename", "self", ".", "wploader", ".", "save", "(", "filename", ".", "strip", "(", "'\"'", ")", ")", "except", "Exception", "as", "...
43.888889
18.333333
def readlines(self, size=None): """Reads a file into a list of strings. It calls :meth:`readline` until the file is read to the end. It does support the optional `size` argument if the underlaying stream supports it for `readline`. """ last_pos = self._pos resul...
[ "def", "readlines", "(", "self", ",", "size", "=", "None", ")", ":", "last_pos", "=", "self", ".", "_pos", "result", "=", "[", "]", "if", "size", "is", "not", "None", ":", "end", "=", "min", "(", "self", ".", "limit", ",", "last_pos", "+", "size"...
34.190476
13.380952
def annotate_tree_properties(comments): """ iterate through nodes and adds some magic properties to each of them representing opening list of children and closing it """ if not comments: return it = iter(comments) # get the first item, this will fail if no items ! old = next(it...
[ "def", "annotate_tree_properties", "(", "comments", ")", ":", "if", "not", "comments", ":", "return", "it", "=", "iter", "(", "comments", ")", "# get the first item, this will fail if no items !", "old", "=", "next", "(", "it", ")", "# first item starts a new thread",...
26.06383
18.06383
def parse_alert(server_handshake_bytes): """ Parses the handshake for protocol alerts :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None or an 2-element tuple of integers: 0: 1 (warning) or 2 (fatal) 1: The alert ...
[ "def", "parse_alert", "(", "server_handshake_bytes", ")", ":", "for", "record_type", ",", "_", ",", "record_data", "in", "parse_tls_records", "(", "server_handshake_bytes", ")", ":", "if", "record_type", "!=", "b'\\x15'", ":", "continue", "if", "len", "(", "reco...
33.55
20.15
def delete_image(self, name: str) -> None: """ Deletes a Docker image with a given name. Parameters: name: the name of the Docker image. """ logger.debug("deleting Docker image: %s", name) path = "docker/images/{}".format(name) response = self.__api.d...
[ "def", "delete_image", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"deleting Docker image: %s\"", ",", "name", ")", "path", "=", "\"docker/images/{}\"", ".", "format", "(", "name", ")", "response", "=", "sel...
35.222222
14.333333
def submit(self, queue=None, options=[]): """Submits the job either locally or to a remote server if it is defined. Args: queue (int, optional): The number of sub-jobs to run. This argmuent will set the num_jobs attribute of this object. Defaults to None, meaning the value o...
[ "def", "submit", "(", "self", ",", "queue", "=", "None", ",", "options", "=", "[", "]", ")", ":", "if", "not", "self", ".", "executable", ":", "log", ".", "error", "(", "'Job %s was submitted with no executable'", ",", "self", ".", "name", ")", "raise", ...
43.6
28.08