text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def filter(self, value=None, model=None, context=None): """ Sequentially applies all the filters to provided value :param value: a value to filter :param model: parent entity :param context: filtering context, usually parent entity :return: filtered value """ ...
[ "def", "filter", "(", "self", ",", "value", "=", "None", ",", "model", "=", "None", ",", "context", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "value", "for", "filter_obj", "in", "self", ".", "filters", ":", "value", "=", "f...
32.444444
13.444444
def search_for_devices_by_serial_number(self, sn): """ Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers. """ import re sn_search = re.compile(sn) matches = [] for dev...
[ "def", "search_for_devices_by_serial_number", "(", "self", ",", "sn", ")", ":", "import", "re", "sn_search", "=", "re", ".", "compile", "(", "sn", ")", "matches", "=", "[", "]", "for", "dev_o", "in", "self", ".", "get_all_devices_in_portal", "(", ")", ":",...
32.608696
18.521739
def GetMTime(path): ''' :param unicode path: Path to file or directory :rtype: float :returns: Modification time for path. If this is a directory, the highest mtime from files inside it will be returned. @note: In some Linux distros (such as CentOs, or anything wit...
[ "def", "GetMTime", "(", "path", ")", ":", "_AssertIsLocal", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "files", "=", "FindFiles", "(", "path", ")", "if", "len", "(", "files", ")", ">", "0", ":", "return", "max...
26.692308
27.769231
def create_edges(self): """Set up edge-node and edge-cell relations. """ # Reshape into individual edges. # Sort the columns to make it possible for `unique()` to identify # individual edges. s = self.idx_hierarchy.shape a = numpy.sort(self.idx_hierarchy.reshape(s...
[ "def", "create_edges", "(", "self", ")", ":", "# Reshape into individual edges.", "# Sort the columns to make it possible for `unique()` to identify", "# individual edges.", "s", "=", "self", ".", "idx_hierarchy", ".", "shape", "a", "=", "numpy", ".", "sort", "(", "self",...
31.666667
19.575758
def callprop(self, prop, *args): '''Call a property prop as a method (this will be self). NOTE: dont pass this and arguments here, these will be added automatically!''' if not isinstance(prop, basestring): prop = prop.to_string().value cand = self.get(prop) i...
[ "def", "callprop", "(", "self", ",", "prop", ",", "*", "args", ")", ":", "if", "not", "isinstance", "(", "prop", ",", "basestring", ")", ":", "prop", "=", "prop", ".", "to_string", "(", ")", ".", "value", "cand", "=", "self", ".", "get", "(", "pr...
40
14
def shift_up_left(self, times=1): """ Finds Location shifted up left by 1 :rtype: Location """ try: return Location(self._rank + times, self._file - times) except IndexError as e: raise IndexError(e)
[ "def", "shift_up_left", "(", "self", ",", "times", "=", "1", ")", ":", "try", ":", "return", "Location", "(", "self", ".", "_rank", "+", "times", ",", "self", ".", "_file", "-", "times", ")", "except", "IndexError", "as", "e", ":", "raise", "IndexErr...
26.3
13.9
def check_vprint(s, vprinter): '''checked verbose printing''' if vprinter is True: print(s); elif callable(vprinter): vprinter(s);
[ "def", "check_vprint", "(", "s", ",", "vprinter", ")", ":", "if", "vprinter", "is", "True", ":", "print", "(", "s", ")", "elif", "callable", "(", "vprinter", ")", ":", "vprinter", "(", "s", ")" ]
25.5
14.5
def serialize(self): """ Convert the data to one that can be saved in h5 structures Returns: pandas.DataFrame: like a cell data frame but serialized. columns """ df = self.copy() df['scored_calls'] = df['scored_calls'].apply(lambda x: json.dumps(x)) d...
[ "def", "serialize", "(", "self", ")", ":", "df", "=", "self", ".", "copy", "(", ")", "df", "[", "'scored_calls'", "]", "=", "df", "[", "'scored_calls'", "]", ".", "apply", "(", "lambda", "x", ":", "json", ".", "dumps", "(", "x", ")", ")", "df", ...
46.733333
27
def parse_object_type_extension(lexer: Lexer) -> ObjectTypeExtensionNode: """ObjectTypeExtension""" start = lexer.token expect_keyword(lexer, "extend") expect_keyword(lexer, "type") name = parse_name(lexer) interfaces = parse_implements_interfaces(lexer) directives = parse_directives(lexer, ...
[ "def", "parse_object_type_extension", "(", "lexer", ":", "Lexer", ")", "->", "ObjectTypeExtensionNode", ":", "start", "=", "lexer", ".", "token", "expect_keyword", "(", "lexer", ",", "\"extend\"", ")", "expect_keyword", "(", "lexer", ",", "\"type\"", ")", "name"...
33.888889
12.277778
def handle_presence(self, old_present): ''' Fire presence events if enabled ''' # On the first run it may need more time for the EventPublisher # to come up and be ready. Set the timeout to account for this. if self.presence_events and self.event.connect_pull(timeout=3): ...
[ "def", "handle_presence", "(", "self", ",", "old_present", ")", ":", "# On the first run it may need more time for the EventPublisher", "# to come up and be ready. Set the timeout to account for this.", "if", "self", ".", "presence_events", "and", "self", ".", "event", ".", "co...
46.368421
15.105263
def early_warning(iterable, name='this generator'): ''' This function logs an early warning that the generator is empty. This is handy for times when you're manually playing with generators and would appreciate the console warning you ahead of time that your generator is now empty, instead of being sur...
[ "def", "early_warning", "(", "iterable", ",", "name", "=", "'this generator'", ")", ":", "nxt", "=", "None", "prev", "=", "next", "(", "iterable", ")", "while", "1", ":", "try", ":", "nxt", "=", "next", "(", "iterable", ")", "except", ":", "warning", ...
33.55
24.95
def dataframe(self): """ Returns a ``pandas DataFrame`` containing all other relevant class properties and values for the specified game. """ fields_to_include = { 'assist_percentage': self.assist_percentage, 'assists': self.assists, 'block_per...
[ "def", "dataframe", "(", "self", ")", ":", "fields_to_include", "=", "{", "'assist_percentage'", ":", "self", ".", "assist_percentage", ",", "'assists'", ":", "self", ".", "assists", ",", "'block_percentage'", ":", "self", ".", "block_percentage", ",", "'blocks'...
51.478261
16.391304
def value_for_keypath(obj, path): """Get value from walking key path with start object obj. """ val = obj for part in path.split('.'): match = re.match(list_index_re, part) if match is not None: val = _extract(val, match.group(1)) if not isinstance(val, list) and ...
[ "def", "value_for_keypath", "(", "obj", ",", "path", ")", ":", "val", "=", "obj", "for", "part", "in", "path", ".", "split", "(", "'.'", ")", ":", "match", "=", "re", ".", "match", "(", "list_index_re", ",", "part", ")", "if", "match", "is", "not",...
33.529412
12.588235
def rigid_linear_interpolate(x_axis, y_axis, x_new_axis): """Interpolate a y = f(x) function using linear interpolation. Rigid means the x_new_axis has to be in x_axis's range. """ f = interp1d(x_axis, y_axis) return f(x_new_axis)
[ "def", "rigid_linear_interpolate", "(", "x_axis", ",", "y_axis", ",", "x_new_axis", ")", ":", "f", "=", "interp1d", "(", "x_axis", ",", "y_axis", ")", "return", "f", "(", "x_new_axis", ")" ]
35
14.285714
def get_plugin_meta(plugins): """ Returns meta data about plugins. :param plugins: A list of plugins. :type plugins: list :returns: A list of dicts containing plugin meta data. :rtype: list """ return [ { "name": p.name, "version": p.version, ...
[ "def", "get_plugin_meta", "(", "plugins", ")", ":", "return", "[", "{", "\"name\"", ":", "p", ".", "name", ",", "\"version\"", ":", "p", ".", "version", ",", "\"homepage\"", ":", "p", ".", "homepage", ",", "\"enabled\"", ":", "p", ".", "enabled", ",", ...
22.315789
16.105263
def CompleteBreakpoint(self, breakpoint_id): """Marks the specified breaking as completed. Appends the ID to set of completed breakpoints and clears it. Args: breakpoint_id: breakpoint ID to complete. """ with self._lock: self._completed.add(breakpoint_id) if breakpoint_id in sel...
[ "def", "CompleteBreakpoint", "(", "self", ",", "breakpoint_id", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_completed", ".", "add", "(", "breakpoint_id", ")", "if", "breakpoint_id", "in", "self", ".", "_active", ":", "self", ".", "_active",...
30.583333
14.583333
def facet_raw(self, **kw): """ Return a new S instance with raw facet args combined with existing set. """ items = kw.items() if six.PY3: items = list(items) return self._clone(next_step=('facet_raw', items))
[ "def", "facet_raw", "(", "self", ",", "*", "*", "kw", ")", ":", "items", "=", "kw", ".", "items", "(", ")", "if", "six", ".", "PY3", ":", "items", "=", "list", "(", "items", ")", "return", "self", ".", "_clone", "(", "next_step", "=", "(", "'fa...
29.777778
13.333333
def radio_buttons_clicked(self): """Handler when selected radio button changed.""" # Disable all spin boxes for spin_box in list(self.spin_boxes.values()): spin_box.setEnabled(False) # Disable list widget self.list_widget.setEnabled(False) # Get selected radi...
[ "def", "radio_buttons_clicked", "(", "self", ")", ":", "# Disable all spin boxes", "for", "spin_box", "in", "list", "(", "self", ".", "spin_boxes", ".", "values", "(", ")", ")", ":", "spin_box", ".", "setEnabled", "(", "False", ")", "# Disable list widget", "s...
43.809524
14.238095
def get_interface_switch(self, nexus_host, intf_type, interface): """Get the interface data from host. :param nexus_host: IP address of Nexus switch :param intf_type: String which specifies interface type. example: ethernet :param...
[ "def", "get_interface_switch", "(", "self", ",", "nexus_host", ",", "intf_type", ",", "interface", ")", ":", "if", "intf_type", "==", "\"ethernet\"", ":", "path_interface", "=", "\"phys-[eth\"", "+", "interface", "+", "\"]\"", "else", ":", "path_interface", "=",...
39.038462
17.538462
def expand_relative_uri(self, context, uri): """If uri is relative then expand in context. Prints warning if expansion happens. """ full_uri = urljoin(context, uri) if (full_uri != uri): print(" WARNING - expanded relative URI to %s" % (full_uri)) uri = ...
[ "def", "expand_relative_uri", "(", "self", ",", "context", ",", "uri", ")", ":", "full_uri", "=", "urljoin", "(", "context", ",", "uri", ")", "if", "(", "full_uri", "!=", "uri", ")", ":", "print", "(", "\" WARNING - expanded relative URI to %s\"", "%", "(",...
33.9
12.7
def complain(self, id, is_spam): """ http://api.yandex.ru/cleanweb/doc/dg/concepts/complain.xml""" r = self.request('post', 'http://cleanweb-api.yandex.ru/1.0/complain', data={'id': id, 'spamtype': 'spam' if is_spam else 'ham'}) return True
[ "def", "complain", "(", "self", ",", "id", ",", "is_spam", ")", ":", "r", "=", "self", ".", "request", "(", "'post'", ",", "'http://cleanweb-api.yandex.ru/1.0/complain'", ",", "data", "=", "{", "'id'", ":", "id", ",", "'spamtype'", ":", "'spam'", "if", "...
57
22
def list_backends(): """Return installed backends. Backends are installed python packages named pyvisa-<something> where <something> is the name of the backend. :rtype: list """ return ['ni'] + [name for (loader, name, ispkg) in pkgutil.iter_modules() if name.startswith('p...
[ "def", "list_backends", "(", ")", ":", "return", "[", "'ni'", "]", "+", "[", "name", "for", "(", "loader", ",", "name", ",", "ispkg", ")", "in", "pkgutil", ".", "iter_modules", "(", ")", "if", "name", ".", "startswith", "(", "'pyvisa-'", ")", "and", ...
35.3
25.9
def searchQueryAll(self, *args, **kwargs): """ Experimental Method Execute a Search query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.SearchRequest` object. The object may be iterated over to yield the rows in ...
[ "def", "searchQueryAll", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "connected", ":", "cb", "=", "lambda", "x", ":", "self", ".", "searchQueryAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", "...
29.828571
21.6
def get_extr_license_ident(self, extr_lic): """ Return an a license identifier from an ExtractedLicense or None. """ identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None))) if not identifier_tripples: self.error = True ...
[ "def", "get_extr_license_ident", "(", "self", ",", "extr_lic", ")", ":", "identifier_tripples", "=", "list", "(", "self", ".", "graph", ".", "triples", "(", "(", "extr_lic", ",", "self", ".", "spdx_namespace", "[", "'licenseId'", "]", ",", "None", ")", ")"...
35.894737
20.315789
def function( name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, expect_minions=False, fail_minions=None, fail_function=None, arg=None, kwarg=None, timeout=None, batch=None, ...
[ "def", "function", "(", "name", ",", "tgt", ",", "ssh", "=", "False", ",", "tgt_type", "=", "'glob'", ",", "ret", "=", "''", ",", "ret_config", "=", "None", ",", "ret_kwargs", "=", "None", ",", "expect_minions", "=", "False", ",", "fail_minions", "=", ...
29.346369
22.75419
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Tex...
[ "def", "deprecated", "(", "reason", ",", "replacement", ",", "gone_in", ",", "issue", "=", "None", ")", ":", "# type: (str, Optional[str], Optional[str], Optional[int]) -> None", "# Construct a nice message.", "# This is purposely eagerly formatted as we want it to appear as if someo...
42.166667
23.75
def _divf16(ins): """ Divides 2 32bit (16.16) fixed point numbers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1, do nothing * If 2nd operand is -1, do NEG32 """ op1, op2 = tuple(ins.quad[2:]) if is_float(op2): if float(op2) == 1: ...
[ "def", "_divf16", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "is_float", "(", "op2", ")", ":", "if", "float", "(", "op2", ")", "==", "1", ":", "output", "=", "_f16_oper", "("...
26.25
16.607143
def _read_register(self, reg): """Read 16 bit register value.""" self.buf[0] = reg with self.i2c_device as i2c: i2c.write(self.buf, end=1, stop=False) i2c.readinto(self.buf, end=2) return self.buf[0] << 8 | self.buf[1]
[ "def", "_read_register", "(", "self", ",", "reg", ")", ":", "self", ".", "buf", "[", "0", "]", "=", "reg", "with", "self", ".", "i2c_device", "as", "i2c", ":", "i2c", ".", "write", "(", "self", ".", "buf", ",", "end", "=", "1", ",", "stop", "="...
38.285714
6.428571
def get_data_statistics(interpreted_files): '''Quick and dirty function to give as redmine compatible iverview table ''' print '| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |' # Mean Tot | Mean rel. BCID' for interpreted_file in interprete...
[ "def", "get_data_statistics", "(", "interpreted_files", ")", ":", "print", "'| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |'", "# Mean Tot | Mean rel. BCID'", "for", "interpreted_file", "in", "interpreted_files", ":", "with"...
87.722222
56.833333
def GetClientsForHashes(cls, hashes, token=None, age=aff4.NEWEST_TIME): """Yields (hash, client_files) pairs for all the specified hashes. Args: hashes: List of RDFURN's. token: Security token. age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be a...
[ "def", "GetClientsForHashes", "(", "cls", ",", "hashes", ",", "token", "=", "None", ",", "age", "=", "aff4", ".", "NEWEST_TIME", ")", ":", "if", "age", "==", "aff4", ".", "ALL_TIMES", ":", "raise", "ValueError", "(", "\"age==aff4.ALL_TIMES is not supported.\""...
43
22.735294
def _process_tasks(self, task_queue, rmgr, logger, mq_hostname, port, local_prof, sid): ''' **Purpose**: The new thread that gets spawned by the main tmgr process invokes this function. This function receives tasks from 'task_queue' and submits them to the RADICAL Pilot RTS. ''' ...
[ "def", "_process_tasks", "(", "self", ",", "task_queue", ",", "rmgr", ",", "logger", ",", "mq_hostname", ",", "port", ",", "local_prof", ",", "sid", ")", ":", "placeholder_dict", "=", "dict", "(", ")", "def", "load_placeholder", "(", "task", ",", "rts_uid"...
39.347222
26.625
def memory_pour(buffer_, *args, **kwargs): """Yield data from entries.""" def opener(archive_res): _LOGGER.debug("Opening from (%d) bytes (memory_pour).", len(buffer_)) _archive_read_open_memory(archive_res, buffer_) return _pour(opener, *args, flags=0, **kwargs)
[ "def", "memory_pour", "(", "buffer_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "opener", "(", "archive_res", ")", ":", "_LOGGER", ".", "debug", "(", "\"Opening from (%d) bytes (memory_pour).\"", ",", "len", "(", "buffer_", ")", ")", "_ar...
35.75
19.5
def create_jar(jar_file, entries): """ Create JAR from given entries. :param jar_file: filename of the created JAR :type jar_file: str :param entries: files to put into the JAR :type entries: list[str] :return: None """ # 'jar' adds separate entries for directories, also for empty o...
[ "def", "create_jar", "(", "jar_file", ",", "entries", ")", ":", "# 'jar' adds separate entries for directories, also for empty ones.", "with", "ZipFile", "(", "jar_file", ",", "\"w\"", ")", "as", "jar", ":", "jar", ".", "writestr", "(", "\"META-INF/\"", ",", "\"\"",...
35.9
12.7
def _ParseExample(self, example_features, example_feature_lists, entries, index): """Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.Fe...
[ "def", "_ParseExample", "(", "self", ",", "example_features", ",", "example_feature_lists", ",", "entries", ",", "index", ")", ":", "features_seen", "=", "set", "(", ")", "for", "feature_list", ",", "is_feature", "in", "zip", "(", "[", "example_features", ",",...
40.609195
15.563218
def convert_to_sequences(dataset, vocab): """This function takes a dataset and converts it into sequences via multiprocessing """ start = time.time() dataset_vocab = map(lambda x: (x, vocab), dataset) with mp.Pool() as pool: # Each sample is processed in an asynchronous manner. o...
[ "def", "convert_to_sequences", "(", "dataset", ",", "vocab", ")", ":", "start", "=", "time", ".", "time", "(", ")", "dataset_vocab", "=", "map", "(", "lambda", "x", ":", "(", "x", ",", "vocab", ")", ",", "dataset", ")", "with", "mp", ".", "Pool", "...
39.923077
12.846154
def cache_data_model(self, raw): """ Cache the data model json. Take data returned by a requests.get call to Earthref. Parameters ---------- raw: requests.models.Response """ output_json = json.loads(raw.content) output_file = self.find_cached_dm...
[ "def", "cache_data_model", "(", "self", ",", "raw", ")", ":", "output_json", "=", "json", ".", "loads", "(", "raw", ".", "content", ")", "output_file", "=", "self", ".", "find_cached_dm", "(", ")", "json", ".", "dump", "(", "output_json", ",", "open", ...
28.153846
14.307692
def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ Fetch object and directly return them Note: `get` won't put the fetched objects in the parent's children list. You c...
[ "def", "get", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ",", "commit", "=", "True", ",", "as...
54.576923
34.269231
def getBackgroundRange(fitParams): ''' return minimum, average, maximum of the background peak ''' smn, _, _ = getSignalParameters(fitParams) bg = fitParams[0] _, avg, std = bg bgmn = max(0, avg - 3 * std) if avg + 4 * std < smn: bgmx = avg + 4 * std if avg + 3 ...
[ "def", "getBackgroundRange", "(", "fitParams", ")", ":", "smn", ",", "_", ",", "_", "=", "getSignalParameters", "(", "fitParams", ")", "bg", "=", "fitParams", "[", "0", "]", "_", ",", "avg", ",", "std", "=", "bg", "bgmn", "=", "max", "(", "0", ",",...
24.631579
18.210526
def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :...
[ "def", "temp_dir", "(", "apply_chown", "=", "None", ",", "apply_chmod", "=", "None", ",", "remove_using_sudo", "=", "None", ",", "remove_force", "=", "False", ")", ":", "path", "=", "get_remote_temp", "(", ")", "try", ":", "if", "apply_chmod", ":", "run", ...
40.607143
19.964286
def add_membership(self, user, role): """ make user a member of a group """ targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False target = AuthMembership.objects(user=user, creator=self.client).first() if not target:...
[ "def", "add_membership", "(", "self", ",", "user", ",", "role", ")", ":", "targetGroup", "=", "AuthGroup", ".", "objects", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", ".", "first", "(", ")", "if", "not", "targetGroup", ...
37.428571
20.785714
def _highlight(self, content, ngrams, highlight): """Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of ...
[ "def", "_highlight", "(", "self", ",", "content", ",", "ngrams", ",", "highlight", ")", ":", "self", ".", "_add_highlight", "=", "highlight", "for", "ngram", "in", "ngrams", ":", "pattern", "=", "self", ".", "_get_regexp_pattern", "(", "ngram", ")", "conte...
36.473684
13.315789
def allow(self): """Allow the add-on to be installed.""" with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_primary_button().click()
[ "def", "allow", "(", "self", ")", ":", "with", "self", ".", "selenium", ".", "context", "(", "self", ".", "selenium", ".", "CONTEXT_CHROME", ")", ":", "self", ".", "find_primary_button", "(", ")", ".", "click", "(", ")" ]
43.5
13.75
def _read(self, fh, fname): """Parse the TIMER section""" if fname in self._timers: raise self.Error("Cannot overwrite timer associated to: %s " % fname) def parse_line(line): """Parse single line.""" name, vals = line[:25], line[25:].split() try:...
[ "def", "_read", "(", "self", ",", "fh", ",", "fname", ")", ":", "if", "fname", "in", "self", ".", "_timers", ":", "raise", "self", ".", "Error", "(", "\"Cannot overwrite timer associated to: %s \"", "%", "fname", ")", "def", "parse_line", "(", "line", ")",...
34.727273
19.287879
def SCISetStyling(self, line: int, col: int, numChar: int, style: bytearray): """ Pythonic wrapper for the SCI_SETSTYLING command. For example, the following code applies style #3 to the first five characters in the second line of the widget: S...
[ "def", "SCISetStyling", "(", "self", ",", "line", ":", "int", ",", "col", ":", "int", ",", "numChar", ":", "int", ",", "style", ":", "bytearray", ")", ":", "if", "not", "self", ".", "isPositionValid", "(", "line", ",", "col", ")", ":", "return", "p...
30.53125
23.46875
def _set_class_path(cls, module_dict=sys.modules): """Sets the absolute path to this class as a string. Used by the Pipeline API to reconstruct the Pipeline sub-class object at execution time instead of passing around a serialized function. Args: module_dict: Used for testing. """ # Do n...
[ "def", "_set_class_path", "(", "cls", ",", "module_dict", "=", "sys", ".", "modules", ")", ":", "# Do not traverse the class hierarchy fetching the class path attribute.", "found", "=", "cls", ".", "__dict__", ".", "get", "(", "'_class_path'", ")", "if", "found", "i...
40.323529
22.470588
def open(self, fname, mode='rb'): """ (Re-)opens a backup file """ self.close() self.fp = open(fname, mode) self.fname = fname
[ "def", "open", "(", "self", ",", "fname", ",", "mode", "=", "'rb'", ")", ":", "self", ".", "close", "(", ")", "self", ".", "fp", "=", "open", "(", "fname", ",", "mode", ")", "self", ".", "fname", "=", "fname" ]
24
7.714286
def setRecordSet( self, recordSet ): """ Sets the record set instance that this widget will use. :param recordSet | <orb.RecordSet> """ if ( recordSet ): self.setQuery( recordSet.query() ) self.setGroupBy( recordSet.groupBy() ...
[ "def", "setRecordSet", "(", "self", ",", "recordSet", ")", ":", "if", "(", "recordSet", ")", ":", "self", ".", "setQuery", "(", "recordSet", ".", "query", "(", ")", ")", "self", ".", "setGroupBy", "(", "recordSet", ".", "groupBy", "(", ")", ")", "sel...
34.9
13.7
def _prepare_disks(self, disks_name): """format disks to xfs and mount it""" fstab = '/etc/fstab' for disk in tqdm(disks_name.split(',')): sudo('umount /dev/{0}'.format(disk), warn_only=True) if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed: ...
[ "def", "_prepare_disks", "(", "self", ",", "disks_name", ")", ":", "fstab", "=", "'/etc/fstab'", "for", "disk", "in", "tqdm", "(", "disks_name", ".", "split", "(", "','", ")", ")", ":", "sudo", "(", "'umount /dev/{0}'", ".", "format", "(", "disk", ")", ...
55.538462
19.307692
def percentage(value: str) -> float: """ ``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). """ try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise A...
[ "def", "percentage", "(", "value", ":", "str", ")", "->", "float", ":", "try", ":", "fvalue", "=", "float", "(", "value", ")", "assert", "0", "<=", "fvalue", "<=", "100", "except", "(", "AssertionError", ",", "TypeError", ",", "ValueError", ")", ":", ...
34.083333
13.75
def _find_package(c): """ Try to find 'the' One True Package for this project. Mostly for obtaining the ``_version`` file within it. Uses the ``packaging.package`` config setting if defined. If not defined, fallback is to look for a single top-level Python package (directory containing ``__ini...
[ "def", "_find_package", "(", "c", ")", ":", "# TODO: is there a way to get this from the same place setup.py does w/o", "# setup.py barfing (since setup() runs at import time and assumes CLI use)?", "configured_value", "=", "c", ".", "get", "(", "\"packaging\"", ",", "{", "}", ")...
38.90625
23.34375
def vectorize( self, docs ): ''' Returns the feature vectors for a set of docs. If model is not already be trained, then self.train() is called. Args: docs (dict or list of tuples): asset_id, body_text of documents you wish to featurize. ''' if ...
[ "def", "vectorize", "(", "self", ",", "docs", ")", ":", "if", "type", "(", "docs", ")", "==", "dict", ":", "docs", "=", "docs", ".", "items", "(", ")", "if", "self", ".", "model", "==", "None", ":", "self", ".", "train", "(", "docs", ")", "asse...
34.914286
25.714286
def set_courses(self, course_ids): """Sets the courses. arg: course_ids (osid.id.Id[]): the course ``Ids`` raise: InvalidArgument - ``course_ids`` is invalid raise: NullArgument - ``course_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *c...
[ "def", "set_courses", "(", "self", ",", "course_ids", ")", ":", "# Implemented from template for osid.learning.ActivityForm.set_assets_template", "if", "not", "isinstance", "(", "course_ids", ",", "list", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", ")", ...
42.190476
14.809524
def setval(self, varname, value): """ Set the value of the variable with the given name. """ if varname in self: self[varname]['value'] = value else: self[varname] = Variable(self.default_type, value=value)
[ "def", "setval", "(", "self", ",", "varname", ",", "value", ")", ":", "if", "varname", "in", "self", ":", "self", "[", "varname", "]", "[", "'value'", "]", "=", "value", "else", ":", "self", "[", "varname", "]", "=", "Variable", "(", "self", ".", ...
32.875
11.875
def servicegroup_add(sg_name, sg_type='HTTP', **connection_args): ''' Add a new service group If no service type is specified, HTTP will be used. Most common service types: HTTP, SSL, and SSL_BRIDGE CLI Example: .. code-block:: bash salt '*' netscaler.servicegroup_add 'serviceGroupNam...
[ "def", "servicegroup_add", "(", "sg_name", ",", "sg_type", "=", "'HTTP'", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "True", "if", "servicegroup_exists", "(", "sg_name", ")", ":", "return", "False", "nitro", "=", "_connect", "(", "*", "*", "...
29.896552
21.344828
def add_enrichr_parser(subparsers): """Add function 'enrichr' argument parsers.""" argparser_enrichr = subparsers.add_parser("enrichr", help="Using Enrichr API to perform GO analysis.") # group for required options. enrichr_opt = argparser_enrichr.add_argument_group("Input arguments") enrichr_opt....
[ "def", "add_enrichr_parser", "(", "subparsers", ")", ":", "argparser_enrichr", "=", "subparsers", ".", "add_parser", "(", "\"enrichr\"", ",", "help", "=", "\"Using Enrichr API to perform GO analysis.\"", ")", "# group for required options.", "enrichr_opt", "=", "argparser_e...
84.6
55.266667
def decrement(self, subname=None, delta=1): '''Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge...
[ "def", "decrement", "(", "self", ",", "subname", "=", "None", ",", "delta", "=", "1", ")", ":", "delta", "=", "-", "int", "(", "delta", ")", "sign", "=", "\"+\"", "if", "delta", ">=", "0", "else", "\"\"", "return", "self", ".", "_send", "(", "sub...
31.7
17.2
def iplot(self, places=-1, c_poly='default', c_holes='default', c_sop='r', s_sop=25, extra_height=0, ret=False, ax=None): """ Improved plot that allows to visualize the Places in the Space selectively. It also allows to plot polygons and holes in different colors and ...
[ "def", "iplot", "(", "self", ",", "places", "=", "-", "1", ",", "c_poly", "=", "'default'", ",", "c_holes", "=", "'default'", ",", "c_sop", "=", "'r'", ",", "s_sop", "=", "25", ",", "extra_height", "=", "0", ",", "ret", "=", "False", ",", "ax", "...
43.891304
15.717391
def image_groups_get(self, resource_url): """Get handle for image group resource at given Url. Parameters ---------- resource_url : string Url for image group resource at SCO-API Returns ------- scoserv.ImageGroupHandle Handle for local c...
[ "def", "image_groups_get", "(", "self", ",", "resource_url", ")", ":", "# Get resource directory, Json representation, active flag, and cache id", "obj_dir", ",", "obj_json", ",", "is_active", ",", "cache_id", "=", "self", ".", "get_object", "(", "resource_url", ")", "#...
38.217391
17.217391
def add_options(self): """ Add program options. """ super(RtorrentControl, self).add_options() # basic options self.add_bool_option("--help-fields", help="show available fields and their description") self.add_bool_option("-n", "--dry-run", help="...
[ "def", "add_options", "(", "self", ")", ":", "super", "(", "RtorrentControl", ",", "self", ")", ".", "add_options", "(", ")", "# basic options", "self", ".", "add_bool_option", "(", "\"--help-fields\"", ",", "help", "=", "\"show available fields and their descriptio...
55.75
21.26087
def wait(self, container, timeout=None, condition=None): """ Block until a container stops, then return its exit code. Similar to the ``docker wait`` command. Args: container (str or dict): The container to wait on. If a dict, the ``Id`` key is used. ...
[ "def", "wait", "(", "self", ",", "container", ",", "timeout", "=", "None", ",", "condition", "=", "None", ")", ":", "url", "=", "self", ".", "_url", "(", "\"/containers/{0}/wait\"", ",", "container", ")", "params", "=", "{", "}", "if", "condition", "is...
39.764706
19.588235
def ldirectory(inpath, outpath, args, scope): """Compile all *.less files in directory Args: inpath (str): Path to compile outpath (str): Output directory args (object): Argparse Object scope (Scope): Scope object or None """ yacctab = 'yacctab' if args.debug else None ...
[ "def", "ldirectory", "(", "inpath", ",", "outpath", ",", "args", ",", "scope", ")", ":", "yacctab", "=", "'yacctab'", "if", "args", ".", "debug", "else", "None", "if", "not", "outpath", ":", "sys", ".", "exit", "(", "\"Compile directory option needs -o ...\"...
37.519231
12.961538
def classify_clusters(points, n=10): """ Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects. """ arr = [[p.x, p.y] for p in points.values] clf = KMeans(n_clusters=n) clf.fit(arr) classes = clf.predict(arr) return classes
[ "def", "classify_clusters", "(", "points", ",", "n", "=", "10", ")", ":", "arr", "=", "[", "[", "p", ".", "x", ",", "p", ".", "y", "]", "for", "p", "in", "points", ".", "values", "]", "clf", "=", "KMeans", "(", "n_clusters", "=", "n", ")", "c...
31.666667
14.555556
def _characteristic_changed(self, characteristic): """Called when the specified characteristic has changed its value.""" # Called when a characteristic is changed. Get the on_changed handler # for this characteristic (if it exists) and call it. on_changed = self._char_on_changed.get(cha...
[ "def", "_characteristic_changed", "(", "self", ",", "characteristic", ")", ":", "# Called when a characteristic is changed. Get the on_changed handler", "# for this characteristic (if it exists) and call it.", "on_changed", "=", "self", ".", "_char_on_changed", ".", "get", "(", ...
57.416667
18.333333
def hash(self, id): """ Creates a unique filename in the cache for the id. """ h = md5(id).hexdigest() return os.path.join(self.path, h+self.type)
[ "def", "hash", "(", "self", ",", "id", ")", ":", "h", "=", "md5", "(", "id", ")", ".", "hexdigest", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "h", "+", "self", ".", "type", ")" ]
24.857143
17.285714
def match(self, context): """Returns True if the current context matches, False if it doesn't and None if matching is not finished, ie must be resumed after child contexts have been matched.""" while context.remaining_codes() > 0 and context.has_matched is None: opcode = cont...
[ "def", "match", "(", "self", ",", "context", ")", ":", "while", "context", ".", "remaining_codes", "(", ")", ">", "0", "and", "context", ".", "has_matched", "is", "None", ":", "opcode", "=", "context", ".", "peek_code", "(", ")", "if", "not", "self", ...
47.181818
10.363636
def angToDisc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False): """ Wrap `query_disc` to use lon, lat, and radius in degrees. """ vec = angToVec(lon,lat) return query_disc(nside,vec,radius,inclusive,fact,nest)
[ "def", "angToDisc", "(", "nside", ",", "lon", ",", "lat", ",", "radius", ",", "inclusive", "=", "False", ",", "fact", "=", "4", ",", "nest", "=", "False", ")", ":", "vec", "=", "angToVec", "(", "lon", ",", "lat", ")", "return", "query_disc", "(", ...
39.5
14.833333
def __insert_represented_points(self, cluster): """! @brief Insert representation points to the k-d tree. @param[in] cluster (cure_cluster): Cluster whose representation points should be inserted. """ for point in cluster.rep: self....
[ "def", "__insert_represented_points", "(", "self", ",", "cluster", ")", ":", "for", "point", "in", "cluster", ".", "rep", ":", "self", ".", "__tree", ".", "insert", "(", "point", ",", "cluster", ")" ]
34
19.3
def branch(self, branch_name, start_point='HEAD', force=True, checkout=False): """Create branch as in `git branch <branch_name> <start_point>`. If 'checkout' is True, checkout the branch after creation. """ return git_branch( self.repo_dir, branch_name, start_...
[ "def", "branch", "(", "self", ",", "branch_name", ",", "start_point", "=", "'HEAD'", ",", "force", "=", "True", ",", "checkout", "=", "False", ")", ":", "return", "git_branch", "(", "self", ".", "repo_dir", ",", "branch_name", ",", "start_point", ",", "f...
40.222222
16.111111
def add_resource(mt_file, ref, cache): """Add a resources entry, downloading the intuiting the file, replacing entries with the same reference""" if isinstance(mt_file, MetapackDoc): doc = mt_file else: doc = MetapackDoc(mt_file) if not 'Resources' in doc: doc.new_section('...
[ "def", "add_resource", "(", "mt_file", ",", "ref", ",", "cache", ")", ":", "if", "isinstance", "(", "mt_file", ",", "MetapackDoc", ")", ":", "doc", "=", "mt_file", "else", ":", "doc", "=", "MetapackDoc", "(", "mt_file", ")", "if", "not", "'Resources'", ...
25.435897
23.717949
def hastext(self, cls='current',strict=True, correctionhandling=CorrectionHandling.CURRENT): """See :meth:`AbstractElement.hastext`""" if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHa...
[ "def", "hastext", "(", "self", ",", "cls", "=", "'current'", ",", "strict", "=", "True", ",", "correctionhandling", "=", "CorrectionHandling", ".", "CURRENT", ")", ":", "if", "cls", "==", "'original'", ":", "correctionhandling", "=", "CorrectionHandling", ".",...
61.416667
28.666667
def _numbers_decades(N): """ >>> _numbers_decades(45) ' 1 2 3 4' """ N = N // 10 lst = range(1, N + 1) return "".join(map(lambda i: "%10s" % i, lst))
[ "def", "_numbers_decades", "(", "N", ")", ":", "N", "=", "N", "//", "10", "lst", "=", "range", "(", "1", ",", "N", "+", "1", ")", "return", "\"\"", ".", "join", "(", "map", "(", "lambda", "i", ":", "\"%10s\"", "%", "i", ",", "lst", ")", ")" ]
25.25
10.5
def register_lookup(cls, lookup, lookup_name=None): """Register a Lookup to a class""" if lookup_name is None: lookup_name = lookup.lookup_name if 'class_lookups' not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_name] = lookup cls._cle...
[ "def", "register_lookup", "(", "cls", ",", "lookup", ",", "lookup_name", "=", "None", ")", ":", "if", "lookup_name", "is", "None", ":", "lookup_name", "=", "lookup", ".", "lookup_name", "if", "'class_lookups'", "not", "in", "cls", ".", "__dict__", ":", "cl...
32
13.454545
def get(self, key, cache=None): """Query the server for an item, parse the JSON, and return the result. Keyword arguments: key -- the key of the item that you'd like to retrieve. Required. cache -- the name of the cache that the item resides in. Defaults to None, which ...
[ "def", "get", "(", "self", ",", "key", ",", "cache", "=", "None", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "self", ".", "name", "if", "cache", "is", "None", ":", "raise", "ValueError", "(", "\"Cache name must be set\"", ")", "cache", ...
39.944444
14.611111
def set_published_date(self, date=None): """ Set the published date of a IOC to the current date. User may specify the date they want to set as well. :param date: Date value to set the published date to. This should be in the xsdDate form. This defaults to the current date if ...
[ "def", "set_published_date", "(", "self", ",", "date", "=", "None", ")", ":", "if", "date", ":", "match", "=", "re", ".", "match", "(", "DATE_REGEX", ",", "date", ")", "if", "not", "match", ":", "raise", "IOCParseError", "(", "'Published date is not valid....
43.235294
20.647059
def _sort_by_region(fnames, regions, ref_file, config): """Sort a set of regionally split files by region for ordered output. """ contig_order = {} for i, sq in enumerate(ref.file_contigs(ref_file, config)): contig_order[sq.name] = i sitems = [] assert len(regions) == len(fnames), (regio...
[ "def", "_sort_by_region", "(", "fnames", ",", "regions", ",", "ref_file", ",", "config", ")", ":", "contig_order", "=", "{", "}", "for", "i", ",", "sq", "in", "enumerate", "(", "ref", ".", "file_contigs", "(", "ref_file", ",", "config", ")", ")", ":", ...
40.086957
13.478261
def include(context, bundle_name, version): """Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version. """ store = Store(context.obj['database'], context.obj['root']) if version: version_obj = store.Version.get(version) if...
[ "def", "include", "(", "context", ",", "bundle_name", ",", "version", ")", ":", "store", "=", "Store", "(", "context", ".", "obj", "[", "'database'", "]", ",", "context", ".", "obj", "[", "'root'", "]", ")", "if", "version", ":", "version_obj", "=", ...
36.2
18.12
def _after_valid_time_range(self): """ In case of uncertainty (times not specified), we assume that we are in a valid range. """ if self.end_time is not None: try: if self.time > self.end_time: return True except TypeError: ...
[ "def", "_after_valid_time_range", "(", "self", ")", ":", "if", "self", ".", "end_time", "is", "not", "None", ":", "try", ":", "if", "self", ".", "time", ">", "self", ".", "end_time", ":", "return", "True", "except", "TypeError", ":", "return", "False", ...
32.272727
13
def source_present(name, source_type='imgapi'): ''' Ensure an image source is present on the computenode name : string source url source_type : string source type (imgapi or docker) ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment...
[ "def", "source_present", "(", "name", ",", "source_type", "=", "'imgapi'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "name", "in", "__salt_...
29.25
20.694444
def _shift2boolean(self, q_mesh_shift, is_gamma_center=False, tolerance=1e-5): """ Tolerance is used to judge zero/half gird shift. This value is not necessary to be changed usually. """ if q_mesh_shift is None:...
[ "def", "_shift2boolean", "(", "self", ",", "q_mesh_shift", ",", "is_gamma_center", "=", "False", ",", "tolerance", "=", "1e-5", ")", ":", "if", "q_mesh_shift", "is", "None", ":", "shift", "=", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "'double'", ...
34.5
15.730769
def require_axis(f): """ Check if the object of the function has axis and sel_axis members """ @wraps(f) def _wrapper(self, *args, **kwargs): if None in (self.axis, self.sel_axis): raise ValueError('%(func_name) requires the node %(node)s ' 'to have an axis and a sel...
[ "def", "require_axis", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "None", "in", "(", "self", ".", "axis", ",", "self", ".", "sel_axis", ")", ":", ...
34.769231
21
def classify_harmonic(self, partial_labels, use_CMN=True): '''Harmonic function method for semi-supervised classification, also known as the Gaussian Mean Fields algorithm. partial_labels: (n,) array of integer labels, -1 for unlabeled. use_CMN : when True, apply Class Mass Normalization From "Sem...
[ "def", "classify_harmonic", "(", "self", ",", "partial_labels", ",", "use_CMN", "=", "True", ")", ":", "# prepare labels", "labels", "=", "np", ".", "array", "(", "partial_labels", ",", "copy", "=", "True", ")", "unlabeled", "=", "labels", "==", "-", "1", ...
30.027027
21.540541
def get_pubkey(self): """ Get the public key of the certificate signing request. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.X509_REQ_get_pubkey(self._req) _openssl_assert(pkey._pkey != _ffi.NULL) ...
[ "def", "get_pubkey", "(", "self", ")", ":", "pkey", "=", "PKey", ".", "__new__", "(", "PKey", ")", "pkey", ".", "_pkey", "=", "_lib", ".", "X509_REQ_get_pubkey", "(", "self", ".", "_req", ")", "_openssl_assert", "(", "pkey", ".", "_pkey", "!=", "_ffi",...
32.076923
13.615385
def connectRelay(self): """Builds the target protocol and connects it to the relay transport. """ self.protocol = self.connector.buildProtocol(None) self.connected = True self.protocol.makeConnection(self)
[ "def", "connectRelay", "(", "self", ")", ":", "self", ".", "protocol", "=", "self", ".", "connector", ".", "buildProtocol", "(", "None", ")", "self", ".", "connected", "=", "True", "self", ".", "protocol", ".", "makeConnection", "(", "self", ")" ]
40
8
def rolling_percentileofscore(series, window, min_periods=None): """Computue the score percentile for the specified window.""" import scipy.stats as stats def _percentile(arr): score = arr[-1] vals = arr[:-1] return stats.percentileofscore(vals, score) notnull = series.dropna()...
[ "def", "rolling_percentileofscore", "(", "series", ",", "window", ",", "min_periods", "=", "None", ")", ":", "import", "scipy", ".", "stats", "as", "stats", "def", "_percentile", "(", "arr", ")", ":", "score", "=", "arr", "[", "-", "1", "]", "vals", "=...
36
21
def _determine_stream_track(self,nTrackChunks): """Determine the track of the stream in real space""" #Determine how much orbital time is necessary for the progenitor's orbit to cover the stream if nTrackChunks is None: #default is floor(self._deltaAngleTrack/0.15)+1 self...
[ "def", "_determine_stream_track", "(", "self", ",", "nTrackChunks", ")", ":", "#Determine how much orbital time is necessary for the progenitor's orbit to cover the stream", "if", "nTrackChunks", "is", "None", ":", "#default is floor(self._deltaAngleTrack/0.15)+1", "self", ".", "_n...
60.884058
24.905797
def to_array(self): """ Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGif, self).to_array() # 'type' and 'id' given by superclass array['gif_url'] =...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "InlineQueryResultGif", ",", "self", ")", ".", "to_array", "(", ")", "# 'type' and 'id' given by superclass", "array", "[", "'gif_url'", "]", "=", "u", "(", "self", ".", "gif_url", ")", ...
51.214286
21.5
def get_all_build_config_set_records(self, id, **kwargs): """ Get all build config set execution records associated with this build config set, returns empty list if none are found This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ple...
[ "def", "get_all_build_config_set_records", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_all_build_...
45.931034
19.655172
def cmd_ip_internal(verbose): """Get the local IP address(es) of the local interfaces. Example: \b $ habu.ip.internal { "lo": { "ipv4": [ { "addr": "127.0.0.1", "netmask": "255.0.0.0", "peer": "127.0.0.1" } ], "l...
[ "def", "cmd_ip_internal", "(", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "print", "(", "\"Gathering NIC details...\"", ",", "file", "=", "sys...
21.093023
23.255814
def python(self, cmd): """Execute a python script using the virtual environment python.""" python_bin = self.cmd_path('python') cmd = '{0} {1}'.format(python_bin, cmd) return self._execute(cmd)
[ "def", "python", "(", "self", ",", "cmd", ")", ":", "python_bin", "=", "self", ".", "cmd_path", "(", "'python'", ")", "cmd", "=", "'{0} {1}'", ".", "format", "(", "python_bin", ",", "cmd", ")", "return", "self", ".", "_execute", "(", "cmd", ")" ]
44.2
7.2
def make_cluster_vector(rev_dict, n_src): """ Converts the cluster membership dictionary to an array Parameters ---------- rev_dict : dict(int:int) A single valued dictionary pointing from source index to cluster key for each source in a cluster. n_src : int Number of ...
[ "def", "make_cluster_vector", "(", "rev_dict", ",", "n_src", ")", ":", "out_array", "=", "-", "1", "*", "np", ".", "ones", "(", "(", "n_src", ")", ",", "int", ")", "for", "k", ",", "v", "in", "rev_dict", ".", "items", "(", ")", ":", "out_array", ...
30.458333
19
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): """Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_n...
[ "def", "_prepare_init_params_from_job_description", "(", "cls", ",", "job_details", ",", "model_channel_name", "=", "None", ")", ":", "init_params", "=", "super", "(", "Framework", ",", "cls", ")", ".", "_prepare_init_params_from_job_description", "(", "job_details", ...
47.424242
29.939394
def user(self, user: str) -> "ChildHTTPAPI": """ Get a child HTTPAPI instance. Args: user: The Matrix ID of the user whose API to get. Returns: A HTTPAPI instance that always uses the given Matrix ID. """ if self.is_real_user: raise V...
[ "def", "user", "(", "self", ",", "user", ":", "str", ")", "->", "\"ChildHTTPAPI\"", ":", "if", "self", ".", "is_real_user", ":", "raise", "ValueError", "(", "\"Can't get child of real user\"", ")", "try", ":", "return", "self", ".", "children", "[", "user", ...
27.947368
17.105263
def get_header_path() -> str: """Return local folder path of header files.""" import os return os.path.abspath(os.path.dirname(os.path.realpath(__file__))) + '/headers/'
[ "def", "get_header_path", "(", ")", "->", "str", ":", "import", "os", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")", "+", "'/headers/'" ]
44.5
20.75
def _set_module_names_for_sphinx(modules: List, new_name: str): """ Trick sphinx into displaying the desired module in these objects' documentation. """ for obj in modules: obj.__module__ = new_name
[ "def", "_set_module_names_for_sphinx", "(", "modules", ":", "List", ",", "new_name", ":", "str", ")", ":", "for", "obj", "in", "modules", ":", "obj", ".", "__module__", "=", "new_name" ]
52.75
11.75
def rotate_slaves(self): "Round-robin slave balancer" slaves = self.sentinel_manager.discover_slaves(self.service_name) if slaves: if self.slave_rr_counter is None: self.slave_rr_counter = random.randint(0, len(slaves) - 1) for _ in xrange(len(slaves)): ...
[ "def", "rotate_slaves", "(", "self", ")", ":", "slaves", "=", "self", ".", "sentinel_manager", ".", "discover_slaves", "(", "self", ".", "service_name", ")", "if", "slaves", ":", "if", "self", ".", "slave_rr_counter", "is", "None", ":", "self", ".", "slave...
42.352941
15.529412
def ParseJavaFlags(self, start_line=0): """Parse Java style flags (com.google.common.flags).""" # The java flags prints starts with a "Standard flags" "module" # that doesn't follow the standard module syntax. modname = 'Standard flags' # name of current module self.module_list.append(modna...
[ "def", "ParseJavaFlags", "(", "self", ",", "start_line", "=", "0", ")", ":", "# The java flags prints starts with a \"Standard flags\" \"module\"", "# that doesn't follow the standard module syntax.", "modname", "=", "'Standard flags'", "# name of current module", "self", ".", "m...
35.891304
15.869565
def interact_alice(agent: Agent): """ Exchange messages between basic pipelines and the Yandex.Dialogs service. If the pipeline returns multiple values, only the first one is forwarded to Yandex. """ data = request.get_json() text = data['request'].get('command', '').strip() payload = data['...
[ "def", "interact_alice", "(", "agent", ":", "Agent", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "text", "=", "data", "[", "'request'", "]", ".", "get", "(", "'command'", ",", "''", ")", ".", "strip", "(", ")", "payload", "=", "dat...
33.324324
20.621622
def count_alleles(self, max_allele=None, subpop=None): """Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles greater than this index will be ignored. subpop : a...
[ "def", "count_alleles", "(", "self", ",", "max_allele", "=", "None", ",", "subpop", "=", "None", ")", ":", "# check inputs", "subpop", "=", "_normalize_subpop_arg", "(", "subpop", ",", "self", ".", "shape", "[", "1", "]", ")", "# determine alleles to count", ...
28.531915
21.574468
def _ixs(self, i, axis=0): """ Return the i-th value or values in the Series by location. Parameters ---------- i : int, slice, or sequence of integers Returns ------- scalar (int) or Series (slice, sequence) """ try: # dispa...
[ "def", "_ixs", "(", "self", ",", "i", ",", "axis", "=", "0", ")", ":", "try", ":", "# dispatch to the values if we need", "values", "=", "self", ".", "_values", "if", "isinstance", "(", "values", ",", "np", ".", "ndarray", ")", ":", "return", "libindex",...
30.75
17.25
def set_world(self, grd, start_y_x, y_x): """ tell the agent to move to location y,x Why is there another grd object in the agent? Because this is NOT the main grid, rather a copy for the agent to overwrite with planning routes, etc. The real grid is initialised in Worl...
[ "def", "set_world", "(", "self", ",", "grd", ",", "start_y_x", ",", "y_x", ")", ":", "self", ".", "grd", "=", "grd", "self", ".", "start_y", "=", "start_y_x", "[", "0", "]", "self", ".", "start_x", "=", "start_y_x", "[", "1", "]", "self", ".", "c...
42.111111
13