text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def modify_contact(self, contact_id, attrs=None, members=None, tags=None): """ :param contact_id: zimbra id of the targetd contact :param attrs : a dictionary of attributes to set ({key:value,...}) :param members: list of dict representing contacts and operation (+|-|reset) ...
[ "def", "modify_contact", "(", "self", ",", "contact_id", ",", "attrs", "=", "None", ",", "members", "=", "None", ",", "tags", "=", "None", ")", ":", "cn", "=", "{", "}", "if", "tags", ":", "tags", "=", "self", ".", "_return_comma_list", "(", "tags", ...
36.478261
0.002323
def chunker(ensemble_list, ncpu): """ Generate successive chunks of ensemble_list. """ # determine sublist lengths length = int(len(ensemble_list) / ncpu) # generator for i in range(0, len(ensemble_list), length): yield ensemble_list[i:i + length]
[ "def", "chunker", "(", "ensemble_list", ",", "ncpu", ")", ":", "# determine sublist lengths", "length", "=", "int", "(", "len", "(", "ensemble_list", ")", "/", "ncpu", ")", "# generator", "for", "i", "in", "range", "(", "0", ",", "len", "(", "ensemble_list...
24.454545
0.017921
def output_sector_netcdf(self,netcdf_path,out_path,patch_radius,config): """ Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. ...
[ "def", "output_sector_netcdf", "(", "self", ",", "netcdf_path", ",", "out_path", ",", "patch_radius", ",", "config", ")", ":", "nc_data", "=", "self", ".", "load_netcdf_data", "(", "netcdf_path", ",", "patch_radius", ")", "if", "nc_data", "is", "not", "None", ...
49.929134
0.01036
def _get(self, url, method, host): """Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments """ url = unquote(h...
[ "def", "_get", "(", "self", ",", "url", ",", "method", ",", "host", ")", ":", "url", "=", "unquote", "(", "host", "+", "url", ")", "# Check against known static routes", "route", "=", "self", ".", "routes_static", ".", "get", "(", "url", ")", "method_not...
41.254902
0.000929
def add_serie(self, y, x, name=None, extra=None, **kwargs): """ add serie - Series are list of data that will be plotted y {1, 2, 3, 4, 5} / x {1, 2, 3, 4, 5} **Attributes**: * ``name`` - set Serie name * ``x`` - x-axis data * ``y`` - y-axis data ...
[ "def", "add_serie", "(", "self", ",", "y", ",", "x", ",", "name", "=", "None", ",", "extra", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", ":", "name", "=", "\"Serie %d\"", "%", "(", "self", ".", "serie_no", ")", "# For sca...
40.62069
0.002072
def peddy_het_check_plot(self): """plot the het_check scatter plot""" # empty dictionary to add sample names, and dictionary of values data = {} # for each sample, and list in self.peddy_data for s_name, d in self.peddy_data.items(): # check the sample contains the r...
[ "def", "peddy_het_check_plot", "(", "self", ")", ":", "# empty dictionary to add sample names, and dictionary of values", "data", "=", "{", "}", "# for each sample, and list in self.peddy_data", "for", "s_name", ",", "d", "in", "self", ".", "peddy_data", ".", "items", "("...
42.515152
0.012544
def tensors_blocked_by_false(ops): """ Follows a set of ops assuming their value is False and find blocked Switch paths. This is used to prune away parts of the model graph that are only used during the training phase (like dropout, batch norm, etc.). """ blocked = [] def recurse(op): i...
[ "def", "tensors_blocked_by_false", "(", "ops", ")", ":", "blocked", "=", "[", "]", "def", "recurse", "(", "op", ")", ":", "if", "op", ".", "type", "==", "\"Switch\"", ":", "blocked", ".", "append", "(", "op", ".", "outputs", "[", "1", "]", ")", "# ...
34.333333
0.009449
def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True): """ Read all instance elements. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular"> """ for instanceElement in self.root.finda...
[ "def", "readInstances", "(", "self", ",", "makeGlyphs", "=", "True", ",", "makeKerning", "=", "True", ",", "makeInfo", "=", "True", ")", ":", "for", "instanceElement", "in", "self", ".", "root", ".", "findall", "(", "'.instances/instance'", ")", ":", "self...
46.5
0.008439
def cli(env, zone_id, by_record, by_id, data, ttl): """Update DNS record.""" manager = SoftLayer.DNSManager(env.client) zone_id = helpers.resolve_id(manager.resolve_ids, zone_id, name='zone') results = manager.get_records(zone_id, host=by_record) for result in results: if by_id and str(res...
[ "def", "cli", "(", "env", ",", "zone_id", ",", "by_record", ",", "by_id", ",", "data", ",", "ttl", ")", ":", "manager", "=", "SoftLayer", ".", "DNSManager", "(", "env", ".", "client", ")", "zone_id", "=", "helpers", ".", "resolve_id", "(", "manager", ...
36.769231
0.002041
def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELE...
[ "def", "db_list", "(", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "ret", "=", "{", "}", "query", "=", "(", "'SELE...
29.15625
0.001037
def register(self, params, target): """Expect observation with known target""" self._space.register(params, target) self.dispatch(Events.OPTMIZATION_STEP)
[ "def", "register", "(", "self", ",", "params", ",", "target", ")", ":", "self", ".", "_space", ".", "register", "(", "params", ",", "target", ")", "self", ".", "dispatch", "(", "Events", ".", "OPTMIZATION_STEP", ")" ]
43.75
0.011236
def write(self, out): """Used in constructing an outgoing packet""" out.write_short(self.priority) out.write_short(self.weight) out.write_short(self.port) out.write_name(self.server)
[ "def", "write", "(", "self", ",", "out", ")", ":", "out", ".", "write_short", "(", "self", ".", "priority", ")", "out", ".", "write_short", "(", "self", ".", "weight", ")", "out", ".", "write_short", "(", "self", ".", "port", ")", "out", ".", "writ...
36.166667
0.009009
def _remove_child_node(node, context, xast, if_empty=False): '''Remove a child node based on the specified xpath. :param node: lxml element relative to which the xpath will be interpreted :param context: any context required for the xpath (e.g., namespace definitions) :param xast: parsed xpat...
[ "def", "_remove_child_node", "(", "node", ",", "context", ",", "xast", ",", "if_empty", "=", "False", ")", ":", "xpath", "=", "serialize", "(", "xast", ")", "child", "=", "_find_xml_node", "(", "xpath", ",", "node", ",", "context", ")", "if", "child", ...
39.583333
0.011305
def from_total_moment_rate(cls, min_mag, b_val, char_mag, total_moment_rate, bin_width): """ Define Youngs and Coppersmith 1985 MFD by constraing cumulative a value and characteristic rate from total moment rate. The cumulative a value and characteristic ra...
[ "def", "from_total_moment_rate", "(", "cls", ",", "min_mag", ",", "b_val", ",", "char_mag", ",", "total_moment_rate", ",", "bin_width", ")", ":", "beta", "=", "b_val", "*", "numpy", ".", "log", "(", "10", ")", "mu", "=", "char_mag", "+", "DELTA_CHAR", "/...
43.2625
0.000847
def initialize_dictionaries(self, p_set): """ Initialize dictionaries with the textual inputs in the PredictorSet object p_set - PredictorSet object that has had data fed in """ success = False if not (hasattr(p_set, '_type')): error_message = "needs to be an ...
[ "def", "initialize_dictionaries", "(", "self", ",", "p_set", ")", ":", "success", "=", "False", "if", "not", "(", "hasattr", "(", "p_set", ",", "'_type'", ")", ")", ":", "error_message", "=", "\"needs to be an essay set of the train type.\"", "log", ".", "except...
42.857143
0.00815
def do_open(self, http_class, req, **http_conn_args): """Return an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. """ host = req.host if not host: raise URLError('no host given') # wi...
[ "def", "do_open", "(", "self", ",", "http_class", ",", "req", ",", "*", "*", "http_conn_args", ")", ":", "host", "=", "req", ".", "host", "if", "not", "host", ":", "raise", "URLError", "(", "'no host given'", ")", "# will parse host:port", "h", "=", "htt...
39.983607
0.001601
def prime_ge(n): """ PRIME_GE returns the smallest prime greater than or equal to N. Example: +-----+--------- | N | PRIME_GE +-----+--------- | -10 | 2 | 1 | 2 | 2 | 2 | 3 | 3 | 4 | 5 | 5 | 5 ...
[ "def", "prime_ge", "(", "n", ")", ":", "p", "=", "max", "(", "np", ".", "ceil", "(", "n", ")", ",", "2", ")", "while", "not", "is_prime", "(", "p", ")", ":", "p", "+=", "1", "return", "p" ]
20.967742
0.001471
def populate(self, usr = None, itemID = None): """ Attempts to populate an item's information with it's ID, returns result Note that the item id must already be set or otherwise supplied and that the item must exist in the associated user's inventory. Parameters: ...
[ "def", "populate", "(", "self", ",", "usr", "=", "None", ",", "itemID", "=", "None", ")", ":", "if", "not", "self", ".", "id", "and", "not", "itemID", ":", "return", "False", "if", "not", "self", ".", "usr", "and", "not", "user", ":", "return", "...
37.196078
0.015922
def Matsumoto_1977(mp, rhop, dp, rhog, D, Vterminal=1): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ and reproduced in [2]_, [3]_, and [4]_. First equation is used if third equation yeilds d* higher than dp. Otherwise, use equation 2. .. math:: \m...
[ "def", "Matsumoto_1977", "(", "mp", ",", "rhop", ",", "dp", ",", "rhog", ",", "D", ",", "Vterminal", "=", "1", ")", ":", "limit", "=", "1.39", "*", "D", "*", "(", "rhop", "/", "rhog", ")", "**", "-", "0.74", "A", "=", "pi", "/", "4", "*", "...
33.863636
0.001304
def number_of_attributes(self): """int: number of attributes.""" if not self._is_parsed: self._Parse() self._is_parsed = True return len(self._attributes)
[ "def", "number_of_attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_is_parsed", ":", "self", ".", "_Parse", "(", ")", "self", ".", "_is_parsed", "=", "True", "return", "len", "(", "self", ".", "_attributes", ")" ]
24.714286
0.01676
def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source()
[ "def", "cleanup_files", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Cleaning up...'", ")", "with", "indent_log", "(", ")", ":", "for", "req", "in", "self", ".", "reqs_to_cleanup", ":", "req", ".", "remove_temporary_source", "(", ")" ]
36.833333
0.00885
def __init(self, project, path, force, init_languages): status = {} """ REFACTOR status to project init result ENUM jelenleg ha a project init False, akkor torlunk minden adatot a projectrol de van egy atmenet, mikor csak a lang init nem sikerult erre valo jelenleg a stat...
[ "def", "__init", "(", "self", ",", "project", ",", "path", ",", "force", ",", "init_languages", ")", ":", "status", "=", "{", "}", "project", ".", "init", "(", "path", ",", "status", ",", "force", ",", "init_languages", "=", "init_languages", ")", "fai...
34.294118
0.008347
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': """Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted """ return ops.insert(s...
[ "def", "insert", "(", "self", ",", "start_time", ":", "int", ",", "schedule", ":", "ScheduleComponent", ")", "->", "'ScheduleComponent'", ":", "return", "ops", ".", "insert", "(", "self", ",", "start_time", ",", "schedule", ")" ]
42.375
0.011561
def _sanitize_value(value): '''Internal helper for converting pythonic values to configuration file values''' # dump dict into compated if isinstance(value, dict): new_value = [] new_value.append('(') for k, v in value.items(): new_value.append(k) new_value.ap...
[ "def", "_sanitize_value", "(", "value", ")", ":", "# dump dict into compated", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "new_value", "=", "[", "]", "new_value", ".", "append", "(", "'('", ")", "for", "k", ",", "v", "in", "value", ".", "...
38.419355
0.002457
def loadCookies(domain): """ Loads all Neopets cookie stored by Google Chrome into a CookieJar Determines the application data path for Google Chrome, finds the cookie database file, queries it for cookies with domain neopets.com, and proceeds to build a CookieJar with the assoc...
[ "def", "loadCookies", "(", "domain", ")", ":", "try", ":", "cj", "=", "requests", ".", "cookies", ".", "RequestsCookieJar", "(", ")", "path", "=", "ChromeCookies", ".", "_getPath", "(", ")", "results", "=", "[", "]", "with", "sqlite", ".", "connect", "...
42.55
0.008616
def _handle_delete(self, method, remainder, request=None): ''' Routes ``DELETE`` actions to the appropriate controller. ''' if request is None: self._raise_method_deprecation_warning(self._handle_delete) if remainder: match = self._handle_custom_action(me...
[ "def", "_handle_delete", "(", "self", ",", "method", ",", "remainder", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "self", ".", "_raise_method_deprecation_warning", "(", "self", ".", "_handle_delete", ")", "if", "remainder", ":...
38.3125
0.001591
def accounts(self): """ A list of structures describing apps and pages owned by this user. """ response = self.graph.get('%s/accounts' % self.id) accounts = [] for item in response['data']: account = Structure( page = Page( ...
[ "def", "accounts", "(", "self", ")", ":", "response", "=", "self", ".", "graph", ".", "get", "(", "'%s/accounts'", "%", "self", ".", "id", ")", "accounts", "=", "[", "]", "for", "item", "in", "response", "[", "'data'", "]", ":", "account", "=", "St...
28.52381
0.022617
def view(self, vleaf, fpath=None, cleanup=True, format=None): """View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanu...
[ "def", "view", "(", "self", ",", "vleaf", ",", "fpath", "=", "None", ",", "cleanup", "=", "True", ",", "format", "=", "None", ")", ":", "graph", "=", "self", ".", "create_graphviz_digraph", "(", "vleaf", ",", "format", "=", "format", ")", "graph", "....
46.615385
0.009709
def pack(window, sizer, expand=1.1): "simple wxPython pack function" tsize = window.GetSize() msize = window.GetMinSize() window.SetSizer(sizer) sizer.Fit(window) nsize = (10*int(expand*(max(msize[0], tsize[0])/10)), 10*int(expand*(max(msize[1], tsize[1])/10.))) window.SetSize...
[ "def", "pack", "(", "window", ",", "sizer", ",", "expand", "=", "1.1", ")", ":", "tsize", "=", "window", ".", "GetSize", "(", ")", "msize", "=", "window", ".", "GetMinSize", "(", ")", "window", ".", "SetSizer", "(", "sizer", ")", "sizer", ".", "Fit...
35.444444
0.009174
def MakeExpandedTrace(frame_records): """Return a list of text lines for the given list of frame records.""" dump = [] for (frame_obj, filename, line_num, fun_name, context_lines, context_index) in frame_records: dump.append('File "%s", line %d, in %s\n' % (filename, line_num, ...
[ "def", "MakeExpandedTrace", "(", "frame_records", ")", ":", "dump", "=", "[", "]", "for", "(", "frame_obj", ",", "filename", ",", "line_num", ",", "fun_name", ",", "context_lines", ",", "context_index", ")", "in", "frame_records", ":", "dump", ".", "append",...
41.571429
0.013434
def create( name, create_file, open_file, remove_file, create_directory, list_directory, remove_empty_directory, temporary_directory, stat, lstat, link, readlink, realpath=_realpath, remove=_recursive_remove, ): """ Create a new kind of filesystem. ...
[ "def", "create", "(", "name", ",", "create_file", ",", "open_file", ",", "remove_file", ",", "create_directory", ",", "list_directory", ",", "remove_empty_directory", ",", "temporary_directory", ",", "stat", ",", "lstat", ",", "link", ",", "readlink", ",", "real...
19.129032
0.000802
def register_backends(vars): """Register backends for use with models. `vars` should be a dictionary of variables obtained from e.g. `locals()`, at least some of which are Backend classes, e.g. from imports. """ new_backends = {x.replace('Backend', ''): cls for x, cls in vars.it...
[ "def", "register_backends", "(", "vars", ")", ":", "new_backends", "=", "{", "x", ".", "replace", "(", "'Backend'", ",", "''", ")", ":", "cls", "for", "x", ",", "cls", "in", "vars", ".", "items", "(", ")", "if", "inspect", ".", "isclass", "(", "cls...
43.4
0.002257
def write_pickles (self, objs): """*objs* must be iterable. Write each of its values to this path in sequence using :mod:`cPickle`. """ try: import cPickle as pickle except ImportError: import pickle with self.open (mode='wb') as f: f...
[ "def", "write_pickles", "(", "self", ",", "objs", ")", ":", "try", ":", "import", "cPickle", "as", "pickle", "except", "ImportError", ":", "import", "pickle", "with", "self", ".", "open", "(", "mode", "=", "'wb'", ")", "as", "f", ":", "for", "obj", "...
27.692308
0.016129
def _distances(value_domain, distance_metric, n_v): """Distances of the different possible values. Parameters ---------- value_domain : array_like, with shape (V,) Possible values V the units can take. If the level of measurement is not nominal, it must be ordered. distance_metric ...
[ "def", "_distances", "(", "value_domain", ",", "distance_metric", ",", "n_v", ")", ":", "return", "np", ".", "array", "(", "[", "[", "distance_metric", "(", "v1", ",", "v2", ",", "i1", "=", "i1", ",", "i2", "=", "i2", ",", "n_v", "=", "n_v", ")", ...
33.173913
0.001274
def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables. If `start` is a callable, start the slice after the first time start(item) == True. If `stop` is a callable, stop the slice ...
[ "def", "iterslice", "(", "iterable", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "step", "=", "1", ")", ":", "# type: (Iterable[T], int, int, int) -> Iterable[T]", "if", "step", "<", "0", ":", "raise", "ValueError", "(", "\"The step can not be negativ...
32.62069
0.001027
def _replace_wildcards(self, name, run_idx=None): """Replaces the $ wildcards and returns True/False in case it was replaced""" if self._root_instance.f_is_wildcard(name): return True, self._root_instance.f_wildcard(name, run_idx) else: return False, name
[ "def", "_replace_wildcards", "(", "self", ",", "name", ",", "run_idx", "=", "None", ")", ":", "if", "self", ".", "_root_instance", ".", "f_is_wildcard", "(", "name", ")", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", ...
49.666667
0.009901
def stop(self) -> None: """ Stop the :class:`~lahja.endpoint.Endpoint` from receiving further events. """ if not self._running: return self._running = False self._receiving_queue.put_nowait((TRANSPARENT_EVENT, None)) self._internal_queue.put_nowait((T...
[ "def", "stop", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_running", ":", "return", "self", ".", "_running", "=", "False", "self", ".", "_receiving_queue", ".", "put_nowait", "(", "(", "TRANSPARENT_EVENT", ",", "None", ")", ")", "s...
33.5
0.008721
def ekfind(query, lenout=_default_len_out): """ Find E-kernel data that satisfy a set of constraints. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekfind_c.html :param query: Query specifying data to be found. :type query: str :param lenout: Declared length of output error message s...
[ "def", "ekfind", "(", "query", ",", "lenout", "=", "_default_len_out", ")", ":", "query", "=", "stypes", ".", "stringToCharP", "(", "query", ")", "lenout", "=", "ctypes", ".", "c_int", "(", "lenout", ")", "nmrows", "=", "ctypes", ".", "c_int", "(", ")"...
35.291667
0.001149
def gen_centers(self): """Set the centre of the Gaussian basis functions be spaced evenly throughout run time""" c = np.linspace(0, 2*np.pi, self.bfs+1) c = c[0:-1] self.c = c
[ "def", "gen_centers", "(", "self", ")", ":", "c", "=", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "self", ".", "bfs", "+", "1", ")", "c", "=", "c", "[", "0", ":", "-", "1", "]", "self", ".", "c", "=", "c" ]
30.142857
0.013825
def _raise_for_status(response): """ make sure that only crate.exceptions are raised that are defined in the DB-API specification """ message = '' if 400 <= response.status < 500: message = '%s Client Error: %s' % (response.status, response.reason) elif 500 <= response.status < 600: ...
[ "def", "_raise_for_status", "(", "response", ")", ":", "message", "=", "''", "if", "400", "<=", "response", ".", "status", "<", "500", ":", "message", "=", "'%s Client Error: %s'", "%", "(", "response", ".", "status", ",", "response", ".", "reason", ")", ...
45.115385
0.000835
def setup_argparse(self, argument_parser): """Set up custom arguments needed for this profile.""" import glob import logging import argparse def get_fonts(pattern): fonts_to_check = [] # use glob.glob to accept *.ufo for fullpath in glob.glob(pattern): fullpath_absolute ...
[ "def", "setup_argparse", "(", "self", ",", "argument_parser", ")", ":", "import", "glob", "import", "logging", "import", "argparse", "def", "get_fonts", "(", "pattern", ")", ":", "fonts_to_check", "=", "[", "]", "# use glob.glob to accept *.ufo", "for", "fullpath"...
30.487179
0.00815
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are bot...
[ "def", "plot", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plo...
39.177419
0.00241
def get_console_width(): """Return width of available window area. Autodetection works for Windows and POSIX platforms. Returns 80 for others Code from http://bitbucket.org/techtonik/python-pager """ if os.name == 'nt': STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 S...
[ "def", "get_console_width", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "STD_INPUT_HANDLE", "=", "-", "10", "STD_OUTPUT_HANDLE", "=", "-", "11", "STD_ERROR_HANDLE", "=", "-", "12", "# get console handle", "from", "ctypes", "import", "windll", ...
32.578947
0.000523
def SelectArtifacts(cls, os_name=None, cpe=None, labels=None, restrict_checks=None): """Takes targeting info, identifies artifacts to fetch. Args: os_name: 0+ OS names. cpe: 0+ CPE identifiers. labels: 0+ ...
[ "def", "SelectArtifacts", "(", "cls", ",", "os_name", "=", "None", ",", "cpe", "=", "None", ",", "labels", "=", "None", ",", "restrict_checks", "=", "None", ")", ":", "results", "=", "set", "(", ")", "for", "condition", "in", "cls", ".", "Conditions", ...
32.208333
0.01005
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
[ "def", "aes_b64_encrypt", "(", "value", ",", "secret", ",", "block_size", "=", "AES", ".", "block_size", ")", ":", "# iv = randstr(block_size * 2, rng=random)", "iv", "=", "randstr", "(", "block_size", "*", "2", ")", "cipher", "=", "AES", ".", "new", "(", "s...
41.045455
0.001082
def _get_available(recommended=False, restart=False): ''' Utility function to get all available update packages. Sample return date: { 'updatename': '1.2.3-45', ... } ''' cmd = ['softwareupdate', '--list'] out = salt.utils.mac_utils.execute_return_result(cmd) # rexp parses lines that l...
[ "def", "_get_available", "(", "recommended", "=", "False", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", "'softwareupdate'", ",", "'--list'", "]", "out", "=", "salt", ".", "utils", ".", "mac_utils", ".", "execute_return_result", "(", "cmd", ")",...
30.692308
0.001214
def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dicti...
[ "def", "convdicts", "(", ")", ":", "pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'data'", ",", "'convdict.npz'", ")", "npz", "=", "np", ".", "load", "(", "pth", ")", "cdd", "=", ...
24.466667
0.001311
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous))
[ "def", "no_sleep", "(", ")", ":", "mode", "=", "power", ".", "ES", ".", "continuous", "|", "power", ".", "ES", ".", "system_required", "handle_nonzero_success", "(", "power", ".", "SetThreadExecutionState", "(", "mode", ")", ")", "try", ":", "yield", "fina...
29
0.033445
def write_index(data, group, append): """Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete...
[ "def", "write_index", "(", "data", ",", "group", ",", "append", ")", ":", "# build the index from data", "nitems", "=", "group", "[", "'items'", "]", ".", "shape", "[", "0", "]", "if", "'items'", "in", "group", "else", "0", "last_index", "=", "group", "[...
36.846154
0.001017
def ConvCnstrMODMaskDcplOptions(opt=None, method='cns'): """A wrapper function that dynamically defines a class derived from the Options class associated with one of the implementations of the Convolutional Constrained MOD with Mask Decoupling problem, and returns an object instantiated with the provid...
[ "def", "ConvCnstrMODMaskDcplOptions", "(", "opt", "=", "None", ",", "method", "=", "'cns'", ")", ":", "# Assign base class depending on method selection argument", "if", "method", "==", "'ism'", ":", "base", "=", "ConvCnstrMODMaskDcpl_IterSM", ".", "Options", "elif", ...
45.454545
0.000653
def wait_for_element_visible(driver, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Searches for the specified element by the given selector. Returns the element object if the element is present and visible on the page. Raises an exception if the element ...
[ "def", "wait_for_element_visible", "(", "driver", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", ")", ":", "element", "=", "None", "start_ms", "=", "time", ".", "time", "(", ")", "*", "1...
35.840909
0.000617
def select_ocv_points(cellpydata, cycles=None, selection_method="martin", number_of_points=5, interval=10, relative_voltage=False, report_times=False, direction=None): """Select points from the ocvrlx step...
[ "def", "select_ocv_points", "(", "cellpydata", ",", "cycles", "=", "None", ",", "selection_method", "=", "\"martin\"", ",", "number_of_points", "=", "5", ",", "interval", "=", "10", ",", "relative_voltage", "=", "False", ",", "report_times", "=", "False", ",",...
32.402235
0.000167
def clone_repo(session, urls): """ Clones the given repos in temp directories :param session: requests Session instance :param urls: list, str URLs :return: tuple, (str -> directory, str -> URL) """ repos = [] for url in urls: dir = mkdtemp() call = ["git", "clone", url, ...
[ "def", "clone_repo", "(", "session", ",", "urls", ")", ":", "repos", "=", "[", "]", "for", "url", "in", "urls", ":", "dir", "=", "mkdtemp", "(", ")", "call", "=", "[", "\"git\"", ",", "\"clone\"", ",", "url", ",", "dir", "]", "subprocess", ".", "...
27.928571
0.002475
async def find( self, *, types=None, data=None, countries=None, post=False, strict=False, dnsbl=None, limit=0, **kwargs ): """Gather and check proxies from providers or from a passed data. :ref:`Example of usage <proxyb...
[ "async", "def", "find", "(", "self", ",", "*", ",", "types", "=", "None", ",", "data", "=", "None", ",", "countries", "=", "None", ",", "post", "=", "False", ",", "strict", "=", "False", ",", "dnsbl", "=", "None", ",", "limit", "=", "0", ",", "...
35.013333
0.001111
def authorize_client_credentials( self, client_id, client_secret=None, scope="private_agent" ): """Authorize to platform with client credentials This should be used if you posses client_id/client_secret pair generated by platform. """ self.auth_data = { "...
[ "def", "authorize_client_credentials", "(", "self", ",", "client_id", ",", "client_secret", "=", "None", ",", "scope", "=", "\"private_agent\"", ")", ":", "self", ".", "auth_data", "=", "{", "\"grant_type\"", ":", "\"client_credentials\"", ",", "\"scope\"", ":", ...
30.625
0.009901
def url_change_check(f): """ View method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @ro...
[ "def", "url_change_check", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "==", "'GET'", "and", "self", ".", "obj", "is", "not",...
39.34375
0.002326
def parse_basic_metric_options(config_obj, section): """ Parse basic options from metric sections of the config :param config_obj: ConfigParser object :param section: Section name :return: all the parsed options """ infile = {} aggr_hosts = None aggr_metrics = None ts_start = None ts_end = None ...
[ "def", "parse_basic_metric_options", "(", "config_obj", ",", "section", ")", ":", "infile", "=", "{", "}", "aggr_hosts", "=", "None", "aggr_metrics", "=", "None", "ts_start", "=", "None", "ts_end", "=", "None", "precision", "=", "None", "hostname", "=", "\"l...
44.677966
0.014848
async def create(cls, device='/dev/ttyUSB0', host=None, username=None, password=None, port=25010, hub_version=2, auto_reconnect=True, loop=None, workdir=None, poll_devices=True, load_aldb=True): """Create a connection to a specific device. ...
[ "async", "def", "create", "(", "cls", ",", "device", "=", "'/dev/ttyUSB0'", ",", "host", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "port", "=", "25010", ",", "hub_version", "=", "2", ",", "auto_reconnect", "=", "True...
35.827586
0.002342
def parse_format_specifier(specification): """ Parse the given format specification and return a dictionary containing relevant values. """ m = _parse_format_specifier_regex.match(specification) if m is None: raise ValueError( "Invalid format specifier: {!r}".format(specific...
[ "def", "parse_format_specifier", "(", "specification", ")", ":", "m", "=", "_parse_format_specifier_regex", ".", "match", "(", "specification", ")", "if", "m", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid format specifier: {!r}\"", ".", "format", "(", ...
32.16
0.000604
def p_width(self, p): 'width : LBRACKET expression COLON expression RBRACKET' p[0] = Width(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_width", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Width", "(", "p", "[", "2", "]", ",", "p", "[", "4", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p...
43
0.011429
def list_clusters(call=None): ''' Returns a list of clusters in OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_clusters opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_clusters function must...
[ "def", "list_clusters", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_clusters function must be called with -f or --function.'", ")", "server", ",", "user", ",", "password", "=", "_get_xml_rpc"...
24.192308
0.001529
def _convert_metadata(data): """ Convert metadata from WA-KAT to Dublin core dictionary like structure, which may be easily converted to xml using :mod:`xmltodict` module. Args: data (dict): Nested WA-KAT data. See tests for example. Returns: dict: Dict in dublin core format. "...
[ "def", "_convert_metadata", "(", "data", ")", ":", "def", "compose", "(", "val", ",", "arguments", "=", "None", ")", ":", "\"\"\"\n If not val, return None.\n\n If not arguments, return just val.\n\n Otherwise, map val into `arguments` dict under the ``#text`` ke...
31.058252
0.000303
def suggest(self, utility_function): """Most promissing point to probe next""" if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) # Sklearn's GP throws a large number of warnings at times, but # we don't really need to see them here. ...
[ "def", "suggest", "(", "self", ",", "utility_function", ")", ":", "if", "len", "(", "self", ".", "_space", ")", "==", "0", ":", "return", "self", ".", "_space", ".", "array_to_params", "(", "self", ".", "_space", ".", "random_sample", "(", ")", ")", ...
37.619048
0.002469
async def load(self, turn_context: TurnContext, force: bool = False) -> None: """ Reads in the current state object and caches it in the context object for this turm. :param turn_context: The context object for this turn. :param force: Optional. True to bypass the cache. """ ...
[ "async", "def", "load", "(", "self", ",", "turn_context", ":", "TurnContext", ",", "force", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "turn_context", "==", "None", ":", "raise", "TypeError", "(", "'BotState.load(): turn_context cannot be None.'", ...
51.0625
0.009615
def status(self): """ Get the status of Alerting Service :return: Status object """ orig_dict = self._get(self._service_url('status')) orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version') orig_dict['built_from_git_sha1'] = orig_dict.pop('...
[ "def", "status", "(", "self", ")", ":", "orig_dict", "=", "self", ".", "_get", "(", "self", ".", "_service_url", "(", "'status'", ")", ")", "orig_dict", "[", "'implementation_version'", "]", "=", "orig_dict", ".", "pop", "(", "'Implementation-Version'", ")",...
36.5
0.008021
def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not...
[ "def", "_optimize_providers", "(", "self", ",", "providers", ")", ":", "new_providers", "=", "{", "}", "provider_by_driver", "=", "{", "}", "for", "alias", ",", "driver", "in", "six", ".", "iteritems", "(", "providers", ")", ":", "for", "name", ",", "dat...
38.363636
0.002311
def order_edges(edges): r"""Return an ordered traversal of the edges of a two-dimensional polygon. Parameters ---------- edges: (2, N) ndarray List of unordered line segments, where each line segment is represented by two unique vertex codes. Returns ------- ordered...
[ "def", "order_edges", "(", "edges", ")", ":", "edge", "=", "edges", "[", "0", "]", "edges", "=", "edges", "[", "1", ":", "]", "ordered_edges", "=", "[", "edge", "]", "num_max", "=", "len", "(", "edges", ")", "while", "len", "(", "edges", ")", ">"...
22.057143
0.001241
def visit_Str(self, node): """ Parse variable names in format strings: '%(my_var)s' % locals() '{my_var}'.format(**locals()) """ # Old format strings. self.used_names |= set(re.findall(r'\%\((\w+)\)', node.s)) def is_identifier(s): return bo...
[ "def", "visit_Str", "(", "self", ",", "node", ")", ":", "# Old format strings.", "self", ".", "used_names", "|=", "set", "(", "re", ".", "findall", "(", "r'\\%\\((\\w+)\\)'", ",", "node", ".", "s", ")", ")", "def", "is_identifier", "(", "s", ")", ":", ...
33.21875
0.001828
def transform_entries(self, entries, terminal_compositions): """ Method to transform all entries to the composition coordinate in the terminal compositions. If the entry does not fall within the space defined by the terminal compositions, they are excluded. For example, Li3PO4 is...
[ "def", "transform_entries", "(", "self", ",", "entries", ",", "terminal_compositions", ")", ":", "new_entries", "=", "[", "]", "if", "self", ".", "normalize_terminals", ":", "fractional_comp", "=", "[", "c", ".", "fractional_composition", "for", "c", "in", "te...
46.191489
0.000902
def _get_deltas(event): """Get the changes from the appkit event.""" delta_x = round(event.deltaX()) delta_y = round(event.deltaY()) delta_z = round(event.deltaZ()) return delta_x, delta_y, delta_z
[ "def", "_get_deltas", "(", "event", ")", ":", "delta_x", "=", "round", "(", "event", ".", "deltaX", "(", ")", ")", "delta_y", "=", "round", "(", "event", ".", "deltaY", "(", ")", ")", "delta_z", "=", "round", "(", "event", ".", "deltaZ", "(", ")", ...
38.666667
0.008439
def _request_exc_message(exc): """ Return a reasonable exception message from a :exc:`request.exceptions.RequestException` exception. The approach is to dig deep to the original reason, if the original exception is present, skipping irrelevant exceptions such as `urllib3.exceptions.MaxRetryErro...
[ "def", "_request_exc_message", "(", "exc", ")", ":", "if", "exc", ".", "args", ":", "if", "isinstance", "(", "exc", ".", "args", "[", "0", "]", ",", "Exception", ")", ":", "org_exc", "=", "exc", ".", "args", "[", "0", "]", "if", "isinstance", "(", ...
35.028571
0.000794
def file_exists( pathname ): """checks that a given file exists""" result = 1 try: file = open( pathname, "r" ) file.close() except: result = None sys.stderr.write( pathname + " couldn't be accessed\n" ) return result
[ "def", "file_exists", "(", "pathname", ")", ":", "result", "=", "1", "try", ":", "file", "=", "open", "(", "pathname", ",", "\"r\"", ")", "file", ".", "close", "(", ")", "except", ":", "result", "=", "None", "sys", ".", "stderr", ".", "write", "(",...
23.727273
0.03321
def register(self): """send the registration_request""" self.log.info("Registering with controller at %s"%self.url) ctx = self.context connect,maybe_tunnel = self.init_connector() reg = ctx.socket(zmq.DEALER) reg.setsockopt(zmq.IDENTITY, self.bident) connect(reg,...
[ "def", "register", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Registering with controller at %s\"", "%", "self", ".", "url", ")", "ctx", "=", "self", ".", "context", "connect", ",", "maybe_tunnel", "=", "self", ".", "init_connector", "...
42.3125
0.013006
def TOEPLITZ(T0, TC, TR, Z): """solve the general toeplitz linear equations Solve TX=Z :param T0: zero lag value :param TC: r1 to rN :param TR: r1 to rN returns X requires 3M^2+M operations instead of M^3 with gaussian elimination .. warning:: not used right now """ ...
[ "def", "TOEPLITZ", "(", "T0", ",", "TC", ",", "TR", ",", "Z", ")", ":", "assert", "len", "(", "TC", ")", ">", "0", "assert", "len", "(", "TC", ")", "==", "len", "(", "TR", ")", "M", "=", "len", "(", "TC", ")", "X", "=", "numpy", ".", "zer...
26.901639
0.010582
def from_pure(cls, z): """ Creates a pure composition. Args: z (int): atomic number """ return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
[ "def", "from_pure", "(", "cls", ",", "z", ")", ":", "return", "cls", "(", "cls", ".", "_key", ",", "{", "z", ":", "1.0", "}", ",", "{", "z", ":", "1.0", "}", ",", "pyxray", ".", "element_symbol", "(", "z", ")", ")" ]
25
0.009662
def get_api( profile=None, config_file=None, requirements=None): ''' Generate a datafs.DataAPI object from a config profile ``get_api`` generates a DataAPI object based on a pre-configured datafs profile specified in your datafs config file. To create a datafs config fi...
[ "def", "get_api", "(", "profile", "=", "None", ",", "config_file", "=", "None", ",", "requirements", "=", "None", ")", ":", "config", "=", "ConfigFile", "(", "config_file", "=", "config_file", ")", "config", ".", "read_config", "(", ")", "if", "profile", ...
29.954198
0.000247
def importaccount(ctx, account, role): """ Import an account using an account password """ from peerplaysbase.account import PasswordKey password = click.prompt("Account Passphrase", hide_input=True) account = Account(account, peerplays_instance=ctx.peerplays) imported = False if role == "...
[ "def", "importaccount", "(", "ctx", ",", "account", ",", "role", ")", ":", "from", "peerplaysbase", ".", "account", "import", "PasswordKey", "password", "=", "click", ".", "prompt", "(", "\"Account Passphrase\"", ",", "hide_input", "=", "True", ")", "account",...
40.477273
0.001645
def finalise(self, filename, totalChunks, status): """ Completes the upload which means converting to a single 1kHz sample rate file output file. :param filename: :param totalChunks: :param status: :return: """ def getChunkIdx(x): try: ...
[ "def", "finalise", "(", "self", ",", "filename", ",", "totalChunks", ",", "status", ")", ":", "def", "getChunkIdx", "(", "x", ")", ":", "try", ":", "return", "int", "(", "x", ".", "suffix", "[", "1", ":", "]", ")", "except", "ValueError", ":", "ret...
40.517241
0.008313
def run(self): """Starts the thread.""" resp = _wait_until(obj=self.obj, att=self.att, desired=self.desired, callback=None, interval=self.interval, attempts=self.attempts, verbose=False, verbose_atts=None) self.callback(resp)
[ "def", "run", "(", "self", ")", ":", "resp", "=", "_wait_until", "(", "obj", "=", "self", ".", "obj", ",", "att", "=", "self", ".", "att", ",", "desired", "=", "self", ".", "desired", ",", "callback", "=", "None", ",", "interval", "=", "self", "....
41.571429
0.016835
def get_ip_address(): """Simple utility to get host IP address.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] except socket_error as sockerr: if sockerr.errno != errno.ENETUNREACH: raise sockerr ip_address = socket...
[ "def", "get_ip_address", "(", ")", ":", "try", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "s", ".", "connect", "(", "(", "\"8.8.8.8\"", ",", "80", ")", ")", "ip_address", "=", "s", ...
27.5
0.017588
def get_api_date(self): ''' Figure out the date to use for API requests. Assumes yesterday's date if between midnight and 10am Eastern time. Override this function in a subclass to change how the API date is calculated. ''' # NOTE: If you are writing your own function to ...
[ "def", "get_api_date", "(", "self", ")", ":", "# NOTE: If you are writing your own function to get the date, make sure", "# to include the first if block below to allow for the ``date``", "# parameter to hard-code a date.", "api_date", "=", "None", "if", "self", ".", "date", "is", ...
47.96
0.001635
def used_in_func(statement: str, filename: str = '<string>', mode: str = 'exec'): '''Parse a Python statement and analyze the symbols used. The result will be used to determine what variables a step depends upon.''' try: return get_used_in_func(ast.parse(statement, filename, mode)) ...
[ "def", "used_in_func", "(", "statement", ":", "str", ",", "filename", ":", "str", "=", "'<string>'", ",", "mode", ":", "str", "=", "'exec'", ")", ":", "try", ":", "return", "get_used_in_func", "(", "ast", ".", "parse", "(", "statement", ",", "filename", ...
51.625
0.002381
def _JsonDecodeDict(self, data): """Json object decode hook that automatically converts unicode objects.""" rv = {} for key, value in data.iteritems(): if isinstance(key, unicode): key = self._TryStr(key) if isinstance(value, unicode): value = self._TryStr(value) elif isins...
[ "def", "_JsonDecodeDict", "(", "self", ",", "data", ")", ":", "rv", "=", "{", "}", "for", "key", ",", "value", "in", "data", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "key", ",", "unicode", ")", ":", "key", "=", "self", ".", "_Try...
34.066667
0.013333
def _init_jupyter(run): """Asks for user input to configure the machine if it isn't already and creates a new run. Log pushing and system stats don't start until `wandb.monitor()` is called. """ from wandb import jupyter # TODO: Should we log to jupyter? # global logging had to be disabled becau...
[ "def", "_init_jupyter", "(", "run", ")", ":", "from", "wandb", "import", "jupyter", "# TODO: Should we log to jupyter?", "# global logging had to be disabled because it set the level to debug", "# I also disabled run logging because we're rairly using it.", "# try_to_set_up_global_logging(...
38.906977
0.002332
def volume_detach(name, profile=None, timeout=300, **kwargs): ''' Attach a block storage volume name Name of the new volume to attach server_name Name of the server to detach from profile Profile to build on CLI Example: .. code-block:: bash salt '*' nov...
[ "def", "volume_detach", "(", "name", ",", "profile", "=", "None", ",", "timeout", "=", "300", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "_auth", "(", "profile", ",", "*", "*", "kwargs", ")", "return", "conn", ".", "volume_detach", "(", "name", ...
17.96
0.002114
def promille_to_gramm(bac, age, weight, height, sex): """Return the amount of alcohol (in gramm) for a person with the given body stats and blood alcohol content (per mill) """ bw = calculate_bw(age, weight, height, sex) return (bac * (PB * bw)) / W
[ "def", "promille_to_gramm", "(", "bac", ",", "age", ",", "weight", ",", "height", ",", "sex", ")", ":", "bw", "=", "calculate_bw", "(", "age", ",", "weight", ",", "height", ",", "sex", ")", "return", "(", "bac", "*", "(", "PB", "*", "bw", ")", ")...
42.833333
0.015267
def tableMaker(inputLabel, outputLabels, port, _E=elementMaker): """ Construct an HTML table to label a state transition. """ colspan = {} if outputLabels: colspan['colspan'] = str(len(outputLabels)) inputLabelCell = _E("td", _E("font", ...
[ "def", "tableMaker", "(", "inputLabel", ",", "outputLabels", ",", "port", ",", "_E", "=", "elementMaker", ")", ":", "colspan", "=", "{", "}", "if", "outputLabels", ":", "colspan", "[", "'colspan'", "]", "=", "str", "(", "len", "(", "outputLabels", ")", ...
29.866667
0.001081
def debug_sphere_out(self, p: Union[Unit, Point2, Point3], r: Union[int, float], color=None): """ Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'. """ self._debug_spheres.append( debug_pb.DebugSphere(p=self.to_debug_point(p), r=r, color=self.to_de...
[ "def", "debug_sphere_out", "(", "self", ",", "p", ":", "Union", "[", "Unit", ",", "Point2", ",", "Point3", "]", ",", "r", ":", "Union", "[", "int", ",", "float", "]", ",", "color", "=", "None", ")", ":", "self", ".", "_debug_spheres", ".", "append"...
68.6
0.014409
def get(self, url, headers=None, params=None, stream=False, timeout=None): """GET request. :param str url: Request url :param dict headers: (optional) Request headers :param dict params: (optional) Request query parameter :param bool stream: (optional) get content as stream ...
[ "def", "get", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "params", "=", "None", ",", "stream", "=", "False", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "timeout", "respons...
39.913043
0.002128
def CMOVG(cpu, dest, src): """ Conditional move - Greater. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param...
[ "def", "CMOVG", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "Operators", ".", "AND", "(", "cpu", ".", "ZF", "==", "0", ",", "cpu", ".", "SF", "==", "cpu", ...
38.538462
0.009747
def load(self): """Load the minimum needs. If the minimum needs defined in QSettings use it, if not, get the most relevant available minimum needs (based on QGIS locale). The last thing to do is to just use the default minimum needs. """ self.minimum_needs = self.setting...
[ "def", "load", "(", "self", ")", ":", "self", ".", "minimum_needs", "=", "self", ".", "settings", ".", "value", "(", "'MinimumNeeds'", ")", "if", "not", "self", ".", "minimum_needs", "or", "self", ".", "minimum_needs", "==", "''", ":", "# Load the most rel...
41.842105
0.00246
def accept(self, origin, protocol): """ Create a new route attached to a L{IBoxReceiver} created by the L{IBoxReceiverFactory} with the indicated protocol. @type origin: C{unicode} @param origin: The identifier of a route on the peer which will be associated with thi...
[ "def", "accept", "(", "self", ",", "origin", ",", "protocol", ")", ":", "for", "factory", "in", "self", ".", "store", ".", "powerupsFor", "(", "IBoxReceiverFactory", ")", ":", "# XXX What if there's a duplicate somewhere?", "if", "factory", ".", "protocol", "=="...
45.033333
0.001449
def change_option_default(self, opt_name, default_val): """ Change the default value of an option :param opt_name: option name :type opt_name: str :param value: new default option value """ if not self.has_option(opt_name): raise ValueError("...
[ "def", "change_option_default", "(", "self", ",", "opt_name", ",", "default_val", ")", ":", "if", "not", "self", ".", "has_option", "(", "opt_name", ")", ":", "raise", "ValueError", "(", "\"Unknow option name (%s)\"", "%", "opt_name", ")", "self", ".", "_optio...
36.363636
0.009756
def check_predefined_conditions(): """Check k8s predefined conditions for the nodes.""" try: node_info = current_k8s_corev1_api_client.list_node() for node in node_info.items: # check based on the predefined conditions about the # node status: MemoryPressure, OutOfDisk, K...
[ "def", "check_predefined_conditions", "(", ")", ":", "try", ":", "node_info", "=", "current_k8s_corev1_api_client", ".", "list_node", "(", ")", "for", "node", "in", "node_info", ".", "items", ":", "# check based on the predefined conditions about the", "# node status: Mem...
41.1875
0.001484
def swagger_ui_template_view(request): """ Serves Swagger UI page, default Swagger UI config is used but you can override the callable that generates the `<script>` tag by setting `cornice_swagger.swagger_ui_script_generator` in pyramid config, it defaults to 'cornice_swagger.views:swagger_ui_script...
[ "def", "swagger_ui_template_view", "(", "request", ")", ":", "script_generator", "=", "request", ".", "registry", ".", "settings", ".", "get", "(", "'cornice_swagger.swagger_ui_script_generator'", ",", "'cornice_swagger.views:swagger_ui_script_template'", ")", "package", ",...
40.423077
0.001859
def run_terraform_init(tf_bin, # pylint: disable=too-many-arguments module_path, backend_options, env_name, env_region, env_vars): """Run Terraform init.""" init_cmd = [tf_bin, 'init'] cmd_opts = {'env_vars': env_vars, 'exit_on_error': False} if backend_op...
[ "def", "run_terraform_init", "(", "tf_bin", ",", "# pylint: disable=too-many-arguments", "module_path", ",", "backend_options", ",", "env_name", ",", "env_region", ",", "env_vars", ")", ":", "init_cmd", "=", "[", "tf_bin", ",", "'init'", "]", "cmd_opts", "=", "{",...
49.289474
0.000524
def lock(tmp_dir, timeout=NOT_SET, min_wait=None, max_wait=None, verbosity=1): """Obtain lock. Obtain lock access by creating a given temporary directory (whose base will be created if needed, but will not be deleted after the lock is removed). If access is refused by the same lock owner during more th...
[ "def", "lock", "(", "tmp_dir", ",", "timeout", "=", "NOT_SET", ",", "min_wait", "=", "None", ",", "max_wait", "=", "None", ",", "verbosity", "=", "1", ")", ":", "if", "min_wait", "is", "None", ":", "min_wait", "=", "MIN_WAIT", "if", "max_wait", "is", ...
39.465116
0.000144
def read_map(fo, writer_schema, reader_schema=None): """Maps are encoded as a series of blocks. Each block consists of a long count value, followed by that many key/value pairs. A block with count zero indicates the end of the map. Each item is encoded per the map's value schema. If a block's co...
[ "def", "read_map", "(", "fo", ",", "writer_schema", ",", "reader_schema", "=", "None", ")", ":", "if", "reader_schema", ":", "def", "item_reader", "(", "fo", ",", "w_schema", ",", "r_schema", ")", ":", "return", "read_data", "(", "fo", ",", "w_schema", "...
36.53125
0.000833
def setParameter(self, name, index, value): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`. """ if name == "learningMode": self.learningMode = bool(int(value)) elif name == "inferenceMode": self.inferenceMode = bool(int(value)) else: return PyRegion...
[ "def", "setParameter", "(", "self", ",", "name", ",", "index", ",", "value", ")", ":", "if", "name", "==", "\"learningMode\"", ":", "self", ".", "learningMode", "=", "bool", "(", "int", "(", "value", ")", ")", "elif", "name", "==", "\"inferenceMode\"", ...
35
0.011142
def from_bubble_file(bblfile:str, oriented:bool=False, symmetric_edges:bool=True) -> 'BubbleTree': """Extract data from given bubble file, then call from_bubble_data method """ return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile), ...
[ "def", "from_bubble_file", "(", "bblfile", ":", "str", ",", "oriented", ":", "bool", "=", "False", ",", "symmetric_edges", ":", "bool", "=", "True", ")", "->", "'BubbleTree'", ":", "return", "BubbleTree", ".", "from_bubble_data", "(", "utils", ".", "data_fro...
54.875
0.022422