text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def CreateNetworkConnectivityNHDPlus(in_drainage_line, out_connectivity_file, file_geodatabase=None): """ Creates Network Connectivity input CSV file for RAPID based on the NHDPlus drainage lines with COMID, FROMNODE, TONODE, and ...
[ "def", "CreateNetworkConnectivityNHDPlus", "(", "in_drainage_line", ",", "out_connectivity_file", ",", "file_geodatabase", "=", "None", ")", ":", "ogr_drainage_line_shapefile_lyr", ",", "ogr_drainage_line_shapefile", "=", "open_shapefile", "(", "in_drainage_line", ",", "file_...
39.95283
22.122642
def _evaluate_oob_savings(self, X, y, cost_mat): """Private function used to calculate the OOB Savings of each estimator.""" estimators_weight = [] for estimator, samples, features in zip(self.estimators_, self.estimators_samples_, self.estimators_...
[ "def", "_evaluate_oob_savings", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ")", ":", "estimators_weight", "=", "[", "]", "for", "estimator", ",", "samples", ",", "features", "in", "zip", "(", "self", ".", "estimators_", ",", "self", ".", "estimato...
48.583333
25.208333
def list_(saltenv='base', test=None): ''' List currently configured reactors CLI Example: .. code-block:: bash salt-run reactor.list ''' sevent = salt.utils.event.get_event( 'master', __opts__['sock_dir'], __opts__['transport'], opts=__o...
[ "def", "list_", "(", "saltenv", "=", "'base'", ",", "test", "=", "None", ")", ":", "sevent", "=", "salt", ".", "utils", ".", "event", ".", "get_event", "(", "'master'", ",", "__opts__", "[", "'sock_dir'", "]", ",", "__opts__", "[", "'transport'", "]", ...
25.583333
23.166667
def _delete_membership(self, pipeline=None): """Removes the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).remove(self.id)
[ "def", "_delete_membership", "(", "self", ",", "pipeline", "=", "None", ")", ":", "Set", "(", "self", ".", "_key", "[", "'all'", "]", ",", "pipeline", "=", "pipeline", ")", ".", "remove", "(", "self", ".", "id", ")" ]
42
9.8
def int_to_base(n, base): """ :type n: int :type base: int :rtype: str """ is_negative = False if n == 0: return '0' elif n < 0: is_negative = True n *= -1 digit = string.digits + string.ascii_uppercase res = '' while n > 0: res += ...
[ "def", "int_to_base", "(", "n", ",", "base", ")", ":", "is_negative", "=", "False", "if", "n", "==", "0", ":", "return", "'0'", "elif", "n", "<", "0", ":", "is_negative", "=", "True", "n", "*=", "-", "1", "digit", "=", "string", ".", "digits", "+...
20
17.809524
def get_next_token(string): ''' "eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str returns a tuple of (ex...
[ "def", "get_next_token", "(", "string", ")", ":", "STOP_CHARS", "=", "\"_ {}^ \\n ,()=\"", "UNARY_CHARS", "=", "\"^_\"", "# ^ and _ are valid leaf expressions--just ones that should be handled on their own", "if", "string", "[", "0", "]", "in", "STOP_CHARS", ":", "return", ...
36.090909
24.363636
def arrays(self): """Return an iterator over (name, value) pairs for arrays only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=1...
[ "def", "arrays", "(", "self", ")", ":", "for", "key", "in", "sorted", "(", "listdir", "(", "self", ".", "_store", ",", "self", ".", "_path", ")", ")", ":", "path", "=", "self", ".", "_key_prefix", "+", "key", "if", "contains_array", "(", "self", "....
39.791667
16.125
def infer(self, rows, headers=1, confidence=0.75): """https://github.com/frictionlessdata/tableschema-py#schema """ # Get headers if isinstance(headers, int): headers_row = headers while True: headers_row -= 1 headers = rows.pop(0)...
[ "def", "infer", "(", "self", ",", "rows", ",", "headers", "=", "1", ",", "confidence", "=", "0.75", ")", ":", "# Get headers", "if", "isinstance", "(", "headers", ",", "int", ")", ":", "headers_row", "=", "headers", "while", "True", ":", "headers_row", ...
35.530612
11.959184
def create_media_asset(access_token, name, options="0"): '''Create Media Service Asset. Args: access_token (str): A valid Azure authentication token. name (str): Media Service Asset Name. options (str): Media Service Options. Returns: HTTP response. JSON body. ''' p...
[ "def", "create_media_asset", "(", "access_token", ",", "name", ",", "options", "=", "\"0\"", ")", ":", "path", "=", "'/Assets'", "endpoint", "=", "''", ".", "join", "(", "[", "ams_rest_endpoint", ",", "path", "]", ")", "body", "=", "'{\"Name\": \"'", "+", ...
33.533333
20.866667
def extend(self, item): """Extend the list with another list. Each member of the list must be a string.""" if not isinstance(item, list): raise TypeError( 'You can only extend lists with lists. ' 'You supplied \"%s\"' % type(item)) for entry in...
[ "def", "extend", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "list", ")", ":", "raise", "TypeError", "(", "'You can only extend lists with lists. '", "'You supplied \\\"%s\\\"'", "%", "type", "(", "item", ")", ")", "for", ...
42.076923
9.538462
def merge_options_and_config(cls, config, options, args): """ Override in subclass if required. """ if args: config.set(CONFIG_SECTION_NAME, 'input_files', ','.join(args)) elif config.has_option(CONFIG_SECTION_NAME, 'input_files'): for i in config.get(CONF...
[ "def", "merge_options_and_config", "(", "cls", ",", "config", ",", "options", ",", "args", ")", ":", "if", "args", ":", "config", ".", "set", "(", "CONFIG_SECTION_NAME", ",", "'input_files'", ",", "','", ".", "join", "(", "args", ")", ")", "elif", "confi...
48.789474
19.631579
def verify_refresh(self, request): """ Verify if the request to refresh the token is valid. If valid it returns the userid which can be used to create an updated identity with ``remember_identity``. Otherwise it raises an exception based on InvalidTokenError. :param requ...
[ "def", "verify_refresh", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "allow_refresh", ":", "raise", "InvalidTokenError", "(", "'Token refresh is disabled'", ")", "token", "=", "self", ".", "get_jwt", "(", "request", ")", "if", "token", "...
39.196078
18.882353
def serialize_html_fragment(el, skip_outer=False): """ Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag """ assert not isinstance(el, basestring), ( "You should pass in an element, not a...
[ "def", "serialize_html_fragment", "(", "el", ",", "skip_outer", "=", "False", ")", ":", "assert", "not", "isinstance", "(", "el", ",", "basestring", ")", ",", "(", "\"You should pass in an element, not a string like %r\"", "%", "el", ")", "html", "=", "etree", "...
37
13.705882
def to_ranges(lst): """ Convert a list of numbers to a list of ranges:: >>> numbers = [1,2,3,5,6] >>> list(to_ranges(numbers)) [(1, 3), (5, 6)] """ for a, b in itertools.groupby(enumerate(lst), lambda t: t[1] - t[0]): b = list(b) yield b[0][1], b[-1][1]
[ "def", "to_ranges", "(", "lst", ")", ":", "for", "a", ",", "b", "in", "itertools", ".", "groupby", "(", "enumerate", "(", "lst", ")", ",", "lambda", "t", ":", "t", "[", "1", "]", "-", "t", "[", "0", "]", ")", ":", "b", "=", "list", "(", "b"...
24
17.833333
def corr_cluster(trace_list, thresh=0.9): """ Group traces based on correlations above threshold with the stack. Will run twice, once with a lower threshold to remove large outliers that would negatively affect the stack, then again with your threshold. :type trace_list: list :param trace_list...
[ "def", "corr_cluster", "(", "trace_list", ",", "thresh", "=", "0.9", ")", ":", "stack", "=", "stacking", ".", "linstack", "(", "[", "Stream", "(", "tr", ")", "for", "tr", "in", "trace_list", "]", ")", "[", "0", "]", "output", "=", "np", ".", "array...
37.369565
21.804348
def write_workbook(filename, table_list, column_width=None): """ Write an Excel workbook from a list of tables. Parameters ---------- filename : str Name of the Excel file to write. table_list : list of ``(str, DataFrame)`` tuples Tables to be saved as individual sheets in the E...
[ "def", "write_workbook", "(", "filename", ",", "table_list", ",", "column_width", "=", "None", ")", ":", "# Modify default header format", "# Pandas' default header format is bold text with thin borders. Here we", "# use bold text only, without borders.", "# The header style structure ...
38.328947
18.460526
def get_active(slug=DEFAULT_TERMS_SLUG): """Finds the latest of a particular terms and conditions""" active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active...
[ "def", "get_active", "(", "slug", "=", "DEFAULT_TERMS_SLUG", ")", ":", "active_terms", "=", "cache", ".", "get", "(", "'tandc.active_terms_'", "+", "slug", ")", "if", "active_terms", "is", "None", ":", "try", ":", "active_terms", "=", "TermsAndConditions", "."...
46
21.5625
def do_init(self, fs_settings, global_quota): fs_settings = deepcopy(fs_settings) # because we store some of the info, we need a deep copy ''' If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice ''' for sender_s...
[ "def", "do_init", "(", "self", ",", "fs_settings", ",", "global_quota", ")", ":", "fs_settings", "=", "deepcopy", "(", "fs_settings", ")", "# because we store some of the info, we need a deep copy", "for", "sender_spec", "in", "fs_settings", ".", "sender_specs", ":", ...
53.631579
24.368421
def _write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """ if gpio is not None: self.gpio = gpio self.i2c.write_list(self.GPIO, self.gpio)
[ "def", "_write_gpio", "(", "self", ",", "gpio", "=", "None", ")", ":", "if", "gpio", "is", "not", "None", ":", "self", ".", "gpio", "=", "gpio", "self", ".", "i2c", ".", "write_list", "(", "self", ".", "GPIO", ",", "self", ".", "gpio", ")" ]
40.857143
8.714286
def to_dict(self): """Render a MessageElement as python dict :return: Python dict representation :rtype: dict """ obj_dict = super(Cell, self).to_dict() child_dict = { 'type': self.__class__.__name__, 'header_flag': self.header_flag, '...
[ "def", "to_dict", "(", "self", ")", ":", "obj_dict", "=", "super", "(", "Cell", ",", "self", ")", ".", "to_dict", "(", ")", "child_dict", "=", "{", "'type'", ":", "self", ".", "__class__", ".", "__name__", ",", "'header_flag'", ":", "self", ".", "hea...
30.1875
11.5625
def load_parameters(self, path): """Load parameters from a file with the specified format. Args: path : path or file object """ nn.load_parameters(path) for v in self.get_modules(): if not isinstance(v, tuple): continue prefix,...
[ "def", "load_parameters", "(", "self", ",", "path", ")", ":", "nn", ".", "load_parameters", "(", "path", ")", "for", "v", "in", "self", ".", "get_modules", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "tuple", ")", ":", "continue", "prefi...
36.708333
11.625
def _wait_for_response(self): """ Wait until the user accepted or rejected the request """ while not self.server.response_code: time.sleep(2) time.sleep(5) self.server.shutdown()
[ "def", "_wait_for_response", "(", "self", ")", ":", "while", "not", "self", ".", "server", ".", "response_code", ":", "time", ".", "sleep", "(", "2", ")", "time", ".", "sleep", "(", "5", ")", "self", ".", "server", ".", "shutdown", "(", ")" ]
23.25
11.5
def createGroup(self, title, tags, description="", snippet="", phone="", access="org", sortField="title", sortOrder="asc", isViewOnly=False, isInvitationOnly=Fa...
[ "def", "createGroup", "(", "self", ",", "title", ",", "tags", ",", "description", "=", "\"\"", ",", "snippet", "=", "\"\"", ",", "phone", "=", "\"\"", ",", "access", "=", "\"org\"", ",", "sortField", "=", "\"title\"", ",", "sortOrder", "=", "\"asc\"", ...
46.952941
24.835294
def merge_equivalent_compounds(model): """Merge equivalent compounds in various compartments. Tries to detect and merge compound entries that represent the same compound in different compartments. The entries are only merged if all properties are equivalent. Compound entries must have an ID with a suff...
[ "def", "merge_equivalent_compounds", "(", "model", ")", ":", "def", "dicts_are_compatible", "(", "d1", ",", "d2", ")", ":", "return", "all", "(", "key", "not", "in", "d1", "or", "key", "not", "in", "d2", "or", "d1", "[", "key", "]", "==", "d2", "[", ...
38.408
18.256
def commit(self, txnCount, stateRoot, txnRoot, ppTime) -> List: """ :param txnCount: The number of requests to commit (The actual requests are picked up from the uncommitted list from the ledger) :param stateRoot: The state trie root after the txns are committed :param txnRoot: T...
[ "def", "commit", "(", "self", ",", "txnCount", ",", "stateRoot", ",", "txnRoot", ",", "ppTime", ")", "->", "List", ":", "return", "self", ".", "_commit", "(", "self", ".", "ledger", ",", "self", ".", "state", ",", "txnCount", ",", "stateRoot", ",", "...
46.75
24.916667
def walk_upgrade_domain(self, service_name, deployment_name, upgrade_domain): ''' Specifies the next upgrade domain to be walked during manual in-place upgrade or configuration change. service_name: Name of the hosted service. deployment_n...
[ "def", "walk_upgrade_domain", "(", "self", ",", "service_name", ",", "deployment_name", ",", "upgrade_domain", ")", ":", "_validate_not_none", "(", "'service_name'", ",", "service_name", ")", "_validate_not_none", "(", "'deployment_name'", ",", "deployment_name", ")", ...
44.458333
19.458333
def quit(self): """ Exit the program due to user's choices. """ self.script.LOG.warn("Abort due to user choice!") sys.exit(self.QUIT_RC)
[ "def", "quit", "(", "self", ")", ":", "self", ".", "script", ".", "LOG", ".", "warn", "(", "\"Abort due to user choice!\"", ")", "sys", ".", "exit", "(", "self", ".", "QUIT_RC", ")" ]
32.8
10.4
def xml_records(filename): """ If the second return value is not None, then it is an Exception encountered during parsing. The first return value will be the XML string. @type filename str @rtype: generator of (etree.Element or str), (None or Exception) """ with Evtx(filename) as e...
[ "def", "xml_records", "(", "filename", ")", ":", "with", "Evtx", "(", "filename", ")", "as", "evtx", ":", "for", "xml", ",", "record", "in", "evtx_file_xml_view", "(", "evtx", ".", "get_file_header", "(", ")", ")", ":", "try", ":", "yield", "to_lxml", ...
34.266667
15.6
def transformer_tall_pretrain_lm(): """Hparams for transformer on LM pretraining (with 64k vocab).""" hparams = transformer_tall() hparams.learning_rate_constant = 2e-4 hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay") hparams.optimizer = "adam_w" hparams.optimizer_adam_beta1 = 0.9 hpar...
[ "def", "transformer_tall_pretrain_lm", "(", ")", ":", "hparams", "=", "transformer_tall", "(", ")", "hparams", ".", "learning_rate_constant", "=", "2e-4", "hparams", ".", "learning_rate_schedule", "=", "(", "\"linear_warmup*constant*cosdecay\"", ")", "hparams", ".", "...
46.6
12.4
def continue_to_install(self): """Continue to install ? """ if (self.count_uni > 0 or self.count_upg > 0 or "--download-only" in self.flag or "--rebuild" in self.flag): if self.master_packages and self.msg.answer() in ["y", "Y"]: installs, upgraded = s...
[ "def", "continue_to_install", "(", "self", ")", ":", "if", "(", "self", ".", "count_uni", ">", "0", "or", "self", ".", "count_upg", ">", "0", "or", "\"--download-only\"", "in", "self", ".", "flag", "or", "\"--rebuild\"", "in", "self", ".", "flag", ")", ...
46.5
11.583333
def _bind_channels(self, events, channels): """ Binds given channel events to callbacks. :param events: str or list :param channels: dict of channel_name: callback_method() pairs :return: """ for channel_name in channels: if channel_name in self.channe...
[ "def", "_bind_channels", "(", "self", ",", "events", ",", "channels", ")", ":", "for", "channel_name", "in", "channels", ":", "if", "channel_name", "in", "self", ".", "channels", ":", "channel", "=", "self", ".", "pusher", ".", "subscribe", "(", "channel_n...
40.8
11.6
def populate(self, installed_bots=None): """ Load bots. Import each bot module. It is thread-safe and idempotent, but not re-entrant. """ if self.ready: return # populate() might be called by two threads in parallel on servers # that create th...
[ "def", "populate", "(", "self", ",", "installed_bots", "=", "None", ")", ":", "if", "self", ".", "ready", ":", "return", "# populate() might be called by two threads in parallel on servers", "# that create threads before initializing the WSGI callable.", "with", "self", ".", ...
35.5
17.5
def is_token_annotation_tier(self, tier): """ returns True, iff all events in the given tier annotate exactly one token. """ for i, event in enumerate(tier.iter('event')): if self.indexdelta(event.attrib['end'], event.attrib['start']) != 1: return Fals...
[ "def", "is_token_annotation_tier", "(", "self", ",", "tier", ")", ":", "for", "i", ",", "event", "in", "enumerate", "(", "tier", ".", "iter", "(", "'event'", ")", ")", ":", "if", "self", ".", "indexdelta", "(", "event", ".", "attrib", "[", "'end'", "...
37
16.555556
def _run_proxy_processes(proxies): ''' Iterate over a list of proxy names and restart any that aren't running ''' ret = [] for proxy in proxies: result = {} if not __salt__['salt_proxy.is_running'](proxy)['result']: __salt__['salt_proxy.configure_proxy'](proxy, st...
[ "def", "_run_proxy_processes", "(", "proxies", ")", ":", "ret", "=", "[", "]", "for", "proxy", "in", "proxies", ":", "result", "=", "{", "}", "if", "not", "__salt__", "[", "'salt_proxy.is_running'", "]", "(", "proxy", ")", "[", "'result'", "]", ":", "_...
30.888889
20.444444
def _coerce_type(self, field_type, value): """Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text. """ if value is None: ...
[ "def", "_coerce_type", "(", "self", ",", "field_type", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "field_type", "==", "'string'", ":", "return", "str", "(", "value", ")", "elif", "field_type", "==", "'text'", ":", ...
30.775
13.675
def cached(self, dependency): """ Get a cached instance of dependency. :param dependency: The ``Dependency`` to retrievie value for :type dependency: ``Dependency`` :return: The cached value """ if dependency.threadlocal: return getattr(self._...
[ "def", "cached", "(", "self", ",", "dependency", ")", ":", "if", "dependency", ".", "threadlocal", ":", "return", "getattr", "(", "self", ".", "_local", ",", "dependency", ".", "name", ",", "None", ")", "elif", "dependency", ".", "singleton", ":", "retur...
35.75
11.083333
def _clean_slice(key, length): """ Validates and normalizes a cell range slice. >>> _clean_slice(slice(None, None), 10) (0, 10) >>> _clean_slice(slice(-10, 10), 10) (0, 10) >>> _clean_slice(slice(-11, 11), 10) (0, 10) >>> _clean_slice(slice('x', 'y'), 10) Traceback (most recent ...
[ "def", "_clean_slice", "(", "key", ",", "length", ")", ":", "if", "key", ".", "step", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'Cell slice with step is not supported.'", ")", "start", ",", "stop", "=", "key", ".", "start", ",", "key", ...
32.325581
16.511628
def refreshUi( self ): """ Load the plugin information to the interface. """ dataSet = self.dataSet() if not dataSet: return False # lookup widgets based on the data set information for widget in self.findChildren(QWidget): pro...
[ "def", "refreshUi", "(", "self", ")", ":", "dataSet", "=", "self", ".", "dataSet", "(", ")", "if", "not", "dataSet", ":", "return", "False", "# lookup widgets based on the data set information", "for", "widget", "in", "self", ".", "findChildren", "(", "QWidget",...
31.952381
13.761905
def _parse_title(dom, details): """ Parse title/name of the book. Args: dom (obj): HTMLElement containing whole HTML page. details (obj): HTMLElement containing slice of the page with details. Returns: str: Book's title. Raises: AssertionError: If title not found. ...
[ "def", "_parse_title", "(", "dom", ",", "details", ")", ":", "title", "=", "details", ".", "find", "(", "\"h1\"", ")", "# if the header is missing, try to parse title from the <title> tag", "if", "not", "title", ":", "title", "=", "dom", ".", "find", "(", "\"tit...
25.416667
21.333333
def rollback(self, revision=None, annotations=None): """ Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the curr...
[ "def", "rollback", "(", "self", ",", "revision", "=", "None", ",", "annotations", "=", "None", ")", ":", "rollback", "=", "DeploymentRollback", "(", ")", "rollback", ".", "name", "=", "self", ".", "name", "rollback_config", "=", "RollbackConfig", "(", ")",...
34
20.693878
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" ...
[ "def", "getOperationNameForId", "(", "i", ":", "int", ")", ":", "assert", "isinstance", "(", "i", ",", "(", "int", ")", ")", ",", "\"This method expects an integer argument\"", "for", "key", "in", "operations", ":", "if", "int", "(", "operations", "[", "key"...
39.625
10.625
def parse(source, world, jointgroup=None, density=1000, color=None): '''Load and parse a source file. Parameters ---------- source : file A file-like object that contains text information describing bodies and joints to add to the world. world : :class:`pagoda.physics.World` ...
[ "def", "parse", "(", "source", ",", "world", ",", "jointgroup", "=", "None", ",", "density", "=", "1000", ",", "color", "=", "None", ")", ":", "visitor", "=", "Visitor", "(", "world", ",", "jointgroup", ",", "density", ",", "color", ")", "visitor", "...
43.130435
19.913043
def vrp(V, c, m, q, Q): """solve_vrp -- solve the vehicle routing problem. - start with assignment model (depot has a special status) - add cuts until all components of the graph are connected Parameters: - V: set/list of nodes in the graph - c[i,j]: cost for traversing edge (i,j) ...
[ "def", "vrp", "(", "V", ",", "c", ",", "m", ",", "q", ",", "Q", ")", ":", "model", "=", "Model", "(", "\"vrp\"", ")", "vrp_conshdlr", "=", "VRPconshdlr", "(", ")", "x", "=", "{", "}", "for", "i", "in", "V", ":", "for", "j", "in", "V", ":", ...
36.121212
22.515152
def _catch(f, exception_type): """Decorator to drop into the debugger if a function throws an exception.""" if not (inspect.isclass(exception_type) and issubclass(exception_type, Exception)): exception_type = Exception @functools.wraps(f) def wrap(*args, **kw): try: return f(*args, **kw...
[ "def", "_catch", "(", "f", ",", "exception_type", ")", ":", "if", "not", "(", "inspect", ".", "isclass", "(", "exception_type", ")", "and", "issubclass", "(", "exception_type", ",", "Exception", ")", ")", ":", "exception_type", "=", "Exception", "@", "func...
34.384615
17.153846
def firmware_download_input_protocol_type_sftp_protocol_sftp_file(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input") ...
[ "def", "firmware_download_input_protocol_type_sftp_protocol_sftp_file", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "firmware_download", "=", "ET", ".", "Element", "(", "\"firmware_download\"", ")", ...
43.933333
14.533333
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs): """ Format csv rows parsed to Dict or Array """ result = None c_headers = [] if c_headers is None else c_headers r_headers = [] if r_headers is None else r_headers rows = [] if rows is None else rows result_f...
[ "def", "csv_format", "(", "csv_data", ",", "c_headers", "=", "None", ",", "r_headers", "=", "None", ",", "rows", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "None", "c_headers", "=", "[", "]", "if", "c_headers", "is", "None", "else...
27.032258
21.354839
def get_ip_from_name(ifname, v6=False): """Backward compatibility: indirectly calls get_ips Deprecated.""" iface = IFACES.dev_from_name(ifname) return get_ips(v6=v6).get(iface, [""])[0]
[ "def", "get_ip_from_name", "(", "ifname", ",", "v6", "=", "False", ")", ":", "iface", "=", "IFACES", ".", "dev_from_name", "(", "ifname", ")", "return", "get_ips", "(", "v6", "=", "v6", ")", ".", "get", "(", "iface", ",", "[", "\"\"", "]", ")", "["...
39.4
1.2
def download(self): """Download this object.""" return self._client.download_object( self._instance, self._bucket, self.name)
[ "def", "download", "(", "self", ")", ":", "return", "self", ".", "_client", ".", "download_object", "(", "self", ".", "_instance", ",", "self", ".", "_bucket", ",", "self", ".", "name", ")" ]
37.5
9.25
def _conn(commit=False): ''' Return an postgres cursor ''' defaults = {'host': 'localhost', 'user': 'salt', 'password': 'salt', 'dbname': 'salt', 'port': 5432} conn_kwargs = {} for key, value in defaults.items(): conn_kwarg...
[ "def", "_conn", "(", "commit", "=", "False", ")", ":", "defaults", "=", "{", "'host'", ":", "'localhost'", ",", "'user'", ":", "'salt'", ",", "'password'", ":", "'salt'", ",", "'dbname'", ":", "'salt'", ",", "'port'", ":", "5432", "}", "conn_kwargs", "...
27.764706
19.941176
def connect_host(kwargs=None, call=None): ''' Connect the specified host system in this VMware environment CLI Example: .. code-block:: bash salt-cloud -f connect_host my-vmware-config host="myHostSystemName" ''' if call != 'function': raise SaltCloudSystemExit( 'T...
[ "def", "connect_host", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The connect_host function must be called with '", "'-f or --function.'", ")", "host_name", "=", "kwar...
29.604167
23.8125
def value(self, key, type_=None): """Get the value of a setting. If `type` is not provided, the key must be for a known setting, present in `self.default_settings`. Conversely if `type` IS provided, the key must be for an unknown setting. """ if type_ is None: ...
[ "def", "value", "(", "self", ",", "key", ",", "type_", "=", "None", ")", ":", "if", "type_", "is", "None", ":", "default", "=", "self", ".", "_default_value", "(", "key", ")", "val", "=", "self", ".", "_value", "(", "key", ",", "default", ")", "i...
36.578947
14.210526
def read_int16(self, little_endian=True): """ Read 2 byte as a signed integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """ if little_endian: endian = "<" ...
[ "def", "read_int16", "(", "self", ",", "little_endian", "=", "True", ")", ":", "if", "little_endian", ":", "endian", "=", "\"<\"", "else", ":", "endian", "=", "\">\"", "return", "self", ".", "unpack", "(", "'%sh'", "%", "endian", ",", "2", ")" ]
25.533333
19.933333
def get_cell_format(column_dict, key=None): """ Return the cell format for the given column :param column_dict: The column datas collected during inspection :param key: The exportation key """ format = column_dict.get('format') prop = column_dict.get('__col__') if format is None and pr...
[ "def", "get_cell_format", "(", "column_dict", ",", "key", "=", "None", ")", ":", "format", "=", "column_dict", ".", "get", "(", "'format'", ")", "prop", "=", "column_dict", ".", "get", "(", "'__col__'", ")", "if", "format", "is", "None", "and", "prop", ...
34.625
13.375
def print_validation_errors(result): """ Accepts validation result object and prints report (in red)""" click.echo(red('\nValidation failed:')) click.echo(red('-' * 40)) messages = result.get_messages() for property in messages.keys(): click.echo(yellow(property + ':')) for error in ...
[ "def", "print_validation_errors", "(", "result", ")", ":", "click", ".", "echo", "(", "red", "(", "'\\nValidation failed:'", ")", ")", "click", ".", "echo", "(", "red", "(", "'-'", "*", "40", ")", ")", "messages", "=", "result", ".", "get_messages", "(",...
39.5
4.7
def zero_state(qubits: Union[int, Qubits]) -> State: """Return the all-zero state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = 1 return State(ket, qubits)
[ "def", "zero_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "...
37.333333
8.5
def send_dictation_result(self, result, sentences=None, app_uuid=None): ''' Send the result of a dictation session :param result: Result of the session :type result: DictationResult :param sentences: list of sentences, each of which is a list of words and punctuation :pa...
[ "def", "send_dictation_result", "(", "self", ",", "result", ",", "sentences", "=", "None", ",", "app_uuid", "=", "None", ")", ":", "assert", "self", ".", "_session_id", "!=", "VoiceService", ".", "SESSION_ID_INVALID", "assert", "isinstance", "(", "result", ","...
43.731707
25.390244
def load_plugins(group='metrics.plugin.10'): """Load and installed metrics plugins. """ # on using entrypoints: # http://stackoverflow.com/questions/774824/explain-python-entry-points file_processors = [] build_processors = [] for ep in pkg_resources.iter_entry_points(group, name=None): ...
[ "def", "load_plugins", "(", "group", "=", "'metrics.plugin.10'", ")", ":", "# on using entrypoints:", "# http://stackoverflow.com/questions/774824/explain-python-entry-points", "file_processors", "=", "[", "]", "build_processors", "=", "[", "]", "for", "ep", "in", "pkg_reso...
44.466667
12.533333
def build_model(input_shape): """Create a compiled Keras model. Parameters ---------- input_shape : tuple, len=3 Shape of each image sample. Returns ------- model : keras.Model Constructed model. """ model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),...
[ "def", "build_model", "(", "input_shape", ")", ":", "model", "=", "Sequential", "(", ")", "model", ".", "add", "(", "Conv2D", "(", "32", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "activation", "=", "'relu'", ",", "input_shape", "=", "inp...
27.15625
16.40625
def _parse_file(self, sar_parts): """ Parses splitted file to get proper information from split parts. :param sar_parts: Array of SAR file parts :return: ``Dictionary``-style info (but still non-parsed) \ from SAR file, split into sections we want to check ...
[ "def", "_parse_file", "(", "self", ",", "sar_parts", ")", ":", "usage", "=", "{", "}", "output", "=", "{", "}", "# If sar_parts is a list", "if", "type", "(", "sar_parts", ")", "is", "list", ":", "restart_pattern", "=", "re", ".", "compile", "(", "PATTER...
38.561404
19.684211
async def executemany(self, command: str, args, *, timeout: float=None): """Execute an SQL *command* for each sequence of arguments in *args*. Pool performs this operation using one of its connections. Other than that, it behaves identically to :meth:`Connection.executemany() <connecti...
[ "async", "def", "executemany", "(", "self", ",", "command", ":", "str", ",", "args", ",", "*", ",", "timeout", ":", "float", "=", "None", ")", ":", "async", "with", "self", ".", "acquire", "(", ")", "as", "con", ":", "return", "await", "con", ".", ...
45.363636
20.818182
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None): """ Order to buy amount of bitcoins for specified price. """ data = {'amount': amount, 'price': price} if limit_price is not None: data['limit_price'] = limit_price url = self...
[ "def", "buy_limit_order", "(", "self", ",", "amount", ",", "price", ",", "base", "=", "\"btc\"", ",", "quote", "=", "\"usd\"", ",", "limit_price", "=", "None", ")", ":", "data", "=", "{", "'amount'", ":", "amount", ",", "'price'", ":", "price", "}", ...
46.555556
14.111111
def get(self, q, limit=None): """ Performs a search against the predict endpoint :param q: query to be searched for [STRING] :return: { score: [0|1] } """ uri = '{}/predict?q={}'.format(self.client.remote, q) self.logger.debug(uri) body = self.client.get...
[ "def", "get", "(", "self", ",", "q", ",", "limit", "=", "None", ")", ":", "uri", "=", "'{}/predict?q={}'", ".", "format", "(", "self", ".", "client", ".", "remote", ",", "q", ")", "self", ".", "logger", ".", "debug", "(", "uri", ")", "body", "=",...
28.583333
14.25
def activate_next(self, _previous=False): """ Activate next value. """ current = self.get_current_value() options = sorted(self.values.keys()) # Get current index. try: index = options.index(current) except ValueError: index = 0 ...
[ "def", "activate_next", "(", "self", ",", "_previous", "=", "False", ")", ":", "current", "=", "self", ".", "get_current_value", "(", ")", "options", "=", "sorted", "(", "self", ".", "values", ".", "keys", "(", ")", ")", "# Get current index.", "try", ":...
24.727273
14.454545
def _get_ns(self, reply): '''_get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap. ''' def get_prefix(...
[ "def", "_get_ns", "(", "self", ",", "reply", ")", ":", "def", "get_prefix", "(", "url", ")", ":", "if", "url", "in", "special_prefixes", ":", "return", "special_prefixes", "[", "url", "]", "for", "i", "in", "self", ".", "namespaces", ":", "if", "url", ...
26.5
19.605263
def build(self, lv2_uri): """ Returns a new :class:`.Lv2Effect` by the valid lv2_uri :param string lv2_uri: :return Lv2Effect: Effect created """ try: plugin = self._plugins[lv2_uri] except KeyError: raise Lv2EffectBuilderError( ...
[ "def", "build", "(", "self", ",", "lv2_uri", ")", ":", "try", ":", "plugin", "=", "self", ".", "_plugins", "[", "lv2_uri", "]", "except", "KeyError", ":", "raise", "Lv2EffectBuilderError", "(", "\"Lv2EffectBuilder not contains metadata information about the plugin '{}...
38.125
21.375
def _gen_find_command(coll, spec, projection, skip, limit, batch_size, options, read_concern=DEFAULT_READ_CONCERN, collation=None): """Generate a find command document.""" cmd = SON([('find', coll)]) if '$query' in spec: cmd.update([(_MODIFIERS[key], val) ...
[ "def", "_gen_find_command", "(", "coll", ",", "spec", ",", "projection", ",", "skip", ",", "limit", ",", "batch_size", ",", "options", ",", "read_concern", "=", "DEFAULT_READ_CONCERN", ",", "collation", "=", "None", ")", ":", "cmd", "=", "SON", "(", "[", ...
31.514286
15.771429
def DeserializeFromDB(buffer): """ Deserialize full object. Args: buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from. Returns: AccountState: """ m = StreamManager.GetStream(buffer) reader = BinaryReader(m) ...
[ "def", "DeserializeFromDB", "(", "buffer", ")", ":", "m", "=", "StreamManager", ".", "GetStream", "(", "buffer", ")", "reader", "=", "BinaryReader", "(", "m", ")", "account", "=", "AccountState", "(", ")", "account", ".", "Deserialize", "(", "reader", ")",...
23.888889
18.777778
def append(self, P, closed=False, itemsize=None, **kwargs): """ Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices posit...
[ "def", "append", "(", "self", ",", "P", ",", "closed", "=", "False", ",", "itemsize", "=", "None", ",", "*", "*", "kwargs", ")", ":", "itemsize", "=", "itemsize", "or", "len", "(", "P", ")", "itemcount", "=", "len", "(", "P", ")", "/", "itemsize"...
32.435294
17.870588
def delete(self, **kwds): """ Endpoint: /action/<id>/delete.json Deletes this action. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.action.delete(self, **kwds) self._delete_fields() return result
[ "def", "delete", "(", "self", ",", "*", "*", "kwds", ")", ":", "result", "=", "self", ".", "_client", ".", "action", ".", "delete", "(", "self", ",", "*", "*", "kwds", ")", "self", ".", "_delete_fields", "(", ")", "return", "result" ]
27
11.181818
def del_host_comment(self, comment_id): """Delete a host comment Format of the line that triggers function call:: DEL_HOST_COMMENT;<comment_id> :param comment_id: comment id to delete :type comment_id: int :return: None """ for item in self.daemon.hosts:...
[ "def", "del_host_comment", "(", "self", ",", "comment_id", ")", ":", "for", "item", "in", "self", ".", "daemon", ".", "hosts", ":", "if", "comment_id", "in", "item", ".", "comments", ":", "item", ".", "del_comment", "(", "comment_id", ")", "self", ".", ...
36.526316
15.526316
def _finish_task_processing(self, queue, task, success): """ After a task is executed, this method is called and ensures that the task gets properly removed from the ACTIVE queue and, in case of an error, retried or marked as failed. """ log = self.log.bind(queue=queue, t...
[ "def", "_finish_task_processing", "(", "self", ",", "queue", ",", "task", ",", "success", ")", ":", "log", "=", "self", ".", "log", ".", "bind", "(", "queue", "=", "queue", ",", "task_id", "=", "task", ".", "id", ")", "def", "_mark_done", "(", ")", ...
37.851485
19.039604
def move(self, queue_item, status): """Move a request/response pair to another status. Args: queue_item (:class:`nyawc.QueueItem`): The queue item to move status (str): The new status of the queue item. """ items = self.__get_var("items_" + queue_item.status) ...
[ "def", "move", "(", "self", ",", "queue_item", ",", "status", ")", ":", "items", "=", "self", ".", "__get_var", "(", "\"items_\"", "+", "queue_item", ".", "status", ")", "del", "items", "[", "queue_item", ".", "get_hash", "(", ")", "]", "self", ".", ...
27.5
20.8125
def check_permission(permission, brain_or_object): """Check whether the security context allows the given permission on the given brain or object. N.B.: This includes also acquired permissions :param permission: Permission name :brain_or_object: Catalog brain or object :returns: True if the...
[ "def", "check_permission", "(", "permission", ",", "brain_or_object", ")", ":", "sm", "=", "get_security_manager", "(", ")", "obj", "=", "api", ".", "get_object", "(", "brain_or_object", ")", "return", "sm", ".", "checkPermission", "(", "permission", ",", "obj...
35.692308
10.846154
def _convert_xml_to_retention_policy(xml, retention_policy): ''' <Enabled>true|false</Enabled> <Days>number-of-days</Days> ''' # Enabled retention_policy.enabled = _bool(xml.find('Enabled').text) # Days days_element = xml.find('Days') if days_element is not None: retention_p...
[ "def", "_convert_xml_to_retention_policy", "(", "xml", ",", "retention_policy", ")", ":", "# Enabled", "retention_policy", ".", "enabled", "=", "_bool", "(", "xml", ".", "find", "(", "'Enabled'", ")", ".", "text", ")", "# Days", "days_element", "=", "xml", "."...
28.666667
20.666667
def as_region_controller(self): """Convert to a `RegionController` object. `node_type` must be `NodeType.REGION_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`. """ if self.node_type not in [ NodeType.REGION_CONTROLLER, NodeType.REGION_AND_RA...
[ "def", "as_region_controller", "(", "self", ")", ":", "if", "self", ".", "node_type", "not", "in", "[", "NodeType", ".", "REGION_CONTROLLER", ",", "NodeType", ".", "REGION_AND_RACK_CONTROLLER", "]", ":", "raise", "ValueError", "(", "'Cannot convert to `RegionControl...
40.307692
12.384615
def make_subquery_heading(self): """ Create a new heading with removed attribute sql_expressions. Used by subqueries, which resolve the sql_expressions. """ return Heading(dict(v.todict(), sql_expression=None) for v in self.attributes.values())
[ "def", "make_subquery_heading", "(", "self", ")", ":", "return", "Heading", "(", "dict", "(", "v", ".", "todict", "(", ")", ",", "sql_expression", "=", "None", ")", "for", "v", "in", "self", ".", "attributes", ".", "values", "(", ")", ")" ]
46.5
18.833333
def add(event, reactors, saltenv='base', test=None): ''' Add a new reactor CLI Example: .. code-block:: bash salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls' ''' if isinstance(reactors, string_types): reactors = [reactors] sevent = salt....
[ "def", "add", "(", "event", ",", "reactors", ",", "saltenv", "=", "'base'", ",", "test", "=", "None", ")", ":", "if", "isinstance", "(", "reactors", ",", "string_types", ")", ":", "reactors", "=", "[", "reactors", "]", "sevent", "=", "salt", ".", "ut...
28.793103
22.862069
def date(self, field=None, val=None): """ Like datetime, but truncated to be a date only """ return self.datetime(field=field, val=val).date()
[ "def", "date", "(", "self", ",", "field", "=", "None", ",", "val", "=", "None", ")", ":", "return", "self", ".", "datetime", "(", "field", "=", "field", ",", "val", "=", "val", ")", ".", "date", "(", ")" ]
34
6.8
def encrypt(self, recipient_id, message): logger.debug("encrypt(recipientid=%s, message=%s)" % (recipient_id, message)) """ :param recipient_id: :type recipient_id: str :param data: :type data: bytes :return: :rtype: """ cipher = self._get_...
[ "def", "encrypt", "(", "self", ",", "recipient_id", ",", "message", ")", ":", "logger", ".", "debug", "(", "\"encrypt(recipientid=%s, message=%s)\"", "%", "(", "recipient_id", ",", "message", ")", ")", "cipher", "=", "self", ".", "_get_session_cipher", "(", "r...
34.166667
16.5
def addSlide(self, slide): """ Adds a new slide to the widget. :param slide | <XWalkthroughSlide> :return <QtGui.QGraphicsView> """ # create the scene scene = XWalkthroughScene(self) scene.setReferenceWidget(self.parent...
[ "def", "addSlide", "(", "self", ",", "slide", ")", ":", "# create the scene\r", "scene", "=", "XWalkthroughScene", "(", "self", ")", "scene", ".", "setReferenceWidget", "(", "self", ".", "parent", "(", ")", ")", "scene", ".", "load", "(", "slide", ")", "...
34.548387
14.290323
def get_dos(self, partial_dos=False, npts_mu=10000, T=None): """ Return a Dos object interpolating bands Args: partial_dos: if True, projections will be interpolated as well and partial doses will be return. Projections must be available ...
[ "def", "get_dos", "(", "self", ",", "partial_dos", "=", "False", ",", "npts_mu", "=", "10000", ",", "T", "=", "None", ")", ":", "spin", "=", "self", ".", "data", ".", "spin", "if", "isinstance", "(", "self", ".", "data", ".", "spin", ",", "int", ...
38.583333
24.5
def vector_str(p, decimal_places=2, print_zero=True): '''Pretty-print the vector values.''' style = '{0:.' + str(decimal_places) + 'f}' return '[{0}]'.format(", ".join([' ' if not print_zero and a == 0 else style.format(a) for a in p]))
[ "def", "vector_str", "(", "p", ",", "decimal_places", "=", "2", ",", "print_zero", "=", "True", ")", ":", "style", "=", "'{0:.'", "+", "str", "(", "decimal_places", ")", "+", "'f}'", "return", "'[{0}]'", ".", "format", "(", "\", \"", ".", "join", "(", ...
61.25
21.25
def to_bytes(self, obj, encoding=None): """ Converts the given resource to bytes representation in the encoding specified by :param:`encoding` and returns it. """ if encoding is None: encoding = self.encoding text = self.to_string(obj) return bytes_(te...
[ "def", "to_bytes", "(", "self", ",", "obj", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "self", ".", "encoding", "text", "=", "self", ".", "to_string", "(", "obj", ")", "return", "bytes_", "(", "text"...
37.666667
9.222222
def _beyond_unit_bound(self, loglstar): """Check whether we should update our bound beyond the initial unit cube.""" if self.logl_first_update is None: # If we haven't already updated our bounds, check if we satisfy # the provided criteria for establishing the first boun...
[ "def", "_beyond_unit_bound", "(", "self", ",", "loglstar", ")", ":", "if", "self", ".", "logl_first_update", "is", "None", ":", "# If we haven't already updated our bounds, check if we satisfy", "# the provided criteria for establishing the first bounding update.", "check", "=", ...
47.555556
18.5
def _set_nd_global(self, v, load=False): """ Setter method for nd_global, mapped from YANG variable /ipv6/ipv6_global_cmds/nd_global (container) If this variable is read-only (config: false) in the source YANG file, then _set_nd_global is considered as a private method. Backends looking to populate ...
[ "def", "_set_nd_global", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
80.045455
37.272727
def collect_instance(self, nick, host, port, unix_socket, auth): """Collect metrics from a single Redis instance :param str nick: nickname of redis instance :param str host: redis host :param int port: redis port :param str unix_socket: unix socket, if applicable :param str auth: authentication password ...
[ "def", "collect_instance", "(", "self", ",", "nick", ",", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", ":", "# Connect to redis and get the info", "info", "=", "self", ".", "_get_info", "(", "host", ",", "port", ",", "unix_socket", ",", "auth",...
39.103896
19.155844
def success_response(self, message=None): """ Returns a 'render redirect' to the result of the `get_success_url` method. """ return self.render(self.request, redirect_url=self.get_success_url(), obj=self.object, ...
[ "def", "success_response", "(", "self", ",", "message", "=", "None", ")", ":", "return", "self", ".", "render", "(", "self", ".", "request", ",", "redirect_url", "=", "self", ".", "get_success_url", "(", ")", ",", "obj", "=", "self", ".", "object", ","...
35.818182
9.636364
def as_graph(self) -> Digraph: # pragma: no cover """Returns a :class:`graphviz.Digraph` representation of this directed match graph.""" if Digraph is None: raise ImportError('The graphviz package is required to draw the graph.') graph = Digraph() subgraphs = [Digraph(graph...
[ "def", "as_graph", "(", "self", ")", "->", "Digraph", ":", "# pragma: no cover", "if", "Digraph", "is", "None", ":", "raise", "ImportError", "(", "'The graphviz package is required to draw the graph.'", ")", "graph", "=", "Digraph", "(", ")", "subgraphs", "=", "["...
48.285714
16.142857
def meta(cls): """Return a dictionary containing meta-information about the given resource.""" if getattr(cls, '__from_class__', None) is not None: cls = cls.__from_class__ attribute_info = {} for name, value in cls.__table__.columns.items(): attribute_inf...
[ "def", "meta", "(", "cls", ")", ":", "if", "getattr", "(", "cls", ",", "'__from_class__'", ",", "None", ")", "is", "not", "None", ":", "cls", "=", "cls", ".", "__from_class__", "attribute_info", "=", "{", "}", "for", "name", ",", "value", "in", "cls"...
39.1
14.3
def is_legal_priority(self, packet: DataPacket): """ Check if the given packet has high enough priority for the stored values for the packet's universe. :param packet: the packet to check :return: returns True if the priority is good. Otherwise False """ # check if the pa...
[ "def", "is_legal_priority", "(", "self", ",", "packet", ":", "DataPacket", ")", ":", "# check if the packet's priority is high enough to get processed", "if", "packet", ".", "universe", "not", "in", "self", ".", "callbacks", ".", "keys", "(", ")", "or", "packet", ...
49.25
21.416667
def get_code(self, code, card_id=None, check_consume=True): """ 查询 code 信息 """ card_data = { 'code': code } if card_id: card_data['card_id'] = card_id if not check_consume: card_data['check_consume'] = check_consume retu...
[ "def", "get_code", "(", "self", ",", "code", ",", "card_id", "=", "None", ",", "check_consume", "=", "True", ")", ":", "card_data", "=", "{", "'code'", ":", "code", "}", "if", "card_id", ":", "card_data", "[", "'card_id'", "]", "=", "card_id", "if", ...
25.733333
15.066667
def _get_full_block(grouped_dicoms): """ Generate a full datablock containing all timepoints """ # For each slice / mosaic create a data volume block data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms))) ...
[ "def", "_get_full_block", "(", "grouped_dicoms", ")", ":", "# For each slice / mosaic create a data volume block", "data_blocks", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "grouped_dicoms", ")", ")", ":", "logger", ".", "info", "("...
48.777778
21.592593
def get_var(self, name, user=None): """ Retrieve a global or user variable :param name: The name of the variable to retrieve :type name: str :param user: If retrieving a user variable, the user identifier :type user: str or None :rtype: str :raises Us...
[ "def", "get_var", "(", "self", ",", "name", ",", "user", "=", "None", ")", ":", "# Retrieve a user variable", "if", "user", "is", "not", "None", ":", "if", "user", "not", "in", "self", ".", "_users", ":", "raise", "UserNotDefinedError", "return", "self", ...
30.538462
17.307692
def _is_modified(self, filepath): """ Returns True if the file has been modified since last seen. Will return False if the file has not been seen before. """ if self._is_new(filepath): return False mtime = self._get_modified_time(filepath) return self....
[ "def", "_is_modified", "(", "self", ",", "filepath", ")", ":", "if", "self", ".", "_is_new", "(", "filepath", ")", ":", "return", "False", "mtime", "=", "self", ".", "_get_modified_time", "(", "filepath", ")", "return", "self", ".", "_watched_files", "[", ...
38.222222
11.111111
def print_header_content(nlh): """Return header content (doesn't actually print like the C library does). https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L34 Positional arguments: nlh -- nlmsghdr class instance. """ answer = 'type={0} length={1} flags=<{2}> sequence-nr={3} pid...
[ "def", "print_header_content", "(", "nlh", ")", ":", "answer", "=", "'type={0} length={1} flags=<{2}> sequence-nr={3} pid={4}'", ".", "format", "(", "nl_nlmsgtype2str", "(", "nlh", ".", "nlmsg_type", ",", "bytearray", "(", ")", ",", "32", ")", ".", "decode", "(", ...
35.3125
22.75
def make_obj_iter(text_iter, query): """ convert text cdx stream to CDXObject/IDXObject. """ if query.secondary_index_only: cls = IDXObject else: cls = CDXObject return (cls(line) for line in text_iter)
[ "def", "make_obj_iter", "(", "text_iter", ",", "query", ")", ":", "if", "query", ".", "secondary_index_only", ":", "cls", "=", "IDXObject", "else", ":", "cls", "=", "CDXObject", "return", "(", "cls", "(", "line", ")", "for", "line", "in", "text_iter", ")...
23.4
13
def iodp_samples_srm(df, spec_file='specimens.txt',samp_file="samples.txt",site_file="sites.txt",dir_path='.', input_dir_path='',comp_depth_key="",lat="",lon=""): """ Convert IODP samples data generated from the SRM measurements file into datamodel 3.0 MagIC samples file. Default is to over...
[ "def", "iodp_samples_srm", "(", "df", ",", "spec_file", "=", "'specimens.txt'", ",", "samp_file", "=", "\"samples.txt\"", ",", "site_file", "=", "\"sites.txt\"", ",", "dir_path", "=", "'.'", ",", "input_dir_path", "=", "''", ",", "comp_depth_key", "=", "\"\"", ...
42.098214
20.008929
def attowiki_distro_path(): """return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? """ attowiki_path = os.path.abspath(__file__) if attowiki_path[-1] != '/': attowiki_path = attowiki_path[:attowiki_path.rfind('/')] else: attowiki_path = atto...
[ "def", "attowiki_distro_path", "(", ")", ":", "attowiki_path", "=", "os", ".", "path", ".", "abspath", "(", "__file__", ")", "if", "attowiki_path", "[", "-", "1", "]", "!=", "'/'", ":", "attowiki_path", "=", "attowiki_path", "[", ":", "attowiki_path", ".",...
34.181818
15.727273
def find_spec(modpath, path=None): """Find a spec for the given module. :type modpath: list or tuple :param modpath: split module's name (i.e name of a module or package split on '.'), with leading empty strings for explicit relative import :type path: list or None :param path: o...
[ "def", "find_spec", "(", "modpath", ",", "path", "=", "None", ")", ":", "_path", "=", "path", "or", "sys", ".", "path", "# Need a copy for not mutating the argument.", "modpath", "=", "modpath", "[", ":", "]", "submodule_path", "=", "None", "module_parts", "="...
29.666667
21.794872
def createReader(clazz, readername): """Static method to create a reader from a reader clazz. @param clazz: the reader class name @param readername: the reader name """ if not clazz in ReaderFactory.factories: ReaderFactory.factories[clazz] = get_class(clazz).Fa...
[ "def", "createReader", "(", "clazz", ",", "readername", ")", ":", "if", "not", "clazz", "in", "ReaderFactory", ".", "factories", ":", "ReaderFactory", ".", "factories", "[", "clazz", "]", "=", "get_class", "(", "clazz", ")", ".", "Factory", "(", ")", "re...
42.666667
13