text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _init_client(self, from_archive=False): """Init client""" return ConduitClient(self.url, self.api_token, self.max_retries, self.sleep_time, self.archive, from_archive)
[ "def", "_init_client", "(", "self", ",", "from_archive", "=", "False", ")", ":", "return", "ConduitClient", "(", "self", ".", "url", ",", "self", ".", "api_token", ",", "self", ".", "max_retries", ",", "self", ".", "sleep_time", ",", "self", ".", "archiv...
40.166667
0.00813
def is_table_included(table, names): """Determines if the table is included by reference in the names. A table can be named by its component or its model (using the short-name or a full python path). eg. 'package.models.SomeModel' or 'package:SomeModel' or 'package' would all include 'SomeMode...
[ "def", "is_table_included", "(", "table", ",", "names", ")", ":", "# No names indicates that every table is included.", "if", "not", "names", ":", "return", "True", "# Introspect the table and pull out the model and component from it.", "model", ",", "component", "=", "table"...
28.625
0.001056
def forward_message(self, message: Message=None, on_success: callable=None): """ Forward message to this peer. :param message: Message to forward to peer. :param on_success: Callback to call when call is complete. :return: """ self.twx.forward_message(self, messag...
[ "def", "forward_message", "(", "self", ",", "message", ":", "Message", "=", "None", ",", "on_success", ":", "callable", "=", "None", ")", ":", "self", ".", "twx", ".", "forward_message", "(", "self", ",", "message", ",", "on_success", "=", "on_success", ...
42.25
0.017391
def lower_bollinger_band(data, period, std=2.0): """ Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] lower_bb = [] for idx in range(len...
[ "def", "lower_bollinger_band", "(", "data", ",", "period", ",", "std", "=", "2.0", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "simple_ma", "=", "sma", "(", "data", "...
27.263158
0.001866
def spkpvn(handle, descr, et): """ For a specified SPK segment and time, return the state (position and velocity) of the segment's target body relative to its center of motion. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpvn_c.html :param handle: File handle. :type handle: i...
[ "def", "spkpvn", "(", "handle", ",", "descr", ",", "et", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "descr", "=", "stypes", ".", "toDoubleVector", "(", "descr", ")", "et", "=", "ctypes", ".", "c_double", "(", "et", ")", "r...
32.689655
0.001025
async def json(self, *, encoding: str = None, loads: JSONDecoder = DEFAULT_JSON_DECODER, content_type: Optional[str] = 'application/json') -> Any: """Read and decodes JSON response.""" return await self._aws_json( en...
[ "async", "def", "json", "(", "self", ",", "*", ",", "encoding", ":", "str", "=", "None", ",", "loads", ":", "JSONDecoder", "=", "DEFAULT_JSON_DECODER", ",", "content_type", ":", "Optional", "[", "str", "]", "=", "'application/json'", ")", "->", "Any", ":...
46.125
0.015957
def _validate_inputs(self, inputdict): """ Validate input links. """ # Check inputdict try: parameters = inputdict.pop(self.get_linkname('parameters')) except KeyError: raise InputValidationError("No parameters specified for this " ...
[ "def", "_validate_inputs", "(", "self", ",", "inputdict", ")", ":", "# Check inputdict", "try", ":", "parameters", "=", "inputdict", ".", "pop", "(", "self", ".", "get_linkname", "(", "'parameters'", ")", ")", "except", "KeyError", ":", "raise", "InputValidati...
39.392157
0.000971
def make_wcs_data_from_hpx_data(self, hpx_data, wcs, normalize=True): """ Creates and fills a wcs map from the hpx data using the pre-calculated mappings hpx_data : the input HEALPix data wcs : the WCS object normalize : True -> perserve integral by splitting HEALPix valu...
[ "def", "make_wcs_data_from_hpx_data", "(", "self", ",", "hpx_data", ",", "wcs", ",", "normalize", "=", "True", ")", ":", "wcs_data", "=", "np", ".", "zeros", "(", "wcs", ".", "npix", ")", "self", ".", "fill_wcs_map_from_hpx_data", "(", "hpx_data", ",", "wc...
42.727273
0.008333
def gen_locale(locale, **kwargs): ''' Generate a locale. Options: .. versionadded:: 2014.7.0 :param locale: Any locale listed in /usr/share/i18n/locales or /usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions, which require the charmap to be specified as part of the loca...
[ "def", "gen_locale", "(", "locale", ",", "*", "*", "kwargs", ")", ":", "on_debian", "=", "__grains__", ".", "get", "(", "'os'", ")", "==", "'Debian'", "on_ubuntu", "=", "__grains__", ".", "get", "(", "'os'", ")", "==", "'Ubuntu'", "on_gentoo", "=", "__...
34.230769
0.001092
def setup_env(app): """ Setup enviroment Creates required directory and storage objects (on the global enviroment) used by this extension. """ env = app.env GalleryEntryExtractor.env = env out_imgdir = os.path.join(app.outdir, '_images') if not os.path.isdir(RST_PATH): os.m...
[ "def", "setup_env", "(", "app", ")", ":", "env", "=", "app", ".", "env", "GalleryEntryExtractor", ".", "env", "=", "env", "out_imgdir", "=", "os", ".", "path", ".", "join", "(", "app", ".", "outdir", ",", "'_images'", ")", "if", "not", "os", ".", "...
30.5
0.001222
def load( self, filename, lineno = 0 ): """ Loads the inputed filename as the current document for this edit. :param filename | <str> lineno | <int> :return <bool> | success """ filename = nativestring(filename) ...
[ "def", "load", "(", "self", ",", "filename", ",", "lineno", "=", "0", ")", ":", "filename", "=", "nativestring", "(", "filename", ")", "if", "(", "not", "(", "filename", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ")", ":", ...
27.166667
0.023692
def weld_cast_scalar(scalar, to_weld_type): """Returns the scalar casted to the request Weld type. Parameters ---------- scalar : {int, float, WeldObject} Input array. to_weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Re...
[ "def", "weld_cast_scalar", "(", "scalar", ",", "to_weld_type", ")", ":", "if", "_not_possible_to_cast", "(", "scalar", ",", "to_weld_type", ")", ":", "raise", "TypeError", "(", "'Cannot cast scalar of type={} to type={}'", ".", "format", "(", "type", "(", "scalar", ...
27.931034
0.002387
def do(self, fn, message=None, *args, **kwargs): """Add a 'do' action to the steps. This is a function to execute :param fn: A function :param message: Message indicating what this function does (used for debugging if assertions fail) """ self.items.put(ChainItem(fn, self.do, me...
[ "def", "do", "(", "self", ",", "fn", ",", "message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "items", ".", "put", "(", "ChainItem", "(", "fn", ",", "self", ".", "do", ",", "message", ",", "*", "args", ",...
44.625
0.008242
def _cost_gp_withGradients(self,x): """ Predicts the time cost and its gradient of evaluating the function at x. """ m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx
[ "def", "_cost_gp_withGradients", "(", "self", ",", "x", ")", ":", "m", ",", "_", ",", "dmdx", ",", "_", "=", "self", ".", "cost_model", ".", "predict_withGradients", "(", "x", ")", "return", "np", ".", "exp", "(", "m", ")", ",", "np", ".", "exp", ...
40
0.020408
def connectRoute(amp, router, receiver, protocol): """ Connect the given receiver to a new box receiver for the given protocol. After connecting this router to an AMP server, use this method similarly to how you would use C{reactor.connectTCP} to establish a new connection to an HTTP, SMTP, or ...
[ "def", "connectRoute", "(", "amp", ",", "router", ",", "receiver", ",", "protocol", ")", ":", "route", "=", "router", ".", "bindRoute", "(", "receiver", ")", "d", "=", "amp", ".", "callRemote", "(", "Connect", ",", "origin", "=", "route", ".", "localRo...
34.142857
0.002035
def get_params(self): """ Get parameters. :return: enabled, size, chunk_delay, start_delay """ return self.enabled, self.size, self.chunk_delay, self.start_delay
[ "def", "get_params", "(", "self", ")", ":", "return", "self", ".", "enabled", ",", "self", ".", "size", ",", "self", ".", "chunk_delay", ",", "self", ".", "start_delay" ]
28
0.009901
def event_hubs(self): """Instance depends on the API version: * 2015-08-01: :class:`EventHubsOperations<azure.mgmt.eventhub.v2015_08_01.operations.EventHubsOperations>` * 2017-04-01: :class:`EventHubsOperations<azure.mgmt.eventhub.v2017_04_01.operations.EventHubsOperations>` """ ...
[ "def", "event_hubs", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'event_hubs'", ")", "if", "api_version", "==", "'2015-08-01'", ":", "from", ".", "v2015_08_01", ".", "operations", "import", "EventHubsOperations", "as", "Oper...
62.142857
0.00906
def related_schema(self): """Get the related schema of a relationship field :return Schema: the related schema """ relationship_field = self.name if relationship_field not in get_relationships(self.schema): raise InvalidFilters("{} has no relationship attribute {}"....
[ "def", "related_schema", "(", "self", ")", ":", "relationship_field", "=", "self", ".", "name", "if", "relationship_field", "not", "in", "get_relationships", "(", "self", ".", "schema", ")", ":", "raise", "InvalidFilters", "(", "\"{} has no relationship attribute {}...
40.090909
0.008869
def FindClassIdInMoMetaIgnoreCase(classId): """ Methods whether classId is valid or not . Given class is case insensitive. """ if not classId: return None if classId in _ManagedObjectMeta: return classId lClassId = classId.lower() for key in _ManagedObjectMeta.keys(): if (key.lower() == lClassId): ...
[ "def", "FindClassIdInMoMetaIgnoreCase", "(", "classId", ")", ":", "if", "not", "classId", ":", "return", "None", "if", "classId", "in", "_ManagedObjectMeta", ":", "return", "classId", "lClassId", "=", "classId", ".", "lower", "(", ")", "for", "key", "in", "_...
30.545455
0.037572
def name(currency, *, plural=False): """ return name of currency """ currency = validate_currency(currency) if plural: return _currencies[currency]['name_plural'] return _currencies[currency]['name']
[ "def", "name", "(", "currency", ",", "*", ",", "plural", "=", "False", ")", ":", "currency", "=", "validate_currency", "(", "currency", ")", "if", "plural", ":", "return", "_currencies", "[", "currency", "]", "[", "'name_plural'", "]", "return", "_currenci...
33.333333
0.029268
def GetWindowsEnvironmentVariablesMap(knowledge_base): """Return a dictionary of environment variables and their values. Implementation maps variables mentioned in https://en.wikipedia.org/wiki/Environment_variable#Windows to known KB definitions. Args: knowledge_base: A knowledgebase object. Returns...
[ "def", "GetWindowsEnvironmentVariablesMap", "(", "knowledge_base", ")", ":", "environ_vars", "=", "{", "}", "if", "knowledge_base", ".", "environ_path", ":", "environ_vars", "[", "\"path\"", "]", "=", "knowledge_base", ".", "environ_path", "if", "knowledge_base", "....
33.016667
0.008824
def _parse_top_cfg(content, filename): ''' Allow top_cfg to be YAML ''' try: obj = salt.utils.yaml.safe_load(content) if isinstance(obj, list): log.debug('MakoStack cfg `%s` parsed as YAML', filename) return obj except Exception as err: pass log.de...
[ "def", "_parse_top_cfg", "(", "content", ",", "filename", ")", ":", "try", ":", "obj", "=", "salt", ".", "utils", ".", "yaml", ".", "safe_load", "(", "content", ")", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "log", ".", "debug", "(", "...
30.461538
0.002451
def get_agent_from_entity_info(entity_info): """Return an INDRA Agent by processing an entity_info dict.""" # This will be the default name. If we get a gene name, it will # override this rawtext name. raw_text = entity_info['entityText'] name = raw_text # Get the db refs. refs = {'TEXT': r...
[ "def", "get_agent_from_entity_info", "(", "entity_info", ")", ":", "# This will be the default name. If we get a gene name, it will", "# override this rawtext name.", "raw_text", "=", "entity_info", "[", "'entityText'", "]", "name", "=", "raw_text", "# Get the db refs.", "refs", ...
48.170732
0.000248
def read_text_from_idx_file( file_name, layer_name=WORDS, keep_init_lines=False ): ''' Reads IDX format morphological annotations from given file, and returns as a Text object. The Text object will be tokenized for paragraphs, sentences, words, and it will contain morphological ann...
[ "def", "read_text_from_idx_file", "(", "file_name", ",", "layer_name", "=", "WORDS", ",", "keep_init_lines", "=", "False", ")", ":", "from", "nltk", ".", "tokenize", ".", "simple", "import", "LineTokenizer", "from", "nltk", ".", "tokenize", ".", "regexp", "imp...
39.728682
0.01542
def _get_session_cookies(session, access_token): """Use the access token to get session cookies. Raises GoogleAuthError if session cookies could not be loaded. Returns dict of cookies. """ headers = {'Authorization': 'Bearer {}'.format(access_token)} try: r = session.get(('https://acc...
[ "def", "_get_session_cookies", "(", "session", ",", "access_token", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "access_token", ")", "}", "try", ":", "r", "=", "session", ".", "get", "(", "(", "'https://accounts....
37.933333
0.000857
def help_text(self, name, text, text_kind='plain', trim_pfx=0): """ Provide help text for the user. This method will convert the text as necessary with docutils and display it in the WBrowser plugin, if available. If the plugin is not available and the text is type 'rst' then t...
[ "def", "help_text", "(", "self", ",", "name", ",", "text", ",", "text_kind", "=", "'plain'", ",", "trim_pfx", "=", "0", ")", ":", "if", "trim_pfx", ">", "0", ":", "# caller wants to trim some space off the front", "# of each line", "text", "=", "toolbox", ".",...
34.053571
0.001019
def rfile(self): """We're a generic Entry, but the caller is actually looking for a File at this point, so morph into one.""" self.__class__ = File self._morph() self.clear() return File.rfile(self)
[ "def", "rfile", "(", "self", ")", ":", "self", ".", "__class__", "=", "File", "self", ".", "_morph", "(", ")", "self", ".", "clear", "(", ")", "return", "File", ".", "rfile", "(", "self", ")" ]
34.285714
0.00813
def validate_account_credentials(deployment, context): """Exit if requested deployment account doesn't match credentials.""" boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if context.env_...
[ "def", "validate_account_credentials", "(", "deployment", ",", "context", ")", ":", "boto_args", "=", "{", "'region_name'", ":", "context", ".", "env_vars", "[", "'AWS_DEFAULT_REGION'", "]", "}", "for", "i", "in", "[", "'aws_access_key_id'", ",", "'aws_secret_acce...
49.666667
0.000823
def eval(self, js_str, timeout=0, max_memory=0): """ Eval the JavaScript string """ if is_unicode(js_str): bytes_val = js_str.encode("utf8") else: bytes_val = js_str res = None self.lock.acquire() try: res = self.ext.mr_eval_context(s...
[ "def", "eval", "(", "self", ",", "js_str", ",", "timeout", "=", "0", ",", "max_memory", "=", "0", ")", ":", "if", "is_unicode", "(", "js_str", ")", ":", "bytes_val", "=", "js_str", ".", "encode", "(", "\"utf8\"", ")", "else", ":", "bytes_val", "=", ...
33.4
0.002328
def _sub_all_refs(self, text, handler_method): """ Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every occurrence of this structure. The value returned by this method directly replaces the reference structure. Ex: text =...
[ "def", "_sub_all_refs", "(", "self", ",", "text", ",", "handler_method", ")", ":", "# RegExp to find pattern \"${logicalId.property}\" and return the word inside bracket", "logical_id_regex", "=", "'[A-Za-z0-9\\.]+|AWS::[A-Z][A-Za-z]*'", "ref_pattern", "=", "re", ".", "compile", ...
52.483871
0.008449
def trim(self, start_time, end_time, strict=False): ''' Trim all the annotations inside the jam and return as a new `JAMS` object. See `Annotation.trim` for details about how the annotations are trimmed. This operation is also documented in the jam-level sandbox ...
[ "def", "trim", "(", "self", ",", "start_time", ",", "end_time", ",", "strict", "=", "False", ")", ":", "# Make sure duration is set in file metadata", "if", "self", ".", "file_metadata", ".", "duration", "is", "None", ":", "raise", "JamsError", "(", "'Duration m...
40.041096
0.000668
def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username:...
[ "def", "parse_dsn", "(", "dsn_string", ")", ":", "dsn", "=", "urlparse", "(", "dsn_string", ")", "scheme", "=", "dsn", ".", "scheme", ".", "split", "(", "'+'", ")", "[", "0", "]", "username", "=", "password", "=", "host", "=", "port", "=", "None", ...
34.318182
0.000644
def thaw_decrypt(vault_client, src_file, tmp_dir, opt): """Decrypts the encrypted ice file""" if not os.path.isdir(opt.secrets): LOG.info("Creating secret directory %s", opt.secrets) os.mkdir(opt.secrets) zip_file = "%s/aomi.zip" % tmp_dir if opt.gpg_pass_path: gpg_path_bits =...
[ "def", "thaw_decrypt", "(", "vault_client", ",", "src_file", ",", "tmp_dir", ",", "opt", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "opt", ".", "secrets", ")", ":", "LOG", ".", "info", "(", "\"Creating secret directory %s\"", ",", "opt"...
36.903226
0.000852
def get_events(fd, timeout=None): """get_events(fd[, timeout]) Return a list of InotifyEvent instances representing events read from inotify. If timeout is None, this will block forever until at least one event can be read. Otherwise, timeout should be an integer or float specifying a timeout in ...
[ "def", "get_events", "(", "fd", ",", "timeout", "=", "None", ")", ":", "(", "rlist", ",", "_", ",", "_", ")", "=", "select", "(", "[", "fd", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", "if", "not", "rlist", ":", "return", "[", "...
34.25
0.000789
def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): ...
[ "def", "delete_user", "(", "user_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "get_user", "(", "user_name", ",", "region", ",", "key", ",", "keyid", ",", ...
27.875
0.001445
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the ObtainLease response payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting ...
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "ObtainLeaseResponsePayload", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", "kmip...
39.086957
0.001085
def spawn_antigen_predictors(job, transgened_files, phlat_files, univ_options, mhc_options): """ Based on the number of alleles obtained from node 14, this module will spawn callers to predict MHCI:peptide and MHCII:peptide binding on the peptide files from node 17. Once all MHC:peptide predictions are...
[ "def", "spawn_antigen_predictors", "(", "job", ",", "transgened_files", ",", "phlat_files", ",", "univ_options", ",", "mhc_options", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running spawn_anti on %s'", "%", "univ_options", "[", "'patient'", "]",...
52.51
0.002243
def current_vote_value(self, **kwargs): ''' Ensures the needed variables are created and set to defaults although a variable number of variables are given. ''' try: kwargs.items() except: pass else: for key, value in kwargs.item...
[ "def", "current_vote_value", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs", ".", "items", "(", ")", "except", ":", "pass", "else", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", ...
36.156863
0.012672
def call(self, path, query=None, method='GET', data=None, files=None, get_all_pages=False, complete_response=False, retry_on=None, max_retries=0, raw_query=None, retval=None, **kwargs): """Make a REST call to the Zendesk web service. Parameters: path - Pat...
[ "def", "call", "(", "self", ",", "path", ",", "query", "=", "None", ",", "method", "=", "'GET'", ",", "data", "=", "None", ",", "files", "=", "None", ",", "get_all_pages", "=", "False", ",", "complete_response", "=", "False", ",", "retry_on", "=", "N...
44.081081
0.000974
def get_local_driver( browser_name, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get...
[ "def", "get_local_driver", "(", "browser_name", ",", "headless", ",", "proxy_string", ",", "proxy_auth", ",", "proxy_user", ",", "proxy_pass", ",", "user_agent", ",", "disable_csp", ")", ":", "downloads_path", "=", "download_helper", ".", "get_downloads_folder", "("...
48.707317
0.000164
def get_soundcloud_data(url): """ Scrapes a SoundCloud page for a track's important information. Returns: dict: of audio data """ data = {} request = requests.get(url) title_tag = request.text.split('<title>')[1].split('</title')[0] data['title'] = title_tag.split(' by ')[0]...
[ "def", "get_soundcloud_data", "(", "url", ")", ":", "data", "=", "{", "}", "request", "=", "requests", ".", "get", "(", "url", ")", "title_tag", "=", "request", ".", "text", ".", "split", "(", "'<title>'", ")", "[", "1", "]", ".", "split", "(", "'<...
21.947368
0.002299
def _parse_env_var_file(data): """ Parses a basic VAR="value data" file contents into a dict :param data: A unicode string of the file data :return: A dict of parsed name/value data """ output = {} for line in data.splitlines(): line = line.strip() if not l...
[ "def", "_parse_env_var_file", "(", "data", ")", ":", "output", "=", "{", "}", "for", "line", "in", "data", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "'='", "not", "in", "line", ":", ...
24.307692
0.001522
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'Flushing tables and arrays to disk...'", ")", "for", "tab", "in", "self", ".", "_tables", ".", "values", "(", ")", ":", "tab", ".", "flush", "(", ")", "self", ".", "_write_n...
38.5
0.008475
def getActiveJobCountForClientInfo(self, clientInfo): """ Return the number of jobs for the given clientInfo and a status that is not completed. """ with ConnectionFactory.get() as conn: query = 'SELECT count(job_id) ' \ 'FROM %s ' \ 'WHERE client_info = %%s ' \ ...
[ "def", "getActiveJobCountForClientInfo", "(", "self", ",", "clientInfo", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "query", "=", "'SELECT count(job_id) '", "'FROM %s '", "'WHERE client_info = %%s '", "' AND status != %%s'", "%", "...
38.692308
0.009709
def append_from_json(self, json_string): """ Creates a ``measurement.Measurement`` object from the supplied JSON string and then appends it to the buffer :param json_string: the JSON formatted string """ a_dict = json.loads(json_string) self.append_from_dict(a_di...
[ "def", "append_from_json", "(", "self", ",", "json_string", ")", ":", "a_dict", "=", "json", ".", "loads", "(", "json_string", ")", "self", ".", "append_from_dict", "(", "a_dict", ")" ]
35
0.009288
def associate_interface_environments(self, int_env_map): """ Method to add an interface. :param int_env_map: List containing interfaces and environments ids desired to be associates. :return: Id. """ data = {'interface_environments': int_env_map} return super(Api...
[ "def", "associate_interface_environments", "(", "self", ",", "int_env_map", ")", ":", "data", "=", "{", "'interface_environments'", ":", "int_env_map", "}", "return", "super", "(", "ApiInterfaceRequest", ",", "self", ")", ".", "post", "(", "'api/v3/interface/environ...
42.222222
0.010309
def record_patch(rec, diff): """Return the JSON-compatible structure that results from applying the changes in `diff` to the record `rec`. The parameters must be structures compatible with json.dumps *or* strings compatible with json.loads. Note that by design, `old == record_patch(new, record_diff(old,...
[ "def", "record_patch", "(", "rec", ",", "diff", ")", ":", "rec", ",", "diff", "=", "_norm_json_params", "(", "rec", ",", "diff", ")", "return", "json_delta", ".", "patch", "(", "rec", ",", "diff", ",", "in_place", "=", "False", ")" ]
60.571429
0.002326
def traceroute(host): ''' Performs a traceroute to a 3rd party host CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] cmd = ['tracert', salt.utils.network.sanitize_host(host)] lines = __salt__['cmd.run'](cmd, python_shell=False).splitline...
[ "def", "traceroute", "(", "host", ")", ":", "ret", "=", "[", "]", "cmd", "=", "[", "'tracert'", ",", "salt", ".", "utils", ".", "network", ".", "sanitize_host", "(", "host", ")", "]", "lines", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ","...
28.538462
0.000651
def recarrayequalspairs(X,Y,weak=True): """ Indices of elements in a sorted numpy recarray (or ndarray with structured dtype) equal to those in another. Record array version of func:`tabular.fast.equalspairs`, but slightly different because the concept of being sorted is less well-defined for a ...
[ "def", "recarrayequalspairs", "(", "X", ",", "Y", ",", "weak", "=", "True", ")", ":", "if", "(", "weak", "and", "set", "(", "X", ".", "dtype", ".", "names", ")", "!=", "set", "(", "Y", ".", "dtype", ".", "names", ")", ")", "or", "(", "not", "...
28.640625
0.011603
def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, ...
[ "def", "get_interfaces_ip", "(", "self", ")", ":", "interfaces_ip", "=", "{", "}", "ipv4_command", "=", "\"show ip interface vrf all\"", "ipv6_command", "=", "\"show ipv6 interface vrf all\"", "output_v4", "=", "self", ".", "_send_command", "(", "ipv4_command", ")", "...
39.450549
0.002174
def title(self): ''' Returns the axis instance where the title will be printed ''' return self.title_left(on=False), self.title_center(on=False), \ self.title_right(on=False)
[ "def", "title", "(", "self", ")", ":", "return", "self", ".", "title_left", "(", "on", "=", "False", ")", ",", "self", ".", "title_center", "(", "on", "=", "False", ")", ",", "self", ".", "title_right", "(", "on", "=", "False", ")" ]
27
0.013453
def autoLayoutNodes( self, nodes, padX = None, padY = None, direction = Qt.Horizontal, layout = 'Layered', animate = 0, centerOn = None, ...
[ "def", "autoLayoutNodes", "(", "self", ",", "nodes", ",", "padX", "=", "None", ",", "padY", "=", "None", ",", "direction", "=", "Qt", ".", "Horizontal", ",", "layout", "=", "'Layered'", ",", "animate", "=", "0", ",", "centerOn", "=", "None", ",", "ce...
40.225806
0.01683
def size(self): """! @brief Return size of self-organized map that is defined by total number of neurons. @return (uint) Size of self-organized map (number of neurons). """ if self.__ccore_som_pointer is not None: self._size = wrapper.som_g...
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "__ccore_som_pointer", "is", "not", "None", ":", "self", ".", "_size", "=", "wrapper", ".", "som_get_size", "(", "self", ".", "__ccore_som_pointer", ")", "return", "self", ".", "_size" ]
31.916667
0.015228
def dump_results(self): """ Save eigenvalue analysis reports Returns ------- None """ system = self.system mu = self.mu partfact = self.part_fact if system.files.no_output: return text = [] header = [] ...
[ "def", "dump_results", "(", "self", ")", ":", "system", "=", "self", ".", "system", "mu", "=", "self", ".", "mu", "partfact", "=", "self", ".", "part_fact", "if", "system", ".", "files", ".", "no_output", ":", "return", "text", "=", "[", "]", "header...
29.50495
0.000649
def newEntry(self, ident = "", seq = "", plus = "", qual = "") : """Appends an empty entry at the end of the CSV and returns it""" e = FastqEntry() self.data.append(e) return e
[ "def", "newEntry", "(", "self", ",", "ident", "=", "\"\"", ",", "seq", "=", "\"\"", ",", "plus", "=", "\"\"", ",", "qual", "=", "\"\"", ")", ":", "e", "=", "FastqEntry", "(", ")", "self", ".", "data", ".", "append", "(", "e", ")", "return", "e"...
36
0.081522
def plot_mag_map_basemap(fignum, element, lons, lats, element_type, cmap='RdYlBu', lon_0=0, date=""): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : l...
[ "def", "plot_mag_map_basemap", "(", "fignum", ",", "element", ",", "lons", ",", "lats", ",", "element_type", ",", "cmap", "=", "'RdYlBu'", ",", "lon_0", "=", "0", ",", "date", "=", "\"\"", ")", ":", "if", "not", "has_basemap", ":", "print", "(", "'-W- ...
39.234375
0.001943
def margin_rate(self): """ [float] 合约最低保证金率(期货专用) """ try: return self.__dict__["margin_rate"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'margin_rate' ".format(self.order_book_id) ...
[ "def", "margin_rate", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dict__", "[", "\"margin_rate\"", "]", "except", "(", "KeyError", ",", "ValueError", ")", ":", "raise", "AttributeError", "(", "\"Instrument(order_book_id={}) has no attribute 'margin_...
32.2
0.009063
def qteGetVariableDoc(self, varName: str, module=None): """ Retrieve documentation for ``varName`` defined in ``module``. If ``module`` is **None** then ``qte_global`` will be used. |Args| * ``varName`` (**str**): variable name. * ``module`` (**Python module**): the mo...
[ "def", "qteGetVariableDoc", "(", "self", ",", "varName", ":", "str", ",", "module", "=", "None", ")", ":", "# Use the global name space per default.", "if", "module", "is", "None", ":", "module", "=", "qte_global", "# No documentation for the variable can exists if the ...
31.8
0.001744
def emit(self, record): """Emit the log record.""" self.entries.append(self.format(record)) if len(self.entries) > self.flush_limit and not self.session.auth.renewing: self.log_to_api() self.entries = []
[ "def", "emit", "(", "self", ",", "record", ")", ":", "self", ".", "entries", ".", "append", "(", "self", ".", "format", "(", "record", ")", ")", "if", "len", "(", "self", ".", "entries", ")", ">", "self", ".", "flush_limit", "and", "not", "self", ...
41
0.011952
def strip_token(self, text, start, end): """{{ a }} -> a""" text = text.replace(start, '', 1) text = text.replace(end, '', 1) return text
[ "def", "strip_token", "(", "self", ",", "text", ",", "start", ",", "end", ")", ":", "text", "=", "text", ".", "replace", "(", "start", ",", "''", ",", "1", ")", "text", "=", "text", ".", "replace", "(", "end", ",", "''", ",", "1", ")", "return"...
33
0.011834
def _fromstring(value): '''_fromstring Convert XML string value to None, boolean, int or float. ''' if not value: return None std_value = value.strip().lower() if std_value == 'true': return 'true' elif std_value == 'false': return 'false' # try: # retur...
[ "def", "_fromstring", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "std_value", "=", "value", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "std_value", "==", "'true'", ":", "return", "'true'", "elif", "std_value", "==",...
20.772727
0.002092
def accept(self): """Do PetaBencana download and display it in QGIS. .. versionadded: 3.3 """ self.save_state() try: self.require_directory() except CanceledImportDialogError: return QgsApplication.instance().setOverrideCursor( ...
[ "def", "accept", "(", "self", ")", ":", "self", ".", "save_state", "(", ")", "try", ":", "self", ".", "require_directory", "(", ")", "except", "CanceledImportDialogError", ":", "return", "QgsApplication", ".", "instance", "(", ")", ".", "setOverrideCursor", ...
31.702381
0.000728
def _save_results(options, module, core_results, fit_results): """ Save results of analysis as tables and figures Parameters ---------- options : dict Option names and values for analysis module : str Module that contained function used to generate core_results core_results ...
[ "def", "_save_results", "(", "options", ",", "module", ",", "core_results", ",", "fit_results", ")", ":", "logging", ".", "info", "(", "\"Saving all results\"", ")", "# Use custom plot format", "mpl", ".", "rcParams", ".", "update", "(", "misc", ".", "rcparams",...
33.025
0.001471
def _check_codons(self): """ If codon table is missing stop codons, then add them. """ for stop_codon in self.stop_codons: if stop_codon in self.codon_table: if self.codon_table[stop_codon] != "*": raise ValueError( ...
[ "def", "_check_codons", "(", "self", ")", ":", "for", "stop_codon", "in", "self", ".", "stop_codons", ":", "if", "stop_codon", "in", "self", ".", "codon_table", ":", "if", "self", ".", "codon_table", "[", "stop_codon", "]", "!=", "\"*\"", ":", "raise", "...
40.655172
0.002486
def _build_vars_dict(vars_file='', variables=None): """Merge variables into a single dictionary Applies to CLI provided variables only """ repex_vars = {} if vars_file: with open(vars_file) as varsfile: repex_vars = yaml.safe_load(varsfile.read()) for var in variables: ...
[ "def", "_build_vars_dict", "(", "vars_file", "=", "''", ",", "variables", "=", "None", ")", ":", "repex_vars", "=", "{", "}", "if", "vars_file", ":", "with", "open", "(", "vars_file", ")", "as", "varsfile", ":", "repex_vars", "=", "yaml", ".", "safe_load...
31.538462
0.00237
def is_coord_subset(subset, superset, atol=1e-8): """ Tests if all coords in subset are contained in superset. Doesn't use periodic boundary conditions Args: subset, superset: List of coords Returns: True if all of subset is in superset. """ c1 = np.array(subset) c2 = n...
[ "def", "is_coord_subset", "(", "subset", ",", "superset", ",", "atol", "=", "1e-8", ")", ":", "c1", "=", "np", ".", "array", "(", "subset", ")", "c2", "=", "np", ".", "array", "(", "superset", ")", "is_close", "=", "np", ".", "all", "(", "np", "....
29.5
0.002053
def _get_config(self): '''Reads the config file from disk or creates a new one.''' filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME) modified_time = os.path.getmtime(filename) if modified_time != self.config_last_modified_time: config = read_pickle(filename, default=self.previous_con...
[ "def", "_get_config", "(", "self", ")", ":", "filename", "=", "'{}/{}'", ".", "format", "(", "self", ".", "PLUGIN_LOGDIR", ",", "CONFIG_FILENAME", ")", "modified_time", "=", "os", ".", "path", ".", "getmtime", "(", "filename", ")", "if", "modified_time", "...
35.692308
0.008403
def simxGetObjectHandle(clientID, objectName, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' handle = ct.c_int() if (sys.version_info[0] == 3) and (type(objectName) is str): objectName=objectName.encode('utf-8') return c_GetO...
[ "def", "simxGetObjectHandle", "(", "clientID", ",", "objectName", ",", "operationMode", ")", ":", "handle", "=", "ct", ".", "c_int", "(", ")", "if", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "and", "(", "type", "(", "objectName", ...
49.125
0.01
def get_listeners(self): """Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.""" return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__]
[ "def", "get_listeners", "(", "self", ")", ":", "return", "[", "(", "name", ",", "getattr", "(", "self", ",", "method_name", ")", ")", "for", "name", ",", "method_name", "in", "self", ".", "__cog_listeners__", "]" ]
75
0.017621
def _format_unhashed_feature(feature, weight, hl_spaces): # type: (...) -> str """ Format unhashed feature: show first (most probable) candidate, display other candidates in title attribute. """ if not feature: return '' else: first, rest = feature[0], feature[1:] html = ...
[ "def", "_format_unhashed_feature", "(", "feature", ",", "weight", ",", "hl_spaces", ")", ":", "# type: (...) -> str", "if", "not", "feature", ":", "return", "''", "else", ":", "first", ",", "rest", "=", "feature", "[", "0", "]", ",", "feature", "[", "1", ...
37.866667
0.001718
def _generate_examples(self, filepath): """Generate mnli examples. Args: filepath: a string Yields: dictionaries containing "premise", "hypothesis" and "label" strings """ for idx, line in enumerate(tf.io.gfile.GFile(filepath, "rb")): if idx == 0: continue # skip header ...
[ "def", "_generate_examples", "(", "self", ",", "filepath", ")", ":", "for", "idx", ",", "line", "in", "enumerate", "(", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "filepath", ",", "\"rb\"", ")", ")", ":", "if", "idx", "==", "0", ":", "contin...
32.041667
0.011364
def container_device_get(name, device_name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Get a container device name : Name of the container device_name : The device name to retrieve remote_addr : An URL to a remote Server, you als...
[ "def", "container_device_get", "(", "name", ",", "device_name", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name", ",", "remote_addr...
25.146341
0.000934
def compile(self): """ This method isn't yet idempotent; calling multiple times may yield unexpected results """ # Can't tell if this is a hack or not. Revisit later self.context.set_query(self) # If any subqueries, translate them and add to beginning of query as...
[ "def", "compile", "(", "self", ")", ":", "# Can't tell if this is a hack or not. Revisit later", "self", ".", "context", ".", "set_query", "(", "self", ")", "# If any subqueries, translate them and add to beginning of query as", "# part of the WITH section", "with_frag", "=", "...
25.695652
0.00163
def fetch_ensembl_genes(build='37'): """Fetch the ensembl genes Args: build(str): ['37', '38'] """ if build == '37': url = 'http://grch37.ensembl.org' else: url = 'http://www.ensembl.org' LOG.info("Fetching ensembl genes from %s", url) dataset_name = 'hsapie...
[ "def", "fetch_ensembl_genes", "(", "build", "=", "'37'", ")", ":", "if", "build", "==", "'37'", ":", "url", "=", "'http://grch37.ensembl.org'", "else", ":", "url", "=", "'http://www.ensembl.org'", "LOG", ".", "info", "(", "\"Fetching ensembl genes from %s\"", ",",...
21.138889
0.015075
def get_content( cls, abspath: str, start: int = None, end: int = None ) -> Generator[bytes, None, None]: """Retrieve the content of the requested resource which is located at the given absolute path. This class method may be overridden by subclasses. Note that its signatur...
[ "def", "get_content", "(", "cls", ",", "abspath", ":", "str", ",", "start", ":", "int", "=", "None", ",", "end", ":", "int", "=", "None", ")", "->", "Generator", "[", "bytes", ",", "None", ",", "None", "]", ":", "with", "open", "(", "abspath", ",...
39.837838
0.001987
def islice(self, start=None, stop=None, reverse=False): """ Returns an iterator that slices `self` from `start` to `stop` index, inclusive and exclusive respectively. When `reverse` is `True`, values are yielded from the iterator in reverse order. Both `start` and `stop...
[ "def", "islice", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "reverse", "=", "False", ")", ":", "_len", "=", "self", ".", "_len", "if", "not", "_len", ":", "return", "iter", "(", "(", ")", ")", "start", ",", "stop", "...
27.6875
0.002181
def repo(name, keyid=None, env=None, use_passphrase=False, gnupghome='/etc/salt/gpgkeys', runas='builder', timeout=15.0): ''' Make a package repository and optionally sign it and packages present The name is directory to turn into a repo. This state is ...
[ "def", "repo", "(", "name", ",", "keyid", "=", "None", ",", "env", "=", "None", ",", "use_passphrase", "=", "False", ",", "gnupghome", "=", "'/etc/salt/gpgkeys'", ",", "runas", "=", "'builder'", ",", "timeout", "=", "15.0", ")", ":", "ret", "=", "{", ...
31.879747
0.000578
def ion_or_solid_comp_object(formula): """ Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object """ m = re.search(r"\[(...
[ "def", "ion_or_solid_comp_object", "(", "formula", ")", ":", "m", "=", "re", ".", "search", "(", "r\"\\[([^\\[\\]]+)\\]|\\(aq\\)\"", ",", "formula", ")", "if", "m", ":", "comp_obj", "=", "Ion", ".", "from_formula", "(", "formula", ")", "elif", "re", ".", "...
26.95
0.001792
def check_file_list_cache(opts, form, list_cache, w_lock): ''' Checks the cache file to see if there is a new enough file list cache, and returns the match (if found, along with booleans used by the fileserver backend to determine if the cache needs to be refreshed/written). ''' refresh_cache = ...
[ "def", "check_file_list_cache", "(", "opts", ",", "form", ",", "list_cache", ",", "w_lock", ")", ":", "refresh_cache", "=", "False", "save_cache", "=", "True", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "wait_lock", "(", "w_loc...
46.564516
0.002035
def __insert_cluster(self, cluster): """! @brief Insert cluster to the list (sorted queue) in line with sequence order (distance). @param[in] cluster (cure_cluster): Cluster that should be inserted. """ for index in range(len(self.__queue)): ...
[ "def", "__insert_cluster", "(", "self", ",", "cluster", ")", ":", "for", "index", "in", "range", "(", "len", "(", "self", ".", "__queue", ")", ")", ":", "if", "cluster", ".", "distance", "<", "self", ".", "__queue", "[", "index", "]", ".", "distance"...
34.928571
0.013944
def _handle_tasks_insert(self, batch_size=None): """Convert all Async's into tasks, then insert them into queues.""" if self._tasks_inserted: raise errors.ContextAlreadyStartedError( "This Context has already had its tasks inserted.") task_map = self._get_tasks_by_qu...
[ "def", "_handle_tasks_insert", "(", "self", ",", "batch_size", "=", "None", ")", ":", "if", "self", ".", "_tasks_inserted", ":", "raise", "errors", ".", "ContextAlreadyStartedError", "(", "\"This Context has already had its tasks inserted.\"", ")", "task_map", "=", "s...
48.225806
0.001311
def accessible(self,fromstate, tostate): """Is state tonode directly accessible (in one step) from state fromnode? (i.e. is there an edge between the nodes). If so, return the probability, else zero""" if (not (fromstate in self.nodes)) or (not (tostate in self.nodes)) or not (fromstate in self.edges_ou...
[ "def", "accessible", "(", "self", ",", "fromstate", ",", "tostate", ")", ":", "if", "(", "not", "(", "fromstate", "in", "self", ".", "nodes", ")", ")", "or", "(", "not", "(", "tostate", "in", "self", ".", "nodes", ")", ")", "or", "not", "(", "fro...
59.375
0.010373
def t_identifier(self, s): r' [$a-z_A-Z/\//][\w/\.\$:#]*' self.rv.append(Token(type='IDENTIFIER', attr=s))
[ "def", "t_identifier", "(", "self", ",", "s", ")", ":", "self", ".", "rv", ".", "append", "(", "Token", "(", "type", "=", "'IDENTIFIER'", ",", "attr", "=", "s", ")", ")" ]
40.666667
0.016129
def poplist(self, key, default=_absent): """ If <key> is in the dictionary, pop it and return its list of values. If <key> is not in the dictionary, return <default>. KeyError is raised if <default> is not provided and <key> is not in the dictionary. Example: omd = omd...
[ "def", "poplist", "(", "self", ",", "key", ",", "default", "=", "_absent", ")", ":", "if", "key", "in", "self", ":", "values", "=", "self", ".", "getlist", "(", "key", ")", "del", "self", ".", "_map", "[", "key", "]", "for", "node", ",", "nodekey...
37.740741
0.001914
def buffer2file(self): """ add the code buffer content to CassetteFile() instance """ if self.current_file is not None and self.buffer: self.current_file.add_block_data(self.buffered_block_length, self.buffer) self.buffer = [] self.buffered_block_lengt...
[ "def", "buffer2file", "(", "self", ")", ":", "if", "self", ".", "current_file", "is", "not", "None", "and", "self", ".", "buffer", ":", "self", ".", "current_file", ".", "add_block_data", "(", "self", ".", "buffered_block_length", ",", "self", ".", "buffer...
39.75
0.009231
def plotER(self,*args,**kwargs): """ NAME: plotER PURPOSE: plot ER(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ if...
[ "def", "plotER", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'normed'", ",", "False", ")", ":", "kwargs", "[", "'d2'", "]", "=", "'ERnorm'", "else", ":", "kwargs", "[", "'d2'", "]", "=", "...
25.111111
0.017058
def logout(self, save=True): """Log out nicely (like clicking on logout button). :params save: False if You don't want to save cookies. """ # self.r.get('https://www.easports.com/signout', params={'ct': self._}) # self.r.get('https://accounts.ea.com/connect/clearsid', params={'c...
[ "def", "logout", "(", "self", ",", "save", "=", "True", ")", ":", "# self.r.get('https://www.easports.com/signout', params={'ct': self._})", "# self.r.get('https://accounts.ea.com/connect/clearsid', params={'ct': self._})", "# self.r.get('https://beta.www.origin.com/views/logout.html', param...
57.642857
0.008537
def list_project_nodes(self, ignore_default_project_node=True): """ Returns the Model :class:`umbra.components.factory.script_editor.nodes.ProjectNode` class nodes. :param ignore_default_project_node: Default ProjectNode will be ignored. :type ignore_default_project_node: bool :...
[ "def", "list_project_nodes", "(", "self", ",", "ignore_default_project_node", "=", "True", ")", ":", "project_nodes", "=", "self", ".", "find_family", "(", "\"Project\"", ")", "return", "filter", "(", "lambda", "x", ":", "x", "!=", "self", ".", "__default_proj...
43.461538
0.008666
def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get('capture_response', False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE,...
[ "def", "run_message", "(", "message", ")", ":", "if", "message", ".", "get", "(", "'capture_response'", ",", "False", ")", ":", "DYNAMODB_CLIENT", ".", "put_item", "(", "TableName", "=", "ASYNC_RESPONSE_TABLE", ",", "Item", "=", "{", "'id'", ":", "{", "'S'...
31.634146
0.000748
def SubmitJob(self, *params, **kw): """Asynchronously execute the specified GP task. This will return a Geoprocessing Job object. Parameters are passed in either in order or as keywords.""" fp = self.__expandparamstodict(params, kw) return self._get_subfolder('submitJob/',...
[ "def", "SubmitJob", "(", "self", ",", "*", "params", ",", "*", "*", "kw", ")", ":", "fp", "=", "self", ".", "__expandparamstodict", "(", "params", ",", "kw", ")", "return", "self", ".", "_get_subfolder", "(", "'submitJob/'", ",", "GPJob", ",", "fp", ...
56.166667
0.008772
def validate(self, object): """Validate an object against the schema. This function just passes if the schema matches the object. If the object does not match the schema, a ValidationException is raised. This error allows debugging. """ resolver=self.get_resolver() ...
[ "def", "validate", "(", "self", ",", "object", ")", ":", "resolver", "=", "self", ".", "get_resolver", "(", ")", "jsonschema", ".", "validate", "(", "object", ",", "self", ".", "get_schema", "(", ")", ",", "resolver", "=", "resolver", ")" ]
42.222222
0.010309
def relocate(self): """Move to the position of self.SearchVar""" name = self.SearchVar.get() if self.kbos.has_key(name): kbo = self.kbos[name] assert isinstance(kbo, orbfit.Orbfit) this_time = Time(self.date.get(), scale='utc') try: ...
[ "def", "relocate", "(", "self", ")", ":", "name", "=", "self", ".", "SearchVar", ".", "get", "(", ")", "if", "self", ".", "kbos", ".", "has_key", "(", "name", ")", ":", "kbo", "=", "self", ".", "kbos", "[", "name", "]", "assert", "isinstance", "(...
43.357143
0.009677
def stk_description_metadata(description): """Return metadata from MetaMorph image description as list of dict. The MetaMorph image description format is unspecified. Expect failures. """ description = description.strip() if not description: return [] try: description = bytes2s...
[ "def", "stk_description_metadata", "(", "description", ")", ":", "description", "=", "description", ".", "strip", "(", ")", "if", "not", "description", ":", "return", "[", "]", "try", ":", "description", "=", "bytes2str", "(", "description", ")", "except", "...
31.53125
0.000962
def isnr(vref, vdeg, vrst): """ Compute Improvement Signal to Noise Ratio (ISNR) for reference, degraded, and restored images. Parameters ---------- vref : array_like Reference image vdeg : array_like Degraded image vrst : array_like Restored image Returns ---...
[ "def", "isnr", "(", "vref", ",", "vdeg", ",", "vrst", ")", ":", "msedeg", "=", "mse", "(", "vref", ",", "vdeg", ")", "mserst", "=", "mse", "(", "vref", ",", "vrst", ")", "with", "np", ".", "errstate", "(", "divide", "=", "'ignore'", ")", ":", "...
21.4
0.001789
def sql_pathdist_func(path1, path2, sep=os.path.sep): """ Return a distance between `path1` and `path2`. >>> sql_pathdist_func('a/b/', 'a/b/', sep='/') 0 >>> sql_pathdist_func('a/', 'a/b/', sep='/') 1 >>> sql_pathdist_func('a', 'a/', sep='/') 0 """ seq1 = path1.rstrip(sep).spli...
[ "def", "sql_pathdist_func", "(", "path1", ",", "path2", ",", "sep", "=", "os", ".", "path", ".", "sep", ")", ":", "seq1", "=", "path1", ".", "rstrip", "(", "sep", ")", ".", "split", "(", "sep", ")", "seq2", "=", "path2", ".", "rstrip", "(", "sep"...
28.133333
0.002294
def get_terminal_size(): """ get size of console: rows x columns :return: tuple, (int, int) """ try: rows, columns = subprocess.check_output(['stty', 'size']).split() except subprocess.CalledProcessError: # not attached to terminal logger.info("not attached to terminal")...
[ "def", "get_terminal_size", "(", ")", ":", "try", ":", "rows", ",", "columns", "=", "subprocess", ".", "check_output", "(", "[", "'stty'", ",", "'size'", "]", ")", ".", "split", "(", ")", "except", "subprocess", ".", "CalledProcessError", ":", "# not attac...
29.928571
0.002315
def _remove_app_models(all_apps, models_to_remove): """ Remove the model specs in models_to_remove from the models specs in the apps in all_apps. If an app has no models left, don't include it in the output. This has the side-effect that the app view e.g. /admin/app/ may not be accessible from ...
[ "def", "_remove_app_models", "(", "all_apps", ",", "models_to_remove", ")", ":", "filtered_apps", "=", "[", "]", "for", "app", "in", "all_apps", ":", "models", "=", "[", "x", "for", "x", "in", "app", "[", "'models'", "]", "if", "x", "not", "in", "model...
30.894737
0.001653
def postprocess_input_todo(self, p_todo): """ Post-processes a parsed todo when adding it to the list. * It converts relative dates to absolute ones. * Automatically inserts a creation date if not present. * Handles more user-friendly dependencies with before:, partof: and ...
[ "def", "postprocess_input_todo", "(", "self", ",", "p_todo", ")", ":", "def", "convert_date", "(", "p_tag", ")", ":", "value", "=", "p_todo", ".", "tag_value", "(", "p_tag", ")", "if", "value", ":", "dateobj", "=", "relative_date_to_date", "(", "value", ")...
33.803571
0.001027
def predict_dims(self, q, dims_x, dims_y, dims_out, sigma=None, k=None): """Provide a prediction of q in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._we...
[ "def", "predict_dims", "(", "self", ",", "q", ",", "dims_x", ",", "dims_y", ",", "dims_out", ",", "sigma", "=", "None", ",", "k", "=", "None", ")", ":", "assert", "len", "(", "q", ")", "==", "len", "(", "dims_x", ")", "+", "len", "(", "dims_y", ...
40.107143
0.015652
def to_sql(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : st...
[ "def", "to_sql", "(", "self", ",", "frame", ",", "name", ",", "if_exists", "=", "'fail'", ",", "index", "=", "True", ",", "index_label", "=", "None", ",", "schema", "=", "None", ",", "chunksize", "=", "None", ",", "dtype", "=", "None", ",", "method",...
48.644737
0.00106