text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def delta(self, signature): "Generates delta for remote file via API using local file's signature." return self.api.post('path/sync/delta', self.path, signature=signature)
[ "def", "delta", "(", "self", ",", "signature", ")", ":", "return", "self", ".", "api", ".", "post", "(", "'path/sync/delta'", ",", "self", ".", "path", ",", "signature", "=", "signature", ")" ]
61.666667
30.333333
def import_file(self, ): """Import a file :returns: None :rtype: None :raises: NotImplementedError """ tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.import_file(tfi)
[ "def", "import_file", "(", "self", ",", ")", ":", "tfi", "=", "self", ".", "get_taskfileinfo_selection", "(", ")", "if", "tfi", ":", "self", ".", "reftrack", ".", "import_file", "(", "tfi", ")" ]
24.1
13.2
def delete_table(self, table_name): """ Deletes the table and all of it's data. After this request the table will be in the DELETING state until DynamoDB completes the delete operation. :type table_name: str :param table_name: The name of the table to delete. ""...
[ "def", "delete_table", "(", "self", ",", "table_name", ")", ":", "data", "=", "{", "'TableName'", ":", "table_name", "}", "json_input", "=", "json", ".", "dumps", "(", "data", ")", "return", "self", ".", "make_request", "(", "'DeleteTable'", ",", "json_inp...
37.416667
12.25
def names_singleton(self): """Returns True if this URI names a file or if URI represents input/output stream. """ if self.stream: return True else: return os.path.isfile(self.object_name)
[ "def", "names_singleton", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "return", "True", "else", ":", "return", "os", ".", "path", ".", "isfile", "(", "self", ".", "object_name", ")" ]
30.5
11.5
def module(self): """The module in which the Template is defined. Python equivalent of the CLIPS deftemplate-module command. """ modname = ffi.string(lib.EnvDeftemplateModule(self._env, self._tpl)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self...
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDeftemplateModule", "(", "self", ".", "_env", ",", "self", ".", "_tpl", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "...
32.8
22.8
def centred_timegrid(cls, simulationstep): """Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step. >>> from hydpy.core.timetools import TOY >>> TOY.centred_timegrid('1d') Timegrid('2000-01-01 12:00:00', '200...
[ "def", "centred_timegrid", "(", "cls", ",", "simulationstep", ")", ":", "simulationstep", "=", "Period", "(", "simulationstep", ")", "return", "Timegrid", "(", "cls", ".", "_STARTDATE", "+", "simulationstep", "/", "2", ",", "cls", ".", "_ENDDATE", "+", "simu...
36.533333
8.6
def start_recording(recorded_events_queue=None): """ Starts recording all keyboard events into a global variable, or the given queue if any. Returns the queue of events and the hooked function. Use `stop_recording()` or `unhook(hooked_function)` to stop. """ recorded_events_queue = recorded_eve...
[ "def", "start_recording", "(", "recorded_events_queue", "=", "None", ")", ":", "recorded_events_queue", "=", "recorded_events_queue", "or", "_queue", ".", "Queue", "(", ")", "global", "_recording", "_recording", "=", "(", "recorded_events_queue", ",", "hook", "(", ...
41.363636
21.545455
def get_value(self, key, args, kwargs): """Get value only from mapping and possibly convert key to string.""" if (self.tolerant and not isinstance(key, basestring) and key not in kwargs): key = str(key) return kwargs[key]
[ "def", "get_value", "(", "self", ",", "key", ",", "args", ",", "kwargs", ")", ":", "if", "(", "self", ".", "tolerant", "and", "not", "isinstance", "(", "key", ",", "basestring", ")", "and", "key", "not", "in", "kwargs", ")", ":", "key", "=", "str",...
35.375
12
def _build_autoload_details(self, autoload_data, relative_path=""): """ Build autoload details :param autoload_data: dict: :param relative_path: str: full relative path of current autoload resource """ self._autoload_details.attributes.extend([AutoLoadAttribute(relative_address...
[ "def", "_build_autoload_details", "(", "self", ",", "autoload_data", ",", "relative_path", "=", "\"\"", ")", ":", "self", ".", "_autoload_details", ".", "attributes", ".", "extend", "(", "[", "AutoLoadAttribute", "(", "relative_address", "=", "relative_path", ",",...
67.857143
45.238095
def save(self, *args, **kwargs): """ Before saving, get publication's PubMed metadata if publication is not already in database or if 'redo_query' is True. """ if self.no_query: if not self.pk or self.pmid > 0: try: pmid_min = Publi...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "no_query", ":", "if", "not", "self", ".", "pk", "or", "self", ".", "pmid", ">", "0", ":", "try", ":", "pmid_min", "=", "Publication", ".", "obj...
36.5
15.875
def proto_ts_from_datetime_str(dt): """Converts string datetime in ISO format to protobuf timestamp. :type dt: str :param dt: string with datetime in ISO format :rtype: :class:`~google.protobuf.timestamp_pb2.Timestamp` :returns: protobuf timestamp """ ts = Timestamp() if (dt is not None...
[ "def", "proto_ts_from_datetime_str", "(", "dt", ")", ":", "ts", "=", "Timestamp", "(", ")", "if", "(", "dt", "is", "not", "None", ")", ":", "try", ":", "ts", ".", "FromJsonString", "(", "dt", ")", "except", "ParseError", ":", "pass", "return", "ts" ]
27.533333
16.133333
def read_config(config_file): '''Reads the ~/.aadbookrc and any authentication data returns the configuration as a dictionary. ''' config = Storage({ # Default values 'cache_filename': '~/.aadbook_cache', 'auth_db_filename': '~/.aadbook_auth.json', 'cache_expiry_hours': '24'}) ...
[ "def", "read_config", "(", "config_file", ")", ":", "config", "=", "Storage", "(", "{", "# Default values", "'cache_filename'", ":", "'~/.aadbook_cache'", ",", "'auth_db_filename'", ":", "'~/.aadbook_auth.json'", ",", "'cache_expiry_hours'", ":", "'24'", "}", ")", "...
32.923077
18.923077
def split_every(iterable, n): # TODO: Remove this, or make it return a generator. """ A generator of n-length chunks of an input iterable """ i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
[ "def", "split_every", "(", "iterable", ",", "n", ")", ":", "# TODO: Remove this, or make it return a generator.", "i", "=", "iter", "(", "iterable", ")", "piece", "=", "list", "(", "islice", "(", "i", ",", "n", ")", ")", "while", "piece", ":", "yield", "pi...
30.222222
15.111111
def select_one(select, tag, namespaces=None, flags=0, **kwargs): """Select a single tag.""" return compile(select, namespaces, flags, **kwargs).select_one(tag)
[ "def", "select_one", "(", "select", ",", "tag", ",", "namespaces", "=", "None", ",", "flags", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "compile", "(", "select", ",", "namespaces", ",", "flags", ",", "*", "*", "kwargs", ")", ".", "sele...
41.25
23.75
def set_left_to_right(self): """Set text direction left to right.""" self.displaymode |= LCD_ENTRYLEFT self.write8(LCD_ENTRYMODESET | self.displaymode)
[ "def", "set_left_to_right", "(", "self", ")", ":", "self", ".", "displaymode", "|=", "LCD_ENTRYLEFT", "self", ".", "write8", "(", "LCD_ENTRYMODESET", "|", "self", ".", "displaymode", ")" ]
43
7.25
def generate_password(self) -> list: """Generate a list of random characters.""" characterset = self._get_password_characters() if ( self.passwordlen is None or not characterset ): raise ValueError("Can't generate password: character set is " ...
[ "def", "generate_password", "(", "self", ")", "->", "list", ":", "characterset", "=", "self", ".", "_get_password_characters", "(", ")", "if", "(", "self", ".", "passwordlen", "is", "None", "or", "not", "characterset", ")", ":", "raise", "ValueError", "(", ...
34.3125
17.125
def parse_headerline(self, line): """ Parses header lines Keywords example: Keyword1, Keyword2, Keyword3, ..., end """ if self._end_header is True: # Header already processed return 0 splitted = [token.strip() for token in line.split(',')...
[ "def", "parse_headerline", "(", "self", ",", "line", ")", ":", "if", "self", ".", "_end_header", "is", "True", ":", "# Header already processed", "return", "0", "splitted", "=", "[", "token", ".", "strip", "(", ")", "for", "token", "in", "line", ".", "sp...
30.8
14.666667
def discover(self, details = False): 'Discover API definitions. Set details=true to show details' if details and not (isinstance(details, str) and details.lower() == 'false'): return copy.deepcopy(self.discoverinfo) else: return dict((k,v.get('description', '')) for k,v i...
[ "def", "discover", "(", "self", ",", "details", "=", "False", ")", ":", "if", "details", "and", "not", "(", "isinstance", "(", "details", ",", "str", ")", "and", "details", ".", "lower", "(", ")", "==", "'false'", ")", ":", "return", "copy", ".", "...
57.166667
27.5
def digest(dirname, glob=None): """Returns the md5 digest of all interesting files (or glob) in `dirname`. """ md5 = hashlib.md5() if glob is None: fnames = [fname for _, fname in list_files(Path(dirname))] for fname in sorted(fnames): fname = os.path.join(dirname, fname) ...
[ "def", "digest", "(", "dirname", ",", "glob", "=", "None", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "if", "glob", "is", "None", ":", "fnames", "=", "[", "fname", "for", "_", ",", "fname", "in", "list_files", "(", "Path", "(", "dirna...
36.857143
10.642857
def _render_pages(self): """Render the complete document once and return the number of pages rendered.""" self.style_log = StyleLog(self.stylesheet) self.floats = set() self.placed_footnotes = set() self._start_time = time.time() part_page_counts = {} par...
[ "def", "_render_pages", "(", "self", ")", ":", "self", ".", "style_log", "=", "StyleLog", "(", "self", ".", "stylesheet", ")", "self", ".", "floats", "=", "set", "(", ")", "self", ".", "placed_footnotes", "=", "set", "(", ")", "self", ".", "_start_time...
43.954545
15
def GetFeedItemIdsForCampaign(campaign_feed): """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. Args: campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. Returns: A list of Feed Item IDs. """ feed_item_ids = set() try: lhs_operand = campaign_feed['...
[ "def", "GetFeedItemIdsForCampaign", "(", "campaign_feed", ")", ":", "feed_item_ids", "=", "set", "(", ")", "try", ":", "lhs_operand", "=", "campaign_feed", "[", "'matchingFunction'", "]", "[", "'lhsOperand'", "]", "except", "KeyError", ":", "lhs_operand", "=", "...
31.555556
23.555556
def plot_result(x_p, y_p, y_p_e, smoothed_data, smoothed_data_diff, filename=None): ''' Fit spline to the profile histogramed data, differentiate, determine MPV and plot. Parameters ---------- x_p, y_p : array like data points (x,y) y_p_e : array like error bars in y...
[ "def", "plot_result", "(", "x_p", ",", "y_p", ",", "y_p_e", ",", "smoothed_data", ",", "smoothed_data_diff", ",", "filename", "=", "None", ")", ":", "logging", ".", "info", "(", "'Plot results'", ")", "plt", ".", "close", "(", ")", "p1", "=", "plt", "....
61.233333
41.1
def outside_root_to_404(fn): """ Decorator for converting PathOutsideRoot errors to 404s. """ @wraps(fn) def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except PathOutsideRoot as e: raise HTTPError(404, "Path outside root: [%s]" % e.args[0]) ...
[ "def", "outside_root_to_404", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "PathOut...
29.454545
13.818182
def _priority_from_env(self, val): """Gets priority pairs from env.""" for part in val.split(':'): try: rule, priority = part.split('=') yield rule, int(priority) except ValueError: continue
[ "def", "_priority_from_env", "(", "self", ",", "val", ")", ":", "for", "part", "in", "val", ".", "split", "(", "':'", ")", ":", "try", ":", "rule", ",", "priority", "=", "part", ".", "split", "(", "'='", ")", "yield", "rule", ",", "int", "(", "pr...
33.875
8.75
def add_entry(self, **kw): """ Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None """ self.data.setdefault('entries', []).append( ...
[ "def", "add_entry", "(", "self", ",", "*", "*", "kw", ")", ":", "self", ".", "data", ".", "setdefault", "(", "'entries'", ",", "[", "]", ")", ".", "append", "(", "{", "'{}_entry'", ".", "format", "(", "self", ".", "typeof", ")", ":", "kw", "}", ...
35.6
16
def fasta(args): """ %prog fasta bedfile scf.fasta pseudomolecules.fasta Use OM bed to scaffold and create pseudomolecules. bedfile can be generated by running jcvi.assembly.opticalmap bed --blockonly """ from jcvi.formats.sizes import Sizes from jcvi.formats.agp import OO, build p = O...
[ "def", "fasta", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "sizes", "import", "Sizes", "from", "jcvi", ".", "formats", ".", "agp", "import", "OO", ",", "build", "p", "=", "OptionParser", "(", "fasta", ".", "__doc__", ")", "opts", ","...
27.421053
16.105263
def est_payouts(self): ''' Calculate current estimate of average payout for each bandit. Returns ------- array of floats or None ''' if len(self.choices) < 1: print('slots: No trials run so far.') return None else: ret...
[ "def", "est_payouts", "(", "self", ")", ":", "if", "len", "(", "self", ".", "choices", ")", "<", "1", ":", "print", "(", "'slots: No trials run so far.'", ")", "return", "None", "else", ":", "return", "self", ".", "wins", "/", "(", "self", ".", "pulls"...
24.071429
22.071429
def _set_desire_distance(self, v, load=False): """ Setter method for desire_distance, mapped from YANG variable /interface/fc_port/desire_distance (desire-distance-type) If this variable is read-only (config: false) in the source YANG file, then _set_desire_distance is considered as a private method...
[ "def", "_set_desire_distance", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
89.454545
42.5
def dict2dzn( objs, declare=False, assign=True, declare_enums=True, wrap=True, fout=None ): """Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``...
[ "def", "dict2dzn", "(", "objs", ",", "declare", "=", "False", ",", "assign", "=", "True", ",", "declare_enums", "=", "True", ",", "wrap", "=", "True", ",", "fout", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", ...
35.655172
22.362069
def check(self, feature): """Check that fit_transform can be called on reference data""" mapper = feature.as_dataframe_mapper() mapper.fit_transform(self.X, y=self.y)
[ "def", "check", "(", "self", ",", "feature", ")", ":", "mapper", "=", "feature", ".", "as_dataframe_mapper", "(", ")", "mapper", ".", "fit_transform", "(", "self", ".", "X", ",", "y", "=", "self", ".", "y", ")" ]
46.75
6.75
def newest_release(self, product): """ Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release. """ releases = yield self.upcoming_rel...
[ "def", "newest_release", "(", "self", ",", "product", ")", ":", "releases", "=", "yield", "self", ".", "upcoming_releases", "(", "product", ")", "if", "not", "releases", ":", "raise", "ProductPagesException", "(", "'no upcoming releases'", ")", "defer", ".", "...
38.416667
16.083333
def build_dummies_dict(data): """ Return a dict with unique values as keys and vectors as values """ unique_val_list = unique(data) output = {} for val in unique_val_list: output[val] = (data == val) return output
[ "def", "build_dummies_dict", "(", "data", ")", ":", "unique_val_list", "=", "unique", "(", "data", ")", "output", "=", "{", "}", "for", "val", "in", "unique_val_list", ":", "output", "[", "val", "]", "=", "(", "data", "==", "val", ")", "return", "outpu...
27.222222
12.111111
def weight_variable(name, shape, trainable): """ :param name: string :param shape: 4D array :return: tf variable """ w = tf.get_variable(name=name, shape=shape, initializer=tf.contrib.layers.variance_scaling_initializer(), trainable=trainable) ...
[ "def", "weight_variable", "(", "name", ",", "shape", ",", "trainable", ")", ":", "w", "=", "tf", ".", "get_variable", "(", "name", "=", "name", ",", "shape", "=", "shape", ",", "initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "variance_sca...
45.25
19.916667
def get_commits_and_names_iter(self, path): ''' Get all commits including a given path following renames ''' log_result = self.git.log( '--pretty=%H', '--follow', '--name-only', '--', path).splitlines() for commit_sha, ...
[ "def", "get_commits_and_names_iter", "(", "self", ",", "path", ")", ":", "log_result", "=", "self", ".", "git", ".", "log", "(", "'--pretty=%H'", ",", "'--follow'", ",", "'--name-only'", ",", "'--'", ",", "path", ")", ".", "splitlines", "(", ")", "for", ...
31
19
def list_websites(self): """ Return all websites, name is not a key """ self.connect() results = self.server.list_websites(self.session_id) return results
[ "def", "list_websites", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "results", "=", "self", ".", "server", ".", "list_websites", "(", "self", ".", "session_id", ")", "return", "results" ]
30.333333
18.666667
def mouseMoveEvent(self, event): """ Tracks when an item is hovered and exited. :param event | <QMoustEvent> """ if self.hoverMode() != XTreeWidget.HoverMode.NoHover: item = self.itemAt(event.pos()) col = self.columnAt(event.pos().x()) ...
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "hoverMode", "(", ")", "!=", "XTreeWidget", ".", "HoverMode", ".", "NoHover", ":", "item", "=", "self", ".", "itemAt", "(", "event", ".", "pos", "(", ")", ")", "col", ...
33.366667
15.9
def grep(expression, file, flags=0, invert=False): """ Search a file and return a list of all lines that match a regular expression. :param str expression: The regex to search for. :param file: The file to search in. :type file: str, file :param int flags: The regex flags to use when searching. :param bool inve...
[ "def", "grep", "(", "expression", ",", "file", ",", "flags", "=", "0", ",", "invert", "=", "False", ")", ":", "# requirements = re", "if", "isinstance", "(", "file", ",", "str", ")", ":", "file", "=", "open", "(", "file", ")", "lines", "=", "[", "]...
29.45
17.85
def upload(self, file_path, golden_image_info): """ Adds a Golden Image resource from the file that is uploaded from a local drive. Only the .zip format file can be used for the upload. Args: file_path (str): File name to upload. golden_image_info (dict): Golden ...
[ "def", "upload", "(", "self", ",", "file_path", ",", "golden_image_info", ")", ":", "uri", "=", "\"{0}?name={1}&description={2}\"", ".", "format", "(", "self", ".", "URI", ",", "quote", "(", "golden_image_info", ".", "get", "(", "'name'", ",", "''", ")", "...
40.764706
26.411765
def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE): ''' How long to wait in seconds before this crontab entry can next be executed. ''' if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None)...
[ "def", "next", "(", "self", ",", "now", "=", "None", ",", "increments", "=", "_increments", ",", "delta", "=", "True", ",", "default_utc", "=", "WARN_CHANGE", ")", ":", "if", "default_utc", "is", "WARN_CHANGE", "and", "(", "isinstance", "(", "now", ",", ...
42.608696
22.927536
def pad(self, pad_width, **kwargs): """Pad this series to a new size Parameters ---------- pad_width : `int`, pair of `ints` number of samples by which to pad each end of the array. Single int to pad both ends by the same amount, or (before, after) `t...
[ "def", "pad", "(", "self", ",", "pad_width", ",", "*", "*", "kwargs", ")", ":", "# format arguments", "kwargs", ".", "setdefault", "(", "'mode'", ",", "'constant'", ")", "if", "isinstance", "(", "pad_width", ",", "int", ")", ":", "pad_width", "=", "(", ...
33.617647
17
def _build_server_url(server_host, server_path) -> str: """Build the server url making sure it ends in a trailing slash.""" server_url = urljoin(server_host, server_path) if server_url[-1] == '/': return server_url return '{}/'.format(server_url)
[ "def", "_build_server_url", "(", "server_host", ",", "server_path", ")", "->", "str", ":", "server_url", "=", "urljoin", "(", "server_host", ",", "server_path", ")", "if", "server_url", "[", "-", "1", "]", "==", "'/'", ":", "return", "server_url", "return", ...
47.5
8
def PlayerTypeEnum(ctx): """Player Type Enumeration.""" return Enum( ctx, absent=0, closed=1, human=2, eliminated=3, computer=4, cyborg=5, spectator=6 )
[ "def", "PlayerTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "absent", "=", "0", ",", "closed", "=", "1", ",", "human", "=", "2", ",", "eliminated", "=", "3", ",", "computer", "=", "4", ",", "cyborg", "=", "5", ",", "spectato...
18.083333
21.416667
def sign_file(self, message_file, key_id=None, passphrase=None, clearsign=True, detach=False, binary=False): ''' Make a signature. :param message_file: File-like object for sign :param key_id: Key for signing, default will be used if null :param passphrase: Key...
[ "def", "sign_file", "(", "self", ",", "message_file", ",", "key_id", "=", "None", ",", "passphrase", "=", "None", ",", "clearsign", "=", "True", ",", "detach", "=", "False", ",", "binary", "=", "False", ")", ":", "args", "=", "[", "'-s'", "if", "bina...
39.363636
16.909091
def reverse_guard(lst): """ Reverse guard expression. not (@a > 5) -> (@a =< 5) Args: lst (list): Expression returns: list """ rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'} return [rev[l] if l in rev else l for l in lst]
[ "def", "reverse_guard", "(", "lst", ")", ":", "rev", "=", "{", "'<'", ":", "'>='", ",", "'>'", ":", "'=<'", ",", "'>='", ":", "'<'", ",", "'=<'", ":", "'>'", "}", "return", "[", "rev", "[", "l", "]", "if", "l", "in", "rev", "else", "l", "for"...
26.5
14.9
def quantile(self, qs, interpolation='linear', axis=0): """ compute the quantiles of the Parameters ---------- qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 Re...
[ "def", "quantile", "(", "self", ",", "qs", ",", "interpolation", "=", "'linear'", ",", "axis", "=", "0", ")", ":", "if", "self", ".", "is_datetimetz", ":", "# TODO: cleanup this special case.", "# We need to operate on i8 values for datetimetz", "# but `Block.get_values...
37.647059
17.588235
async def send_chat_message(self, send_chat_message_request): """Send a chat message to a conversation.""" response = hangouts_pb2.SendChatMessageResponse() await self._pb_request('conversations/sendchatmessage', send_chat_message_request, response) return ...
[ "async", "def", "send_chat_message", "(", "self", ",", "send_chat_message_request", ")", ":", "response", "=", "hangouts_pb2", ".", "SendChatMessageResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/sendchatmessage'", ",", "send_chat_message_...
53.833333
17.5
def main(context, subject, debug, no_colors): """ Eh is a terminal program that will provide you with quick reminders about a subject. To get started run: eh help To figure out what eh knows about run: eh list To update the list of subjects: eh update Note: Eh will make a directory ...
[ "def", "main", "(", "context", ",", "subject", ",", "debug", ",", "no_colors", ")", ":", "eho", "=", "Eh", "(", "debug", ",", "no_colors", ")", "if", "subject", "==", "'list'", ":", "eho", ".", "subject_list", "(", ")", "exit", "(", "0", ")", "if",...
23.48
18.28
def copy(self): """ Return a new :class:`~pywbem.CIMInstanceName` object that is a copy of this CIM instance path. This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original obje...
[ "def", "copy", "(", "self", ")", ":", "return", "CIMInstanceName", "(", "self", ".", "classname", ",", "keybindings", "=", "self", ".", "keybindings", ",", "# setter copies", "host", "=", "self", ".", "host", ",", "namespace", "=", "self", ".", "namespace"...
43.416667
23.166667
def kv_format_object(o, keys=None, separator=DEFAULT_SEPARATOR): """Formats an object's attributes. Useful for object representation implementation. Will skip methods or private attributes. For more details see :func:`kv_format`. :param o: Object to format. :param collections.Sequence ke...
[ "def", "kv_format_object", "(", "o", ",", "keys", "=", "None", ",", "separator", "=", "DEFAULT_SEPARATOR", ")", ":", "if", "keys", "is", "None", ":", "key_values", "=", "[", "]", "for", "k", ",", "v", "in", "(", "(", "x", ",", "getattr", "(", "o", ...
34
18.321429
def _build(self, inputs, prev_state): """Connects the highway core module into the graph. Args: inputs: Tensor of size `[batch_size, input_size]`. prev_state: Tensor of size `[batch_size, hidden_size]`. Returns: A tuple (output, next_state) where `output` is a Tensor of size `[batc...
[ "def", "_build", "(", "self", ",", "inputs", ",", "prev_state", ")", ":", "input_size", "=", "inputs", ".", "get_shape", "(", ")", "[", "1", "]", "weight_shape", "=", "(", "input_size", ",", "self", ".", "_hidden_size", ")", "u_shape", "=", "(", "self"...
38.12
18.56
def delete_mirror(name, config_path=_DEFAULT_CONFIG_PATH, force=False): ''' Remove a mirrored remote repository. By default, Package data is not removed. :param str name: The name of the remote repository mirror. :param str config_path: The path to the configuration file for the aptly instance. :pa...
[ "def", "delete_mirror", "(", "name", ",", "config_path", "=", "_DEFAULT_CONFIG_PATH", ",", "force", "=", "False", ")", ":", "_validate_config", "(", "config_path", ")", "force", "=", "six", ".", "text_type", "(", "bool", "(", "force", ")", ")", ".", "lower...
31.868421
27.342105
def xml(self): """ :rtype: str """ if six.PY3: data = ElementTree.tostring(self.et, encoding="unicode") else: data = ElementTree.tostring(self.et) return data
[ "def", "xml", "(", "self", ")", ":", "if", "six", ".", "PY3", ":", "data", "=", "ElementTree", ".", "tostring", "(", "self", ".", "et", ",", "encoding", "=", "\"unicode\"", ")", "else", ":", "data", "=", "ElementTree", ".", "tostring", "(", "self", ...
24.666667
16.888889
def instruction_PSH(self, opcode, m, register): """ All, some, or none of the processor registers are pushed onto stack (with the exception of stack pointer itself). A single register may be placed on the stack with the condition codes set by doing an autodecrement store onto th...
[ "def", "instruction_PSH", "(", "self", ",", "opcode", ",", "m", ",", "register", ")", ":", "assert", "register", "in", "(", "self", ".", "system_stack_pointer", ",", "self", ".", "user_stack_pointer", ")", "def", "push", "(", "register_str", ",", "stack_poin...
42.210526
25.052632
def debug(self, status=None, nids=None): """ This method is usually used when the flow didn't completed succesfully It analyzes the files produced the tasks to facilitate debugging. Info are printed to stdout. Args: status: If not None, only the tasks with this statu...
[ "def", "debug", "(", "self", ",", "status", "=", "None", ",", "nids", "=", "None", ")", ":", "nrows", ",", "ncols", "=", "get_terminal_size", "(", ")", "# Test for scheduler exceptions first.", "sched_excfile", "=", "os", ".", "path", ".", "join", "(", "se...
43.227273
22.522727
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Can't exit from root (if root)""" if self.username == "root": exit_config_mode = False return super(LinuxSSH, self).send_config_set( config_commands=config_commands, exit_config_mode=exit...
[ "def", "send_config_set", "(", "self", ",", "config_commands", "=", "None", ",", "exit_config_mode", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "username", "==", "\"root\"", ":", "exit_config_mode", "=", "False", "return", "super", ...
49.428571
20.285714
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(se...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'id'", ")", "and", "self", ".", "id", "is", "not", "None", ":", "_dict", "[", "'id'", "]", "=", "self", ".", "id", "if", "hasattr", "(", "self...
49.2
15.55
def call(method, *args, **kwargs): ''' Calls an arbitrary netmiko method. ''' kwargs = clean_kwargs(**kwargs) if not netmiko_device['always_alive']: connection = ConnectHandler(**netmiko_device['args']) ret = getattr(connection, method)(*args, **kwargs) connection.disconnect(...
[ "def", "call", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "clean_kwargs", "(", "*", "*", "kwargs", ")", "if", "not", "netmiko_device", "[", "'always_alive'", "]", ":", "connection", "=", "ConnectHandler", "(", "*...
36.727273
16.727273
def _sort_resources_per_hosting_device(resources): """This function will sort the resources on hosting device. The sorting on hosting device is done by looking up the `hosting_device` attribute of the resource, and its `id`. :param resources: a dict with key of resource name :r...
[ "def", "_sort_resources_per_hosting_device", "(", "resources", ")", ":", "hosting_devices", "=", "{", "}", "for", "key", "in", "resources", ".", "keys", "(", ")", ":", "for", "r", "in", "resources", ".", "get", "(", "key", ")", "or", "[", "]", ":", "if...
44.583333
16.916667
def astype(self, data_type): """ Cast to a new data type. :param data_type: the new data type :return: casted sequence :Example: >>> df.id.astype('float') """ data_type = types.validate_data_type(data_type) if data_type == self._data_type: ...
[ "def", "astype", "(", "self", ",", "data_type", ")", ":", "data_type", "=", "types", ".", "validate_data_type", "(", "data_type", ")", "if", "data_type", "==", "self", ".", "_data_type", ":", "return", "self", "attr_dict", "=", "dict", "(", ")", "attr_dict...
22.92
19.48
def merge_otus_and_trees(nexson_blob): """Takes a nexson object: 1. merges trees elements 2 - # trees into the first trees element., 2. merges otus elements 2 - # otus into the first otus element. 3. if there is no ot:originalLabel field for any otu, it sets that field based on @...
[ "def", "merge_otus_and_trees", "(", "nexson_blob", ")", ":", "id_to_replace_id", "=", "{", "}", "orig_version", "=", "detect_nexson_version", "(", "nexson_blob", ")", "convert_nexson_format", "(", "nexson_blob", ",", "BY_ID_HONEY_BADGERFISH", ")", "nexson", "=", "get_...
50.3
16.171429
def send_messages(self, messages): """Sending SMS messages via sms.sluzba.cz API. Note: This method returns number of actually sent sms messages not number of SmsMessage instances processed. :param messages: list of sms messages :type messages: list of sendsms.messa...
[ "def", "send_messages", "(", "self", ",", "messages", ")", ":", "count", "=", "0", "for", "message", "in", "messages", ":", "message_body", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "unicode", "(", "message", ".", "body", ")", ")", ".", ...
36.928571
22.25
def parse_file(self, fpath): ''' Read a file on the file system (relative to salt's base project dir) :returns: A file-like object. :raises IOError: If the file cannot be found or read. ''' sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__), ...
[ "def", "parse_file", "(", "self", ",", "fpath", ")", ":", "sdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "salt", ".", "__file__", ")", ",", "os", ".", "pardir", ...
37.363636
22.454545
def advise(self, item, stop=False): """Request updates when DDE data changes.""" hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD()) ...
[ "def", "advise", "(", "self", ",", "item", ",", "stop", "=", "False", ")", ":", "hszItem", "=", "DDE", ".", "CreateStringHandle", "(", "self", ".", "_idInst", ",", "item", ",", "CP_WINUNICODE", ")", "hDdeData", "=", "DDE", ".", "ClientTransaction", "(", ...
64.875
29.625
def get_tail_incidence_matrix(H, nodes_to_indices, hyperedge_ids_to_indices): """Creates the incidence matrix of the tail nodes of the given hypergraph as a sparse matrix. :param H: the hypergraph for which to create the incidence matrix of. :param nodes_to_indices: for each node, maps the node to its ...
[ "def", "get_tail_incidence_matrix", "(", "H", ",", "nodes_to_indices", ",", "hyperedge_ids_to_indices", ")", ":", "if", "not", "isinstance", "(", "H", ",", "DirectedHypergraph", ")", ":", "raise", "TypeError", "(", "\"Algorithm only applicable to directed hypergraphs\"", ...
46.482759
22.241379
def depth_file_for_nir_file(video_filename, depth_file_list): """Returns the corresponding depth filename given a NIR filename""" (root, filename) = os.path.split(video_filename) needle_ts = int(filename.split('-')[2].split('.')[0]) haystack_ts_list = np.array(Kinect.timestamps_from_file...
[ "def", "depth_file_for_nir_file", "(", "video_filename", ",", "depth_file_list", ")", ":", "(", "root", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "video_filename", ")", "needle_ts", "=", "int", "(", "filename", ".", "split", "(", "'-...
61.625
20
def stop_batch_learning(self): """Finish a series of batch learn operations.""" self._learning = False self.graph.commit() self.graph.cursor().execute("PRAGMA journal_mode=truncate") self.graph.ensure_indexes()
[ "def", "stop_batch_learning", "(", "self", ")", ":", "self", ".", "_learning", "=", "False", "self", ".", "graph", ".", "commit", "(", ")", "self", ".", "graph", ".", "cursor", "(", ")", ".", "execute", "(", "\"PRAGMA journal_mode=truncate\"", ")", "self",...
35
15
def update_count(self): """ updates rating count and rating average """ node_rating_count = self.node.rating_count node_rating_count.rating_count = self.node.rating_set.count() node_rating_count.rating_avg = self.node.rating_set.aggregate(rate=Avg('value'))['rate'] # if all rati...
[ "def", "update_count", "(", "self", ")", ":", "node_rating_count", "=", "self", ".", "node", ".", "rating_count", "node_rating_count", ".", "rating_count", "=", "self", ".", "node", ".", "rating_set", ".", "count", "(", ")", "node_rating_count", ".", "rating_a...
44.333333
20.583333
def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_b...
[ "def", "overlay", "(", "self", ",", "block_start_string", "=", "missing", ",", "block_end_string", "=", "missing", ",", "variable_start_string", "=", "missing", ",", "variable_end_string", "=", "missing", ",", "comment_start_string", "=", "missing", ",", "comment_en...
44.818182
20.681818
def gen_nop(): """Return a NOP instruction. """ empty_reg = ReilEmptyOperand() return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg)
[ "def", "gen_nop", "(", ")", ":", "empty_reg", "=", "ReilEmptyOperand", "(", ")", "return", "ReilBuilder", ".", "build", "(", "ReilMnemonic", ".", "NOP", ",", "empty_reg", ",", "empty_reg", ",", "empty_reg", ")" ]
30.333333
18.5
def edit(self, request, id): """Render a form to edit an object.""" try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { ...
[ "def", "edit", "(", "self", ",", "request", ",", "id", ")", ":", "try", ":", "object", "=", "self", ".", "model", ".", "objects", ".", "get", "(", "id", "=", "id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "return", "self", "...
32.965517
19.586207
def count_plus(self, uid): ''' Ajax request, that the view count will plus 1. ''' self.set_header("Content-Type", "application/json") output = { # ToDo: Test the following codes. # MPost.__update_view_count_by_uid(uid) else 0, 'status': 1 if MP...
[ "def", "count_plus", "(", "self", ",", "uid", ")", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "output", "=", "{", "# ToDo: Test the following codes.", "# MPost.__update_view_count_by_uid(uid) else 0,", "'status'", ":", "1"...
36.25
17.416667
def _parse_geoms(self, **kwargs): """ Finds supported geometry types, parses them and returns the bbox """ bbox = kwargs.get('bbox', None) wkt_geom = kwargs.get('wkt', None) geojson = kwargs.get('geojson', None) if bbox is not None: g = box(*bbox) elif wkt_geo...
[ "def", "_parse_geoms", "(", "self", ",", "*", "*", "kwargs", ")", ":", "bbox", "=", "kwargs", ".", "get", "(", "'bbox'", ",", "None", ")", "wkt_geom", "=", "kwargs", ".", "get", "(", "'wkt'", ",", "None", ")", "geojson", "=", "kwargs", ".", "get", ...
35.764706
12.705882
def kmer_lca_records(seqs_path, one_codex_api_key: 'One Codex API key' = None, fastq: 'input is fastq; disable autodetection' = False, progress: 'show progress bar (sent to stderr)' = False): ''' Parallel lowest common ancestor sequence classificati...
[ "def", "kmer_lca_records", "(", "seqs_path", ",", "one_codex_api_key", ":", "'One Codex API key'", "=", "None", ",", "fastq", ":", "'input is fastq; disable autodetection'", "=", "False", ",", "progress", ":", "'show progress bar (sent to stderr)'", "=", "False", ")", "...
62.235294
33.647059
def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(dump_yaml(data)) return ...
[ "def", "save_yamlf", "(", "data", ":", "Union", "[", "list", ",", "dict", "]", ",", "fpath", ":", "str", ",", "encoding", ":", "str", ")", "->", "str", ":", "with", "codecs", ".", "open", "(", "fpath", ",", "mode", "=", "'w'", ",", "encoding", "=...
31.6
13
def _non_unicode_repr(objekt, context, maxlevels, level): """ Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'. """ repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context, ...
[ "def", "_non_unicode_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "repr_string", ",", "isreadable", ",", "isrecursive", "=", "pprint", ".", "_safe_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ...
44.636364
19.181818
def message(self, value): """ Setter for **self.__message** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) in (unicode, QString), \ "'{0}' attribute: '{1}' type is not 'unicode' or ...
[ "def", "message", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "in", "(", "unicode", ",", "QString", ")", ",", "\"'{0}' attribute: '{1}' type is not 'unicode' or 'QString'!\"", ".", "format"...
31.333333
17.833333
def json_to_params(fn=None, return_json=True): """ Convert JSON in the body of the request to the parameters for the wrapped function. If the JSON is list, add it to ``*args``. If dict, add it to ``**kwargs`` in non-rewrite mode (no key in ``**kwargs`` will be overwritten). If single valu...
[ "def", "json_to_params", "(", "fn", "=", "None", ",", "return_json", "=", "True", ")", ":", "def", "json_to_params_decorator", "(", "fn", ")", ":", "@", "handle_type_error", "@", "wraps", "(", "fn", ")", "def", "json_to_params_wrapper", "(", "*", "args", "...
31.152174
18.065217
def get_process(cmd): """Get a command process.""" if sys.platform.startswith('win'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen( cmd, startupinfo=startupinfo, stdout=subpro...
[ "def", "get_process", "(", "cmd", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "startupinfo", "=", "subprocess", ".", "STARTUPINFO", "(", ")", "startupinfo", ".", "dwFlags", "|=", "subprocess", ".", "STARTF_USESHOWWINDOW...
27.826087
14.26087
def load_conf(): '''获取基本设定信息, 里面存放着所有可用的profiles, 以及默认的profile''' if os.path.exists(_conf_file): with open(_conf_file) as fh: return json.load(fh) else: dump_conf(_base_conf) return _base_conf
[ "def", "load_conf", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "_conf_file", ")", ":", "with", "open", "(", "_conf_file", ")", "as", "fh", ":", "return", "json", ".", "load", "(", "fh", ")", "else", ":", "dump_conf", "(", "_base_co...
29.125
13.875
def recall_checksum(self, cache_file): """ Get the checksum of the input used to generate a binary distribution archive. :param cache_file: The pathname of the binary distribution archive (a string). :returns: The checksum (a string) or :data:`None` (when no checksum is available). ...
[ "def", "recall_checksum", "(", "self", ",", "cache_file", ")", ":", "# EAFP instead of LBYL because of concurrency between pip-accel", "# processes (https://docs.python.org/2/glossary.html#term-lbyl).", "checksum_file", "=", "'%s.txt'", "%", "cache_file", "try", ":", "with", "ope...
42.52381
18.904762
def Filter(self, filename_spec): """Use pkg_resources to find the path to the required resource.""" if "@" in filename_spec: file_path, package_name = filename_spec.split("@") else: file_path, package_name = filename_spec, Resource.default_package resource_path = package.ResourcePath(packag...
[ "def", "Filter", "(", "self", ",", "filename_spec", ")", ":", "if", "\"@\"", "in", "filename_spec", ":", "file_path", ",", "package_name", "=", "filename_spec", ".", "split", "(", "\"@\"", ")", "else", ":", "file_path", ",", "package_name", "=", "filename_sp...
34.666667
21.6
def format_from_extension(fname): """ Tries to infer a protocol from the file extension.""" _base, ext = os.path.splitext(fname) if not ext: return None try: format = known_extensions[ext.replace('.', '')] except KeyError: format = None return format
[ "def", "format_from_extension", "(", "fname", ")", ":", "_base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "if", "not", "ext", ":", "return", "None", "try", ":", "format", "=", "known_extensions", "[", "ext", ".", "replace...
28.9
16.2
def get_dir_walker(recursive, topdown=True, followlinks=False): """ Returns a recursive or a non-recursive directory walker. :param recursive: ``True`` produces a recursive walker; ``False`` produces a non-recursive walker. :returns: A walker function. """ if recursive: ...
[ "def", "get_dir_walker", "(", "recursive", ",", "topdown", "=", "True", ",", "followlinks", "=", "False", ")", ":", "if", "recursive", ":", "walk", "=", "partial", "(", "os", ".", "walk", ",", "topdown", "=", "topdown", ",", "followlinks", "=", "followli...
36.684211
25.315789
def _resolve_dep(self, key): """ this method resolves dependencies for the given key. call the method afther the item "key" was added to the list of avalable items """ if key in self.future_values_key_dep: # there are some dependencies that can be resoled ...
[ "def", "_resolve_dep", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "future_values_key_dep", ":", "# there are some dependencies that can be resoled", "dep_list", "=", "self", ".", "future_values_key_dep", "[", "key", "]", "del", "self", ".",...
47.647059
15.647059
def _compute_start_end(df, start, end): """ Compute two dataframes with value for start and end Args: totals(dataframe): Returns: Dataframe, Dataframe """ result = {} time_dict = {'start': start, 'end': end} totals = df.groupby('date').agg({'value': sum}).reset_index() for ...
[ "def", "_compute_start_end", "(", "df", ",", "start", ",", "end", ")", ":", "result", "=", "{", "}", "time_dict", "=", "{", "'start'", ":", "start", ",", "'end'", ":", "end", "}", "totals", "=", "df", ".", "groupby", "(", "'date'", ")", ".", "agg",...
29.44
14.64
def download_icon_font(icon_font, directory): """Download given (implemented) icon font into passed directory""" try: downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory) downloader.download_files() return downloader except KeyError: # pragma: no cover raise...
[ "def", "download_icon_font", "(", "icon_font", ",", "directory", ")", ":", "try", ":", "downloader", "=", "AVAILABLE_ICON_FONTS", "[", "icon_font", "]", "[", "'downloader'", "]", "(", "directory", ")", "downloader", ".", "download_files", "(", ")", "return", "...
41.2
17.4
def set_compiler_channels(self, channel_list, operator="mix"): """General method for setting the input channels for the status process Given a list of status channels that are gathered during the pipeline construction, this method will automatically set the input channel for the status ...
[ "def", "set_compiler_channels", "(", "self", ",", "channel_list", ",", "operator", "=", "\"mix\"", ")", ":", "if", "not", "channel_list", ":", "raise", "eh", ".", "ProcessError", "(", "\"At least one status channel must be \"", "\"provided to include this process in the \...
34.519231
23.288462
def get_all_client_events(self, client): """ Returns the list of current events for a given client. """ data = self._request('GET', '/events/{}'.format(client)) return data.json()
[ "def", "get_all_client_events", "(", "self", ",", "client", ")", ":", "data", "=", "self", ".", "_request", "(", "'GET'", ",", "'/events/{}'", ".", "format", "(", "client", ")", ")", "return", "data", ".", "json", "(", ")" ]
35.666667
10
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=lim...
[ "def", "gt", "(", "self", ",", "v", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "if", "limit", "is", "not", "None", "and", "offset", "is", "None", ":", "offset", "=", "0", "return", "self", ".", "zrangebyscore", "(", "\"(%f\"",...
39.5
8.125
def build( self, endpoint, values=None, method=None, force_external=False, append_unknown=True, ): """Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for...
[ "def", "build", "(", "self", ",", "endpoint", ",", "values", "=", "None", ",", "method", "=", "None", ",", "force_external", "=", "False", ",", "append_unknown", "=", "True", ",", ")", ":", "self", ".", "map", ".", "update", "(", ")", "if", "values",...
39.144068
23.059322
def get_parsed_context(pipeline, context_in_string): """Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. c...
[ "def", "get_parsed_context", "(", "pipeline", ",", "context_in_string", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "if", "'context_parser'", "in", "pipeline", ":", "parser_module_name", "=", "pipeline", "[", "'context_parser'", "]", "logger", ".",...
39.489796
22.183673
def update_Broyden_J(self): """Execute a Broyden update of J""" CLOG.debug('Broyden update.') delta_vals = self.param_vals - self._last_vals delta_residuals = self.calc_residuals() - self._last_residuals nrm = np.sqrt(np.dot(delta_vals, delta_vals)) direction = delta_vals...
[ "def", "update_Broyden_J", "(", "self", ")", ":", "CLOG", ".", "debug", "(", "'Broyden update.'", ")", "delta_vals", "=", "self", ".", "param_vals", "-", "self", ".", "_last_vals", "delta_residuals", "=", "self", ".", "calc_residuals", "(", ")", "-", "self",...
44.5
9
def n_dir(self): """ Count how many folders in this directory. Including folder in sub folder. """ self.assert_is_dir_and_exists() n = 0 for _ in self.select_dir(recursive=True): n += 1 return n
[ "def", "n_dir", "(", "self", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "n", "=", "0", "for", "_", "in", "self", ".", "select_dir", "(", "recursive", "=", "True", ")", ":", "n", "+=", "1", "return", "n" ]
28.222222
16.444444
def add_bundle(self, data: dict) -> models.Bundle: """Build a new bundle version of files. The format of the input dict is defined in the `schema` module. """ bundle_obj = self.bundle(data['name']) if bundle_obj and self.version(bundle_obj.name, data['created']): LOG...
[ "def", "add_bundle", "(", "self", ",", "data", ":", "dict", ")", "->", "models", ".", "Bundle", ":", "bundle_obj", "=", "self", ".", "bundle", "(", "data", "[", "'name'", "]", ")", "if", "bundle_obj", "and", "self", ".", "version", "(", "bundle_obj", ...
44.142857
24.285714
def native_types(code): """Convert code elements from strings to native Python types.""" out = [] for c in code: if isconstant(c, quoted=True): if isstring(c, quoted=True): v = c[1:-1] elif isbool(c): v = to_bool(c) elif isnumber(c)...
[ "def", "native_types", "(", "code", ")", ":", "out", "=", "[", "]", "for", "c", "in", "code", ":", "if", "isconstant", "(", "c", ",", "quoted", "=", "True", ")", ":", "if", "isstring", "(", "c", ",", "quoted", "=", "True", ")", ":", "v", "=", ...
34.26087
18
def region_from_segment(image, segment): """given a segment (rectangle) and an image, returns it's corresponding subimage""" x, y, w, h = segment return image[y:y + h, x:x + w]
[ "def", "region_from_segment", "(", "image", ",", "segment", ")", ":", "x", ",", "y", ",", "w", ",", "h", "=", "segment", "return", "image", "[", "y", ":", "y", "+", "h", ",", "x", ":", "x", "+", "w", "]" ]
46.25
5.5
def find_elements(self, by=By.ID, value=None, el_class=None): """ usages with ``'one string'`` selector: - find_elements(by: str) -> PageElementsList[ListElement] - find_elements(by: str, value: T <= ListElement) -> PageElementsList[T] usages with ``'webdriver'`` By selector ...
[ "def", "find_elements", "(", "self", ",", "by", "=", "By", ".", "ID", ",", "value", "=", "None", ",", "el_class", "=", "None", ")", ":", "els", "=", "self", ".", "child_elements", "(", "by", ",", "value", ",", "el_class", ")", "els", ".", "reload",...
37.318182
20.136364
def _get_space(self): ''' a helper method to retrieve id of drive space ''' title = '%s._space_id' % self.__class__.__name__ list_kwargs = { 'q': "'%s' in parents" % self.drive_space, 'spaces': self.drive_space, 'fields': 'files(name, parents...
[ "def", "_get_space", "(", "self", ")", ":", "title", "=", "'%s._space_id'", "%", "self", ".", "__class__", ".", "__name__", "list_kwargs", "=", "{", "'q'", ":", "\"'%s' in parents\"", "%", "self", ".", "drive_space", ",", "'spaces'", ":", "self", ".", "dri...
32.842105
17.578947
def underlying_variable(t): """Find the underlying tf.Variable object. Args: t: a Tensor Returns: tf.Variable. """ t = underlying_variable_ref(t) assert t is not None # make sure that the graph has a variable index and that it is up-to-date if not hasattr(tf.get_default_graph(), "var_index"): ...
[ "def", "underlying_variable", "(", "t", ")", ":", "t", "=", "underlying_variable_ref", "(", "t", ")", "assert", "t", "is", "not", "None", "# make sure that the graph has a variable index and that it is up-to-date", "if", "not", "hasattr", "(", "tf", ".", "get_default_...
27.5
18.111111
def angle_delta(self): """The angle delta in degrees between the last and the current :attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE` event. For gesture events that are not of type :attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE`, this property raises :exc:`AttributeError`. The angle de...
[ "def", "angle_delta", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "GESTURE_PINCH_UPDATE", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput...
38.413793
22.517241