text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def sample_truncated_gaussian_vector(data, uncertainties, bounds=None): ''' Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_boots...
[ "def", "sample_truncated_gaussian_vector", "(", "data", ",", "uncertainties", ",", "bounds", "=", "None", ")", ":", "nvals", "=", "len", "(", "data", ")", "if", "bounds", ":", "# if bounds[0] or (fabs(bounds[0]) < PRECISION):", "if", "bounds", "[", "0", "]", "is...
34.258065
0.000916
def _fetch_pkg(self, gopath, pkg, rev): """Fetch the package and setup symlinks.""" fetcher = self._get_fetcher(pkg) root = fetcher.root() root_dir = os.path.join(self.workdir, 'fetches', root, rev) # Only fetch each remote root once. if not os.path.exists(root_dir): with temporary_dir() ...
[ "def", "_fetch_pkg", "(", "self", ",", "gopath", ",", "pkg", ",", "rev", ")", ":", "fetcher", "=", "self", ".", "_get_fetcher", "(", "pkg", ")", "root", "=", "fetcher", ".", "root", "(", ")", "root_dir", "=", "os", ".", "path", ".", "join", "(", ...
55.344828
0.008573
def extract_hmaps(dstore, what): """ Extracts hazard maps. Use it as /extract/hmaps?imt=PGA """ info = get_info(dstore) if what == '': # npz exports for QGIS sitecol = dstore['sitecol'] mesh = get_mesh(sitecol, complete=False) dic = _get_dict(dstore, 'hmaps-stats', ...
[ "def", "extract_hmaps", "(", "dstore", ",", "what", ")", ":", "info", "=", "get_info", "(", "dstore", ")", "if", "what", "==", "''", ":", "# npz exports for QGIS", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "mesh", "=", "get_mesh", "(", "sitecol", ...
33.903226
0.000925
def list_get(l, idx, default=None): """ Get from a list with an optional default value. """ try: if l[idx]: return l[idx] else: return default except IndexError: return default
[ "def", "list_get", "(", "l", ",", "idx", ",", "default", "=", "None", ")", ":", "try", ":", "if", "l", "[", "idx", "]", ":", "return", "l", "[", "idx", "]", "else", ":", "return", "default", "except", "IndexError", ":", "return", "default" ]
21.272727
0.008197
def scene_active(sequence_number, scene_id): """Create a scene.setactive message""" return MessageWriter().string("scene.setactive").uint64(sequence_number).uint32(scene_id).get()
[ "def", "scene_active", "(", "sequence_number", ",", "scene_id", ")", ":", "return", "MessageWriter", "(", ")", ".", "string", "(", "\"scene.setactive\"", ")", ".", "uint64", "(", "sequence_number", ")", ".", "uint32", "(", "scene_id", ")", ".", "get", "(", ...
64.333333
0.015385
def get_conn(self): """ Retrieves connection to Cloud Natural Language service. :return: Cloud Natural Language service object :rtype: google.cloud.language_v1.LanguageServiceClient """ if not self._conn: self._conn = LanguageServiceClient(credentials=self._g...
[ "def", "get_conn", "(", "self", ")", ":", "if", "not", "self", ".", "_conn", ":", "self", ".", "_conn", "=", "LanguageServiceClient", "(", "credentials", "=", "self", ".", "_get_credentials", "(", ")", ")", "return", "self", ".", "_conn" ]
35.4
0.008264
def create_publication_assistant(self, **args): ''' Create an assistant for a dataset that allows to make PID requests for the dataset and all of its files. :param drs_id: Mandatory. The dataset id of the dataset to be published. :param version_number: Mandatory. Th...
[ "def", "create_publication_assistant", "(", "self", ",", "*", "*", "args", ")", ":", "# Check args", "logdebug", "(", "LOGGER", ",", "'Creating publication assistant..'", ")", "mandatory_args", "=", "[", "'drs_id'", ",", "'version_number'", ",", "'is_replica'", "]",...
42.054545
0.002112
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element: """Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element """ if isinstance(xml,...
[ "def", "xml_to_root", "(", "xml", ":", "Union", "[", "str", ",", "IO", "]", ")", "->", "ElementTree", ".", "Element", ":", "if", "isinstance", "(", "xml", ",", "str", ")", ":", "if", "'<'", "in", "xml", ":", "return", "ElementTree", ".", "fromstring"...
24.571429
0.001866
def add_not_filter(self, *value): """ Add a filter using "NOT" logic. Typically this filter is used in conjunction with and AND or OR filters, but can be used by itself as well. This might be more useful as a standalone filter when displaying logs in real time and filtering out ...
[ "def", "add_not_filter", "(", "self", ",", "*", "value", ")", ":", "filt", "=", "NotFilter", "(", "*", "value", ")", "self", ".", "update_filter", "(", "filt", ")", "return", "filt" ]
42.166667
0.009021
def values(self): "Property to access the Histogram values provided for backward compatibility" if util.config.future_deprecations: self.param.warning('Histogram.values is deprecated in favor of ' 'common dimension_values method.') return self.dimension...
[ "def", "values", "(", "self", ")", ":", "if", "util", ".", "config", ".", "future_deprecations", ":", "self", ".", "param", ".", "warning", "(", "'Histogram.values is deprecated in favor of '", "'common dimension_values method.'", ")", "return", "self", ".", "dimens...
54.166667
0.009091
def count(args): """ %prog count bamfile gtf Count the number of reads mapped using `htseq-count`. """ p = OptionParser(count.__doc__) p.add_option("--type", default="exon", help="Only count feature type") p.set_cpus(cpus=8) opts, args = p.parse_args(args) if len(a...
[ "def", "count", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "count", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--type\"", ",", "default", "=", "\"exon\"", ",", "help", "=", "\"Only count feature type\"", ")", "p", ".", "set_cpus", "(...
30.371429
0.000912
def element(self, inp=None): """Create a `CartesianProduct` element. Parameters ---------- inp : iterable, optional Collection of input values for the `LinearSpace.element` methods of all sets in the Cartesian product. Returns -------...
[ "def", "element", "(", "self", ",", "inp", "=", "None", ")", ":", "if", "inp", "is", "None", ":", "tpl", "=", "tuple", "(", "set_", ".", "element", "(", ")", "for", "set_", "in", "self", ".", "sets", ")", "else", ":", "tpl", "=", "tuple", "(", ...
30
0.002484
def where(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o=i.get('out','') duoa=i.get('data_uoa','') r=c...
[ "def", "where", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "duoa", "=", "i", ".", "get", "(", "'data_uoa'", ",", "''", ")", "r", "=", "ck", ".", "find_path_to_repo", "(", "{", "'repo_uoa'", ":", "duoa", "}", ...
16.7
0.035849
def default(self, obj): """Encode object if it implements to_python().""" if hasattr(obj, 'to_python'): return obj.to_python() return super(CLIJSONEncoder, self).default(obj)
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'to_python'", ")", ":", "return", "obj", ".", "to_python", "(", ")", "return", "super", "(", "CLIJSONEncoder", ",", "self", ")", ".", "default", "(", "obj", ")" ]
41.2
0.009524
def _deleteCompletedMeasurement(self, measurementId): """ Deletes the named measurement from the completed measurement store if it exists. :param measurementId: :return: String: error messages Integer: count of measurements deleted """ message, cou...
[ "def", "_deleteCompletedMeasurement", "(", "self", ",", "measurementId", ")", ":", "message", ",", "count", ",", "deleted", "=", "self", ".", "deleteFrom", "(", "measurementId", ",", "self", ".", "completeMeasurements", ")", "if", "count", "is", "0", ":", "m...
44.666667
0.009141
def check_python_modules(): """Check if all necessary / recommended modules are installed.""" print("\033[1mCheck modules\033[0m") required_modules = ['argparse', 'matplotlib', 'natsort', 'pymysql', 'cPickle', 'theano', 'dropbox', 'yaml', 'webbrowser', 'hashli...
[ "def", "check_python_modules", "(", ")", ":", "print", "(", "\"\\033[1mCheck modules\\033[0m\"", ")", "required_modules", "=", "[", "'argparse'", ",", "'matplotlib'", ",", "'natsort'", ",", "'pymysql'", ",", "'cPickle'", ",", "'theano'", ",", "'dropbox'", ",", "'y...
39.45614
0.000434
def deleteable(self, request): ''' Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set ''' return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none...
[ "def", "deleteable", "(", "self", ",", "request", ")", ":", "return", "self", ".", "apply_deleteable", "(", "self", ".", "get_queryset", "(", ")", ",", "request", ")", "if", "self", ".", "check_deleteable", "(", "self", ".", "model", ",", "request", ")",...
63.6
0.012422
def write(self, path): """Write buffer to file""" with open(path, "wb") as fout: fout.write(self.m_buf)
[ "def", "write", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "fout", ":", "fout", ".", "write", "(", "self", ".", "m_buf", ")" ]
25.6
0.015152
def translate(cls, f=None, output=0, **kwargs): """translate(f=None, *, output=TranslateOutput.code, **kwargs) Decorator that turns a function into a shellcode emitting function. Arguments: f(callable): The function to decorate. If ``f`` is ``None`` a decorator will ...
[ "def", "translate", "(", "cls", ",", "f", "=", "None", ",", "output", "=", "0", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "proxy", "(", "*", "p_args", ",", ...
35.909091
0.001848
def _getter(self, uri, headers, local_object): """Perform HEAD request on a specified object in the container. :param uri: ``str`` :param headers: ``dict`` """ if self.job_args.get('sync'): sync = self._sync_check( uri=uri, headers=he...
[ "def", "_getter", "(", "self", ",", "uri", ",", "headers", ",", "local_object", ")", ":", "if", "self", ".", "job_args", ".", "get", "(", "'sync'", ")", ":", "sync", "=", "self", ".", "_sync_check", "(", "uri", "=", "uri", ",", "headers", "=", "hea...
33.702128
0.001227
def list_tags(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Return a list of tags cwd The path to the git checkout user User under which to run the git command. By ...
[ "def", "list_tags", "(", "cwd", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path", "(", "cwd", ",", "user", ")", "command", "=", "[", ...
29.017857
0.000595
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]: "Factory method to convert a batch of model images to a list of ModelImageSet." image_sets = [] x,y = batch[0],batch[1] preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True) for ori...
[ "def", "get_list_from_model", "(", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", ",", "batch", ":", "Tuple", ")", "->", "[", "]", ":", "image_sets", "=", "[", "]", "x", ",", "y", "=", "batch", "[", "0", "]", ",", "batch", "[", "1", ...
54.6
0.025225
def create_namespaced_pod_binding(self, name, namespace, body, **kwargs): # noqa: E501 """create_namespaced_pod_binding # noqa: E501 create binding of a Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_r...
[ "def", "create_namespaced_pod_binding", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", "...
63.423077
0.001195
def restart_workers(gunicorn_master_proc, num_workers_expected, master_timeout): """ Runs forever, monitoring the child processes of @gunicorn_master_proc and restarting workers occasionally. Each iteration of the loop traverses one edge of this state transition diagram, where each state (node) repr...
[ "def", "restart_workers", "(", "gunicorn_master_proc", ",", "num_workers_expected", ",", "master_timeout", ")", ":", "def", "wait_until_true", "(", "fn", ",", "timeout", "=", "0", ")", ":", "\"\"\"\n Sleeps until fn is true\n \"\"\"", "t", "=", "time", "...
44.584906
0.002484
def to_dnf(self): """Return an equivalent expression in disjunctive normal form.""" node = self.node.to_dnf() if node is self.node: return self else: return _expr(node)
[ "def", "to_dnf", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "to_dnf", "(", ")", "if", "node", "is", "self", ".", "node", ":", "return", "self", "else", ":", "return", "_expr", "(", "node", ")" ]
31.142857
0.008929
def union(self, b): """ The union operation. It might return a DiscreteStridedIntervalSet to allow for better precision in analysis. :param b: Operand :return: A new DiscreteStridedIntervalSet, or a new StridedInterval. """ if not allow_dsis: return StridedI...
[ "def", "union", "(", "self", ",", "b", ")", ":", "if", "not", "allow_dsis", ":", "return", "StridedInterval", ".", "least_upper_bound", "(", "self", ",", "b", ")", "else", ":", "if", "self", ".", "cardinality", ">", "discrete_strided_interval_set", ".", "D...
41
0.010038
def sample_loci(self): """ finds loci with sufficient sampling for this test""" ## store idx of passing loci idxs = np.random.choice(self.idxs, self.ntests) ## open handle, make a proper generator to reduce mem with open(self.data) as indata: liter = (indata.read()....
[ "def", "sample_loci", "(", "self", ")", ":", "## store idx of passing loci", "idxs", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "idxs", ",", "self", ".", "ntests", ")", "## open handle, make a proper generator to reduce mem", "with", "open", "(", ...
34.967742
0.01167
def _photometricErrors(self, catalog=None, n_per_bin=100): """ Realistic photometric errors estimated from catalog objects and mask. Extend below the magnitude threshold with a flat extrapolation. """ if catalog is None: # Simple proxy for photometric errors ...
[ "def", "_photometricErrors", "(", "self", ",", "catalog", "=", "None", ",", "n_per_bin", "=", "100", ")", ":", "if", "catalog", "is", "None", ":", "# Simple proxy for photometric errors", "release", "=", "self", ".", "config", "[", "'data'", "]", "[", "'rele...
49.675325
0.008716
def buffer(self): """ Context manager to temporarily buffer the output. :raise RuntimeError: If two :meth:`buffer` context managers are used nestedly. If the context manager is left without exception, the buffered output is sent to the actual sink. ...
[ "def", "buffer", "(", "self", ")", ":", "if", "self", ".", "_buf_in_use", ":", "raise", "RuntimeError", "(", "\"nested use of buffer() is not supported\"", ")", "self", ".", "_buf_in_use", "=", "True", "old_write", "=", "self", ".", "_write", "old_flush", "=", ...
35.686275
0.00107
def find_same_between_dicts(dict1, dict2): """ 查找两个字典中的相同点,包括键、值、项,仅支持 hashable 对象 :param: * dict1: (dict) 比较的字典 1 * dict2: (dict) 比较的字典 2 :return: * dup_info: (namedtuple) 返回两个字典中相同的信息组成的具名元组 举例如下:: print('--- find_same_between_dicts demo---') dict1 = {'x...
[ "def", "find_same_between_dicts", "(", "dict1", ",", "dict2", ")", ":", "Same_info", "=", "namedtuple", "(", "'Same_info'", ",", "[", "'item'", ",", "'key'", ",", "'value'", "]", ")", "same_info", "=", "Same_info", "(", "set", "(", "dict1", ".", "items", ...
25.222222
0.00106
def firmware_manifest_create(self, datafile, name, **kwargs): # noqa: E501 """Create a manifest # noqa: E501 Create a firmware manifest. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >...
[ "def", "firmware_manifest_create", "(", "self", ",", "datafile", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return...
52.875
0.001548
def val_to_json(key, val, mode="summary", step=None): """Converts a wandb datatype to its JSON representation""" converted = val typename = util.get_full_typename(val) if util.is_matplotlib_typename(typename): # This handles plots with images in it because plotly doesn't support it # TOD...
[ "def", "val_to_json", "(", "key", ",", "val", ",", "mode", "=", "\"summary\"", ",", "step", "=", "None", ")", ":", "converted", "=", "val", "typename", "=", "util", ".", "get_full_typename", "(", "val", ")", "if", "util", ".", "is_matplotlib_typename", "...
44.104167
0.001386
def solve_factorized_schur(z, Fval, LU, G, A): M, N=G.shape P, N=A.shape """Total number of inequality constraints""" m = M """Primal variable""" x = z[0:N] """Multiplier for equality constraints""" nu = z[N:N+P] """Multiplier for inequality constraints""" l = z[N+P:N+P+M...
[ "def", "solve_factorized_schur", "(", "z", ",", "Fval", ",", "LU", ",", "G", ",", "A", ")", ":", "M", ",", "N", "=", "G", ".", "shape", "P", ",", "N", "=", "A", ".", "shape", "m", "=", "M", "\"\"\"Primal variable\"\"\"", "x", "=", "z", "[", "0"...
20.518519
0.008613
def NumExpr(ex, signature=(), **kwargs): """ Compile an expression built using E.<variable> variables to a function. ex can also be specified as a string "2*a+3*b". The order of the input variables and their types can be specified using the signature parameter, which is a list of (name, type) pair...
[ "def", "NumExpr", "(", "ex", ",", "signature", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "# NumExpr can be called either directly by the end-user, in which case", "# kwargs need to be sanitized by getContext, or by evaluate,", "# in which case kwargs are in already sanitize...
47.541667
0.001718
def wrap_xml(self, xml, encoding ='ISO-8859-1', standalone='no'): """ Method that provides a standard svg header string for a file """ header = '''<?xml version="1.0" encoding="%s" standalone="%s"?>''' %(encoding, standalone) return header+xml
[ "def", "wrap_xml", "(", "self", ",", "xml", ",", "encoding", "=", "'ISO-8859-1'", ",", "standalone", "=", "'no'", ")", ":", "header", "=", "'''<?xml version=\"1.0\" encoding=\"%s\" standalone=\"%s\"?>'''", "%", "(", "encoding", ",", "standalone", ")", "return", "h...
46.5
0.021127
def get_conn(self): """ Returns a snowflake.connection object """ conn_config = self._get_conn_params() conn = snowflake.connector.connect(**conn_config) return conn
[ "def", "get_conn", "(", "self", ")", ":", "conn_config", "=", "self", ".", "_get_conn_params", "(", ")", "conn", "=", "snowflake", ".", "connector", ".", "connect", "(", "*", "*", "conn_config", ")", "return", "conn" ]
29.571429
0.00939
def get(item, default=None): """Get item from value (value[item]). If the item is not found, return the default. Handles XML elements, regex matches and anything that has __getitem__. """ def getter(value): if ET.iselement(value): value = value.attrib try: ...
[ "def", "get", "(", "item", ",", "default", "=", "None", ")", ":", "def", "getter", "(", "value", ")", ":", "if", "ET", ".", "iselement", "(", "value", ")", ":", "value", "=", "value", ".", "attrib", "try", ":", "# Use .group() if this is a regex match ob...
27.291667
0.001475
def configure_mock(self, **kwargs): """Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {'method.return_value': 3...
[ "def", "configure_mock", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "arg", ",", "val", "in", "sorted", "(", "kwargs", ".", "items", "(", ")", ",", "# we sort on the number of dots so that", "# attributes are set before we set attributes on", "# attribute...
44.4
0.002205
def setMotorShutdown(self, value, device=DEFAULT_DEVICE_ID, message=True): """ Set the motor shutdown on error status stored on the hardware device. :Parameters: value : `int` An integer indicating the effect on the motors when an error occurs. A `1` will cause...
[ "def", "setMotorShutdown", "(", "self", ",", "value", ",", "device", "=", "DEFAULT_DEVICE_ID", ",", "message", "=", "True", ")", ":", "return", "self", ".", "_setMotorShutdown", "(", "value", ",", "device", ",", "message", ")" ]
40.655172
0.002486
def taxids(self): """Distinct NCBI taxonomy identifiers (``taxid``) in :class:`.models.Entry` :return: NCBI taxonomy identifiers :rtype: list[int] """ r = self.session.query(distinct(models.Entry.taxid)).all() return [x[0] for x in r]
[ "def", "taxids", "(", "self", ")", ":", "r", "=", "self", ".", "session", ".", "query", "(", "distinct", "(", "models", ".", "Entry", ".", "taxid", ")", ")", ".", "all", "(", ")", "return", "[", "x", "[", "0", "]", "for", "x", "in", "r", "]" ...
34.5
0.010601
def _reset_model(self, table, model): """Set the model in the given table.""" old_sel_model = table.selectionModel() table.setModel(model) if old_sel_model: del old_sel_model
[ "def", "_reset_model", "(", "self", ",", "table", ",", "model", ")", ":", "old_sel_model", "=", "table", ".", "selectionModel", "(", ")", "table", ".", "setModel", "(", "model", ")", "if", "old_sel_model", ":", "del", "old_sel_model" ]
36.333333
0.008969
def sonify(annotation, sr=22050, duration=None, **kwargs): '''Sonify a jams annotation through mir_eval Parameters ---------- annotation : jams.Annotation The annotation to sonify sr = : positive number The sampling rate of the output waveform duration : float (optional) ...
[ "def", "sonify", "(", "annotation", ",", "sr", "=", "22050", ",", "duration", "=", "None", ",", "*", "*", "kwargs", ")", ":", "length", "=", "None", "if", "duration", "is", "None", ":", "duration", "=", "annotation", ".", "duration", "if", "duration", ...
29.320755
0.000623
def net_graph(block=None, split_state=False): """ Return a graph representation of the current block. Graph has the following form: { node1: { nodeA: edge1A, nodeB: edge1B}, node2: { nodeB: edge2B, nodeC: edge2C}, ... } aka: edge = graph[source][dest] Each node can...
[ "def", "net_graph", "(", "block", "=", "None", ",", "split_state", "=", "False", ")", ":", "# FIXME: make it not try to add unused wires (issue #204)", "block", "=", "working_block", "(", "block", ")", "from", ".", "wire", "import", "Register", "# self.sanity_check()"...
30.160714
0.00172
def cross_phenotype_jsd(data, groupby, bins, n_iter=100): """Jensen-Shannon divergence of features across phenotypes Parameters ---------- data : pandas.DataFrame A (n_samples, n_features) Dataframe groupby : mappable A samples to phenotypes mapping n_iter : int Number o...
[ "def", "cross_phenotype_jsd", "(", "data", ",", "groupby", ",", "bins", ",", "n_iter", "=", "100", ")", ":", "grouped", "=", "data", ".", "groupby", "(", "groupby", ")", "jsds", "=", "[", "]", "seen", "=", "set", "(", "[", "]", ")", "for", "phenoty...
34.183673
0.00058
def get_fd_from_freqtau(template=None, **kwargs): """Return frequency domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute for keyword arguments. A common example would be a row in an ...
[ "def", "get_fd_from_freqtau", "(", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "input_params", "=", "props", "(", "template", ",", "freqtau_required_args", ",", "*", "*", "kwargs", ")", "# Get required args", "f_0", ",", "tau", "=", "lm_freqs...
43.011628
0.00185
def post_signup(self, user, login_user=None, send_email=None): """Executes post signup actions: sending the signal, logging in the user and sending the welcome email """ self.signup_signal.send(self, user=user) if (login_user is None and self.options["login_user_on_signup"]) or ...
[ "def", "post_signup", "(", "self", ",", "user", ",", "login_user", "=", "None", ",", "send_email", "=", "None", ")", ":", "self", ".", "signup_signal", ".", "send", "(", "self", ",", "user", "=", "user", ")", "if", "(", "login_user", "is", "None", "a...
57.461538
0.009223
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ServiceContext for this ServiceInstance :rtype: twilio.rest.preview.acc_security.service.ServiceC...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "ServiceContext", "(", "self", ".", "_version", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return", ...
43.454545
0.010246
def prompt(self, error=''): """ Prompts the user to set the value for this item. :return <bool> | success """ if self.hidden: return True cmd = [self.label] if self.default is not None: cmd.append('(default: {0})'.format(self...
[ "def", "prompt", "(", "self", ",", "error", "=", "''", ")", ":", "if", "self", ".", "hidden", ":", "return", "True", "cmd", "=", "[", "self", ".", "label", "]", "if", "self", ".", "default", "is", "not", "None", ":", "cmd", ".", "append", "(", ...
25.744681
0.002389
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'...
[ "def", "sql_datetime_literal", "(", "dt", ":", "DateTimeLikeType", ",", "subsecond", ":", "bool", "=", "False", ")", "->", "str", ":", "# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt", "# <timestamp string>", "# ... the subsecond part is non-ANSI", "fmt",...
45.692308
0.00165
def pool_boy(Pool, traces, **kwargs): """ A context manager for handling the setup and cleanup of a pool object. :param Pool: any Class (not instance) that implements the multiprocessing Pool interface :param traces: The number of traces to process :type traces: int """ # All parall...
[ "def", "pool_boy", "(", "Pool", ",", "traces", ",", "*", "*", "kwargs", ")", ":", "# All parallel processing happens on a per-trace basis, we shouldn't create", "# more workers than there are traces", "n_cores", "=", "kwargs", ".", "get", "(", "'cores'", ",", "cpu_count",...
31.45
0.001543
def get_root_folder(): """ returns the home folder and program root depending on OS """ locations = { 'linux':{'hme':'/home/duncan/', 'core_folder':'/home/duncan/dev/src/python/AIKIF'}, 'win32':{'hme':'T:\\user\\', 'core_folder':'T:\\user\\dev\\src\\python\\AIKIF'}, 'cygwin':{'hme':os....
[ "def", "get_root_folder", "(", ")", ":", "locations", "=", "{", "'linux'", ":", "{", "'hme'", ":", "'/home/duncan/'", ",", "'core_folder'", ":", "'/home/duncan/dev/src/python/AIKIF'", "}", ",", "'win32'", ":", "{", "'hme'", ":", "'T:\\\\user\\\\'", ",", "'core_f...
42.333333
0.021823
def main(clargs=None): """Command line entry point.""" from argparse import ArgumentParser from librarian.library import Library import sys parser = ArgumentParser( description="A test runner for each card in a librarian library.") parser.add_argument("library", help="Library database")...
[ "def", "main", "(", "clargs", "=", "None", ")", ":", "from", "argparse", "import", "ArgumentParser", "from", "librarian", ".", "library", "import", "Library", "import", "sys", "parser", "=", "ArgumentParser", "(", "description", "=", "\"A test runner for each card...
34.65
0.001404
def start(self): """ Prepare the server to start serving connections. Configure the server socket handler and establish a TLS wrapping socket from which all client connections descend. Bind this TLS socket to the specified network address for the server. Raises: ...
[ "def", "start", "(", "self", ")", ":", "self", ".", "manager", "=", "multiprocessing", ".", "Manager", "(", ")", "self", ".", "policies", "=", "self", ".", "manager", ".", "dict", "(", ")", "policies", "=", "copy", ".", "deepcopy", "(", "operation_poli...
36.231579
0.000566
def init(quick): # type: () -> None """ Create an empty pelconf.yaml from template """ config_file = 'pelconf.yaml' prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file) if exists(config_file) and not click.confirm(shell.fmt(prompt)): log.info("Canceled") return ...
[ "def", "init", "(", "quick", ")", ":", "# type: () -> None", "config_file", "=", "'pelconf.yaml'", "prompt", "=", "\"-- <35>{} <32>already exists. Wipe it?<0>\"", ".", "format", "(", "config_file", ")", "if", "exists", "(", "config_file", ")", "and", "not", "click",...
35
0.001855
def recalc(self, sheet=None): 'reset column cache, attach to sheet, and reify name' if self._cachedValues: self._cachedValues.clear() if sheet: self.sheet = sheet self.name = self._name
[ "def", "recalc", "(", "self", ",", "sheet", "=", "None", ")", ":", "if", "self", ".", "_cachedValues", ":", "self", ".", "_cachedValues", ".", "clear", "(", ")", "if", "sheet", ":", "self", ".", "sheet", "=", "sheet", "self", ".", "name", "=", "sel...
33.571429
0.008299
def modulo11(base): """Calcula o dígito verificador (DV) para o argumento usando "Módulo 11". :param str base: String contendo os dígitos sobre os quais o DV será calculado, assumindo que o DV não está incluído no argumento. :return: O dígito verificador calculado. :rtype: int """ pes...
[ "def", "modulo11", "(", "base", ")", ":", "pesos", "=", "'23456789'", "*", "(", "(", "len", "(", "base", ")", "//", "8", ")", "+", "1", ")", "acumulado", "=", "sum", "(", "[", "int", "(", "a", ")", "*", "int", "(", "b", ")", "for", "a", ","...
35.5
0.001961
async def release_control(self): """Release control of QTM. """ cmd = "releasecontrol" return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "async", "def", "release_control", "(", "self", ")", ":", "cmd", "=", "\"releasecontrol\"", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")...
27.625
0.008772
def activate_hopscotch(driver): """ Allows you to use Hopscotch Tours with SeleniumBase http://linkedin.github.io/hopscotch/ """ hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style verify_script = ("""// ...
[ "def", "activate_hopscotch", "(", "driver", ")", ":", "hopscotch_css", "=", "constants", ".", "Hopscotch", ".", "MIN_CSS", "hopscotch_js", "=", "constants", ".", "Hopscotch", ".", "MIN_JS", "backdrop_style", "=", "style_sheet", ".", "hops_backdrop_style", "verify_sc...
38.875
0.000784
def _read_time_from_string(str1): """ Reads the time from a string in the format HH:MM:SS.S and returns :class: datetime.time """ full_time = [float(x) for x in str1.split(':')] hour = int(full_time[0]) minute = int(full_time[1]) if full_time[2] > 59.99: minute += 1 secon...
[ "def", "_read_time_from_string", "(", "str1", ")", ":", "full_time", "=", "[", "float", "(", "x", ")", "for", "x", "in", "str1", ".", "split", "(", "':'", ")", "]", "hour", "=", "int", "(", "full_time", "[", "0", "]", ")", "minute", "=", "int", "...
32.533333
0.001992
def _bind_method(self, name, unconditionally=False): """Generate a Matlab function and bind it to the instance This is where the magic happens. When an unknown attribute of the Matlab class is requested, it is assumed to be a call to a Matlab function, and is generated and bound to the ...
[ "def", "_bind_method", "(", "self", ",", "name", ",", "unconditionally", "=", "False", ")", ":", "# TODO: This does not work if the function is a mex function inside a folder of the same name", "exists", "=", "self", ".", "run_func", "(", "'exist'", ",", "name", ")", "[...
40.433962
0.002278
def _best_version(fields): """Detect the best version depending on the fields used.""" def _has_marker(keys, markers): for marker in markers: if marker in keys: return True return False keys = [] for key, value in fields.items(): if value in ([], 'UNK...
[ "def", "_best_version", "(", "fields", ")", ":", "def", "_has_marker", "(", "keys", ",", "markers", ")", ":", "for", "marker", "in", "markers", ":", "if", "marker", "in", "keys", ":", "return", "True", "return", "False", "keys", "=", "[", "]", "for", ...
42.085714
0.000995
def _get_num_locations(d): """ Find out how many locations are being parsed. Compare lengths of each coordinate list and return the max :param dict d: Geo metadata :return int: Max number of locations """ lengths = [] for key in EXCEL_GEO: try: if key != "siteName": ...
[ "def", "_get_num_locations", "(", "d", ")", ":", "lengths", "=", "[", "]", "for", "key", "in", "EXCEL_GEO", ":", "try", ":", "if", "key", "!=", "\"siteName\"", ":", "lengths", ".", "append", "(", "len", "(", "d", "[", "key", "]", ")", ")", "except"...
24.5
0.001965
def createsuperusers(): """ Creates all superusers defined in settings.INITIAL_SUPERUSERS. These superusers do not have any circles. They are plain superusers. However you may want to signup yourself and make this new user a super user then. """ from django.contrib.auth import models as auth_mod...
[ "def", "createsuperusers", "(", ")", ":", "from", "django", ".", "contrib", ".", "auth", "import", "models", "as", "auth_models", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "core", ".", "mail", "import", "send_mail", "from", ...
40.54717
0.002272
def get_device_id(handler_input): # type: (HandlerInput) -> Optional[AnyStr] """Return the device id from the input request. The method retrieves the `deviceId` property from the input request. This value uniquely identifies the device and is generally used as input for some Alexa-specific API call...
[ "def", "get_device_id", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> Optional[AnyStr]", "device", "=", "handler_input", ".", "request_envelope", ".", "context", ".", "system", ".", "device", "if", "device", ":", "return", "device", ".", "device_id", "e...
42.24
0.000926
def superuser_required(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_superuser: ...
[ "def", "superuser_required", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "def", "_checklogin", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "user", ".", "is_active", "and", "request", "...
44.869565
0.001898
def rsync_cmdline(self, src, dest, *rsync_options): """ Get argument list for meth:`subprocess.Popen()` to run rsync. :param src: source file or directory :param dest: destination file or directory :param rsync_options: any additional argument...
[ "def", "rsync_cmdline", "(", "self", ",", "src", ",", "dest", ",", "*", "rsync_options", ")", ":", "if", "not", "all", "(", "isinstance", "(", "item", ",", "str", ")", "for", "item", "in", "rsync_options", ")", ":", "raise", "TypeError", "(", "\"cmd ne...
40.589744
0.001234
def limitReal(x, max_denominator=1000000): """Creates an pysmt Real constant from x. Args: x (number): A number to be cast to a pysmt constant. max_denominator (int, optional): The maximum size of the denominator. Default 1000000. Returns: A Real constant with the given...
[ "def", "limitReal", "(", "x", ",", "max_denominator", "=", "1000000", ")", ":", "f", "=", "Fraction", "(", "x", ")", ".", "limit_denominator", "(", "max_denominator", ")", "return", "Real", "(", "(", "f", ".", "numerator", ",", "f", ".", "denominator", ...
32.285714
0.002151
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.3 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
[ "def", "content", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "paragraph", "=", "m", ".", "Paragraph", "(", "m", ".", "Image", "(", "'file:///%s/img/screenshots/'", "'petabencana-screenshot.png'", "%", "resources_path", "(", ")", ")", ",", ...
37.140351
0.00046
def custom_object_extension_prefix_lax(instance): """Ensure custom observable object extensions follow naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): ...
[ "def", "custom_object_extension_prefix_lax", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "not", "(", "'extensions'", "in", "obj", "and", "'type'", "in", "obj", "and", "o...
50.666667
0.001292
def format_snippet(sensor_graph): """Format this sensor graph as iotile command snippets. This includes commands to reset and clear previously stored sensor graphs. Args: sensor_graph (SensorGraph): the sensor graph that we want to format """ output = [] # Clear any old sensor gr...
[ "def", "format_snippet", "(", "sensor_graph", ")", ":", "output", "=", "[", "]", "# Clear any old sensor graph", "output", ".", "append", "(", "\"disable\"", ")", "output", ".", "append", "(", "\"clear\"", ")", "output", ".", "append", "(", "\"reset\"", ")", ...
31.591549
0.002162
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "if", "self", ".", "value", "==", "pi", ":", "return", "\"pi\"", "return", "ccode", "(", "self", ".", "value", ",", "precision", "=", "prec", ")" ]
29.666667
0.010929
def inherit_doc(cls): """ A decorator that makes a class inherit documentation from its parents. """ for name, func in vars(cls).items(): # only inherit docstring for public functions if name.startswith("_"): continue if not func.__doc__: for parent in cls...
[ "def", "inherit_doc", "(", "cls", ")", ":", "for", "name", ",", "func", "in", "vars", "(", "cls", ")", ".", "items", "(", ")", ":", "# only inherit docstring for public functions", "if", "name", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "if", ...
36.333333
0.001789
def display_markers(self): """Mark all the markers, from the dataset. This function should be called only when we load the dataset or when we change the settings. """ for rect in self.idx_markers: self.scene.removeItem(rect) self.idx_markers = [] mar...
[ "def", "display_markers", "(", "self", ")", ":", "for", "rect", "in", "self", ".", "idx_markers", ":", "self", ".", "scene", ".", "removeItem", "(", "rect", ")", "self", ".", "idx_markers", "=", "[", "]", "markers", "=", "[", "]", "if", "self", ".", ...
36.259259
0.00199
def link(self, x,y,w,h,link): "Put a link on the page" if not self.page in self.page_links: self.page_links[self.page] = [] self.page_links[self.page] += [(x*self.k,self.h_pt-y*self.k,w*self.k,h*self.k,link),]
[ "def", "link", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ",", "link", ")", ":", "if", "not", "self", ".", "page", "in", "self", ".", "page_links", ":", "self", ".", "page_links", "[", "self", ".", "page", "]", "=", "[", "]", "self"...
48.2
0.053061
def perform_flag(request, comment): """ Actually perform the flagging of a comment from a request. """ flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) sig...
[ "def", "perform_flag", "(", "request", ",", "comment", ")", ":", "flag", ",", "created", "=", "comments", ".", "models", ".", "CommentFlag", ".", "objects", ".", "get_or_create", "(", "comment", "=", "comment", ",", "user", "=", "request", ".", "user", "...
30.1875
0.042169
def read_csv_with_different_type(csv_name, column_types_dict, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/. Reads the CSV as string. """ csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv( csv_path, usecols=usecols, encoding="utf-8", ...
[ "def", "read_csv_with_different_type", "(", "csv_name", ",", "column_types_dict", ",", "usecols", "=", "None", ")", ":", "csv_path", "=", "os", ".", "path", ".", "join", "(", "DATA_FOLDER", ",", "csv_name", ")", "csv", "=", "pd", ".", "read_csv", "(", "csv...
31.058824
0.001838
def update(self, attributes=None): """Update this resource. Not all aspects of a resource can be updated. If the server rejects updates an error will be thrown. Keyword Arguments: attributes(dict): Attributes that are to be updated Returns: Resource: A ne...
[ "def", "update", "(", "self", ",", "attributes", "=", "None", ")", ":", "resource_type", "=", "self", ".", "_resource_type", "(", ")", "resource_path", "=", "self", ".", "_resource_path", "(", ")", "session", "=", "self", ".", "_session", "singleton", "=",...
36.038462
0.002079
def lex(args): """ Lex input and return a list of actions to perform. """ if len(args) == 0 or args[0] == SHOW: return [(SHOW, None)] elif args[0] == LOG: return [(LOG, None)] elif args[0] == ECHO: return [(ECHO, None)] elif args[0] == SET and args[1] == RATE: return ...
[ "def", "lex", "(", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", "or", "args", "[", "0", "]", "==", "SHOW", ":", "return", "[", "(", "SHOW", ",", "None", ")", "]", "elif", "args", "[", "0", "]", "==", "LOG", ":", "return", "["...
33
0.001403
def get(self, resource, **params): """ Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response obje...
[ "def", "get", "(", "self", ",", "resource", ",", "*", "*", "params", ")", ":", "return", "self", ".", "_execute", "(", "self", ".", "session", ".", "get", ",", "'GET'", ",", "resource", ",", "*", "*", "params", ")" ]
44.555556
0.00978
def multipack(polygons, sheet_size=None, iterations=50, density_escape=.95, spacing=0.094, quantity=None): """ Pack polygons into a rectangle by taking each Polygon's OBB and then packing that as a rectangle. Parameters ---------...
[ "def", "multipack", "(", "polygons", ",", "sheet_size", "=", "None", ",", "iterations", "=", "50", ",", "density_escape", "=", ".95", ",", "spacing", "=", "0.094", ",", "quantity", "=", "None", ")", ":", "from", ".", "polygons", "import", "polygons_obb", ...
31.05
0.000312
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
[ "def", "_perform_validation", "(", "self", ",", "path", ",", "value", ",", "results", ")", ":", "path", "=", "self", ".", "name", "if", "path", "==", "None", "or", "len", "(", "path", ")", "==", "0", "else", "path", "+", "\".\"", "+", "self", ".", ...
40.714286
0.008576
def return_dat(self, chan, begsam, endsam): """Return the data as 2D numpy.ndarray. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the first sample (inclusively) endsam : int inde...
[ "def", "return_dat", "(", "self", ",", "chan", ",", "begsam", ",", "endsam", ")", ":", "#n_sam = self.hdr[4]", "interval", "=", "endsam", "-", "begsam", "dat", "=", "empty", "(", "(", "len", "(", "chan", ")", ",", "interval", ")", ")", "#beg_block = floo...
29.777778
0.008671
def spawn( cls, argv, cwd=None, env=None, echo=True, preexec_fn=None, dimensions=(24, 80)): '''Start the given command in a child process in a pseudo terminal. This does all the fork/exec type of stuff for a pty, and returns an instance of PtyProcess. If preexec...
[ "def", "spawn", "(", "cls", ",", "argv", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "echo", "=", "True", ",", "preexec_fn", "=", "None", ",", "dimensions", "=", "(", "24", ",", "80", ")", ")", ":", "# Note that it is difficult for this meth...
40.70625
0.001349
def enter_transaction_management(using=None): """ Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or ...
[ "def", "enter_transaction_management", "(", "using", "=", "None", ")", ":", "if", "using", "is", "None", ":", "for", "using", "in", "tldap", ".", "backend", ".", "connections", ":", "connection", "=", "tldap", ".", "backend", ".", "connections", "[", "usin...
42.294118
0.001361
def execute_one_to_many_job(parent_class=None, get_unfinished_kwargs=None, get_unfinished_limit=None, parser_func=None, parser_func_kwargs=None, build_url_func_kwargs=None, ...
[ "def", "execute_one_to_many_job", "(", "parent_class", "=", "None", ",", "get_unfinished_kwargs", "=", "None", ",", "get_unfinished_limit", "=", "None", ",", "parser_func", "=", "None", ",", "parser_func_kwargs", "=", "None", ",", "build_url_func_kwargs", "=", "None...
41.230769
0.000521
def ConvBPDNOptions(opt=None, method='admm'): """A wrapper function that dynamically defines a class derived from the Options class associated with one of the implementations of the Convolutional BPDN problem, and returns an object instantiated with the provided parameters. The wrapper is designed t...
[ "def", "ConvBPDNOptions", "(", "opt", "=", "None", ",", "method", "=", "'admm'", ")", ":", "# Assign base class depending on method selection argument", "base", "=", "cbpdn_class_label_lookup", "(", "method", ")", ".", "Options", "# Nested class with dynamically determined ...
43.96
0.00089
def retrieve_paths(self, products, report_path, suffix=None): """Helper method to retrieve path from particular report metadata. :param products: Report products. :type products: list :param report_path: Path of the IF output. :type report_path: str :param suffix: Expe...
[ "def", "retrieve_paths", "(", "self", ",", "products", ",", "report_path", ",", "suffix", "=", "None", ")", ":", "paths", "=", "[", "]", "for", "product", "in", "products", ":", "path", "=", "ImpactReport", ".", "absolute_output_path", "(", "join", "(", ...
32.029412
0.001783
def diff(f, s): """ Given two models, return the difference between them. Args: f (Pybindbase): First element. s (Pybindbase): Second element. Returns: dict: A dictionary highlighting the differences. Examples: >>> diff = napalm_yang.utils.diff(candidate, runnin...
[ "def", "diff", "(", "f", ",", "s", ")", ":", "if", "isinstance", "(", "f", ",", "base", ".", "Root", ")", "or", "f", ".", "_yang_type", "in", "(", "\"container\"", ",", "None", ")", ":", "result", "=", "_diff_root", "(", "f", ",", "s", ")", "el...
27.711538
0.00067
def load_file(self, path, objtype=None, encoding='utf-8'): ''' Load the file specified by path This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk Args: path (string): The full or relative...
[ "def", "load_file", "(", "self", ",", "path", ",", "objtype", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "self", ".", "abspath", "(", "path", ")", "debug", "(", "'file path is %s'", "%", "path", ")", "if", "path", "in", "sel...
35.981132
0.001531
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size ...
[ "def", "on_resize", "(", "self", ",", "event", ")", ":", "self", ".", "_update_transforms", "(", ")", "if", "self", ".", "_central_widget", "is", "not", "None", ":", "self", ".", "_central_widget", ".", "size", "=", "self", ".", "size", "if", "len", "(...
27.133333
0.009501
def list_subnets(self, retrieve_all=True, **_params): """Fetches a list of all subnets for a project.""" return self.list('subnets', self.subnets_path, retrieve_all, **_params)
[ "def", "list_subnets", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'subnets'", ",", "self", ".", "subnets_path", ",", "retrieve_all", ",", "*", "*", "_params", ")" ]
53.5
0.009217
def ConvBPDNMask(*args, **kwargs): """A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to...
[ "def", "ConvBPDNMask", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract method selection argument or set default", "method", "=", "kwargs", ".", "pop", "(", "'method'", ",", "'admm'", ")", "# Assign base class depending on method selection argument", "bas...
39.558824
0.000726
def smooth(x, y, degree=1, logx=False, logy=False): """Smooth y-values and return new x, y pair. :param x,y: data values :param degree: degree of smoothing Smooth data by using a recursive linear interpolation technique. For degree = 0, return the original values. For degree = 1, generate a ...
[ "def", "smooth", "(", "x", ",", "y", ",", "degree", "=", "1", ",", "logx", "=", "False", ",", "logy", "=", "False", ")", ":", "if", "degree", "==", "0", ":", "return", "x", ",", "y", "else", ":", "if", "logx", ":", "x", "=", "np", ".", "log...
35.341463
0.000672
def strip_text_after_string(txt, junk): """ used to strip any poorly documented comments at the end of function defs """ if junk in txt: return txt[:txt.find(junk)] else: return txt
[ "def", "strip_text_after_string", "(", "txt", ",", "junk", ")", ":", "if", "junk", "in", "txt", ":", "return", "txt", "[", ":", "txt", ".", "find", "(", "junk", ")", "]", "else", ":", "return", "txt" ]
34
0.009569
def _is_related(parent_entry, child_entry): '''This function checks if a child entry is related to the parent entry. This is done by comparing the reference and sequence numbers.''' if parent_entry.header.mft_record == child_entry.header.base_record_ref and \ parent_entry.header.seq_n...
[ "def", "_is_related", "(", "parent_entry", ",", "child_entry", ")", ":", "if", "parent_entry", ".", "header", ".", "mft_record", "==", "child_entry", ".", "header", ".", "base_record_ref", "and", "parent_entry", ".", "header", ".", "seq_number", "==", "child_ent...
52.5
0.01171
def with_options(self, **kwargs): """Make a copy of this CodecOptions, overriding some options:: >>> from bson.codec_options import DEFAULT_CODEC_OPTIONS >>> DEFAULT_CODEC_OPTIONS.tz_aware False >>> options = DEFAULT_CODEC_OPTIONS.with_options(tz_aware=True) ...
[ "def", "with_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "CodecOptions", "(", "kwargs", ".", "get", "(", "'document_class'", ",", "self", ".", "document_class", ")", ",", "kwargs", ".", "get", "(", "'tz_aware'", ",", "self", ".", ...
39.761905
0.002339
def prune(symbol: str, all: str): """ Delete old prices, leaving just the last. """ app = PriceDbApplication() app.logger = logger count = 0 if symbol is not None: sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) deleted = app.prune(sec_symbol) if delete...
[ "def", "prune", "(", "symbol", ":", "str", ",", "all", ":", "str", ")", ":", "app", "=", "PriceDbApplication", "(", ")", "app", ".", "logger", "=", "logger", "count", "=", "0", "if", "symbol", "is", "not", "None", ":", "sec_symbol", "=", "SecuritySym...
24.705882
0.002294
async def async_fetch_image_data(self, image_name, username, password): """ Fetch image data from the Xeoma web server Arguments: image_name: the name of the image to fetch (i.e. image01) username: the username to directly access this image ...
[ "async", "def", "async_fetch_image_data", "(", "self", ",", "image_name", ",", "username", ",", "password", ")", ":", "params", "=", "{", "}", "cookies", "=", "self", ".", "get_session_cookie", "(", ")", "if", "username", "is", "not", "None", "and", "passw...
39.2
0.001992
def update_coordinates(self, coordinates=None): """Update the coordinates (and derived quantities) Argument: coordinates -- new Cartesian coordinates of the system """ if coordinates is not None: self.coordinates = coordinates self.numc = len(self.c...
[ "def", "update_coordinates", "(", "self", ",", "coordinates", "=", "None", ")", ":", "if", "coordinates", "is", "not", "None", ":", "self", ".", "coordinates", "=", "coordinates", "self", ".", "numc", "=", "len", "(", "self", ".", "coordinates", ")", "se...
49.043478
0.001739
def Counter(a, b, delta): """Counter derivative """ if b < a: return None return (b - a) / float(delta)
[ "def", "Counter", "(", "a", ",", "b", ",", "delta", ")", ":", "if", "b", "<", "a", ":", "return", "None", "return", "(", "b", "-", "a", ")", "/", "float", "(", "delta", ")" ]
17.571429
0.015504