text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def acquire_read(self, timeout=None): """ Acquire a read lock for the current thread, waiting at most timeout seconds or doing a non-blocking check in case timeout is <= 0. In case timeout is None, the call to acquire_read blocks until the lock request can be serviced. ...
[ "def", "acquire_read", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "endtime", "=", "time", ".", "time", "(", ")", "+", "timeout", "me", "=", "threading", ".", "currentThread", "(", ")", "self", ".", ...
40.5
0.001096
def start(self): """Sub-command start.""" self.discover() # startup_info only gets loaded from protocol version 2 on, # check if it's loaded if not self.startup_info: # hack to make environment startable with older protocol # versions < 2: try to start no...
[ "def", "start", "(", "self", ")", ":", "self", ".", "discover", "(", ")", "# startup_info only gets loaded from protocol version 2 on,", "# check if it's loaded", "if", "not", "self", ".", "startup_info", ":", "# hack to make environment startable with older protocol", "# ver...
42.412698
0.000732
def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.d...
[ "def", "day_interval", "(", "year", ",", "month", ",", "day", ",", "milliseconds", "=", "False", ",", "return_string", "=", "False", ")", ":", "if", "milliseconds", ":", "# pragma: no cover", "delta", "=", "timedelta", "(", "milliseconds", "=", "1", ")", "...
27.678571
0.001247
def transform_ipy_prompt(line): """Handle inputs that start classic IPython prompt syntax.""" if not line or line.isspace(): return line #print 'LINE: %r' % line # dbg m = _ipy_prompt_re.match(line) if m: #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg retur...
[ "def", "transform_ipy_prompt", "(", "line", ")", ":", "if", "not", "line", "or", "line", ".", "isspace", "(", ")", ":", "return", "line", "#print 'LINE: %r' % line # dbg", "m", "=", "_ipy_prompt_re", ".", "match", "(", "line", ")", "if", "m", ":", "#print...
30.25
0.008021
def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}", project=project, tenant=tenant )
[ "def", "tenant_path", "(", "cls", ",", "project", ",", "tenant", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/tenants/{tenant}\"", ",", "project", "=", "project", ",", "tenant", "=", "tenant", "...
46.6
0.012658
def get_links_of_type(self, link_type): """ Returns list of additional links of specific type. :Returns: As tuple returns list of links. """ return (link for link in self.links if link.get('type', '') == link_type)
[ "def", "get_links_of_type", "(", "self", ",", "link_type", ")", ":", "return", "(", "link", "for", "link", "in", "self", ".", "links", "if", "link", ".", "get", "(", "'type'", ",", "''", ")", "==", "link_type", ")" ]
32.25
0.011321
def is_not_null_predicate( raw_crash, dumps, processed_crash, processor, key='' ): """a predicate that converts the key'd source to boolean. parameters: raw_crash - dict dumps - placeholder in a fat interface - unused processed_crash - placeholder in a fat interface - unused ...
[ "def", "is_not_null_predicate", "(", "raw_crash", ",", "dumps", ",", "processed_crash", ",", "processor", ",", "key", "=", "''", ")", ":", "try", ":", "return", "bool", "(", "raw_crash", "[", "key", "]", ")", "except", "KeyError", ":", "return", "False" ]
30.2
0.002141
def conf_interval(x,L,conf=0.683,shortest=True, conftol=0.001,return_max=False): """ Returns desired 1-d confidence interval for provided x, L[PDF] """ cum = np.cumsum(L) cdf = cum/cum.max() if shortest: maxind = L.argmax() if maxind==0: #hack alert ...
[ "def", "conf_interval", "(", "x", ",", "L", ",", "conf", "=", "0.683", ",", "shortest", "=", "True", ",", "conftol", "=", "0.001", ",", "return_max", "=", "False", ")", ":", "cum", "=", "np", ".", "cumsum", "(", "L", ")", "cdf", "=", "cum", "/", ...
25
0.009464
def createWPPointer(self): '''Creates the waypoint pointer relative to current heading.''' self.headingWPTri = patches.RegularPolygon((0.0,0.55),3,0.05,facecolor='lime',zorder=4,ec='k') self.axes.add_patch(self.headingWPTri) self.headingWPText = self.axes.text(0.0,0.45,'1',color='lime',s...
[ "def", "createWPPointer", "(", "self", ")", ":", "self", ".", "headingWPTri", "=", "patches", ".", "RegularPolygon", "(", "(", "0.0", ",", "0.55", ")", ",", "3", ",", "0.05", ",", "facecolor", "=", "'lime'", ",", "zorder", "=", "4", ",", "ec", "=", ...
83.166667
0.039683
async def message_handler(self, event): """Callback method for received events.NewMessage""" # Note that message_handler is called when a Telegram update occurs # and an event is created. Telegram may not always send information # about the ``.sender`` or the ``.chat``, so if you *reall...
[ "async", "def", "message_handler", "(", "self", ",", "event", ")", ":", "# Note that message_handler is called when a Telegram update occurs", "# and an event is created. Telegram may not always send information", "# about the ``.sender`` or the ``.chat``, so if you *really* want it", "# you...
41.733333
0.001561
def _psplit(self): """ Split `self` at both north and south poles. :return: A list of split StridedIntervals """ nsplit_list = self._nsplit() psplit_list = [ ] for si in nsplit_list: psplit_list.extend(si._ssplit()) return psplit_list
[ "def", "_psplit", "(", "self", ")", ":", "nsplit_list", "=", "self", ".", "_nsplit", "(", ")", "psplit_list", "=", "[", "]", "for", "si", "in", "nsplit_list", ":", "psplit_list", ".", "extend", "(", "si", ".", "_ssplit", "(", ")", ")", "return", "psp...
21.5
0.009554
def lookup(self, req, parent, name): """Look up a directory entry by name and get its attributes. Valid replies: reply_entry reply_err """ self.reply_err(req, errno.ENOENT)
[ "def", "lookup", "(", "self", ",", "req", ",", "parent", ",", "name", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "ENOENT", ")" ]
27.75
0.008734
def getRankingBruteForce(self, profile): """ Returns a list that orders all candidates from best to worst when we use brute force to compute Bayesian utilities for an election profile. This function assumes that getCandScoresMapBruteForce(profile) is implemented for the child Mechanism...
[ "def", "getRankingBruteForce", "(", "self", ",", "profile", ")", ":", "# We generate a map that associates each score with the candidates that have that score.", "candScoresMapBruteForce", "=", "self", ".", "getCandScoresMapBruteForce", "(", "profile", ")", "reverseCandScoresMap", ...
47.59375
0.011583
def _enableTracesVerilog(self, verilogFile): ''' Enables traces in a Verilog file''' fname, _ = os.path.splitext(verilogFile) inserted = False for _, line in enumerate(fileinput.input(verilogFile, inplace = 1)): sys.stdout.write(line) if line.startswith("end") and...
[ "def", "_enableTracesVerilog", "(", "self", ",", "verilogFile", ")", ":", "fname", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "verilogFile", ")", "inserted", "=", "False", "for", "_", ",", "line", "in", "enumerate", "(", "fileinput", ".", ...
49.153846
0.013825
def plot_gen(epoch, batch, generated_variables, pairs_to_plot=[[0, 1]]): """Plot generated pairs of variables.""" from matplotlib import pyplot as plt if epoch == 0: plt.ion() plt.clf() for (i, j) in pairs_to_plot: plt.scatter(generated_variables[i].data.cpu().numpy( ), batc...
[ "def", "plot_gen", "(", "epoch", ",", "batch", ",", "generated_variables", ",", "pairs_to_plot", "=", "[", "[", "0", ",", "1", "]", "]", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "epoch", "==", "0", ":", "plt", ".", "ion"...
35.166667
0.001538
def to_list(self): """Returns list containing values of attributes listed in self.attrs""" ret = OrderedDict() for attrname in self.attrs: ret[attrname] = self.__getattribute__(attrname) return ret
[ "def", "to_list", "(", "self", ")", ":", "ret", "=", "OrderedDict", "(", ")", "for", "attrname", "in", "self", ".", "attrs", ":", "ret", "[", "attrname", "]", "=", "self", ".", "__getattribute__", "(", "attrname", ")", "return", "ret" ]
34.571429
0.008065
def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func)...
[ "def", "timeout", "(", "seconds", ")", ":", "def", "_timeout_error", "(", "signal", ",", "frame", ")", ":", "raise", "TimeoutError", "(", "\"Operation did not finish within \\\n {} seconds\"", ".", "format", "(", "seconds", ")", ")", "def", "timeout_decorator...
26.652174
0.001575
def _raw_open(self, flags, mode=0o777): """ Open the file pointed by this path and return a file descriptor, as os.open() does. """ return self._accessor.open(self, flags, mode)
[ "def", "_raw_open", "(", "self", ",", "flags", ",", "mode", "=", "0o777", ")", ":", "return", "self", ".", "_accessor", ".", "open", "(", "self", ",", "flags", ",", "mode", ")" ]
35.333333
0.009217
def scene_remove(frames): """parse a scene.rm message""" # "scene.rm" <scene_id> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").assert_end().get() if results.command != "scene.rm": raise MessageParserError("Command is not 'scene.r...
[ "def", "scene_remove", "(", "frames", ")", ":", "# \"scene.rm\" <scene_id>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "assert_end", "(", ...
44
0.008357
def highlight_differences(s1, s2, color): """Highlight the characters in s2 that differ from those in s1.""" ls1, ls2 = len(s1), len(s2) diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b] print(s1) if ls2 > ls1: colorise.cprint('_' * (ls2-ls1), fg=color) else: ...
[ "def", "highlight_differences", "(", "s1", ",", "s2", ",", "color", ")", ":", "ls1", ",", "ls2", "=", "len", "(", "s1", ")", ",", "len", "(", "s2", ")", "diff_indices", "=", "[", "i", "for", "i", ",", "(", "a", ",", "b", ")", "in", "enumerate",...
25
0.002028
def matchiter(r, s, flags=0): """ Yields contiguous MatchObjects of r in s. Raises ValueError if r eventually doesn't match contiguously. """ if isinstance(r, basestring): r = re.compile(r, flags) i = 0 while s: m = r.match(s) g = m and m.group(0) if not m or ...
[ "def", "matchiter", "(", "r", ",", "s", ",", "flags", "=", "0", ")", ":", "if", "isinstance", "(", "r", ",", "basestring", ")", ":", "r", "=", "re", ".", "compile", "(", "r", ",", "flags", ")", "i", "=", "0", "while", "s", ":", "m", "=", "r...
26.8125
0.002252
def replace_id(ast, id_name, replacement): """ Replace all matching ID nodes in ast (in-place), with replacement. :param id_name: name of ID node to match :param replacement: single or list of node to insert in replacement for ID node. """ for a in ast: if isinstance(a, c_ast.ID) and a....
[ "def", "replace_id", "(", "ast", ",", "id_name", ",", "replacement", ")", ":", "for", "a", "in", "ast", ":", "if", "isinstance", "(", "a", ",", "c_ast", ".", "ID", ")", "and", "a", ".", "name", "==", "id_name", ":", "# Check all attributes of ast", "fo...
45
0.002175
def pagerank_centrality(A, d, falff=None): ''' The PageRank centrality is a variant of eigenvector centrality. This function computes the PageRank centrality of each vertex in a graph. Formally, PageRank is defined as the stationary distribution achieved by instantiating a Markov chain on a graph. ...
[ "def", "pagerank_centrality", "(", "A", ",", "d", ",", "falff", "=", "None", ")", ":", "from", "scipy", "import", "linalg", "N", "=", "len", "(", "A", ")", "if", "falff", "is", "None", ":", "norm_falff", "=", "np", ".", "ones", "(", "(", "N", ","...
32.169811
0.000569
def _find_remove_targets(name=None, version=None, pkgs=None, normalize=True, ignore_epoch=False, **kwargs): ''' Inspect the arguments to pkg.removed and discover what packages need to ...
[ "def", "_find_remove_targets", "(", "name", "=", "None", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "normalize", "=", "True", ",", "ignore_epoch", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "__grains__", "[", "'os'", "]", ...
35.582278
0.001038
def slugs_camera_order_send(self, target, pan, tilt, zoom, moveHome, force_mavlink1=False): ''' Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount t...
[ "def", "slugs_camera_order_send", "(", "self", ",", "target", ",", "pan", ",", "tilt", ",", "zoom", ",", "moveHome", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "slugs_camera_order_encode", "(", "target", ...
72.75
0.010181
def delunnamedcol(df): """ Deletes all the unnamed columns :param df: pandas dataframe """ cols_del=[c for c in df.columns if 'Unnamed' in c] return df.drop(cols_del,axis=1)
[ "def", "delunnamedcol", "(", "df", ")", ":", "cols_del", "=", "[", "c", "for", "c", "in", "df", ".", "columns", "if", "'Unnamed'", "in", "c", "]", "return", "df", ".", "drop", "(", "cols_del", ",", "axis", "=", "1", ")" ]
23.875
0.015152
def file_decrypt( blockchain_id, hostname, sender_blockchain_id, sender_key_id, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Decrypt a file from a sender's blockchain ID. Try our current key, and then the old keys (but warn if there are revoked keys) Ret...
[ "def", "file_decrypt", "(", "blockchain_id", ",", "hostname", ",", "sender_blockchain_id", ",", "sender_key_id", ",", "input_path", ",", "output_path", ",", "passphrase", "=", "None", ",", "config_path", "=", "CONFIG_PATH", ",", "wallet_keys", "=", "None", ")", ...
39.913043
0.00815
def query_mongo( database_name, collection_name, query={}, include_num_results="0", skip=0, sort=None, limit=getattr( settings, 'MONGO_LIMIT', 200), cast_strings_to_integers=False, return_keys=()): """return ...
[ "def", "query_mongo", "(", "database_name", ",", "collection_name", ",", "query", "=", "{", "}", ",", "include_num_results", "=", "\"0\"", ",", "skip", "=", "0", ",", "sort", "=", "None", ",", "limit", "=", "getattr", "(", "settings", ",", "'MONGO_LIMIT'",...
30.628571
0.002259
def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None): # pylint: disable=unused-argument """Calculate an PSD of this `TimeSeries` using Bartlett's method Parameters ---------- timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `...
[ "def", "bartlett", "(", "timeseries", ",", "segmentlength", ",", "noverlap", "=", "None", ",", "window", "=", "None", ",", "plan", "=", "None", ")", ":", "# pylint: disable=unused-argument", "return", "_lal_spectrum", "(", "timeseries", ",", "segmentlength", ","...
29.71875
0.001018
def _writeResponse(self, response): """ Serializes the response to JSON, and writes it to the transport. """ encoded = dumps(response, default=_default) self.transport.write(encoded)
[ "def", "_writeResponse", "(", "self", ",", "response", ")", ":", "encoded", "=", "dumps", "(", "response", ",", "default", "=", "_default", ")", "self", ".", "transport", ".", "write", "(", "encoded", ")" ]
36.166667
0.009009
def underlying_likelihood(self, binary_outcomes, modelparams, expparams): """ Given outcomes hypothesized for the underlying model, returns the likelihood which which those outcomes occur. """ original_mps = modelparams[..., self._orig_mps_slice] return self.underlying_mo...
[ "def", "underlying_likelihood", "(", "self", ",", "binary_outcomes", ",", "modelparams", ",", "expparams", ")", ":", "original_mps", "=", "modelparams", "[", "...", ",", "self", ".", "_orig_mps_slice", "]", "return", "self", ".", "underlying_model", ".", "likeli...
52.857143
0.010638
def make_github_markdown_writer(opts): """ Creates a Writer object used for parsing and writing Markdown files with a GitHub style anchor transformation opts is a namespace object containing runtime options. It should generally include the following attributes: * 'open': a string correspondi...
[ "def", "make_github_markdown_writer", "(", "opts", ")", ":", "assert", "hasattr", "(", "opts", ",", "'wrapper_regex'", ")", "atx", "=", "MarkdownATXWriterStrategy", "(", "opts", ",", "'ATX headers'", ")", "setext", "=", "MarkdownSetextWriterStrategy", "(", "opts", ...
45.818182
0.001295
def RunScript(self, script): ''' Actuate on the vehicle through a script. The script is a sequence of commands. Each command is a sequence with the first element as the command name and the remaining values as parameters. The script is executed asynchronously by a timer with a p...
[ "def", "RunScript", "(", "self", ",", "script", ")", ":", "self", ".", "script", "=", "script", "self", ".", "script_command", "=", "0", "self", ".", "script_command_start_time", "=", "0", "self", ".", "script_command_state", "=", "'ready'", "self", ".", "...
43.025641
0.001166
def _error_check(err, prefix=""): """Pretty-print a numerical error code if there is an error.""" if err != 0: err_str = _snd.sf_error_number(err) raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
[ "def", "_error_check", "(", "err", ",", "prefix", "=", "\"\"", ")", ":", "if", "err", "!=", "0", ":", "err_str", "=", "_snd", ".", "sf_error_number", "(", "err", ")", "raise", "RuntimeError", "(", "prefix", "+", "_ffi", ".", "string", "(", "err_str", ...
48.6
0.008097
def unsubscribe(self): """Unsubscribe from the service's events. Once unsubscribed, a Subscription instance should not be reused """ # Trying to unsubscribe if already unsubscribed, or not yet # subscribed, fails silently if self._has_been_unsubscribed or not self.is_sub...
[ "def", "unsubscribe", "(", "self", ")", ":", "# Trying to unsubscribe if already unsubscribed, or not yet", "# subscribed, fails silently", "if", "self", ".", "_has_been_unsubscribed", "or", "not", "self", ".", "is_subscribed", ":", "return", "# Cancel any auto renew", "self"...
33.479167
0.001209
def isobaric_to_ambient_temperature(self, data): """ Calculates temperature from isobaric temperature. Parameters ---------- data: DataFrame Must contain columns pressure, temperature_iso, temperature_dew_iso. Input temperature in K. Returns ...
[ "def", "isobaric_to_ambient_temperature", "(", "self", ",", "data", ")", ":", "P", "=", "data", "[", "'pressure'", "]", "/", "100.0", "# noqa: N806", "Tiso", "=", "data", "[", "'temperature_iso'", "]", "# noqa: N806", "Td", "=", "data", "[", "'temperature_dew_...
30
0.002227
def addLimitedLogHandler(func): """ Add a custom log handler. @param func: a function object with prototype (level, object, category, message) where level is either ERROR, WARN, INFO, DEBUG, or LOG, and the rest of the arguments are strings or None. Use ge...
[ "def", "addLimitedLogHandler", "(", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "\"func must be callable\"", ")", "if", "func", "not", "in", "_log_handlers_limited", ":", "_log_handlers_limited", ".", "append", "(...
37.117647
0.001546
def progress_bar(name, maxval, prefix='Converting'): """Manages a progress bar for a conversion. Parameters ---------- name : str Name of the file being converted. maxval : int Total number of steps for the conversion. """ widgets = ['{} {}: '.format(prefix, name), Percenta...
[ "def", "progress_bar", "(", "name", ",", "maxval", ",", "prefix", "=", "'Converting'", ")", ":", "widgets", "=", "[", "'{} {}: '", ".", "format", "(", "prefix", ",", "name", ")", ",", "Percentage", "(", ")", ",", "' '", ",", "Bar", "(", "marker", "="...
28.684211
0.001776
def humanize_bytes(b, precision=1): """Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '...
[ "def", "humanize_bytes", "(", "b", ",", "precision", "=", "1", ")", ":", "# abbrevs = (", "# (1 << 50L, 'PB'),", "# (1 << 40L, 'TB'),", "# (1 << 30L, 'GB'),", "# (1 << 20L, 'MB'),", "# (1 << 10L, 'kB'),", "# (1, 'b')", "# )", "abbrevs", "=", "(", "("...
24.2
0.000883
def _calculate_phases(self, solution, t, step, int_step): """! @brief Calculates new phases for oscillators in the network in line with current step. @param[in] solution (solve_type): Type solver of the differential equation. @param[in] t (double): Time of simulation. ...
[ "def", "_calculate_phases", "(", "self", ",", "solution", ",", "t", ",", "step", ",", "int_step", ")", ":", "next_phases", "=", "[", "0.0", "]", "*", "self", ".", "_num_osc", "# new oscillator _phases\r", "for", "index", "in", "range", "(", "0", ",", "se...
51.821429
0.020298
def _get_course_content_from_ecommerce(course_id, site_code=None): """ Get course information using the Ecommerce course api. In case of error returns empty response. Arguments: course_id (str): course key of the course site_code (str): site code Returns: course information...
[ "def", "_get_course_content_from_ecommerce", "(", "course_id", ",", "site_code", "=", "None", ")", ":", "api", "=", "get_ecommerce_client", "(", "site_code", "=", "site_code", ")", "try", ":", "api_response", "=", "api", ".", "courses", "(", "course_id", ")", ...
30.444444
0.002358
def _get_status_from_xml_tags(self, root, relevant_tags): """ Get relevant status tags from XML structure with this internal method. Status is saved to internal attributes. Return dictionary of tags not found in XML. """ for child in root: if child.tag not in...
[ "def", "_get_status_from_xml_tags", "(", "self", ",", "root", ",", "relevant_tags", ")", ":", "for", "child", "in", "root", ":", "if", "child", ".", "tag", "not", "in", "relevant_tags", ".", "keys", "(", ")", ":", "continue", "elif", "child", ".", "tag",...
43.692308
0.001148
def rename_in_module(occurrences_finder, new_name, resource=None, pymodule=None, replace_primary=False, region=None, reads=True, writes=True): """Returns the changed source or `None` if there is no changes""" if resource is not None: source_code = resource.read(...
[ "def", "rename_in_module", "(", "occurrences_finder", ",", "new_name", ",", "resource", "=", "None", ",", "pymodule", "=", "None", ",", "replace_primary", "=", "False", ",", "region", "=", "None", ",", "reads", "=", "True", ",", "writes", "=", "True", ")",...
46.863636
0.000951
def timeShift(requestContext, seriesList, timeShift, resetEnd=True, alignDST=False): """ Takes one metric or a wildcard seriesList, followed by a quoted string with the length of time (See ``from / until`` in the render\_api_ for examples of time formats). Draws the selected metrics s...
[ "def", "timeShift", "(", "requestContext", ",", "seriesList", ",", "timeShift", ",", "resetEnd", "=", "True", ",", "alignDST", "=", "False", ")", ":", "# Default to negative. parseTimeOffset defaults to +", "if", "timeShift", "[", "0", "]", ".", "isdigit", "(", ...
39.255814
0.000578
def SUSSelection(self, mating_pool_size): ''' Make Selection of the mating pool with the stochastic universal sampling algorithm ''' A = numpy.zeros(self.length) mating_pool = numpy.zeros(mating_pool_size) r = numpy.random.random()/float(mating_pool_size) [F,S,P] = self.rankingEval() P_Sorted = num...
[ "def", "SUSSelection", "(", "self", ",", "mating_pool_size", ")", ":", "A", "=", "numpy", ".", "zeros", "(", "self", ".", "length", ")", "mating_pool", "=", "numpy", ".", "zeros", "(", "mating_pool_size", ")", "r", "=", "numpy", ".", "random", ".", "ra...
22.071429
0.049612
def wait_for_channel_in_states( raiden: 'RaidenService', payment_network_id: PaymentNetworkID, token_address: TokenAddress, channel_ids: List[ChannelID], retry_timeout: float, target_states: Sequence[str], ) -> None: """Wait until all channels are in `target_states`. ...
[ "def", "wait_for_channel_in_states", "(", "raiden", ":", "'RaidenService'", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "channel_ids", ":", "List", "[", "ChannelID", "]", ",", "retry_timeout", ":", "float", ","...
29.931034
0.001115
def create_security_group(self, name, description, vpc_id=None): """Create security group. @param name: Name of the new security group. @param description: Description of the new security group. @param vpc_id: ID of the VPC to which the security group will belong. @return: A C{D...
[ "def", "create_security_group", "(", "self", ",", "name", ",", "description", ",", "vpc_id", "=", "None", ")", ":", "parameters", "=", "{", "\"GroupName\"", ":", "name", ",", "\"GroupDescription\"", ":", "description", "}", "if", "vpc_id", ":", "parameters", ...
46.294118
0.002491
def index_is_empty(self) -> bool: """ :return: True if index is empty (no staged changes) :rtype: bool """ index_empty: bool = len(self.repo.index.diff(self.repo.head.commit)) == 0 LOGGER.debug('index is empty: %s', index_empty) return index_empty
[ "def", "index_is_empty", "(", "self", ")", "->", "bool", ":", "index_empty", ":", "bool", "=", "len", "(", "self", ".", "repo", ".", "index", ".", "diff", "(", "self", ".", "repo", ".", "head", ".", "commit", ")", ")", "==", "0", "LOGGER", ".", "...
37
0.009901
def _Rforce(self,R,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the radial force INPUT: R phi t OUTPUT: F_R(R(,\phi,t)) HISTORY: 2010-07-13 - Written - Bovy (NYU) """ return s...
[ "def", "_Rforce", "(", "self", ",", "R", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_Pot", ".", "Rforce", "(", "R", ",", "0.", ",", "t", "=", "t", ",", "use_physical", "=", "False", ")" ]
21.8125
0.024725
def _reorder_lines(lines): """ Reorder lines so that the distance from the end of one to the beginning of the next is minimised. """ x = 0 y = 0 new_lines = [] # treat the list of lines as a stack, off which we keep popping the best # one to add next. while lines: # loo...
[ "def", "_reorder_lines", "(", "lines", ")", ":", "x", "=", "0", "y", "=", "0", "new_lines", "=", "[", "]", "# treat the list of lines as a stack, off which we keep popping the best", "# one to add next.", "while", "lines", ":", "# looping over all the lines like this isn't ...
26.941176
0.001054
def cbpdnmd_ystep(k): """Do the Y step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables. """ if mp_W.shape[0] > 1: W = mp_W[k] else: W = mp_W AXU0 = mp_DX[k] - mp_S[k] + mp_Z...
[ "def", "cbpdnmd_ystep", "(", "k", ")", ":", "if", "mp_W", ".", "shape", "[", "0", "]", ">", "1", ":", "W", "=", "mp_W", "[", "k", "]", "else", ":", "W", "=", "mp_W", "AXU0", "=", "mp_DX", "[", "k", "]", "-", "mp_S", "[", "k", "]", "+", "m...
32.142857
0.00216
def _decrypt_verify_session_keys(encrypted, session_keys): """Decrypts the given ciphertext string using the session_keys and returns both the signatures (if any) and the plaintext. :param bytes encrypted: the mail to decrypt :param list[str] session_keys: a list OpenPGP session keys :returns: the ...
[ "def", "_decrypt_verify_session_keys", "(", "encrypted", ",", "session_keys", ")", ":", "for", "key", "in", "session_keys", ":", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", ")", "ctx", ".", "set_ctx_flag", "(", "\"override-session-key\"", ",", "key", ...
42.833333
0.001269
def dataset_list_files(self, dataset): """ list files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if dataset is None: raise ValueError('A dat...
[ "def", "dataset_list_files", "(", "self", ",", "dataset", ")", ":", "if", "dataset", "is", "None", ":", "raise", "ValueError", "(", "'A dataset must be specified'", ")", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ...
42.238095
0.002205
def add(self, node): """Add one node as descendant """ self.sons.append(node) node.parent = self
[ "def", "add", "(", "self", ",", "node", ")", ":", "self", ".", "sons", ".", "append", "(", "node", ")", "node", ".", "parent", "=", "self" ]
24.8
0.015625
def template_statemgr_yaml(cl_args, zookeepers): ''' Template statemgr.yaml ''' statemgr_config_file_template = "%s/standalone/templates/statemgr.template.yaml" \ % cl_args["config_path"] statemgr_config_file_actual = "%s/standalone/statemgr.yaml" % cl_args["config_path"] ...
[ "def", "template_statemgr_yaml", "(", "cl_args", ",", "zookeepers", ")", ":", "statemgr_config_file_template", "=", "\"%s/standalone/templates/statemgr.template.yaml\"", "%", "cl_args", "[", "\"config_path\"", "]", "statemgr_config_file_actual", "=", "\"%s/standalone/statemgr.yam...
48.909091
0.014599
def remove_event(self, name=None, time=None, chan=None): """Action: remove single event.""" self.annot.remove_event(name=name, time=time, chan=chan) self.update_annotations()
[ "def", "remove_event", "(", "self", ",", "name", "=", "None", ",", "time", "=", "None", ",", "chan", "=", "None", ")", ":", "self", ".", "annot", ".", "remove_event", "(", "name", "=", "name", ",", "time", "=", "time", ",", "chan", "=", "chan", "...
48.75
0.010101
def _render(request, data, encrypted, format=None): """ Render the data to Geckoboard. If the `format` parameter is passed to the widget it defines the output format. Otherwise the output format is based on the `format` request parameter. A `format` paramater of ``json`` or ``2`` renders JSON outpu...
[ "def", "_render", "(", "request", ",", "data", ",", "encrypted", ",", "format", "=", "None", ")", ":", "if", "not", "format", ":", "format", "=", "request", ".", "POST", ".", "get", "(", "'format'", ",", "''", ")", "if", "not", "format", ":", "form...
36.529412
0.00157
def prepare_pip_requirements_file_if_needed(requirements): """ Make requirements be passed to pip via a requirements file if needed. We must be careful about how we pass shell operator characters (e.g. '<', '>', '|' or '^') included in our command-line arguments or they might cause problems i...
[ "def", "prepare_pip_requirements_file_if_needed", "(", "requirements", ")", ":", "if", "utility", ".", "any_contains_any", "(", "requirements", ",", "\"<>|()&^\"", ")", ":", "file_path", ",", "janitor", "=", "pip_requirements_file", "(", "requirements", ")", "requirem...
43.333333
0.001255
def extract_replacements(self, trajectory): """Extracts the wildcards and file replacements from the `trajectory`""" self.env_name = trajectory.v_environment_name self.traj_name = trajectory.v_name self.set_name = trajectory.f_wildcard('$set') self.run_name = trajectory.f_wildca...
[ "def", "extract_replacements", "(", "self", ",", "trajectory", ")", ":", "self", ".", "env_name", "=", "trajectory", ".", "v_environment_name", "self", ".", "traj_name", "=", "trajectory", ".", "v_name", "self", ".", "set_name", "=", "trajectory", ".", "f_wild...
53.666667
0.012232
def split_snps_indels(orig_file, ref_file, config): """Split a variant call file into SNPs and INDELs for processing. """ base, ext = utils.splitext_plus(orig_file) snp_file = "{base}-snp{ext}".format(base=base, ext=ext) indel_file = "{base}-indel{ext}".format(base=base, ext=ext) for out_file, s...
[ "def", "split_snps_indels", "(", "orig_file", ",", "ref_file", ",", "config", ")", ":", "base", ",", "ext", "=", "utils", ".", "splitext_plus", "(", "orig_file", ")", "snp_file", "=", "\"{base}-snp{ext}\"", ".", "format", "(", "base", "=", "base", ",", "ex...
56.529412
0.002047
def update_unit(self, unit_id, unit_dict): """ Updates an unit :param unit_id: the unit id :param unit_dict: dict :return: dict """ return self._create_put_request(resource=UNITS, billomat_id=unit_id, send_data=unit_dict)
[ "def", "update_unit", "(", "self", ",", "unit_id", ",", "unit_dict", ")", ":", "return", "self", ".", "_create_put_request", "(", "resource", "=", "UNITS", ",", "billomat_id", "=", "unit_id", ",", "send_data", "=", "unit_dict", ")" ]
30
0.010791
def python_to_jupyter_cli(args=None, namespace=None): """Exposes the jupyter notebook renderer to the command line Takes the same arguments as ArgumentParser.parse_args """ from . import gen_gallery # To avoid circular import parser = argparse.ArgumentParser( description='Sphinx-Gallery No...
[ "def", "python_to_jupyter_cli", "(", "args", "=", "None", ",", "namespace", "=", "None", ")", ":", "from", ".", "import", "gen_gallery", "# To avoid circular import", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Sphinx-Gallery Noteboo...
47.4
0.001034
def get_color(name, stream=STD_OUTPUT_HANDLE): ''' Returns current colors of console. https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo Arguments: name: one of ('background', 'bg', 'foreground', 'fg') stream: Handle to stdout, stderr, etc. ...
[ "def", "get_color", "(", "name", ",", "stream", "=", "STD_OUTPUT_HANDLE", ")", ":", "stream", "=", "kernel32", ".", "GetStdHandle", "(", "stream", ")", "csbi", "=", "CONSOLE_SCREEN_BUFFER_INFO", "(", ")", "kernel32", ".", "GetConsoleScreenBufferInfo", "(", "stre...
37.576923
0.000998
def stamp_excerpt(kb_app: kb, sphinx_app: Sphinx, doctree: doctree): """ Walk the tree and extract excert into resource.excerpt """ # First, find out which resource this is. Won't be easy. resources = sphinx_app.env.resources confdir = sphinx_app.confdir source =...
[ "def", "stamp_excerpt", "(", "kb_app", ":", "kb", ",", "sphinx_app", ":", "Sphinx", ",", "doctree", ":", "doctree", ")", ":", "# First, find out which resource this is. Won't be easy.", "resources", "=", "sphinx_app", ".", "env", ".", "resources", "confdir", "=", ...
38.037037
0.00095
def allDayForDate(self,this_date,timeZone=None): ''' This method determines whether the occurrence lasts the entirety of a specified day in the specified time zone. If no time zone is specified, then it uses the default time zone). Also, give a grace period of a few minutes to ...
[ "def", "allDayForDate", "(", "self", ",", "this_date", ",", "timeZone", "=", "None", ")", ":", "if", "isinstance", "(", "this_date", ",", "datetime", ")", ":", "d", "=", "this_date", ".", "date", "(", ")", "else", ":", "d", "=", "this_date", "date_star...
47.857143
0.012683
def _get_ordered_idx(self, mask_missing_values): """Decide in what order we will update the features. As a homage to the MICE R package, we will have 4 main options of how to order the updates, and use a random order if anything else is specified. Also, this function skips feat...
[ "def", "_get_ordered_idx", "(", "self", ",", "mask_missing_values", ")", ":", "frac_of_missing_values", "=", "mask_missing_values", ".", "mean", "(", "axis", "=", "0", ")", "missing_values_idx", "=", "np", ".", "nonzero", "(", "frac_of_missing_values", ")", "[", ...
46.767442
0.000974
def _send_message_with_response(self, operation, read_preference=None, exhaust=False, address=None): """Send a message to MongoDB and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `read_preference` (optional): A Rea...
[ "def", "_send_message_with_response", "(", "self", ",", "operation", ",", "read_preference", "=", "None", ",", "exhaust", "=", "False", ",", "address", "=", "None", ")", ":", "with", "self", ".", "__lock", ":", "# If needed, restart kill-cursors thread after a fork....
42.97619
0.001625
def do_files_exist(filenames): """Whether any of the filenames exist.""" preexisting = [tf.io.gfile.exists(f) for f in filenames] return any(preexisting)
[ "def", "do_files_exist", "(", "filenames", ")", ":", "preexisting", "=", "[", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "f", ")", "for", "f", "in", "filenames", "]", "return", "any", "(", "preexisting", ")" ]
39
0.025157
def histograms(dat, keys=None, bins=25, logy=False, cmap=None, ncol=4): """ Plot histograms of all items in dat. Parameters ---------- dat : dict Data in {key: array} pairs. keys : arra-like The keys in dat that you want to plot. If None, all are plotted. bins : int ...
[ "def", "histograms", "(", "dat", ",", "keys", "=", "None", ",", "bins", "=", "25", ",", "logy", "=", "False", ",", "cmap", "=", "None", ",", "ncol", "=", "4", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "dat", ".", "keys", "(", ")...
22.046875
0.000678
def cycle_gan_small(): """Set of hyperparameters.""" hparams = transformer_vae.transformer_ae_small() hparams.batch_size = 2048 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparam...
[ "def", "cycle_gan_small", "(", ")", ":", "hparams", "=", "transformer_vae", ".", "transformer_ae_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "bottom", "=", "{", "\"inputs\"", ":", "modalities", ".", "identity_bottom", ",", "\"t...
33.157895
0.021605
def alias_field(model, field): """ Return the prefix name of a field """ for part in field.split(LOOKUP_SEP)[:-1]: model = associate_model(model,part) return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
[ "def", "alias_field", "(", "model", ",", "field", ")", ":", "for", "part", "in", "field", ".", "split", "(", "LOOKUP_SEP", ")", "[", ":", "-", "1", "]", ":", "model", "=", "associate_model", "(", "model", ",", "part", ")", "return", "model", ".", "...
32.857143
0.008475
def _unary_op(cls, x: 'TensorFluent', op: Callable[[tf.Tensor], tf.Tensor], dtype: tf.DType) -> 'TensorFluent': '''Returns a TensorFluent for the unary `op` applied to fluent `x`. Args: x: The input fluent. op: The unary operation. ...
[ "def", "_unary_op", "(", "cls", ",", "x", ":", "'TensorFluent'", ",", "op", ":", "Callable", "[", "[", "tf", ".", "Tensor", "]", ",", "tf", ".", "Tensor", "]", ",", "dtype", ":", "tf", ".", "DType", ")", "->", "'TensorFluent'", ":", "x", "=", "x"...
30.947368
0.008251
def add(self, tid, result, role, session, oid=None, content=None, anony=None): '''taobao.traderate.add 新增单个评价 新增单个评价(注:在评价之前需要对订单成功的时间进行判定(end_time),如果超过15天,不能再通过该接口进行评价)''' request = TOPRequest('taobao.traderate.add') request['tid'] = tid request['result'] = result ...
[ "def", "add", "(", "self", ",", "tid", ",", "result", ",", "role", ",", "session", ",", "oid", "=", "None", ",", "content", "=", "None", ",", "anony", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.traderate.add'", ")", "request", ...
43.615385
0.020725
def DOMSnapshot_getSnapshot(self, computedStyleWhitelist): """ Function path: DOMSnapshot.getSnapshot Domain: DOMSnapshot Method name: getSnapshot Parameters: Required arguments: 'computedStyleWhitelist' (type: array) -> Whitelist of computed styles to return. Returns: 'domNodes' (type: ...
[ "def", "DOMSnapshot_getSnapshot", "(", "self", ",", "computedStyleWhitelist", ")", ":", "assert", "isinstance", "(", "computedStyleWhitelist", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'computedStyleWhitelist' must be of type '['list', 'tuple']'. Received typ...
55.636364
0.028916
def _method_complete(self, result): """Called after an extention method with the result.""" if isinstance(result, PrettyTensor): self._head = result return self elif isinstance(result, Loss): return result elif isinstance(result, PrettyTensorTupleMixin): self._head = result[0] ...
[ "def", "_method_complete", "(", "self", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "PrettyTensor", ")", ":", "self", ".", "_head", "=", "result", "return", "self", "elif", "isinstance", "(", "result", ",", "Loss", ")", ":", "return"...
31
0.019277
def human_size(size, a_kilobyte_is_1024_bytes=False, precision=1, target=None): '''Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 if False, use multiples of 10...
[ "def", "human_size", "(", "size", ",", "a_kilobyte_is_1024_bytes", "=", "False", ",", "precision", "=", "1", ",", "target", "=", "None", ")", ":", "if", "size", "<", "0", ":", "raise", "ValueError", "(", "'number must be non-negative'", ")", "multiple", "=",...
28.828571
0.000959
def wait(self, sensor_name, condition_or_value, timeout=5): """Wait for a sensor in this resource to satisfy a condition. Parameters ---------- sensor_name : string The name of the sensor to check condition_or_value : obj or callable, or seq of objs or callables ...
[ "def", "wait", "(", "self", ",", "sensor_name", ",", "condition_or_value", ",", "timeout", "=", "5", ")", ":", "sensor_name", "=", "escape_name", "(", "sensor_name", ")", "sensor", "=", "self", ".", "sensor", "[", "sensor_name", "]", "try", ":", "yield", ...
38.783784
0.00136
def encode_bytes(src_buf, dst_file): """Encode a buffer length followed by the bytes of the buffer itself. Parameters ---------- src_buf: bytes Source bytes to be encoded. Function asserts that 0 <= len(src_buf) <= 2**16-1. dst_file: file File-like object with write met...
[ "def", "encode_bytes", "(", "src_buf", ",", "dst_file", ")", ":", "if", "not", "isinstance", "(", "src_buf", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'src_buf must by bytes.'", ")", "len_src_buf", "=", "len", "(", "src_buf", ")", "assert", "0", ...
24.586207
0.00135
def add_organization(session, name): """Add an organization to the session. This function adds a new organization to the session, using the given `name` as an identifier. Name cannot be empty or `None`. It returns a new `Organization` object. :param session: database session :param name: ...
[ "def", "add_organization", "(", "session", ",", "name", ")", ":", "if", "name", "is", "None", ":", "raise", "ValueError", "(", "\"'name' cannot be None\"", ")", "if", "name", "==", "''", ":", "raise", "ValueError", "(", "\"'name' cannot be an empty string\"", ")...
25.653846
0.001445
def _input_github_repo(url=None): """ Grabs input from the user and saves it as their trytravis target repo """ if url is None: url = user_input('Input the URL of the GitHub repository ' 'to use as a `trytravis` repository: ') url = url.strip() http_match = _HTTPS_RE...
[ "def", "_input_github_repo", "(", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "user_input", "(", "'Input the URL of the GitHub repository '", "'to use as a `trytravis` repository: '", ")", "url", "=", "url", ".", "strip", "(", ")", ...
45.2
0.000541
def issues(self, kind, email): """ Filter unique issues for given activity type and email """ return list(set([unicode(activity.issue) for activity in self.activities() if kind == activity.kind and activity.user['email'] == email]))
[ "def", "issues", "(", "self", ",", "kind", ",", "email", ")", ":", "return", "list", "(", "set", "(", "[", "unicode", "(", "activity", ".", "issue", ")", "for", "activity", "in", "self", ".", "activities", "(", ")", "if", "kind", "==", "activity", ...
53.6
0.014706
def on_natural_language(keywords: Union[Optional[Iterable], Callable] = None, *, permission: int = perm.EVERYBODY, only_to_me: bool = True, only_short_message: bool = True, allow_empty_message: bool = False) -> Callable: ...
[ "def", "on_natural_language", "(", "keywords", ":", "Union", "[", "Optional", "[", "Iterable", "]", ",", "Callable", "]", "=", "None", ",", "*", ",", "permission", ":", "int", "=", "perm", ".", "EVERYBODY", ",", "only_to_me", ":", "bool", "=", "True", ...
44.310345
0.000762
def rn(shape, dtype=None, impl='numpy', **kwargs): """Return a space of real tensors. Parameters ---------- shape : positive int or sequence of positive ints Number of entries per axis for elements in this space. A single integer results in a space with 1 axis. dtype : optional ...
[ "def", "rn", "(", "shape", ",", "dtype", "=", "None", ",", "impl", "=", "'numpy'", ",", "*", "*", "kwargs", ")", ":", "rn_cls", "=", "tensor_space_impl", "(", "impl", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "rn_cls", ".", "default_dtype"...
29.8125
0.000507
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None): ''' Given a function to map from an ID to an underlying object, and a function to map from an underlying object to the concrete GraphQLObjectType it corresponds to, constructs a `Node` interface that objects can implement, and a...
[ "def", "node_definitions", "(", "id_fetcher", ",", "type_resolver", "=", "None", ",", "id_resolver", "=", "None", ")", ":", "node_interface", "=", "GraphQLInterfaceType", "(", "'Node'", ",", "description", "=", "'An object with an ID'", ",", "fields", "=", "lambda...
37.914286
0.000735
def extendsTree( self ): """ Returns whether or not the grid lines should extend through the tree \ area or not. :return <bool> """ delegate = self.itemDelegate() if ( isinstance(delegate, XTreeWidgetDelegate) ): return delegate.exten...
[ "def", "extendsTree", "(", "self", ")", ":", "delegate", "=", "self", ".", "itemDelegate", "(", ")", "if", "(", "isinstance", "(", "delegate", ",", "XTreeWidgetDelegate", ")", ")", ":", "return", "delegate", ".", "extendsTree", "(", ")", "return", "False" ...
30.909091
0.022857
def predict(self, X, **kwargs): """Predict the closest cluster each sample in X belongs to. Parameters ---------- X : array-like, shape = [n_samples, n_features] New data to predict. Returns ------- labels : array, shape [n_samples,] Inde...
[ "def", "predict", "(", "self", ",", "X", ",", "*", "*", "kwargs", ")", ":", "assert", "hasattr", "(", "self", ",", "'_enc_cluster_centroids'", ")", ",", "\"Model not yet fitted.\"", "if", "self", ".", "verbose", "and", "self", ".", "cat_dissim", "==", "ng_...
36.44
0.002139
def process_configs(file_lookup, app_config_format, pipeline_config): """Processes the configs from lookup sources. Args: file_lookup (FileLookup): Source to look for file/config app_config_format (str): The format for application config files. pipeline_config (str): Name/path of the pi...
[ "def", "process_configs", "(", "file_lookup", ",", "app_config_format", ",", "pipeline_config", ")", ":", "app_configs", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "env", "in", "ENVS", ":", "file_json", "=", "app_config_format", ".", "forma...
37.827586
0.001778
def knots_from_marginal(marginal, nr_knots, spline_order): """ Determines knot placement based on a marginal distribution. It places knots such that each knot covers the same amount of probability mass. Two of the knots are reserved for the borders which are treated seperatly. For example, a uni...
[ "def", "knots_from_marginal", "(", "marginal", ",", "nr_knots", ",", "spline_order", ")", ":", "cumsum", "=", "np", ".", "cumsum", "(", "marginal", ")", "cumsum", "=", "cumsum", "/", "cumsum", ".", "max", "(", ")", "borders", "=", "np", ".", "linspace", ...
35.333333
0.010101
def _normalize(self, addr): """Take any format of address and turn it into a hex string.""" normalize = None if isinstance(addr, Address): normalize = addr.addr self._is_x10 = addr.is_x10 elif isinstance(addr, bytearray): normalize = binascii.unhexlif...
[ "def", "_normalize", "(", "self", ",", "addr", ")", ":", "normalize", "=", "None", "if", "isinstance", "(", "addr", ",", "Address", ")", ":", "normalize", "=", "addr", ".", "addr", "self", ".", "_is_x10", "=", "addr", ".", "is_x10", "elif", "isinstance...
32.8
0.001974
def _create_variables(self, n_features, W_=None, bh_=None, bv_=None): """Create the TensorFlow variables for the model. :return: self """ if W_: self.W_ = tf.Variable(W_, name='enc-w') else: self.W_ = tf.Variable( tf.truncated_normal( ...
[ "def", "_create_variables", "(", "self", ",", "n_features", ",", "W_", "=", "None", ",", "bh_", "=", "None", ",", "bv_", "=", "None", ")", ":", "if", "W_", ":", "self", ".", "W_", "=", "tf", ".", "Variable", "(", "W_", ",", "name", "=", "'enc-w'"...
33.541667
0.002415
def _expose_models(cls): """ Register the models and assign them to `models` :return: """ if db._IS_OK_: register_models(**{m.__name__: m for m in db.Model.__subclasses__() if not hasattr(models, m.__name_...
[ "def", "_expose_models", "(", "cls", ")", ":", "if", "db", ".", "_IS_OK_", ":", "register_models", "(", "*", "*", "{", "m", ".", "__name__", ":", "m", "for", "m", "in", "db", ".", "Model", ".", "__subclasses__", "(", ")", "if", "not", "hasattr", "(...
35.111111
0.009259
def _gen_from_dircmp(dc, lpath, rpath): """ do the work of comparing the dircmp """ left_only = dc.left_only left_only.sort() for f in left_only: fp = join(dc.left, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, lpath) fo...
[ "def", "_gen_from_dircmp", "(", "dc", ",", "lpath", ",", "rpath", ")", ":", "left_only", "=", "dc", ".", "left_only", "left_only", ".", "sort", "(", ")", "for", "f", "in", "left_only", ":", "fp", "=", "join", "(", "dc", ".", "left", ",", "f", ")", ...
24.4375
0.00082
def all(self, endpoint, *args, **kwargs): """Retrieve all the data of a paginated endpoint, using GET. :returns: The endpoint unpaginated data :rtype: dict """ # 1. Initialize the pagination parameters. kwargs.setdefault('params', {})['offset'] = 0 kwargs.setdefau...
[ "def", "all", "(", "self", ",", "endpoint", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# 1. Initialize the pagination parameters.", "kwargs", ".", "setdefault", "(", "'params'", ",", "{", "}", ")", "[", "'offset'", "]", "=", "0", "kwargs", "."...
42.730769
0.001761
def where(self, field_path, op_string, value): """Create a "where" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.where` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of ...
[ "def", "where", "(", "self", ",", "field_path", ",", "op_string", ",", "value", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "where", "(", "field_path", ",", "op_string", ",", "value", ")" ]
40.727273
0.002181
def log_similarity_result(logfile, result): """Log a similarity evaluation result dictionary as TSV to logfile.""" assert result['task'] == 'similarity' if not logfile: return with open(logfile, 'a') as f: f.write('\t'.join([ str(result['global_step']), result['...
[ "def", "log_similarity_result", "(", "logfile", ",", "result", ")", ":", "assert", "result", "[", "'task'", "]", "==", "'similarity'", "if", "not", "logfile", ":", "return", "with", "open", "(", "logfile", ",", "'a'", ")", "as", "f", ":", "f", ".", "wr...
29
0.001757
def sct2e(sc, sclkdp): """ Convert encoded spacecraft clock ("ticks") to ephemeris seconds past J2000 (ET). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sct2e_c.html :param sc: NAIF spacecraft ID code. :type sc: int :param sclkdp: SCLK, encoded as ticks since spacecraft clock st...
[ "def", "sct2e", "(", "sc", ",", "sclkdp", ")", ":", "sc", "=", "ctypes", ".", "c_int", "(", "sc", ")", "sclkdp", "=", "ctypes", ".", "c_double", "(", "sclkdp", ")", "et", "=", "ctypes", ".", "c_double", "(", ")", "libspice", ".", "sct2e_c", "(", ...
29.789474
0.001712
def get_goa_gene_sets(go_annotations): """Generate a list of gene sets from a collection of GO annotations. Each gene set corresponds to all genes annotated with a certain GO term. """ go_term_genes = OrderedDict() term_ids = {} for ann in go_annotations: term_ids[ann.go_term.id] = ann....
[ "def", "get_goa_gene_sets", "(", "go_annotations", ")", ":", "go_term_genes", "=", "OrderedDict", "(", ")", "term_ids", "=", "{", "}", "for", "ann", "in", "go_annotations", ":", "term_ids", "[", "ann", ".", "go_term", ".", "id", "]", "=", "ann", ".", "go...
37.04
0.002105
def default_filter_filename(filename): # type: (Optional[str]) -> Optional[str] """Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection(). """ if filename is None: return None elif filename.startswith(TOP_D...
[ "def", "default_filter_filename", "(", "filename", ")", ":", "# type: (Optional[str]) -> Optional[str]", "if", "filename", "is", "None", ":", "return", "None", "elif", "filename", ".", "startswith", "(", "TOP_DIR", ")", ":", "if", "filename", ".", "startswith", "(...
34.52381
0.001342
def lock(self, source_node): """Lock the task, source is the :class:`Node` that applies the lock.""" if self.status != self.S_INIT: raise ValueError("Trying to lock a task with status %s" % self.status) self._status = self.S_LOCKED self.history.info("Locked by node %s", sour...
[ "def", "lock", "(", "self", ",", "source_node", ")", ":", "if", "self", ".", "status", "!=", "self", ".", "S_INIT", ":", "raise", "ValueError", "(", "\"Trying to lock a task with status %s\"", "%", "self", ".", "status", ")", "self", ".", "_status", "=", "...
46
0.009146
def backoff(start, stop, count=None, factor=2.0, jitter=False): """Returns a list of geometrically-increasing floating-point numbers, suitable for usage with `exponential backoff`_. Exactly like :func:`backoff_iter`, but without the ``'repeat'`` option for *count*. See :func:`backoff_iter` for more deta...
[ "def", "backoff", "(", "start", ",", "stop", ",", "count", "=", "None", ",", "factor", "=", "2.0", ",", "jitter", "=", "False", ")", ":", "if", "count", "==", "'repeat'", ":", "raise", "ValueError", "(", "\"'repeat' supported in backoff_iter, not backoff\"", ...
44.666667
0.001462