text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def push_to_server(self): """ Use appropriate CIM API call to save payment profile to Authorize.NET 1. If customer has no profile yet, create one with this payment profile 2. If payment profile is not on Authorize.NET yet, create it there 3. If payment profile exists on Authorize...
[ "def", "push_to_server", "(", "self", ")", ":", "if", "not", "self", ".", "customer_profile_id", ":", "try", ":", "self", ".", "customer_profile", "=", "CustomerProfile", ".", "objects", ".", "get", "(", "customer", "=", "self", ".", "customer", ")", "exce...
38.704545
13.568182
def display_notes(self, notes): """Renders "notes" reported by ENSIME, such as typecheck errors.""" # TODO: this can probably be a cached property like isneovim hassyntastic = bool(int(self._vim.eval('exists(":SyntasticCheck")'))) if hassyntastic: self.__display_notes_with_...
[ "def", "display_notes", "(", "self", ",", "notes", ")", ":", "# TODO: this can probably be a cached property like isneovim", "hassyntastic", "=", "bool", "(", "int", "(", "self", ".", "_vim", ".", "eval", "(", "'exists(\":SyntasticCheck\")'", ")", ")", ")", "if", ...
34.75
21.333333
def _GetStringValue(self, data_dict, name, default_value=None): """Retrieves a specific string value from the data dict. Args: data_dict (dict[str, list[str]): values per name. name (str): name of the value to retrieve. default_value (Optional[object]): value to return if the name has no valu...
[ "def", "_GetStringValue", "(", "self", ",", "data_dict", ",", "name", ",", "default_value", "=", "None", ")", ":", "values", "=", "data_dict", ".", "get", "(", "name", ",", "None", ")", "if", "not", "values", ":", "return", "default_value", "for", "index...
29.666667
18.857143
def main(): """ Main entrypoint for command-line webserver. """ parser = argparse.ArgumentParser() parser.add_argument("-H", "--host", help="Web server Host address to bind to", default="0.0.0.0", action="store", required=False) parser.add_argument("-p", "--port", help="W...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-H\"", ",", "\"--host\"", ",", "help", "=", "\"Web server Host address to bind to\"", ",", "default", "=", "\"0.0.0.0\"", ",", "act...
41
20.846154
def not_(self, value, name=''): """ Bitwise integer complement: name = ~value """ if isinstance(value.type, types.VectorType): rhs = values.Constant(value.type, (-1,) * value.type.count) else: rhs = values.Constant(value.type, -1) retur...
[ "def", "not_", "(", "self", ",", "value", ",", "name", "=", "''", ")", ":", "if", "isinstance", "(", "value", ".", "type", ",", "types", ".", "VectorType", ")", ":", "rhs", "=", "values", ".", "Constant", "(", "value", ".", "type", ",", "(", "-",...
34.4
11.4
def itertags(html, tag): """ Brute force regex based HTML tag parser. This is a rough-and-ready searcher to find HTML tags when standards compliance is not required. Will find tags that are commented out, or inside script tag etc. :param html: HTML page :param tag: tag name to find :return: gen...
[ "def", "itertags", "(", "html", ",", "tag", ")", ":", "for", "match", "in", "tag_re", ".", "finditer", "(", "html", ")", ":", "if", "match", ".", "group", "(", "\"tag\"", ")", "==", "tag", ":", "attrs", "=", "dict", "(", "(", "a", ".", "group", ...
45.923077
24.846154
def get_input_media_referenced_files(self, var_name): """ Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload. Will return something which might be similar to `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'ima...
[ "def", "get_input_media_referenced_files", "(", "self", ",", "var_name", ")", ":", "# file to be uploaded", "string", "=", "'attach://{name}'", ".", "format", "(", "name", "=", "var_name", ")", "return", "string", ",", "self", ".", "get_request_files", "(", "var_n...
41.388889
22.611111
def task_done(self): """Indicate that a formerly enqueued task is complete. Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will res...
[ "def", "task_done", "(", "self", ")", ":", "self", ".", "_parent", ".", "_check_closing", "(", ")", "with", "self", ".", "_parent", ".", "_all_tasks_done", ":", "if", "self", ".", "_parent", ".", "_unfinished_tasks", "<=", "0", ":", "raise", "ValueError", ...
44
20.045455
def all(self): " execute query, get all list of lists" query,inputs = self._toedn() return self.db.q(query, inputs = inputs, limit = self._limit, offset = self._offset, history = self._history)
[ "def", "all", "(", "self", ")", ":", "query", ",", "inputs", "=", "self", ".", "_toedn", "(", ")", "return", "self", ".", "db", ".", "q", "(", "query", ",", "inputs", "=", "inputs", ",", "limit", "=", "self", ".", "_limit", ",", "offset", "=", ...
28.25
12.5
def ensure_remote_branch_is_tracked(branch): """Track the specified remote branch if it is not already tracked.""" if branch == MASTER_BRANCH: # We don't need to explicitly track the master branch, so we're done. return # Ensure the specified branch is in the local branch list. output =...
[ "def", "ensure_remote_branch_is_tracked", "(", "branch", ")", ":", "if", "branch", "==", "MASTER_BRANCH", ":", "# We don't need to explicitly track the master branch, so we're done.", "return", "# Ensure the specified branch is in the local branch list.", "output", "=", "subprocess",...
40.9
17.95
def SampleStart(self): """Starts measuring the CPU time.""" self._start_cpu_time = time.clock() self.start_sample_time = time.time() self.total_cpu_time = 0
[ "def", "SampleStart", "(", "self", ")", ":", "self", ".", "_start_cpu_time", "=", "time", ".", "clock", "(", ")", "self", ".", "start_sample_time", "=", "time", ".", "time", "(", ")", "self", ".", "total_cpu_time", "=", "0" ]
33.6
6.4
def get_module_part(dotted_name, context_file=None): """given a dotted name return the module part of the name : >>> get_module_part('astroid.as_string.dump') 'astroid.as_string' :type dotted_name: str :param dotted_name: full name of the identifier we are interested in :type context_file: st...
[ "def", "get_module_part", "(", "dotted_name", ",", "context_file", "=", "None", ")", ":", "# os.path trick", "if", "dotted_name", ".", "startswith", "(", "\"os.path\"", ")", ":", "return", "\"os.path\"", "parts", "=", "dotted_name", ".", "split", "(", "\".\"", ...
33.644068
19.372881
def _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys): """ Try, in order: - The key passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if all...
[ "def", "_auth", "(", "self", ",", "username", ",", "password", ",", "pkey", ",", "key_filenames", ",", "allow_agent", ",", "look_for_keys", ")", ":", "saved_exception", "=", "None", "two_factor", "=", "False", "allowed_types", "=", "[", "]", "if", "pkey", ...
42.096154
19.596154
def add_items(self, items_list, incl_pmag=True, incl_parents=True): """ Add items and/or update existing items in grid """ num_rows = self.GetNumberRows() current_grid_rows = [self.GetCellValue(num, 0) for num in range(num_rows)] er_data = {item.name: item.er_data for ite...
[ "def", "add_items", "(", "self", ",", "items_list", ",", "incl_pmag", "=", "True", ",", "incl_parents", "=", "True", ")", ":", "num_rows", "=", "self", ".", "GetNumberRows", "(", ")", "current_grid_rows", "=", "[", "self", ".", "GetCellValue", "(", "num", ...
41.842105
14.894737
def get_create_option(self, context, q): """Form the correct create_option to append to results.""" create_option = [] display_create_option = False if self.create_field and q: page_obj = context.get('page_obj', None) if page_obj is None or page_obj.number =...
[ "def", "get_create_option", "(", "self", ",", "context", ",", "q", ")", ":", "create_option", "=", "[", "]", "display_create_option", "=", "False", "if", "self", ".", "create_field", "and", "q", ":", "page_obj", "=", "context", ".", "get", "(", "'page_obj'...
40.107143
20.125
def to_dict(self): """Converts this embed object into a dict.""" # add in the raw data into the dict result = { key[1:]: getattr(self, key) for key in self.__slots__ if key[0] == '_' and hasattr(self, key) } # deal with basic convenience wrap...
[ "def", "to_dict", "(", "self", ")", ":", "# add in the raw data into the dict", "result", "=", "{", "key", "[", "1", ":", "]", ":", "getattr", "(", "self", ",", "key", ")", "for", "key", "in", "self", ".", "__slots__", "if", "key", "[", "0", "]", "==...
26.755556
21.088889
def __save_reference(self, o, cls, args, kwargs): """ Saves a reference to the original object Facade is passed. This will either be the object itself or a LazyBones instance for lazy-loading later :param mixed o: The original object :param class cls: The class definition for th...
[ "def", "__save_reference", "(", "self", ",", "o", ",", "cls", ",", "args", ",", "kwargs", ")", ":", "if", "not", "o", "and", "cls", ":", "self", "[", "'__original_object'", "]", "=", "LazyBones", "(", "cls", ",", "args", ",", "kwargs", ")", "else", ...
43.941176
21.823529
def labels_to_onehots(labels, num_classes): """Convert a vector of integer class labels to a matrix of one-hot target vectors. :param labels: a vector of integer labels, 0 to num_classes. Has shape (batch_size,). :param num_classes: the total number of classes :return: has shape (batch_size, num_classe...
[ "def", "labels_to_onehots", "(", "labels", ",", "num_classes", ")", ":", "batch_size", "=", "labels", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "0", "]", "with", "tf", ".", "name_scope", "(", "\"one_hot\"", ")", ":", "labels", "=", "tf...
45.0625
17.25
def run(self, parent=None): """Start the configeditor :returns: None :rtype: None :raises: None """ self.gw = GuerillaMGMTWin(parent=parent) self.gw.show()
[ "def", "run", "(", "self", ",", "parent", "=", "None", ")", ":", "self", ".", "gw", "=", "GuerillaMGMTWin", "(", "parent", "=", "parent", ")", "self", ".", "gw", ".", "show", "(", ")" ]
22.666667
15.111111
def updateFeature(self, features, gdbVersion=None, rollbackOnFailure=True): """ updates an existing feature in a feature service layer Input: feature - feature object(s) to get updated. A single feature ...
[ "def", "updateFeature", "(", "self", ",", "features", ",", "gdbVersion", "=", "None", ",", "rollbackOnFailure", "=", "True", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"rollbackOnFailure\"", ":", "rollbackOnFailure", "}", "if", "gdbVersion"...
41.513514
14.972973
def _resolv_name(self, hostname): """Convert hostname to IP address.""" ip = hostname try: ip = socket.gethostbyname(hostname) except Exception as e: logger.debug("{}: Cannot convert {} to IP address ({})".format(self.plugin_name, hostname, e)) return ip
[ "def", "_resolv_name", "(", "self", ",", "hostname", ")", ":", "ip", "=", "hostname", "try", ":", "ip", "=", "socket", ".", "gethostbyname", "(", "hostname", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"{}: Cannot convert {} ...
38.875
20
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
[ "def", "upload", "(", "target", ")", ":", "# type: (str) -> None", "log", ".", "info", "(", "\"Uploading to pypi server <33>{}\"", ".", "format", "(", "target", ")", ")", "with", "conf", ".", "within_proj_dir", "(", ")", ":", "shell", ".", "run", "(", "'pyth...
34.642857
21.571429
def create_http_monitor(self, topics, transport_url, transport_token=None, transport_method='PUT', connect_timeout=0, response_timeout=0, batch_size=1, batch_duration=0, compression='none', format_type='json'): """Creates a HTTP Monitor instance in Device Cloud for a given list of to...
[ "def", "create_http_monitor", "(", "self", ",", "topics", ",", "transport_url", ",", "transport_token", "=", "None", ",", "transport_method", "=", "'PUT'", ",", "connect_timeout", "=", "0", ",", "response_timeout", "=", "0", ",", "batch_size", "=", "1", ",", ...
52.352941
22.921569
def save_model(self, request, obj, form, change): """ If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``, send a notification email to the user being saved if their ``active`` status has changed to ``True``. If the ``ACCOUNTS_VERIFICATION_REQUIRED`` setting is ``True``, ...
[ "def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "must_send_verification_mail_after_save", "=", "False", "if", "change", "and", "settings", ".", "ACCOUNTS_APPROVAL_REQUIRED", ":", "if", "obj", ".", "is_active", ...
54
18
def divide_url(self, url): """ divide url into host and path two parts """ if 'https://' in url: host = url[8:].split('/')[0] path = url[8 + len(host):] elif 'http://' in url: host = url[7:].split('/')[0] path = url[7 + len(host):] ...
[ "def", "divide_url", "(", "self", ",", "url", ")", ":", "if", "'https://'", "in", "url", ":", "host", "=", "url", "[", "8", ":", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "path", "=", "url", "[", "8", "+", "len", "(", "host", ")", ...
29.857143
7
def format(self, format_str): """Returns a formatted version of format_str. The only named replacement fields supported by this method and their corresponding API calls are: * {num} group_num * {name} group_name * {symbol} group_symbol *...
[ "def", "format", "(", "self", ",", "format_str", ")", ":", "return", "format_str", ".", "format", "(", "*", "*", "{", "\"num\"", ":", "self", ".", "group_num", ",", "\"name\"", ":", "self", ".", "group_name", ",", "\"symbol\"", ":", "self", ".", "group...
36.5
9
def restore_expanded_state(self): """Restore all items expanded state""" if self.__expanded_state is None: return for item in self.get_items()+self.get_top_level_items(): user_text = get_item_user_text(item) is_expanded = self.__expanded_state.get(hash(u...
[ "def", "restore_expanded_state", "(", "self", ")", ":", "if", "self", ".", "__expanded_state", "is", "None", ":", "return", "for", "item", "in", "self", ".", "get_items", "(", ")", "+", "self", ".", "get_top_level_items", "(", ")", ":", "user_text", "=", ...
45.555556
10.777778
def update(gandi, resource, name, size, quantity, password, sshkey, upgrade, console, snapshotprofile, reset_mysql_password, background, delete_snapshotprofile): """Update a PaaS instance. Resource can be a Hostname or an ID """ if snapshotprofile and delete_snapshotprofile: ...
[ "def", "update", "(", "gandi", ",", "resource", ",", "name", ",", "size", ",", "quantity", ",", "password", ",", "sshkey", ",", "upgrade", ",", "console", ",", "snapshotprofile", ",", "reset_mysql_password", ",", "background", ",", "delete_snapshotprofile", ")...
32.925926
21.555556
def to_dict(self): """Converts this object to an (ordered) dictionary of field-value pairs. >>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict() >>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10...
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "OrderedDict", "(", ")", "result", "[", "'mrz_type'", "]", "=", "self", ".", "mrz_type", "result", "[", "'valid_score'", "]", "=", "self", ".", "valid_score", "if", "self", ".", "mrz_type", "is", ...
51.977778
19.422222
def save_var(name, value): """ Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. """ connection = _State.connection() _State.reflect_metadata() vars_table = sqlalchemy.Table( _State.vars_table_name, _State.meta...
[ "def", "save_var", "(", "name", ",", "value", ")", ":", "connection", "=", "_State", ".", "connection", "(", ")", "_State", ".", "reflect_metadata", "(", ")", "vars_table", "=", "sqlalchemy", ".", "Table", "(", "_State", ".", "vars_table_name", ",", "_Stat...
33
19.709677
def versions_available(self): """ Query PyPI for a particular version or all versions of a package @returns: 0 if version(s) found or 1 if none found """ if self.version: spec = "%s==%s" % (self.project_name, self.version) else: spec = self.proje...
[ "def", "versions_available", "(", "self", ")", ":", "if", "self", ".", "version", ":", "spec", "=", "\"%s==%s\"", "%", "(", "self", ".", "project_name", ",", "self", ".", "version", ")", "else", ":", "spec", "=", "self", ".", "project_name", "if", "sel...
35.458333
21.625
def onMessage(self, payload, isBinary): """ Send the payload onto the {slack.[payload['type]'} channel. The message is transalated from IDs to human-readable identifiers. Note: The slack API only sends JSON, isBinary will always be false. """ msg = self.translate(unpack(...
[ "def", "onMessage", "(", "self", ",", "payload", ",", "isBinary", ")", ":", "msg", "=", "self", ".", "translate", "(", "unpack", "(", "payload", ")", ")", "if", "'type'", "in", "msg", ":", "channel_name", "=", "'slack.{}'", ".", "format", "(", "msg", ...
43.916667
18.083333
def add_ini_opts(self, cp, sec): """Add job-specific options from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this ...
[ "def", "add_ini_opts", "(", "self", ",", "cp", ",", "sec", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "sec", ")", ":", "value", "=", "string", ".", "strip", "(", "cp", ".", "get", "(", "sec", ",", "opt", ")", ")", "opt", "=", "'...
43.985714
17.628571
def check_version(): """ Tells you if you have an old version of intern. """ import requests r = requests.get('https://pypi.python.org/pypi/intern/json').json() r = r['info']['version'] if r != __version__: print("You are using version {}. A newer version of intern is available: {} "...
[ "def", "check_version", "(", ")", ":", "import", "requests", "r", "=", "requests", ".", "get", "(", "'https://pypi.python.org/pypi/intern/json'", ")", ".", "json", "(", ")", "r", "=", "r", "[", "'info'", "]", "[", "'version'", "]", "if", "r", "!=", "__ve...
36.727273
20.363636
def make_defaults_and_annotations(make_function_instr, builders): """ Get the AST expressions corresponding to the defaults, kwonly defaults, and annotations for a function created by `make_function_instr`. """ # Integer counts. n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_...
[ "def", "make_defaults_and_annotations", "(", "make_function_instr", ",", "builders", ")", ":", "# Integer counts.", "n_defaults", ",", "n_kwonlydefaults", ",", "n_annotations", "=", "unpack_make_function_arg", "(", "make_function_instr", ".", "arg", ")", "if", "n_annotati...
34.894737
17.789474
def _maybe_dt_data(data, feature_names, feature_types): """ Validate feature names and types if data table """ if not isinstance(data, DataTable): return data, feature_names, feature_types data_types_names = tuple(lt.name for lt in data.ltypes) bad_fields = [data.names[i] ...
[ "def", "_maybe_dt_data", "(", "data", ",", "feature_names", ",", "feature_types", ")", ":", "if", "not", "isinstance", "(", "data", ",", "DataTable", ")", ":", "return", "data", ",", "feature_names", ",", "feature_types", "data_types_names", "=", "tuple", "(",...
38.6
16.28
def batchDF(symbols, fields=None, range_='1m', last=10, token='', version=''): '''Batch several data requests into one invocation https://iexcloud.io/docs/api/#batch-requests Args: symbols (list); List of tickers to request fields (list); List of fields to request range_ (string);...
[ "def", "batchDF", "(", "symbols", ",", "fields", "=", "None", ",", "range_", "=", "'1m'", ",", "last", "=", "10", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "x", "=", "batch", "(", "symbols", ",", "fields", ",", "range_", ",", ...
28.5
19.944444
def get_display_name(self, role): """get the display name of a role""" if role not in self.flatten: raise MissingRole(role) return self.flatten[role]['display_name']
[ "def", "get_display_name", "(", "self", ",", "role", ")", ":", "if", "role", "not", "in", "self", ".", "flatten", ":", "raise", "MissingRole", "(", "role", ")", "return", "self", ".", "flatten", "[", "role", "]", "[", "'display_name'", "]" ]
39.4
5
def get(self, timeout=None): """Return the next available item from the tube. Blocks if tube is empty, until a producer for the tube puts an item on it.""" if timeout: try: result = self._queue.get(True, timeout) except multiprocessing.Queue.Empty: ...
[ "def", "get", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", ":", "try", ":", "result", "=", "self", ".", "_queue", ".", "get", "(", "True", ",", "timeout", ")", "except", "multiprocessing", ".", "Queue", ".", "Empty", ":", "r...
36.818182
12.727273
def maximize(self, bAsync = True): """ Maximize the window. @see: L{minimize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """ if bAsync: ...
[ "def", "maximize", "(", "self", ",", "bAsync", "=", "True", ")", ":", "if", "bAsync", ":", "win32", ".", "ShowWindowAsync", "(", "self", ".", "get_handle", "(", ")", ",", "win32", ".", "SW_MAXIMIZE", ")", "else", ":", "win32", ".", "ShowWindow", "(", ...
30.266667
21.2
def _get_renamed_deleted_sourcesapp(self): """ Get renamed and deleted sources lists from receiver . Internal method which queries device via HTTP to get names of renamed input sources. In this method AppCommand.xml is used. """ # renamed_sources and deleted_sources are ...
[ "def", "_get_renamed_deleted_sourcesapp", "(", "self", ")", ":", "# renamed_sources and deleted_sources are dicts with \"source\" as key", "# and \"renamed_source\" or deletion flag as value.", "renamed_sources", "=", "{", "}", "deleted_sources", "=", "{", "}", "# Collect tags for Ap...
39.767442
20.604651
def disable_paging(self, command="terminal length 999", delay_factor=1): """Disable paging default to a Cisco CLI method.""" delay_factor = self.select_delay_factor(delay_factor) time.sleep(delay_factor * 0.1) self.clear_buffer() command = self.normalize_cmd(command) log....
[ "def", "disable_paging", "(", "self", ",", "command", "=", "\"terminal length 999\"", ",", "delay_factor", "=", "1", ")", ":", "delay_factor", "=", "self", ".", "select_delay_factor", "(", "delay_factor", ")", "time", ".", "sleep", "(", "delay_factor", "*", "0...
43.933333
9.066667
def tree_to_stream(entries, write): """Write the give list of entries into a stream using its write method :param entries: **sorted** list of tuples with (binsha, mode, name) :param write: write method which takes a data string""" ord_zero = ord('0') bit_mask = 7 # 3 bits set for bin...
[ "def", "tree_to_stream", "(", "entries", ",", "write", ")", ":", "ord_zero", "=", "ord", "(", "'0'", ")", "bit_mask", "=", "7", "# 3 bits set", "for", "binsha", ",", "mode", ",", "name", "in", "entries", ":", "mode_str", "=", "b''", "for", "i", "in", ...
45.692308
19.192308
def time_window_cutoff(sw_time, time_cutoff): """ Allows for cutting the declustering time window at a specific time, outside of which an event of any magnitude is no longer identified as a cluster """ sw_time = np.array( [(time_cutoff / DAYS) if x > (time_cutoff / DAYS) else x f...
[ "def", "time_window_cutoff", "(", "sw_time", ",", "time_cutoff", ")", ":", "sw_time", "=", "np", ".", "array", "(", "[", "(", "time_cutoff", "/", "DAYS", ")", "if", "x", ">", "(", "time_cutoff", "/", "DAYS", ")", "else", "x", "for", "x", "in", "sw_ti...
38.777778
15.222222
def bias_correct(params, data, acf=None): """ Calculate and apply a bias correction to the given fit parameters Parameters ---------- params : lmfit.Parameters The model parameters. These will be modified. data : 2d-array The data which was used in the fitting acf : 2d-ar...
[ "def", "bias_correct", "(", "params", ",", "data", ",", "acf", "=", "None", ")", ":", "bias", "=", "RB_bias", "(", "data", ",", "params", ",", "acf", "=", "acf", ")", "i", "=", "0", "for", "p", "in", "params", ":", "if", "'theta'", "in", "p", "...
19.878788
21.151515
def set_objective(self, expression): """Set objective of problem.""" if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression(offset=expression) # Clear previous objectiv...
[ "def", "set_objective", "(", "self", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "numbers", ".", "Number", ")", ":", "# Allow expressions with no variables as objective,", "# represented as a number", "expression", "=", "Expression", "(", ...
39.176471
19.588235
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
[ "def", "user_exists", "(", "username", ")", ":", "try", ":", "pwd", ".", "getpwnam", "(", "username", ")", "user_exists", "=", "True", "except", "KeyError", ":", "user_exists", "=", "False", "return", "user_exists" ]
23.875
15.125
def convert_msg(self, msg): """ Takes one POEntry object and converts it (adds a dummy translation to it) msg is an instance of polib.POEntry """ source = msg.msgid if not source: # don't translate empty string return plural = msg.msgid_pl...
[ "def", "convert_msg", "(", "self", ",", "msg", ")", ":", "source", "=", "msg", ".", "msgid", "if", "not", "source", ":", "# don't translate empty string", "return", "plural", "=", "msg", ".", "msgid_plural", "if", "plural", ":", "# translate singular and plural"...
34.304348
15.086957
def Run(self): """The main run method of the client.""" for thread in itervalues(self._threads): thread.start() logging.info(START_STRING) while True: dead_threads = [ tn for (tn, t) in iteritems(self._threads) if not t.isAlive() ] if dead_threads: raise FatalE...
[ "def", "Run", "(", "self", ")", ":", "for", "thread", "in", "itervalues", "(", "self", ".", "_threads", ")", ":", "thread", ".", "start", "(", ")", "logging", ".", "info", "(", "START_STRING", ")", "while", "True", ":", "dead_threads", "=", "[", "tn"...
29.142857
21
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Get request payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read me...
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "GetRequestPayload", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", "kmip_version"...
36.4
18.666667
def _GetMergeTaskStorageFilePath(self, task): """Retrieves the path of a task storage file in the merge directory. Args: task (Task): task. Returns: str: path of a task storage file file in the merge directory. """ filename = '{0:s}.plaso'.format(task.identifier) return os.path.joi...
[ "def", "_GetMergeTaskStorageFilePath", "(", "self", ",", "task", ")", ":", "filename", "=", "'{0:s}.plaso'", ".", "format", "(", "task", ".", "identifier", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_merge_task_storage_path", ",", "fil...
32
20.272727
def sum_grad_and_var_all_reduce(grad_and_vars, num_workers, alg, gpu_indices, aux_devices=None, num_shards=1): """Apply all-reduce algorithm over specified ...
[ "def", "sum_grad_and_var_all_reduce", "(", "grad_and_vars", ",", "num_workers", ",", "alg", ",", "gpu_indices", ",", "aux_devices", "=", "None", ",", "num_shards", "=", "1", ")", ":", "with", "tf", ".", "name_scope", "(", "\"allreduce\"", ")", ":", "# Note tha...
44.833333
14.520833
def _open(self): """Bind, use tls""" try: self.ldap.start_tls_s() #pylint: disable=no-member except ldap.CONNECT_ERROR: #pylint: enable=no-member logging.error('Unable to establish a connection to the LDAP server, ' + \ 'please ch...
[ "def", "_open", "(", "self", ")", ":", "try", ":", "self", ".", "ldap", ".", "start_tls_s", "(", ")", "#pylint: disable=no-member", "except", "ldap", ".", "CONNECT_ERROR", ":", "#pylint: enable=no-member", "logging", ".", "error", "(", "'Unable to establish a conn...
39.461538
21.846154
def get_pretty_format(self, max_name_length=0): """Returns a nicely formatted string describing the result. Parameters ---------- max_name_length: int [0] The maximum length of the gene set name (in characters). If the gene set name is longer than this number, it...
[ "def", "get_pretty_format", "(", "self", ",", "max_name_length", "=", "0", ")", ":", "assert", "isinstance", "(", "max_name_length", ",", "(", "int", ",", "np", ".", "integer", ")", ")", "if", "max_name_length", "<", "0", "or", "(", "1", "<=", "max_name_...
34.631579
22.894737
def _get_result_paths(self, data): """Gets the results for a run of bwa index. bwa index outputs 5 files when the index is created. The filename prefix will be the same as the input fasta, unless overridden with the -p option, and the 5 extensions are listed below: .amb ...
[ "def", "_get_result_paths", "(", "self", ",", "data", ")", ":", "# determine the names of the files. The name will be the same as the", "# input fasta file unless overridden with the -p option", "if", "self", ".", "Parameters", "[", "'-p'", "]", ".", "isOn", "(", ")", ":", ...
32.032258
22.806452
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
[ "def", "prepare_for_reraise", "(", "error", ",", "exc_info", "=", "None", ")", ":", "if", "not", "hasattr", "(", "error", ",", "\"_type_\"", ")", ":", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "error", ".",...
33.461538
14.230769
def napus(args): """ %prog napus napus.bed brapa.boleracea.i1.blocks diploid.napus.fractionation Extract napus gene loss vs diploid ancestors. We are looking specifically for anything that has the pattern: BR - BO or BR - BO | | AN ...
[ "def", "napus", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "cbook", "import", "SummaryStats", "p", "=", "OptionParser", "(", "napus", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len",...
32.061404
18.026316
def setAutoRangeOff(self): """ Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target. """ # TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-...
[ "def", "setAutoRangeOff", "(", "self", ")", ":", "# TODO: catch exceptions. How?", "# /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean", "if", "self", ".", "getRefreshBlocked", "(", ")", ":", "logger", ".", "debug", "...
42.333333
22
def findattr(self,attr,connector='parent'): """Returns the attribute named {attr}, from either the self or the self's parents (recursively).""" if (not hasattr(self,attr)): if (not hasattr(self,connector)): return None else: con=getattr(self,connector) if not con: return None if type(con)...
[ "def", "findattr", "(", "self", ",", "attr", ",", "connector", "=", "'parent'", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "attr", ")", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "connector", ")", ")", ":", "return", "...
30.6
15.6
def mpfr_mod(rop, x, y, rnd): """ Given two MPRF numbers x and y, compute x - floor(x / y) * y, rounded if necessary using the given rounding mode. The result is placed in 'rop'. This is the 'remainder' operation, with sign convention compatible with Python's % operator (where x % y has th...
[ "def", "mpfr_mod", "(", "rop", ",", "x", ",", "y", ",", "rnd", ")", ":", "# There are various cases:", "#", "# 0. If either argument is a NaN, the result is NaN.", "#", "# 1. If x is infinite or y is zero, the result is NaN.", "#", "# 2. If y is infinite, return 0 with the sign o...
37.409836
17.934426
def list_traces( self, project_id, view=None, page_size=None, start_time=None, end_time=None, filter_=None, order_by=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None...
[ "def", "list_traces", "(", "self", ",", "project_id", ",", "view", "=", "None", ",", "page_size", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "filter_", "=", "None", ",", "order_by", "=", "None", ",", "retry", "=", ...
46.16568
25.254438
def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Bar plot of 1D histograms.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) value_format = kwargs.pop("value_format", None) density = kwargs.pop("density", False) cumulative = ...
[ "def", "bar", "(", "h1", ":", "Histogram1D", ",", "ax", ":", "Axes", ",", "*", ",", "errors", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", "(", "\"show_stats\"", ",", "False", ")", "show_val...
35.945946
18
def named_entity_spans(self): """The spans of named entities.""" if not self.is_tagged(NAMED_ENTITIES): self.tag_named_entities() return self.spans(NAMED_ENTITIES)
[ "def", "named_entity_spans", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "NAMED_ENTITIES", ")", ":", "self", ".", "tag_named_entities", "(", ")", "return", "self", ".", "spans", "(", "NAMED_ENTITIES", ")" ]
39
4.2
def generate(self, request, **kwargs): """ proxy for the tileset.generate method """ # method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) ...
[ "def", "generate", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# method check to avoid bad requests", "self", ".", "method_check", "(", "request", ",", "allowed", "=", "[", "'get'", "]", ")", "# create a basic bundle object for self.get_cached_o...
40.375
21.0625
def find_other_sources(self, edge_lim = 0.015, min_val = 5000, ntargets = 250, extend_region_size=3, remove_excess=4, plot_flag = False, plot_window=15): """ Identify apertures for all sources on the postcard, both for the target and potenti...
[ "def", "find_other_sources", "(", "self", ",", "edge_lim", "=", "0.015", ",", "min_val", "=", "5000", ",", "ntargets", "=", "250", ",", "extend_region_size", "=", "3", ",", "remove_excess", "=", "4", ",", "plot_flag", "=", "False", ",", "plot_window", "=",...
45.981132
27.584906
def validate_participation(self): """Ensure participation is of a certain type.""" if self.participation not in self._participation_valid_values: raise ValueError("participation should be one of: {valid}".format( valid=", ".join(self._participation_valid_values) )...
[ "def", "validate_participation", "(", "self", ")", ":", "if", "self", ".", "participation", "not", "in", "self", ".", "_participation_valid_values", ":", "raise", "ValueError", "(", "\"participation should be one of: {valid}\"", ".", "format", "(", "valid", "=", "\"...
52.666667
21
def get_unfrozen_copy(values): """Recursively convert `value`'s tuple values into lists, and frozendicts into dicts. Args: values (frozendict/tuple): the frozendict/tuple. Returns: values (dict/list): the unfrozen copy. """ if isinstance(values, (frozendict, dict)): return...
[ "def", "get_unfrozen_copy", "(", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "frozendict", ",", "dict", ")", ")", ":", "return", "{", "key", ":", "get_unfrozen_copy", "(", "value", ")", "for", "key", ",", "value", "in", "values", "...
30.647059
21
def get_characters(self, *args, **kwargs): """Fetches lists of comic characters with optional filters. get /v1/public/characters/{characterId} :returns: CharacterDataWrapper >>> m = Marvel(public_key, private_key) >>> cdw = m.get_characters(orderBy="name,-modified", limit="5"...
[ "def", "get_characters", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#pass url string and params string to _call", "response", "=", "json", ".", "loads", "(", "self", ".", "_call", "(", "Character", ".", "resource_url", "(", ")", ",", ...
32.782609
19.913043
def get_user_by_userid(self, userid): ''' get user by user id ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, respons...
[ "def", "get_user_by_userid", "(", "self", ",", "userid", ")", ":", "response", ",", "status_code", "=", "self", ".", "__pod__", ".", "Users", ".", "get_v2_user", "(", "sessionToken", "=", "self", ".", "__session__", ",", "uid", "=", "userid", ")", ".", "...
39.25
12.25
async def on_shutdown(self, app): """ Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown """ for ws in self.clients.copy(): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') ...
[ "async", "def", "on_shutdown", "(", "self", ",", "app", ")", ":", "for", "ws", "in", "self", ".", "clients", ".", "copy", "(", ")", ":", "await", "ws", ".", "close", "(", "code", "=", "WSCloseCode", ".", "GOING_AWAY", ",", "message", "=", "'Server sh...
33
13.4
def noaa(D="", path="", wds_url="", lpd_url="", version=""): """ Convert between NOAA and LiPD files | Example: LiPD to NOAA converter | 1: L = lipd.readLipd() | 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version...
[ "def", "noaa", "(", "D", "=", "\"\"", ",", "path", "=", "\"\"", ",", "wds_url", "=", "\"\"", ",", "lpd_url", "=", "\"\"", ",", "version", "=", "\"\"", ")", ":", "global", "files", ",", "cwd", "# When going from NOAA to LPD, use the global \"files\" variable.",...
40.590909
23.80303
def maintainer(self): """ >>> package = yarg.get('yarg') >>> package.maintainer Maintainer(name=u'Kura', email=u'kura@kura.io') """ maintainer = namedtuple('Maintainer', 'name email') return maintainer(name=self._package['maintainer'], ...
[ "def", "maintainer", "(", "self", ")", ":", "maintainer", "=", "namedtuple", "(", "'Maintainer'", ",", "'name email'", ")", "return", "maintainer", "(", "name", "=", "self", ".", "_package", "[", "'maintainer'", "]", ",", "email", "=", "self", ".", "_packa...
40.222222
12.222222
def get_objects(self): """Returns a list of objects coming from the "uids" request parameter """ # Create a mapping of source ARs for copy uids = self.request.form.get("uids", "") if not uids: # check for the `items` parammeter uids = self.request.form.get...
[ "def", "get_objects", "(", "self", ")", ":", "# Create a mapping of source ARs for copy", "uids", "=", "self", ".", "request", ".", "form", ".", "get", "(", "\"uids\"", ",", "\"\"", ")", "if", "not", "uids", ":", "# check for the `items` parammeter", "uids", "="...
43.833333
10.5
def run_once(cls, the_callable, userdata=None, delay_until=None): """Class method to run a one-shot task, immediately.""" cls.run_iterations(the_callable, userdata=userdata, run_immediately=True, delay_until=delay_until)
[ "def", "run_once", "(", "cls", ",", "the_callable", ",", "userdata", "=", "None", ",", "delay_until", "=", "None", ")", ":", "cls", ".", "run_iterations", "(", "the_callable", ",", "userdata", "=", "userdata", ",", "run_immediately", "=", "True", ",", "del...
78
30.333333
def path(project, credentials): """Get the path to the project (static method)""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable return settings.ROOT + "projects/" + user + '/' + project + "/"
[ "def", "path", "(", "project", ",", "credentials", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "#pylint: disable=unused-variable", "return", "settings", ".", "ROOT", "+", "\"projects/\"", "+", "user", "+", "'/'", ...
64
24.25
def export_mv_grid(self, session, mv_grid_districts): """ Exports MV grids to database for visualization purposes Parameters ---------- session : sqlalchemy.orm.session.Session Database session mv_grid_districts : List of MV grid_districts (instances of MVGridDistric...
[ "def", "export_mv_grid", "(", "self", ",", "session", ",", "mv_grid_districts", ")", ":", "# check arguments", "if", "not", "all", "(", "isinstance", "(", "_", ",", "int", ")", "for", "_", "in", "mv_grid_districts", ")", ":", "raise", "TypeError", "(", "'`...
42.162602
22.634146
def add_cable_dist(self, lv_cable_dist): """Adds a LV cable_dist to _cable_dists and grid graph if not already existing Parameters ---------- lv_cable_dist : Description #TODO """ if lv_cable_dist not in self._cable_distributors and isinstance(lv_cab...
[ "def", "add_cable_dist", "(", "self", ",", "lv_cable_dist", ")", ":", "if", "lv_cable_dist", "not", "in", "self", ".", "_cable_distributors", "and", "isinstance", "(", "lv_cable_dist", ",", "LVCableDistributorDing0", ")", ":", "self", ".", "_cable_distributors", "...
43.416667
19.166667
async def xtrim(self, name: str, max_len: int, approximate=True) -> int: """ [NOTICE] Not officially released yet XTRIM is designed to accept different trimming strategies, even if currently only MAXLEN is implemented. :param name: name of the stream :param max_len: max...
[ "async", "def", "xtrim", "(", "self", ",", "name", ":", "str", ",", "max_len", ":", "int", ",", "approximate", "=", "True", ")", "->", "int", ":", "pieces", "=", "[", "'MAXLEN'", "]", "if", "approximate", ":", "pieces", ".", "append", "(", "'~'", "...
37.428571
16.571429
def fetch_aggregation_results(self): """ Loops though the self.aggregations dict and adds them to the Search object in order in which they were created. Queries elasticsearch and returns a dict containing the results :returns: a dictionary containing the response from elasticsea...
[ "def", "fetch_aggregation_results", "(", "self", ")", ":", "self", ".", "reset_aggregations", "(", ")", "for", "key", ",", "val", "in", "self", ".", "aggregations", ".", "items", "(", ")", ":", "self", ".", "search", ".", "aggs", ".", "bucket", "(", "s...
35.210526
18.789474
def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rena...
[ "def", "_add_annots", "(", "self", ",", "layout", ",", "annots", ")", ":", "if", "annots", ":", "for", "annot", "in", "resolve1", "(", "annots", ")", ":", "annot", "=", "resolve1", "(", "annot", ")", "if", "annot", ".", "get", "(", "'Rect'", ")", "...
41.684211
12.052632
def diff(old, new): """ Returns differences of two network topologies old and new in NetJSON NetworkGraph compatible format """ protocol = new.protocol version = new.version revision = new.revision metric = new.metric # calculate differences in_both = _find_unchanged(old.graph, n...
[ "def", "diff", "(", "old", ",", "new", ")", ":", "protocol", "=", "new", ".", "protocol", "version", "=", "new", ".", "version", "revision", "=", "new", ".", "revision", "metric", "=", "new", ".", "metric", "# calculate differences", "in_both", "=", "_fi...
39.714286
18.714286
def __splitAttrs(self, strArgs): ''' Splits the C{View} attributes in C{strArgs} and optionally adds the view id to the C{viewsById} list. Unique Ids ========== It is very common to find C{View}s having B{NO_ID} as the Id. This turns very difficult to use L{self.findView...
[ "def", "__splitAttrs", "(", "self", ",", "strArgs", ")", ":", "if", "self", ".", "useUiAutomator", ":", "raise", "RuntimeError", "(", "\"This method is not compatible with UIAutomator\"", ")", "# replace the spaces in text:mText to preserve them in later split", "# they are tra...
41.670455
23.147727
def messages(self): """Return remaining messages before limiting.""" return int(math.floor(((self.limit.unit_value - self.level) / self.limit.unit_value) * self.limit.value))
[ "def", "messages", "(", "self", ")", ":", "return", "int", "(", "math", ".", "floor", "(", "(", "(", "self", ".", "limit", ".", "unit_value", "-", "self", ".", "level", ")", "/", "self", ".", "limit", ".", "unit_value", ")", "*", "self", ".", "li...
43.6
24.8
def namedb_create(path, genesis_block): """ Create a sqlite3 db at the given path. Create all the tables and indexes we need. """ global BLOCKSTACK_DB_SCRIPT if os.path.exists( path ): raise Exception("Database '%s' already exists" % path) lines = [l + ";" for l in BLOCKSTACK_DB_S...
[ "def", "namedb_create", "(", "path", ",", "genesis_block", ")", ":", "global", "BLOCKSTACK_DB_SCRIPT", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "Exception", "(", "\"Database '%s' already exists\"", "%", "path", ")", "lines", "=",...
28.272727
20.272727
def Zigrang_Sylvester_1(Re, eD): r'''Calculates Darcy friction factor using the method in Zigrang and Sylvester (1982) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_f}} = -4\log\left[\frac{\epsilon}{3.7D} - \frac{5.02}{Re}\log A_5\right] A_5 = \frac{\epsilon}{3.7D} + \frac{13}...
[ "def", "Zigrang_Sylvester_1", "(", "Re", ",", "eD", ")", ":", "A5", "=", "eD", "/", "3.7", "+", "13", "/", "Re", "ff", "=", "(", "-", "4", "*", "log10", "(", "eD", "/", "3.7", "-", "5.02", "/", "Re", "*", "log10", "(", "A5", ")", ")", ")", ...
28.181818
24.454545
def get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported. """ value = self.get(key) ...
[ "def", "get_as_nullable_float", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "FloatConverter", ".", "to_nullable_float", "(", "value", ")" ]
36
20.6
def get_template(self, template_id): """ Get the template for a given template id. :param template_id: id of the template, str :return: """ template = self.contract_concise.getTemplate(template_id) if template and len(template) == 4: return AgreementT...
[ "def", "get_template", "(", "self", ",", "template_id", ")", ":", "template", "=", "self", ".", "contract_concise", ".", "getTemplate", "(", "template_id", ")", "if", "template", "and", "len", "(", "template", ")", "==", "4", ":", "return", "AgreementTemplat...
29
15.333333
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
[ "def", "write_contents", "(", "self", ",", "table", ",", "reader", ")", ":", "f", "=", "self", ".", "FileObjFaker", "(", "table", ",", "reader", ".", "read", "(", "table", ")", ",", "self", ".", "process_row", ",", "self", ".", "verbose", ")", "self"...
54
38.454545
def read (self, files): """Read settings from given config files. @raises: LinkCheckerError on syntax errors in the config file(s) """ assert isinstance(files, list), "Invalid file list %r" % files try: self.read_ok = super(LCConfigParser, self).read(files) ...
[ "def", "read", "(", "self", ",", "files", ")", ":", "assert", "isinstance", "(", "files", ",", "list", ")", ",", "\"Invalid file list %r\"", "%", "files", "try", ":", "self", ".", "read_ok", "=", "super", "(", "LCConfigParser", ",", "self", ")", ".", "...
45.25
16.75
def get_json_response_object(self, datatable): """ Returns the JSON-compatible dictionary that will be serialized for an AJAX response. The value names are in the form "s~" for strings, "i~" for integers, and "a~" for arrays, if you're unfamiliar with the old C-style jargon used in data...
[ "def", "get_json_response_object", "(", "self", ",", "datatable", ")", ":", "# Ensure the object list is calculated.", "# Calling get_records() will do this implicitly, but we want simultaneous access to the", "# 'total_initial_record_count', and 'unpaged_record_count' values.", "datatable", ...
46.071429
23.285714
def resolve_invite(invite): """ Resolves an invite from a :class:`Invite`, URL or ID Parameters ----------- invite: Union[:class:`Invite`, :class:`Object`, :class:`str`] The invite. Returns -------- :class:`str` The invite code. """ from .invite import Invite #...
[ "def", "resolve_invite", "(", "invite", ")", ":", "from", ".", "invite", "import", "Invite", "# circular import", "if", "isinstance", "(", "invite", ",", "Invite", ")", "or", "isinstance", "(", "invite", ",", "Object", ")", ":", "return", "invite", ".", "i...
25.26087
21
def name(self, gender: Optional[Gender] = None) -> str: """Generate a random name. :param gender: Gender's enum object. :return: Name. :Example: John. """ key = self._validate_enum(gender, Gender) names = self._data['names'].get(key) return s...
[ "def", "name", "(", "self", ",", "gender", ":", "Optional", "[", "Gender", "]", "=", "None", ")", "->", "str", ":", "key", "=", "self", ".", "_validate_enum", "(", "gender", ",", "Gender", ")", "names", "=", "self", ".", "_data", "[", "'names'", "]...
27.75
14.666667
def password_change_done(self, request, extra_context=None): """ Displays the "success" page after a password change. """ from django.contrib.auth.views import password_change_done defaults = { 'extra_context': extra_context or {}, 'template_name': 'cms/pa...
[ "def", "password_change_done", "(", "self", ",", "request", ",", "extra_context", "=", "None", ")", ":", "from", "django", ".", "contrib", ".", "auth", ".", "views", "import", "password_change_done", "defaults", "=", "{", "'extra_context'", ":", "extra_context",...
44.583333
17.916667
def write_ply(self, output_file): """Export ``PointCloud`` to PLY file for viewing in MeshLab.""" points = np.hstack([self.coordinates, self.colors]) with open(output_file, 'w') as outfile: outfile.write(self.ply_header.format( vertex_count...
[ "def", "write_ply", "(", "self", ",", "output_file", ")", ":", "points", "=", "np", ".", "hstack", "(", "[", "self", ".", "coordinates", ",", "self", ".", "colors", "]", ")", "with", "open", "(", "output_file", ",", "'w'", ")", "as", "outfile", ":", ...
57
14.571429
def flag_dipthongs(self, syllables: List[str]) -> List[int]: """ Return a list of syllables that contain a dipthong :param syllables: :return: """ long_positions = [] for idx, syl in enumerate(syllables): for dipthong in self.constants.DIPTHONGS: ...
[ "def", "flag_dipthongs", "(", "self", ",", "syllables", ":", "List", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "long_positions", "=", "[", "]", "for", "idx", ",", "syl", "in", "enumerate", "(", "syllables", ")", ":", "for", "dipthong"...
35.857143
14.714286
def route_create_or_update(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, **kwargs): ''' .. versionadded:: 2019.2.0 Create or update a route within a specified route table. :param name: The name of the route to create. :param...
[ "def", "route_create_or_update", "(", "name", ",", "address_prefix", ",", "next_hop_type", ",", "route_table", ",", "resource_group", ",", "next_hop_ip_address", "=", "None", ",", "*", "*", "kwargs", ")", ":", "netconn", "=", "__utils__", "[", "'azurearm.get_clien...
34.901639
27.590164
def rtt_read(self, buffer_index, num_bytes): """Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the ent...
[ "def", "rtt_read", "(", "self", ",", "buffer_index", ",", "num_bytes", ")", ":", "buf", "=", "(", "ctypes", ".", "c_ubyte", "*", "num_bytes", ")", "(", ")", "bytes_read", "=", "self", ".", "_dll", ".", "JLINK_RTTERMINAL_Read", "(", "buffer_index", ",", "...
36.653846
23.307692
def est_gaba_conc(self): """ Estimate gaba concentration based on equation adapted from Sanacora 1999, p1045 Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder, F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical $\gamma$-aminobutyric acid...
[ "def", "est_gaba_conc", "(", "self", ")", ":", "# need gaba_auc and creatine_auc", "if", "not", "hasattr", "(", "self", ",", "'gaba_params'", ")", ":", "self", ".", "fit_gaba", "(", ")", "# estimate [GABA] according to equation9", "gaba_conc_est", "=", "self", ".", ...
37.25
22.25
def toNoUintArray(arr): ''' cast array to the next higher integer array if dtype=unsigned integer ''' d = arr.dtype if d.kind == 'u': arr = arr.astype({1: np.int16, 2: np.int32, 4: np.int64}[d.itemsize]) return arr
[ "def", "toNoUintArray", "(", "arr", ")", ":", "d", "=", "arr", ".", "dtype", "if", "d", ".", "kind", "==", "'u'", ":", "arr", "=", "arr", ".", "astype", "(", "{", "1", ":", "np", ".", "int16", ",", "2", ":", "np", ".", "int32", ",", "4", ":...
27.454545
16.181818
def do_async_recv(self, bufsize): """ Receive any completed frames from the socket. This function should only be called after a read event on a file descriptor. """ data = self.sock.recv(bufsize) if len(data) == 0: raise socket.error('no data to receive') ...
[ "def", "do_async_recv", "(", "self", ",", "bufsize", ")", ":", "data", "=", "self", ".", "sock", ".", "recv", "(", "bufsize", ")", "if", "len", "(", "data", ")", "==", "0", ":", "raise", "socket", ".", "error", "(", "'no data to receive'", ")", "self...
31.9
18.8