text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def if_begin_action(self, text, loc, arg): """Code executed after recognising an if statement (if keyword)""" exshared.setpos(loc, text) if DEBUG > 0: print("IF_BEGIN:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return self.false_la...
[ "def", "if_begin_action", "(", "self", ",", "text", ",", "loc", ",", "arg", ")", ":", "exshared", ".", "setpos", "(", "loc", ",", "text", ")", "if", "DEBUG", ">", "0", ":", "print", "(", "\"IF_BEGIN:\"", ",", "arg", ")", "if", "DEBUG", "==", "2", ...
46.2
0.012739
def wait_for_operation_completion(self, operation, timeout): """Waits until the given operation is done with a given timeout in milliseconds; specify -1 for an indefinite wait. See :py:func:`wait_for_completion` for event queue considerations. in operation of type int ...
[ "def", "wait_for_operation_completion", "(", "self", ",", "operation", ",", "timeout", ")", ":", "if", "not", "isinstance", "(", "operation", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"operation can only be an instance of type baseinteger\"", ")", "if...
42.956522
0.006931
def list_and_add(a, b): """ Concatenate anything into a list. Args: a: the first thing b: the second thing Returns: list. All the things in a list. """ if not isinstance(b, list): b = [b] if not isinstance(a, list): a = [a] return a + b
[ "def", "list_and_add", "(", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "b", ",", "list", ")", ":", "b", "=", "[", "b", "]", "if", "not", "isinstance", "(", "a", ",", "list", ")", ":", "a", "=", "[", "a", "]", "return", "a", "+...
18.4375
0.003226
def vesting_balance_withdraw(self, vesting_id, amount=None, account=None, **kwargs): """ Withdraw vesting balance :param str vesting_id: Id of the vesting object :param bitshares.amount.Amount Amount: to withdraw ("all" if not provided") :param str account: (...
[ "def", "vesting_balance_withdraw", "(", "self", ",", "vesting_id", ",", "amount", "=", "None", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "ac...
39.290323
0.003205
def ws_disconnect(message): """ Channels connection close. Deregister the client """ language = message.channel_session['knocker'] gr = Group('knocker-{0}'.format(language)) gr.discard(message.reply_channel)
[ "def", "ws_disconnect", "(", "message", ")", ":", "language", "=", "message", ".", "channel_session", "[", "'knocker'", "]", "gr", "=", "Group", "(", "'knocker-{0}'", ".", "format", "(", "language", ")", ")", "gr", ".", "discard", "(", "message", ".", "r...
28.5
0.004255
def add_nodes(self, node_name_list, dataframe=False): """ Add new nodes to the network :param node_name_list: list of node names, e.g. ['a', 'b', 'c'] :param dataframe: If True, return a pandas dataframe instead of a dict. :return: A dict mapping names to SUIDs for the newly-cre...
[ "def", "add_nodes", "(", "self", ",", "node_name_list", ",", "dataframe", "=", "False", ")", ":", "res", "=", "self", ".", "session", ".", "post", "(", "self", ".", "__url", "+", "'nodes'", ",", "data", "=", "json", ".", "dumps", "(", "node_name_list",...
43.266667
0.004525
def _parse_proc_mount(self): """Parse /proc/mounts""" """ cgroup /cgroup/cpu cgroup rw,relatime,cpuacct,cpu,release_agent=/sbin/cgroup_clean 0 0 cgroup /cgroup/memory cgroup rw,relatime,memory 0 0 cgroup /cgroup/blkio cgroup rw,relatime,blkio 0 0 cgroup /cgroup/freezer c...
[ "def", "_parse_proc_mount", "(", "self", ")", ":", "\"\"\"\n cgroup /cgroup/cpu cgroup rw,relatime,cpuacct,cpu,release_agent=/sbin/cgroup_clean 0 0\n cgroup /cgroup/memory cgroup rw,relatime,memory 0 0\n cgroup /cgroup/blkio cgroup rw,relatime,blkio 0 0\n cgroup /cgroup/freez...
36.388889
0.002974
def _compile(self, source, filename): """Override jinja's compilation to stash the rendered source inside the python linecache for debugging. """ if filename == '<template>': # make a better filename filename = 'dbt-{}'.format( codecs.encode(os.ura...
[ "def", "_compile", "(", "self", ",", "source", ",", "filename", ")", ":", "if", "filename", "==", "'<template>'", ":", "# make a better filename", "filename", "=", "'dbt-{}'", ".", "format", "(", "codecs", ".", "encode", "(", "os", ".", "urandom", "(", "12...
39
0.002503
def get(self, block=True, timeout=None): """ Removes and returns an item from the queue. """ value = self._queue.get(block, timeout) if self._queue.empty(): self.clear() return value
[ "def", "get", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "value", "=", "self", ".", "_queue", ".", "get", "(", "block", ",", "timeout", ")", "if", "self", ".", "_queue", ".", "empty", "(", ")", ":", "self", "...
36.833333
0.00885
def valid_str(x: str) -> bool: """ Return ``True`` if ``x`` is a non-blank string; otherwise return ``False``. """ if isinstance(x, str) and x.strip(): return True else: return False
[ "def", "valid_str", "(", "x", ":", "str", ")", "->", "bool", ":", "if", "isinstance", "(", "x", ",", "str", ")", "and", "x", ".", "strip", "(", ")", ":", "return", "True", "else", ":", "return", "False" ]
23.777778
0.004505
def poplistitem(self, last=True): """ Pop and return a key:valuelist item comprised of a key and that key's list of values. If <last> is False, a key:valuelist item comprised of keys()[0] and its list of values is popped and returned. If <last> is True, a key:valuelist item compr...
[ "def", "poplistitem", "(", "self", ",", "last", "=", "True", ")", ":", "if", "not", "self", ".", "_items", ":", "s", "=", "'poplistitem(): %s is empty'", "%", "self", ".", "__class__", ".", "__name__", "raise", "KeyError", "(", "s", ")", "key", "=", "s...
40.961538
0.001835
def read_raw(self, length, *, error=None): """Read raw packet data.""" if length is None: length = len(self) raw = dict( packet=self._read_fileng(length), error=error or None, ) return raw
[ "def", "read_raw", "(", "self", ",", "length", ",", "*", ",", "error", "=", "None", ")", ":", "if", "length", "is", "None", ":", "length", "=", "len", "(", "self", ")", "raw", "=", "dict", "(", "packet", "=", "self", ".", "_read_fileng", "(", "le...
23.272727
0.007519
def list_operations(self, name, filter_, page_size=0, options=None): """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns ``UNIMPLEMENTED``. NOTE: the ``name`` binding below allows API services to override the binding ...
[ "def", "list_operations", "(", "self", ",", "name", ",", "filter_", ",", "page_size", "=", "0", ",", "options", "=", "None", ")", ":", "# Create the request object.", "request", "=", "operations_pb2", ".", "ListOperationsRequest", "(", "name", "=", "name", ","...
47.06
0.002082
def send(self, *fields): """ Serialize and send the given fields using the IB socket protocol. """ if not self.isConnected(): raise ConnectionError('Not connected') msg = io.StringIO() for field in fields: typ = type(field) if field in...
[ "def", "send", "(", "self", ",", "*", "fields", ")", ":", "if", "not", "self", ".", "isConnected", "(", ")", ":", "raise", "ConnectionError", "(", "'Not connected'", ")", "msg", "=", "io", ".", "StringIO", "(", ")", "for", "field", "in", "fields", ":...
36.09375
0.001686
def sparse_is_desireable(lhs, rhs): ''' Examines a pair of matrices and determines if the result of their multiplication should be sparse or not. ''' return False if len(lhs.shape) == 1: return False else: lhs_rows, lhs_cols = lhs.shape if len(rhs.shape) == 1: rhs_ro...
[ "def", "sparse_is_desireable", "(", "lhs", ",", "rhs", ")", ":", "return", "False", "if", "len", "(", "lhs", ".", "shape", ")", "==", "1", ":", "return", "False", "else", ":", "lhs_rows", ",", "lhs_cols", "=", "lhs", ".", "shape", "if", "len", "(", ...
40.171429
0.006944
def prim(G, start, weight='weight'): """ Algorithm for finding a minimum spanning tree for a weighted undirected graph. """ if len(connected_components(G)) != 1: raise GraphInsertError("Prim algorithm work with connected graph only") if start not in G.vertices: raise Grap...
[ "def", "prim", "(", "G", ",", "start", ",", "weight", "=", "'weight'", ")", ":", "if", "len", "(", "connected_components", "(", "G", ")", ")", "!=", "1", ":", "raise", "GraphInsertError", "(", "\"Prim algorithm work with connected graph only\"", ")", "if", "...
36.290323
0.000866
def display(self): """Display the recordings.""" if self.data is None: return if self.scene is not None: self.y_scrollbar_value = self.verticalScrollBar().value() self.scene.clear() self.create_chan_labels() self.create_time_labels() ...
[ "def", "display", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "if", "self", ".", "scene", "is", "not", "None", ":", "self", ".", "y_scrollbar_value", "=", "self", ".", "verticalScrollBar", "(", ")", ".", "value", "(...
33.414634
0.001418
def get_subnets(context, limit=None, page_reverse=False, sorts=['id'], marker=None, filters=None, fields=None): """Retrieve a list of subnets. The contents of the list depends on the identity of the user making the request (as indicated by the context) as well as any filters. : para...
[ "def", "get_subnets", "(", "context", ",", "limit", "=", "None", ",", "page_reverse", "=", "False", ",", "sorts", "=", "[", "'id'", "]", ",", "marker", "=", "None", ",", "filters", "=", "None", ",", "fields", "=", "None", ")", ":", "LOG", ".", "inf...
50.848485
0.000585
def to_array(self): """ Serializes this OrderInfo to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(OrderInfo, self).to_array() if self.name is not None: array['name'] = u(self.name) # py2: type unicod...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "OrderInfo", ",", "self", ")", ".", "to_array", "(", ")", "if", "self", ".", "name", "is", "not", "None", ":", "array", "[", "'name'", "]", "=", "u", "(", "self", ".", "name", ...
43.117647
0.00534
def only(iterable, default=None, too_long=None): """If *iterable* has only one item, return it. If it has zero items, return *default*. If it has more than one item, raise the exception given by *too_long*, which is ``ValueError`` by default. >>> only([], default='missing') 'missing' >>> on...
[ "def", "only", "(", "iterable", ",", "default", "=", "None", ",", "too_long", "=", "None", ")", ":", "it", "=", "iter", "(", "iterable", ")", "value", "=", "next", "(", "it", ",", "default", ")", "try", ":", "next", "(", "it", ")", "except", "Sto...
30.235294
0.000943
def fromfile(file_, threadpool_size=None, ignore_lock=False): """ Instantiate BlockStorageRAM device from a file saved in block storage format. The file_ argument can be a file object or a string that represents a filename. If called with a file ...
[ "def", "fromfile", "(", "file_", ",", "threadpool_size", "=", "None", ",", "ignore_lock", "=", "False", ")", ":", "close_file", "=", "False", "if", "not", "hasattr", "(", "file_", ",", "'read'", ")", ":", "file_", "=", "open", "(", "file_", ",", "'rb'"...
42.585366
0.003359
def _dims2shape(*dims): """Convert input dimensions to a shape.""" if not dims: raise ValueError("expected at least one dimension spec") shape = list() for dim in dims: if isinstance(dim, int): dim = (0, dim) if isinstance(dim, tuple) and len(dim) == 2: if...
[ "def", "_dims2shape", "(", "*", "dims", ")", ":", "if", "not", "dims", ":", "raise", "ValueError", "(", "\"expected at least one dimension spec\"", ")", "shape", "=", "list", "(", ")", "for", "dim", "in", "dims", ":", "if", "isinstance", "(", "dim", ",", ...
37.95
0.001285
def rerunTask(self, *args, **kwargs): """ Rerun a Resolved Task This method _reruns_ a previously resolved task, even if it was _completed_. This is useful if your task completes unsuccessfully, and you just want to run it from scratch again. This will also reset the num...
[ "def", "rerunTask", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"rerunTask\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
40.115385
0.005618
def _load_rule_file(self, filename): """Import the given rule file""" if not (os.path.exists(filename)): sys.stderr.write("rflint: %s: No such file or directory\n" % filename) return try: basename = os.path.basename(filename) (name, ext) = os.path....
[ "def", "_load_rule_file", "(", "self", ",", "filename", ")", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"rflint: %s: No such file or directory\\n\"", "%", "filename", ...
45.272727
0.007874
def as_square_array(arr): """Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged. """ arr = np.atleast_2d(arr) if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Expected square array") return arr
[ "def", "as_square_array", "(", "arr", ")", ":", "arr", "=", "np", ".", "atleast_2d", "(", "arr", ")", "if", "len", "(", "arr", ".", "shape", ")", "!=", "2", "or", "arr", ".", "shape", "[", "0", "]", "!=", "arr", ".", "shape", "[", "1", "]", "...
31.111111
0.006944
def b_rgb(self, r, g, b, text=None, fore=None, style=None): """ A chained method that sets the back color to an RGB value. Arguments: r : Red value. g : Green value. b : Blue value. text : Text to style if not building up c...
[ "def", "b_rgb", "(", "self", ",", "r", ",", "g", ",", "b", ",", "text", "=", "None", ",", "fore", "=", "None", ",", "style", "=", "None", ")", ":", "return", "self", ".", "chained", "(", "text", "=", "text", ",", "fore", "=", "fore", ",", "ba...
45.909091
0.003883
def find_exe(name, multi=False, path=None): """ Locate a command. Search your local filesystem for an executable and return the first matching file with executable permission. Args: name (str): globstr of matching filename multi (bool): if True return all matches instead of just t...
[ "def", "find_exe", "(", "name", ",", "multi", "=", "False", ",", "path", "=", "None", ")", ":", "candidates", "=", "find_path", "(", "name", ",", "path", "=", "path", ",", "exact", "=", "True", ")", "mode", "=", "os", ".", "X_OK", "|", "os", ".",...
33.4375
0.000454
def delete_object(self, cont, obj): ''' Delete a file from Swift ''' try: self.conn.delete_object(cont, obj) return True except Exception as exc: log.error('There was an error::') if hasattr(exc, 'code') and hasattr(exc, 'msg'): ...
[ "def", "delete_object", "(", "self", ",", "cont", ",", "obj", ")", ":", "try", ":", "self", ".", "conn", ".", "delete_object", "(", "cont", ",", "obj", ")", "return", "True", "except", "Exception", "as", "exc", ":", "log", ".", "error", "(", "'There ...
37.615385
0.005988
def rgChromaticity(img): ''' returns the normalized RGB space (RGB/intensity) see https://en.wikipedia.org/wiki/Rg_chromaticity ''' out = _calc(img) if img.dtype == np.uint8: out = (255 * out).astype(np.uint8) return out
[ "def", "rgChromaticity", "(", "img", ")", ":", "out", "=", "_calc", "(", "img", ")", "if", "img", ".", "dtype", "==", "np", ".", "uint8", ":", "out", "=", "(", "255", "*", "out", ")", ".", "astype", "(", "np", ".", "uint8", ")", "return", "out"...
28.444444
0.003788
def run_to_states(self): """Property for the _run_to_states field """ self.execution_engine_lock.acquire() return_value = self._run_to_states self.execution_engine_lock.release() return return_value
[ "def", "run_to_states", "(", "self", ")", ":", "self", ".", "execution_engine_lock", ".", "acquire", "(", ")", "return_value", "=", "self", ".", "_run_to_states", "self", ".", "execution_engine_lock", ".", "release", "(", ")", "return", "return_value" ]
30
0.008097
def configure(cls, name, registry_host: str="0.0.0.0", registry_port: int=4500, pubsub_host: str="0.0.0.0", pubsub_port: int=6379): """ A convenience method for providing registry and pubsub(redis) endpoints :param name: Used for process name :param registry_host: IP Address f...
[ "def", "configure", "(", "cls", ",", "name", ",", "registry_host", ":", "str", "=", "\"0.0.0.0\"", ",", "registry_port", ":", "int", "=", "4500", ",", "pubsub_host", ":", "str", "=", "\"0.0.0.0\"", ",", "pubsub_port", ":", "int", "=", "6379", ")", ":", ...
49.8125
0.01601
def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path...
[ "def", "find_on_path", "(", "importer", ",", "path_item", ",", "only", "=", "False", ")", ":", "path_item", "=", "_normalize_cached", "(", "path_item", ")", "if", "_is_unpacked_egg", "(", "path_item", ")", ":", "yield", "Distribution", ".", "from_filename", "(...
31.4
0.00103
def inverse_transform(self, X_in): """ Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue warnings when some of those cases occur. ...
[ "def", "inverse_transform", "(", "self", ",", "X_in", ")", ":", "X", "=", "X_in", ".", "copy", "(", "deep", "=", "True", ")", "# first check the type", "X", "=", "util", ".", "convert_input", "(", "X", ")", "if", "self", ".", "_dim", "is", "None", ":...
41.283019
0.006696
def pb_for_delete(document_path, option): """Make a ``Write`` protobuf for ``delete()`` methods. Args: document_path (str): A fully-qualified document path. option (optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server ...
[ "def", "pb_for_delete", "(", "document_path", ",", "option", ")", ":", "write_pb", "=", "write_pb2", ".", "Write", "(", "delete", "=", "document_path", ")", "if", "option", "is", "not", "None", ":", "option", ".", "modify_write", "(", "write_pb", ")", "ret...
34.944444
0.001548
def user_in_group(user, group): """Returns True if the given user is in given group""" if isinstance(group, Group): return user_is_superuser(user) or group in user.groups.all() elif isinstance(group, six.string_types): return user_is_superuser(user) or user.groups.filter(name=group).exists()...
[ "def", "user_in_group", "(", "user", ",", "group", ")", ":", "if", "isinstance", "(", "group", ",", "Group", ")", ":", "return", "user_is_superuser", "(", "user", ")", "or", "group", "in", "user", ".", "groups", ".", "all", "(", ")", "elif", "isinstanc...
55.857143
0.005038
def to_point(self, timestamp): """Get a Point conversion of this aggregation. :type timestamp: :class: `datetime.datetime` :param timestamp: The time to report the point as having been recorded. :rtype: :class: `opencensus.metrics.export.point.Point` :return: a :class: `opencen...
[ "def", "to_point", "(", "self", ",", "timestamp", ")", ":", "return", "point", ".", "Point", "(", "value", ".", "ValueDouble", "(", "self", ".", "sum_data", ")", ",", "timestamp", ")" ]
44
0.004049
def agg(self, aggregations): """Multiple aggregations optimized. Parameters ---------- aggregations : list of str Which aggregations to perform. Returns ------- Series Series with resulting aggregations. """ check_type(ag...
[ "def", "agg", "(", "self", ",", "aggregations", ")", ":", "check_type", "(", "aggregations", ",", "list", ")", "new_index", "=", "Index", "(", "np", ".", "array", "(", "aggregations", ",", "dtype", "=", "np", ".", "bytes_", ")", ",", "np", ".", "dtyp...
24.578947
0.006186
def match(self, name, chamber=None): """ If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-...
[ "def", "match", "(", "self", ",", "name", ",", "chamber", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_manual", "[", "chamber", "]", "[", "name", "]", "except", "KeyError", ":", "pass", "if", "chamber", "==", "'joint'", ":", "chamber",...
28
0.002301
def read_user_choice(var_name, options): """Prompt the user to choose from several options for the given variable. The first item will be returned if no input happens. :param str var_name: Variable as specified in the context :param list options: Sequence of options that are available to select from ...
[ "def", "read_user_choice", "(", "var_name", ",", "options", ")", ":", "# Please see http://click.pocoo.org/4/api/#click.prompt", "if", "not", "isinstance", "(", "options", ",", "list", ")", ":", "raise", "TypeError", "if", "not", "options", ":", "raise", "ValueError...
32.30303
0.000911
def options(argv=[]): """ A helper function that returns a dictionary of the default key-values pairs """ parser = HendrixOptionParser parsed_args = parser.parse_args(argv) return vars(parsed_args[0])
[ "def", "options", "(", "argv", "=", "[", "]", ")", ":", "parser", "=", "HendrixOptionParser", "parsed_args", "=", "parser", ".", "parse_args", "(", "argv", ")", "return", "vars", "(", "parsed_args", "[", "0", "]", ")" ]
31.142857
0.004464
def warning(self, *args) -> "Err": """ Creates a warning message """ error = self._create_err("warning", *args) print(self._errmsg(error)) return error
[ "def", "warning", "(", "self", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_create_err", "(", "\"warning\"", ",", "*", "args", ")", "print", "(", "self", ".", "_errmsg", "(", "error", ")", ")", "return", "error" ]
27.571429
0.01005
def easeInOutBack(n, s=1.70158): """A "back-in" tween function that overshoots both the start and destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine()....
[ "def", "easeInOutBack", "(", "n", ",", "s", "=", "1.70158", ")", ":", "_checkRange", "(", "n", ")", "n", "=", "n", "*", "2", "if", "n", "<", "1", ":", "s", "*=", "1.525", "return", "0.5", "*", "(", "n", "*", "n", "*", "(", "(", "s", "+", ...
29.055556
0.005556
def get_details_letssingit(song_name): ''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = ur...
[ "def", "get_details_letssingit", "(", "song_name", ")", ":", "song_name", "=", "improvename", ".", "songname", "(", "song_name", ")", "url", "=", "\"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\"", "+", "quote", "(", "song_name", ".", "enco...
31.813559
0.001034
def new_result(self, loss, budget, parameters, update_model=True): """ Function to register finished runs. Every time a run has finished, this function should be called to register it with the loss. Parameters: ----------- loss: float the loss of the paramete...
[ "def", "new_result", "(", "self", ",", "loss", ",", "budget", ",", "parameters", ",", "update_model", "=", "True", ")", ":", "if", "loss", "is", "None", ":", "# One could skip crashed results, but we decided", "# assign a +inf loss and count them as bad configurations", ...
39.940476
0.005526
def run_gevent(self): """Created the server that runs the application supplied a subclass""" from pywb.utils.geventserver import GeventServer, RequestURIWSGIHandler logging.info('Starting Gevent Server on ' + str(self.r.port)) ge = GeventServer(self.application, ...
[ "def", "run_gevent", "(", "self", ")", ":", "from", "pywb", ".", "utils", ".", "geventserver", "import", "GeventServer", ",", "RequestURIWSGIHandler", "logging", ".", "info", "(", "'Starting Gevent Server on '", "+", "str", "(", "self", ".", "r", ".", "port", ...
53.333333
0.004098
def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(...
[ "def", "steemconnect", "(", "self", ",", "accesstoken", "=", "None", ")", ":", "if", "self", ".", "sc", "is", "not", "None", ":", "return", "self", ".", "sc", "if", "accesstoken", "is", "not", "None", ":", "self", ".", "accesstoken", "=", "accesstoken"...
37.9375
0.011254
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized m...
[ "def", "serialize_model", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "response", "=", "self", ".", "_serialize_model_helper", "(", "model", ",", "field_dict", "=", "field_dict", ")", "return", "make_json_safe", "(", "response", ")" ]
38.75
0.004202
def finish_section(section, name): '''finish_section will add the header to a section, to finish the recipe take a custom command or list and return a section. Parameters ========== section: the section content, without a header name: the name of the section for the header '...
[ "def", "finish_section", "(", "section", ",", "name", ")", ":", "if", "not", "isinstance", "(", "section", ",", "list", ")", ":", "section", "=", "[", "section", "]", "header", "=", "[", "'%'", "+", "name", "]", "return", "header", "+", "section" ]
28.866667
0.006711
def _create_affine_features(output_shape, source_shape): """Generates n-dimensional homogenous coordinates for a given grid definition. `source_shape` and `output_shape` are used to define the size of the source and output signal domains, as opposed to the shape of the respective Tensors. For example, for an i...
[ "def", "_create_affine_features", "(", "output_shape", ",", "source_shape", ")", ":", "ranges", "=", "[", "np", ".", "linspace", "(", "-", "1", ",", "1", ",", "x", ",", "dtype", "=", "np", ".", "float32", ")", "for", "x", "in", "reversed", "(", "outp...
41.390244
0.005757
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.en...
[ "def", "encrypt", "(", "key", ",", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "encrypt", "(", "KeyId", "=", "key", ",", "Plaintext", "=", "message", ")", "encrypted_data", "=", "base64", ".", "encodestring", "(", "ret", ".", "get", "(",...
38.785714
0.003597
def potential_from_grid(self, grid): """ Calculate the potential at a given set of arc-second gridded coordinates. Parameters ---------- grid : grids.RegularGrid The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ eta =...
[ "def", "potential_from_grid", "(", "self", ",", "grid", ")", ":", "eta", "=", "(", "1.0", "/", "self", ".", "scale_radius", ")", "*", "self", ".", "grid_to_grid_radii", "(", "grid", ")", "+", "0j", "return", "np", ".", "real", "(", "2.0", "*", "self"...
42.454545
0.010482
def notequal(x, y): """ Return True if x != y and False otherwise. This function returns True whenever x and/or y is a NaN. """ x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return not mpfr.mpfr_equal_p(x, y)
[ "def", "notequal", "(", "x", ",", "y", ")", ":", "x", "=", "BigFloat", ".", "_implicit_convert", "(", "x", ")", "y", "=", "BigFloat", ".", "_implicit_convert", "(", "y", ")", "return", "not", "mpfr", ".", "mpfr_equal_p", "(", "x", ",", "y", ")" ]
25.1
0.003846
def add_user(username='',password='',group='', site_user=False): """ Adds the username """ if group: group = '-g %s'% group if not site_user: run('echo %s:%s > /tmp/users.txt'% (username,password)) if not site_user: sudo('useradd -m -s /bin/bash %s %s'% (group,username)) ...
[ "def", "add_user", "(", "username", "=", "''", ",", "password", "=", "''", ",", "group", "=", "''", ",", "site_user", "=", "False", ")", ":", "if", "group", ":", "group", "=", "'-g %s'", "%", "group", "if", "not", "site_user", ":", "run", "(", "'ec...
36.071429
0.021236
def p_notificationTypeClause(self, p): """notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}'""" # some MIBs have uppercase and/or lowercase id p[0] = ('notificationTypeClause',...
[ "def", "p_notificationTypeClause", "(", "self", ",", "p", ")", ":", "# some MIBs have uppercase and/or lowercase id", "p", "[", "0", "]", "=", "(", "'notificationTypeClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # NOTIFICATION_TYPE", "p", "[", "3", "...
61.555556
0.005338
def get_immoralities(self): """ Finds all the immoralities in the model A v-structure X -> Z <- Y is an immorality if there is no direct edge between X and Y . Returns ------- set: A set of all the immoralities in the model Examples --------- >>>...
[ "def", "get_immoralities", "(", "self", ")", ":", "immoralities", "=", "set", "(", ")", "for", "node", "in", "self", ".", "nodes", "(", ")", ":", "for", "parents", "in", "itertools", ".", "combinations", "(", "self", ".", "predecessors", "(", "node", "...
38.333333
0.004242
def map(self, func, iterable, chunksize=None): """A parallel equivalent of the map() builtin function. It blocks till the result is ready. This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of the...
[ "def", "map", "(", "self", ",", "func", ",", "iterable", ",", "chunksize", "=", "None", ")", ":", "return", "self", ".", "map_async", "(", "func", ",", "iterable", ",", "chunksize", ")", ".", "get", "(", ")" ]
50.666667
0.00431
def is_magic(s): """Check whether given string is a __magic__ Python identifier. :return: Whether ``s`` is a __magic__ Python identifier """ if not is_identifier(s): return False return len(s) > 4 and s.startswith('__') and s.endswith('__')
[ "def", "is_magic", "(", "s", ")", ":", "if", "not", "is_identifier", "(", "s", ")", ":", "return", "False", "return", "len", "(", "s", ")", ">", "4", "and", "s", ".", "startswith", "(", "'__'", ")", "and", "s", ".", "endswith", "(", "'__'", ")" ]
37.428571
0.003731
def guess_payload_class(self, payload): """ Handles NTPv4 extensions and MAC part (when authentication is used.) """ plen = len(payload) if plen > _NTP_AUTH_MD5_TAIL_SIZE: return NTPExtensions elif plen == _NTP_AUTH_MD5_TAIL_SIZE: return NTPAuthen...
[ "def", "guess_payload_class", "(", "self", ",", "payload", ")", ":", "plen", "=", "len", "(", "payload", ")", "if", "plen", ">", "_NTP_AUTH_MD5_TAIL_SIZE", ":", "return", "NTPExtensions", "elif", "plen", "==", "_NTP_AUTH_MD5_TAIL_SIZE", ":", "return", "NTPAuthen...
31.166667
0.005195
def find(self, path, all=False): ''' Looks for files in the app directories. ''' found = os.path.join(settings.STATIC_ROOT, path) if all: return [found] else: return found
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "found", "=", "os", ".", "path", ".", "join", "(", "settings", ".", "STATIC_ROOT", ",", "path", ")", "if", "all", ":", "return", "[", "found", "]", "else", ":", "return"...
26.111111
0.00823
def resolve_id(marked_id): """Given a marked ID, returns the original ID and its :tl:`Peer` type.""" if marked_id >= 0: return marked_id, types.PeerUser # There have been report of chat IDs being 10000xyz, which means their # marked version is -10000xyz, which in turn looks like a channel but ...
[ "def", "resolve_id", "(", "marked_id", ")", ":", "if", "marked_id", ">=", "0", ":", "return", "marked_id", ",", "types", ".", "PeerUser", "# There have been report of chat IDs being 10000xyz, which means their", "# marked version is -10000xyz, which in turn looks like a channel b...
39.071429
0.001786
def bookmarks_index_changed(self): """Update the UI when the bookmarks combobox has changed.""" index = self.bookmarks_list.currentIndex() if index >= 0: self.tool.reset() rectangle = self.bookmarks_list.itemData(index) self.tool.set_rectangle(rectangle) ...
[ "def", "bookmarks_index_changed", "(", "self", ")", ":", "index", "=", "self", ".", "bookmarks_list", ".", "currentIndex", "(", ")", "if", "index", ">=", "0", ":", "self", ".", "tool", ".", "reset", "(", ")", "rectangle", "=", "self", ".", "bookmarks_lis...
41.090909
0.004329
def _read_results(self, memory): """Read back the probed results. Returns ------- str A string of "0"s and "1"s, one for each millisecond of simulation. """ # Seek to the simulation data and read it all back memory.seek(8) bits = bitarray(endi...
[ "def", "_read_results", "(", "self", ",", "memory", ")", ":", "# Seek to the simulation data and read it all back", "memory", ".", "seek", "(", "8", ")", "bits", "=", "bitarray", "(", "endian", "=", "\"little\"", ")", "bits", ".", "frombytes", "(", "memory", "...
30.692308
0.004866
def custom_str(self, sc_expr_str_fn): """ Works like MenuNode.__str__(), but allows a custom format to be used for all symbol/choice references. See expr_str(). """ return self._menu_comment_node_str(sc_expr_str_fn) \ if self.item in _MENU_COMMENT else \ ...
[ "def", "custom_str", "(", "self", ",", "sc_expr_str_fn", ")", ":", "return", "self", ".", "_menu_comment_node_str", "(", "sc_expr_str_fn", ")", "if", "self", ".", "item", "in", "_MENU_COMMENT", "else", "self", ".", "_sym_choice_node_str", "(", "sc_expr_str_fn", ...
44.875
0.010929
def has_nans(obj): """Check if obj has any NaNs Compatible with different behavior of np.isnan, which sometimes applies over all axes (py35, py35) and sometimes does not (py34). """ nans = np.isnan(obj) while np.ndim(nans): nans = np.any(nans) return bool(nans)
[ "def", "has_nans", "(", "obj", ")", ":", "nans", "=", "np", ".", "isnan", "(", "obj", ")", "while", "np", ".", "ndim", "(", "nans", ")", ":", "nans", "=", "np", ".", "any", "(", "nans", ")", "return", "bool", "(", "nans", ")" ]
28.9
0.003356
def _sensoryComputeInferenceMode(self, anchorInput): """ Infer the location from sensory input. Activate any cells with enough active synapses to this sensory input. Deactivate all other cells. @param anchorInput (numpy array) A sensory input. This will often come from a feature-location pair layer...
[ "def", "_sensoryComputeInferenceMode", "(", "self", ",", "anchorInput", ")", ":", "if", "len", "(", "anchorInput", ")", "==", "0", ":", "return", "overlaps", "=", "self", ".", "connections", ".", "computeActivity", "(", "anchorInput", ",", "self", ".", "conn...
38.590909
0.004598
def get_tunnel_info_input_page_cursor(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info input = ET.SubElement(get_tunnel_info, "input") page_cursor = ET.SubElement(inp...
[ "def", "get_tunnel_info_input_page_cursor", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_tunnel_info", "=", "ET", ".", "Element", "(", "\"get_tunnel_info\"", ")", "config", "=", "get_tunnel_i...
39.25
0.004149
def get_changed_files(self) -> List[str]: """Get the files changed on one git branch vs another. Returns: List[str]: File paths of changed files, relative to the git repo root. """ out = shell_tools.output_of( 'git', 'diff', ...
[ "def", "get_changed_files", "(", "self", ")", "->", "List", "[", "str", "]", ":", "out", "=", "shell_tools", ".", "output_of", "(", "'git'", ",", "'diff'", ",", "'--name-only'", ",", "self", ".", "compare_commit_id", ",", "self", ".", "actual_commit_id", "...
31.9375
0.003802
def load_baseline_from_dict(cls, data): """Initializes a SecretsCollection object from dictionary. :type data: dict :param data: properly formatted dictionary to load SecretsCollection from. :rtype: SecretsCollection :raises: IOError """ result = SecretsCollecti...
[ "def", "load_baseline_from_dict", "(", "cls", ",", "data", ")", ":", "result", "=", "SecretsCollection", "(", ")", "if", "not", "all", "(", "key", "in", "data", "for", "key", "in", "(", "'plugins_used'", ",", "'results'", ",", ")", ")", ":", "raise", "...
30.147541
0.00158
def add_listener(self, listener, message_type, data=None, one_shot=False): """Add a listener that will receice incoming messages.""" lst = self._one_shots if one_shot else self._listeners if message_type not in lst: lst[message_type] = [] lst[message_type].append(Listener(l...
[ "def", "add_listener", "(", "self", ",", "listener", ",", "message_type", ",", "data", "=", "None", ",", "one_shot", "=", "False", ")", ":", "lst", "=", "self", ".", "_one_shots", "if", "one_shot", "else", "self", ".", "_listeners", "if", "message_type", ...
41
0.00597
def sample(self, n): """ Samples data into a Pandas DataFrame. Args: n: number of sampled counts. Returns: A dataframe containing sampled data. Raises: Exception if n is larger than number of rows. """ row_total_count = 0 row_counts = [] for file in self.files: w...
[ "def", "sample", "(", "self", ",", "n", ")", ":", "row_total_count", "=", "0", "row_counts", "=", "[", "]", "for", "file", "in", "self", ".", "files", ":", "with", "_util", ".", "open_local_or_gcs", "(", "file", ",", "'r'", ")", "as", "f", ":", "nu...
35.097561
0.007437
def write(self, location, text, encoding): """ Write file to disk. """ location = os.path.expanduser(location) with codecs.open(location, 'w', encoding) as f: f.write(text)
[ "def", "write", "(", "self", ",", "location", ",", "text", ",", "encoding", ")", ":", "location", "=", "os", ".", "path", ".", "expanduser", "(", "location", ")", "with", "codecs", ".", "open", "(", "location", ",", "'w'", ",", "encoding", ")", "as",...
27.25
0.008889
def can_cast_to(v: Literal, dt: str) -> bool: """ 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]." """ # TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257...
[ "def", "can_cast_to", "(", "v", ":", "Literal", ",", "dt", ":", "str", ")", "->", "bool", ":", "# TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257 is a valid XSD.byte)", "return", "v", ".", "value", "is", "not", "None", "and", "Literal", "(", "s...
52
0.009456
def delete(self, job: JobOrID) -> None: """Deletes a job. :param job: The job or job ID to delete. """ self._send_cmd(b'delete %d' % _to_id(job), b'DELETED')
[ "def", "delete", "(", "self", ",", "job", ":", "JobOrID", ")", "->", "None", ":", "self", ".", "_send_cmd", "(", "b'delete %d'", "%", "_to_id", "(", "job", ")", ",", "b'DELETED'", ")" ]
30.833333
0.010526
def show(name, root=None): ''' .. versionadded:: 2014.7.0 Show properties of one or more units/jobs or the manager root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.show <service name> ''' ret = {} out = __salt__['cmd.ru...
[ "def", "show", "(", "name", ",", "root", "=", "None", ")", ":", "ret", "=", "{", "}", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "_systemctl_cmd", "(", "'show'", ",", "name", ",", "root", "=", "root", ")", ",", "python_shell", "=", "False"...
29.59375
0.001022
def get_data(model, instance_id, kind=''): """Get instance data by id. :param model: a string, model name in rio.models :param id: an integer, instance id. :param kind: a string specified which kind of dict tranformer should be called. :return: data. """ instance = get_instance(model, insta...
[ "def", "get_data", "(", "model", ",", "instance_id", ",", "kind", "=", "''", ")", ":", "instance", "=", "get_instance", "(", "model", ",", "instance_id", ")", "if", "not", "instance", ":", "return", "return", "ins2dict", "(", "instance", ",", "kind", ")"...
27.714286
0.004988
def stageContent(self, configFiles, dateTimeFormat=None): """Parses a JSON configuration file to stage content. Args: configFiles (list): A list of JSON files on disk containing configuration data for staging content. dateTimeFormat (str): A valid date formatting...
[ "def", "stageContent", "(", "self", ",", "configFiles", ",", "dateTimeFormat", "=", "None", ")", ":", "results", "=", "None", "groups", "=", "None", "items", "=", "None", "group", "=", "None", "content", "=", "None", "contentInfo", "=", "None", "startTime"...
42.133858
0.01059
def fetch_service_config(service_name=None, service_version=None): """Fetches the service config from Google Service Management API. Args: service_name: the service name. When this argument is unspecified, this method uses the value of the "SERVICE_NAME" environment variable as the servic...
[ "def", "fetch_service_config", "(", "service_name", "=", "None", ",", "service_version", "=", "None", ")", ":", "if", "not", "service_name", ":", "service_name", "=", "_get_env_var_or_raise", "(", "_SERVICE_NAME_ENV_KEY", ")", "if", "not", "service_version", ":", ...
50.515152
0.00412
def from_shape_pixel_scale_and_sub_grid_size(cls, shape, pixel_scale, sub_grid_size): """Setup a sub-grid from a 2D array shape and pixel scale. Here, the center of every pixel on the 2D \ array gives the grid's (y,x) arc-second coordinates, where each pixel has sub-pixels specified by the \ sub...
[ "def", "from_shape_pixel_scale_and_sub_grid_size", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "sub_grid_size", ")", ":", "mask", "=", "msk", ".", "Mask", ".", "unmasked_for_shape_and_pixel_scale", "(", "shape", "=", "shape", ",", "pixel_scale", "=", "pixel...
60.333333
0.009324
def properties(self): ''' This is a lazily loaded dictionary containing the launchd runtime information of the job in question. Internally, this is retrieved using ServiceManagement.SMJobCopyDictionary(). Keep in mind that some dictionary keys are not always present (for example ...
[ "def", "properties", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_nsproperties'", ")", ":", "self", ".", "_properties", "=", "convert_NSDictionary_to_dict", "(", "self", ".", "_nsproperties", ")", "del", "self", ".", "_nsproperties", "#self._ns...
46.4375
0.003958
def update(self, shuffled=True, cohesion=100, separation=10, alignment=5, goal=20, limit=30): """ Calculates the next motion frame for the flock. """ # Shuffling the list of boids ens...
[ "def", "update", "(", "self", ",", "shuffled", "=", "True", ",", "cohesion", "=", "100", ",", "separation", "=", "10", ",", "alignment", "=", "5", ",", "goal", "=", "20", ",", "limit", "=", "30", ")", ":", "# Shuffling the list of boids ensures fluid movem...
32.84507
0.012073
def _parse_module_with_import(self, uri): """Look for functions and classes in an importable module. Parameters ---------- uri : str The name of the module to be parsed. This module needs to be importable. Returns ------- functions : list...
[ "def", "_parse_module_with_import", "(", "self", ",", "uri", ")", ":", "mod", "=", "__import__", "(", "uri", ",", "fromlist", "=", "[", "uri", "]", ")", "# find all public objects in the module.", "obj_strs", "=", "[", "obj", "for", "obj", "in", "dir", "(", ...
35.105263
0.001459
def next(self, skip=None): """ Remove the next datum from the buffer and return it. """ buffer = self._buffer popleft = buffer.popleft if skip is not None: while True: try: if not skip(buffer[0]): bre...
[ "def", "next", "(", "self", ",", "skip", "=", "None", ")", ":", "buffer", "=", "self", ".", "_buffer", "popleft", "=", "buffer", ".", "popleft", "if", "skip", "is", "not", "None", ":", "while", "True", ":", "try", ":", "if", "not", "skip", "(", "...
28.05
0.003448
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ClientExtensionFactory]], ) -> List[Extension]: """ Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return ...
[ "def", "process_extensions", "(", "headers", ":", "Headers", ",", "available_extensions", ":", "Optional", "[", "Sequence", "[", "ClientExtensionFactory", "]", "]", ",", ")", "->", "List", "[", "Extension", "]", ":", "accepted_extensions", ":", "List", "[", "E...
38.216216
0.001379
def user_sessions_delete(self, user_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/sessions#bulk-deleting-sessions" api_path = "/api/v2/users/{user_id}/sessions.json" api_path = api_path.format(user_id=user_id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "user_sessions_delete", "(", "self", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/users/{user_id}/sessions.json\"", "api_path", "=", "api_path", ".", "format", "(", "user_id", "=", "user_id", ")", "return", "self", ".", ...
62
0.009554
def get_symbol_info(self, symbol): """Return information about a symbol :param symbol: required e.g BNBBTC :type symbol: str :returns: Dict if found, None if not .. code-block:: python { "symbol": "ETHBTC", "status": "TRADING", ...
[ "def", "get_symbol_info", "(", "self", ",", "symbol", ")", ":", "res", "=", "self", ".", "_get", "(", "'exchangeInfo'", ")", "for", "item", "in", "res", "[", "'symbols'", "]", ":", "if", "item", "[", "'symbol'", "]", "==", "symbol", ".", "upper", "("...
29.833333
0.001352
def delete_record(self, domain, record): """ Deletes an existing record for a domain. """ uri = "/domains/%s/records/%s" % (utils.get_id(domain), utils.get_id(record)) resp, resp_body = self._async_call(uri, method="DELETE", error_class=exc.DomainR...
[ "def", "delete_record", "(", "self", ",", "domain", ",", "record", ")", ":", "uri", "=", "\"/domains/%s/records/%s\"", "%", "(", "utils", ".", "get_id", "(", "domain", ")", ",", "utils", ".", "get_id", "(", "record", ")", ")", "resp", ",", "resp_body", ...
41.888889
0.01039
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expressi...
[ "def", "filter_query", "(", "key", ",", "expression", ")", ":", "if", "(", "isinstance", "(", "expression", ",", "dict", ")", "and", "len", "(", "expression", ")", "==", "1", "and", "list", "(", "expression", ".", "keys", "(", ")", ")", "[", "0", "...
39.318182
0.001129
def FixmatStimuliFactory(fm, loader): """ Constructs an categories object for all image / category combinations in the fixmat. Parameters: fm: FixMat Used for extracting valid category/image combination. loader: loader Loader that accesses the stimuli for th...
[ "def", "FixmatStimuliFactory", "(", "fm", ",", "loader", ")", ":", "# Find all feature names", "features", "=", "[", "]", "if", "loader", ".", "ftrpath", ":", "assert", "os", ".", "access", "(", "loader", ".", "ftrpath", ",", "os", ".", "R_OK", ")", "fea...
41.512195
0.014351
def make_value_setter(**model_kwargs): """Creates a value-setting interceptor. This function creates an interceptor that sets values of Edward2 random variable objects. This is useful for a range of tasks, including conditioning on observed data, sampling from posterior predictive distributions, and as a bui...
[ "def", "make_value_setter", "(", "*", "*", "model_kwargs", ")", ":", "def", "set_values", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sets random variable values to its aligned value.\"\"\"", "name", "=", "kwargs", ".", "get", "(", "\...
38.715686
0.001481
def _anova(self, dv=None, between=None, detailed=False, export_filename=None): """Return one-way and two-way ANOVA.""" aov = anova(data=self, dv=dv, between=between, detailed=detailed, export_filename=export_filename) return aov
[ "def", "_anova", "(", "self", ",", "dv", "=", "None", ",", "between", "=", "None", ",", "detailed", "=", "False", ",", "export_filename", "=", "None", ")", ":", "aov", "=", "anova", "(", "data", "=", "self", ",", "dv", "=", "dv", ",", "between", ...
50.4
0.003906
def query(self, startTime=None, endTime=None, sinceServerStart=False, level="WARNING", services="*", machines="*", server="*", codes=[], processIds=[], export=False, ...
[ "def", "query", "(", "self", ",", "startTime", "=", "None", ",", "endTime", "=", "None", ",", "sinceServerStart", "=", "False", ",", "level", "=", "\"WARNING\"", ",", "services", "=", "\"*\"", ",", "machines", "=", "\"*\"", ",", "server", "=", "\"*\"", ...
37.272727
0.009844
def words(min_size, max_size = None): """ Generates a random text that consists of random number of random words separated by spaces. :param min_size: (optional) a minimum number of words. :param max_size: a maximum number of words. :return: a random text. """ ...
[ "def", "words", "(", "min_size", ",", "max_size", "=", "None", ")", ":", "max_size", "=", "max_size", "if", "max_size", "!=", "None", "else", "min_size", "result", "=", "\"\"", "count", "=", "RandomInteger", ".", "next_integer", "(", "min_size", ",", "max_...
30.555556
0.012346
def qtrim_back(self, name, size=1): """ Sets the list element at ``index`` to ``value``. An error is returned for out of range indexes. :param string name: the queue name :param int size: the max length of removed elements :return: the length of removed elements ...
[ "def", "qtrim_back", "(", "self", ",", "name", ",", "size", "=", "1", ")", ":", "size", "=", "get_positive_integer", "(", "\"size\"", ",", "size", ")", "return", "self", ".", "execute_command", "(", "'qtrim_back'", ",", "name", ",", "size", ")" ]
35.384615
0.010593
def put(self, *msgs): """Put one or more messages onto the queue. Example: >>> queue.put("my message") >>> queue.put("another message") To put messages onto the queue in bulk, which can be significantly faster if you have a large number of messages: ...
[ "def", "put", "(", "self", ",", "*", "msgs", ")", ":", "if", "self", ".", "serializer", "is", "not", "None", ":", "msgs", "=", "map", "(", "self", ".", "serializer", ".", "dumps", ",", "msgs", ")", "self", ".", "__redis", ".", "rpush", "(", "self...
37.357143
0.009328
def color_diff(rgb1, rgb2): """ Calculate distance between two RGB colors. See discussion: http://stackoverflow.com/questions/8863810/python-find-similar-colors-best-way - for basic / fast calculations, you can use dE76 but beware of its problems - for graphics arts use we recommend dE94 and perha...
[ "def", "color_diff", "(", "rgb1", ",", "rgb2", ")", ":", "import", "numpy", "as", "np", "from", "skimage", ".", "color", "import", "rgb2lab", ",", "deltaE_cmc", "rgb1", "=", "np", ".", "array", "(", "rgb1", ",", "dtype", "=", "\"float64\"", ")", ".", ...
36.888889
0.002937
def _disc_kn(clearness_index, airmass, max_airmass=12): """ Calculate Kn for `disc` Args: clearness_index : numeric airmass : numeric max_airmass : float airmass > max_airmass is set to max_airmass before being used in calculating Kn. Returns: Kn...
[ "def", "_disc_kn", "(", "clearness_index", ",", "airmass", ",", "max_airmass", "=", "12", ")", ":", "# short names for equations", "kt", "=", "clearness_index", "am", "=", "airmass", "am", "=", "min", "(", "am", ",", "max_airmass", ")", "# GH 450", "# powers o...
28.3
0.000854
def _findSwiplDar(): """ This function uses several heuristics to guess where SWI-Prolog is installed in MacOS. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # If the exec is in path (path, swiHome)...
[ "def", "_findSwiplDar", "(", ")", ":", "# If the exec is in path", "(", "path", ",", "swiHome", ")", "=", "_findSwiplFromExec", "(", ")", "if", "path", "is", "not", "None", ":", "return", "(", "path", ",", "swiHome", ")", "# If it is not, use find_library", "...
26
0.001124
def find_best_ensemble(results, options): """ Return the best performing ensemble. If the user hasn't specified a FPF, the default behavior sorts ensembles by largest enrichment factor at the smallest FPF (1 / n, where n is the total number of decoys). If the user supplied a FPF, ensembles are sorted by...
[ "def", "find_best_ensemble", "(", "results", ",", "options", ")", ":", "# We need the total number of decoys in the set to determine the number of decoys that correspond to the FPF values", "# at which enrichment factors were measured. The number of decoys are keys in the ef dictionary of each", ...
56.210526
0.009204
def draw_pl_vote(m, gamma): """ Description: Generate a Plackett-Luce vote given the model parameters. Parameters: m: number of alternatives gamma: parameters of the Plackett-Luce model """ localgamma = np.copy(gamma) # work on a copy of gamma localalts = n...
[ "def", "draw_pl_vote", "(", "m", ",", "gamma", ")", ":", "localgamma", "=", "np", ".", "copy", "(", "gamma", ")", "# work on a copy of gamma\r", "localalts", "=", "np", ".", "arange", "(", "m", ")", "# enumeration of the candidates\r", "vote", "=", "[", "]",...
38.53125
0.007911
def make_tables(job_dict): """Build and return an `astropy.table.Table' to store `JobDetails`""" col_dbkey = Column(name='dbkey', dtype=int) col_jobname = Column(name='jobname', dtype='S64') col_jobkey = Column(name='jobkey', dtype='S64') col_appname = Column(name='appname', dtyp...
[ "def", "make_tables", "(", "job_dict", ")", ":", "col_dbkey", "=", "Column", "(", "name", "=", "'dbkey'", ",", "dtype", "=", "int", ")", "col_jobname", "=", "Column", "(", "name", "=", "'jobname'", ",", "dtype", "=", "'S64'", ")", "col_jobkey", "=", "C...
49.214286
0.001423