text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _check_gle_response(result): """Return getlasterror response as a dict, or raise OperationFailure.""" # Did getlasterror itself fail? _check_command_response(result) if result.get("wtimeout", False): # MongoDB versions before 1.8.0 return the error message in an "errmsg" # field. If...
[ "def", "_check_gle_response", "(", "result", ")", ":", "# Did getlasterror itself fail?", "_check_command_response", "(", "result", ")", "if", "result", ".", "get", "(", "\"wtimeout\"", ",", "False", ")", ":", "# MongoDB versions before 1.8.0 return the error message in an ...
35.818182
17.333333
def add_parameters(self, traj): """Adds parameters and config from the `.ini` file to the trajectory""" if self.config_file: parameters = self._collect_section('parameters') for name in parameters: value = parameters[name] if not isinstance(value, ...
[ "def", "add_parameters", "(", "self", ",", "traj", ")", ":", "if", "self", ".", "config_file", ":", "parameters", "=", "self", ".", "_collect_section", "(", "'parameters'", ")", "for", "name", "in", "parameters", ":", "value", "=", "parameters", "[", "name...
43.8
7.466667
def mandelagol_and_line_fit_magseries( times, mags, errs, fitparams, priorbounds, fixedparams, trueparams=None, burninpercent=0.3, plotcorner=False, timeoffset=0, samplesavpath=False, n_walkers=50, n_mcmc_steps=400, eps=1e-4...
[ "def", "mandelagol_and_line_fit_magseries", "(", "times", ",", "mags", ",", "errs", ",", "fitparams", ",", "priorbounds", ",", "fixedparams", ",", "trueparams", "=", "None", ",", "burninpercent", "=", "0.3", ",", "plotcorner", "=", "False", ",", "timeoffset", ...
37.613248
22.963675
async def delete(query): """Perform DELETE query asynchronously. Returns number of rows deleted. """ assert isinstance(query, peewee.Delete),\ ("Error, trying to run delete coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cu...
[ "async", "def", "delete", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Delete", ")", ",", "(", "\"Error, trying to run delete coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", ...
30.833333
14.166667
def first(self, values, axis=0): """return values at first occurance of its associated key Parameters ---------- values : array_like, [keys, ...] values to pick the first value of per group axis : int, optional alternative reduction axis for values ...
[ "def", "first", "(", "self", ",", "values", ",", "axis", "=", "0", ")", ":", "values", "=", "np", ".", "asarray", "(", "values", ")", "return", "self", ".", "unique", ",", "np", ".", "take", "(", "values", ",", "self", ".", "index", ".", "sorter"...
31.947368
15.631579
def main(): """Parses the command line parameters and decide if dbus methods should be called or not. If there is already a guake instance running it will be used and a True value will be returned, otherwise, false will be returned. """ # Force to xterm-256 colors for compatibility with some old...
[ "def", "main", "(", ")", ":", "# Force to xterm-256 colors for compatibility with some old command line programs", "os", ".", "environ", "[", "\"TERM\"", "]", "=", "\"xterm-256color\"", "# Force use X11 backend underwayland", "os", ".", "environ", "[", "\"GDK_BACKEND\"", "]",...
27.5625
20.486111
def get_version(version=None): """Returns a PEP 386-compliant version number from VERSION. :param version: A tuple that represent a version. :type version: tuple :returns: a PEP 386-compliant version number. :rtype: str """ if version is None: version_list = inasafe_version.split(...
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version_list", "=", "inasafe_version", ".", "split", "(", "'.'", ")", "version", "=", "tuple", "(", "version_list", "+", "[", "inasafe_release_status", "]", "...
32
18.625
def node_contents_str(tag): """ Return the contents of a tag, including it's children, as a string. Does not include the root/parent of the tag. """ if not tag: return None tag_string = '' for child_tag in tag.children: if isinstance(child_tag, Comment): # Beautif...
[ "def", "node_contents_str", "(", "tag", ")", ":", "if", "not", "tag", ":", "return", "None", "tag_string", "=", "''", "for", "child_tag", "in", "tag", ".", "children", ":", "if", "isinstance", "(", "child_tag", ",", "Comment", ")", ":", "# BeautifulSoup do...
36
15.466667
def get_user_submissions(self, task): """ Get all the user's submissions for a given task """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to get his submissions") cursor = self._database.submissions.find({"username": self._user_manager.se...
[ "def", "get_user_submissions", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "_user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "Exception", "(", "\"A user must be logged in to get his submissions\"", ")", "cursor", "=", "self", "."...
56.777778
26.666667
def predict_in_sample(self, exogenous=None, start=None, end=None, dynamic=False): """Generate in-sample predictions from the fit ARIMA model. This can be useful when wanting to visualize the fit, and qualitatively inspect the efficacy of the model, or when wanting to co...
[ "def", "predict_in_sample", "(", "self", ",", "exogenous", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "dynamic", "=", "False", ")", ":", "check_is_fitted", "(", "self", ",", "'arima_res_'", ")", "# if we fit with exog, make sure one ...
45.095238
23.785714
def beautify_date(inasafe_time, feature, parent): """Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable. """ _ = feature, parent # NOQA datet...
[ "def", "beautify_date", "(", "inasafe_time", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "datetime_object", "=", "parse", "(", "inasafe_time", ")", "date", "=", "datetime_object", ".", "strftime", "(", "'%Y-%m-%d'", ...
33.75
15.166667
def get_object(self, cat, **kwargs): """ This method is used for retrieving objects from facebook. "cat", the category, must be passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the cat is "multiple", only pass the...
[ "def", "get_object", "(", "self", ",", "cat", ",", "*", "*", "kwargs", ")", ":", "if", "'id'", "not", "in", "kwargs", ".", "keys", "(", ")", ":", "kwargs", "[", "'id'", "]", "=", "''", "res", "=", "request", ".", "get_object_cat1", "(", "self", "...
56
23.8
def subject(sid, subjects_path=None, meta_data=None, default_alignment='MSMAll'): ''' subject(sid) yields a HCP Subject object for the subject with the given subject id; sid may be a path to a subject or a subject id, in which case the subject paths are searched for it. subject(None, path) yields a no...
[ "def", "subject", "(", "sid", ",", "subjects_path", "=", "None", ",", "meta_data", "=", "None", ",", "default_alignment", "=", "'MSMAll'", ")", ":", "if", "subjects_path", "is", "None", ":", "if", "os", ".", "path", ".", "isdir", "(", "str", "(", "sid"...
49.025641
27.076923
def ldap_server_host_basedn(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host, ...
[ "def", "ldap_server_host_basedn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ldap_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ldap-server\"", ",", "xmlns", "=", "\"urn:bro...
42.384615
13.384615
def urlencode(txt): """Url encode a path.""" if isinstance(txt, unicode): txt = txt.encode('utf-8') return urllib.quote_plus(txt)
[ "def", "urlencode", "(", "txt", ")", ":", "if", "isinstance", "(", "txt", ",", "unicode", ")", ":", "txt", "=", "txt", ".", "encode", "(", "'utf-8'", ")", "return", "urllib", ".", "quote_plus", "(", "txt", ")" ]
29
8.6
def random(self, n: Optional[int] = None) -> Union[List[float], float]: """ Similar to :py:func:`randint` """ return self._generate_randoms(self._request_randoms, max_n=self.config.MAX_NUMBER_OF_FLOATS, n=n)
[ "def", "random", "(", "self", ",", "n", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Union", "[", "List", "[", "float", "]", ",", "float", "]", ":", "return", "self", ".", "_generate_randoms", "(", "self", ".", "_request_randoms", ",", ...
64.5
23.25
def detectFirefoxOSPhone(self): """Return detection of a Firefox OS phone Detects a phone (probably) running the Firefox OS. """ if self.detectIos() \ or self.detectAndroid() \ or self.detectSailfish(): return False if UAgentInfo.engineFirefo...
[ "def", "detectFirefoxOSPhone", "(", "self", ")", ":", "if", "self", ".", "detectIos", "(", ")", "or", "self", ".", "detectAndroid", "(", ")", "or", "self", ".", "detectSailfish", "(", ")", ":", "return", "False", "if", "UAgentInfo", ".", "engineFirefox", ...
28.6
16.466667
def blake2b(data=b'', **kwargs): ''' byte-like -> bytes ''' b2 = hashlib.blake2b(**kwargs) b2.update(data) return b2.digest()
[ "def", "blake2b", "(", "data", "=", "b''", ",", "*", "*", "kwargs", ")", ":", "b2", "=", "hashlib", ".", "blake2b", "(", "*", "*", "kwargs", ")", "b2", ".", "update", "(", "data", ")", "return", "b2", ".", "digest", "(", ")" ]
20.428571
19.571429
def thermostat_state(self): """The state of the thermostat programming :return: A thermostat state object of the current setting """ current_state = self.thermostat_info.active_state state = self.get_thermostat_state_by_id(current_state) if not state: self._l...
[ "def", "thermostat_state", "(", "self", ")", ":", "current_state", "=", "self", ".", "thermostat_info", ".", "active_state", "state", "=", "self", ".", "get_thermostat_state_by_id", "(", "current_state", ")", "if", "not", "state", ":", "self", ".", "_logger", ...
39.363636
17.818182
def htmlNodeDumpOutput(self, doc, cur, encoding): """Dump an HTML node, recursive behaviour,children are printed too, and formatting returns/spaces are added. """ if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o ...
[ "def", "htmlNodeDumpOutput", "(", "self", ",", "doc", ",", "cur", ",", "encoding", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "cur", "is", "None", ":", "cur__o", "=", "None",...
47.875
8.625
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) if not HAVE_ST: raise RuntimeError( "Trying to run fermipy analysis, but don't have ST") if args.load_baseline: gta = GTAnalysis.create(args.roi_baseline, ...
[ "def", "run_analysis", "(", "self", ",", "argv", ")", ":", "args", "=", "self", ".", "_parser", ".", "parse_args", "(", "argv", ")", "if", "not", "HAVE_ST", ":", "raise", "RuntimeError", "(", "\"Trying to run fermipy analysis, but don't have ST\"", ")", "if", ...
42.539683
19.825397
def getContactItems(self, person): """ Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person} """ notes = list(person.store.query(Notes, Notes.person == person)) ...
[ "def", "getContactItems", "(", "self", ",", "person", ")", ":", "notes", "=", "list", "(", "person", ".", "store", ".", "query", "(", "Notes", ",", "Notes", ".", "person", "==", "person", ")", ")", "if", "not", "notes", ":", "return", "[", "Notes", ...
36.076923
15.461538
def float_str(f, min_digits=2, max_digits=6): """ Returns a string representing a float, where the number of significant digits is min_digits unless it takes more digits to hit a non-zero digit (and the number is 0 < x < 1). We stop looking for a non-zero digit after max_digits. """ if f >= ...
[ "def", "float_str", "(", "f", ",", "min_digits", "=", "2", ",", "max_digits", "=", "6", ")", ":", "if", "f", ">=", "1", "or", "f", "<=", "0", ":", "return", "str", "(", "round_float", "(", "f", ",", "min_digits", ")", ")", "start_str", "=", "str"...
41.043478
14.434783
def _str_desc(self, reader): """String containing information about the current GO DAG.""" data_version = reader.data_version if data_version is not None: data_version = data_version.replace("releases/", "") desc = "{OBO}: fmt({FMT}) rel({REL}) {N:,} GO Terms".format( ...
[ "def", "_str_desc", "(", "self", ",", "reader", ")", ":", "data_version", "=", "reader", ".", "data_version", "if", "data_version", "is", "not", "None", ":", "data_version", "=", "data_version", ".", "replace", "(", "\"releases/\"", ",", "\"\"", ")", "desc",...
51.090909
17.909091
def parse_torrent_properties(table_datas): """ Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties. :param list lxml.HtmlElement table_datas: table_datas to...
[ "def", "parse_torrent_properties", "(", "table_datas", ")", ":", "output", "=", "{", "'category'", ":", "table_datas", "[", "0", "]", ".", "text", ",", "'subcategory'", ":", "None", ",", "'quality'", ":", "None", ",", "'language'", ":", "None", "}", "for",...
50.047619
21.952381
def create(self, attributes=None, **kwargs): """ Creates a webhook with given attributes. """ return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
[ "def", "create", "(", "self", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "WebhooksProxy", ",", "self", ")", ".", "create", "(", "resource_id", "=", "None", ",", "attributes", "=", "attributes", ")" ]
33.833333
16.833333
def _do_document(self, node): '''_do_document(self, node) -> None Process a document node. documentOrder holds whether the document element has been encountered such that PIs/comments can be written as specified.''' self.documentOrder = _LesserElement for child in node.c...
[ "def", "_do_document", "(", "self", ",", "node", ")", ":", "self", ".", "documentOrder", "=", "_LesserElement", "for", "child", "in", "node", ".", "childNodes", ":", "if", "child", ".", "nodeType", "==", "Node", ".", "ELEMENT_NODE", ":", "self", ".", "do...
44.85
16.95
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
[ "def", "planetRadiusType", "(", "radius", ")", ":", "if", "radius", "is", "np", ".", "nan", ":", "return", "None", "for", "radiusLimit", ",", "radiusType", "in", "planetAssumptions", "[", "'radiusType'", "]", ":", "if", "radius", "<", "radiusLimit", ":", "...
27.363636
19.454545
def transform(foci, mat): """ Convert coordinates from one space to another using provided transformation matrix. """ t = linalg.pinv(mat) foci = np.hstack((foci, np.ones((foci.shape[0], 1)))) return np.dot(foci, t)[:, 0:3]
[ "def", "transform", "(", "foci", ",", "mat", ")", ":", "t", "=", "linalg", ".", "pinv", "(", "mat", ")", "foci", "=", "np", ".", "hstack", "(", "(", "foci", ",", "np", ".", "ones", "(", "(", "foci", ".", "shape", "[", "0", "]", ",", "1", ")...
39.666667
9
def _sample_item(self, **kwargs): """Sample an item from the pool according to the instrumental distribution """ loc = np.random.choice(self._n_items, p = self._inst_pmf) weight = (1/self._n_items)/self._inst_pmf[loc] return loc, weight, {}
[ "def", "_sample_item", "(", "self", ",", "*", "*", "kwargs", ")", ":", "loc", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "_n_items", ",", "p", "=", "self", ".", "_inst_pmf", ")", "weight", "=", "(", "1", "/", "self", ".", "_n_item...
40.285714
10.857143
def process_request(self, req, resp): """ Process the request before routing it. We always enforce the use of SSL. """ if goldman.config.TLS_REQUIRED and req.protocol != 'https': abort(TLSRequired)
[ "def", "process_request", "(", "self", ",", "req", ",", "resp", ")", ":", "if", "goldman", ".", "config", ".", "TLS_REQUIRED", "and", "req", ".", "protocol", "!=", "'https'", ":", "abort", "(", "TLSRequired", ")" ]
29.5
15.125
def construct_event_logger(event_record_callback): ''' Callback receives a stream of event_records ''' check.callable_param(event_record_callback, 'event_record_callback') return construct_single_handler_logger( 'event-logger', DEBUG, StructuredLoggerHandler( lam...
[ "def", "construct_event_logger", "(", "event_record_callback", ")", ":", "check", ".", "callable_param", "(", "event_record_callback", ",", "'event_record_callback'", ")", "return", "construct_single_handler_logger", "(", "'event-logger'", ",", "DEBUG", ",", "StructuredLogg...
31.230769
25.384615
def _build_basic_network(self, word_outputs): """ Creates the basic network architecture, transforming word embeddings to intermediate outputs """ if self.word_dropout > 0.0: lstm_outputs = kl.Dropout(self.word_dropout)(word_outputs) else: lstm_out...
[ "def", "_build_basic_network", "(", "self", ",", "word_outputs", ")", ":", "if", "self", ".", "word_dropout", ">", "0.0", ":", "lstm_outputs", "=", "kl", ".", "Dropout", "(", "self", ".", "word_dropout", ")", "(", "word_outputs", ")", "else", ":", "lstm_ou...
46.904762
12.904762
def update_by_external_id(self, api_objects): """ Update (PUT) one or more API objects by external_id. :param api_objects: """ if not isinstance(api_objects, collections.Iterable): api_objects = [api_objects] return CRUDRequest(self).put(api_objects, update_m...
[ "def", "update_by_external_id", "(", "self", ",", "api_objects", ")", ":", "if", "not", "isinstance", "(", "api_objects", ",", "collections", ".", "Iterable", ")", ":", "api_objects", "=", "[", "api_objects", "]", "return", "CRUDRequest", "(", "self", ")", "...
36.666667
15.111111
def install(): """Manual install main script. """ # check installed package print("Compare to '%s' ..." % _DST) need_install_flag = check_need_install() if not need_install_flag: print("\tpackage is up-to-date, no need to install.") return print("Difference been found, start ...
[ "def", "install", "(", ")", ":", "# check installed package", "print", "(", "\"Compare to '%s' ...\"", "%", "_DST", ")", "need_install_flag", "=", "check_need_install", "(", ")", "if", "not", "need_install_flag", ":", "print", "(", "\"\\tpackage is up-to-date, no need t...
31.909091
15.393939
def add_feature(feature, package=None, source=None, limit_access=False, enable_parent=False, image=None, restart=False): ''' Install a feature using DISM Args: feature (str): The feature to install ...
[ "def", "add_feature", "(", "feature", ",", "package", "=", "None", ",", "source", "=", "None", ",", "limit_access", "=", "False", ",", "enable_parent", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "cmd", "=", "[", ...
35.346154
21.692308
def xstep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`. """ self.YU[:] = self.Y - self.U b = self.DSf + self.rho*sl.rfftn(self.YU, None, self.cri.axisN) if self.cri.Cd == 1: self.Xf[:] = sl.solvedbi_sm(self.Df, self.mu + self.r...
[ "def", "xstep", "(", "self", ")", ":", "self", ".", "YU", "[", ":", "]", "=", "self", ".", "Y", "-", "self", ".", "U", "b", "=", "self", ".", "DSf", "+", "self", ".", "rho", "*", "sl", ".", "rfftn", "(", "self", ".", "YU", ",", "None", ",...
38.535714
21.535714
def run(command): ''' Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings ''' if isinstance(command, list): command = ' '.join(command) out = subprocess.run(command, shell=True, stdout=subprocess.PIP...
[ "def", "run", "(", "command", ")", ":", "if", "isinstance", "(", "command", ",", "list", ")", ":", "command", "=", "' '", ".", "join", "(", "command", ")", "out", "=", "subprocess", ".", "run", "(", "command", ",", "shell", "=", "True", ",", "stdou...
40.9
21.1
def get_program_path(): """Returns the path in which pyspread is installed""" src_folder = os.path.dirname(__file__) program_path = os.sep.join(src_folder.split(os.sep)[:-1]) + os.sep return program_path
[ "def", "get_program_path", "(", ")", ":", "src_folder", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "program_path", "=", "os", ".", "sep", ".", "join", "(", "src_folder", ".", "split", "(", "os", ".", "sep", ")", "[", ":", "-", "1...
30.714286
20.857143
def today(self): """ Access the today :returns: twilio.rest.api.v2010.account.usage.record.today.TodayList :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayList """ if self._today is None: self._today = TodayList(self._version, account_sid=self._...
[ "def", "today", "(", "self", ")", ":", "if", "self", ".", "_today", "is", "None", ":", "self", ".", "_today", "=", "TodayList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")", "ret...
36.4
22.8
def _create_properties(self): """Populate a frame with a list of all editable properties""" self._frame = f = ttk.Labelframe(self._sframe.innerframe, text=_('Widget properties')) f.grid(sticky='nswe') label_tpl = "{0}:" row = 0 co...
[ "def", "_create_properties", "(", "self", ")", ":", "self", ".", "_frame", "=", "f", "=", "ttk", ".", "Labelframe", "(", "self", ".", "_sframe", ".", "innerframe", ",", "text", "=", "_", "(", "'Widget properties'", ")", ")", "f", ".", "grid", "(", "s...
45.526316
20.815789
def gen_txn_path(self, txn): """Return path to state as 'str' type or None""" txn_type = get_type(txn) if txn_type not in self.state_update_handlers: logger.error('Cannot generate id for txn of type {}'.format(txn_type)) return None if txn_type == NYM: ...
[ "def", "gen_txn_path", "(", "self", ",", "txn", ")", ":", "txn_type", "=", "get_type", "(", "txn", ")", "if", "txn_type", "not", "in", "self", ".", "state_update_handlers", ":", "logger", ".", "error", "(", "'Cannot generate id for txn of type {}'", ".", "form...
44.103448
19.551724
def _update_retryable( self, criteria, document, upsert=False, check_keys=True, multi=False, manipulate=False, write_concern=None, op_id=None, ordered=True, bypass_doc_val=False, collation=None, array_filters=None, session=None): """Internal update / r...
[ "def", "_update_retryable", "(", "self", ",", "criteria", ",", "document", ",", "upsert", "=", "False", ",", "check_keys", "=", "True", ",", "multi", "=", "False", ",", "manipulate", "=", "False", ",", "write_concern", "=", "None", ",", "op_id", "=", "No...
50.842105
20.052632
def _write_config(self, memory): """Write the configuration for this probe to memory.""" memory.seek(0) memory.write(struct.pack("<II", # sim_length self._simulator.length, # input_key ...
[ "def", "_write_config", "(", "self", ",", "memory", ")", ":", "memory", ".", "seek", "(", "0", ")", "memory", ".", "write", "(", "struct", ".", "pack", "(", "\"<II\"", ",", "# sim_length", "self", ".", "_simulator", ".", "length", ",", "# input_key", "...
46.6
9.7
def ratio_value_number_to_time_series_length(self, x): """ As in tsfresh `ratio_value_number_to_time_series_length <https://github.com/blue-yonder/tsfresh/blob/master\ /tsfresh/feature_extraction/feature_calculators.py#L830>`_ Returns a factor which is 1 if all values in the...
[ "def", "ratio_value_number_to_time_series_length", "(", "self", ",", "x", ")", ":", "ratio", "=", "feature_calculators", ".", "ratio_value_number_to_time_series_length", "(", "x", ")", "logging", ".", "debug", "(", "\"ratio value number to time series length by tsfresh calcul...
49.529412
25.764706
def explained_variance(self): """ Proportion of variance that is explained by the first two principal components (which together represent the planar fit). Analogous to R^2 of linear least squares. """ v = N.diagonal(self.covariance_matrix) return v[0:2].s...
[ "def", "explained_variance", "(", "self", ")", ":", "v", "=", "N", ".", "diagonal", "(", "self", ".", "covariance_matrix", ")", "return", "v", "[", "0", ":", "2", "]", ".", "sum", "(", ")", "/", "v", ".", "sum", "(", ")" ]
36
8.444444
def _set_axis_limits(self, axis, view, subplots, ranges): """ Compute extents for current view and apply as axis limits """ # Extents extents = self.get_extents(view, ranges) if not extents or self.overlaid: axis.autoscale_view(scalex=True, scaley=True) ...
[ "def", "_set_axis_limits", "(", "self", ",", "axis", ",", "view", ",", "subplots", ",", "ranges", ")", ":", "# Extents", "extents", "=", "self", ".", "get_extents", "(", "view", ",", "ranges", ")", "if", "not", "extents", "or", "self", ".", "overlaid", ...
42.342105
20.131579
def get_private_room_info(self, room_id, **kwargs): """ Get various information about a specific private group :param room_id: :param kwargs: :return: """ return GetPrivateRoomInfo(settings=self.settings, **kwargs).call( room_id=room_id, *...
[ "def", "get_private_room_info", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "GetPrivateRoomInfo", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "room_id", "=", "room_id", ",",...
27.166667
19
def _get_host_details(self): """Get the system details.""" # Assuming only one system present as part of collection, # as we are dealing with iLO's here. status, headers, system = self._rest_get('/rest/v1/Systems/1') if status < 300: stype = self._get_type(system) ...
[ "def", "_get_host_details", "(", "self", ")", ":", "# Assuming only one system present as part of collection,", "# as we are dealing with iLO's here.", "status", ",", "headers", ",", "system", "=", "self", ".", "_rest_get", "(", "'/rest/v1/Systems/1'", ")", "if", "status", ...
40.733333
16.133333
def inv(z: int) -> int: """$= z^{-1} mod q$, for z != 0""" # Adapted from curve25519_athlon.c in djb's Curve25519. z2 = z * z % q # 2 z9 = pow2(z2, 2) * z % q # 9 z11 = z9 * z2 % q # 11 z2_5_0 = (z11 * z11) % q * z9 % q # 31 == 2^5 - 2^0 z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % q # 2^10 - 2...
[ "def", "inv", "(", "z", ":", "int", ")", "->", "int", ":", "# Adapted from curve25519_athlon.c in djb's Curve25519.", "z2", "=", "z", "*", "z", "%", "q", "# 2", "z9", "=", "pow2", "(", "z2", ",", "2", ")", "*", "z", "%", "q", "# 9", "z11", "=", "z9...
43.466667
11.066667
def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data): """ Run macs2 for chip and input samples avoiding errors due to samples. """ # output file name need to have the caller name config = dd.get_config(data) out_file = os.path.join(out_dir, name + "_peaks_macs2....
[ "def", "run", "(", "name", ",", "chip_bam", ",", "input_bam", ",", "genome_build", ",", "out_dir", ",", "method", ",", "resources", ",", "data", ")", ":", "# output file name need to have the caller name", "config", "=", "dd", ".", "get_config", "(", "data", "...
52.096774
20.032258
def color_string(color, string): """ Colorizes a given string, if coloring is available. """ if not color_available: return string return color + string + colorama.Fore.RESET
[ "def", "color_string", "(", "color", ",", "string", ")", ":", "if", "not", "color_available", ":", "return", "string", "return", "color", "+", "string", "+", "colorama", ".", "Fore", ".", "RESET" ]
24.5
12.75
def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)): """ A feature passthrough layer inspired by yolo9000 and the inverse tiling layer. It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)). This layer has no activation functi...
[ "def", "feature_passthrough", "(", "early_feat", ",", "late_feat", ",", "filters", ",", "name", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ")", ":", "_", ",", "h_early", ",", "w_early", ",", "c_early", "=", "early_feat", ".", "get_shape", "(", "...
52.481481
31.37037
def config_from_file(config_file_path, config_role): """ Create a configuration dictionary from a config file section. This dictionary is what the TruStar class constructor ultimately requires. :param config_file_path: The path to the config file. :param config_role: The sectio...
[ "def", "config_from_file", "(", "config_file_path", ",", "config_role", ")", ":", "# read config file depending on filetype, parse into dictionary", "ext", "=", "os", ".", "path", ".", "splitext", "(", "config_file_path", ")", "[", "-", "1", "]", "if", "ext", "in", ...
44.533333
21.111111
def provideData(self): """ reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read from the device itself. :return: a list of data where each item is a single sample of data converted into real values and stored as a dict. ...
[ "def", "provideData", "(", "self", ")", ":", "samples", "=", "[", "]", "fifoBytesAvailable", "=", "0", "fifoWasReset", "=", "False", "logger", ".", "debug", "(", "\">> provideData target %d samples\"", ",", "self", ".", "samplesPerBatch", ")", "iterations", "=",...
62.915493
30.211268
def fibre_channel_wwns(): ''' Return list of fiber channel HBA WWNs ''' grains = {'fc_wwn': False} if salt.utils.platform.is_linux(): grains['fc_wwn'] = _linux_wwns() elif salt.utils.platform.is_windows(): grains['fc_wwn'] = _windows_wwns() return grains
[ "def", "fibre_channel_wwns", "(", ")", ":", "grains", "=", "{", "'fc_wwn'", ":", "False", "}", "if", "salt", ".", "utils", ".", "platform", ".", "is_linux", "(", ")", ":", "grains", "[", "'fc_wwn'", "]", "=", "_linux_wwns", "(", ")", "elif", "salt", ...
28.9
12.1
def vm_info(name, quiet=False): ''' Return the information on the named VM ''' data = query(quiet=True) return _find_vm(name, data, quiet)
[ "def", "vm_info", "(", "name", ",", "quiet", "=", "False", ")", ":", "data", "=", "query", "(", "quiet", "=", "True", ")", "return", "_find_vm", "(", "name", ",", "data", ",", "quiet", ")" ]
25.5
15.166667
def login(self, username=None, password=None): """ 登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。 """ if username: self.set('username', username) if password: self.set('password', password) response = client.post('/login', params=self.dump()) con...
[ "def", "login", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "username", ":", "self", ".", "set", "(", "'username'", ",", "username", ")", "if", "password", ":", "self", ".", "set", "(", "'password'", ",", ...
35
7.571429
def img2img_transformer2d_n24(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.hidden_size = 1024 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout = 0.2 hparams.num_decoder_layers = 8 hparams.query_shape = (8, 16) hparams.memory_flan...
[ "def", "img2img_transformer2d_n24", "(", ")", ":", "hparams", "=", "img2img_transformer2d_base", "(", ")", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "hidden_size", "=", "1024", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prep...
30.818182
9.090909
def parse_interval_records(interval_record, interval_date, interval, uom, quality_method) -> List[Reading]: """ Convert interval values into tuples with datetime """ interval_delta = timedelta(minutes=interval) return [ Reading( t_start=interval_date + (i *...
[ "def", "parse_interval_records", "(", "interval_record", ",", "interval_date", ",", "interval", ",", "uom", ",", "quality_method", ")", "->", "List", "[", "Reading", "]", ":", "interval_delta", "=", "timedelta", "(", "minutes", "=", "interval", ")", "return", ...
43.888889
18
def runner( engine, configfile, output_vars, interval, pause, mpi, tracker, port, bmi_class ): """ run a BMI compatible model """ # keep track of info # update mpi information or use rank 0 runner = mmi.runner.Runner( ...
[ "def", "runner", "(", "engine", ",", "configfile", ",", "output_vars", ",", "interval", ",", "pause", ",", "mpi", ",", "tracker", ",", "port", ",", "bmi_class", ")", ":", "# keep track of info", "# update mpi information or use rank 0", "runner", "=", "mmi", "."...
19.035714
18.75
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a mask of all values falling between the given percentiles. """ # TODO: Review whether there's a better way of handling small numbers # of columns. data = arrays[0].copy().asty...
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "# TODO: Review whether there's a better way of handling small numbers", "# of columns.", "data", "=", "arrays", "[", "0", "]", ".", "copy", "(", ")", ".", "astype...
35.074074
18.111111
def printed_out(self, name): """ Create a string describing the APIObject and its children """ out = '' out += '|\n' if self._id_variable: subs = '[{}]'.format(self._id_variable) else: subs = '' out += '|---{}{}\n'.format(name, subs...
[ "def", "printed_out", "(", "self", ",", "name", ")", ":", "out", "=", "''", "out", "+=", "'|\\n'", "if", "self", ".", "_id_variable", ":", "subs", "=", "'[{}]'", ".", "format", "(", "self", ".", "_id_variable", ")", "else", ":", "subs", "=", "''", ...
31.875
13.75
def export(self): """ This method deactivates the security context for the calling process and returns an interprocess token which, when passed to :meth:`imprt` in another process, will re-activate the context in the second process. Only a single instantiation of a given context may be ...
[ "def", "export", "(", "self", ")", ":", "if", "not", "(", "self", ".", "flags", "&", "C", ".", "GSS_C_TRANS_FLAG", ")", ":", "raise", "GSSException", "(", "\"Context is not transferable.\"", ")", "if", "not", "self", ".", "_ctx", ":", "raise", "GSSExceptio...
44.157895
23.315789
def get_queue(self, path, n_procs=4, read_ahead=None, cyclic=False, block_size=None, ordered=False): """ Get a queue that allows direct access to the internal buffer. If the dataset to be read is chunked, the block_size should be a multiple of the chunk size to maximise performance. In this case...
[ "def", "get_queue", "(", "self", ",", "path", ",", "n_procs", "=", "4", ",", "read_ahead", "=", "None", ",", "cyclic", "=", "False", ",", "block_size", "=", "None", ",", "ordered", "=", "False", ")", ":", "# Get a block_size length of elements from the dataset...
54.459016
33.016393
def from_seed(cls, seed, encoder=encoding.RawEncoder): """ Generate a PrivateKey using a deterministic construction starting from a caller-provided seed .. warning:: The seed **must** be high-entropy; therefore, its generator **must** be a cryptographic quality r...
[ "def", "from_seed", "(", "cls", ",", "seed", ",", "encoder", "=", "encoding", ".", "RawEncoder", ")", ":", "# decode the seed", "seed", "=", "encoder", ".", "decode", "(", "seed", ")", "# Verify the given seed type and size are correct", "if", "not", "(", "isins...
45.962963
20.037037
def nl2p(s): """Add paragraphs to a text.""" return u"\n".join(u"<p>%s</p>" % p for p in _par_re.split(s))
[ "def", "nl2p", "(", "s", ")", ":", "return", "u\"\\n\"", ".", "join", "(", "u\"<p>%s</p>\"", "%", "p", "for", "p", "in", "_par_re", ".", "split", "(", "s", ")", ")" ]
37.333333
17.666667
def p_expression_srl(self, p): 'expression : expression RSHIFT expression' p[0] = Srl(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_srl", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Srl", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",...
41.75
8.75
def list_cache_subnet_groups(region=None, key=None, keyid=None, profile=None): ''' Return a list of all cache subnet group names Example: .. code-block:: bash salt myminion boto3_elasticache.list_cache_subnet_groups region=us-east-1 ''' return [g['CacheSubnetGroupName'] for g in ...
[ "def", "list_cache_subnet_groups", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "[", "g", "[", "'CacheSubnetGroupName'", "]", "for", "g", "in", "describe_cache_subnet_groups"...
31.666667
30
def GetValue(self): ''' Positionals have no associated options_string, so only the supplied arguments are returned. The order is assumed to be the same as the order of declaration in the client code Returns "argument_value" ''' self.AssertInitialization('Positional') if str(se...
[ "def", "GetValue", "(", "self", ")", ":", "self", ".", "AssertInitialization", "(", "'Positional'", ")", "if", "str", "(", "self", ".", "_widget", ".", "GetValue", "(", ")", ")", "==", "EMPTY", ":", "return", "None", "return", "self", ".", "_widget", "...
28
17.428571
def condense(input_string): """ Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn'...
[ "def", "condense", "(", "input_string", ")", ":", "try", ":", "assert", "isinstance", "(", "input_string", ",", "basestring", ")", "except", "AssertionError", ":", "raise", "TypeError", "removed_leading_whitespace", "=", "re", ".", "sub", "(", "'>\\s+'", ",", ...
32.7
24.6
def extract_pem(pem, private_pem=False): """ <Purpose> Extract only the portion of the pem that includes the header and footer, with any leading and trailing characters removed. The string returned has the following form: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' or '----...
[ "def", "extract_pem", "(", "pem", ",", "private_pem", "=", "False", ")", ":", "if", "private_pem", ":", "pem_header", "=", "'-----BEGIN RSA PRIVATE KEY-----'", "pem_footer", "=", "'-----END RSA PRIVATE KEY-----'", "else", ":", "pem_header", "=", "'-----BEGIN PUBLIC KEY-...
31.905882
27.529412
def gabc(key, value, fmt, meta): # pylint:disable=I0011,W0613 """Handle gabc file inclusion and gabc code block.""" if key == 'Code': [[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612 kvs = {key: value for key, value in kvs} if "gabc" in classes: ...
[ "def", "gabc", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "# pylint:disable=I0011,W0613", "if", "key", "==", "'Code'", ":", "[", "[", "ident", ",", "classes", ",", "kvs", "]", ",", "contents", "]", "=", "value", "# pylint:disable=I0011,...
36.830189
15.037736
def mode(self): """``PIL.Image.mode`` equivalent for this image""" m = '' if self.indexed: m = 'P' elif self.bits_per_component == 1: m = '1' elif self.bits_per_component == 8: if self.colorspace == '/DeviceRGB': m = 'RGB' ...
[ "def", "mode", "(", "self", ")", ":", "m", "=", "''", "if", "self", ".", "indexed", ":", "m", "=", "'P'", "elif", "self", ".", "bits_per_component", "==", "1", ":", "m", "=", "'1'", "elif", "self", ".", "bits_per_component", "==", "8", ":", "if", ...
33.823529
16.294118
def contains_if(self, include_loop=True): """ Check if the node is a IF node Returns: bool: True if the node is a conditional node (IF or IFLOOP) """ if include_loop: return self.type in [NodeType.IF, NodeType.IFLOOP] return self.type == NodeTy...
[ "def", "contains_if", "(", "self", ",", "include_loop", "=", "True", ")", ":", "if", "include_loop", ":", "return", "self", ".", "type", "in", "[", "NodeType", ".", "IF", ",", "NodeType", ".", "IFLOOP", "]", "return", "self", ".", "type", "==", "NodeTy...
35.222222
10.777778
def _rank(sample): """ Assign numeric ranks to all values in the sample. The ranks begin with 1 for the smallest value. When there are groups of tied values, assign a rank equal to the midpoint of unadjusted rankings. E.g.:: >>> rank({3: 1, 5: 4, 9: 1}) {3: 1.0, 5: 3.5, 9: 6.0} ...
[ "def", "_rank", "(", "sample", ")", ":", "rank", "=", "1", "ranks", "=", "{", "}", "for", "k", "in", "sorted", "(", "sample", ".", "keys", "(", ")", ")", ":", "n", "=", "sample", "[", "k", "]", "ranks", "[", "k", "]", "=", "rank", "+", "(",...
21.181818
23.454545
def _get_coords(self, obj): """ Get the coordinates of the 2D aggregate, maintaining the correct sorting order. """ xdim, ydim = obj.dimensions(label=True)[:2] xcoords = obj.dimension_values(xdim, False) ycoords = obj.dimension_values(ydim, False) # Deter...
[ "def", "_get_coords", "(", "self", ",", "obj", ")", ":", "xdim", ",", "ydim", "=", "obj", ".", "dimensions", "(", "label", "=", "True", ")", "[", ":", "2", "]", "xcoords", "=", "obj", ".", "dimension_values", "(", "xdim", ",", "False", ")", "ycoord...
41.060606
14.636364
def _entity_paginator(namespace, workspace, etype, page_size=500, filter_terms=None, sort_direction="asc"): """Pages through the get_entities_query endpoint to get all entities in the workspace without crashing. """ page = 1 all_entities = [] # Make initial reques...
[ "def", "_entity_paginator", "(", "namespace", ",", "workspace", ",", "etype", ",", "page_size", "=", "500", ",", "filter_terms", "=", "None", ",", "sort_direction", "=", "\"asc\"", ")", ":", "page", "=", "1", "all_entities", "=", "[", "]", "# Make initial re...
38.545455
18.909091
def _set_metric_type(self, v, load=False): """ Setter method for metric_type, mapped from YANG variable /routing_system/route_map/content/set/metric_type (container) If this variable is read-only (config: false) in the source YANG file, then _set_metric_type is considered as a private method. Backen...
[ "def", "_set_metric_type", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "ba...
73.375
35.958333
def inner_parser(self) -> BaseParser: """ Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exis...
[ "def", "inner_parser", "(", "self", ")", "->", "BaseParser", ":", "if", "self", ".", "_inner_parser", "is", "not", "None", ":", "return", "self", ".", "_inner_parser", "__index", ",", "response_config", "=", "self", ".", "client", ".", "kv", ".", "get", ...
39.551724
26.37931
def _ParseIndex(self, preread, precompile): """Reads index file and stores entries in TextTable. For optimisation reasons, a second table is created with compiled entries. Args: preread: func, Pre-processing, applied to each field as it is read. precompile: func, Pre-compilation, applied to ...
[ "def", "_ParseIndex", "(", "self", ",", "preread", ",", "precompile", ")", ":", "self", ".", "index", "=", "texttable", ".", "TextTable", "(", ")", "self", ".", "index", ".", "CsvToTable", "(", "self", ".", "_index_handle", ")", "if", "preread", ":", "...
39.16
19.2
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
[ "def", "runCLI", "(", ")", ":", "args", "=", "docopt", "(", "__doc__", ",", "version", "=", "'0.3.0'", ")", "try", ":", "check_arguments", "(", "args", ")", "command_list", "=", "[", "'genconfig'", ",", "'run'", ",", "'generate'", "]", "select", "=", "...
41.105263
20.263158
def decrypt_ecb_cts(self, data): """ Return an iterator that decrypts `data` using the Electronic Codebook with Ciphertext Stealing (ECB-CTS) mode of operation. ECB-CTS mode can only operate on `data` that is greater than 8 bytes in length. Each iteration, except the last, always retur...
[ "def", "decrypt_ecb_cts", "(", "self", ",", "data", ")", ":", "data_len", "=", "len", "(", "data", ")", "if", "data_len", "<=", "8", ":", "raise", "ValueError", "(", "\"data is not greater than 8 bytes in length\"", ")", "S1", ",", "S2", ",", "S3", ",", "S...
33.019231
23.711538
def template_subst(template, subs, delims=('<', '>')): """ Perform substitution of content into tagged string. For substitutions into template input files for external computational packages, no checks for valid syntax are performed. Each key in `subs` corresponds to a delimited substitution tag t...
[ "def", "template_subst", "(", "template", ",", "subs", ",", "delims", "=", "(", "'<'", ",", "'>'", ")", ")", ":", "# Store the template into the working variable", "subst_text", "=", "template", "# Iterate over subs and perform the .replace() calls", "for", "(", "k", ...
36.3
24.366667
def __update_throughput( table_name, table_key, gsi_name, gsi_key, read_units, write_units): """ Update throughput on the GSI :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: st...
[ "def", "__update_throughput", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "read_units", ",", "write_units", ")", ":", "try", ":", "current_ru", "=", "dynamodb", ".", "get_provisioned_gsi_read_units", "(", "table_name", ",", "gsi_name...
32.193548
19.693548
def get_gradebook_column(self, gradebook_column_id): """Gets the ``GradebookColumn`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``GradebookColumn`` may have a different ``Id`` than requested, such as the case wh...
[ "def", "get_gradebook_column", "(", "self", ",", "gradebook_column_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resource", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "JSONClientValidated", "(", "'grad...
53
22.413793
def getEndpoints(self,typeOfEndpoint=""): """ Get list of all endpoints on the domain. :param str typeOfEndpoint: Optional filter endpoints returned by type :return: list of all endpoints :rtype: asyncResult """ q = {} result = asyncResult() if typeOfEndpoint: q['type'] = typeOfEndpoint resul...
[ "def", "getEndpoints", "(", "self", ",", "typeOfEndpoint", "=", "\"\"", ")", ":", "q", "=", "{", "}", "result", "=", "asyncResult", "(", ")", "if", "typeOfEndpoint", ":", "q", "[", "'type'", "]", "=", "typeOfEndpoint", "result", ".", "extra", "[", "'ty...
27.047619
15.904762
def set_delimiter(self, delimiter): """Override the default or passed in delimiter with a new value. If the requested delimiter already exists in a key, a :exc:`ValueError` will be raised. :param str delimiter: The delimiter to use :raises: ValueError """ for ke...
[ "def", "set_delimiter", "(", "self", ",", "delimiter", ")", ":", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "if", "delimiter", "in", "key", ":", "raise", "ValueError", "(", "'Key {!r} collides with delimiter {!r}'", ",", "key", ",", "delimiter",...
39.294118
15.176471
def decode_msg(msg, enc='utf-8'): """ Decodes a message fragment. Args: msg - A Message object representing the fragment enc - The encoding to use for decoding the message """ # We avoid the get_payload decoding machinery for raw # content-transfer-encodings potentially containing non...
[ "def", "decode_msg", "(", "msg", ",", "enc", "=", "'utf-8'", ")", ":", "# We avoid the get_payload decoding machinery for raw", "# content-transfer-encodings potentially containing non-ascii characters,", "# such as 8bit or binary, as these are encoded using raw-unicode-escape which", "# s...
43.066667
15.866667
def reprioritize(self, stream_id, depends_on=None, weight=16, exclusive=False): """ Update the priority status of an existing stream. :param stream_id: The stream ID of the stream being updated. :param depends_on: (optional) The ID of the stream that the stream now ...
[ "def", "reprioritize", "(", "self", ",", "stream_id", ",", "depends_on", "=", "None", ",", "weight", "=", "16", ",", "exclusive", "=", "False", ")", ":", "self", ".", "_priority", ".", "reprioritize", "(", "stream_id", ",", "depends_on", ",", "weight", "...
49.5
23.5
def updateStatus(self, dataset, is_dataset_valid): """ Used to toggle the status of a dataset is_dataset_valid=0/1 (invalid/valid) """ if( dataset == "" ): dbsExceptionHandler("dbsException-invalid-input", "DBSDataset/updateStatus. dataset is required.") conn = self...
[ "def", "updateStatus", "(", "self", ",", "dataset", ",", "is_dataset_valid", ")", ":", "if", "(", "dataset", "==", "\"\"", ")", ":", "dbsExceptionHandler", "(", "\"dbsException-invalid-input\"", ",", "\"DBSDataset/updateStatus. dataset is required.\"", ")", "conn", "=...
31.217391
20.26087
def app_name_from_ini_parser(ini_parser): """ Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:main section, us...
[ "def", "app_name_from_ini_parser", "(", "ini_parser", ")", ":", "app_names", "=", "[", "sect", ".", "split", "(", "':'", ")", "[", "-", "1", "]", "for", "sect", "in", "ini_parser", ".", "sections", "(", ")", "if", "sect", "[", ":", "4", "]", "==", ...
40.433333
15.9
def plot_phase_space_sns(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, kind="hex", timeStart=None, timeEnd =None, PointsOfPadding=500, units="nm", logscale=False, cmap=None, marginalColor=None, gridsize=200, show_fig=True, ShowPSD=False, alpha=0.5, *args, **kwargs): """ Plots the phas...
[ "def", "plot_phase_space_sns", "(", "self", ",", "freq", ",", "ConvFactor", ",", "PeakWidth", "=", "10000", ",", "FractionOfSampleFreq", "=", "1", ",", "kind", "=", "\"hex\"", ",", "timeStart", "=", "None", ",", "timeEnd", "=", "None", ",", "PointsOfPadding"...
46.341463
23.430894
def generate_getter(value): """Generate getter for given value.""" @property @wraps(is_) def getter(self): return self.is_(value) return getter
[ "def", "generate_getter", "(", "value", ")", ":", "@", "property", "@", "wraps", "(", "is_", ")", "def", "getter", "(", "self", ")", ":", "return", "self", ".", "is_", "(", "value", ")", "return", "getter" ]
20.625
19.625
def get_logout_information(self, logout_token): """Return Clef user info after exchanging logout token.""" data = dict(logout_token=logout_token, app_id=self.app_id, app_secret=self.app_secret) logout_response = self._call('POST', self.logout_url, params=data) clef_user_id = logout_respo...
[ "def", "get_logout_information", "(", "self", ",", "logout_token", ")", ":", "data", "=", "dict", "(", "logout_token", "=", "logout_token", ",", "app_id", "=", "self", ".", "app_id", ",", "app_secret", "=", "self", ".", "app_secret", ")", "logout_response", ...
60.166667
20.166667
def delete(self): """ Removes project from disk """ for module in self.compute(): yield from module.instance().project_closing(self) yield from self._close_and_clean(True) for module in self.compute(): yield from module.instance().project_closed(s...
[ "def", "delete", "(", "self", ")", ":", "for", "module", "in", "self", ".", "compute", "(", ")", ":", "yield", "from", "module", ".", "instance", "(", ")", ".", "project_closing", "(", "self", ")", "yield", "from", "self", ".", "_close_and_clean", "(",...
31.5
12.5
def libvlc_audio_set_volume_callback(mp, set_volume): '''Set callbacks and private data for decoded audio. This only works in combination with L{libvlc_audio_set_callbacks}(). Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}() to configure the decoded audio format. @param mp:...
[ "def", "libvlc_audio_set_volume_callback", "(", "mp", ",", "set_volume", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_audio_set_volume_callback'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_set_volume_callback'", ",", "(", "(", "1", ...
53.538462
22.307692
def search(self, pattern): """ Top level search method on entries. """ try: return self.advanced_search(pattern) except Exception: return self.basic_search(pattern)
[ "def", "search", "(", "self", ",", "pattern", ")", ":", "try", ":", "return", "self", ".", "advanced_search", "(", "pattern", ")", "except", "Exception", ":", "return", "self", ".", "basic_search", "(", "pattern", ")" ]
27.625
9.125
def data_discovery(self, region, keywords=None, regex=None, time=None, boundaries=None, include_quantiles=False): """Discover Data Observatory measures. This method returns the full Data Observatory metadata model for each measure or measures that match the conditions from...
[ "def", "data_discovery", "(", "self", ",", "region", ",", "keywords", "=", "None", ",", "regex", "=", "None", ",", "time", "=", "None", ",", "boundaries", "=", "None", ",", "include_quantiles", "=", "False", ")", ":", "if", "isinstance", "(", "region", ...
47.305344
23.007634
def start(self): """Start client.""" self.proc = [] for telldus, port in ( (TELLDUS_CLIENT, self.port_client), (TELLDUS_EVENTS, self.port_events)): args = shlex.split(SOCAT_CLIENT.format( type=telldus, host=self.host, port=port)) ...
[ "def", "start", "(", "self", ")", ":", "self", ".", "proc", "=", "[", "]", "for", "telldus", ",", "port", "in", "(", "(", "TELLDUS_CLIENT", ",", "self", ".", "port_client", ")", ",", "(", "TELLDUS_EVENTS", ",", "self", ".", "port_events", ")", ")", ...
36.5
11.285714