text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def from_file(cls, filename): """ Read an Fiesta input from a file. Currently tested to work with files generated from this class itself. Args: filename: Filename to parse. Returns: FiestaInput object """ with zopen(filename) as f: ...
[ "def", "from_file", "(", "cls", ",", "filename", ")", ":", "with", "zopen", "(", "filename", ")", "as", "f", ":", "return", "cls", ".", "from_string", "(", "f", ".", "read", "(", ")", ")" ]
26.615385
15.384615
def decrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'mor...
[ "def", "decrypt_dynamodb_item", "(", "item", ",", "crypto_config", ")", ":", "# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM", "unique_actions", "=", "set", "(", "[", "crypto_config", ".", "attribute_actions", ".", "default_action", ".", "name", "]", "...
42.202532
30.556962
def get_edxml(self): """stub""" if self.has_raw_edxml(): has_python = False my_files = self.my_osid_object.object_map['fileIds'] raw_text = self.get_text('edxml').text soup = BeautifulSoup(raw_text, 'xml') # replace all file listings with an ap...
[ "def", "get_edxml", "(", "self", ")", ":", "if", "self", ".", "has_raw_edxml", "(", ")", ":", "has_python", "=", "False", "my_files", "=", "self", ".", "my_osid_object", ".", "object_map", "[", "'fileIds'", "]", "raw_text", "=", "self", ".", "get_text", ...
44.916667
16.4375
def train(self, X): """ Trains multiple logistic regression classifiers to handle the multiclass problem posed by ``X`` X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each corr...
[ "def", "train", "(", "self", ",", "X", ")", ":", "_trainer", "=", "bob", ".", "learn", ".", "linear", ".", "CGLogRegTrainer", "(", "*", "*", "{", "'lambda'", ":", "self", ".", "regularizer", "}", ")", "if", "len", "(", "X", ")", "==", "2", ":", ...
32.5
27.029412
def idle_task(self): '''called on idle''' for m in self.mpstate.mav_outputs: m.source_system = self.settings.source_system m.mav.srcSystem = m.source_system m.mav.srcComponent = self.settings.source_component
[ "def", "idle_task", "(", "self", ")", ":", "for", "m", "in", "self", ".", "mpstate", ".", "mav_outputs", ":", "m", ".", "source_system", "=", "self", ".", "settings", ".", "source_system", "m", ".", "mav", ".", "srcSystem", "=", "m", ".", "source_syste...
42.5
13.166667
def internal_get_statistics(self): """Internal method; do not use as it might change at any time. out cpu_user of type int Percentage of processor time spent in user mode as seen by the guest. out cpu_kernel of type int Percentage of processor time spent in kernel mode ...
[ "def", "internal_get_statistics", "(", "self", ")", ":", "(", "cpu_user", ",", "cpu_kernel", ",", "cpu_idle", ",", "mem_total", ",", "mem_free", ",", "mem_balloon", ",", "mem_shared", ",", "mem_cache", ",", "paged_total", ",", "mem_alloc_total", ",", "mem_free_t...
39.288889
27.222222
def pull(remote='origin', branch='master'): """git pull commit""" print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch))) local("git pull %s %s" % (remote, branch))
[ "def", "pull", "(", "remote", "=", "'origin'", ",", "branch", "=", "'master'", ")", ":", "print", "(", "cyan", "(", "\"Pulling changes from repo ( %s / %s)...\"", "%", "(", "remote", ",", "branch", ")", ")", ")", "local", "(", "\"git pull %s %s\"", "%", "(",...
47.75
11.5
def hovering_widgets( kmgraph, graph_fw, ctooltips=False, width=400, height=300, top=100, left=50, bgcolor="rgb(240,240,240)", y_gridcolor="white", member_textbox_width=200, ): """Defines the widgets that display the distribution of each node on hover and...
[ "def", "hovering_widgets", "(", "kmgraph", ",", "graph_fw", ",", "ctooltips", "=", "False", ",", "width", "=", "400", ",", "height", "=", "300", ",", "top", "=", "100", ",", "left", "=", "50", ",", "bgcolor", "=", "\"rgb(240,240,240)\"", ",", "y_gridcolo...
32.965517
21.321839
def search(self): """ Execute solr search query """ params = self.solr_params() logging.info("PARAMS=" + str(params)) results = self.solr.search(**params) logging.info("Docs found: {}".format(results.hits)) return self._process_search_results(results)
[ "def", "search", "(", "self", ")", ":", "params", "=", "self", ".", "solr_params", "(", ")", "logging", ".", "info", "(", "\"PARAMS=\"", "+", "str", "(", "params", ")", ")", "results", "=", "self", ".", "solr", ".", "search", "(", "*", "*", "params...
34.111111
8.333333
def verify2(self, atv_public_key, data): """Last device verification step.""" self._check_initialized() log_binary(_LOGGER, 'Verify', PublicSecret=atv_public_key, Data=data) # Generate a shared secret key public = curve25519.Public(atv_public_key) shared = self._verify_p...
[ "def", "verify2", "(", "self", ",", "atv_public_key", ",", "data", ")", ":", "self", ".", "_check_initialized", "(", ")", "log_binary", "(", "_LOGGER", ",", "'Verify'", ",", "PublicSecret", "=", "atv_public_key", ",", "Data", "=", "data", ")", "# Generate a ...
47.166667
21.083333
def cli(env, start, end, sortby): """Bandwidth report for every pool/server. This reports on the total data transfered for each virtual sever, hardware server and bandwidth pool. """ env.err('Generating bandwidth report for %s to %s' % (start, end)) table = formatting.Table([ 'type', ...
[ "def", "cli", "(", "env", ",", "start", ",", "end", ",", "sortby", ")", ":", "env", ".", "err", "(", "'Generating bandwidth report for %s to %s'", "%", "(", "start", ",", "end", ")", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'type'", ",...
34.826087
21.282609
def get_term_and_background_counts(self): ''' Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. >>> corpus.get_unigram_corpus.get_term_and...
[ "def", "get_term_and_background_counts", "(", "self", ")", ":", "background_df", "=", "self", ".", "_get_background_unigram_frequencies", "(", ")", "corpus_freq_df", "=", "pd", ".", "DataFrame", "(", "{", "'corpus'", ":", "self", ".", "term_category_freq_df", ".", ...
39.47619
24.714286
def tail(self, bytes): """ Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return. """ self.io.seek(max(0, self.size() - bytes)) return self.io.read()
[ "def", "tail", "(", "self", ",", "bytes", ")", ":", "self", ".", "io", ".", "seek", "(", "max", "(", "0", ",", "self", ".", "size", "(", ")", "-", "bytes", ")", ")", "return", "self", ".", "io", ".", "read", "(", ")" ]
30.6
13.8
def _step_failure(self, exc): """ Log failure of a step """ self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label)) self.step_index += 1 self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError)
[ "def", "_step_failure", "(", "self", ",", "exc", ")", ":", "self", ".", "log_crit", "(", "u\"STEP %d (%s) FAILURE\"", "%", "(", "self", ".", "step_index", ",", "self", ".", "step_label", ")", ")", "self", ".", "step_index", "+=", "1", "self", ".", "log_e...
55.4
25.2
def auditlog(*, event, actor, data, level=logging.INFO): """Generate and insert a new event Args: event (`str`): Action performed actor (`str`): Actor (user or subsystem) triggering the event data (`dict`): Any extra data necessary for describing the event level (`str` or `int`)...
[ "def", "auditlog", "(", "*", ",", "event", ",", "actor", ",", "data", ",", "level", "=", "logging", ".", "INFO", ")", ":", "try", ":", "entry", "=", "AuditLog", "(", ")", "entry", ".", "event", "=", "event", "entry", ".", "actor", "=", "actor", "...
28.69697
23.393939
def resample(self, rate): """Resample this `StateVector` to a new rate Because of the nature of a state-vector, downsampling is done by taking the logical 'and' of all original samples in each new sampling interval, while upsampling is achieved by repeating samples. Par...
[ "def", "resample", "(", "self", ",", "rate", ")", ":", "rate1", "=", "self", ".", "sample_rate", ".", "value", "if", "isinstance", "(", "rate", ",", "units", ".", "Quantity", ")", ":", "rate2", "=", "rate", ".", "value", "else", ":", "rate2", "=", ...
41.164179
18.104478
def credit_card_provider(self, card_type=None): """ Returns the provider's name of the credit card. """ if card_type is None: card_type = self.random_element(self.credit_card_types.keys()) return self._credit_card_type(card_type).name
[ "def", "credit_card_provider", "(", "self", ",", "card_type", "=", "None", ")", ":", "if", "card_type", "is", "None", ":", "card_type", "=", "self", ".", "random_element", "(", "self", ".", "credit_card_types", ".", "keys", "(", ")", ")", "return", "self",...
53.2
13
def _set_class_balance(self, class_balance, Y_dev): """Set a prior for the class balance In order of preference: 1) Use user-provided class_balance 2) Estimate balance from Y_dev 3) Assume uniform class distribution """ if class_balance is not None: s...
[ "def", "_set_class_balance", "(", "self", ",", "class_balance", ",", "Y_dev", ")", ":", "if", "class_balance", "is", "not", "None", ":", "self", ".", "p", "=", "np", ".", "array", "(", "class_balance", ")", "elif", "Y_dev", "is", "not", "None", ":", "c...
39.764706
11.823529
def evaluate(data_file, pred_file): ''' Evaluate. ''' expected_version = '1.1' with open(data_file) as dataset_file: dataset_json = json.load(dataset_file) if dataset_json['version'] != expected_version: print('Evaluation expects v-' + expected_version + ...
[ "def", "evaluate", "(", "data_file", ",", "pred_file", ")", ":", "expected_version", "=", "'1.1'", "with", "open", "(", "data_file", ")", "as", "dataset_file", ":", "dataset_json", "=", "json", ".", "load", "(", "dataset_file", ")", "if", "dataset_json", "["...
40.166667
14.166667
def get_queue_bindings(self, vhost, qname): """ Return a list of dicts, one dict per binding. The dict format coming from RabbitMQ for queue named 'testq' is: {"source":"sourceExch","vhost":"/","destination":"testq", "destination_type":"queue","routing_key":"*.*","arguments":{}...
[ "def", "get_queue_bindings", "(", "self", ",", "vhost", ",", "qname", ")", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "qname", "=", "quote", "(", "qname", ",", "''", ")", "path", "=", "Client", ".", "urls", "[", "'bindings_on_queue'", ...
39.642857
14.785714
def _spawnAsBatch(self, processProtocol, executable, args, env, path, usePTY): """A cheat that routes around the impedance mismatch between twisted and cmd.exe with respect to escaping quotes""" # NamedTemporaryFile differs in PY2 and PY3. # In PY2, it needs encode...
[ "def", "_spawnAsBatch", "(", "self", ",", "processProtocol", ",", "executable", ",", "args", ",", "env", ",", "path", ",", "usePTY", ")", ":", "# NamedTemporaryFile differs in PY2 and PY3.", "# In PY2, it needs encoded str and its encoding cannot be specified.", "# In PY3, it...
43.028571
23.714286
def with_args(self, *args, **kwargs): """Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge ...
[ "def", "with_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "expected_args", "=", "args", "if", "kwargs", ":", "exp", ".", "expected_kwar...
30.848485
26.075758
async def add(request: web.Request) -> web.Response: """ Add a public key to the authorized_keys file. POST /server/ssh_keys {"key": key string} -> 201 Created If the key string doesn't look like an openssh public key, rejects with 400 """ body = await request.json() if 'key' not in body o...
[ "async", "def", "add", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "body", "=", "await", "request", ".", "json", "(", ")", "if", "'key'", "not", "in", "body", "or", "not", "isinstance", "(", "body", "[", "'ke...
38.522727
18.704545
def list(self, s3_folder='', full_key_data=False): """Get a list of keys for the accounts""" if not s3_folder.startswith('/'): s3_folder = '/' + s3_folder s3_prefix = self.prefix + s3_folder bucket_data = self.client.list_objects(Bucket=self.bucket, Prefix=s3_prefix) ...
[ "def", "list", "(", "self", ",", "s3_folder", "=", "''", ",", "full_key_data", "=", "False", ")", ":", "if", "not", "s3_folder", ".", "startswith", "(", "'/'", ")", ":", "s3_folder", "=", "'/'", "+", "s3_folder", "s3_prefix", "=", "self", ".", "prefix"...
34.461538
18.846154
def get_table_name(self, ind): """ Return both the table_name (i.e., 'specimens') and the col_name (i.e., 'specimen') for a given index in self.ancestry. """ if ind >= len(self.ancestry): return "", "" if ind > -1: table_name = self.ancestr...
[ "def", "get_table_name", "(", "self", ",", "ind", ")", ":", "if", "ind", ">=", "len", "(", "self", ".", "ancestry", ")", ":", "return", "\"\"", ",", "\"\"", "if", "ind", ">", "-", "1", ":", "table_name", "=", "self", ".", "ancestry", "[", "ind", ...
32.428571
7.714286
def unique(items, key=None): """ Generates unique items in the order they appear. Args: items (Iterable): list of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. Yields: object: a unique item fr...
[ "def", "unique", "(", "items", ",", "key", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "if", "key", "is", "None", ":", "for", "item", "in", "items", ":", "if", "item", "not", "in", "seen", ":", "seen", ".", "add", "(", "item", ")", "...
30.333333
20.142857
async def handle_player_update(self, state: "node.PlayerState"): """ Handles player updates from lavalink. Parameters ---------- state : websocket.PlayerState """ if state.position > self.position: self._is_playing = True self.position = state...
[ "async", "def", "handle_player_update", "(", "self", ",", "state", ":", "\"node.PlayerState\"", ")", ":", "if", "state", ".", "position", ">", "self", ".", "position", ":", "self", ".", "_is_playing", "=", "True", "self", ".", "position", "=", "state", "."...
29
11.363636
def get_container(self, path): """Return single container.""" if not settings.container_permitted(path): raise errors.NotPermittedException( "Access to container \"%s\" is not permitted." % path) return self._get_container(path)
[ "def", "get_container", "(", "self", ",", "path", ")", ":", "if", "not", "settings", ".", "container_permitted", "(", "path", ")", ":", "raise", "errors", ".", "NotPermittedException", "(", "\"Access to container \\\"%s\\\" is not permitted.\"", "%", "path", ")", ...
45.833333
9.5
def _crossover_a_pair(chromosome_1, chromosome_2, mask): """! @brief Crossovers a pair of chromosomes. @param[in] chromosome_1 (numpy.array): The first chromosome for crossover. @param[in] chromosome_2 (numpy.array): The second chromosome for crossover. @param[in] mask (...
[ "def", "_crossover_a_pair", "(", "chromosome_1", ",", "chromosome_2", ",", "mask", ")", ":", "for", "_idx", "in", "range", "(", "len", "(", "chromosome_1", ")", ")", ":", "if", "mask", "[", "_idx", "]", "==", "1", ":", "# Swap values", "chromosome_1", "[...
40.333333
26
def markdown(value, arg=None): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. Syntax: :: {{value|markdown}} {{value|markdown:"tables,codehilite"}} :returns: A rendered markdown ""...
[ "def", "markdown", "(", "value", ",", "arg", "=", "None", ")", ":", "extensions", "=", "(", "arg", "and", "arg", ".", "split", "(", "','", ")", ")", "or", "settings", ".", "MARKDOWN_EXTENSIONS", "return", "_markdown", "(", "value", ",", "extensions", "...
27.6875
24.4375
def ProcessContent(self, strip_expansion=False): """Processes the file contents.""" self._ParseFile() if strip_expansion: # Without a collection the expansions become blank, removing them. collection = None else: collection = MacroCollection() for section in self._sections: s...
[ "def", "ProcessContent", "(", "self", ",", "strip_expansion", "=", "False", ")", ":", "self", ".", "_ParseFile", "(", ")", "if", "strip_expansion", ":", "# Without a collection the expansions become blank, removing them.", "collection", "=", "None", "else", ":", "coll...
33
13.285714
def remove_non_ground_states(self): """ Removes all non-ground state entries, i.e., only keep the lowest energy per atom entry at each composition. """ group_func = lambda e: e.composition.reduced_formula entries = sorted(self.entries, key=group_func) ground_state...
[ "def", "remove_non_ground_states", "(", "self", ")", ":", "group_func", "=", "lambda", "e", ":", "e", ".", "composition", ".", "reduced_formula", "entries", "=", "sorted", "(", "self", ".", "entries", ",", "key", "=", "group_func", ")", "ground_states", "=",...
44.636364
13.545455
def set_dtreat_indch(self, indch=None): """ Store the desired index array for the channels If None => all channels Must be a 1d array """ if indch is not None: indch = np.asarray(indch) assert indch.ndim==1 indch = _format_ind(indch, n=self._ddat...
[ "def", "set_dtreat_indch", "(", "self", ",", "indch", "=", "None", ")", ":", "if", "indch", "is", "not", "None", ":", "indch", "=", "np", ".", "asarray", "(", "indch", ")", "assert", "indch", ".", "ndim", "==", "1", "indch", "=", "_format_ind", "(", ...
30.615385
11.461538
def _parse_sig(sig, arg_names, validate=False): """ Parses signatures into a ``OrderedDict`` of paramName => type. Numerically-indexed arguments that do not correspond to an argument name in python (ie: it takes a variable number of arguments) will be keyed as the stringified version of it's index. ...
[ "def", "_parse_sig", "(", "sig", ",", "arg_names", ",", "validate", "=", "False", ")", ":", "d", "=", "SIG_RE", ".", "match", "(", "sig", ")", "if", "not", "d", ":", "raise", "ValueError", "(", "'Invalid method signature %s'", "%", "sig", ")", "d", "="...
45.857143
17.938776
def write_real (self, url_data): """Write url_data.url.""" self.writeln("<tr><td>"+self.part("realurl")+u"</td><td>"+ u'<a target="top" href="'+url_data.url+ u'">'+cgi.escape(url_data.url)+u"</a></td></tr>")
[ "def", "write_real", "(", "self", ",", "url_data", ")", ":", "self", ".", "writeln", "(", "\"<tr><td>\"", "+", "self", ".", "part", "(", "\"realurl\"", ")", "+", "u\"</td><td>\"", "+", "u'<a target=\"top\" href=\"'", "+", "url_data", ".", "url", "+", "u'\">'...
52.2
16.8
def clean_text(text): """Clean text for TFIDF.""" new_text = re.sub(ur'\p{P}+', ' ', text) new_text = [stem(i) for i in new_text.lower().split() if not re.findall(r'[0-9]', i)] new_text = ' '.join(new_text) return new_text
[ "def", "clean_text", "(", "text", ")", ":", "new_text", "=", "re", ".", "sub", "(", "ur'\\p{P}+'", ",", "' '", ",", "text", ")", "new_text", "=", "[", "stem", "(", "i", ")", "for", "i", "in", "new_text", ".", "lower", "(", ")", ".", "split", "(",...
25.2
19.5
async def get_attached_modules(request): """ On success (including an empty "modules" list if no modules are detected): // status: 200 { "modules": [ { /** name of module */ "name": "string", /** model identifier (i.e. part number) */ ...
[ "async", "def", "get_attached_modules", "(", "request", ")", ":", "hw", "=", "hw_from_req", "(", "request", ")", "if", "ff", ".", "use_protocol_api_v2", "(", ")", ":", "hw_mods", "=", "await", "hw", ".", "discover_modules", "(", ")", "module_data", "=", "[...
31.333333
16.031746
def get_proficiency_query_session_for_objective_bank(self, objective_bank_id): """Gets the ``OsidSession`` associated with the proficiency query service for the given objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of the obective bank return: (osid.learning.P...
[ "def", "get_proficiency_query_session_for_objective_bank", "(", "self", ",", "objective_bank_id", ")", ":", "if", "not", "self", ".", "supports_proficiency_query", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "##", "# Also include check to see if th...
49.2
21.44
def count_star(session: Union[Session, Engine, Connection], tablename: str, *criteria: Any) -> int: """ Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`...
[ "def", "count_star", "(", "session", ":", "Union", "[", "Session", ",", "Engine", ",", "Connection", "]", ",", "tablename", ":", "str", ",", "*", "criteria", ":", "Any", ")", "->", "int", ":", "# works if you pass a connection or a session or an engine; all have",...
34.454545
16.272727
def check_atd(text): """Check for redundancies from After the Deadline.""" err = "after_the_deadline.redundancy" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ [u"Bō", ["Bo Staff"]], ["Challah", ["Challah bread"]], ["Hallah", ["...
[ "def", "check_atd", "(", "text", ")", ":", "err", "=", "\"after_the_deadline.redundancy\"", "msg", "=", "\"Redundancy. Use '{}' instead of '{}'.\"", "redundancies", "=", "[", "[", "u\"Bō\",", " ", "\"", "Bo Staff\"]", "]", ",", "", "[", "\"Challah\"", ",", "[", ...
52.287324
13.112676
def stations(self, *, generated=True, library=True): """Get a listing of library stations. The listing can contain stations added to the library and generated from the library. Parameters: generated (bool, Optional): Include generated stations. Default: True library (bool, Optional): Include library s...
[ "def", "stations", "(", "self", ",", "*", ",", "generated", "=", "True", ",", "library", "=", "True", ")", ":", "station_list", "=", "[", "]", "for", "chunk", "in", "self", ".", "stations_iter", "(", "page_size", "=", "49995", ")", ":", "for", "stati...
25.76
22.16
def pop_configuration(self): """ Pushes the currently active configuration from the stack of configurations managed by this mapping. :raises IndexError: If there is only one configuration in the stack. """ if len(self.__configurations) == 1: raise IndexError(...
[ "def", "pop_configuration", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__configurations", ")", "==", "1", ":", "raise", "IndexError", "(", "'Can not pop the last configuration from the '", "'stack of configurations.'", ")", "self", ".", "__configurations",...
40.75
15.083333
def get_file_path(self, file_ref): """ Parameters ---------- file_ref: str reference of file. Available references: 'idf', 'epw', 'eio', 'eso', 'mtr', 'mtd', 'mdd', 'err', 'summary_table' See EnergyPlus documentation for more information. Ret...
[ "def", "get_file_path", "(", "self", ",", "file_ref", ")", ":", "if", "not", "self", ".", "exists", "(", "file_ref", ")", ":", "raise", "FileNotFoundError", "(", "\"File '%s' not found in simulation '%s'.\"", "%", "(", "file_ref", ",", "self", ".", "_path", "(...
35.125
21.375
def _lemke_howson_tbl(tableaux, bases, init_pivot, max_iter): """ Main body of the Lemke-Howson algorithm implementation. Perform the complementary pivoting. Modify `tablaux` and `bases` in place. Parameters ---------- tableaux : tuple(ndarray(float, ndim=2)) Tuple of two arrays co...
[ "def", "_lemke_howson_tbl", "(", "tableaux", ",", "bases", ",", "init_pivot", ",", "max_iter", ")", ":", "init_player", "=", "0", "for", "k", "in", "bases", "[", "0", "]", ":", "if", "k", "==", "init_pivot", ":", "init_player", "=", "1", "break", "pls"...
31.09
22.45
def get_configuration(cls, resource): """ Return how much consumables are used by resource with current configuration. Output example: { <ConsumableItem instance>: <usage>, <ConsumableItem instance>: <usage>, ... } """ ...
[ "def", "get_configuration", "(", "cls", ",", "resource", ")", ":", "strategy", "=", "cls", ".", "_get_strategy", "(", "resource", ".", "__class__", ")", "return", "strategy", ".", "get_configuration", "(", "resource", ")" ]
34.75
15
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`SSHKey` require...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "# read() should not change the state of the object it's called on, but", "# super() alters the attributes of any entity ...
38.884615
22.846154
def get_pause_time(self, speed=ETHER_SPEED_MBIT_1000): """ get pause time for given link speed in seconds :param speed: select link speed to get the pause time for, must be ETHER_SPEED_MBIT_[10,100,1000] # noqa: E501 :return: pause time in seconds :raises MACControlInvalidSpeed...
[ "def", "get_pause_time", "(", "self", ",", "speed", "=", "ETHER_SPEED_MBIT_1000", ")", ":", "try", ":", "return", "self", ".", "pause_time", "*", "{", "ETHER_SPEED_MBIT_10", ":", "(", "0.0000001", "*", "512", ")", ",", "ETHER_SPEED_MBIT_100", ":", "(", "0.00...
45.722222
25.388889
async def add_reactions(self): """Adds the reactions buttons to the current message""" self.statuslog.info("Loading buttons") for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"): try: if self.embed is not None: await client.add_reaction(self.embed.sent...
[ "async", "def", "add_reactions", "(", "self", ")", ":", "self", ".", "statuslog", ".", "info", "(", "\"Loading buttons\"", ")", "for", "e", "in", "(", "\"⏯\", ", "\"", "\", \"⏹", "\"", " \"⏭\",", " ", "🔀\", \"", "🔉", ", \"🔊\")", ":", "", "", "", "",...
46.916667
13.333333
def http_request(url, post_data=None): '''Make an HTTP request to a given URL with optional parameters. ''' logger.debug('Requesting URL: %s' % url) buf = bio() curl = pycurl.Curl() curl.setopt(curl.URL, url.encode('ascii', 'ignore')) # Disable HTTPS verification methods if insecure is set ...
[ "def", "http_request", "(", "url", ",", "post_data", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Requesting URL: %s'", "%", "url", ")", "buf", "=", "bio", "(", ")", "curl", "=", "pycurl", ".", "Curl", "(", ")", "curl", ".", "setopt", "(", ...
37.294118
17
def targets(self, predicate=None, **kwargs): """Selects targets in-play in this run from the target roots and their transitive dependencies. Also includes any new synthetic targets created from the target roots or their transitive dependencies during the course of the run. See Target.closure_for_targe...
[ "def", "targets", "(", "self", ",", "predicate", "=", "None", ",", "*", "*", "kwargs", ")", ":", "target_set", "=", "self", ".", "_collect_targets", "(", "self", ".", "target_roots", ",", "*", "*", "kwargs", ")", "synthetics", "=", "OrderedSet", "(", "...
44.44
26.12
def validate_block(self, block: BaseBlock) -> None: """ Validate the the given block. """ if not isinstance(block, self.get_block_class()): raise ValidationError( "This vm ({0!r}) is not equipped to validate a block of type {1!r}".format( s...
[ "def", "validate_block", "(", "self", ",", "block", ":", "BaseBlock", ")", "->", "None", ":", "if", "not", "isinstance", "(", "block", ",", "self", ".", "get_block_class", "(", ")", ")", ":", "raise", "ValidationError", "(", "\"This vm ({0!r}) is not equipped ...
39.714286
18.979592
def _l_skew_weight(self, donor_catchment): """ Return L-SKEW weighting for donor catchment. Methodology source: Science Report SC050050, eqn. 6.19 and 6.22b """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._simila...
[ "def", "_l_skew_weight", "(", "self", ",", "donor_catchment", ")", ":", "try", ":", "dist", "=", "donor_catchment", ".", "similarity_dist", "except", "AttributeError", ":", "dist", "=", "self", ".", "_similarity_distance", "(", "self", ".", "catchment", ",", "...
37.307692
15.923077
def get_term_by_sis_id(self, sis_term_id): """ Return a term resource for the passed SIS ID. """ for term in self.get_all_terms(): if term.sis_term_id == sis_term_id: return term
[ "def", "get_term_by_sis_id", "(", "self", ",", "sis_term_id", ")", ":", "for", "term", "in", "self", ".", "get_all_terms", "(", ")", ":", "if", "term", ".", "sis_term_id", "==", "sis_term_id", ":", "return", "term" ]
33.142857
5.142857
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this mod...
[ "def", "graph_structure", "(", "self", ",", "x", ",", "standalone", "=", "True", ")", ":", "if", "standalone", ":", "x", "=", "tf", ".", "concat", "(", "tf", ".", "split", "(", "x", ",", "2", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ...
66.403846
41.557692
def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.rstrip() + '\n' file_mode = getattr(logfile, 'mode', None) if file_mode is not None: if 'b' in file_mode: ...
[ "def", "log", "(", "self", ",", "logfile", "=", "None", ")", ":", "if", "logfile", "is", "None", ":", "logfile", "=", "sys", ".", "stderr", "tb", "=", "self", ".", "plaintext", ".", "rstrip", "(", ")", "+", "'\\n'", "file_mode", "=", "getattr", "("...
33.636364
10.272727
def _retry(function): """ Internal mechanism to try to send data to multiple Solr Hosts if the query fails on the first one. """ def inner(self, **kwargs): last_exception = None #for host in self.router.get_hosts(**kwargs): for host in self.ho...
[ "def", "_retry", "(", "function", ")", ":", "def", "inner", "(", "self", ",", "*", "*", "kwargs", ")", ":", "last_exception", "=", "None", "#for host in self.router.get_hosts(**kwargs):", "for", "host", "in", "self", ".", "host", ":", "try", ":", "return", ...
40.041667
15.125
def reverse(path): """Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/...
[ "def", "reverse", "(", "path", ")", ":", "if", "is_rooted", "(", "path", ")", "or", "'..'", "in", "path", ":", "from", "b2", ".", "manager", "import", "get_manager", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "'reverse(path): path is either roo...
29.413793
18
def set_default_bg(): """Get bacground from default values based on the TERM environment variable """ term = environ.get('TERM', None) if term: if (term.startswith('xterm',) or term.startswith('eterm') or term == 'dtterm'): return False return True
[ "def", "set_default_bg", "(", ")", ":", "term", "=", "environ", ".", "get", "(", "'TERM'", ",", "None", ")", "if", "term", ":", "if", "(", "term", ".", "startswith", "(", "'xterm'", ",", ")", "or", "term", ".", "startswith", "(", "'eterm'", ")", "o...
29.5
14.1
def report(self, align_bam, ref_file, gtf_file, is_paired=False, rrna_file="null"): """Produce report metrics for a RNASeq experiment using Picard with a sorted aligned BAM file. """ # collect duplication metrics dup_metrics = self._get_current_dup_metrics(align_bam) al...
[ "def", "report", "(", "self", ",", "align_bam", ",", "ref_file", ",", "gtf_file", ",", "is_paired", "=", "False", ",", "rrna_file", "=", "\"null\"", ")", ":", "# collect duplication metrics", "dup_metrics", "=", "self", ".", "_get_current_dup_metrics", "(", "ali...
45.791667
23.166667
def detectIphone(self): """Return detection of an iPhone Detects if the current device is an iPhone. """ # The iPad and iPod touch say they're an iPhone! So let's disambiguate. return UAgentInfo.deviceIphone in self.__userAgent \ and not self.detectIpad() \ ...
[ "def", "detectIphone", "(", "self", ")", ":", "# The iPad and iPod touch say they're an iPhone! So let's disambiguate.", "return", "UAgentInfo", ".", "deviceIphone", "in", "self", ".", "__userAgent", "and", "not", "self", ".", "detectIpad", "(", ")", "and", "not", "se...
37.777778
14.555556
def convert(self, lat, lon, source, dest, height=0, datetime=None, precision=1e-10, ssheight=50*6371): """Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Long...
[ "def", "convert", "(", "self", ",", "lat", ",", "lon", ",", "source", ",", "dest", ",", "height", "=", "0", ",", "datetime", "=", "None", ",", "precision", "=", "1e-10", ",", "ssheight", "=", "50", "*", "6371", ")", ":", "if", "datetime", "is", "...
44.617978
19.460674
def get(self, field_name, default=None): """Like dict.get, except that it checks that the field name is defined by the simple registration specification""" checkFieldName(field_name) return self.data.get(field_name, default)
[ "def", "get", "(", "self", ",", "field_name", ",", "default", "=", "None", ")", ":", "checkFieldName", "(", "field_name", ")", "return", "self", ".", "data", ".", "get", "(", "field_name", ",", "default", ")" ]
50.4
3
def group_and_order_srv_records(all_records, rng=None): """ Order a list of SRV record information (as returned by :func:`lookup_srv`) and group and order them as specified by the RFC. Return an iterable, yielding each ``(hostname, port)`` tuple inside the SRV records in the order specified by the ...
[ "def", "group_and_order_srv_records", "(", "all_records", ",", "rng", "=", "None", ")", ":", "rng", "=", "rng", "or", "random", "all_records", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", ":", "2", "]", ")", "for", "priority", ",", "re...
32.756757
17.243243
def _format_ase2clusgeo(obj, all_atomtypes=None): """ Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo. Apos is currently a flattened out numpy array Args: obj(): all_atomtypes(): sort(): """ #atoms metadata total...
[ "def", "_format_ase2clusgeo", "(", "obj", ",", "all_atomtypes", "=", "None", ")", ":", "#atoms metadata", "totalAN", "=", "len", "(", "obj", ")", "if", "all_atomtypes", "is", "not", "None", ":", "atomtype_set", "=", "set", "(", "all_atomtypes", ")", "else", ...
30.058824
16.411765
def str2dict_values(str_in): ''' Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: - ''' tmp_dict = str2d...
[ "def", "str2dict_values", "(", "str_in", ")", ":", "tmp_dict", "=", "str2dict", "(", "str_in", ")", "if", "tmp_dict", "is", "None", ":", "return", "None", "return", "[", "tmp_dict", "[", "key", "]", "for", "key", "in", "sorted", "(", "k", "for", "k", ...
26.6875
24.8125
def _gregorian_to_ssweek(date_value): "Sundaystarting-week year, week and day for the given Gregorian calendar date" yearStart = _ssweek_year_start(date_value.year) weekNum = ((date_value - yearStart).days) // 7 + 1 dayOfWeek = date_value.weekday()+1 return (date_value.year, weekNum, dayOfWeek)
[ "def", "_gregorian_to_ssweek", "(", "date_value", ")", ":", "yearStart", "=", "_ssweek_year_start", "(", "date_value", ".", "year", ")", "weekNum", "=", "(", "(", "date_value", "-", "yearStart", ")", ".", "days", ")", "//", "7", "+", "1", "dayOfWeek", "=",...
51.833333
13.5
def find_environment_dirs(environment_name=None, data_only=False): """ :param environment_name: exising environment name, path or None to look in current or parent directories for project returns (srcdir, extension_dir, datadir) extension_dir is the name of extension directory user was in/ref...
[ "def", "find_environment_dirs", "(", "environment_name", "=", "None", ",", "data_only", "=", "False", ")", ":", "docker", ".", "require_images", "(", ")", "if", "environment_name", "is", "None", ":", "environment_name", "=", "'.'", "extension_dir", "=", "'ckan'"...
34.320755
22.09434
def read_one(self, sequence): """ Reads one item from the Ringbuffer. If the sequence is one beyond the current tail, this call blocks until an item is added. Currently it isn't possible to control how long this call is going to block. :param sequence: (long), the sequence of the item t...
[ "def", "read_one", "(", "self", ",", "sequence", ")", ":", "check_not_negative", "(", "sequence", ",", "\"sequence can't be smaller than 0\"", ")", "return", "self", ".", "_encode_invoke", "(", "ringbuffer_read_one_codec", ",", "sequence", "=", "sequence", ")" ]
52.6
28.6
def overview(name, server): """ Overview of the server as seen through the properties of the server class. """ print('%s OVERVIEW' % name) print(" Interop namespace: %s" % server.interop_ns) print(" Brand: %s" % server.brand) print(" Version: %s" % server.version) print(" Namespa...
[ "def", "overview", "(", "name", ",", "server", ")", ":", "print", "(", "'%s OVERVIEW'", "%", "name", ")", "print", "(", "\" Interop namespace: %s\"", "%", "server", ".", "interop_ns", ")", "print", "(", "\" Brand: %s\"", "%", "server", ".", "brand", ")", ...
42.125
17.8125
def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the ...
[ "def", "_graphics_equal", "(", "gfx1", ",", "gfx2", ")", ":", "def", "_filter_graphics", "(", "gfx", ")", ":", "'''\n When the domain is running, the graphics element may contain additional properties\n with the default values. This function will strip down the default valu...
44.608696
30
def copy(self, site_properties=None, sanitize=False): """ Convenience method to get a copy of the structure, with options to add site properties. Args: site_properties (dict): Properties to add or override. The properties are specified in the same way as the ...
[ "def", "copy", "(", "self", ",", "site_properties", "=", "None", ",", "sanitize", "=", "False", ")", ":", "props", "=", "self", ".", "site_properties", "if", "site_properties", ":", "props", ".", "update", "(", "site_properties", ")", "if", "not", "sanitiz...
48.111111
20.955556
def _handle_substatements(self, stmt: Statement, sctx: SchemaContext) -> None: """Dispatch actions for substatements of `stmt`.""" for s in stmt.substatements: if s.prefix: key = ( sctx.schema_data.modules[sctx.text_mid].prefix_map[s.prefix][0] ...
[ "def", "_handle_substatements", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "None", ":", "for", "s", "in", "stmt", ".", "substatements", ":", "if", "s", ".", "prefix", ":", "key", "=", "(", "sctx", ".", "...
43.333333
15.75
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import u...
[ "def", "as_coeff_unit", "(", "self", ")", ":", "coeff", ",", "mul", "=", "self", ".", "expr", ".", "as_coeff_Mul", "(", ")", "coeff", "=", "float", "(", "coeff", ")", "ret", "=", "Unit", "(", "mul", ",", "self", ".", "base_value", "/", "coeff", ","...
26.37037
18.333333
def seoify_hyperlink(hyperlink): """Modify a hyperlink to make it SEO-friendly by replacing hyphens with spaces and trimming multiple spaces. :param hyperlink: URL to attempt to grab SEO from """ last_slash = hyperlink.rfind('/') return re.sub(r' +|-', ' ', hyperlink[last_slash + 1:])
[ "def", "seoify_hyperlink", "(", "hyperlink", ")", ":", "last_slash", "=", "hyperlink", ".", "rfind", "(", "'/'", ")", "return", "re", ".", "sub", "(", "r' +|-'", ",", "' '", ",", "hyperlink", "[", "last_slash", "+", "1", ":", "]", ")" ]
42.857143
11.857143
def ensure_compatible_admin(view): """ Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. """ def wrapper(request, *args, **kwargs): user_roles = request.user.user_data.get('roles', []) if len(user_roles) ...
[ "def", "ensure_compatible_admin", "(", "view", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_roles", "=", "request", ".", "user", ".", "user_data", ".", "get", "(", "'roles'", ",", "[", "]", ")...
38.705882
21.411765
def main(): """ AWS support script's main method """ p = argparse.ArgumentParser(description='Manage Amazon AWS services', prog='aws', version=__version__) subparsers = p.add_subparsers(help='Select Amazon AWS service to use') # Au...
[ "def", "main", "(", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Manage Amazon AWS services'", ",", "prog", "=", "'aws'", ",", "version", "=", "__version__", ")", "subparsers", "=", "p", ".", "add_subparsers", "(", "help"...
60.844037
37.889908
def generate_matching_datasets(self, data_slug): """Return datasets that match data_slug (hub_slug).""" matching_datasets = Dataset.objects.filter( hub_slug=data_slug ).order_by('-date_uploaded') if len(matching_datasets) > 0: return matching_datasets els...
[ "def", "generate_matching_datasets", "(", "self", ",", "data_slug", ")", ":", "matching_datasets", "=", "Dataset", ".", "objects", ".", "filter", "(", "hub_slug", "=", "data_slug", ")", ".", "order_by", "(", "'-date_uploaded'", ")", "if", "len", "(", "matching...
33.7
12.3
def send(self, message, level=Level.NOTICE): "Send a syslog message to remote host using UDP or TCP" data = "<%d>%s" % (level + self.facility*8, message) if self.protocol == 'UDP': self.socket.sendto(data.encode('utf-8'), (self.host, self.port)) else: self.socket.send(data.encode('utf-8'...
[ "def", "send", "(", "self", ",", "message", ",", "level", "=", "Level", ".", "NOTICE", ")", ":", "data", "=", "\"<%d>%s\"", "%", "(", "level", "+", "self", ".", "facility", "*", "8", ",", "message", ")", "if", "self", ".", "protocol", "==", "'UDP'"...
45.142857
16.857143
def oauth_error_handler(f): """Decorator to handle exceptions.""" @wraps(f) def inner(*args, **kwargs): # OAuthErrors should not happen, so they are not caught here. Hence # they will result in a 500 Internal Server Error which is what we # are interested in. try: ...
[ "def", "oauth_error_handler", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# OAuthErrors should not happen, so they are not caught here. Hence", "# they will result in a 500 Internal Server Error ...
42.75
15.785714
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m: rai...
[ "def", "strip_bewit", "(", "url", ")", ":", "m", "=", "re", ".", "search", "(", "'[?&]bewit=([^&]+)'", ",", "url", ")", "if", "not", "m", ":", "raise", "InvalidBewit", "(", "'no bewit data found'", ")", "bewit", "=", "m", ".", "group", "(", "1", ")", ...
24.777778
15.222222
def use(module=None, decode=None, encode=None): """Set the JSON library that should be used, either by specifying a known module name, or by providing a decode and encode function. The modules "simplejson", "cjson", and "json" are currently supported for the ``module`` parameter. If provided, the ...
[ "def", "use", "(", "module", "=", "None", ",", "decode", "=", "None", ",", "encode", "=", "None", ")", ":", "global", "_decode", ",", "_encode", ",", "_initialized", ",", "_using", "if", "module", "is", "not", "None", ":", "if", "not", "isinstance", ...
41.171429
18.942857
def _get_access_token(self, verifier=None): """ Fetch an access token from `self.access_token_url`. """ response, content = self.client(verifier).request( self.access_token_url, "POST") content = smart_unicode(content) if not response['statu...
[ "def", "_get_access_token", "(", "self", ",", "verifier", "=", "None", ")", ":", "response", ",", "content", "=", "self", ".", "client", "(", "verifier", ")", ".", "request", "(", "self", ".", "access_token_url", ",", "\"POST\"", ")", "content", "=", "sm...
33.95
19.95
def make_handlers(base_url, server_processes): """ Get tornado handlers for registered server_processes """ handlers = [] for sp in server_processes: handler = _make_serverproxy_handler( sp.name, sp.command, sp.environment, sp.timeout, ...
[ "def", "make_handlers", "(", "base_url", ",", "server_processes", ")", ":", "handlers", "=", "[", "]", "for", "sp", "in", "server_processes", ":", "handler", "=", "_make_serverproxy_handler", "(", "sp", ".", "name", ",", "sp", ".", "command", ",", "sp", "....
27.190476
16.333333
def get_form(self, request, obj=None, **kwargs): """ Build the form used for changing the model. """ kwargs.update(widgets={ 'plugin_type': widgets.Select(choices=self.plugins_for_site), 'css_classes': JSONMultiWidget(self.classname_fields), 'inline_st...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "widgets", "=", "{", "'plugin_type'", ":", "widgets", ".", "Select", "(", "choices", "=", "self", ".", "plugins_...
49.466667
21.333333
def proto_fill_from_dict(message, data, clear=True): """Fills protobuf message parameters inplace from a :class:`dict` :param message: protobuf message instance :param data: parameters and values :type data: dict :param clear: whether clear exisiting values :type clear: bool :return: value ...
[ "def", "proto_fill_from_dict", "(", "message", ",", "data", ",", "clear", "=", "True", ")", ":", "if", "not", "isinstance", "(", "message", ",", "_ProtoMessageType", ")", ":", "raise", "TypeError", "(", "\"Expected `message` to be a instance of protobuf message\"", ...
38.326531
20.530612
def set_channel_groups(self, channel_ids, groups): '''This function sets the group property of each specified channel id with the corresponding group of the passed in groups list. Parameters ---------- channel_ids: array_like The channel ids (ints) for which the grou...
[ "def", "set_channel_groups", "(", "self", ",", "channel_ids", ",", "groups", ")", ":", "if", "len", "(", "channel_ids", ")", "==", "len", "(", "groups", ")", ":", "for", "i", "in", "range", "(", "len", "(", "channel_ids", ")", ")", ":", "if", "isinst...
44.263158
23.421053
def check_all(self, all_entries, *args, **kwargs): """ Go through lists of entries, find overlaps among each, return the total """ all_overlaps = 0 while True: try: user_entries = all_entries.next() except StopIteration: ret...
[ "def", "check_all", "(", "self", ",", "all_entries", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_overlaps", "=", "0", "while", "True", ":", "try", ":", "user_entries", "=", "all_entries", ".", "next", "(", ")", "except", "StopIteration", ...
35.714286
13.571429
def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: ...
[ "def", "_is_hostmask", "(", "self", ",", "ip_str", ")", ":", "bits", "=", "ip_str", ".", "split", "(", "'.'", ")", "try", ":", "parts", "=", "[", "x", "for", "x", "in", "map", "(", "int", ",", "bits", ")", "if", "x", "in", "self", ".", "_valid_...
28.05
19.15
def retry(*excepts): '''A decorator to specify a bunch of exceptions that should be caught and the job retried. It turns out this comes up with relative frequency''' @decorator.decorator def new_func(func, job): '''No docstring''' try: func(job) except tuple(excepts):...
[ "def", "retry", "(", "*", "excepts", ")", ":", "@", "decorator", ".", "decorator", "def", "new_func", "(", "func", ",", "job", ")", ":", "'''No docstring'''", "try", ":", "func", "(", "job", ")", "except", "tuple", "(", "excepts", ")", ":", "job", "....
32.181818
20.727273
def update_from_xso_item(self, xso_item): """ Update the attributes (except :attr:`jid`) with the values obtained from the gixen `xso_item`. `xso_item` must be a valid :class:`.xso.Item` instance. """ self.subscription = xso_item.subscription self.approved = xso_...
[ "def", "update_from_xso_item", "(", "self", ",", "xso_item", ")", ":", "self", ".", "subscription", "=", "xso_item", ".", "subscription", "self", ".", "approved", "=", "xso_item", ".", "approved", "self", ".", "ask", "=", "xso_item", ".", "ask", "self", "....
37.666667
12.833333
def main(): """ Runs a filter from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ parser = argparse.ArgumentParser( description='Executes a filter from the command-line. Calls JVM start/stop automatically.') parser.add_argument("-j", metavar="classpa...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Executes a filter from the command-line. Calls JVM start/stop automatically.'", ")", "parser", ".", "add_argument", "(", "\"-j\"", ",", "metavar", "=", "\"classpat...
44.2
20.2
def param_remove(self, param: 'str') -> None: """ Remove a param from this model :param param: name of the parameter to be removed :type param: str """ for attr in self._param_attr_dicts: if param in self.__dict__[attr]: self.__dict__[attr].po...
[ "def", "param_remove", "(", "self", ",", "param", ":", "'str'", ")", "->", "None", ":", "for", "attr", "in", "self", ".", "_param_attr_dicts", ":", "if", "param", "in", "self", ".", "__dict__", "[", "attr", "]", ":", "self", ".", "__dict__", "[", "at...
32.5
10.642857
def is_set(self): """Returns True if the request has finished or False if it is still pending. Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a network related problem. """ if self.__event.is_set(): if self...
[ "def", "is_set", "(", "self", ")", ":", "if", "self", ".", "__event", ".", "is_set", "(", ")", ":", "if", "self", ".", "exception", "is", "not", "None", ":", "# todo better way to raise errors on behalf of other Threads?", "raise", "self", ".", "exception", "#...
44
21.916667
def create_empty(self, name=None, renderers=None, RootNetworkList=None, verbose=False): """ Create a new, empty network. The new network may be created as part of an existing network collection or a new network collection. :param name (string, optional): Enter the name of the new networ...
[ "def", "create_empty", "(", "self", ",", "name", "=", "None", ",", "renderers", "=", "None", ",", "RootNetworkList", "=", "None", ",", "verbose", "=", "False", ")", ":", "PARAMS", "=", "set_param", "(", "[", "\"name\"", ",", "\"renderers\"", ",", "\"Root...
60
31.111111
def writeSamples(self, data_list, digital = False): """ Writes physical samples (uV, mA, Ohm) from data belonging to all signals The physical samples will be converted to digital samples using the values of physical maximum, physical minimum, digital maximum and digital minimum. ...
[ "def", "writeSamples", "(", "self", ",", "data_list", ",", "digital", "=", "False", ")", ":", "if", "(", "len", "(", "data_list", ")", "!=", "len", "(", "self", ".", "channels", ")", ")", ":", "raise", "WrongInputSize", "(", "len", "(", "data_list", ...
48.506849
27.684932
def stop(self): """Output Checkstyle XML reports.""" et = ET.ElementTree(self.checkstyle_element) f = BytesIO() et.write(f, encoding='utf-8', xml_declaration=True) xml = f.getvalue().decode('utf-8') if self.output_fd is None: print(xml) else: ...
[ "def", "stop", "(", "self", ")", ":", "et", "=", "ET", ".", "ElementTree", "(", "self", ".", "checkstyle_element", ")", "f", "=", "BytesIO", "(", ")", "et", ".", "write", "(", "f", ",", "encoding", "=", "'utf-8'", ",", "xml_declaration", "=", "True",...
34.818182
12.272727
def _systemctl_status(name): ''' Helper function which leverages __context__ to keep from running 'systemctl status' more than once. ''' contextkey = 'systemd._systemctl_status.%s' % name if contextkey in __context__: return __context__[contextkey] __context__[contextkey] = __salt__[...
[ "def", "_systemctl_status", "(", "name", ")", ":", "contextkey", "=", "'systemd._systemctl_status.%s'", "%", "name", "if", "contextkey", "in", "__context__", ":", "return", "__context__", "[", "contextkey", "]", "__context__", "[", "contextkey", "]", "=", "__salt_...
32.533333
16.4
def eval(self, orig): """ Apply the less or equal algorithm on the ordered list of metadata statements :param orig: Start values :return: """ _le = {} _err = [] for k, v in self.sup_items(): if k in DoNotCompare: ...
[ "def", "eval", "(", "self", ",", "orig", ")", ":", "_le", "=", "{", "}", "_err", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "sup_items", "(", ")", ":", "if", "k", "in", "DoNotCompare", ":", "continue", "if", "k", "in", "orig", ":...
26.6
16.8
def read_local_files(*file_paths: str) -> str: """ Reads one or more text files and returns them joined together. A title is automatically created based on the file name. Args: *file_paths: list of files to aggregate Returns: content of files """ def _read_single_file(file_path): ...
[ "def", "read_local_files", "(", "*", "file_paths", ":", "str", ")", "->", "str", ":", "def", "_read_single_file", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ")", "as", "f", ":", "filename", "=", "os", ".", "path", ".", "splitext", "(...
31.388889
18.5
def circular_shift(X): """Shifts circularly the X squre matrix in order to get a time-lag matrix.""" N = X.shape[0] L = np.zeros(X.shape) for i in range(N): L[i, :] = np.asarray([X[(i + j) % N, j] for j in range(N)]) return L
[ "def", "circular_shift", "(", "X", ")", ":", "N", "=", "X", ".", "shape", "[", "0", "]", "L", "=", "np", ".", "zeros", "(", "X", ".", "shape", ")", "for", "i", "in", "range", "(", "N", ")", ":", "L", "[", "i", ",", ":", "]", "=", "np", ...
31.75
16