text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def isc(data, pairwise=False, summary_statistic=None, tolerate_nans=True): """Intersubject correlation For each voxel or ROI, compute the Pearson correlation between each subject's response time series and other subjects' response time series. If pairwise is False (default), use the leave-one-out appro...
[ "def", "isc", "(", "data", ",", "pairwise", "=", "False", ",", "summary_statistic", "=", "None", ",", "tolerate_nans", "=", "True", ")", ":", "# Check response time series input format", "data", ",", "n_TRs", ",", "n_voxels", ",", "n_subjects", "=", "_check_time...
42.171875
0.000181
def get_cookie(self, *args): """ Return the (decoded) value of a cookie. """ value = self.COOKIES.get(*args) sec = self.app.config['securecookie.key'] dec = cookie_decode(value, sec) return dec or value
[ "def", "get_cookie", "(", "self", ",", "*", "args", ")", ":", "value", "=", "self", ".", "COOKIES", ".", "get", "(", "*", "args", ")", "sec", "=", "self", ".", "app", ".", "config", "[", "'securecookie.key'", "]", "dec", "=", "cookie_decode", "(", ...
39.5
0.008264
def MigrateNode(r, node, mode=None, dry_run=False, iallocator=None, target_node=None): """ Migrates all primary instances from a node. @type node: str @param node: node to migrate @type mode: string @param mode: if passed, it will overwrite the live migration type, o...
[ "def", "MigrateNode", "(", "r", ",", "node", ",", "mode", "=", "None", ",", "dry_run", "=", "False", ",", "iallocator", "=", "None", ",", "target_node", "=", "None", ")", ":", "query", "=", "{", "\"dry-run\"", ":", "dry_run", ",", "}", "if", "NODE_MI...
28.125
0.000716
def _get_jsmap_name(self, url): """return 'name' of the map in .js format""" ret = urlopen(url) return ret.read().decode('utf-8').split('=')[0].replace(" ", "")
[ "def", "_get_jsmap_name", "(", "self", ",", "url", ")", ":", "ret", "=", "urlopen", "(", "url", ")", "return", "ret", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ".", "split", "(", "'='", ")", "[", "0", "]", ".", "replace", "(", ...
37.8
0.015544
def _relation_module(role, interface): """ Return module for relation based on its role and interface, or None. Prefers new location (reactive/relations) over old (hooks/relations). """ _append_path(hookenv.charm_dir()) _append_path(os.path.join(hookenv.charm_dir(), 'hooks')) base_module = ...
[ "def", "_relation_module", "(", "role", ",", "interface", ")", ":", "_append_path", "(", "hookenv", ".", "charm_dir", "(", ")", ")", "_append_path", "(", "os", ".", "path", ".", "join", "(", "hookenv", ".", "charm_dir", "(", ")", ",", "'hooks'", ")", "...
35.590909
0.001244
def _lookup_handler(name): """ Look up the implementation of a named handler. Broken out for testing purposes. :param name: The name of the handler to look up. :returns: A factory function for the log handler. """ # Look up and load the handler factory for ep in pkg_resources.iter_en...
[ "def", "_lookup_handler", "(", "name", ")", ":", "# Look up and load the handler factory", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'bark.handler'", ",", "name", ")", ":", "try", ":", "# Load and return the handler factory", "return", "ep", ...
30
0.001616
def module_broadcast(m, broadcast_fn, *args, **kwargs): """ Call given function in all submodules with given parameters """ apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs))
[ "def", "module_broadcast", "(", "m", ",", "broadcast_fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "apply_leaf", "(", "m", ",", "lambda", "x", ":", "module_apply_broadcast", "(", "x", ",", "broadcast_fn", ",", "args", ",", "kwargs", ")", ")...
69.333333
0.009524
def switch_to_table(self, event): """Switches grid to table Parameters ---------- event.newtable: Integer \tTable that the grid is switched to """ newtable = event.newtable no_tabs = self.grid.code_array.shape[2] - 1 if 0 <= newtable <= no_ta...
[ "def", "switch_to_table", "(", "self", ",", "event", ")", ":", "newtable", "=", "event", ".", "newtable", "no_tabs", "=", "self", ".", "grid", ".", "code_array", ".", "shape", "[", "2", "]", "-", "1", "if", "0", "<=", "newtable", "<=", "no_tabs", ":"...
28.176471
0.001345
def _region_code_for_number_from_list(numobj, regions): """Find the region in a list that matches a number""" national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot...
[ "def", "_region_code_for_number_from_list", "(", "numobj", ",", "regions", ")", ":", "national_number", "=", "national_significant_number", "(", "numobj", ")", "for", "region_code", "in", "regions", ":", "# If leading_digits is present, use this. Otherwise, do full", "# valid...
46.421053
0.002222
def is_float(value, min=None, max=None): """ A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative...
[ "def", "is_float", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "(", "min_val", ",", "max_val", ")", "=", "_is_num_param", "(", "(", "'min'", ",", "'max'", ")", ",", "(", "min", ",", "max", ")", ",", "to_float", "=", ...
34.019608
0.00056
def pause(self, movie=None, show=None, episode=None, progress=0.0, **kwargs): """Send the scrobble "pause' action. Use this method when the video is paused. The playback progress will be saved and :code:`Trakt['sync/playback'].get()` can be used to resume the video from this exact posit...
[ "def", "pause", "(", "self", ",", "movie", "=", "None", ",", "show", "=", "None", ",", "episode", "=", "None", ",", "progress", "=", "0.0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "action", "(", "'pause'", ",", "movie", ",", "sh...
25.353535
0.001917
def name(self): """ access to classic name attribute is hidden by this property """ return self.NAME_SEPARATOR.join([super(TaggedVertex, self).name] + self.get_tags_as_list_of_strings())
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "NAME_SEPARATOR", ".", "join", "(", "[", "super", "(", "TaggedVertex", ",", "self", ")", ".", "name", "]", "+", "self", ".", "get_tags_as_list_of_strings", "(", ")", ")" ]
66.666667
0.014851
def LE64(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): '''64-bit field, Little endian encoded''' return UInt64(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range)
[ "def", "LE64", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ",", "full_range", "=", "False", ")", ":", "return", "UInt64", "(", "value", ",", "min_value", "=", "mi...
92
0.010791
def store_property(url, property_name, value): """ Look into database and store `value` under `property_name` in `url`. This is part of the REST API. """ logger.debug( "store_property(): Received property_name=%s value=%s" % ( property_name, value, ), ...
[ "def", "store_property", "(", "url", ",", "property_name", ",", "value", ")", ":", "logger", ".", "debug", "(", "\"store_property(): Received property_name=%s value=%s\"", "%", "(", "property_name", ",", "value", ",", ")", ",", "url", "=", "url", ",", ")", "ri...
23.304348
0.001792
def _resolve_one( self, requirement_set, # type: RequirementSet req_to_install, # type: InstallRequirement ignore_requires_python=False # type: bool ): # type: (...) -> List[InstallRequirement] """Prepare a single requirements file. :return: A list of addi...
[ "def", "_resolve_one", "(", "self", ",", "requirement_set", ",", "# type: RequirementSet", "req_to_install", ",", "# type: InstallRequirement", "ignore_requires_python", "=", "False", "# type: bool", ")", ":", "# type: (...) -> List[InstallRequirement]", "# Tell user what we are ...
39.697479
0.001652
def hydrophobic_atoms(self, all_atoms): """Select all carbon atoms which have only carbons and/or hydrogens as direct neighbors.""" atom_set = [] data = namedtuple('hydrophobic', 'atom orig_atom orig_idx') atm = [a for a in all_atoms if a.atomicnum == 6 and set([natom.GetAtomicNum() for ...
[ "def", "hydrophobic_atoms", "(", "self", ",", "all_atoms", ")", ":", "atom_set", "=", "[", "]", "data", "=", "namedtuple", "(", "'hydrophobic'", ",", "'atom orig_atom orig_idx'", ")", "atm", "=", "[", "a", "for", "a", "in", "all_atoms", "if", "a", ".", "...
59.461538
0.008917
def get(self, name: str, default: Optional[Any]=None) -> Any: """Get a named attribute of this instance, or return the default.""" return self.__dict__.get(name, default)
[ "def", "get", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Optional", "[", "Any", "]", "=", "None", ")", "->", "Any", ":", "return", "self", ".", "__dict__", ".", "get", "(", "name", ",", "default", ")" ]
61.333333
0.021505
def _sql_expand_insert(self, spec, key_prefix = '', col_prefix = ''): """ Expand a dict so it fits in a INSERT clause """ col = list(spec) sql = '(' sql += ', '.join(col_prefix + key for key in col) sql += ') VALUES (' sql += ', '.join('%(' + key_prefix + key + ')...
[ "def", "_sql_expand_insert", "(", "self", ",", "spec", ",", "key_prefix", "=", "''", ",", "col_prefix", "=", "''", ")", ":", "col", "=", "list", "(", "spec", ")", "sql", "=", "'('", "sql", "+=", "', '", ".", "join", "(", "col_prefix", "+", "key", "...
33.285714
0.012526
def mb_filter(fastq, cores): ''' Filters umis with non-ACGT bases Expects formatted fastq files. ''' filter_mb = partial(umi_filter) p = multiprocessing.Pool(cores) chunks = tz.partition_all(10000, read_fastq(fastq)) bigchunks = tz.partition_all(cores, chunks) for bigchunk in bigchunks:...
[ "def", "mb_filter", "(", "fastq", ",", "cores", ")", ":", "filter_mb", "=", "partial", "(", "umi_filter", ")", "p", "=", "multiprocessing", ".", "Pool", "(", "cores", ")", "chunks", "=", "tz", ".", "partition_all", "(", "10000", ",", "read_fastq", "(", ...
33.307692
0.002247
def keystoneclient(request, admin=False): """Returns a client connected to the Keystone backend. Several forms of authentication are supported: * Username + password -> Unscoped authentication * Username + password + tenant id -> Scoped authentication * Unscoped token -> Unscoped authe...
[ "def", "keystoneclient", "(", "request", ",", "admin", "=", "False", ")", ":", "client_version", "=", "VERSIONS", ".", "get_active_version", "(", ")", "user", "=", "request", ".", "user", "token_id", "=", "user", ".", "token", ".", "id", "if", "is_multi_do...
43.090909
0.000344
def create_bodies(self, translate=(0, 1, 0), size=0.1): '''Traverse the bone hierarchy and create physics bodies.''' stack = [('root', 0, self.root['position'] + translate)] while stack: name, depth, end = stack.pop() for child in self.hierarchy.get(name, ()): ...
[ "def", "create_bodies", "(", "self", ",", "translate", "=", "(", "0", ",", "1", ",", "0", ")", ",", "size", "=", "0.1", ")", ":", "stack", "=", "[", "(", "'root'", ",", "0", ",", "self", ".", "root", "[", "'position'", "]", "+", "translate", ")...
38.837838
0.002037
def get(self, key): '''Return the object named by key. Checks each datastore in order.''' value = None for store in self._stores: value = store.get(key) if value is not None: break # add model to lower stores only if value is not None: for store2 in self._stores: i...
[ "def", "get", "(", "self", ",", "key", ")", ":", "value", "=", "None", "for", "store", "in", "self", ".", "_stores", ":", "value", "=", "store", ".", "get", "(", "key", ")", "if", "value", "is", "not", "None", ":", "break", "# add model to lower stor...
24.25
0.012407
def hwvtep_attach_vlan_vid(self, **kwargs): """ Identifies exported VLANs in VXLAN gateway configurations. Args: name (str): overlay_gateway name vlan(str): vlan_id range callback (function): A function executed upon completion of the method...
[ "def", "hwvtep_attach_vlan_vid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "mac", "=", "kwargs", ".", "pop", "(", "'mac'", ")", "vlan", "=", "kwargs", ".", "pop", "(", "'vlan'", ")", "nam...
31.076923
0.002401
def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False, **kwargs): """ Serialize a Python object into a YAML stream with OrderedDict and default_flow_style defaulted to False. If stream is None, return the produced string instead. OrderedDict reference: http://s...
[ "def", "to_yaml", "(", "obj", ",", "stream", "=", "None", ",", "dumper_cls", "=", "yaml", ".", "Dumper", ",", "default_flow_style", "=", "False", ",", "*", "*", "kwargs", ")", ":", "class", "OrderedDumper", "(", "dumper_cls", ")", ":", "pass", "def", "...
33.59375
0.000904
def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]: """ Make sure we have appropriate keys and say if we should write """ to_return = {} should_write = False for keyname, typekind, default in REQUIRED_DATA: if keyname not in data: LOG.debug(f"Defaulted config ...
[ "def", "_ensure_values", "(", "data", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "Any", "]", ",", "bool", "]", ":", "to_return", "=", "{", "}", "should_write", "=", "False", "for", "keyname", ",",...
43.444444
0.001252
def sg_arg_def(**kwargs): r"""Defines command line options Args: **kwargs: key: A name for the option. value : Default value or a tuple of (default value, description). Returns: None For example, ``` # Either of the following two lines will define `--n_epoch` comm...
[ "def", "sg_arg_def", "(", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "type", "(", "v", ")", "is", "tuple", "or", "type", "(", "v", ")", "is", "list", ":", "v", ",", "c", "=", "v", ...
26.939394
0.002172
def rel_path(self, other): """Return a path to "other" relative to this directory. """ # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths ...
[ "def", "rel_path", "(", "self", ",", "other", ")", ":", "# This complicated and expensive method, which constructs relative", "# paths between arbitrary Node.FS objects, is no longer used", "# by SCons itself. It was introduced to store dependency paths", "# in .sconsign files relative to the...
33.358491
0.002198
def optimize(host=None, core_name=None): ''' Search queries fast, but it is a very expensive operation. The ideal process is to run this with a master/slave configuration. Then you can optimize the master, and push the optimized index to the slaves. If you are running a single solr instance, or if ...
[ "def", "optimize", "(", "host", "=", "None", ",", "core_name", "=", "None", ")", ":", "ret", "=", "_get_return_dict", "(", ")", "if", "_get_none_or_value", "(", "core_name", ")", "is", "None", "and", "_check_for_cores", "(", ")", ":", "success", "=", "Tr...
40.142857
0.001489
def read_chunk_header(self): '''Read a single chunk's header. Returns: tuple: 2-item tuple with the size of the content in the chunk and the raw header byte string. Coroutine. ''' # _logger.debug('Reading chunk.') try: chunk_size_hex...
[ "def", "read_chunk_header", "(", "self", ")", ":", "# _logger.debug('Reading chunk.')", "try", ":", "chunk_size_hex", "=", "yield", "from", "self", ".", "_connection", ".", "readline", "(", ")", "except", "ValueError", "as", "error", ":", "raise", "ProtocolError",...
30.90625
0.001961
def wer_201_2018(): r"""Werthmüller 201 pt Hankel filter, 2018. Designed with the empymod add-on ``fdesign``, see https://github.com/empymod/article-fdesign. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_. """ dlf = DigitalFilter('Werthmüller 201', ...
[ "def", "wer_201_2018", "(", ")", ":", "dlf", "=", "DigitalFilter", "(", "'Werthmüller 201',", " ", "wer_201_2018')", "", "dlf", ".", "base", "=", "np", ".", "array", "(", "[", "8.653980893285999343e-04", ",", "9.170399868578506730e-04", ",", "9.717635708540675208e...
56.763077
0.000053
def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, tupleize_cols=No...
[ "def", "to_csv", "(", "self", ",", "path_or_buf", "=", "None", ",", "sep", "=", "\",\"", ",", "na_rep", "=", "''", ",", "float_format", "=", "None", ",", "columns", "=", "None", ",", "header", "=", "True", ",", "index", "=", "True", ",", "index_label...
43.5
0.001108
def _bucket_time(self, event_time): """ The seconds since epoch that represent a computed bucket. An event bucket is the time of the earliest possible event for that `bucket_width`. Example: if `bucket_width = timedelta(minutes=10)`, bucket times will be the number of seconds since epoch at 12...
[ "def", "_bucket_time", "(", "self", ",", "event_time", ")", ":", "event_time", "=", "kronos_time_to_epoch_time", "(", "event_time", ")", "return", "event_time", "-", "(", "event_time", "%", "self", ".", "_bucket_width", ")" ]
41.818182
0.002128
def scan_devices(self, subnet, timeout=None): """ Scan cameras in a range of ips Params: subnet - subnet, i.e: 192.168.1.0/24 if mask not used, assuming mask 24 timeout_sec - timeout in sec Returns: """ # Maximum range from mask ...
[ "def", "scan_devices", "(", "self", ",", "subnet", ",", "timeout", "=", "None", ")", ":", "# Maximum range from mask", "# Format is mask: max_range", "max_range", "=", "{", "16", ":", "256", ",", "24", ":", "256", ",", "25", ":", "128", ",", "27", ":", "...
29.086957
0.000964
def _calculate_states(self, solution, t, step, int_step): """! @brief Caclculates new state of each oscillator in the network. Returns only excitatory state of oscillators. @param[in] solution (solve_type): Type solver of the differential equations. @param[in] t (double): C...
[ "def", "_calculate_states", "(", "self", ",", "solution", ",", "t", ",", "step", ",", "int_step", ")", ":", "next_membrane", "=", "[", "0.0", "]", "*", "self", ".", "_num_osc", "next_active_sodium", "=", "[", "0.0", "]", "*", "self", ".", "_num_osc", "...
59.807692
0.022145
def from_output_script(output_script, cashaddr=True): ''' bytes -> str Convert output script (the on-chain format) to an address There's probably a better way to do this ''' try: if (len(output_script) == len(riemann.network.P2WSH_PREFIX) + 32 and output_script.find(riema...
[ "def", "from_output_script", "(", "output_script", ",", "cashaddr", "=", "True", ")", ":", "try", ":", "if", "(", "len", "(", "output_script", ")", "==", "len", "(", "riemann", ".", "network", ".", "P2WSH_PREFIX", ")", "+", "32", "and", "output_script", ...
39.78125
0.000767
def compile_and_process(self, in_path): """compile a file, save it to the ouput file if the inline flag true""" out_path = self.path_mapping[in_path] if not self.embed: pdebug("[%s::%s] %s -> %s" % ( self.compiler_name, self.name, os.p...
[ "def", "compile_and_process", "(", "self", ",", "in_path", ")", ":", "out_path", "=", "self", ".", "path_mapping", "[", "in_path", "]", "if", "not", "self", ".", "embed", ":", "pdebug", "(", "\"[%s::%s] %s -> %s\"", "%", "(", "self", ".", "compiler_name", ...
32.571429
0.00213
def error_string(mqtt_errno): """Return the error string associated with an mqtt error number.""" if mqtt_errno == MQTT_ERR_SUCCESS: return "No error." elif mqtt_errno == MQTT_ERR_NOMEM: return "Out of memory." elif mqtt_errno == MQTT_ERR_PROTOCOL: return "A network protocol erro...
[ "def", "error_string", "(", "mqtt_errno", ")", ":", "if", "mqtt_errno", "==", "MQTT_ERR_SUCCESS", ":", "return", "\"No error.\"", "elif", "mqtt_errno", "==", "MQTT_ERR_NOMEM", ":", "return", "\"Out of memory.\"", "elif", "mqtt_errno", "==", "MQTT_ERR_PROTOCOL", ":", ...
41.294118
0.001392
def patch_session_send(context, http_filter): """ Monkey patches requests' Session class, if available. Overloads the send method to add tracing and metrics collection. """ if Session is None: return def send(self, *args, **kwargs): id = ensure_utf8(str(uuid.uuid4())) wi...
[ "def", "patch_session_send", "(", "context", ",", "http_filter", ")", ":", "if", "Session", "is", "None", ":", "return", "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "id", "=", "ensure_utf8", "(", "str", "(", "uuid...
33.888889
0.001595
def redirect(to, *args, **kwargs): """ Similar to the Django ``redirect`` shortcut but with altered functionality. If an optional ``params`` argument is provided, the dictionary items will be injected as query parameters on the redirection URL. """ params = kwargs.pop('params', {}) try:...
[ "def", "redirect", "(", "to", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", ".", "pop", "(", "'params'", ",", "{", "}", ")", "try", ":", "to", "=", "reverse", "(", "to", ",", "args", "=", "args", ",", "kwargs", ...
30.545455
0.001443
def _FetchMostRecentGraphSeriesFromTheLegacyDB( label, report_type, token = None ): """Fetches the latest graph-series for a client label from the legacy DB. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. token: ACL token ...
[ "def", "_FetchMostRecentGraphSeriesFromTheLegacyDB", "(", "label", ",", "report_type", ",", "token", "=", "None", ")", ":", "try", ":", "stats_for_label", "=", "aff4", ".", "FACTORY", ".", "Open", "(", "GetAFF4ClientReportsURN", "(", ")", ".", "Add", "(", "lab...
32.4
0.009987
def retry(default=None): """Retry functions after failures""" def decorator(func): """Retry decorator""" @functools.wraps(func) def _wrapper(*args, **kw): for pos in range(1, MAX_RETRIES): try: return func(*args, **kw) exc...
[ "def", "retry", "(", "default", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"Retry decorator\"\"\"", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "fo...
27.333333
0.001473
def save(self): """Serialize this mesh to a string appropriate for disk storage Returns ------- state : dict The state. """ import pickle if self._faces is not None: names = ['_vertices', '_faces'] else: names = ['_vert...
[ "def", "save", "(", "self", ")", ":", "import", "pickle", "if", "self", ".", "_faces", "is", "not", "None", ":", "names", "=", "[", "'_vertices'", ",", "'_faces'", "]", "else", ":", "names", "=", "[", "'_vertices_indexed_by_faces'", "]", "if", "self", ...
31.884615
0.002342
def get_last_week_range(weekday_start="Sunday"): """ Gets the date for the first and the last day of the previous complete week. :param weekday_start: Either "Monday" or "Sunday", indicating the first day of the week. :returns: A tuple containing two date objects, for the first and the last day of the week...
[ "def", "get_last_week_range", "(", "weekday_start", "=", "\"Sunday\"", ")", ":", "today", "=", "date", ".", "today", "(", ")", "# Get the first day of the past complete week.", "start_of_week", "=", "snap_to_beginning_of_week", "(", "today", ",", "weekday_start", ")", ...
50.166667
0.008157
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
[ "def", "loss", "(", "params", ",", "batch", ",", "model_predict", ",", "rng", ")", ":", "inputs", ",", "targets", "=", "batch", "predictions", "=", "model_predict", "(", "inputs", ",", "params", ",", "rng", "=", "rng", ")", "predictions", ",", "targets",...
42.222222
0.020619
def align_texts(source_blocks, target_blocks, params = LanguageIndependent): """Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of...
[ "def", "align_texts", "(", "source_blocks", ",", "target_blocks", ",", "params", "=", "LanguageIndependent", ")", ":", "if", "len", "(", "source_blocks", ")", "!=", "len", "(", "target_blocks", ")", ":", "raise", "ValueError", "(", "\"Source and target texts do no...
43.45
0.013514
def parseArgsPy26(): """ Argument parser for Python 2.6 """ from gsmtermlib.posoptparse import PosOptionParser, Option parser = PosOptionParser(description='Simple script for sending SMS messages') parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number...
[ "def", "parseArgsPy26", "(", ")", ":", "from", "gsmtermlib", ".", "posoptparse", "import", "PosOptionParser", ",", "Option", "parser", "=", "PosOptionParser", "(", "description", "=", "'Simple script for sending SMS messages'", ")", "parser", ".", "add_option", "(", ...
66.933333
0.009823
def get_gene_goterms(self, gene, ancestors=False): """Return all GO terms a particular gene is annotated with. Parameters ---------- gene: str The gene symbol of the gene. ancestors: bool, optional If set to True, also return all ancestor GO terms. ...
[ "def", "get_gene_goterms", "(", "self", ",", "gene", ",", "ancestors", "=", "False", ")", ":", "annotations", "=", "self", ".", "gene_annotations", "[", "gene", "]", "terms", "=", "set", "(", "ann", ".", "term", "for", "ann", "in", "annotations", ")", ...
29.875
0.002026
def list_devices(self): """List devices in the ALDB.""" if self.plm.devices: for addr in self.plm.devices: device = self.plm.devices[addr] if device.address.is_x10: _LOGGING.info('Device: %s %s', device.address.human, ...
[ "def", "list_devices", "(", "self", ")", ":", "if", "self", ".", "plm", ".", "devices", ":", "for", "addr", "in", "self", ".", "plm", ".", "devices", ":", "device", "=", "self", ".", "plm", ".", "devices", "[", "addr", "]", "if", "device", ".", "...
48.210526
0.002141
def update(self, style_sheet=values.unset): """ Update the StyleSheetInstance :param dict style_sheet: The JSON string that describes the style sheet object :returns: Updated StyleSheetInstance :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance ""...
[ "def", "update", "(", "self", ",", "style_sheet", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'StyleSheet'", ":", "serialize", ".", "object", "(", "style_sheet", ")", ",", "}", ")", "payload", "=", "self", ".",...
33.5
0.008065
def server_reboot(host=None, admin_username=None, admin_password=None, module=None): ''' Issues a power-cycle operation on the managed server. This action is similar to pressing the power button on the system's front panel to power down and then powe...
[ "def", "server_reboot", "(", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ",", "module", "=", "None", ")", ":", "return", "__execute_cmd", "(", "'serveraction powercycle'", ",", "host", "=", "host", ",", "admin...
28.575758
0.001026
def nsDefs(self): """Get the namespace of a node """ ret = libxml2mod.xmlNodeGetNsDefs(self._o) if ret is None:return None __tmp = xmlNs(_obj=ret) return __tmp
[ "def", "nsDefs", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNodeGetNsDefs", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "return", "None", "__tmp", "=", "xmlNs", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
32.333333
0.020101
def install_hg(path): """ Install hook in Mercurial repository. """ hook = op.join(path, 'hgrc') if not op.isfile(hook): open(hook, 'w+').close() c = ConfigParser() c.readfp(open(hook, 'r')) if not c.has_section('hooks'): c.add_section('hooks') if not c.has_option('hooks', ...
[ "def", "install_hg", "(", "path", ")", ":", "hook", "=", "op", ".", "join", "(", "path", ",", "'hgrc'", ")", "if", "not", "op", ".", "isfile", "(", "hook", ")", ":", "open", "(", "hook", ",", "'w+'", ")", ".", "close", "(", ")", "c", "=", "Co...
28.944444
0.001859
def roger_root(word, max_length=5, zero_pad=True): """Return the Roger Root code for a word. This is a wrapper for :py:meth:`RogerRoot.encode`. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 5) of the code to return zero_...
[ "def", "roger_root", "(", "word", ",", "max_length", "=", "5", ",", "zero_pad", "=", "True", ")", ":", "return", "RogerRoot", "(", ")", ".", "encode", "(", "word", ",", "max_length", ",", "zero_pad", ")" ]
21.90625
0.001366
def pad_batch(batch, max_len=0, type="int"): """Pad the batch into matrix :param batch: The data for padding. :type batch: list of word index sequences :param max_len: Max length of sequence of padding. :type max_len: int :param type: mask value type. :type type: str :return: The padded...
[ "def", "pad_batch", "(", "batch", ",", "max_len", "=", "0", ",", "type", "=", "\"int\"", ")", ":", "batch_size", "=", "len", "(", "batch", ")", "max_sent_len", "=", "int", "(", "np", ".", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", ...
35.433333
0.000916
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): r"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a DSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with a...
[ "def", "loads", "(", "s", ",", "encoding", "=", "None", ",", "cls", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "object_pairs_hook", "=", "None", ...
49
0.000678
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): """Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of as...
[ "def", "add_subassistants_to", "(", "cls", ",", "parser", ",", "assistant_tuple", ",", "level", ",", "alias", "=", "None", ")", ":", "name", "=", "alias", "or", "assistant_tuple", "[", "0", "]", ".", "name", "p", "=", "parser", ".", "add_parser", "(", ...
50.571429
0.008316
def build_package_configs(project_name, version=None, copyright=None, doxygen_xml_dirname=None): """Builds a `dict` of Sphinx configurations useful for the ``doc/conf.py`` files of individual LSST Stack packages. The ``doc/conf.p...
[ "def", "build_package_configs", "(", "project_name", ",", "version", "=", "None", ",", "copyright", "=", "None", ",", "doxygen_xml_dirname", "=", "None", ")", ":", "c", "=", "{", "}", "c", "=", "_insert_common_sphinx_configs", "(", "c", ",", "project_name", ...
27.721739
0.000303
def gzscore(x): """Geometric standard (Z) score. Parameters ---------- x : array_like Array of raw values Returns ------- gzscore : array_like Array of geometric z-scores (same shape as x) Notes ----- Geometric Z-scores are better measures of dispersion than ar...
[ "def", "gzscore", "(", "x", ")", ":", "from", "scipy", ".", "stats", "import", "gmean", "# Geometric mean", "geo_mean", "=", "gmean", "(", "x", ")", "# Geometric standard deviation", "gstd", "=", "np", ".", "exp", "(", "np", ".", "sqrt", "(", "np", ".", ...
26
0.000756
def __remove_method(m: lmap.Map, key: T) -> lmap.Map: """Swap the methods atom to remove method with key.""" return m.dissoc(key)
[ "def", "__remove_method", "(", "m", ":", "lmap", ".", "Map", ",", "key", ":", "T", ")", "->", "lmap", ".", "Map", ":", "return", "m", ".", "dissoc", "(", "key", ")" ]
47.666667
0.013793
def getH264V4l2(verbose=False): """Find all V4l2 cameras with H264 encoding, and returns a list of tuples with .. (device file, device name), e.g. ("/dev/video2", "HD Pro Webcam C920 (/dev/video2)") """ import glob from subprocess import Popen, PIPE cams=[] for device in glob.glob...
[ "def", "getH264V4l2", "(", "verbose", "=", "False", ")", ":", "import", "glob", "from", "subprocess", "import", "Popen", ",", "PIPE", "cams", "=", "[", "]", "for", "device", "in", "glob", ".", "glob", "(", "\"/sys/class/video4linux/*\"", ")", ":", "devname...
30.333333
0.016859
def service(url, api_key, help_url = None): '''Marks a function as having been published and causes all invocations to go to the remote operationalized service. >>> @service(url, api_key) >>> def f(a, b): >>> pass ''' def do_publish(func): return published(url, api_key, help_url, func, None) re...
[ "def", "service", "(", "url", ",", "api_key", ",", "help_url", "=", "None", ")", ":", "def", "do_publish", "(", "func", ")", ":", "return", "published", "(", "url", ",", "api_key", ",", "help_url", ",", "func", ",", "None", ")", "return", "do_publish" ...
29.545455
0.01194
def get(self, guild_id): """ Returns a player from the cache, or creates one if it does not exist. """ if guild_id not in self._players: p = self._player(lavalink=self.lavalink, guild_id=guild_id) self._players[guild_id] = p return self._players[guild_id]
[ "def", "get", "(", "self", ",", "guild_id", ")", ":", "if", "guild_id", "not", "in", "self", ".", "_players", ":", "p", "=", "self", ".", "_player", "(", "lavalink", "=", "self", ".", "lavalink", ",", "guild_id", "=", "guild_id", ")", "self", ".", ...
43.428571
0.009677
def sort(imports, separate=True, import_before_from=True, **classify_kwargs): """Sort import objects into groups. :param list imports: FromImport / ImportImport objects :param bool separate: Whether to classify and return separate segments of imports based on classification. :param bool import_...
[ "def", "sort", "(", "imports", ",", "separate", "=", "True", ",", "import_before_from", "=", "True", ",", "*", "*", "classify_kwargs", ")", ":", "if", "separate", ":", "def", "classify_func", "(", "obj", ")", ":", "return", "classify_import", "(", "obj", ...
27.938272
0.000427
def close(self): """ Closes pipe :return: """ resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) self.session.delete(resource)
[ "def", "close", "(", "self", ")", ":", "resource", "=", "ResourceLocator", "(", "CommandShell", ".", "ShellResource", ")", "resource", ".", "add_selector", "(", "'ShellId'", ",", "self", ".", "__shell_id", ")", "self", ".", "session", ".", "delete", "(", "...
28.625
0.008475
def merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6} >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}} >>> c = merge(a, b) >>> from pprint import pprint; pprint(c) {'a': 1, 'b': {1...
[ "def", "merge", "(", "a", ",", "b", ")", ":", "assert", "quacks_like_dict", "(", "a", ")", ",", "quacks_like_dict", "(", "b", ")", "dst", "=", "a", ".", "copy", "(", ")", "stack", "=", "[", "(", "dst", ",", "b", ")", "]", "while", "stack", ":",...
36.966667
0.000879
def writeHeader(self, msg): """write header: [8bit][16bit] [protocol_version][msg_length] """ header = bytearray([self.protocol_version]) #protocol version 1.0 header.extend(struct.pack('<H', len(msg))) msg = header + msg return msg
[ "def", "writeHeader", "(", "self", ",", "msg", ")", ":", "header", "=", "bytearray", "(", "[", "self", ".", "protocol_version", "]", ")", "#protocol version 1.0", "header", ".", "extend", "(", "struct", ".", "pack", "(", "'<H'", ",", "len", "(", "msg", ...
20
0.047809
def transform(src, dst, converter, overwrite=False, stream=True, chunksize=1024**2, **kwargs): """ A file stream transform IO utility function. :param src: original file path :param dst: destination file path :param converter: binary content converter function :param overwrite: de...
[ "def", "transform", "(", "src", ",", "dst", ",", "converter", ",", "overwrite", "=", "False", ",", "stream", "=", "True", ",", "chunksize", "=", "1024", "**", "2", ",", "*", "*", "kwargs", ")", ":", "if", "not", "overwrite", ":", "# pragma: no cover", ...
36.742857
0.000758
def script_run(trun, script): """Execute a script or testcase""" if trun["conf"]["VERBOSE"]: cij.emph("rnr:script:run { script: %s }" % script) cij.emph("rnr:script:run:evars: %s" % script["evars"]) launchers = { ".py": "python", ".sh": "source" } ext = os.path.spl...
[ "def", "script_run", "(", "trun", ",", "script", ")", ":", "if", "trun", "[", "\"conf\"", "]", "[", "\"VERBOSE\"", "]", ":", "cij", ".", "emph", "(", "\"rnr:script:run { script: %s }\"", "%", "script", ")", "cij", ".", "emph", "(", "\"rnr:script:run:evars: %...
27.919355
0.001674
def _secant2_inner(value_and_gradients_function, initial_args, val_0, val_c, f_lim, sufficient_decrease_param, curvature_param): """Helper function for secant square.""" # Apply the `update` function on...
[ "def", "_secant2_inner", "(", "value_and_gradients_function", ",", "initial_args", ",", "val_0", ",", "val_c", ",", "f_lim", ",", "sufficient_decrease_param", ",", "curvature_param", ")", ":", "# Apply the `update` function on active branch members to squeeze their", "# bracket...
38.870968
0.009713
def find_gui_and_backend(gui=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','...
[ "def", "find_gui_and_backend", "(", "gui", "=", "None", ")", ":", "import", "matplotlib", "if", "gui", "and", "gui", "!=", "'auto'", ":", "# select backend based on requested gui", "backend", "=", "backends", "[", "gui", "]", "else", ":", "backend", "=", "matp...
30.56
0.001269
def find_devices (self, lookup_names=True, duration=8, flush_cache=True): """ find_devices (lookup_names=True, service_name=None, duration=8, flush_cache=True) Call this method to initiate the device discovery process lookup_names - set to...
[ "def", "find_devices", "(", "self", ",", "lookup_names", "=", "True", ",", "duration", "=", "8", ",", "flush_cache", "=", "True", ")", ":", "if", "self", ".", "is_inquiring", ":", "raise", "BluetoothError", "(", "EBUSY", ",", "\"Already inquiring!\"", ")", ...
33.534483
0.00999
def run(self, *args): """ Run a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID i...
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "volumes", ":", "volumes", "=", "\" --bind \"", "+", "\" --bind \"", ".", "join", "(", "self", ".", "volumes", ")", "else", ":", "volumes", "=", "\"\"", "self", ".", "_print", ...
33.764706
0.011864
def autorange(self, analyte='total_counts', gwin=5, swin=3, win=30, on_mult=[1., 1.], off_mult=[1., 1.5], ploterrs=True, transform='log', **kwargs): """ Automatically separates signal and background data regions. Automatically detect signal and background reg...
[ "def", "autorange", "(", "self", ",", "analyte", "=", "'total_counts'", ",", "gwin", "=", "5", ",", "swin", "=", "3", ",", "win", "=", "30", ",", "on_mult", "=", "[", "1.", ",", "1.", "]", ",", "off_mult", "=", "[", "1.", ",", "1.5", "]", ",", ...
45.565657
0.001519
def _insert_options(self, menu): """Add configuration options to menu.""" menu.append(Gtk.SeparatorMenuItem()) menu.append(self._menuitem( _('Mount disc image'), self._icons.get_icon('losetup', Gtk.IconSize.MENU), run_bg(lambda _: self._losetup()) )) ...
[ "def", "_insert_options", "(", "self", ",", "menu", ")", ":", "menu", ".", "append", "(", "Gtk", ".", "SeparatorMenuItem", "(", ")", ")", "menu", ".", "append", "(", "self", ".", "_menuitem", "(", "_", "(", "'Mount disc image'", ")", ",", "self", ".", ...
38.241379
0.001759
def process_input_graph(func): """Decorator, ensuring first argument is a networkx graph object. If the first arg is a dict {node: succs}, a networkx graph equivalent to the dict will be send in place of it.""" @wraps(func) def wrapped_func(*args, **kwargs): input_graph = args[0] if ...
[ "def", "process_input_graph", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "input_graph", "=", "args", "[", "0", "]", "if", "isinstance", "(", "input_graph", ",", "...
40.571429
0.001721
def checkBinary(name, bindir=None): """ Checks for the given binary in the places, defined by the environment variables SUMO_HOME and <NAME>_BINARY. """ if name == "sumo-gui": envName = "GUISIM_BINARY" else: envName = name.upper() + "_BINARY" env = os.environ join = os.pa...
[ "def", "checkBinary", "(", "name", ",", "bindir", "=", "None", ")", ":", "if", "name", "==", "\"sumo-gui\"", ":", "envName", "=", "\"GUISIM_BINARY\"", "else", ":", "envName", "=", "name", ".", "upper", "(", ")", "+", "\"_BINARY\"", "env", "=", "os", "....
31.076923
0.0012
def clean(ctx, dry_run=False): """Cleanup temporary dirs/files to regain a clean state.""" # -- VARIATION-POINT 1: Allow user to override in configuration-file directories = ctx.clean.directories files = ctx.clean.files # -- VARIATION-POINT 2: Allow user to add more files/dirs to be removed. ex...
[ "def", "clean", "(", "ctx", ",", "dry_run", "=", "False", ")", ":", "# -- VARIATION-POINT 1: Allow user to override in configuration-file", "directories", "=", "ctx", ".", "clean", ".", "directories", "files", "=", "ctx", ".", "clean", ".", "files", "# -- VARIATION-...
39.166667
0.001385
def format_page(self, page): """ Banana banana """ self.formatting_page_signal(self, page) return self._format_page(page)
[ "def", "format_page", "(", "self", ",", "page", ")", ":", "self", ".", "formatting_page_signal", "(", "self", ",", "page", ")", "return", "self", ".", "_format_page", "(", "page", ")" ]
26
0.012422
def has_access_api(f): """ Use this decorator to enable granular security permissions to your API methods. Permissions will be associated to a role, and roles are associated to users. By default the permission's name is the methods name. this will return a message and HTTP 401 is c...
[ "def", "has_access_api", "(", "f", ")", ":", "if", "hasattr", "(", "f", ",", "'_permission_name'", ")", ":", "permission_str", "=", "f", ".", "_permission_name", "else", ":", "permission_str", "=", "f", ".", "__name__", "def", "wraps", "(", "self", ",", ...
33.536585
0.00212
def insert_text(self, s, from_undo=False): """Natural numbers only.""" return super().insert_text( ''.join(c for c in s if c in '0123456789'), from_undo )
[ "def", "insert_text", "(", "self", ",", "s", ",", "from_undo", "=", "False", ")", ":", "return", "super", "(", ")", ".", "insert_text", "(", "''", ".", "join", "(", "c", "for", "c", "in", "s", "if", "c", "in", "'0123456789'", ")", ",", "from_undo",...
32.833333
0.009901
def check_coverage(): """Checks if the coverage is 100%.""" with lcd(settings.LOCAL_COVERAGE_PATH): total_line = local('grep -n Total index.html', capture=True) match = re.search(r'^(\d+):', total_line) total_line_number = int(match.groups()[0]) percentage_line_number = total_lin...
[ "def", "check_coverage", "(", ")", ":", "with", "lcd", "(", "settings", ".", "LOCAL_COVERAGE_PATH", ")", ":", "total_line", "=", "local", "(", "'grep -n Total index.html'", ",", "capture", "=", "True", ")", "match", "=", "re", ".", "search", "(", "r'^(\\d+):...
44.4
0.001103
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions): """ Concatenate a sequence of datasets along a new or existing dimension """ from .dataset import Dataset if compat not in ['equals', 'identical']: raise ValueError("compat=%r invalid: must be 'equals' " ...
[ "def", "_dataset_concat", "(", "datasets", ",", "dim", ",", "data_vars", ",", "coords", ",", "compat", ",", "positions", ")", ":", "from", ".", "dataset", "import", "Dataset", "if", "compat", "not", "in", "[", "'equals'", ",", "'identical'", "]", ":", "r...
41.45098
0.000231
def send_handle_delete_request(self, **args): ''' Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A...
[ "def", "send_handle_delete_request", "(", "self", ",", "*", "*", "args", ")", ":", "# Check if we have write access at all:", "if", "not", "self", ".", "__has_write_access", ":", "raise", "HandleAuthenticationError", "(", "msg", "=", "self", ".", "__no_auth_message", ...
38.903226
0.002426
def update(self, **kwargs): """Updates global configuration settings with given values. First checks if given configuration values differ from current values. If any of the configuration values changed, generates a change event. Currently we generate change event for any configuration c...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Update inherited configurations", "super", "(", "CommonConf", ",", "self", ")", ".", "update", "(", "*", "*", "kwargs", ")", "conf_changed", "=", "False", "# Validate given configurations and ch...
41.827586
0.001612
def header_to_id(header): """ We can receive headers in the following formats: 1. unsigned base 16 hex string of variable length 2. [eventual] :param header: the header to analyze, validate and convert (if needed) :return: a valid ID to be used internal to the tracer """ if not isin...
[ "def", "header_to_id", "(", "header", ")", ":", "if", "not", "isinstance", "(", "header", ",", "string_types", ")", ":", "return", "BAD_ID", "try", ":", "# Test that header is truly a hexadecimal value before we try to convert", "int", "(", "header", ",", "16", ")",...
28.851852
0.002484
def _process_virtual(self, mod, module_name, virtual_func='__virtual__'): ''' Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. i...
[ "def", "_process_virtual", "(", "self", ",", "mod", ",", "module_name", ",", "virtual_func", "=", "'__virtual__'", ")", ":", "# The __virtual__ function will return either a True or False value.", "# If it returns a True value it can also set a module level attribute", "# named __vir...
49.455357
0.001239
def shapeRef_to_iriref(self, ref: ShExDocParser.ShapeRefContext) -> ShExJ.IRIREF: """ shapeRef: ATPNAME_NS | ATPNAME_LN | '@' shapeExprLabel """ if ref.ATPNAME_NS(): return ShExJ.IRIREF(self._lookup_prefix(ref.ATPNAME_NS().getText()[1:])) elif ref.ATPNAME_LN(): prefix, lo...
[ "def", "shapeRef_to_iriref", "(", "self", ",", "ref", ":", "ShExDocParser", ".", "ShapeRefContext", ")", "->", "ShExJ", ".", "IRIREF", ":", "if", "ref", ".", "ATPNAME_NS", "(", ")", ":", "return", "ShExJ", ".", "IRIREF", "(", "self", ".", "_lookup_prefix",...
59.777778
0.009158
def Kdp(scatterer): """ Specific differential phase (K_dp) for the current setup. Args: scatterer: a Scatterer instance. Returns: K_dp [deg/km]. NOTE: This only returns the correct value if the particle diameter and wavelength are given in [mm]. The scatterer object should be ...
[ "def", "Kdp", "(", "scatterer", ")", ":", "if", "(", "scatterer", ".", "thet0", "!=", "scatterer", ".", "thet", ")", "or", "(", "scatterer", ".", "phi0", "!=", "scatterer", ".", "phi", ")", ":", "raise", "ValueError", "(", "\"A forward scattering geometry ...
32.363636
0.010914
def my_init(self): """ Method automatically called from base class constructor. """ self._start_time = time.time() self._stats = {} self._stats_lock = threading.Lock()
[ "def", "my_init", "(", "self", ")", ":", "self", ".", "_start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_stats", "=", "{", "}", "self", ".", "_stats_lock", "=", "threading", ".", "Lock", "(", ")" ]
29.857143
0.009302
def check_surface_validity(cls, edges): """ Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by...
[ "def", "check_surface_validity", "(", "cls", ",", "edges", ")", ":", "# extract coordinates of surface boundary (as defined from edges)", "full_boundary", "=", "[", "]", "left_boundary", "=", "[", "]", "right_boundary", "=", "[", "]", "for", "i", "in", "range", "(",...
40.22449
0.000991
def initrepo(repopath, bare, shared): """ Initialize an activegit repo. Default makes base shared repo that should be cloned for users """ ag = activegit.ActiveGit(repopath, bare=bare, shared=shared)
[ "def", "initrepo", "(", "repopath", ",", "bare", ",", "shared", ")", ":", "ag", "=", "activegit", ".", "ActiveGit", "(", "repopath", ",", "bare", "=", "bare", ",", "shared", "=", "shared", ")" ]
41.8
0.00939
def category(self, value): """ Setter for **self.__category** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "cat...
[ "def", "category", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"category\"", ",", "value", ...
29.583333
0.008197
def print_plans(self, plans): """Print method for plans. """ for plan in plans: print('Name: {} "{}" Price: {} USD'.format(plan.name, plan.slug, plan.pricing['hour'])) self.pprint(plan.specs) print('\n')
[ "def", "print_plans", "(", "self", ",", "plans", ")", ":", "for", "plan", "in", "plans", ":", "print", "(", "'Name: {} \"{}\" Price: {} USD'", ".", "format", "(", "plan", ".", "name", ",", "plan", ".", "slug", ",", "plan", ".", "pricing", "[", "'hour'", ...
36.714286
0.011407
def create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None): """Create a model run object with the given list of arguments. The initial state of the object is RUNNING. Raises ValueError if given arguments are invalid. Parameters ------...
[ "def", "create_object", "(", "self", ",", "name", ",", "experiment_id", ",", "model_id", ",", "argument_defs", ",", "arguments", "=", "None", ",", "properties", "=", "None", ")", ":", "# Create a new object identifier.", "identifier", "=", "str", "(", "uuid", ...
41.029851
0.002487
def _forecast_model(self,beta,h): """ Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states ...
[ "def", "_forecast_model", "(", "self", ",", "beta", ",", "h", ")", ":", "T", ",", "Z", ",", "R", ",", "Q", ",", "H", "=", "self", ".", "_ss_matrices", "(", "beta", ")", "return", "univariate_kalman_fcst", "(", "self", ".", "data", ",", "Z", ",", ...
25.789474
0.023622
def recoverHash(self, message_hash, vrs=None, signature=None): ''' Get the address of the account that signed the message with the given hash. You must specify exactly one of: vrs or signature :param message_hash: the hash of the message that you want to verify :type message_has...
[ "def", "recoverHash", "(", "self", ",", "message_hash", ",", "vrs", "=", "None", ",", "signature", "=", "None", ")", ":", "hash_bytes", "=", "HexBytes", "(", "message_hash", ")", "if", "len", "(", "hash_bytes", ")", "!=", "32", ":", "raise", "ValueError"...
58.849315
0.001145
def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None): ''' upload a directory using Aspera ''' check_io_access(directory, os.R_OK) return self._queue_task(bucket, [FilePair(key, directory)], transfer_config, subscribers, enumAs...
[ "def", "upload_directory", "(", "self", ",", "directory", ",", "bucket", ",", "key", ",", "transfer_config", "=", "None", ",", "subscribers", "=", "None", ")", ":", "check_io_access", "(", "directory", ",", "os", ".", "R_OK", ")", "return", "self", ".", ...
67
0.011799
def createLocationEncoder(t, w=15): """ A default coordinate encoder for encoding locations into sparse distributed representations. """ encoder = CoordinateEncoder(name="positionEncoder", n=t.l6CellCount, w=w) return encoder
[ "def", "createLocationEncoder", "(", "t", ",", "w", "=", "15", ")", ":", "encoder", "=", "CoordinateEncoder", "(", "name", "=", "\"positionEncoder\"", ",", "n", "=", "t", ".", "l6CellCount", ",", "w", "=", "w", ")", "return", "encoder" ]
33
0.016878
def resize_volume(self, volumeObj, sizeInGb, bsize=1000): """ Resize a volume to new GB size, must be larger than original. :param volumeObj: ScaleIO Volume Object :param sizeInGb: New size in GB (have to be larger than original) :param bsize: 1000 :return: POST request r...
[ "def", "resize_volume", "(", "self", ",", "volumeObj", ",", "sizeInGb", ",", "bsize", "=", "1000", ")", ":", "current_vol", "=", "self", ".", "get_volume_by_id", "(", "volumeObj", ".", "id", ")", "if", "current_vol", ".", "size_kb", ">", "(", "sizeInGb", ...
49.722222
0.008772
def _get_dir_list(load): ''' Get a list of all directories on the master ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if 'saltenv' not in load or load['saltenv'] not in envs(): return [] ret = set() for repo in init(): repo['...
[ "def", "_get_dir_list", "(", "load", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "if", "'saltenv'", "not", "in", "load", "or", "load", "[", "'saltenv'", "]", "not", "in", ...
35.096774
0.000894