text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _ScanVolumeSystemRootNode( self, scan_context, scan_node, auto_recurse=True): """Scans a volume system root node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): Tru...
[ "def", "_ScanVolumeSystemRootNode", "(", "self", ",", "scan_context", ",", "scan_node", ",", "auto_recurse", "=", "True", ")", ":", "if", "scan_node", ".", "type_indicator", "==", "definitions", ".", "TYPE_INDICATOR_VSHADOW", ":", "# For VSS add a scan node for the curr...
41.794118
23.205882
def render_meta(meta, fn="meta.pandas.html", title="Project Metadata - MSMBuilder", pandas_kwargs=None): """Render a metadata dataframe as an html webpage for inspection. Parameters ---------- meta : pd.Dataframe The DataFrame of metadata fn : str Output filename (sh...
[ "def", "render_meta", "(", "meta", ",", "fn", "=", "\"meta.pandas.html\"", ",", "title", "=", "\"Project Metadata - MSMBuilder\"", ",", "pandas_kwargs", "=", "None", ")", ":", "if", "pandas_kwargs", "is", "None", ":", "pandas_kwargs", "=", "{", "}", "kwargs_with...
27.540541
20.135135
def _validate_config(self, config): """ Validates some parts of the module config :type config: dict[str, dict[str, Any] | str] :param config: The module config """ required_keys = [ self.KEY_IDP_CONFIG, self.KEY_ENDPOINTS, ] if no...
[ "def", "_validate_config", "(", "self", ",", "config", ")", ":", "required_keys", "=", "[", "self", ".", "KEY_IDP_CONFIG", ",", "self", ".", "KEY_ENDPOINTS", ",", "]", "if", "not", "config", ":", "raise", "ValueError", "(", "\"No configuration given\"", ")", ...
29.789474
14.947368
def wait_socket(_socket, session, timeout=1): """Helper function for testing non-blocking mode. This function blocks the calling thread for <timeout> seconds - to be used only for testing purposes. Also available at `ssh2.utils.wait_socket` """ directions = session.block_directions() if di...
[ "def", "wait_socket", "(", "_socket", ",", "session", ",", "timeout", "=", "1", ")", ":", "directions", "=", "session", ".", "block_directions", "(", ")", "if", "directions", "==", "0", ":", "return", "0", "readfds", "=", "[", "_socket", "]", "if", "("...
35.5
15.5
def cycle(self): """ Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn. Subclasses may override this method to alter loop functionality. """ try: events = self.getEvents() except requests.ConnectionError: retu...
[ "def", "cycle", "(", "self", ")", ":", "try", ":", "events", "=", "self", ".", "getEvents", "(", ")", "except", "requests", ".", "ConnectionError", ":", "return", "for", "event", "in", "events", ":", "self", ".", "onEvent", "(", "event", ")", "if", "...
30.5
17.928571
def xminvsks(self, **kwargs): """ Plot xmin versus the ks value for derived alpha. This plot can be used as a diagnostic of whether you have derived the 'best' fit: if there are multiple local minima, your data set may be well suited to a broken powerlaw or a different function....
[ "def", "xminvsks", "(", "self", ",", "*", "*", "kwargs", ")", ":", "pylab", ".", "plot", "(", "self", ".", "_xmins", ",", "self", ".", "_xmin_kstest", ",", "'.'", ")", "pylab", ".", "plot", "(", "self", ".", "_xmin", ",", "self", ".", "_ks", ",",...
34.666667
20.555556
def writeable(value, allow_empty = False, **kwargs): """Validate that ``value`` is a path to a writeable file. .. caution:: This validator does **NOT** work correctly on a Windows file system. This is due to the vagaries of how Windows manages its file system and the ...
[ "def", "writeable", "(", "value", ",", "allow_empty", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "value", "and", "not", "allow_empty", ":", "raise", "errors", ".", "EmptyValueError", "(", "'value (%s) was empty'", "%", "value", ")", "eli...
37.988372
27.825581
def encodeCodon(seq_vec, ignore_stop_codons=True, maxlen=None, seq_align="start", encode_type="one_hot"): """Convert the Codon sequence into 1-hot-encoding numpy array # Arguments seq_vec: List of strings/DNA sequences ignore_stop_codons: boolean; if True, STOP_CODONS are omitted from one-hot e...
[ "def", "encodeCodon", "(", "seq_vec", ",", "ignore_stop_codons", "=", "True", ",", "maxlen", "=", "None", ",", "seq_align", "=", "\"start\"", ",", "encode_type", "=", "\"one_hot\"", ")", ":", "if", "ignore_stop_codons", ":", "vocab", "=", "CODONS", "neutral_vo...
42.733333
23.333333
def sort_protein_group(pgroup, sortfunctions, sortfunc_index): """Recursive function that sorts protein group by a number of sorting functions.""" pgroup_out = [] subgroups = sortfunctions[sortfunc_index](pgroup) sortfunc_index += 1 for subgroup in subgroups: if len(subgroup) > 1 and sor...
[ "def", "sort_protein_group", "(", "pgroup", ",", "sortfunctions", ",", "sortfunc_index", ")", ":", "pgroup_out", "=", "[", "]", "subgroups", "=", "sortfunctions", "[", "sortfunc_index", "]", "(", "pgroup", ")", "sortfunc_index", "+=", "1", "for", "subgroup", "...
43.214286
16.071429
def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] """ if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in...
[ "def", "removeall", "(", "item", ",", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "str", ")", ":", "return", "seq", ".", "replace", "(", "item", ",", "''", ")", "else", ":", "return", "[", "x", "for", "x", "in", "seq", "if", "x", "!="...
29.818182
11.727273
def _get_eligible_broker_pair(self, under_loaded_rg, eligible_partition): """Evaluate and return source and destination broker-pair from over-loaded and under-loaded replication-group if possible, return None otherwise. Return source broker with maximum partitions and destination broker with ...
[ "def", "_get_eligible_broker_pair", "(", "self", ",", "under_loaded_rg", ",", "eligible_partition", ")", ":", "under_brokers", "=", "list", "(", "filter", "(", "lambda", "b", ":", "eligible_partition", "not", "in", "b", ".", "partitions", ",", "under_loaded_rg", ...
41.5
19.34375
def find_pyd_file(): """ Return path to .pyd after successful build command. :return: Path to .pyd file or None. """ if not os.path.isdir("./build"): raise NotADirectoryError for path, dirs, files in os.walk("./build"): for file_name in files: file_name_parts = os.p...
[ "def", "find_pyd_file", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "\"./build\"", ")", ":", "raise", "NotADirectoryError", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "\"./build\"", ")", ":", "for", ...
27.866667
13.6
def deviation(reference_intervals, estimated_intervals, trim=False): """Compute the median deviations between reference and estimated boundary times. Examples -------- >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab') >>> est_intervals, _ = mir_eval.io.load_labeled_intervals(...
[ "def", "deviation", "(", "reference_intervals", ",", "estimated_intervals", ",", "trim", "=", "False", ")", ":", "validate_boundary", "(", "reference_intervals", ",", "estimated_intervals", ",", "trim", ")", "# Convert intervals to boundaries", "reference_boundaries", "="...
37.559322
21.949153
def parse(self, limit=None): """ Override Source.parse() Args: :param limit (int, optional) limit the number of rows processed Returns: :return None """ if limit is not None: LOG.info("Only parsing first %d rows", limit) ensemb...
[ "def", "parse", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "not", "None", ":", "LOG", ".", "info", "(", "\"Only parsing first %d rows\"", ",", "limit", ")", "ensembl_file", "=", "'/'", ".", "join", "(", "(", "self", ".", "...
38.157895
22.789474
def bundles(ctx): """ List discovered bundles. """ bundles = _get_bundles(ctx.obj.data['env']) print_table(('Name', 'Location'), [(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}') for bundle in bundles])
[ "def", "bundles", "(", "ctx", ")", ":", "bundles", "=", "_get_bundles", "(", "ctx", ".", "obj", ".", "data", "[", "'env'", "]", ")", "print_table", "(", "(", "'Name'", ",", "'Location'", ")", ",", "[", "(", "bundle", ".", "name", ",", "f'{bundle.__mo...
33.125
10.875
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.stat...
[ "def", "debug_string", "(", "self", ",", "max_debug", "=", "MAX_DEBUG_TRIALS", ")", ":", "messages", "=", "self", ".", "_debug_messages", "(", ")", "states", "=", "collections", ".", "defaultdict", "(", "set", ")", "limit_per_state", "=", "collections", ".", ...
40.654545
14.636364
def pairwise(iterable): """ For an iterable, group values into pairs. Parameters ----------- iterable : (m, ) list A sequence of values Returns ----------- pairs: (n, 2) Pairs of sequential values Example ----------- In [1]: data Out[1]: [0, 1, 2, 3, 4, 5,...
[ "def", "pairwise", "(", "iterable", ")", ":", "# looping through a giant numpy array would be dumb", "# so special case ndarrays and use numpy operations", "if", "isinstance", "(", "iterable", ",", "np", ".", "ndarray", ")", ":", "iterable", "=", "iterable", ".", "reshape...
24.184211
19.710526
def populate(self, other): """Like update, but clears the contents first.""" self.clear() self.update(other) self.reset_all_changes()
[ "def", "populate", "(", "self", ",", "other", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "update", "(", "other", ")", "self", ".", "reset_all_changes", "(", ")" ]
32.2
11.2
def __split_nonleaf_node(self, node): """! @brief Performs splitting of the specified non-leaf node. @param[in] node (non_leaf_node): Non-leaf node that should be splitted. @return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2]. ...
[ "def", "__split_nonleaf_node", "(", "self", ",", "node", ")", ":", "[", "farthest_node1", ",", "farthest_node2", "]", "=", "node", ".", "get_farthest_successors", "(", "self", ".", "__type_measurement", ")", "# create new non-leaf nodes\r", "new_node1", "=", "non_le...
44.096774
25.225806
def check_inlet(self, helper): """ check the Inlets of Raritan PDUs """ # walk the data try: inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value']) inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit']) inlet_digits = self.sess....
[ "def", "check_inlet", "(", "self", ",", "helper", ")", ":", "# walk the data", "try", ":", "inlet_values", "=", "self", ".", "sess", ".", "walk_oid", "(", "self", ".", "oids", "[", "'oid_inlet_value'", "]", ")", "inlet_units", "=", "self", ".", "sess", "...
59.840909
31.25
def _generate_dir_structure(path): """ Internal function intended to generate the biosignalsnotebooks directories in order to the user can visualise and execute the Notebook created with "notebook" class in Jupyter. ---------- Parameters ---------- path : str Path where the biosigna...
[ "def", "_generate_dir_structure", "(", "path", ")", ":", "# ============================ Creation of the main directory ==================================", "current_dir", "=", "(", "path", "+", "\"\\\\opensignalsfactory_environment\"", ")", ".", "replace", "(", "\"\\\\\"", ",", ...
40.644444
27.933333
def get_value(self, symbol): """ Hierarchically searches for 'symbol' in the parameters blob if there is one (would have been retrieved by 'load()'). Order is: default, <env_short>, <env> Args: symbol: the key to resolve Returns: Hierarchically resolved value for 'symbol' in the environm...
[ "def", "get_value", "(", "self", ",", "symbol", ")", ":", "default", "=", "\"default\"", "if", "not", "self", ".", "parameters", ":", "return", "None", "# Hierarchically lookup the value", "result", "=", "None", "if", "default", "in", "self", ".", "parameters"...
42.37037
22.37037
def tick(self): """Mark the passage of time and decay the current rate accordingly.""" instant_rate = self.count / float(self.tick_interval_s) self.count = 0 if self.initialized: self.rate += (self.alpha * (instant_rate - self.rate)) else: self.rate = inst...
[ "def", "tick", "(", "self", ")", ":", "instant_rate", "=", "self", ".", "count", "/", "float", "(", "self", ".", "tick_interval_s", ")", "self", ".", "count", "=", "0", "if", "self", ".", "initialized", ":", "self", ".", "rate", "+=", "(", "self", ...
39.555556
15.555556
def write(self, fptr): """Write a data entry url box to file. """ # Make sure it is written out as null-terminated. url = self.url if self.url[-1] != chr(0): url = url + chr(0) url = url.encode() length = 8 + 1 + 3 + len(url) write_buffer = st...
[ "def", "write", "(", "self", ",", "fptr", ")", ":", "# Make sure it is written out as null-terminated.", "url", "=", "self", ".", "url", "if", "self", ".", "url", "[", "-", "1", "]", "!=", "chr", "(", "0", ")", ":", "url", "=", "url", "+", "chr", "("...
35.0625
13.25
def get_frame(self, idx, history_length=1): """ Return frame from the buffer """ if idx >= self.current_size: raise VelException("Requested frame beyond the size of the buffer") if history_length > 1: assert self.state_buffer.shape[-1] == 1, \ "State buff...
[ "def", "get_frame", "(", "self", ",", "idx", ",", "history_length", "=", "1", ")", ":", "if", "idx", ">=", "self", ".", "current_size", ":", "raise", "VelException", "(", "\"Requested frame beyond the size of the buffer\"", ")", "if", "history_length", ">", "1",...
38.75
20.392857
def sqlCreate(self): """ Reasonably portable SQL CREATE for defined fields. Returns: string: Portable as possible SQL Create for all-reads table. """ count = 0 qry_str = "CREATE TABLE Meter_Reads ( \n\r" qry_str = self.fillCreate(qry_str) ekm_log(qry_s...
[ "def", "sqlCreate", "(", "self", ")", ":", "count", "=", "0", "qry_str", "=", "\"CREATE TABLE Meter_Reads ( \\n\\r\"", "qry_str", "=", "self", ".", "fillCreate", "(", "qry_str", ")", "ekm_log", "(", "qry_str", ",", "4", ")", "return", "qry_str" ]
34
14.3
def _check_data_port_name(self, data_port): """Checks the validity of a data port name Checks whether the name of the given data port is already used by anther data port within the state. Names must be unique with input data ports and output data ports. :param rafcon.core.data_port.Dat...
[ "def", "_check_data_port_name", "(", "self", ",", "data_port", ")", ":", "if", "data_port", ".", "data_port_id", "in", "self", ".", "input_data_ports", ":", "for", "input_data_port", "in", "self", ".", "input_data_ports", ".", "values", "(", ")", ":", "if", ...
58.095238
35.380952
def pending(self, start='-', stop='+', count=1000, consumer=None): """ List pending messages within the consumer group for this stream. :param start: start id (or '-' for oldest pending) :param stop: stop id (or '+' for newest pending) :param count: limit number of messages retu...
[ "def", "pending", "(", "self", ",", "start", "=", "'-'", ",", "stop", "=", "'+'", ",", "count", "=", "1000", ",", "consumer", "=", "None", ")", ":", "return", "self", ".", "database", ".", "xpending_range", "(", "self", ".", "key", ",", "self", "."...
52.461538
23.076923
def from_str(cls, s): """ Accepts both the output of to_simple_str() and __str__(). """ if not isinstance(s, str): raise TypeError("Expected an str instance, received %r" % (s,)) return cls(cls.bits_from_str(s))
[ "def", "from_str", "(", "cls", ",", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Expected an str instance, received %r\"", "%", "(", "s", ",", ")", ")", "return", "cls", "(", "cls", ".", "bits_...
48.6
12
def filter_nan(s, o): """ this functions removed the data from simulated and observed data whereever the observed data contains nan this is used by all other functions, otherwise they will produce nan as output """ data = np.array([s.flatten(), o.flatten()]) data = ...
[ "def", "filter_nan", "(", "s", ",", "o", ")", ":", "data", "=", "np", ".", "array", "(", "[", "s", ".", "flatten", "(", ")", ",", "o", ".", "flatten", "(", ")", "]", ")", "data", "=", "np", ".", "transpose", "(", "data", ")", "data", "=", "...
33.416667
15.916667
def _on_connect(self, participant): """Called from the WebSocket consumer. Checks if all players in the group have connected; runs :meth:`when_all_players_ready` once all connections are established. """ lock = get_redis_lock() if not lock: lock = fake_lock() ...
[ "def", "_on_connect", "(", "self", ",", "participant", ")", ":", "lock", "=", "get_redis_lock", "(", ")", "if", "not", "lock", ":", "lock", "=", "fake_lock", "(", ")", "with", "lock", ":", "self", ".", "refresh_from_db", "(", ")", "if", "self", ".", ...
38.206897
17.586207
def subset(train, idx, keep_other=True): """Subset the `train=(x, y)` data tuple, each of the form: - list, np.ndarray - tuple, np.ndarray - dictionary, np.ndarray - np.ndarray, np.ndarray # Note In case there are other data present in the tuple: `(x, y, other1, other2, ...)`, ...
[ "def", "subset", "(", "train", ",", "idx", ",", "keep_other", "=", "True", ")", ":", "test_len", "(", "train", ")", "y", "=", "train", "[", "1", "]", "[", "idx", "]", "# x split", "if", "isinstance", "(", "train", "[", "0", "]", ",", "(", "list",...
31.542857
18.828571
def get_metric_by_week(self, unique_identifier, metric, from_date, limit=10, **kwargs): """ Returns the ``metric`` for ``unique_identifier`` segmented by week starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metr...
[ "def", "get_metric_by_week", "(", "self", ",", "unique_identifier", ",", "metric", ",", "from_date", ",", "limit", "=", "10", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "kwargs", ".", "get", "(", "\"connection\"", ",", "None", ")", "closest_monday_fro...
50.419355
31.387097
def batch_row_ids(data_batch): """ Generate row ids based on the current mini-batch """ item = data_batch.data[0] user = data_batch.data[1] return {'user_weight': user.astype(np.int64), 'item_weight': item.astype(np.int64)}
[ "def", "batch_row_ids", "(", "data_batch", ")", ":", "item", "=", "data_batch", ".", "data", "[", "0", "]", "user", "=", "data_batch", ".", "data", "[", "1", "]", "return", "{", "'user_weight'", ":", "user", ".", "astype", "(", "np", ".", "int64", ")...
41
8.333333
def getName(self, value, defaultName = None): ''' Get the enumerate name of a specified value. :param value: the enumerate value :param defaultName: returns if the enumerate value is not defined :returns: the corresponding enumerate value or *defaultName* if not found '''...
[ "def", "getName", "(", "self", ",", "value", ",", "defaultName", "=", "None", ")", ":", "for", "k", ",", "v", "in", "self", ".", "_values", ".", "items", "(", ")", ":", "if", "v", "==", "value", ":", "return", "k", "return", "defaultName" ]
39.090909
17.636364
def inject(self, span_context, format, carrier): """Injects `span_context` into `carrier`. The type of `carrier` is determined by `format`. See the :class:`Format` class/namespace for the built-in OpenTracing formats. Implementations *must* raise :exc:`UnsupportedFormatException` if ...
[ "def", "inject", "(", "self", ",", "span_context", ",", "format", ",", "carrier", ")", ":", "if", "format", "in", "Tracer", ".", "_supported_formats", ":", "return", "raise", "UnsupportedFormatException", "(", "format", ")" ]
42.238095
21.761905
def init_app(self, app, path='templates.yaml'): """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: ...
[ "def", "init_app", "(", "self", ",", "app", ",", "path", "=", "'templates.yaml'", ")", ":", "if", "self", ".", "_route", "is", "None", ":", "raise", "TypeError", "(", "\"route is a required argument when app is not None\"", ")", "self", ".", "app", "=", "app",...
46.952381
34.619048
def tree_compare(self, othertree, vntree_meta=False): """Compare the (sub-)tree rooted at `self` with another tree. `tree_compare` converts the trees being compared into JSON string representations, and uses `difflib.SequenceMatcher().ratio()` to calculate a measure of the similarity of...
[ "def", "tree_compare", "(", "self", ",", "othertree", ",", "vntree_meta", "=", "False", ")", ":", "return", "SequenceMatcher", "(", "None", ",", "json", ".", "dumps", "(", "self", ".", "to_treedict", "(", "vntree_meta", "=", "vntree_meta", ")", ",", "defau...
47.5
22.611111
def draw_nodes(self): """ Draw nodes to screen. """ node_r = self.node_sizes for i, node in enumerate(self.nodes): x = self.node_coords["x"][i] y = self.node_coords["y"][i] color = self.node_colors[i] node_patch = patches.Ellipse( ...
[ "def", "draw_nodes", "(", "self", ")", ":", "node_r", "=", "self", ".", "node_sizes", "for", "i", ",", "node", "in", "enumerate", "(", "self", ".", "nodes", ")", ":", "x", "=", "self", ".", "node_coords", "[", "\"x\"", "]", "[", "i", "]", "y", "=...
33.538462
8.153846
def _mzmlListAttribToTuple(oldList): """Turns the param entries of elements in a list elements into tuples, used in :func:`MzmlScan._fromJSON()` and :func:`MzmlPrecursor._fromJSON()`. .. note:: only intended for a list of elements that contain params. For example the mzML element ``selectedIonList`...
[ "def", "_mzmlListAttribToTuple", "(", "oldList", ")", ":", "newList", "=", "list", "(", ")", "for", "oldParamList", "in", "oldList", ":", "newParamLIst", "=", "[", "tuple", "(", "param", ")", "for", "param", "in", "oldParamList", "]", "newList", ".", "appe...
38.6875
20.5625
def progress(progress): """Convert given progress to a JSON object. Check that progress can be represented as float between 0 and 1 and return it in JSON of the form: {"proc.progress": progress} """ if isinstance(progress, int) or isinstance(progress, float): progress = float(prog...
[ "def", "progress", "(", "progress", ")", ":", "if", "isinstance", "(", "progress", ",", "int", ")", "or", "isinstance", "(", "progress", ",", "float", ")", ":", "progress", "=", "float", "(", "progress", ")", "else", ":", "try", ":", "progress", "=", ...
29.857143
20.047619
def add_error(self, group, term, sub_term, value): """For records that are not defined as terms, either add it to the errors list.""" self._errors[(group, term, sub_term)] = value
[ "def", "add_error", "(", "self", ",", "group", ",", "term", ",", "sub_term", ",", "value", ")", ":", "self", ".", "_errors", "[", "(", "group", ",", "term", ",", "sub_term", ")", "]", "=", "value" ]
40
12.6
def workflow_set_details(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/setDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FsetDetails """ return DXHTTPRequest('/%s/se...
[ "def", "workflow_set_details", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/setDetails'", "%", "object_id", ",", "input_params", ",", "always_re...
55.285714
36.142857
def list_joined_topics(self, start=0): """ 已加入的所有小组的话题列表 :param start: 翻页 :return: 带下一页的列表 """ xml = self.api.xml(API_GROUP_HOME, params={'start': start}) return build_list_result(self._parse_topic_table(xml, 'title,comment,created,group'), xml)
[ "def", "list_joined_topics", "(", "self", ",", "start", "=", "0", ")", ":", "xml", "=", "self", ".", "api", ".", "xml", "(", "API_GROUP_HOME", ",", "params", "=", "{", "'start'", ":", "start", "}", ")", "return", "build_list_result", "(", "self", ".", ...
33.555556
18.888889
def make_ranges(self, file_url): """ Divides file_url size into an array of ranges to be downloaded by workers. :param: file_url: ProjectFileUrl: file url to download :return: [(int,int)]: array of (start, end) tuples """ size = file_url.size bytes_per_chunk = sel...
[ "def", "make_ranges", "(", "self", ",", "file_url", ")", ":", "size", "=", "file_url", ".", "size", "bytes_per_chunk", "=", "self", ".", "determine_bytes_per_chunk", "(", "size", ")", "start", "=", "0", "ranges", "=", "[", "]", "while", "size", ">", "0",...
34.833333
15.055556
def segment_text(text=os.path.join(DATA_PATH, 'goodreads-omniscient-books.txt'), start=None, stop=r'^Rate\ this', ignore=r'^[\d]'): """ Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start """ start = start if hasattr(start, 'match') else re.comp...
[ "def", "segment_text", "(", "text", "=", "os", ".", "path", ".", "join", "(", "DATA_PATH", ",", "'goodreads-omniscient-books.txt'", ")", ",", "start", "=", "None", ",", "stop", "=", "r'^Rate\\ this'", ",", "ignore", "=", "r'^[\\d]'", ")", ":", "start", "="...
45.681818
20.772727
def _get_directory_stash(self, path): """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) save_dir.create() except ...
[ "def", "_get_directory_stash", "(", "self", ",", "path", ")", ":", "try", ":", "save_dir", "=", "AdjacentTempDirectory", "(", "path", ")", "save_dir", ".", "create", "(", ")", "except", "OSError", ":", "save_dir", "=", "TempDirectory", "(", "kind", "=", "\...
32.533333
18.266667
def is_cnpj(numero, estrito=False): """Uma versão conveniente para usar em testes condicionais. Apenas retorna verdadeiro ou falso, conforme o argumento é validado. :param bool estrito: Padrão ``False``, indica se apenas os dígitos do número deverão ser considerados. Se verdadeiro, potenciais carac...
[ "def", "is_cnpj", "(", "numero", ",", "estrito", "=", "False", ")", ":", "try", ":", "cnpj", "(", "digitos", "(", "numero", ")", "if", "not", "estrito", "else", "numero", ")", "return", "True", "except", "NumeroCNPJError", ":", "pass", "return", "False" ...
36.2
22.933333
def post(self, path, body): """POST request.""" return self._make_request('post', self._format_url(API_ROOT + path), { 'json': body })
[ "def", "post", "(", "self", ",", "path", ",", "body", ")", ":", "return", "self", ".", "_make_request", "(", "'post'", ",", "self", ".", "_format_url", "(", "API_ROOT", "+", "path", ")", ",", "{", "'json'", ":", "body", "}", ")" ]
30.833333
10
def parse_version(package): """ Statically parse the version number from __init__.py CommandLine: python -c "import setup; print(setup.parse_version('ubelt'))" """ from os.path import dirname, join, exists import ast # Check if the package is a single-file or multi-file package ...
[ "def", "parse_version", "(", "package", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", "import", "ast", "# Check if the package is a single-file or multi-file package", "_candiates", "=", "[", "join", "(", "dirname", "(", "__...
33.676471
16.794118
def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandEx...
[ "def", "build_interface", "(", "iface", ",", "iface_type", ",", "enabled", ",", "*", "*", "settings", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'N...
34.911765
24.264706
def absolute_path(path=None, base_dir=None): """ Return absolute path if path is local. Parameters: ----------- path : path to file base_dir : base directory used for absolute path Returns: -------- absolute path """ if path_is_remote(path): return path else: ...
[ "def", "absolute_path", "(", "path", "=", "None", ",", "base_dir", "=", "None", ")", ":", "if", "path_is_remote", "(", "path", ")", ":", "return", "path", "else", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", ...
25.681818
19.863636
def standard_sc_expr_str(sc): """ Standard symbol/choice printing function. Uses plain Kconfig syntax, and displays choices as <choice> (or <choice NAME>, for named choices). See expr_str(). """ if sc.__class__ is Symbol: return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.n...
[ "def", "standard_sc_expr_str", "(", "sc", ")", ":", "if", "sc", ".", "__class__", "is", "Symbol", ":", "return", "'\"{}\"'", ".", "format", "(", "escape", "(", "sc", ".", "name", ")", ")", "if", "sc", ".", "is_constant", "else", "sc", ".", "name", "#...
32.833333
23.333333
def liked(parser, token): """ {% liked objects by user as varname %} """ tag, objects, _, user, _, varname = token.split_contents() return LikedObjectsNode(objects, user, varname)
[ "def", "liked", "(", "parser", ",", "token", ")", ":", "tag", ",", "objects", ",", "_", ",", "user", ",", "_", ",", "varname", "=", "token", ".", "split_contents", "(", ")", "return", "LikedObjectsNode", "(", "objects", ",", "user", ",", "varname", "...
32.333333
8.333333
def to_hdf(self, path_or_buf, key, **kwargs): """ Write the contained data to an HDF5 file using HDFStore. Hierarchical Data Format (HDF) is self-describing, allowing an application to interpret the structure and contents of a file with no outside information. One HDF file can h...
[ "def", "to_hdf", "(", "self", ",", "path_or_buf", ",", "key", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "io", "import", "pytables", "return", "pytables", ".", "to_hdf", "(", "path_or_buf", ",", "key", ",", "self", ",", "*", "*", "kwar...
39.970874
21.485437
def execute_before_scenario_steps(self, context): """ actions before each scenario :param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave. """ if not self.feature_error: self.__execute_steps_by_a...
[ "def", "execute_before_scenario_steps", "(", "self", ",", "context", ")", ":", "if", "not", "self", ".", "feature_error", ":", "self", ".", "__execute_steps_by_action", "(", "context", ",", "ACTIONS_BEFORE_SCENARIO", ")", "if", "context", ".", "dyn_env", ".", "s...
46.363636
20.727273
def load(path): """ Load pickled object from the specified file path. Parameters ---------- path : string File path Returns ------- unpickled : type of object stored in file """ f = open(path, 'rb') try: return pickle.load(f) finally: f.close()
[ "def", "load", "(", "path", ")", ":", "f", "=", "open", "(", "path", ",", "'rb'", ")", "try", ":", "return", "pickle", ".", "load", "(", "f", ")", "finally", ":", "f", ".", "close", "(", ")" ]
16.722222
21.611111
def connect_forwarder(forward_host=None, forward_port=None, max_retries=-1, sleep_interval=1.0): """connect_forwarder :param forward_host: host for receiving forwarded packets :param forward_port: port for the forwarded packets :param ma...
[ "def", "connect_forwarder", "(", "forward_host", "=", "None", ",", "forward_port", "=", "None", ",", "max_retries", "=", "-", "1", ",", "sleep_interval", "=", "1.0", ")", ":", "forward_skt", "=", "None", "retry_count", "=", "0", "if", "max_retries", "==", ...
35.595745
11.489362
def interact_plain(header=UP_LINE, local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None): """ Create an interactive python console """ frame = sys._getframe(stack_depth) variables = {} if local_ns is not None: variables.update(loca...
[ "def", "interact_plain", "(", "header", "=", "UP_LINE", ",", "local_ns", "=", "None", ",", "module", "=", "None", ",", "dummy", "=", "None", ",", "stack_depth", "=", "1", ",", "global_ns", "=", "None", ")", ":", "frame", "=", "sys", ".", "_getframe", ...
25.545455
14.090909
def get_POST_data(self): """ Returns: dict: POST data, which can be sent to webform using \ :py:mod:`urllib` or similar library """ self._postprocess() # some fields need to be remapped (depends on type of media) self._apply_mapping( ...
[ "def", "get_POST_data", "(", "self", ")", ":", "self", ".", "_postprocess", "(", ")", "# some fields need to be remapped (depends on type of media)", "self", ".", "_apply_mapping", "(", "self", ".", "mapping", ".", "get", "(", "self", ".", "_POST", "[", "\"P050201...
28.1875
21.0625
def get_pull_request_files(project, num, auth=False): """get list of files in a pull request""" url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num) if auth: header = make_auth_header() else: header = None return get_paged_request(url, hea...
[ "def", "get_pull_request_files", "(", "project", ",", "num", ",", "auth", "=", "False", ")", ":", "url", "=", "\"https://api.github.com/repos/{project}/pulls/{num}/files\"", ".", "format", "(", "project", "=", "project", ",", "num", "=", "num", ")", "if", "auth"...
40.625
20.75
def whois_domains(self, domains): """Calls WHOIS domain end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_result} """ api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self._multi_get(a...
[ "def", "whois_domains", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-whois-domain'", "fmt_url_path", "=", "u'whois/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
31
12.454545
def find(self, i): ''' API: find(self, i) Description: Returns root of set that has i. Input: i: Item. Return: Returns root of set that has i. ''' current = i edge_list = [] while len(self.get_neighbo...
[ "def", "find", "(", "self", ",", "i", ")", ":", "current", "=", "i", "edge_list", "=", "[", "]", "while", "len", "(", "self", ".", "get_neighbors", "(", "current", ")", ")", "!=", "0", ":", "successor", "=", "self", ".", "get_neighbors", "(", "curr...
29.043478
15.913043
def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: raise SpamCError('The action option is invalid') return action
[ "def", "_check_action", "(", "action", ")", ":", "if", "isinstance", "(", "action", ",", "types", ".", "StringTypes", ")", ":", "action", "=", "action", ".", "lower", "(", ")", "if", "action", "not", "in", "[", "'learn'", ",", "'forget'", ",", "'report...
33.875
16
def sorted(self, by, **kwargs): """Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time'). """ sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=se...
[ "def", "sorted", "(", "self", ",", "by", ",", "*", "*", "kwargs", ")", ":", "sort_idc", "=", "np", ".", "argsort", "(", "self", "[", "by", "]", ",", "*", "*", "kwargs", ")", "return", "self", ".", "__class__", "(", "self", "[", "sort_idc", "]", ...
25.866667
15.133333
def is_consistent(self) -> bool: """ Returns True if number of nodes are consistent with number of leaves """ from ledger.compact_merkle_tree import CompactMerkleTree return self.nodeCount == CompactMerkleTree.get_expected_node_count( self.leafCount)
[ "def", "is_consistent", "(", "self", ")", "->", "bool", ":", "from", "ledger", ".", "compact_merkle_tree", "import", "CompactMerkleTree", "return", "self", ".", "nodeCount", "==", "CompactMerkleTree", ".", "get_expected_node_count", "(", "self", ".", "leafCount", ...
42.285714
16.571429
def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwa...
[ "def", "_create_connection", "(", "self", ",", "future", ")", ":", "LOGGER", ".", "debug", "(", "'Creating a new connection for %s'", ",", "self", ".", "pid", ")", "# Create a new PostgreSQL connection", "kwargs", "=", "utils", ".", "uri_to_kwargs", "(", "self", "...
36.088235
20.25
def _validate_channel_definition(self, jp2h, colr): """Validate the channel definition box.""" cdef_lst = [j for (j, box) in enumerate(jp2h.box) if box.box_id == 'cdef'] if len(cdef_lst) > 1: msg = ("Only one channel definition box is allowed in the " ...
[ "def", "_validate_channel_definition", "(", "self", ",", "jp2h", ",", "colr", ")", ":", "cdef_lst", "=", "[", "j", "for", "(", "j", ",", "box", ")", "in", "enumerate", "(", "jp2h", ".", "box", ")", "if", "box", ".", "box_id", "==", "'cdef'", "]", "...
49.428571
12.761905
def convert_ranges(cls, ranges, length): """Converts to valid byte ranges""" result = [] for start, end in ranges: if end is None: result.append( (start, length-1) ) elif start is None: s = length - end result.append( (0 if ...
[ "def", "convert_ranges", "(", "cls", ",", "ranges", ",", "length", ")", ":", "result", "=", "[", "]", "for", "start", ",", "end", "in", "ranges", ":", "if", "end", "is", "None", ":", "result", ".", "append", "(", "(", "start", ",", "length", "-", ...
37.5
13.916667
def next(self): """next(self) -> Annot""" CheckParent(self) val = _fitz.Annot_next(self) if val: val.thisown = True val.parent = self.parent # copy owning page object from previous annot val.parent._annot_refs[id(val)] = val return val
[ "def", "next", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Annot_next", "(", "self", ")", "if", "val", ":", "val", ".", "thisown", "=", "True", "val", ".", "parent", "=", "self", ".", "parent", "# copy owning pa...
27.545455
21.090909
def inspect_built_image(self): """ inspect built image :return: dict """ logger.info("inspecting built image '%s'", self.image_id) self.ensure_is_built() # dict with lots of data, see man docker-inspect inspect_data = self.tasker.inspect_image(self.image_...
[ "def", "inspect_built_image", "(", "self", ")", ":", "logger", ".", "info", "(", "\"inspecting built image '%s'\"", ",", "self", ".", "image_id", ")", "self", ".", "ensure_is_built", "(", ")", "# dict with lots of data, see man docker-inspect", "inspect_data", "=", "s...
31
15.363636
def _merge_with_other_stm(self, other: "IfContainer") -> None: """ Merge other statement to this statement """ merge = self._merge_statement_lists newCases = [] for (c, caseA), (_, caseB) in zip(self.cases, other.cases): newCases.append((c, merge(caseA, caseB)...
[ "def", "_merge_with_other_stm", "(", "self", ",", "other", ":", "\"IfContainer\"", ")", "->", "None", ":", "merge", "=", "self", ".", "_merge_statement_lists", "newCases", "=", "[", "]", "for", "(", "c", ",", "caseA", ")", ",", "(", "_", ",", "caseB", ...
31.333333
17.2
def is_rdemo(file_name): """ Return True if file_name matches a regexp for an R demo. False otherwise. :param file_name: file to test """ packaged_demos = ["h2o.anomaly.R", "h2o.deeplearning.R", "h2o.gbm.R", "h2o.glm.R", "h2o.glrm.R", "h2o.kmeans.R", "h2o.naiveBayes.R", "h2o.p...
[ "def", "is_rdemo", "(", "file_name", ")", ":", "packaged_demos", "=", "[", "\"h2o.anomaly.R\"", ",", "\"h2o.deeplearning.R\"", ",", "\"h2o.gbm.R\"", ",", "\"h2o.glm.R\"", ",", "\"h2o.glrm.R\"", ",", "\"h2o.kmeans.R\"", ",", "\"h2o.naiveBayes.R\"", ",", "\"h2o.prcomp.R\"...
47.3
23.1
def fromxml(node): """Return a profile instance from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) args = [] if node.tag == 'profile': ...
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "args", "=", "[", "]", "if", "node", ".", ...
47.6
19.5
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
[ "def", "textify", "(", "self", ",", "nums", ":", "Collection", "[", "int", "]", ",", "sep", "=", "' '", ")", "->", "List", "[", "str", "]", ":", "return", "sep", ".", "join", "(", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nu...
73
33
def returner(load): ''' Return data to a postgres server ''' conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, return, id, success) VALUES (%s, %s, %s, %s, %s)''' try: ret = six.text_ty...
[ "def", "returner", "(", "load", ")", ":", "conn", "=", "_get_conn", "(", ")", "if", "conn", "is", "None", ":", "return", "None", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''INSERT INTO salt_returns\n (fun, jid, return, id, success)\n ...
25.566667
15.7
def GroupSizer(field_number, is_repeated, is_packed): """Returns a sizer for a group field.""" tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() ...
[ "def", "GroupSizer", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "tag_size", "=", "_TagSize", "(", "field_number", ")", "*", "2", "assert", "not", "is_packed", "if", "is_repeated", ":", "def", "RepeatedFieldSize", "(", "value", ")", ...
27.75
14
def dict_values(src): """ Recursively get values in dict. Unlike the builtin dict.values() function, this method will descend into nested dicts, returning all nested values. Arguments: src (dict): Source dict. Returns: list: List of values. """ for v in src.values(): ...
[ "def", "dict_values", "(", "src", ")", ":", "for", "v", "in", "src", ".", "values", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "for", "v", "in", "dict_values", "(", "v", ")", ":", "yield", "v", "else", ":", "yield", "v"...
22.473684
18.473684
def _reindex(self): """ Create a case-insensitive index of the paths """ self.index = [] for path in self.paths: target_path = os.path.normpath(os.path.join(BASE_PATH, path)) for root, subdirs, files ...
[ "def", "_reindex", "(", "self", ")", ":", "self", ".", "index", "=", "[", "]", "for", "path", "in", "self", ".", "paths", ":", "target_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "BASE_PATH", ",", "pa...
39.076923
12.461538
def giant_text_sqltype(dialect: Dialect) -> str: """ Returns the SQL column type used to make very large text columns for a given dialect. Args: dialect: a SQLAlchemy :class:`Dialect` Returns: the SQL data type of "giant text", typically 'LONGTEXT' for MySQL and 'NVARCHAR(MA...
[ "def", "giant_text_sqltype", "(", "dialect", ":", "Dialect", ")", "->", "str", ":", "if", "dialect", ".", "name", "==", "SqlaDialectName", ".", "SQLSERVER", ":", "return", "'NVARCHAR(MAX)'", "elif", "dialect", ".", "name", "==", "SqlaDialectName", ".", "MYSQL"...
33.235294
17.941176
def pprint(self, output, prefix=""): """ Pretty-print the encoded output using ascii art. :param output: to print :param prefix: printed before the header if specified """ print prefix, description = self.getDescription() + [("end", self.getWidth())] for i in xrange(len(description) - 1...
[ "def", "pprint", "(", "self", ",", "output", ",", "prefix", "=", "\"\"", ")", ":", "print", "prefix", ",", "description", "=", "self", ".", "getDescription", "(", ")", "+", "[", "(", "\"end\"", ",", "self", ".", "getWidth", "(", ")", ")", "]", "for...
32.357143
14.357143
def embedded_tweet(self): """ Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object Returns: Tweet (or None, if the Tweet is neither a quote tweet or a Retweet): a Tweet representing the quote Tweet or the Retweet (see tweet_embeds.get_e...
[ "def", "embedded_tweet", "(", "self", ")", ":", "embedded_tweet", "=", "tweet_embeds", ".", "get_embedded_tweet", "(", "self", ")", "if", "embedded_tweet", "is", "not", "None", ":", "try", ":", "return", "Tweet", "(", "embedded_tweet", ")", "except", "NotATwee...
40.761905
23.904762
def configure_settings(settings, environment_settings=True): ''' Given a settings object, run automatic configuration of all the apps in INSTALLED_APPS. ''' changes = 1 iterations = 0 while changes: changes = 0 app_names = ['django_autoconfig'] + list(settings['INSTALLED_APP...
[ "def", "configure_settings", "(", "settings", ",", "environment_settings", "=", "True", ")", ":", "changes", "=", "1", "iterations", "=", "0", "while", "changes", ":", "changes", "=", "0", "app_names", "=", "[", "'django_autoconfig'", "]", "+", "list", "(", ...
38.475
20.075
def xslt_transformation(xml, template): """ Transform `xml` using XSLT `template`. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. template (str): Filename or XML string. Don't use ``\\n`` in case of filename. R...
[ "def", "xslt_transformation", "(", "xml", ",", "template", ")", ":", "transformer", "=", "ET", ".", "XSLT", "(", "_read_template", "(", "template", ")", ")", "newdom", "=", "transformer", "(", "_read_marcxml", "(", "xml", ")", ")", "return", "ET", ".", "...
26.238095
19.857143
def _learn(self, legislator): """ Expects a dictionary with full_name, first_name, last_name and middle_name elements as key. While this can grow quickly, we should never be dealing with more than a few hundred legislators at a time so don't worry about it. """ ...
[ "def", "_learn", "(", "self", ",", "legislator", ")", ":", "name", ",", "obj", "=", "legislator", ",", "legislator", "[", "'_id'", "]", "if", "(", "legislator", "[", "'roles'", "]", "and", "legislator", "[", "'roles'", "]", "[", "0", "]", "[", "'term...
44.578313
21.46988
def read_table(self, table, key_filter=True): """ Yield rows in the [incr tsdb()] *table* that pass any defined filters, and with values changed by any applicators. If no filters or applicators are defined, the result is the same as from ItsdbProfile.read_raw_table(). """...
[ "def", "read_table", "(", "self", ",", "table", ",", "key_filter", "=", "True", ")", ":", "filters", "=", "self", ".", "filters", "[", "None", "]", "+", "self", ".", "filters", "[", "table", "]", "if", "key_filter", ":", "for", "f", "in", "self", "...
50.380952
16
def make_clean_visible_file(i_chunk, clean_visible_path): '''make a temp file of clean_visible text''' _clean = open(clean_visible_path, 'wb') _clean.write('<?xml version="1.0" encoding="UTF-8"?>') _clean.write('<root>') for idx, si in enumerate(i_chunk): if si.stream_id is None: ...
[ "def", "make_clean_visible_file", "(", "i_chunk", ",", "clean_visible_path", ")", ":", "_clean", "=", "open", "(", "clean_visible_path", ",", "'wb'", ")", "_clean", ".", "write", "(", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", ")", "_clean", ".", "write", "(", ...
43.230769
16.769231
def get_doctype(self, index, name): """ Returns a doctype given an index and a name """ if index not in self.indices: self.get_all_indices() return self.indices.get(index, {}).get(name, None)
[ "def", "get_doctype", "(", "self", ",", "index", ",", "name", ")", ":", "if", "index", "not", "in", "self", ".", "indices", ":", "self", ".", "get_all_indices", "(", ")", "return", "self", ".", "indices", ".", "get", "(", "index", ",", "{", "}", ")...
33.857143
6.142857
def unstar(self, login, repo): """Unstar to login/repo :param str login: (required), owner of the repo :param str repo: (required), name of the repo :return: bool """ resp = False if login and repo: url = self._build_url('user', 'starred', login, repo...
[ "def", "unstar", "(", "self", ",", "login", ",", "repo", ")", ":", "resp", "=", "False", "if", "login", "and", "repo", ":", "url", "=", "self", ".", "_build_url", "(", "'user'", ",", "'starred'", ",", "login", ",", "repo", ")", "resp", "=", "self",...
32.666667
16.5
def get_object_id_from_graph(access_token=None): '''Return the object ID for the Graph user who owns the access token. Args: access_token (str): A Microsoft Graph access token. (Not an Azure access token.) If not provided, attempt to get it from MSI_ENDPOINT. Returns: ...
[ "def", "get_object_id_from_graph", "(", "access_token", "=", "None", ")", ":", "if", "access_token", "is", "None", ":", "access_token", "=", "get_graph_token_from_msi", "(", ")", "endpoint", "=", "'https://'", "+", "GRAPH_RESOURCE_HOST", "+", "'/v1.0/me/'", "headers...
39.882353
27.764706
def check_output(self, cmd): """Calls a command through SSH and returns its output. """ ret, output = self._call(cmd, True) if ret != 0: # pragma: no cover raise RemoteCommandFailure(command=cmd, ret=ret) logger.debug("Output: %r", output) return output
[ "def", "check_output", "(", "self", ",", "cmd", ")", ":", "ret", ",", "output", "=", "self", ".", "_call", "(", "cmd", ",", "True", ")", "if", "ret", "!=", "0", ":", "# pragma: no cover", "raise", "RemoteCommandFailure", "(", "command", "=", "cmd", ","...
38.375
7
def _git_enable_branch(desired_branch): """Enable desired branch name.""" preserved_branch = _git_get_current_branch() try: if preserved_branch != desired_branch: _tool_run('git checkout ' + desired_branch) yield finally: if preserved_branch and preserved_branch != de...
[ "def", "_git_enable_branch", "(", "desired_branch", ")", ":", "preserved_branch", "=", "_git_get_current_branch", "(", ")", "try", ":", "if", "preserved_branch", "!=", "desired_branch", ":", "_tool_run", "(", "'git checkout '", "+", "desired_branch", ")", "yield", "...
38.2
16.1
def check_captcha(self, captcha, value, id=None): """ http://api.yandex.ru/cleanweb/doc/dg/concepts/check-captcha.xml""" payload = {'captcha': captcha, 'value': value, 'id': id} r = self.request('get', 'http://cleanweb-api.yandex.ru/1.0/check-captcha', param...
[ "def", "check_captcha", "(", "self", ",", "captcha", ",", "value", ",", "id", "=", "None", ")", ":", "payload", "=", "{", "'captcha'", ":", "captcha", ",", "'value'", ":", "value", ",", "'id'", ":", "id", "}", "r", "=", "self", ".", "request", "(",...
43.181818
12.454545
def router_add(self, params): """add new router (mongos) into existing configuration""" if self.uses_rs_configdb: # Replica set configdb. rs_id = self._configsvrs[0] config_members = ReplicaSets().members(rs_id) configdb = '%s/%s' % ( rs_id...
[ "def", "router_add", "(", "self", ",", "params", ")", ":", "if", "self", ".", "uses_rs_configdb", ":", "# Replica set configdb.", "rs_id", "=", "self", ".", "_configsvrs", "[", "0", "]", "config_members", "=", "ReplicaSets", "(", ")", ".", "members", "(", ...
43.75
15.125
def process_file(self): """Deprecated.""" warnings.warn(DeprecationWarning("'self.process_file' is deprecated")) return os.path.join(self._raw["config_dir"], self._raw["process"])
[ "def", "process_file", "(", "self", ")", ":", "warnings", ".", "warn", "(", "DeprecationWarning", "(", "\"'self.process_file' is deprecated\"", ")", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_raw", "[", "\"config_dir\"", "]", ",", "se...
50
22.25
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in...
[ "def", "_find_address_range", "(", "addresses", ")", ":", "it", "=", "iter", "(", "addresses", ")", "first", "=", "last", "=", "next", "(", "it", ")", "for", "ip", "in", "it", ":", "if", "ip", ".", "_ip", "!=", "last", ".", "_ip", "+", "1", ":", ...
24.166667
19.888889
def has_file(self, name: str): ''' check whether this directory contains the file. ''' return os.path.isfile(self._path / name)
[ "def", "has_file", "(", "self", ",", "name", ":", "str", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "self", ".", "_path", "/", "name", ")" ]
31
18.2
def indicator(self, data): """Update the request URI to include the Indicator for specific indicator retrieval. Args: data (string): The indicator value """ # handle hashes in form md5 : sha1 : sha256 data = self.get_first_hash(data) super(File, self).indicat...
[ "def", "indicator", "(", "self", ",", "data", ")", ":", "# handle hashes in form md5 : sha1 : sha256", "data", "=", "self", ".", "get_first_hash", "(", "data", ")", "super", "(", "File", ",", "self", ")", ".", "indicator", "(", "data", ")" ]
35.555556
11
def random_sense(ambiguous_word: str, pos=None) -> "wn.Synset": """ Returns a random sense. :param ambiguous_word: String, a single word. :param pos: String, one of 'a', 'r', 's', 'n', 'v', or None. :return: A random Synset. """ if pos is None: return custom_random.choice(wn.synset...
[ "def", "random_sense", "(", "ambiguous_word", ":", "str", ",", "pos", "=", "None", ")", "->", "\"wn.Synset\"", ":", "if", "pos", "is", "None", ":", "return", "custom_random", ".", "choice", "(", "wn", ".", "synsets", "(", "ambiguous_word", ")", ")", "els...
31.153846
20.230769
def hexdump(src, length=8, colorize=False): """ Produce a string hexdump of src, for debug output. Input: bytestring; output: text string """ if not src: return str(src) if type(src) is not bytes: raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type...
[ "def", "hexdump", "(", "src", ",", "length", "=", "8", ",", "colorize", "=", "False", ")", ":", "if", "not", "src", ":", "return", "str", "(", "src", ")", "if", "type", "(", "src", ")", "is", "not", "bytes", ":", "raise", "yubico_exception", ".", ...
38.178571
16.714286