text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def prepare(self): """Un-serialize data from data attribute and add instance_id key if necessary :return: None """ # Maybe the Brok is a old daemon one or was already prepared # if so, the data is already ok if hasattr(self, 'prepared') and not self.prepared: ...
[ "def", "prepare", "(", "self", ")", ":", "# Maybe the Brok is a old daemon one or was already prepared", "# if so, the data is already ok", "if", "hasattr", "(", "self", ",", "'prepared'", ")", "and", "not", "self", ".", "prepared", ":", "self", ".", "data", "=", "u...
38.833333
14.5
def getAllReadGroupSets(self): """ Returns all readgroup sets on the server. """ for dataset in self.getAllDatasets(): iterator = self._client.search_read_group_sets( dataset_id=dataset.id) for readGroupSet in iterator: yield readGr...
[ "def", "getAllReadGroupSets", "(", "self", ")", ":", "for", "dataset", "in", "self", ".", "getAllDatasets", "(", ")", ":", "iterator", "=", "self", ".", "_client", ".", "search_read_group_sets", "(", "dataset_id", "=", "dataset", ".", "id", ")", "for", "re...
35.333333
5.777778
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True): ''' Create and attach volumes to created node ''' if call != 'action': raise SaltCloudSystemExit( 'The create_attach_volumes action must be called with ' '-a or --action.' ) if 'instance...
[ "def", "create_attach_volumes", "(", "name", ",", "kwargs", ",", "call", "=", "None", ",", "wait_to_finish", "=", "True", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_attach_volumes action must be called with '", "...
33.821429
19.345238
def cos_c(self, N=None): # percent=0.9, """Return the squared cosines for each column.""" if not hasattr(self, 'G') or self.G.shape[1] < self.rank: self.fs_c(N=self.rank) # generate self.dc = norm(self.G, axis=1)**2 # cheaper than diag(self.G.dot(self.G.T))? return apply_along_axis(lambda _: _/self.dc,...
[ "def", "cos_c", "(", "self", ",", "N", "=", "None", ")", ":", "# percent=0.9,", "if", "not", "hasattr", "(", "self", ",", "'G'", ")", "or", "self", ".", "G", ".", "shape", "[", "1", "]", "<", "self", ".", "rank", ":", "self", ".", "fs_c", "(", ...
37
15.333333
def halt(self): """Halt a sampling running in another thread.""" self.status = 'halt' # The _halt method is called by _loop. if hasattr( self, '_sampling_thread') and self._sampling_thread.isAlive(): print_('Waiting for current iteration to finish...') ...
[ "def", "halt", "(", "self", ")", ":", "self", ".", "status", "=", "'halt'", "# The _halt method is called by _loop.", "if", "hasattr", "(", "self", ",", "'_sampling_thread'", ")", "and", "self", ".", "_sampling_thread", ".", "isAlive", "(", ")", ":", "print_",...
42.333333
16.777778
def before(func): """ Run a function before the handler is invoked, is passed the event & context and must return an event & context too. Usage:: >>> # to create a reusable decorator >>> @before ... def print_request_id(event, context): ... print(context.aws_request...
[ "def", "before", "(", "func", ")", ":", "class", "BeforeDecorator", "(", "LambdaDecorator", ")", ":", "def", "before", "(", "self", ",", "event", ",", "context", ")", ":", "return", "func", "(", "event", ",", "context", ")", "return", "BeforeDecorator" ]
29.419355
13.741935
def ask_overwrite(dest): """Check if file *dest* exists. If 'True', asks if the user wants to overwrite it (just remove the file for later overwrite). """ msg = "File '{}' already exists. Overwrite file?".format(dest) if os.path.exists(dest): if yes_no_query(msg): os.remove(dest...
[ "def", "ask_overwrite", "(", "dest", ")", ":", "msg", "=", "\"File '{}' already exists. Overwrite file?\"", ".", "format", "(", "dest", ")", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "if", "yes_no_query", "(", "msg", ")", ":", "os", ...
33.909091
15.909091
def wiggleFileHandleToProtocol(self, fileHandle): """ Return a continuous protocol object satsifiying the given query parameters from the given wiggle file handle. """ for line in fileHandle: self.readWiggleLine(line) return self._data
[ "def", "wiggleFileHandleToProtocol", "(", "self", ",", "fileHandle", ")", ":", "for", "line", "in", "fileHandle", ":", "self", ".", "readWiggleLine", "(", "line", ")", "return", "self", ".", "_data" ]
36
10
def get_client_kwargs(self, path): """ Get base keyword arguments for client for a specific path. Args: path (str): Absolute path or URL. Returns: dict: client args """ container, obj = self.split_locator(path) kwargs = dict(conta...
[ "def", "get_client_kwargs", "(", "self", ",", "path", ")", ":", "container", ",", "obj", "=", "self", ".", "split_locator", "(", "path", ")", "kwargs", "=", "dict", "(", "container", "=", "container", ")", "if", "obj", ":", "kwargs", "[", "'obj'", "]",...
24.375
15.375
def load_adjustment_values(self, c): """load adjustment values for auto shape types in self""" # retrieve auto shape types in const_name order -------- for mast in self: # retriev adj vals for this auto shape type -------- c.execute( ' SELECT name, val\n'...
[ "def", "load_adjustment_values", "(", "self", ",", "c", ")", ":", "# retrieve auto shape types in const_name order --------", "for", "mast", "in", "self", ":", "# retriev adj vals for this auto shape type --------", "c", ".", "execute", "(", "' SELECT name, val\\n'", "' F...
42.615385
12.692308
def _from_string(cls, serialized): """ Return a CourseLocator parsing the given serialized string :param serialized: matches the string to a CourseLocator """ parse = cls.parse_url(serialized) if parse['version_guid']: parse['version_guid'] = cls.as_object_id...
[ "def", "_from_string", "(", "cls", ",", "serialized", ")", ":", "parse", "=", "cls", ".", "parse_url", "(", "serialized", ")", "if", "parse", "[", "'version_guid'", "]", ":", "parse", "[", "'version_guid'", "]", "=", "cls", ".", "as_object_id", "(", "par...
36.727273
18.909091
def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT): # type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum] """ Create an enum config :param enum_type: :param help_string: :param default: :return: """ # noinspection Py...
[ "def", "create_enum", "(", "enum_type", ",", "help_string", "=", "NO_HELP", ",", "default", "=", "NO_DEFAULT", ")", ":", "# type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum]", "# noinspection PyTypeChecker", "return", "ParamEnum", "(", "help_string", "=", "...
30.133333
14.533333
def value(self, t): """See Schedule.value""" fraction = min(float(t) / max(1, self.schedule_timesteps), 1.0) return self.initial_p + fraction * (self.final_p - self.initial_p)
[ "def", "value", "(", "self", ",", "t", ")", ":", "fraction", "=", "min", "(", "float", "(", "t", ")", "/", "max", "(", "1", ",", "self", ".", "schedule_timesteps", ")", ",", "1.0", ")", "return", "self", ".", "initial_p", "+", "fraction", "*", "(...
49
21.5
def get_cluster_view(p): """get ipython running""" from cluster_helper import cluster as ipc return ipc.cluster_view(p['scheduler'], p['queue'], p['num_jobs'], p['cores_per_job'], start_wait=p['timeout'], extra_params={"resources": p['resources'], "mem": p['mem'], "tag": p['tag'], "run_local": False})
[ "def", "get_cluster_view", "(", "p", ")", ":", "from", "cluster_helper", "import", "cluster", "as", "ipc", "return", "ipc", ".", "cluster_view", "(", "p", "[", "'scheduler'", "]", ",", "p", "[", "'queue'", "]", ",", "p", "[", "'num_jobs'", "]", ",", "p...
77.75
48.5
def get_attrs(obj): """Helper for dir2 implementation.""" if not hasattr(obj, '__dict__'): return [] # slots only proxy_type = types.MappingProxyType if six.PY3 else types.DictProxyType if not isinstance(obj.__dict__, (dict, proxy_type)): print(type(obj.__dict__), obj) raise Typ...
[ "def", "get_attrs", "(", "obj", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "return", "[", "]", "# slots only", "proxy_type", "=", "types", ".", "MappingProxyType", "if", "six", ".", "PY3", "else", "types", ".", "DictProxyT...
44.333333
14.444444
def delay_2(year): '''Check for delay in start of new year due to length of adjacent years''' last = delay_1(year - 1) present = delay_1(year) next_ = delay_1(year + 1) if next_ - present == 356: return 2 elif present - last == 382: return 1 else: return 0
[ "def", "delay_2", "(", "year", ")", ":", "last", "=", "delay_1", "(", "year", "-", "1", ")", "present", "=", "delay_1", "(", "year", ")", "next_", "=", "delay_1", "(", "year", "+", "1", ")", "if", "next_", "-", "present", "==", "356", ":", "retur...
22.923077
22.923077
def get_poll_option_formset(self, formset_class): """ Returns an instance of the poll option formset to be used in the view. """ if self.request.forum_permission_handler.can_create_polls( self.get_forum(), self.request.user, ): return formset_class(**self.get_poll_option_...
[ "def", "get_poll_option_formset", "(", "self", ",", "formset_class", ")", ":", "if", "self", ".", "request", ".", "forum_permission_handler", ".", "can_create_polls", "(", "self", ".", "get_forum", "(", ")", ",", "self", ".", "request", ".", "user", ",", ")"...
55.333333
17.666667
def _write_service_config(self): """ Will write the config out to disk. """ with open(self.config_path, 'w') as output: output.write(json.dumps(self.data, sort_keys=True, indent=4))
[ "def", "_write_service_config", "(", "self", ")", ":", "with", "open", "(", "self", ".", "config_path", ",", "'w'", ")", "as", "output", ":", "output", ".", "write", "(", "json", ".", "dumps", "(", "self", ".", "data", ",", "sort_keys", "=", "True", ...
36.666667
9
def pop_first_arg(argv): """ find first positional arg (does not start with -), take it out of array and return it separately returns (arg, array) """ for arg in argv: if not arg.startswith('-'): argv.remove(arg) return (arg, argv) return (None, argv)
[ "def", "pop_first_arg", "(", "argv", ")", ":", "for", "arg", "in", "argv", ":", "if", "not", "arg", ".", "startswith", "(", "'-'", ")", ":", "argv", ".", "remove", "(", "arg", ")", "return", "(", "arg", ",", "argv", ")", "return", "(", "None", ",...
27.090909
17.818182
def __flush_buffer(self): """Flush the buffer contents out to a chunk. """ self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = StringIO()
[ "def", "__flush_buffer", "(", "self", ")", ":", "self", ".", "__flush_data", "(", "self", ".", "_buffer", ".", "getvalue", "(", ")", ")", "self", ".", "_buffer", ".", "close", "(", ")", "self", ".", "_buffer", "=", "StringIO", "(", ")" ]
33.166667
7.333333
def set_sync_info(self, name, mtime, size): """Store mtime/size when this resource was last synchronized with remote.""" if not self.is_local(): return self.peer.set_sync_info(name, mtime, size) return self.cur_dir_meta.set_sync_info(name, mtime, size)
[ "def", "set_sync_info", "(", "self", ",", "name", ",", "mtime", ",", "size", ")", ":", "if", "not", "self", ".", "is_local", "(", ")", ":", "return", "self", ".", "peer", ".", "set_sync_info", "(", "name", ",", "mtime", ",", "size", ")", "return", ...
56.8
11.6
def disassociate_health_monitor(self, pool, health_monitor): """Disassociate specified load balancer health monitor and pool.""" path = (self.disassociate_pool_health_monitors_path % {'pool': pool, 'health_monitor': health_monitor}) return self.delete(path)
[ "def", "disassociate_health_monitor", "(", "self", ",", "pool", ",", "health_monitor", ")", ":", "path", "=", "(", "self", ".", "disassociate_pool_health_monitors_path", "%", "{", "'pool'", ":", "pool", ",", "'health_monitor'", ":", "health_monitor", "}", ")", "...
58.6
14.8
def trace(f): """ Tracing decorator """ @functools.wraps(f) def decorator(*args, **kwargs): print 'Calling ' + f.func_name + ' in ' + str(args[0]) return f(*args, **kwargs) return decorator
[ "def", "trace", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "'Calling '", "+", "f", ".", "func_name", "+", "' in '", "+", "str", "(", "args",...
30.714286
14
def _name_search(cls, method, filters): """Helper for search methods that use name filters. Args: method (callable): The Five9 API method to call with the name filters. filters (dict): A dictionary of search parameters, keyed by the name of the fi...
[ "def", "_name_search", "(", "cls", ",", "method", ",", "filters", ")", ":", "filters", "=", "cls", ".", "_get_name_filters", "(", "filters", ")", "return", "[", "cls", ".", "deserialize", "(", "cls", ".", "_zeep_to_dict", "(", "row", ")", ")", "for", "...
39.588235
24.058824
def _get_or_create_hostfile(): ''' Wrapper of __get_hosts_filename but create host file if it does not exist. ''' hfn = __get_hosts_filename() if hfn is None: hfn = '' if not os.path.exists(hfn): with salt.utils.files.fopen(hfn, 'w'): pass return hfn
[ "def", "_get_or_create_hostfile", "(", ")", ":", "hfn", "=", "__get_hosts_filename", "(", ")", "if", "hfn", "is", "None", ":", "hfn", "=", "''", "if", "not", "os", ".", "path", ".", "exists", "(", "hfn", ")", ":", "with", "salt", ".", "utils", ".", ...
24.916667
19.75
def put_subsegment(self, subsegment): """ Store the subsegment created by ``xray_recorder`` to the context. If you put a new subsegment while there is already an open subsegment, the new subsegment becomes the child of the existing subsegment. """ entity = self.get_trace_...
[ "def", "put_subsegment", "(", "self", ",", "subsegment", ")", ":", "entity", "=", "self", ".", "get_trace_entity", "(", ")", "if", "not", "entity", ":", "log", ".", "warning", "(", "\"Active segment or subsegment not found. Discarded %s.\"", "%", "subsegment", "."...
42.153846
19.384615
def _create_eni_if_necessary(interface, vm_): ''' Create an Elastic Interface if necessary and return a Network Interface Specification ''' if 'NetworkInterfaceId' in interface and interface['NetworkInterfaceId'] is not None: return {'DeviceIndex': interface['DeviceIndex'], 'Netw...
[ "def", "_create_eni_if_necessary", "(", "interface", ",", "vm_", ")", ":", "if", "'NetworkInterfaceId'", "in", "interface", "and", "interface", "[", "'NetworkInterfaceId'", "]", "is", "not", "None", ":", "return", "{", "'DeviceIndex'", ":", "interface", "[", "'D...
42.55102
20.714286
def get_widget(self): """ Create the widget for the URL type. """ form_field = self.get_form_field() widget = form_field.widget if isinstance(widget, type): widget = widget() # Widget instantiation needs to happen manually. # Auto skip if choi...
[ "def", "get_widget", "(", "self", ")", ":", "form_field", "=", "self", ".", "get_form_field", "(", ")", "widget", "=", "form_field", ".", "widget", "if", "isinstance", "(", "widget", ",", "type", ")", ":", "widget", "=", "widget", "(", ")", "# Widget ins...
35.25
11.25
def getACLs(self, base, searchstr): """ Query LDAP to obtain the network ACLs of a given user, parse the ACLs, and return the results in a dict of the form acls[group][cidr] = description """ acls = dict() res = self.query(base, searchstr, ['cn', 'ipHostNumber']) for dn,attr in res: cn = attr['cn'...
[ "def", "getACLs", "(", "self", ",", "base", ",", "searchstr", ")", ":", "acls", "=", "dict", "(", ")", "res", "=", "self", ".", "query", "(", "base", ",", "searchstr", ",", "[", "'cn'", ",", "'ipHostNumber'", "]", ")", "for", "dn", ",", "attr", "...
29.666667
14.25
def readf(nb_file, fmt=None): """Read a notebook from the file with given name""" if nb_file == '-': text = sys.stdin.read() fmt = fmt or divine_format(text) return reads(text, fmt) _, ext = os.path.splitext(nb_file) fmt = copy(fmt or {}) fmt.update({'extension': ext}) w...
[ "def", "readf", "(", "nb_file", ",", "fmt", "=", "None", ")", ":", "if", "nb_file", "==", "'-'", ":", "text", "=", "sys", ".", "stdin", ".", "read", "(", ")", "fmt", "=", "fmt", "or", "divine_format", "(", "text", ")", "return", "reads", "(", "te...
33.75
10.833333
def sort_ascending(self, key): """Sorts selection (or grid if none) corresponding to column of key""" row, col, tab = key scells = self.grid.code_array[:, col, tab] def sorter(i): sorted_ele = scells[i] return sorted_ele is None, sorted_ele sorted_row_...
[ "def", "sort_ascending", "(", "self", ",", "key", ")", ":", "row", ",", "col", ",", "tab", "=", "key", "scells", "=", "self", ".", "grid", ".", "code_array", "[", ":", ",", "col", ",", "tab", "]", "def", "sorter", "(", "i", ")", ":", "sorted_ele"...
27.1875
21.6875
def vm_deploy(name, kwargs=None, call=None): ''' Initiates the instance of the given VM on the target host. .. versionadded:: 2016.3.0 name The name of the VM to deploy. host_id The ID of the target host where the VM will be deployed. Can be used instead of ``host_name``. ...
[ "def", "vm_deploy", "(", "name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_deploy action must be called with -a or --action.'", ")", "if", "kwargs", "is", "N...
33.958763
25.484536
def use_federated_log_view(self): """Pass through to provider LogEntryLookupSession.use_federated_log_view""" self._log_view = FEDERATED # self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): ...
[ "def", "use_federated_log_view", "(", "self", ")", ":", "self", ".", "_log_view", "=", "FEDERATED", "# self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provider_sessions", "(", ")", ":", ...
47
16.222222
def set_state(self, new_state): """Assign the specified state to this consumer object. :param int new_state: The new state of the object :raises: ValueError """ # Make sure it's a valid state if new_state not in self.STATES: raise ValueError('Invalid state v...
[ "def", "set_state", "(", "self", ",", "new_state", ")", ":", "# Make sure it's a valid state", "if", "new_state", "not", "in", "self", ".", "STATES", ":", "raise", "ValueError", "(", "'Invalid state value: %r'", "%", "new_state", ")", "# Set the state", "LOGGER", ...
34.0625
16.125
def pop(self, i): """ Pop a column from the H2OFrame at index i. :param i: The index (int) or name (str) of the column to pop. :returns: an H2OFrame containing the column dropped from the current frame; the current frame is modified in-place and loses the column. """...
[ "def", "pop", "(", "self", ",", "i", ")", ":", "if", "is_type", "(", "i", ",", "str", ")", ":", "i", "=", "self", ".", "names", ".", "index", "(", "i", ")", "col", "=", "H2OFrame", ".", "_expr", "(", "expr", "=", "ExprNode", "(", "\"cols\"", ...
44.894737
19.315789
def visualize(self, display=True): """! @brief Display KD-tree to console. @param[in] display (bool): If 'True' then tree will be shown in console. @return (string) Text representation of the KD-tree. """ kdnodes = self.__get_nodes() ...
[ "def", "visualize", "(", "self", ",", "display", "=", "True", ")", ":", "kdnodes", "=", "self", ".", "__get_nodes", "(", ")", "level", "=", "kdnodes", "[", "0", "]", "for", "kdnode", "in", "kdnodes", ":", "self", ".", "__print_node", "(", "level", ",...
27.52381
17.571429
def remove(self, item): """ See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method """ self.real_list.remove(item) self._items.remove(item)
[ "def", "remove", "(", "self", ",", "item", ")", ":", "self", ".", "real_list", ".", "remove", "(", "item", ")", "self", ".", "_items", ".", "remove", "(", "item", ")" ]
33.833333
13.5
def get_inline_func(inline_str, modules=None, **stream_kwargs): """returns a function decorated by `cbox.stream` decorator. :param str inline_str: the inline function to execute, can use `s` - local variable as the input line/char/raw (according to `input_type` param). :param str modules: comma...
[ "def", "get_inline_func", "(", "inline_str", ",", "modules", "=", "None", ",", "*", "*", "stream_kwargs", ")", ":", "if", "not", "_is_compilable", "(", "inline_str", ")", ":", "raise", "ValueError", "(", "'cannot compile the inline expression - \"%s\"'", "%", "inl...
40.578947
19.947368
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge Symbolic Link record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdlibexception.Py...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'SL record not yet initialized!'", ")", "outlist", "=", "[", "b'SL'", ",", "struct", ".", ...
32.055556
25.388889
def stream_create_default_file_stream(fname, isa_read_stream): """Wraps openjp2 library function opj_stream_create_default_vile_stream. Sets the stream to be a file stream. This function is only valid for the 2.1 version of the openjp2 library. Parameters ---------- fname : str Specif...
[ "def", "stream_create_default_file_stream", "(", "fname", ",", "isa_read_stream", ")", ":", "ARGTYPES", "=", "[", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int32", "]", "OPENJP2", ".", "opj_stream_create_default_file_stream", ".", "argtypes", "=", "ARGTYPES"...
35.115385
21.076923
def register_callback(self, fun, npts): """ Provide a function to be executed periodically on data collection, every time after the specified number of points are collected. :param fun: the function that gets called, it must have a single positional argument that will be the d...
[ "def", "register_callback", "(", "self", ",", "fun", ",", "npts", ")", ":", "self", ".", "callback_fun", "=", "fun", "self", ".", "n", "=", "npts", "self", ".", "AutoRegisterEveryNSamplesEvent", "(", "DAQmx_Val_Acquired_Into_Buffer", ",", "npts", ",", "0", "...
48.571429
23.214286
def comment(self, body): """Adds a comment to the issue. :params body: body, content of the comment :returns: issue object :rtype: :class:`exreporter.stores.github.GithubIssue` """ self.github_request.comment(issue=self, body=body) if self.state == 'closed': ...
[ "def", "comment", "(", "self", ",", "body", ")", ":", "self", ".", "github_request", ".", "comment", "(", "issue", "=", "self", ",", "body", "=", "body", ")", "if", "self", ".", "state", "==", "'closed'", ":", "self", ".", "open_issue", "(", ")", "...
29.583333
16.083333
def pprint(self, seconds): """ Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds :param seconds: The time in seconds. """ return ("%d:%02d:%02d.%03d", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))
[ "def", "pprint", "(", "self", ",", "seconds", ")", ":", "return", "(", "\"%d:%02d:%02d.%03d\"", ",", "reduce", "(", "lambda", "ll", ",", "b", ":", "divmod", "(", "ll", "[", "0", "]", ",", "b", ")", "+", "ll", "[", "1", ":", "]", ",", "[", "(", ...
40
23.714286
def read_config(self, path): """ parse alot's config file :param path: path to alot's config file :type path: str """ spec = os.path.join(DEFAULTSPATH, 'alot.rc.spec') newconfig = read_config(path, spec, report_extra=True, checks={ 'mail_container'...
[ "def", "read_config", "(", "self", ",", "path", ")", ":", "spec", "=", "os", ".", "path", ".", "join", "(", "DEFAULTSPATH", ",", "'alot.rc.spec'", ")", "newconfig", "=", "read_config", "(", "path", ",", "spec", ",", "report_extra", "=", "True", ",", "c...
43.492308
19.738462
def get_bucket(self, bucket_name, validate=True, headers=None, force=None): """Return a bucket from MimicDB if it exists. Return a S3ResponseError if the bucket does not exist and validate is passed. :param boolean force: If true, API call is forced to S3 """ if force: ...
[ "def", "get_bucket", "(", "self", ",", "bucket_name", ",", "validate", "=", "True", ",", "headers", "=", "None", ",", "force", "=", "None", ")", ":", "if", "force", ":", "bucket", "=", "super", "(", "S3Connection", ",", "self", ")", ".", "get_bucket", ...
41.611111
22.444444
def parse_estimateReadFiltering(self): """Find estimateReadFiltering output. Only the output from --table is supported.""" self.deeptools_estimateReadFiltering = dict() for f in self.find_log_files('deeptools/estimateReadFiltering'): parsed_data = self.parseEstimateReadFilteringFile(...
[ "def", "parse_estimateReadFiltering", "(", "self", ")", ":", "self", ".", "deeptools_estimateReadFiltering", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/estimateReadFiltering'", ")", ":", "parsed_data", "=", "self", "."...
45.219298
21.438596
def fixup_instance(sender, **kwargs): """ Cache JSONAttributes data on instance and vice versa for convenience. """ instance = kwargs['instance'] for model_field in instance._meta.fields: if not isinstance(model_field, JSONAttributeField): continue if hasattr(instance, ...
[ "def", "fixup_instance", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "kwargs", "[", "'instance'", "]", "for", "model_field", "in", "instance", ".", "_meta", ".", "fields", ":", "if", "not", "isinstance", "(", "model_field", ",", "J...
37.483871
17.870968
def Likelihood(self, data): """Computes the likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float probability """ m = len(data) if self.n < m: return 0 x = data p = self.Random() q = ...
[ "def", "Likelihood", "(", "self", ",", "data", ")", ":", "m", "=", "len", "(", "data", ")", "if", "self", ".", "n", "<", "m", ":", "return", "0", "x", "=", "data", "p", "=", "self", ".", "Random", "(", ")", "q", "=", "p", "[", ":", "m", "...
22.666667
20.133333
def process_events(args): """Process actions related to events switch.""" client = EventsClient.from_config() client.set_debug(True) if args.get: response = client.get_events() elif args.flush: response = client.flush_events() return response
[ "def", "process_events", "(", "args", ")", ":", "client", "=", "EventsClient", ".", "from_config", "(", ")", "client", ".", "set_debug", "(", "True", ")", "if", "args", ".", "get", ":", "response", "=", "client", ".", "get_events", "(", ")", "elif", "a...
30.444444
10.777778
def read_msg(self): """Read one message unit. It's possible however that more than one message will be set in a receive, so we will have to buffer that for the next read. EOFError will be raised on EOF. """ if self.state == 'connected': if 0 == len(self.buf): ...
[ "def", "read_msg", "(", "self", ")", ":", "if", "self", ".", "state", "==", "'connected'", ":", "if", "0", "==", "len", "(", "self", ".", "buf", ")", ":", "self", ".", "buf", "=", "self", ".", "inout", ".", "recv", "(", "Mtcpfns", ".", "TCP_MAX_P...
40.823529
11.941176
def _update_3d_datalim(ax, obj): '''unlike w/ 2d Axes, the dataLim isn't set by collections, so it has to be updated manually''' min_bounding_box, max_bounding_box = geom.bounding_box(obj) xy_bounds = np.vstack((min_bounding_box[:COLS.Z], max_bounding_box[:COLS.Z])) ax.xy_data...
[ "def", "_update_3d_datalim", "(", "ax", ",", "obj", ")", ":", "min_bounding_box", ",", "max_bounding_box", "=", "geom", ".", "bounding_box", "(", "obj", ")", "xy_bounds", "=", "np", ".", "vstack", "(", "(", "min_bounding_box", "[", ":", "COLS", ".", "Z", ...
58.3
27.9
def rename(self, names, inplace=False): """ Rename the columns using the 'names' dict. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current ...
[ "def", "rename", "(", "self", ",", "names", ",", "inplace", "=", "False", ")", ":", "if", "(", "type", "(", "names", ")", "is", "not", "dict", ")", ":", "raise", "TypeError", "(", "'names must be a dictionary: oldname -> newname'", ")", "if", "inplace", ":...
39.914286
21.971429
def log_event(event, logger=root_logger, **log_dict): """ Utility function for logging an event (e.g. for metric analysis). If no logger is given, fallback to the root logger. """ msg = "event={}".format(event) msg = add_items_to_message(msg, log_dict) log_dict.update({'event': event}) ...
[ "def", "log_event", "(", "event", ",", "logger", "=", "root_logger", ",", "*", "*", "log_dict", ")", ":", "msg", "=", "\"event={}\"", ".", "format", "(", "event", ")", "msg", "=", "add_items_to_message", "(", "msg", ",", "log_dict", ")", "log_dict", ".",...
31.181818
14.090909
def _update_pref(self, lmin, lmax, cur): """ update the self rating based on the parameters. If min max is a range (ie not equal) then add fixed value to rating depending if current value is in range, otherwise compare distance away from min/max (same value) """ r...
[ "def", "_update_pref", "(", "self", ",", "lmin", ",", "lmax", ",", "cur", ")", ":", "rate_of_change_positive", "=", "10", "rate_of_change_negative", "=", "2", "add_positive", "=", "10", "add_negative", "=", "2", "if", "lmin", "==", "lmax", ":", "self", "."...
44.227273
20.954545
def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): """Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to ...
[ "def", "infixNotation", "(", "baseExpr", ",", "opList", ",", "lpar", "=", "Suppress", "(", "'('", ")", ",", "rpar", "=", "Suppress", "(", "')'", ")", ")", ":", "ret", "=", "Forward", "(", ")", "lastExpr", "=", "baseExpr", "|", "(", "lpar", "+", "re...
55.767123
26.794521
def load(path, sr=22050, mono=True, offset=0.0, duration=None, dtype=np.float32, res_type='kaiser_best'): """Load an audio file as a floating point time series. Audio will be automatically resampled to the given rate (default `sr=22050`). To preserve the native sampling rate of the file, use ...
[ "def", "load", "(", "path", ",", "sr", "=", "22050", ",", "mono", "=", "True", ",", "offset", "=", "0.0", ",", "duration", "=", "None", ",", "dtype", "=", "np", ".", "float32", ",", "res_type", "=", "'kaiser_best'", ")", ":", "try", ":", "with", ...
27.752066
25.181818
def handle_error(self, error, download_request): """ Checks what error occured and looks for an appropriate solution. Args: error: Exception The error that has occured. download_request: The request which resulted in the error. """ if ...
[ "def", "handle_error", "(", "self", ",", "error", ",", "download_request", ")", ":", "if", "hasattr", "(", "error", ",", "\"errno\"", ")", "and", "error", ".", "errno", "==", "errno", ".", "EACCES", ":", "self", ".", "handle_certificate_problem", "(", "str...
36.428571
18
def SetAlpha(self, alpha): ''' Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: ''' self._AlphaChannel = alpha if self._AlphaChannel is not None: self.QT_QMainWindow.setWindowOpacity(self._AlphaCha...
[ "def", "SetAlpha", "(", "self", ",", "alpha", ")", ":", "self", ".", "_AlphaChannel", "=", "alpha", "if", "self", ".", "_AlphaChannel", "is", "not", "None", ":", "self", ".", "QT_QMainWindow", ".", "setWindowOpacity", "(", "self", ".", "_AlphaChannel", ")"...
35.222222
17.888889
def posterior_marginals(self, observations, name=None): """Compute marginal posterior distribution for each state. This function computes, for each time step, the marginal conditional probability that the hidden Markov model was in each possible state given the observations that were made at each t...
[ "def", "posterior_marginals", "(", "self", ",", "observations", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "\"posterior_marginals\"", ")", ":", "with", "tf", ".", "control_dependencies", "(", "self", ".", "_runtim...
46.026786
25.267857
def wait_for(self, timeout=3000): """Hault execution until self resolves.""" results = [None] results_called = [False] def results_callback(val): results[0] = val results_called[0] = True self.then(results_callback) start = time.time() w...
[ "def", "wait_for", "(", "self", ",", "timeout", "=", "3000", ")", ":", "results", "=", "[", "None", "]", "results_called", "=", "[", "False", "]", "def", "results_callback", "(", "val", ")", ":", "results", "[", "0", "]", "=", "val", "results_called", ...
30.705882
14.823529
def reset_scan_stats(self): """Clears the scan event statistics and updates the last reset time""" self._scan_event_count = 0 self._v1_scan_count = 0 self._v1_scan_response_count = 0 self._v2_scan_count = 0 self._device_scan_counts = {} self._last_reset_time = tim...
[ "def", "reset_scan_stats", "(", "self", ")", ":", "self", ".", "_scan_event_count", "=", "0", "self", ".", "_v1_scan_count", "=", "0", "self", ".", "_v1_scan_response_count", "=", "0", "self", ".", "_v2_scan_count", "=", "0", "self", ".", "_device_scan_counts"...
40.125
5.375
def add_subsegment(self, subsegment): """ Add input subsegment as a child subsegment and increment reference counter and total subsegments counter of the parent segment. """ super(Subsegment, self).add_subsegment(subsegment) self.parent_segment.increment()
[ "def", "add_subsegment", "(", "self", ",", "subsegment", ")", ":", "super", "(", "Subsegment", ",", "self", ")", ".", "add_subsegment", "(", "subsegment", ")", "self", ".", "parent_segment", ".", "increment", "(", ")" ]
38.125
10.625
def hydrate(cls, db, limit): """ Given a limit dict, as generated by dehydrate(), generate an appropriate instance of Limit (or a subclass). If the required limit class cannot be found, returns None. """ # Extract the limit name from the keyword arguments cls_na...
[ "def", "hydrate", "(", "cls", ",", "db", ",", "limit", ")", ":", "# Extract the limit name from the keyword arguments", "cls_name", "=", "limit", ".", "pop", "(", "'limit_class'", ")", "# Is it in the registry yet?", "if", "cls_name", "not", "in", "cls", ".", "_re...
32.789474
15.736842
def is_binary(self, component): """ especially useful for constraints tells whether any component (star, envelope) is part of a binary by checking its parent """ if component not in self._is_binary.keys(): self._update_cache() return self._is_binary....
[ "def", "is_binary", "(", "self", ",", "component", ")", ":", "if", "component", "not", "in", "self", ".", "_is_binary", ".", "keys", "(", ")", ":", "self", ".", "_update_cache", "(", ")", "return", "self", ".", "_is_binary", ".", "get", "(", "component...
29.454545
14.181818
def _update_consumers(self): """Update Consumers. - Add more if requested. - Make sure the consumers are healthy. - Remove excess consumers. :return: """ # Do we need to start more consumers. consumer_to_start = \ min(max(self.num...
[ "def", "_update_consumers", "(", "self", ")", ":", "# Do we need to start more consumers.", "consumer_to_start", "=", "min", "(", "max", "(", "self", ".", "number_of_consumers", "-", "len", "(", "self", ".", "_consumers", ")", ",", "0", ")", ",", "2", ")", "...
32.153846
13.807692
def databases_to_delete(cls): # pragma: no cover """ Set the databases files to delete. """ # We initiate the directory we have to look for. directory = PyFunceble.CURRENT_DIRECTORY # We initate the result variable. result = [] # We append the dir_stru...
[ "def", "databases_to_delete", "(", "cls", ")", ":", "# pragma: no cover", "# We initiate the directory we have to look for.", "directory", "=", "PyFunceble", ".", "CURRENT_DIRECTORY", "# We initate the result variable.", "result", "=", "[", "]", "# We append the dir_structure fil...
29.066667
24
def authorize_url(self): """ Return a URL to redirect the user to for OAuth authentication. """ auth_url = OAUTH_ROOT + '/authorize' params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, } return "{}?{}".format(auth_url...
[ "def", "authorize_url", "(", "self", ")", ":", "auth_url", "=", "OAUTH_ROOT", "+", "'/authorize'", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "}", "return", "\"{}?{}\"", "."...
33.1
12.7
def pre_check(self, data): """Count chars, words and sentences in the text.""" sentences = len(re.findall('[\.!?]+\W+', data)) or 1 chars = len(data) - len(re.findall('[^a-zA-Z0-9]', data)) num_words = len(re.findall('\s+', data)) data = re.split('[^a-zA-Z]+', data) retur...
[ "def", "pre_check", "(", "self", ",", "data", ")", ":", "sentences", "=", "len", "(", "re", ".", "findall", "(", "'[\\.!?]+\\W+'", ",", "data", ")", ")", "or", "1", "chars", "=", "len", "(", "data", ")", "-", "len", "(", "re", ".", "findall", "("...
49.857143
11.142857
def _file_has_tag_anchor_keypair(self, anchors, file_key, tag): """ Is there an AnchorHub tag, 'tag', registered for file 'file_key' in 'anchors'? :param anchors: Dictionary mapping string file paths to inner dictionaries. These inner dictionaries map string AnchorHub tags ...
[ "def", "_file_has_tag_anchor_keypair", "(", "self", ",", "anchors", ",", "file_key", ",", "tag", ")", ":", "return", "file_key", "in", "anchors", "and", "tag", "in", "anchors", "[", "file_key", "]" ]
47.4
21.4
def do_photometry(self, image, init_guesses=None): """ Perform PSF photometry in ``image``. This method assumes that ``psf_model`` has centroids and flux parameters which will be fitted to the data provided in ``image``. A compound model, in fact a sum of ``psf_model``, ...
[ "def", "do_photometry", "(", "self", ",", "image", ",", "init_guesses", "=", "None", ")", ":", "if", "init_guesses", "is", "not", "None", ":", "table", "=", "super", "(", ")", ".", "do_photometry", "(", "image", ",", "init_guesses", ")", "table", "[", ...
49.184615
23.615385
def artist_list(self, query=None, artist_id=None, creator_name=None, creator_id=None, is_active=None, is_banned=None, empty_only=None, order=None): """Get an artist of a list of artists. Parameters: query (str): This field has multiple...
[ "def", "artist_list", "(", "self", ",", "query", "=", "None", ",", "artist_id", "=", "None", ",", "creator_name", "=", "None", ",", "creator_id", "=", "None", ",", "is_active", "=", "None", ",", "is_banned", "=", "None", ",", "empty_only", "=", "None", ...
43.738095
14.904762
def parse_ids(chrom, pos, ref, alt, case_id, variant_type): """Construct the necessary ids for a variant Args: chrom(str): Variant chromosome pos(int): Variant position ref(str): Variant reference alt(str): Variant alternative case_id(str): Unique case id variant...
[ "def", "parse_ids", "(", "chrom", ",", "pos", ",", "ref", ",", "alt", ",", "case_id", ",", "variant_type", ")", ":", "ids", "=", "{", "}", "pos", "=", "str", "(", "pos", ")", "ids", "[", "'simple_id'", "]", "=", "parse_simple_id", "(", "chrom", ","...
33.217391
21.695652
def print_critical_paths(critical_paths): """ Prints the results of the critical path length analysis. Done by default by the `timing_critical_path()` function. """ line_indent = " " * 2 # print the critical path for cp_with_num in enumerate(critical_paths): ...
[ "def", "print_critical_paths", "(", "critical_paths", ")", ":", "line_indent", "=", "\" \"", "*", "2", "# print the critical path", "for", "cp_with_num", "in", "enumerate", "(", "critical_paths", ")", ":", "print", "(", "\"Critical path\"", ",", "cp_with_num", "[",...
44.333333
10.75
def great_distance(**kwargs): """ Named arguments: start_latitude = starting latitude, in DECIMAL DEGREES start_longitude = starting longitude, in DECIMAL DEGREES end_latitude = ending latitude, in DECIMAL DEGREES end_longitude = ending longitude, in DECIMAL DEGREES ...
[ "def", "great_distance", "(", "*", "*", "kwargs", ")", ":", "sy", "=", "kwargs", ".", "pop", "(", "'start_latitude'", ")", "sx", "=", "kwargs", ".", "pop", "(", "'start_longitude'", ")", "ey", "=", "kwargs", ".", "pop", "(", "'end_latitude'", ")", "ex"...
36.75641
17.730769
def create_tags(user): """Create a tag.""" values = { 'id': utils.gen_uuid(), 'created_at': datetime.datetime.utcnow().isoformat() } values.update(schemas.tag.post(flask.request.json)) with flask.g.db_conn.begin(): where_clause = sql.and_( _TABLE.c.name == values...
[ "def", "create_tags", "(", "user", ")", ":", "values", "=", "{", "'id'", ":", "utils", ".", "gen_uuid", "(", ")", ",", "'created_at'", ":", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", "}", "values", ".", "update"...
35
16.590909
def safeprintf(file, format, *args): """Write to a file object, ignoring errors. """ try: if args: file.write(format % args) else: file.write(format) except IOError, e: if e.errno == errno.EPIPE: # if our output is closed, exit; e.g. when loggi...
[ "def", "safeprintf", "(", "file", ",", "format", ",", "*", "args", ")", ":", "try", ":", "if", "args", ":", "file", ".", "write", "(", "format", "%", "args", ")", "else", ":", "file", ".", "write", "(", "format", ")", "except", "IOError", ",", "e...
31.846154
14
def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code): """Formats a phone number in national format for dialing using the carrier as specified in the preferred_domestic_carrier_code field of the PhoneNumber object passed in. If that is missing, use the fallback_carrier_co...
[ "def", "format_national_number_with_preferred_carrier_code", "(", "numobj", ",", "fallback_carrier_code", ")", ":", "# Historically, we set this to an empty string when parsing with raw input", "# if none was found in the input string. However, this doesn't result in a", "# number we can dial. F...
50.96875
25.375
def get_sitecol_shakemap(array_or_id, imts, sitecol=None, assoc_dist=None, discard_assets=False): """ :param array_or_id: shakemap array or shakemap ID :param imts: required IMTs as a list of strings :param sitecol: SiteCollection used to reduce the shakemap :param assoc_dis...
[ "def", "get_sitecol_shakemap", "(", "array_or_id", ",", "imts", ",", "sitecol", "=", "None", ",", "assoc_dist", "=", "None", ",", "discard_assets", "=", "False", ")", ":", "if", "isinstance", "(", "array_or_id", ",", "str", ")", ":", "# shakemap ID", "array"...
43.5
15.7
def _handleReadableSocket(self, src_socket): ''' :returns: :data:`python:True` if the connect has been disconnected and :data:`python:False` if the connection is still alive and everything was processed normally ''' msg = src_socket.recv(self._max_mess...
[ "def", "_handleReadableSocket", "(", "self", ",", "src_socket", ")", ":", "msg", "=", "src_socket", ".", "recv", "(", "self", ".", "_max_message_size", ")", "return", "self", ".", "_handleMessage", "(", "src_socket", ",", "msg", ")" ]
46.75
21.25
def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on node properties. See documentation for _OTIWrapper class.""" assert self.use_v1 return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix), query_d...
[ "def", "find_nodes", "(", "self", ",", "query_dict", "=", "None", ",", "exact", "=", "False", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "use_v1", "return", "self", ".", "_do_query", "(", "'{p}/singlePropertyS...
58.888889
17.555556
def threat(self, name, owner=None, **kwargs): """ Create the Threat TI object. Args: owner: name: **kwargs: Return: """ return Threat(self.tcex, name, owner=owner, **kwargs)
[ "def", "threat", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Threat", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
19.076923
20.461538
def make_pydot_graph(layers, output_shape=True, verbose=False): """ :parameters: - layers : list List of the layers, as obtained from lasagne.layers.get_all_layers - output_shape: (default `True`) If `True`, the output shape of each layer will be displayed. - verb...
[ "def", "make_pydot_graph", "(", "layers", ",", "output_shape", "=", "True", ",", "verbose", "=", "False", ")", ":", "import", "pydotplus", "as", "pydot", "pydot_graph", "=", "pydot", ".", "Dot", "(", "'Network'", ",", "graph_type", "=", "'digraph'", ")", "...
38.491228
18.035088
def choice(choices=[], message='Pick something.', default=None, title=''): """ Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. :ref:`screenshots<choice>` :param choices: a list of the choices to be displayed :pa...
[ "def", "choice", "(", "choices", "=", "[", "]", ",", "message", "=", "'Pick something.'", ",", "default", "=", "None", ",", "title", "=", "''", ")", ":", "return", "backend_api", ".", "opendialog", "(", "\"choice\"", ",", "dict", "(", "choices", "=", "...
37.866667
17.733333
def _merge_json(self, stmt_json, ev_counts): """Merge these statement jsons with new jsons.""" # Where there is overlap, there _should_ be agreement. self.__evidence_counts.update(ev_counts) for k, sj in stmt_json.items(): if k not in self.__statement_jsons: ...
[ "def", "_merge_json", "(", "self", ",", "stmt_json", ",", "ev_counts", ")", ":", "# Where there is overlap, there _should_ be agreement.", "self", ".", "__evidence_counts", ".", "update", "(", "ev_counts", ")", "for", "k", ",", "sj", "in", "stmt_json", ".", "items...
40.5
15.888889
def add_argument(self, arg_name, arg_value): '''Add an additional argument to be passed to the fitness function via additional arguments dictionary; this argument/value is not tuned Args: arg_name (string): name/dictionary key of argument arg_value (any): dictionary valu...
[ "def", "add_argument", "(", "self", ",", "arg_name", ",", "arg_value", ")", ":", "if", "len", "(", "self", ".", "_employers", ")", ">", "0", ":", "self", ".", "_logger", ".", "log", "(", "'warn'", ",", "'Adding an argument after the employers have been created...
35.882353
21.529412
def _is_paste(keys): """ Return `True` when we should consider this list of keys as a paste event. Pasted text on windows will be turned into a `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably the best possible way to detect pasting of text and handle that ...
[ "def", "_is_paste", "(", "keys", ")", ":", "# Consider paste when it contains at least one newline and at least one", "# other character.", "text_count", "=", "0", "newline_count", "=", "0", "for", "k", "in", "keys", ":", "if", "isinstance", "(", "k", ".", "key", ",...
36.05
19.25
def zfill(self, width): """Pad a numeric string with zeros on the left, to fill a field of the specified width. The string is never truncated. :param int width: Length of output string. """ if not self.value_no_colors: result = self.value_no_colors.zfill(width) ...
[ "def", "zfill", "(", "self", ",", "width", ")", ":", "if", "not", "self", ".", "value_no_colors", ":", "result", "=", "self", ".", "value_no_colors", ".", "zfill", "(", "width", ")", "else", ":", "result", "=", "self", ".", "value_colors", ".", "replac...
39.666667
19.166667
def noop(self): """ Send a NOOP command :return: Returns the status. :rtype: int """ logger.debug('Sending NOOP') data = struct.pack(self.HEADER_STRUCT + self.COMMANDS['noop']['struct'], self.MAGIC['request'],...
[ "def", "noop", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Sending NOOP'", ")", "data", "=", "struct", ".", "pack", "(", "self", ".", "HEADER_STRUCT", "+", "self", ".", "COMMANDS", "[", "'noop'", "]", "[", "'struct'", "]", ",", "self", ".",...
33.92
20
def from_nuniq_interval_set(cls, nuniq_is): """ Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix cells following the NESTED numbering scheme. Parameters ---------- nuniq_is : `IntervalSet` IntervalSet object storing HEA...
[ "def", "from_nuniq_interval_set", "(", "cls", ",", "nuniq_is", ")", ":", "nested_is", "=", "IntervalSet", "(", ")", "# Appending a list is faster than appending a numpy array", "# For these algorithms we append a list and create the interval set from the finished list", "rtmp", "=", ...
39.973684
22.5
def getScalarNames(self, parentFieldName=''): """ See method description in base.py """ names = [] # This forms a name which is the concatenation of the parentFieldName # passed in and the encoder's own name. def _formFieldName(encoder): if parentFieldName == '': return encoder.nam...
[ "def", "getScalarNames", "(", "self", ",", "parentFieldName", "=", "''", ")", ":", "names", "=", "[", "]", "# This forms a name which is the concatenation of the parentFieldName", "# passed in and the encoder's own name.", "def", "_formFieldName", "(", "encoder", ")", ":"...
32.235294
19.911765
def _make_cmap(colors, position=None, bit=False): ''' _make_cmap takes a list of tuples which contain RGB values. The RGB values may either be in 8-bit [0 to 255] (in which bit must be set to True when called) or arithmetic [0 to 1] (default). _make_cmap returns a cmap with equally spaced colors. ...
[ "def", "_make_cmap", "(", "colors", ",", "position", "=", "None", ",", "bit", "=", "False", ")", ":", "bit_rgb", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "256", ")", "if", "position", "==", "None", ":", "position", "=", "np", ".", "li...
45.409091
19.681818
def fileio(): ''' This tests for the file read and write operations Various modes of operations are * sequential write * sequential rewrite * sequential read * random read * random write * random read and write The test works with 32 files with each file being 1Gb in size T...
[ "def", "fileio", "(", ")", ":", "# Test data", "test_modes", "=", "[", "'seqwr'", ",", "'seqrewr'", ",", "'seqrd'", ",", "'rndrd'", ",", "'rndwr'", ",", "'rndrw'", "]", "# Initializing the required variables", "test_command", "=", "'sysbench --num-threads=16 --test=fi...
25.408163
23.040816
def getRnaQuantificationSetByName(self, name): """ Returns the RnaQuantification set with the specified name, or raises an exception otherwise. """ if name not in self._rnaQuantificationSetNameMap: raise exceptions.RnaQuantificationSetNameNotFoundException(name) ...
[ "def", "getRnaQuantificationSetByName", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_rnaQuantificationSetNameMap", ":", "raise", "exceptions", ".", "RnaQuantificationSetNameNotFoundException", "(", "name", ")", "return", "self", ".",...
45.25
14.75
def add_neighbor(self, edge: "Edge") -> None: """ Adds a new neighbor to the node. Arguments: edge (Edge): The edge that would connect this node with its neighbor. """ if edge is None or (edge.source != self and edge.target != self): return ...
[ "def", "add_neighbor", "(", "self", ",", "edge", ":", "\"Edge\"", ")", "->", "None", ":", "if", "edge", "is", "None", "or", "(", "edge", ".", "source", "!=", "self", "and", "edge", ".", "target", "!=", "self", ")", ":", "return", "if", "edge", ".",...
36.56
21.28
def rect2pathd(rect): """Converts an SVG-rect element to a Path d-string. The rectangle will start at the (x,y) coordinate specified by the rectangle object and proceed counter-clockwise.""" x0, y0 = float(rect.get('x', 0)), float(rect.get('y', 0)) w, h = float(rect.get('width', 0)), float(rec...
[ "def", "rect2pathd", "(", "rect", ")", ":", "x0", ",", "y0", "=", "float", "(", "rect", ".", "get", "(", "'x'", ",", "0", ")", ")", ",", "float", "(", "rect", ".", "get", "(", "'y'", ",", "0", ")", ")", "w", ",", "h", "=", "float", "(", "...
36.571429
18.785714
def check_int(integer): """ Check if number is integer or not. :param integer: Number as str :return: Boolean """ if not isinstance(integer, str): return False if integer[0] in ('-', '+'): return integer[1:].isdigit() return integer.isdigit()
[ "def", "check_int", "(", "integer", ")", ":", "if", "not", "isinstance", "(", "integer", ",", "str", ")", ":", "return", "False", "if", "integer", "[", "0", "]", "in", "(", "'-'", ",", "'+'", ")", ":", "return", "integer", "[", "1", ":", "]", "."...
23.333333
11.166667
def fail_tmp(item, max_tries=None, ttl=None): '''Try to fail a work-item temporarily (up recount and keep in queue), if max tries or ttl is exhausted, escalate to permanant failure.''' try: max_tries = item.max_tries if max_tries is None else max_tries ttl = item.ttl if ttl is None else t...
[ "def", "fail_tmp", "(", "item", ",", "max_tries", "=", "None", ",", "ttl", "=", "None", ")", ":", "try", ":", "max_tries", "=", "item", ".", "max_tries", "if", "max_tries", "is", "None", "else", "max_tries", "ttl", "=", "item", ".", "ttl", "if", "ttl...
45.08
22.52
def create_version(self, service_id, inherit_service_id=None, comment=None): """Create a version for a particular service.""" body = self._formdata({ "service_id": service_id, "inherit_service_id": inherit_service_id, "comment": comment, }, FastlyVersion.FIELDS) content = self._fetch("/service/%s/versi...
[ "def", "create_version", "(", "self", ",", "service_id", ",", "inherit_service_id", "=", "None", ",", "comment", "=", "None", ")", ":", "body", "=", "self", ".", "_formdata", "(", "{", "\"service_id\"", ":", "service_id", ",", "\"inherit_service_id\"", ":", ...
43.666667
16.333333
def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" ...
[ "def", "get_abbreviations", "(", "self", ")", ":", "abbreviations", "=", "[", "]", "try", ":", "type_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", ".", "session", ".", "get_class",...
52.7
29.2
def compare_files(pyc_filename1, pyc_filename2, verify): """Compare two .pyc files.""" (version1, timestamp, magic_int1, code_obj1, is_pypy, source_size) = uncompyle6.load_module(pyc_filename1) (version2, timestamp, magic_int2, code_obj2, is_pypy, source_size) = uncompyle6.load_module(pyc_filen...
[ "def", "compare_files", "(", "pyc_filename1", ",", "pyc_filename2", ",", "verify", ")", ":", "(", "version1", ",", "timestamp", ",", "magic_int1", ",", "code_obj1", ",", "is_pypy", ",", "source_size", ")", "=", "uncompyle6", ".", "load_module", "(", "pyc_filen...
53
15.777778