text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _progress(bytes_received, bytes_total, worker): """Return download progress.""" worker.sig_download_progress.emit( worker.url, worker.path, bytes_received, bytes_total)
[ "def", "_progress", "(", "bytes_received", ",", "bytes_total", ",", "worker", ")", ":", "worker", ".", "sig_download_progress", ".", "emit", "(", "worker", ".", "url", ",", "worker", ".", "path", ",", "bytes_received", ",", "bytes_total", ")" ]
49.25
0.01
def lscsum(lx, epsilon=None): """ Accepts log-values as input, exponentiates them, computes the sum, then converts the sum back to log-space and returns the result. Handles underflow by rescaling so that the largest values is exactly 1.0. """ lx = numpy.asarray(lx) base = lx.max() # If the input is the...
[ "def", "lscsum", "(", "lx", ",", "epsilon", "=", "None", ")", ":", "lx", "=", "numpy", ".", "asarray", "(", "lx", ")", "base", "=", "lx", ".", "max", "(", ")", "# If the input is the log of 0's, catch this condition before we generate", "# an exception, and retur...
32.85
0.021434
def fetchmany(self, *args, **kwargs): """ Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single cursor mode. """ if not self.single_cursor_mode: raise S3MError("Calling Connection.fetchmany() while not in single cursor mode") return sel...
[ "def", "fetchmany", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "single_cursor_mode", ":", "raise", "S3MError", "(", "\"Calling Connection.fetchmany() while not in single cursor mode\"", ")", "return", "self", ".", ...
31.454545
0.008427
def train_by_stream(self, stream: StreamWrapper) -> None: """ Train the model with the given stream. :param stream: stream to train with """ self._run_epoch(stream=stream, train=True)
[ "def", "train_by_stream", "(", "self", ",", "stream", ":", "StreamWrapper", ")", "->", "None", ":", "self", ".", "_run_epoch", "(", "stream", "=", "stream", ",", "train", "=", "True", ")" ]
31.142857
0.008929
def calculate_deltat(year, month): """Calculate the difference between Terrestrial Dynamical Time (TD) and Universal Time (UT). Note: This function is not yet compatible for calculations using Numba. Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html """ plw = 'Delta...
[ "def", "calculate_deltat", "(", "year", ",", "month", ")", ":", "plw", "=", "'Deltat is unknown for years before -1999 and after 3000. '", "'Delta values will be calculated, but the calculations '", "'are not intended to be used for these years.'", "try", ":", "if", "np", ".", "a...
32.565891
0.000231
def __generate_actors(self, operator, upstream_channels, downstream_channels): """Generates one actor for each instance of the given logical operator. Attributes: operator (Operator): The logical operator metadata. upstream_channels (list): A li...
[ "def", "__generate_actors", "(", "self", ",", "operator", ",", "upstream_channels", ",", "downstream_channels", ")", ":", "num_instances", "=", "operator", ".", "num_instances", "logger", ".", "info", "(", "\"Generating {} actors of type {}...\"", ".", "format", "(", ...
45.894737
0.001684
def _request(self, method, url, headers=None, **kwargs): """ Normally the connection guarantees response times of 3 seconds on average, if there is an abnormal situation, the maximum response time is 1 minute. It is highly recommended that you set “timeouts” when you connect with PayU. ...
[ "def", "_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "_headers", "=", "{", "'Accept'", ":", "'application/json'", ",", "'Content-Type'", ":", "'application/json'", "}", "if", "headers", ...
32.16
0.008454
def prior_GP_var_inv_gamma(y_invK_y, n_y, tau_range): """ Imposing an inverse-Gamma prior onto the variance (tau^2) parameter of a Gaussian Process, which is in turn a prior imposed over an unknown function y = f(x). The inverse-Gamma prior of tau^2, tau^2 ~ invgamma(shape, scale) is...
[ "def", "prior_GP_var_inv_gamma", "(", "y_invK_y", ",", "n_y", ",", "tau_range", ")", ":", "alpha", "=", "2", "tau2", "=", "(", "y_invK_y", "+", "2", "*", "tau_range", "**", "2", ")", "/", "(", "alpha", "*", "2", "+", "2", "+", "n_y", ")", "log_ptau...
48.133333
0.000339
def permutation_arbitrary(qubit_inds, n_qubits): """ Generate the permutation matrix that permutes an arbitrary number of single-particle Hilbert spaces into adjacent positions. Transposes the qubit indices in the order they are passed to a contiguous region in the complete Hilbert space, in increa...
[ "def", "permutation_arbitrary", "(", "qubit_inds", ",", "n_qubits", ")", ":", "# Begin construction of permutation", "perm", "=", "np", ".", "eye", "(", "2", "**", "n_qubits", ",", "dtype", "=", "np", ".", "complex128", ")", "# First, sort the list and find the medi...
42.916667
0.001356
def _checkinput(zi, Mi, z=False, verbose=None): """ Check and convert any input scalar or array to numpy array """ # How many halo redshifts provided? zi = np.array(zi, ndmin=1, dtype=float) # How many halo masses provided? Mi = np.array(Mi, ndmin=1, dtype=float) # Check the input sizes for zi...
[ "def", "_checkinput", "(", "zi", ",", "Mi", ",", "z", "=", "False", ",", "verbose", "=", "None", ")", ":", "# How many halo redshifts provided?", "zi", "=", "np", ".", "array", "(", "zi", ",", "ndmin", "=", "1", ",", "dtype", "=", "float", ")", "# Ho...
38.195122
0.000623
def gen_local_driver(browser, capabilities): ''' Generate localhost drivers with desired capabilities(self.__caps) @param browser: firefox or chrome @param capabilities: A dictionary of capabilities to request when starting the browser session. @return: localhost driver '...
[ "def", "gen_local_driver", "(", "browser", ",", "capabilities", ")", ":", "if", "browser", "==", "\"firefox\"", ":", "fp", "=", "capabilities", ".", "pop", "(", "\"firefox_profile\"", ",", "None", ")", "return", "webdriver", ".", "Firefox", "(", "desired_capab...
48.6
0.012113
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Applies to the main object in the AdjointLayout. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values ...
[ "def", "dimension_values", "(", "self", ",", "dimension", ",", "expanded", "=", "True", ",", "flat", "=", "True", ")", ":", "dimension", "=", "self", ".", "get_dimension", "(", "dimension", ",", "strict", "=", "True", ")", ".", "name", "return", "self", ...
44.8
0.002186
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a mask of all values falling between the given percentiles. """ # TODO: Review whether there's a better way of handling small numbers # of columns. data = arrays[0].copy().asty...
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "# TODO: Review whether there's a better way of handling small numbers", "# of columns.", "data", "=", "arrays", "[", "0", "]", ".", "copy", "(", ")", ".", "astype...
35.074074
0.002055
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/ """ url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey type, ext, size = url_info(url) print_info(site_info, title, 'flv', size) ...
[ "def", "sina_download_by_vkey", "(", "vkey", ",", "title", "=", "None", ",", "output_dir", "=", "'.'", ",", "merge", "=", "True", ",", "info_only", "=", "False", ")", ":", "url", "=", "'http://video.sina.com/v/flvideo/%s_0.flv'", "%", "vkey", "type", ",", "e...
38.090909
0.016317
def cache_set(site, key, data): '''Sets cache data for a site. All keys related to a site are stored in a meta key. This key is per-site.''' tkey = getkey(T_ITEM, site.id, key) mkey = getkey(T_META, site.id) tmp = cache.get(mkey) longdur = 365*24*60*60 if not tmp: tmp = [tkey] cache.set(mkey, [tkey], longdu...
[ "def", "cache_set", "(", "site", ",", "key", ",", "data", ")", ":", "tkey", "=", "getkey", "(", "T_ITEM", ",", "site", ".", "id", ",", "key", ")", "mkey", "=", "getkey", "(", "T_META", ",", "site", ".", "id", ")", "tmp", "=", "cache", ".", "get...
30.5
0.031818
def im_create(self, username, **kwargs): """Create a direct message session with another user.""" return self.__call_api_post('im.create', username=username, kwargs=kwargs)
[ "def", "im_create", "(", "self", ",", "username", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'im.create'", ",", "username", "=", "username", ",", "kwargs", "=", "kwargs", ")" ]
62
0.015957
def wait_for_stable_cluster( hosts, jolokia_port, jolokia_prefix, check_interval, check_count, unhealthy_time_limit, ): """ Block the caller until the cluster can be considered stable. :param hosts: list of brokers ip addresses :type hosts: list of strings :param jolokia_por...
[ "def", "wait_for_stable_cluster", "(", "hosts", ",", "jolokia_port", ",", "jolokia_prefix", ",", "check_interval", ",", "check_count", ",", "unhealthy_time_limit", ",", ")", ":", "stable_counter", "=", "0", "max_checks", "=", "int", "(", "math", ".", "ceil", "("...
34.117647
0.001676
def handle_packets(pk): """handle_packets :param pk: data packet that kamene sends in """ log.info(("processing with pub={}") .format(pub)) # get the lowest layer eth = pk.getlayer(kamene.Ether) should_forward = False send_msg = {"data": {}, "created": rn...
[ "def", "handle_packets", "(", "pk", ")", ":", "log", ".", "info", "(", "(", "\"processing with pub={}\"", ")", ".", "format", "(", "pub", ")", ")", "# get the lowest layer", "eth", "=", "pk", ".", "getlayer", "(", "kamene", ".", "Ether", ")", "should_forwa...
26.384615
0.000937
def as_repository(resource): """ Adapts the given registered resource to its configured repository. :return: object implementing :class:`everest.repositories.interfaces.IRepository`. """ reg = get_current_registry() if IInterface in provided_by(resource): resource = reg.getUtility...
[ "def", "as_repository", "(", "resource", ")", ":", "reg", "=", "get_current_registry", "(", ")", "if", "IInterface", "in", "provided_by", "(", "resource", ")", ":", "resource", "=", "reg", ".", "getUtility", "(", "resource", ",", "name", "=", "'collection-cl...
35.818182
0.002475
def fn_var(self, a, axis=None): """ Compute the variance of an array, ignoring NaNs. :param a: The array. :return: The variance of the array. """ return numpy.nanvar(self._to_ndarray(a), axis=axis)
[ "def", "fn_var", "(", "self", ",", "a", ",", "axis", "=", "None", ")", ":", "return", "numpy", ".", "nanvar", "(", "self", ".", "_to_ndarray", "(", "a", ")", ",", "axis", "=", "axis", ")" ]
26.555556
0.008097
def get_ht_capability(cap): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n541. Positional arguments: cap -- c_uint16 Returns: List. """ answers = list() if cap & 1: answers.append('RX LDPC') if cap & 2: answers.append('HT20/HT40')...
[ "def", "get_ht_capability", "(", "cap", ")", ":", "answers", "=", "list", "(", ")", "if", "cap", "&", "1", ":", "answers", ".", "append", "(", "'RX LDPC'", ")", "if", "cap", "&", "2", ":", "answers", ".", "append", "(", "'HT20/HT40'", ")", "if", "n...
29.320755
0.000623
def mask(args): """ %prog mask data.bin samples.ids STR.ids meta.tsv OR %prog mask data.tsv meta.tsv Compute P-values based on meta and data. The `data.bin` should be the matrix containing filtered loci and the output mask.tsv will have the same dimension. """ p = OptionParser(mas...
[ "def", "mask", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mask", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "not", "in", "(", "2", ",", "4", ")", ":", "s...
29.954545
0.00147
def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain tha...
[ "def", "disable_pow_check", "(", "chain_class", ":", "Type", "[", "BaseChain", "]", ")", "->", "Type", "[", "BaseChain", "]", ":", "if", "not", "chain_class", ".", "vm_configuration", ":", "raise", "ValidationError", "(", "\"Chain class has no vm_configuration\"", ...
39
0.001854
def selection(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, minimize_starting_points, minimize_constraints_fun=None): ''' selection ''' outputs = None sys.stderr.write("[%s] Exercise \"%s\" acquisi...
[ "def", "selection", "(", "acquisition_function", ",", "samples_y_aggregation", ",", "x_bounds", ",", "x_types", ",", "regressor_gp", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "None", ")", ":", "outputs", "=", "None", "sys", ".", "stderr"...
48.928571
0.012169
async def ssh_exec(server, cmd, timeout=10, **ssh_kwargs): """Execute a command on a given server using asynchronous SSH-connection. The connection to the server is wrapped in :func:`asyncio.wait_for` and given :attr:`timeout` is applied to it. If the server is not reachable before timeout expires, :ex...
[ "async", "def", "ssh_exec", "(", "server", ",", "cmd", ",", "timeout", "=", "10", ",", "*", "*", "ssh_kwargs", ")", ":", "conn", "=", "await", "asyncio", ".", "wait_for", "(", "asyncssh", ".", "connect", "(", "server", ",", "*", "*", "ssh_kwargs", ")...
38.24
0.00102
def setup_limits(conf_file, limits_file, do_reload=True, dry_run=False, debug=False): """ Set up or update limits in the Redis database. :param conf_file: Name of the configuration file, for connecting to the Redis database. :param limits_file: Name of the XML fil...
[ "def", "setup_limits", "(", "conf_file", ",", "limits_file", ",", "do_reload", "=", "True", ",", "dry_run", "=", "False", ",", "debug", "=", "False", ")", ":", "# If dry_run is set, default debug to True", "if", "dry_run", ":", "debug", "=", "True", "# Connect t...
36.289157
0.000323
def matrix(self, x=(0, 0), y=(0, 0) , z=(0, 0)): """ Copy the ``pyny.Polyhedron`` along a 3D matrix given by the three tuples x, y, z: :param x: Number of copies and distance between them in this direction. :type x: tuple (len=2) :returns: li...
[ "def", "matrix", "(", "self", ",", "x", "=", "(", "0", ",", "0", ")", ",", "y", "=", "(", "0", ",", "0", ")", ",", "z", "=", "(", "0", ",", "0", ")", ")", ":", "polygon", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", "]", "...
40.071429
0.013937
def suggestions(self, word): """Returns a list of suggestions for a misspelled word. Args: word: The word to check. Returns: List of zero or more suggested replacements for word. """ suggestions = set(self._misspelling_dict.get(word, [])).union( set(self._misspelling_dict.get(w...
[ "def", "suggestions", "(", "self", ",", "word", ")", ":", "suggestions", "=", "set", "(", "self", ".", "_misspelling_dict", ".", "get", "(", "word", ",", "[", "]", ")", ")", ".", "union", "(", "set", "(", "self", ".", "_misspelling_dict", ".", "get",...
32.692308
0.002288
def _segmentation_guts(root, file_paths, max_partition_size): """Segment a series of file paths into TarPartition values These TarPartitions are disjoint and roughly below the prescribed size. """ # Canonicalize root to include the trailing slash, since root is # intended to be a directory anyw...
[ "def", "_segmentation_guts", "(", "root", ",", "file_paths", ",", "max_partition_size", ")", ":", "# Canonicalize root to include the trailing slash, since root is", "# intended to be a directory anyway.", "if", "not", "root", ".", "endswith", "(", "os", ".", "path", ".", ...
38.946809
0.000799
def get_modules(path, prepend_module_root=True): """Return a list containing tuples of e.g. ('test_project.utils', 'example/test_project/utils.py') """ module_root = os.path.split(path)[1] modules = list() for root, directories, filenames in os.walk(path): for filename in filenames: ...
[ "def", "get_modules", "(", "path", ",", "prepend_module_root", "=", "True", ")", ":", "module_root", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "modules", "=", "list", "(", ")", "for", "root", ",", "directories", ",", "fil...
35.054054
0.00075
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total = 0.0 for value in l: total += value return total / len(l)
[ "def", "calc_list_average", "(", "l", ")", ":", "total", "=", "0.0", "for", "value", "in", "l", ":", "total", "+=", "value", "return", "total", "/", "len", "(", "l", ")" ]
21.333333
0.01
def robinson_foulds(self, t2, attr_t1="name", attr_t2="name", unrooted_trees=False, expand_polytomies=False, polytomy_size_limit=5, skip_large_polytomies=False, correct_by_polytomy_size=False, min_support_t1=0.0, min_support_t2=0.0): ...
[ "def", "robinson_foulds", "(", "self", ",", "t2", ",", "attr_t1", "=", "\"name\"", ",", "attr_t2", "=", "\"name\"", ",", "unrooted_trees", "=", "False", ",", "expand_polytomies", "=", "False", ",", "polytomy_size_limit", "=", "5", ",", "skip_large_polytomies", ...
50.384181
0.008687
def row_to_obj(self, row, cur): """Convert a SQL row to an object supporting dict and attribute access.""" obj = tornado.util.ObjectDict() for val, desc in zip(row, cur.description): obj[desc.name] = val return obj
[ "def", "row_to_obj", "(", "self", ",", "row", ",", "cur", ")", ":", "obj", "=", "tornado", ".", "util", ".", "ObjectDict", "(", ")", "for", "val", ",", "desc", "in", "zip", "(", "row", ",", "cur", ".", "description", ")", ":", "obj", "[", "desc",...
42.166667
0.011628
def do_file_sub(self, srcpath, regexp, subst): '''Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in...
[ "def", "do_file_sub", "(", "self", ",", "srcpath", ",", "regexp", ",", "subst", ")", ":", "try", ":", "path", "=", "self", ".", "_get_dest_for_srcpath", "(", "srcpath", ")", "self", ".", "_log_debug", "(", "\"substituting scrpath '%s'\"", "%", "srcpath", ")"...
45.428571
0.001232
def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ): """ Given the hexlified 128-bit hash of a name, get the name. """ unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number ) select_query = "SELECT name FROM name_records JOIN namespaces ON name_re...
[ "def", "namedb_get_name_from_name_hash128", "(", "cur", ",", "name_hash128", ",", "block_number", ")", ":", "unexpired_query", ",", "unexpired_args", "=", "namedb_select_where_unexpired_names", "(", "block_number", ")", "select_query", "=", "\"SELECT name FROM name_records JO...
36.368421
0.016925
def calculate_bin_edges(centers): """ Calculate the edges of wavelength bins given the centers. The algorithm calculates bin edges as the midpoints between bin centers and treats the first and last bins as symmetric about their centers. Parameters ---------- centers : array_like Se...
[ "def", "calculate_bin_edges", "(", "centers", ")", ":", "centers", "=", "np", ".", "asanyarray", "(", "centers", ")", "if", "centers", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "'centers input array must be 1D.'", ")", "if", "centers", ".", "s...
27.527778
0.001949
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating a DataFrame containing evaluated data and index. See `LazyResult` Returns ------- DataFrame DataFrame with evaluated data and index. ...
[ "def", "evaluate", "(", "self", ",", "verbose", "=", "False", ",", "decode", "=", "True", ",", "passes", "=", "None", ",", "num_threads", "=", "1", ",", "apply_experimental", "=", "True", ")", ":", "evaluated_index", "=", "self", ".", "index", ".", "ev...
42.941176
0.009383
def blank_stim(self,type=None,fill=0): '''Makes a blank version of stim. If a type is not given, returned as same type as current stim. If a column stim, will fill in blanks with ``fill``''' blank = copy.copy(self) blank.name = 'Blank' if type==None: type = self.type(...
[ "def", "blank_stim", "(", "self", ",", "type", "=", "None", ",", "fill", "=", "0", ")", ":", "blank", "=", "copy", ".", "copy", "(", "self", ")", "blank", ".", "name", "=", "'Blank'", "if", "type", "==", "None", ":", "type", "=", "self", ".", "...
41.85
0.016355
def drawItem(self, item, painter, option): """ Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem> """ dataset = item.dataset() ...
[ "def", "drawItem", "(", "self", ",", "item", ",", "painter", ",", "option", ")", ":", "dataset", "=", "item", ".", "dataset", "(", ")", "painter", ".", "save", "(", ")", "painter", ".", "setRenderHint", "(", "painter", ".", "Antialiasing", ")", "pen", ...
32.545455
0.008137
def addScalarBar(self, actor=None, c=None, title="", horizontal=False, vmin=None, vmax=None): """Add a 2D scalar bar for the specified actor. If `actor` is ``None`` will add it to the last actor in ``self.actors``. .. hint:: |mesh_bands| |mesh_bands.py|_ """ return addons.addSc...
[ "def", "addScalarBar", "(", "self", ",", "actor", "=", "None", ",", "c", "=", "None", ",", "title", "=", "\"\"", ",", "horizontal", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "return", "addons", ".", "addScalarBar", ...
45.125
0.01087
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 ...
[ "def", "_handle_execute_reply", "(", "self", ",", "msg", ")", ":", "msg_id", "=", "msg", "[", "'parent_header'", "]", ".", "get", "(", "'msg_id'", ")", "info", "=", "self", ".", "_request_info", "[", "'execute'", "]", ".", "get", "(", "msg_id", ")", "i...
44
0.012146
def init_process_dut(contextlist, conf, index, args): """ Initialize process type Dut as DutProcess or DutConsole. """ if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(c...
[ "def", "init_process_dut", "(", "contextlist", ",", "conf", ",", "index", ",", "args", ")", ":", "if", "\"subtype\"", "in", "conf", "and", "conf", "[", "\"subtype\"", "]", ":", "if", "conf", "[", "\"subtype\"", "]", "!=", "\"console\"", ":", "msg", "=", ...
42.3
0.000924
def build_machine(system_info, core_resource=Cores, sdram_resource=SDRAM, sram_resource=SRAM): """Build a :py:class:`~rig.place_and_route.Machine` object from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. .. note:: Lin...
[ "def", "build_machine", "(", "system_info", ",", "core_resource", "=", "Cores", ",", "sdram_resource", "=", "SDRAM", ",", "sram_resource", "=", "SRAM", ")", ":", "try", ":", "max_cores", "=", "max", "(", "c", ".", "num_cores", "for", "c", "in", "itervalues...
45.434343
0.000218
def smart_scrubf(df,col_name,error_rate = 0): """ Scrubs from the front of an 'object' column in a DataFrame until the scrub would semantically alter the contents of the column. If only a subset of the elements in the column are scrubbed, then a boolean array indicating which elements have been scrubbe...
[ "def", "smart_scrubf", "(", "df", ",", "col_name", ",", "error_rate", "=", "0", ")", ":", "scrubbed", "=", "\"\"", "while", "True", ":", "valcounts", "=", "df", "[", "col_name", "]", ".", "str", "[", ":", "len", "(", "scrubbed", ")", "+", "1", "]",...
43.034483
0.01489
def _repr_html_(self): """ Return a html representation for a particular DataFrame. Mainly for IPython notebook. """ if self._info_repr(): buf = StringIO("") self.info(buf=buf) # need to escape the <class>, should be the first line. ...
[ "def", "_repr_html_", "(", "self", ")", ":", "if", "self", ".", "_info_repr", "(", ")", ":", "buf", "=", "StringIO", "(", "\"\"", ")", "self", ".", "info", "(", "buf", "=", "buf", ")", "# need to escape the <class>, should be the first line.", "val", "=", ...
37.304348
0.002273
def only(self, *fields): ''' Restricts the fields to be fetched when mapping. Set to `__model` to fetch all fields define in the ModelIndex. ''' s = self._clone() if len(fields) == 1 and fields[0] == '__model': s._only = '__model' else: s._only = f...
[ "def", "only", "(", "self", ",", "*", "fields", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "if", "len", "(", "fields", ")", "==", "1", "and", "fields", "[", "0", "]", "==", "'__model'", ":", "s", ".", "_only", "=", "'__model'", "else"...
33.3
0.008772
def extract_phrases(self, text): """ Given some text, extract phrases of up to 2 content words, and map their normalized form to the complete phrase. """ analysis = self.analyze(text) for pos1 in range(len(analysis)): rec1 = analysis[pos1] if not s...
[ "def", "extract_phrases", "(", "self", ",", "text", ")", ":", "analysis", "=", "self", ".", "analyze", "(", "text", ")", "for", "pos1", "in", "range", "(", "len", "(", "analysis", ")", ")", ":", "rec1", "=", "analysis", "[", "pos1", "]", "if", "not...
45.9
0.002134
def unicode_to_hex(unicode_string): """ Return a string containing the Unicode hexadecimal codepoint of each Unicode character in the given Unicode string. Return ``None`` if ``unicode_string`` is ``None``. Example:: a => U+0061 ab => U+0061 U+0062 :param str unicode_string: ...
[ "def", "unicode_to_hex", "(", "unicode_string", ")", ":", "if", "unicode_string", "is", "None", ":", "return", "None", "acc", "=", "[", "]", "for", "c", "in", "unicode_string", ":", "s", "=", "hex", "(", "ord", "(", "c", ")", ")", ".", "replace", "("...
27.809524
0.001656
def get_oligomeric_state(swiss_model_path): """Parse the oligomeric prediction in a SWISS-MODEL repository file As of 2018-02-26, works on all E. coli models. Untested on other pre-made organism models. Args: swiss_model_path (str): Path to SWISS-MODEL PDB file Returns: dict: Informat...
[ "def", "get_oligomeric_state", "(", "swiss_model_path", ")", ":", "oligo_info", "=", "{", "}", "with", "open", "(", "swiss_model_path", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'REMARK 3 MODEL...
37.823529
0.001516
def _parse_date_greek(dateString): '''Parse a string according to a Greek 8-bit date format.''' m = _greek_date_format_re.match(dateString) if not m: return wday = _greek_wdays[m.group(1)] month = _greek_months[m.group(3)] rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(min...
[ "def", "_parse_date_greek", "(", "dateString", ")", ":", "m", "=", "_greek_date_format_re", ".", "match", "(", "dateString", ")", "if", "not", "m", ":", "return", "wday", "=", "_greek_wdays", "[", "m", ".", "group", "(", "1", ")", "]", "month", "=", "_...
49.833333
0.009852
def get_module_defined_tf_var(terraform_version_opts, env_name): """Return version of Terraform requested in module options.""" if isinstance(terraform_version_opts, six.string_types): return terraform_version_opts if terraform_version_opts.get(env_name): return terraform_version_opts.get(en...
[ "def", "get_module_defined_tf_var", "(", "terraform_version_opts", ",", "env_name", ")", ":", "if", "isinstance", "(", "terraform_version_opts", ",", "six", ".", "string_types", ")", ":", "return", "terraform_version_opts", "if", "terraform_version_opts", ".", "get", ...
46.888889
0.002326
def finto(x, ii, n, null=0): ''' finto(x,ii,n) yields a vector u of length n such that u[ii] = x. Notes: * The ii index may be a tuple (as can be passed to numpy arrays' getitem method) in order to specify that the specific elements of a multidimensional output be set. In this case, the ...
[ "def", "finto", "(", "x", ",", "ii", ",", "n", ",", "null", "=", "0", ")", ":", "x", "=", "x", ".", "toarray", "(", ")", "if", "sps", ".", "issparse", "(", "x", ")", "else", "np", ".", "asarray", "(", "x", ")", "shx", "=", "x", ".", "shap...
45.36
0.011226
def _replace_star(fmt, size): """ Replace the `*` placeholder in a format string (fmt), so that struct.calcsize(fmt) is equal to the given `size` using the format following the placeholder. Raises `ValueError` if number of `*` is larger than 1. If no `*` in `fmt`, returns `fmt` without checking...
[ "def", "_replace_star", "(", "fmt", ",", "size", ")", ":", "n_stars", "=", "fmt", ".", "count", "(", "'*'", ")", "if", "n_stars", ">", "1", ":", "raise", "ValueError", "(", "\"More than one `*` in format (%s).\"", "%", "fmt", ")", "if", "n_stars", ":", "...
26.777778
0.001335
def read_folder(folder): """Read all files of `folder` and return a list of HandwrittenData objects. Parameters ---------- folder : string Path to a folder Returns ------- list : A list of all .ink files in the given folder. """ recordings = [] for filename ...
[ "def", "read_folder", "(", "folder", ")", ":", "recordings", "=", "[", "]", "for", "filename", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "folder", ",", "'*.ink'", ")", ")", ":", "recording", "=", "parse_scg_ink_file", "(", ...
23.894737
0.002119
def iterscan(self, match="*", count=1000): """ Much slower than iter(), but much more memory efficient if k/v's retrieved are one-offs @match: matches member names in the sorted set @count: the user specified the amount of work that should be done at every ca...
[ "def", "iterscan", "(", "self", ",", "match", "=", "\"*\"", ",", "count", "=", "1000", ")", ":", "if", "self", ".", "serialized", ":", "return", "map", "(", "lambda", "x", ":", "(", "self", ".", "_loads", "(", "x", "[", "0", "]", ")", ",", "sel...
42.3
0.002312
def substitute(s, objlist=(), globals={}, locals={}): """Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also ...
[ "def", "substitute", "(", "s", ",", "objlist", "=", "(", ")", ",", "globals", "=", "{", "}", ",", "locals", "=", "{", "}", ")", ":", "# Get the local variables at the caller level if not given.", "if", "not", "locals", ":", "locals", "=", "getlocals", "(", ...
36.772414
0.000183
def __vDecodeDIGICAMControl(self, mCommand_Long): '''Session''' if mCommand_Long.param1 != 0: print ("Session = %d" % mCommand_Long.param1) '''Zooming Step Value''' if mCommand_Long.param2 != 0: print ("Zooming Step = %d" % mCommand_Long.param2) ...
[ "def", "__vDecodeDIGICAMControl", "(", "self", ",", "mCommand_Long", ")", ":", "if", "mCommand_Long", ".", "param1", "!=", "0", ":", "print", "(", "\"Session = %d\"", "%", "mCommand_Long", ".", "param1", ")", "'''Zooming Step Value'''", "if", "mCommand_Long", ".",...
35.178571
0.011858
def generate_confusables(): """Generates the confusables JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool """ url = 'ftp://ftp.unicode.org/Public/security/latest/confusables.txt' file = get(url) confusables_matrix = defaultdict(list) ...
[ "def", "generate_confusables", "(", ")", ":", "url", "=", "'ftp://ftp.unicode.org/Public/security/latest/confusables.txt'", "file", "=", "get", "(", "url", ")", "confusables_matrix", "=", "defaultdict", "(", "list", ")", "match", "=", "re", ".", "compile", "(", "r...
33.538462
0.001115
def add(self, crash): """ Adds a new crash to the container. If the crash appears to be already known, it's ignored. @see: L{Crash.key} @type crash: L{Crash} @param crash: Crash object to add. """ if crash not in self: key = crash.key() ...
[ "def", "add", "(", "self", ",", "crash", ")", ":", "if", "crash", "not", "in", "self", ":", "key", "=", "crash", ".", "key", "(", ")", "skey", "=", "self", ".", "marshall_key", "(", "key", ")", "data", "=", "self", ".", "marshall_value", "(", "cr...
29.866667
0.010823
def start(self): """ Starts the partition service. """ self.logger.debug("Starting partition service", extra=self._logger_extras) def partition_updater(): self._do_refresh() self.timer = self._client.reactor.add_timer(PARTITION_UPDATE_INTERVAL, partition_...
[ "def", "start", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Starting partition service\"", ",", "extra", "=", "self", ".", "_logger_extras", ")", "def", "partition_updater", "(", ")", ":", "self", ".", "_do_refresh", "(", ")", "self...
37.909091
0.01171
def as_processed_list(func): """ A decorator used to return a JSON response of a list of model objects. It differs from `as_list` in that it accepts a variety of querying parameters and can use them to filter and modify the results. It expects the decorated function to return either Model Cl...
[ "def", "as_processed_list", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func_argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "func_args", "=", "func_argsp...
39.75
0.000682
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]: """Convert a schedule into an iterable of proto dictionaries. Args: schedule: The schedule to convert to a proto dict. Must contain only gates that can be cast to xmon gates. Yields: A proto dictionary correspon...
[ "def", "schedule_to_proto_dicts", "(", "schedule", ":", "Schedule", ")", "->", "Iterable", "[", "Dict", "]", ":", "last_time_picos", "=", "None", "# type: Optional[int]", "for", "so", "in", "schedule", ".", "scheduled_operations", ":", "op", "=", "gate_to_proto_di...
38
0.001167
def get_as_datadict(self): """ Get data of this object as a data dictionary. Used by websocket service. """ d = super().get_as_datadict() d.update(dict(status=self.status, data_type=self.data_type, editable=self.editable)) return d
[ "def", "get_as_datadict", "(", "self", ")", ":", "d", "=", "super", "(", ")", ".", "get_as_datadict", "(", ")", "d", ".", "update", "(", "dict", "(", "status", "=", "self", ".", "status", ",", "data_type", "=", "self", ".", "data_type", ",", "editabl...
39.571429
0.014134
def get(self, sid): """ Constructs a TaskContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task.TaskContext :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskContext """ return TaskContext(self._version, workspace_sid=self._solution['w...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "TaskContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
33.7
0.008671
def delete_model(self): """Delete the SageMaker model backing this pipeline model. This does not delete the list of SageMaker models used in multiple containers to build the inference pipeline. """ if self.name is None: raise ValueError('The SageMaker model must be created ...
[ "def", "delete_model", "(", "self", ")", ":", "if", "self", ".", "name", "is", "None", ":", "raise", "ValueError", "(", "'The SageMaker model must be created before attempting to delete.'", ")", "self", ".", "sagemaker_session", ".", "delete_model", "(", "self", "."...
39.7
0.009852
def require_user(wa, email): """Require that the user has an account""" cache_key = 'user-list' try: # Get the cached value data = userCache[cache_key] except KeyError: # If we hit a key error above, indicating that # we couldn't find the key, we'll simply re-request ...
[ "def", "require_user", "(", "wa", ",", "email", ")", ":", "cache_key", "=", "'user-list'", "try", ":", "# Get the cached value", "data", "=", "userCache", "[", "cache_key", "]", "except", "KeyError", ":", "# If we hit a key error above, indicating that", "# we couldn'...
32.714286
0.002123
def put(self, tpart): """Upload a tar volume Blocks if there is too much work outstanding already, and raise errors of previously submitted greenlets that die unexpectedly. """ if self.closed: raise UserCritical(msg='attempt to upload tar after closing', ...
[ "def", "put", "(", "self", ",", "tpart", ")", ":", "if", "self", ".", "closed", ":", "raise", "UserCritical", "(", "msg", "=", "'attempt to upload tar after closing'", ",", "hint", "=", "'report a bug'", ")", "while", "True", ":", "too_many", "=", "(", "se...
40.697674
0.001116
def fishrot(k=20, n=100, dec=0, inc=90, di_block=True): """ Generates Fisher distributed unit vectors from a specified distribution using the pmag.py fshdev and dodirot functions. Parameters ---------- k : kappa precision parameter (default is 20) n : number of vectors to determine (default...
[ "def", "fishrot", "(", "k", "=", "20", ",", "n", "=", "100", ",", "dec", "=", "0", ",", "inc", "=", "90", ",", "di_block", "=", "True", ")", ":", "directions", "=", "[", "]", "declinations", "=", "[", "]", "inclinations", "=", "[", "]", "if", ...
35.863636
0.001851
def AddCustomJsonEnumMapping(enum_type, python_name, json_name, package=None): # pylint: disable=unused-argument """Add a custom wire encoding for a given enum value. This is primarily used in generated code, to handle enum values which happen to be Python keywords. Args:...
[ "def", "AddCustomJsonEnumMapping", "(", "enum_type", ",", "python_name", ",", "json_name", ",", "package", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "not", "issubclass", "(", "enum_type", ",", "messages", ".", "Enum", ")", ":", "raise", "...
48.772727
0.000914
def _is_import_binding(node, name, package=None): """ Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples. """ if node.type == syms.import_name and not package: imp = node.children[1] if imp.typ...
[ "def", "_is_import_binding", "(", "node", ",", "name", ",", "package", "=", "None", ")", ":", "if", "node", ".", "type", "==", "syms", ".", "import_name", "and", "not", "package", ":", "imp", "=", "node", ".", "children", "[", "1", "]", "if", "imp", ...
42.25
0.000578
def param_set(self, param_name, _value=None, **kwargs): """ Setting parameter. if _value, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _value: optional value :param kwargs: each extra kwarg will be put in the value if structur...
[ "def", "param_set", "(", "self", ",", "param_name", ",", "_value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "#changing unicode to string ( testing stability of multiprocess debugging )", "if", "isinstance", "(", "param_name", ",", "unicode", ")", ":", "param_...
41.391304
0.008214
def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} form...
[ "def", "_format_kwargs", "(", "func", ")", ":", "formats", "=", "{", "}", "formats", "[", "'blk'", "]", "=", "[", "\"blank\"", "]", "formats", "[", "'dft'", "]", "=", "[", "\"default\"", "]", "formats", "[", "'hdr'", "]", "=", "[", "\"header\"", "]",...
35.772727
0.002475
def vreenqueue(item_f, *args, **kwargs): '''Enqueue the contents of a file, or file-like object, FSQWorkItem, file-descriptor or the contents of a files queues at an address (e.g. '/my/file') queue with arbitrary arguments from one queue to other queues, reenqueue is to vreenqueue what printf i...
[ "def", "vreenqueue", "(", "item_f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "item_id", "=", "None", "src_queue", "=", "kwargs", ".", "pop", "(", "'src_queue'", ",", "None", ")", "link", "=", "kwargs", ".", "pop", "(", "'link'", ",", "F...
44.903704
0.001453
def _make_sql_params(self,kw): """Make a list of strings to pass to an SQL statement from the dictionary kw with Python types""" vals = [] for k,v in kw.iteritems(): vals.append('%s=%s' %(k,self._conv(v))) return vals
[ "def", "_make_sql_params", "(", "self", ",", "kw", ")", ":", "vals", "=", "[", "]", "for", "k", ",", "v", "in", "kw", ".", "iteritems", "(", ")", ":", "vals", ".", "append", "(", "'%s=%s'", "%", "(", "k", ",", "self", ".", "_conv", "(", "v", ...
38.428571
0.021818
def rouge_2_fscore(logits, labels): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: ...
[ "def", "rouge_2_fscore", "(", "logits", ",", "labels", ")", ":", "predictions", "=", "tf", ".", "to_int32", "(", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "-", "1", ")", ")", "# TODO: Look into removing use of py_func", "rouge_2_f_score", "=", "t...
33.529412
0.010239
def ssh(name): """Executes the given command""" env.host_string = lib.get_env_host_string() print("\nExecuting the command '{0}' on node {1}...".format( name, env.host_string)) # Execute remotely using either the sudo or the run fabric functions with settings(hide("warnings"), warn_only=Tr...
[ "def", "ssh", "(", "name", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "print", "(", "\"\\nExecuting the command '{0}' on node {1}...\"", ".", "format", "(", "name", ",", "env", ".", "host_string", ")", ")", "# Execut...
37.636364
0.002358
def _decode(self, s, encode_nominal=False, matrix_type=DENSE): '''Do the job the ``encode``.''' # Make sure this method is idempotent self._current_line = 0 # If string, convert to a list of lines if isinstance(s, basestring): s = s.strip('\r\n ').replace('\r\n', '\...
[ "def", "_decode", "(", "self", ",", "s", ",", "encode_nominal", "=", "False", ",", "matrix_type", "=", "DENSE", ")", ":", "# Make sure this method is idempotent", "self", ".", "_current_line", "=", "0", "# If string, convert to a list of lines", "if", "isinstance", ...
36.858491
0.000748
def _annotated_unpack_infer(stmt, context=None): """ Recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements. Returns an iterator which yields tuples in the format ('original node', 'infered node'). """ if isinstance(stm...
[ "def", "_annotated_unpack_infer", "(", "stmt", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "stmt", ",", "(", "astroid", ".", "List", ",", "astroid", ".", "Tuple", ")", ")", ":", "for", "elt", "in", "stmt", ".", "elts", ":", "infer...
38.882353
0.001477
def decrypt(key, ciphertext): """Decrypt Simple Substitution enciphered ``ciphertext`` using ``key``. Example: >>> decrypt("PQSTUVWXYZCODEBRAKINGFHJLM", "XUOOB") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted...
[ "def", "decrypt", "(", "key", ",", "ciphertext", ")", ":", "# TODO: Is it worth keeping this here I should I only accept strings?", "key", "=", "''", ".", "join", "(", "key", ")", "alphabet", "=", "string", ".", "ascii_letters", "cipher_alphabet", "=", "key", ".", ...
30.315789
0.001684
def learn(self, bottomUpInput): """ Parameters: -------------------------------------------- input: Current bottom-up input retval: ? """ self.lrnIterationIdx = self.lrnIterationIdx + 1 self.iterationIdx = self.iterationIdx + 1 if self.verbosity >= 3: print "\n===...
[ "def", "learn", "(", "self", ",", "bottomUpInput", ")", ":", "self", ".", "lrnIterationIdx", "=", "self", ".", "lrnIterationIdx", "+", "1", "self", ".", "iterationIdx", "=", "self", ".", "iterationIdx", "+", "1", "if", "self", ".", "verbosity", ">=", "3"...
39.857955
0.011683
def lists(self, column, key=None): """ Get a list with the values of a given column :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: list or dict """ ...
[ "def", "lists", "(", "self", ",", "column", ",", "key", "=", "None", ")", ":", "results", "=", "self", ".", "_query", ".", "lists", "(", "column", ",", "key", ")", "if", "self", ".", "_model", ".", "has_get_mutator", "(", "column", ")", ":", "if", ...
28.928571
0.002389
def calculate(self, **state): """ Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param x: [mole fraction] composition dictionary , e.g. {'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25} :returns: [Pa.s] dyn...
[ "def", "calculate", "(", "self", ",", "*", "*", "state", ")", ":", "def", "phi", "(", "i", ",", "j", ",", "mu_i", ",", "mu_j", ")", ":", "M_i", "=", "M", "(", "i", ")", "M_j", "=", "M", "(", "j", ")", "result", "=", "(", "1.0", "+", "(", ...
28.4375
0.002125
def query(options, collection_name, num_to_skip, num_to_return, query, field_selector=None): """Get a **query** message. """ data = struct.pack("<I", options) data += bson._make_c_string(collection_name) data += struct.pack("<i", num_to_skip) data += struct.pack("<i", num_to_return) ...
[ "def", "query", "(", "options", ",", "collection_name", ",", "num_to_skip", ",", "num_to_return", ",", "query", ",", "field_selector", "=", "None", ")", ":", "data", "=", "struct", ".", "pack", "(", "\"<I\"", ",", "options", ")", "data", "+=", "bson", "....
38.666667
0.002105
def WriteClientSnapshotHistory(self, clients): """Writes the full history for a particular client.""" if clients[0].client_id not in self.metadatas: raise db.UnknownClientError(clients[0].client_id) for client in clients: startup_info = client.startup_info client.startup_info = None ...
[ "def", "WriteClientSnapshotHistory", "(", "self", ",", "clients", ")", ":", "if", "clients", "[", "0", "]", ".", "client_id", "not", "in", "self", ".", "metadatas", ":", "raise", "db", ".", "UnknownClientError", "(", "clients", "[", "0", "]", ".", "clien...
38.6875
0.014196
def set_default(font=DEFAULT_FONT, chr_ignore=True, filename="art", print_status=True): """ Change text2art, tprint and tsave default values. :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :param filename: outpu...
[ "def", "set_default", "(", "font", "=", "DEFAULT_FONT", ",", "chr_ignore", "=", "True", ",", "filename", "=", "\"art\"", ",", "print_status", "=", "True", ")", ":", "if", "isinstance", "(", "font", ",", "str", ")", "is", "False", ":", "raise", "artError"...
37.269231
0.001006
def to_docx( self, filename=None, input_dataset=True, summary_table=True, recommendation_details=True, recommended_model=True, all_models=False, ): """ Write batch sessions to a Word file. Parameters ---------- filename...
[ "def", "to_docx", "(", "self", ",", "filename", "=", "None", ",", "input_dataset", "=", "True", ",", "summary_table", "=", "True", ",", "recommendation_details", "=", "True", ",", "recommended_model", "=", "True", ",", "all_models", "=", "False", ",", ")", ...
26.44
0.002188
def _add_element(self, cls, **kwargs): """Add an element.""" # Convert stylename strings to actual style elements. kwargs = self._replace_stylename(kwargs) el = cls(**kwargs) self._doc.text.addElement(el)
[ "def", "_add_element", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "# Convert stylename strings to actual style elements.", "kwargs", "=", "self", ".", "_replace_stylename", "(", "kwargs", ")", "el", "=", "cls", "(", "*", "*", "kwargs", ")", ...
39.833333
0.008197
def create_AWS_request_url(base_url, argd, _amazon_secret_access_key, _timestamp=None): """ Create a signed AWS (Amazon Web Service) request URL corresponding to the given parameters. Example: >> create_AWS_request_url("http://ecs.amazon.com/onca/xml", ...
[ "def", "create_AWS_request_url", "(", "base_url", ",", "argd", ",", "_amazon_secret_access_key", ",", "_timestamp", "=", "None", ")", ":", "# First define a few util functions", "def", "get_AWS_signature", "(", "argd", ",", "_amazon_secret_access_key", ",", "method", "=...
36.84
0.001269
def make_plot(fnames=[], name=[], dims=None, plot_method=None, output=None, project=None, engine=None, formatoptions=None, tight=False, rc_file=None, encoding=None, enable_post=False, seaborn_style=None, output_project=None, concat_dim=get_default_value(xr.open_mf...
[ "def", "make_plot", "(", "fnames", "=", "[", "]", ",", "name", "=", "[", "]", ",", "dims", "=", "None", ",", "plot_method", "=", "None", ",", "output", "=", "None", ",", "project", "=", "None", ",", "engine", "=", "None", ",", "formatoptions", "=",...
42.807339
0.000628
def reduce_value(cls, value): """Cleans the value by either compressing it if it is a string, or reducing it if it is a number. """ if isinstance(value, str): return to_compressed_string(value) elif isinstance(value, bool): return value elif isinstance(value, Number): return re...
[ "def", "reduce_value", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "to_compressed_string", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "elif", ...
29.666667
0.016349
def _prepare_model_data(packages, linked, pip=None, private_packages=None): """Prepare model data for the packages table model.""" pip = pip if pip else [] private_packages = private_packages if private_packages else {} data = [] if private_packages ...
[ "def", "_prepare_model_data", "(", "packages", ",", "linked", ",", "pip", "=", "None", ",", "private_packages", "=", "None", ")", ":", "pip", "=", "pip", "if", "pip", "else", "[", "]", "private_packages", "=", "private_packages", "if", "private_packages", "e...
40.770833
0.000748
def find_files(self): """ Gets modules routes.py and converts to module imports """ modules = self.evernode_app.get_modules() root_path = sys.path[0] if self.evernode_app.root_path is None \ else self.evernode_app.root_path dirs = [dict( dir=os.path.join(roo...
[ "def", "find_files", "(", "self", ")", ":", "modules", "=", "self", ".", "evernode_app", ".", "get_modules", "(", ")", "root_path", "=", "sys", ".", "path", "[", "0", "]", "if", "self", ".", "evernode_app", ".", "root_path", "is", "None", "else", "self...
46.365854
0.00103
def to_csv_path(graph: BELGraph, path: str, sep: Optional[str] = None) -> None: """Write the graph as a tab-separated edge list to a file at the given path.""" with open(path, 'w') as file: to_csv(graph, file, sep=sep)
[ "def", "to_csv_path", "(", "graph", ":", "BELGraph", ",", "path", ":", "str", ",", "sep", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "file", ":", "to_csv", "(", "grap...
57.75
0.008547
def get_sequence_properties(self, clean_seq=False, representatives_only=True): """Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences. Results are stored in the protein's respective SeqProp objects at ``.annotations`` Args: repres...
[ "def", "get_sequence_properties", "(", "self", ",", "clean_seq", "=", "False", ",", "representatives_only", "=", "True", ")", ":", "for", "g", "in", "tqdm", "(", "self", ".", "genes", ")", ":", "g", ".", "protein", ".", "get_sequence_properties", "(", "cle...
55.2
0.010695
def export_collada(mesh, **kwargs): """ Export a mesh or a list of meshes as a COLLADA .dae file. Parameters ----------- mesh: Trimesh object or list of Trimesh objects The mesh(es) to export. Returns ----------- export: str, string of COLLADA format output """ meshes =...
[ "def", "export_collada", "(", "mesh", ",", "*", "*", "kwargs", ")", ":", "meshes", "=", "mesh", "if", "not", "isinstance", "(", "mesh", ",", "(", "list", ",", "tuple", ",", "set", ",", "np", ".", "ndarray", ")", ")", ":", "meshes", "=", "[", "mes...
34.25641
0.000728
def round_edge_screen(alpha, Re, angle=0): r'''Returns the loss coefficient for a round edged wire screen or bar screen, as shown in [1]_. Angle of inclination may be specified as well. Parameters ---------- alpha : float Fraction of screen open to flow [-] Re : float Reynolds n...
[ "def", "round_edge_screen", "(", "alpha", ",", "Re", ",", "angle", "=", "0", ")", ":", "beta", "=", "interp", "(", "Re", ",", "round_Res", ",", "round_betas", ")", "alpha2", "=", "alpha", "*", "alpha", "K", "=", "beta", "*", "(", "1.0", "-", "alpha...
28.979167
0.000695
def smoothed(mesh, angle): """ Return a non- watertight version of the mesh which will render nicely with smooth shading by disconnecting faces at sharp angles to each other. Parameters --------- mesh : trimesh.Trimesh Source geometry angle : float Angle in radians, adjacent...
[ "def", "smoothed", "(", "mesh", ",", "angle", ")", ":", "# if the mesh has no adjacent faces return a copy", "if", "len", "(", "mesh", ".", "face_adjacency", ")", "==", "0", ":", "return", "mesh", ".", "copy", "(", ")", "# face pairs below angle threshold", "angle...
31.944444
0.000844
def usearch_fasta_sort_from_filepath( fasta_filepath, output_filepath=None, log_name="sortlen.log", HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None): """Generates sorted fasta file via usearch --mergesort. fasta...
[ "def", "usearch_fasta_sort_from_filepath", "(", "fasta_filepath", ",", "output_filepath", "=", "None", ",", "log_name", "=", "\"sortlen.log\"", ",", "HALT_EXEC", "=", "False", ",", "save_intermediate_files", "=", "False", ",", "remove_usearch_logs", "=", "False", ",",...
30.685714
0.000903
def get_marker_style(line): """Get the style dictionary for matplotlib marker objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['facecolor'] = color_to_hex(line.get_markerfacecolor()) style['edgecolor'] = color_to_hex(line.get_ma...
[ "def", "get_marker_style", "(", "line", ")", ":", "style", "=", "{", "}", "style", "[", "'alpha'", "]", "=", "line", ".", "get_alpha", "(", ")", "if", "style", "[", "'alpha'", "]", "is", "None", ":", "style", "[", "'alpha'", "]", "=", "1", "style",...
39.095238
0.001189
def xarrayfunc(func): """Make a function compatible with xarray.DataArray. This function is intended to be used as a decorator like:: >>> @dc.xarrayfunc >>> def func(array): ... # do something ... return newarray >>> >>> result = func(array) Args: ...
[ "def", "xarrayfunc", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "any", "(", "isinstance", "(", "arg", ",", "xr", ".", "DataArray", ")", "for", "arg", "in", ...
28.029412
0.001014