text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online)
[ "def", "put_attachment", "(", "self", ",", "id", ",", "filename", ",", "file", ",", "content_type", ",", "include_online", "=", "False", ")", ":", "return", "self", ".", "put_attachment_data", "(", "id", ",", "filename", ",", "file", ".", "read", "(", ")...
88.333333
0.014981
def parse(text: str, style: Style = Style.auto) -> Docstring: """ Parse the docstring into its components. :param text: docstring text to parse :param style: docstring style :returns: parsed docstring representation """ if style != Style.auto: return _styles[style](text) rets =...
[ "def", "parse", "(", "text", ":", "str", ",", "style", ":", "Style", "=", "Style", ".", "auto", ")", "->", "Docstring", ":", "if", "style", "!=", "Style", ".", "auto", ":", "return", "_styles", "[", "style", "]", "(", "text", ")", "rets", "=", "[...
27.3
0.00177
def construct_request(model_type, client_name, client_pass, command, values): """ Construct the request url. Inputs: - model_type: PServer usage mode type. - client_name: The PServer client name. - client_pass: The PServer client's password. - command: A PServer command....
[ "def", "construct_request", "(", "model_type", ",", "client_name", ",", "client_pass", ",", "command", ",", "values", ")", ":", "base_request", "=", "(", "\"{model_type}?\"", "\"clnt={client_name}|{client_pass}&\"", "\"com={command}&{values}\"", ".", "format", "(", "mod...
44.7
0.001095
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ------...
[ "def", "write", "(", "self", ",", "equities", "=", "None", ",", "futures", "=", "None", ",", "exchanges", "=", "None", ",", "root_symbols", "=", "None", ",", "equity_supplementary_mappings", "=", "None", ",", "chunk_size", "=", "DEFAULT_CHUNK_SIZE", ")", ":"...
41.429688
0.001473
def discover(service, timeout=5, retries=5): ''' Discovers services on a network using the SSDP Protocol. ''' group = ('239.255.255.250', 1900) message = '\r\n'.join([ 'M-SEARCH * HTTP/1.1', 'HOST: {0}:{1}', 'MAN: "ssdp:discover"', 'ST: {st}', 'MX: 3', '', '']) so...
[ "def", "discover", "(", "service", ",", "timeout", "=", "5", ",", "retries", "=", "5", ")", ":", "group", "=", "(", "'239.255.255.250'", ",", "1900", ")", "message", "=", "'\\r\\n'", ".", "join", "(", "[", "'M-SEARCH * HTTP/1.1'", ",", "'HOST: {0}:{1}'", ...
29.470588
0.000966
def hide(self, selections): '''Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection represent...
[ "def", "hide", "(", "self", ",", "selections", ")", ":", "if", "'atoms'", "in", "selections", ":", "self", ".", "hidden_state", "[", "'atoms'", "]", "=", "selections", "[", "'atoms'", "]", "self", ".", "on_atom_hidden_changed", "(", ")", "if", "'bonds'", ...
37.96875
0.001605
def select(self, timeout=None): """ Wait until one or more of the registered file objects becomes ready or until the timeout expires. :param timeout: maximum wait time, in seconds (see below for special meaning) :returns: A list of pairs (key, events) fo...
[ "def", "select", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "epoll_timeout", "=", "-", "1", "elif", "timeout", "<=", "0", ":", "epoll_timeout", "=", "0", "else", ":", "epoll_timeout", "=", "timeout", "max_ev...
37.181818
0.001589
def read_param_file(filename, delimiter=None): """Unpacks a parameter file into a dictionary Reads a parameter file of format:: Param1,0,1,Group1,dist1 Param2,0,1,Group2,dist2 Param3,0,1,Group3,dist3 (Group and Dist columns are optional) Returns a dictionary containing: ...
[ "def", "read_param_file", "(", "filename", ",", "delimiter", "=", "None", ")", ":", "names", "=", "[", "]", "bounds", "=", "[", "]", "groups", "=", "[", "]", "dists", "=", "[", "]", "num_vars", "=", "0", "fieldnames", "=", "[", "'name'", ",", "'low...
33.192308
0.000375
def movementCompute(self, displacement, noiseFactor = 0): """ Shift the current active cells by a vector. @param displacement (pair of floats) A translation vector [di, dj]. """ if noiseFactor != 0: displacement = copy.deepcopy(displacement) xnoise = np.random.normal(0, noiseFactor...
[ "def", "movementCompute", "(", "self", ",", "displacement", ",", "noiseFactor", "=", "0", ")", ":", "if", "noiseFactor", "!=", "0", ":", "displacement", "=", "copy", ".", "deepcopy", "(", "displacement", ")", "xnoise", "=", "np", ".", "random", ".", "nor...
34.551724
0.009709
def plot(self, plot_limits=None, fixed_inputs=None, resolution=None, plot_raw=False, apply_link=False, which_data_ycols='all', which_data_rows='all', visible_dims=None, levels=20, samples=0, samples_likelihood=0, lower=2.5, upper=97.5, ...
[ "def", "plot", "(", "self", ",", "plot_limits", "=", "None", ",", "fixed_inputs", "=", "None", ",", "resolution", "=", "None", ",", "plot_raw", "=", "False", ",", "apply_link", "=", "False", ",", "which_data_ycols", "=", "'all'", ",", "which_data_rows", "=...
64.067568
0.008517
def _get_token( request=None, allowed_auth_schemes=('OAuth', 'Bearer'), allowed_query_keys=('bearer_token', 'access_token')): """Get the auth token for this request. Auth token may be specified in either the Authorization header or as a query param (either access_token or bearer_token). We'll check in ...
[ "def", "_get_token", "(", "request", "=", "None", ",", "allowed_auth_schemes", "=", "(", "'OAuth'", ",", "'Bearer'", ")", ",", "allowed_query_keys", "=", "(", "'bearer_token'", ",", "'access_token'", ")", ")", ":", "allowed_auth_schemes", "=", "_listlike_guard", ...
34.631579
0.008869
def existing_users(context): """ Look up the full user details for current workspace members """ members = IWorkspace(context).members info = [] for userid, details in members.items(): user = api.user.get(userid) if user is None: continue user = user.getUser()...
[ "def", "existing_users", "(", "context", ")", ":", "members", "=", "IWorkspace", "(", "context", ")", ".", "members", "info", "=", "[", "]", "for", "userid", ",", "details", "in", "members", ".", "items", "(", ")", ":", "user", "=", "api", ".", "user...
33.806452
0.000928
def _all_spec(self): """ All specifiers and their lengths. """ base = self._mod_spec for spec in self.basic_spec: base[spec] = self.basic_spec[spec] return base
[ "def", "_all_spec", "(", "self", ")", ":", "base", "=", "self", ".", "_mod_spec", "for", "spec", "in", "self", ".", "basic_spec", ":", "base", "[", "spec", "]", "=", "self", ".", "basic_spec", "[", "spec", "]", "return", "base" ]
19.363636
0.008969
def read_words(filename="nietzsche.txt", replace=None): """Read list format context from a file. For customized read_words method, see ``tutorial_generate_text.py``. Parameters ---------- filename : str a file path. replace : list of str replace original string by target string...
[ "def", "read_words", "(", "filename", "=", "\"nietzsche.txt\"", ",", "replace", "=", "None", ")", ":", "if", "replace", "is", "None", ":", "replace", "=", "[", "'\\n'", ",", "'<eos>'", "]", "with", "tf", ".", "gfile", ".", "GFile", "(", "filename", ","...
28.821429
0.001199
def to_nmtoken(rand_token): """ Convert a (random) token given as raw :class:`bytes` or :class:`int` to a valid NMTOKEN <https://www.w3.org/TR/xml/#NT-Nmtoken>. The encoding as a valid nmtoken is injective, ensuring that two different inputs cannot yield the same token. Nevertheless, it is ...
[ "def", "to_nmtoken", "(", "rand_token", ")", ":", "if", "isinstance", "(", "rand_token", ",", "int", ")", ":", "rand_token", "=", "rand_token", ".", "to_bytes", "(", "(", "rand_token", ".", "bit_length", "(", ")", "+", "7", ")", "//", "8", ",", "\"litt...
33.592593
0.002144
def rename_feature(self, mapobject_type_name, name, new_name): '''Renames a feature. Parameters ---------- mapobject_type_name: str name of the segmented objects type name: str name of the feature that should be renamed new_name: str n...
[ "def", "rename_feature", "(", "self", ",", "mapobject_type_name", ",", "name", ",", "new_name", ")", ":", "logger", ".", "info", "(", "'rename feature \"%s\" of experiment \"%s\", mapobject type \"%s\"'", ",", "name", ",", "self", ".", "experiment_name", ",", "mapobje...
32.96875
0.001842
def get_all(self): """Gets all items in file.""" logger.debug('Fetching items. Path: {data_file}'.format( data_file=self.data_file )) return load_file(self.data_file)
[ "def", "get_all", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Fetching items. Path: {data_file}'", ".", "format", "(", "data_file", "=", "self", ".", "data_file", ")", ")", "return", "load_file", "(", "self", ".", "data_file", ")" ]
29.285714
0.009479
def get(self, service_id, insert_defaults=None): """ Get a service. Args: service_id (str): The ID of the service. insert_defaults (boolean): If true, default values will be merged into the output. Returns: :py:class:`Service`: The se...
[ "def", "get", "(", "self", ",", "service_id", ",", "insert_defaults", "=", "None", ")", ":", "return", "self", ".", "prepare_model", "(", "self", ".", "client", ".", "api", ".", "inspect_service", "(", "service_id", ",", "insert_defaults", ")", ")" ]
33.125
0.002445
def get_rackspace_info(server_id, region, access_key_id, secret_access_key, username): """ queries Rackspace for details about a particular server id """ nova = connect_to_rackspace(region, access_key_id, secret_acce...
[ "def", "get_rackspace_info", "(", "server_id", ",", "region", ",", "access_key_id", ",", "secret_access_key", ",", "username", ")", ":", "nova", "=", "connect_to_rackspace", "(", "region", ",", "access_key_id", ",", "secret_access_key", ")", "server", "=", "nova",...
36.066667
0.0009
def APEValue(value, kind): """APEv2 tag value factory. Use this if you need to specify the value's type manually. Binary and text data are automatically detected by APEv2.__setitem__. """ if kind in (TEXT, EXTERNAL): if not isinstance(value, text_type): # stricter with py3 ...
[ "def", "APEValue", "(", "value", ",", "kind", ")", ":", "if", "kind", "in", "(", "TEXT", ",", "EXTERNAL", ")", ":", "if", "not", "isinstance", "(", "value", ",", "text_type", ")", ":", "# stricter with py3", "if", "PY3", ":", "raise", "TypeError", "(",...
31.043478
0.001359
def apply_uncertainty(self, value, source): """ Apply this branchset's uncertainty with value ``value`` to source ``source``, if it passes :meth:`filters <filter_source>`. This method is not called for uncertainties of types "gmpeModel" and "sourceModel". :param value: ...
[ "def", "apply_uncertainty", "(", "self", ",", "value", ",", "source", ")", ":", "if", "not", "self", ".", "filter_source", "(", "source", ")", ":", "# source didn't pass the filter", "return", "0", "if", "self", ".", "uncertainty_type", "in", "MFD_UNCERTAINTY_TY...
40.037037
0.001807
def object_to_dict(obj): ''' .. versionadded:: 2015.8.0 Convert an object to a dictionary ''' if isinstance(obj, list) or isinstance(obj, tuple): ret = [] for item in obj: ret.append(object_to_dict(item)) elif hasattr(obj, '__dict__'): ret = {} for it...
[ "def", "object_to_dict", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", "or", "isinstance", "(", "obj", ",", "tuple", ")", ":", "ret", "=", "[", "]", "for", "item", "in", "obj", ":", "ret", ".", "append", "(", "object_to_di...
25.526316
0.001988
def generate_timing_stats(file_list, var_list): """ Parse all of the timing files, and generate some statistics about the run. Args: file_list: A list of timing files to parse var_list: A list of variables to look for in the timing file Returns: A dict containing values tha...
[ "def", "generate_timing_stats", "(", "file_list", ",", "var_list", ")", ":", "timing_result", "=", "dict", "(", ")", "timing_summary", "=", "dict", "(", ")", "for", "file", "in", "file_list", ":", "timing_result", "[", "file", "]", "=", "functions", ".", "...
33.7
0.001923
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings tha...
[ "def", "ensure_all_alt_ids_have_a_nest", "(", "nest_spec", ",", "list_elements", ",", "all_ids", ")", ":", "unaccounted_alt_ids", "=", "[", "]", "for", "alt_id", "in", "all_ids", ":", "if", "alt_id", "not", "in", "list_elements", ":", "unaccounted_alt_ids", ".", ...
37.03125
0.000822
def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
[ "def", "_debug_log", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "debug", ":", "return", "sys", ".", "stderr", ".", "write", "(", "'{}\\n'", ".", "format", "(", "msg", ")", ")" ]
32
0.012195
def rename(args): """ %prog rename map markers.bed > renamed.map Rename markers according to the new mapping locations. """ p = OptionParser(rename.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) mstmap, bedfile = ar...
[ "def", "rename", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "rename", ".", "__doc__", ")", "p", ".", "set_outfile", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2",...
26.054054
0.001
def from_attrs(cls, desired_attrs=None, except_attrs=None, critical_attrs=None): """ Get a generator of mechanisms supporting the specified attributes. See RFC 5587's :func:`indicate_mechs_by_attrs` for more information. Args: desired_attrs ([OID]): Desire...
[ "def", "from_attrs", "(", "cls", ",", "desired_attrs", "=", "None", ",", "except_attrs", "=", "None", ",", "critical_attrs", "=", "None", ")", ":", "if", "isinstance", "(", "desired_attrs", ",", "roids", ".", "OID", ")", ":", "desired_attrs", "=", "set", ...
37.764706
0.002278
def search(self, **kwargs): '''Query this object (and its descendants). Parameters ---------- kwargs Each `(key, value)` pair encodes a search field in `key` and a target value in `value`. `key` must be a string, and should correspond to a property i...
[ "def", "search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "match", "=", "False", "r_query", "=", "{", "}", "myself", "=", "self", ".", "__class__", ".", "__name__", "# Pop this object name off the query", "for", "k", ",", "value", "in", "six", "."...
28.528571
0.000968
def items_convert(self, fields=[], **kwargs): '''taobao.taobaoke.items.convert 淘客商品转换 淘宝客商品转换''' request = TOPRequest('taobao.taobaoke.items.convert') if not fields: taobaokeItem = TaobaokeItem() fields = taobaokeItem.fields request['fields'] = fi...
[ "def", "items_convert", "(", "self", ",", "fields", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.taobaoke.items.convert'", ")", "if", "not", "fields", ":", "taobaokeItem", "=", "TaobaokeItem", "(", ")", "fie...
45.785714
0.013761
def get_derived_metric(self, id, **kwargs): # noqa: E501 """Get a specific registered query # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_derived_metric...
[ "def", "get_derived_metric", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_deriv...
42.238095
0.002205
def generate_config_file(self): """generate default config file from Configurables""" lines = ["# Configuration file for %s."%self.name] lines.append('') lines.append('c = get_config()') lines.append('') for cls in self.classes: lines.append(cls.class_config_s...
[ "def", "generate_config_file", "(", "self", ")", ":", "lines", "=", "[", "\"# Configuration file for %s.\"", "%", "self", ".", "name", "]", "lines", ".", "append", "(", "''", ")", "lines", ".", "append", "(", "'c = get_config()'", ")", "lines", ".", "append"...
39.222222
0.00831
def _get_auth(self, attachment, reg_key, md5=None): """ Step 1: get upload authorisation for a file """ mtypes = mimetypes.guess_type(attachment) digest = hashlib.md5() with open(attachment, "rb") as att: for chunk in iter(lambda: att.read(8192), b""): ...
[ "def", "_get_auth", "(", "self", ",", "attachment", ",", "reg_key", ",", "md5", "=", "None", ")", ":", "mtypes", "=", "mimetypes", ".", "guess_type", "(", "attachment", ")", "digest", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "attachme...
38.473684
0.002001
def rule_low_registers(self, arg): """Low registers are R0 - R7""" r_num = self.check_register(arg) if r_num > 7: raise iarm.exceptions.RuleError( "Register {} is not a low register".format(arg))
[ "def", "rule_low_registers", "(", "self", ",", "arg", ")", ":", "r_num", "=", "self", ".", "check_register", "(", "arg", ")", "if", "r_num", ">", "7", ":", "raise", "iarm", ".", "exceptions", ".", "RuleError", "(", "\"Register {} is not a low register\"", "....
40.333333
0.008097
def save(self, *args, **kwargs): """ **uid**: :code:`{office.uid}_{cycle.uid}_race` """ self.uid = '{}_{}_race'.format( self.office.uid, self.cycle.uid ) name_label = '{0} {1}'.format( self.cycle.name, self.office.label ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "uid", "=", "'{}_{}_race'", ".", "format", "(", "self", ".", "office", ".", "uid", ",", "self", ".", "cycle", ".", "uid", ")", "name_label", "=", "'{0} ...
24.205882
0.002336
def interleave(*arrays,**kwargs): ''' arr1 = [1,2,3,4] arr2 = ['a','b','c','d'] arr3 = ['@','#','%','*'] interleave(arr1,arr2,arr3) ''' anum = arrays.__len__() rslt = [] length = arrays[0].__len__() for j in range(0,length): for i in range(0,anum): ...
[ "def", "interleave", "(", "*", "arrays", ",", "*", "*", "kwargs", ")", ":", "anum", "=", "arrays", ".", "__len__", "(", ")", "rslt", "=", "[", "]", "length", "=", "arrays", "[", "0", "]", ".", "__len__", "(", ")", "for", "j", "in", "range", "("...
25.266667
0.010178
def _execute(self, command, stdin=None, stdout=subprocess.PIPE): """Executes the specified command relative to the repository root. Returns a tuple containing the return code and the process output. """ process = subprocess.Popen(command, shell=True, cwd=self.root_path, stdin=stdin, stdo...
[ "def", "_execute", "(", "self", ",", "command", ",", "stdin", "=", "None", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ",", "cwd", "=", "self", ".", ...
73.666667
0.008949
def get_udim(cls, name): """ Checks a string for a possible base name of an object (no prefix, no suffix) :param name: str, string that represents a possible name of an object :returns: int, the last found match because convention keeps UDIM markers at the end. """ match = cls._...
[ "def", "get_udim", "(", "cls", ",", "name", ")", ":", "match", "=", "cls", ".", "_get_regex_search", "(", "name", ",", "cls", ".", "REGEX_UDIM", ",", "match_index", "=", "-", "1", ")", "if", "match", ":", "match", ".", "update", "(", "{", "'match_int...
44.363636
0.008032
def connected_sets(C, mincount_connectivity=0, strong=True): """ Computes the connected sets of C. C : count matrix mincount_connectivity : float Minimum count which counts as a connection. strong : boolean True: Seek strongly connected sets. False: Seek weakly connected sets. """ ...
[ "def", "connected_sets", "(", "C", ",", "mincount_connectivity", "=", "0", ",", "strong", "=", "True", ")", ":", "import", "msmtools", ".", "estimation", "as", "msmest", "Cconn", "=", "C", ".", "copy", "(", ")", "Cconn", "[", "np", ".", "where", "(", ...
32.9375
0.001845
def haydavies(surface_tilt, surface_azimuth, dhi, dni, dni_extra, solar_zenith=None, solar_azimuth=None, projection_ratio=None): r''' Determine diffuse irradiance from the sky on a tilted surface using Hay & Davies' 1980 model .. math:: I_{d} = DHI ( A R_b + (1 - A) (\frac{1 + \co...
[ "def", "haydavies", "(", "surface_tilt", ",", "surface_azimuth", ",", "dhi", ",", "dni", ",", "dni_extra", ",", "solar_zenith", "=", "None", ",", "solar_azimuth", "=", "None", ",", "projection_ratio", "=", "None", ")", ":", "# if necessary, calculate ratio of titl...
36.255556
0.000298
def unzip(iterable): """The inverse of :func:`zip`, this function disaggregates the elements of the zipped *iterable*. The ``i``-th iterable contains the ``i``-th element from each element of the zipped iterable. The first element is used to to determine the length of the remaining elements. ...
[ "def", "unzip", "(", "iterable", ")", ":", "head", ",", "iterable", "=", "spy", "(", "iter", "(", "iterable", ")", ")", "if", "not", "head", ":", "# empty iterable, e.g. zip([], [], [])", "return", "(", ")", "# spy returns a one-length iterable as head", "head", ...
37.369565
0.000567
def remove_father(self, father): """ Remove the father node. Do nothing if the node is not a father Args: fathers: list of fathers to add """ self._fathers = [x for x in self._fathers if x.node_id != father.node_id]
[ "def", "remove_father", "(", "self", ",", "father", ")", ":", "self", ".", "_fathers", "=", "[", "x", "for", "x", "in", "self", ".", "_fathers", "if", "x", ".", "node_id", "!=", "father", ".", "node_id", "]" ]
36.285714
0.011538
def add_resource(self, handler, uri, methods=frozenset({'GET'}), **kwargs): """ Register a resource route. :param handler: function or class instance :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :p...
[ "def", "add_resource", "(", "self", ",", "handler", ",", "uri", ",", "methods", "=", "frozenset", "(", "{", "'GET'", "}", ")", ",", "*", "*", "kwargs", ")", ":", "sanic_args", "=", "(", "'host'", ",", "'strict_slashes'", ",", "'version'", ",", "'name'"...
35.763158
0.002149
def _add_get_or_change_to_method(self): """ Add a ``get_or_change_to_x()`` method to the element class for this child element. """ def get_or_change_to_child(obj): child = getattr(obj, self._prop_name) if child is not None: return child ...
[ "def", "_add_get_or_change_to_method", "(", "self", ")", ":", "def", "get_or_change_to_child", "(", "obj", ")", ":", "child", "=", "getattr", "(", "obj", ",", "self", ".", "_prop_name", ")", "if", "child", "is", "not", "None", ":", "return", "child", "remo...
34.875
0.002326
def expand_ranges(value): """ :param str value: The value to be "expanded". :return: A generator to yield the different resulting values from expanding the eventual ranges present in the input value. >>> tuple(expand_ranges("Item [1-3] - Bla")) ('Item 1 - Bla', 'Item 2 - Bla', 'Item 3 ...
[ "def", "expand_ranges", "(", "value", ")", ":", "match_dict", "=", "RANGE_REGEX", ".", "match", "(", "value", ")", ".", "groupdict", "(", ")", "# the regex is supposed to always match..", "before", "=", "match_dict", "[", "'before'", "]", "after", "=", "match_di...
41
0.001702
def get(self, request, *args, **kwargs): """ Retrieve list of nodes of the specified layer """ self.get_layer() # get nodes of layer nodes = self.get_nodes(request, *args, **kwargs) return Response(nodes)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "get_layer", "(", ")", "# get nodes of layer", "nodes", "=", "self", ".", "get_nodes", "(", "request", ",", "*", "args", ",", "*", "*", "kw...
39.833333
0.008197
def update(self, id, values, key_names='all'): """ Update reaction info for a selected row Parameters ---------- id: int row integer values: dict See write() method for details key_names: list or 'all' list with name of columns...
[ "def", "update", "(", "self", ",", "id", ",", "values", ",", "key_names", "=", "'all'", ")", ":", "con", "=", "self", ".", "connection", "or", "self", ".", "_connect", "(", ")", "self", ".", "_initialize", "(", "con", ")", "cur", "=", "con", ".", ...
33.084746
0.000995
def cli(env, keyword, package_type): """List packages that can be ordered via the placeOrder API. :: # List out all packages for ordering slcli order package-list # List out all packages with "server" in the name slcli order package-list --keyword server # Select onl...
[ "def", "cli", "(", "env", ",", "keyword", ",", "package_type", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "_filter", "=", "{", "'type'", "...
28.676471
0.000992
def salience(self, salience): """Activation salience value.""" lib.EnvSetActivationSalience(self._env, self._act, salience)
[ "def", "salience", "(", "self", ",", "salience", ")", ":", "lib", ".", "EnvSetActivationSalience", "(", "self", ".", "_env", ",", "self", ".", "_act", ",", "salience", ")" ]
45.666667
0.014388
def r_cred(ns_run, logw=None, simulate=False, probability=0.5): """One-tailed credible interval on the value of the radial coordinate (magnitude of theta vector). Parameters ---------- ns_run: dict Nested sampling run dict (see the data_processing module docstring for more details)....
[ "def", "r_cred", "(", "ns_run", ",", "logw", "=", "None", ",", "simulate", "=", "False", ",", "probability", "=", "0.5", ")", ":", "if", "logw", "is", "None", ":", "logw", "=", "nestcheck", ".", "ns_run_utils", ".", "get_logw", "(", "ns_run", ",", "s...
36.142857
0.000962
def get_property(self, filename): """Opens the file and reads the value""" with open(self.filepath(filename)) as f: return f.read().strip()
[ "def", "get_property", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "self", ".", "filepath", "(", "filename", ")", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", ".", "strip", "(", ")" ]
32.8
0.011905
def disable_all(self, disable): """Disables all modulation and outputs of the Standford MW func. generator""" commands = ['ENBH 0', #disable high freq. rear output 'ENBL 0', #disable low freq. front bnc 'MODL 0' #disable modulation ] ...
[ "def", "disable_all", "(", "self", ",", "disable", ")", ":", "commands", "=", "[", "'ENBH 0'", ",", "#disable high freq. rear output", "'ENBL 0'", ",", "#disable low freq. front bnc", "'MODL 0'", "#disable modulation", "]", "command_string", "=", "'\\n'", ".", "join",...
46.818182
0.015238
def parse_query_value(combined_value): """Parse value in form of '>value' to a lambda and a value.""" split = len(combined_value) - len(combined_value.lstrip('<>=')) operator = combined_value[:split] if operator == '': operator = '=' try: operator_func = search_operators[operator] ...
[ "def", "parse_query_value", "(", "combined_value", ")", ":", "split", "=", "len", "(", "combined_value", ")", "-", "len", "(", "combined_value", ".", "lstrip", "(", "'<>='", ")", ")", "operator", "=", "combined_value", "[", ":", "split", "]", "if", "operat...
39.071429
0.001786
def get_catalogs(self): """Pass through to provider CatalogLookupSession.get_catalogs""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs() cat_list = [] ...
[ "def", "get_catalogs", "(", "self", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinLookupSession.get_bins_template", "catalogs", "=", "self", ".", "_get_provider_session", "(", "'catalog_lookup_session'", ")", ".", "get_catalogs", "(", ")", "cat_li...
51.777778
0.008439
def _on_action_toggle(self): """Toggle the current fold trigger.""" block = FoldScope.find_parent_scope(self.editor.textCursor().block()) self.toggle_fold_trigger(block)
[ "def", "_on_action_toggle", "(", "self", ")", ":", "block", "=", "FoldScope", ".", "find_parent_scope", "(", "self", ".", "editor", ".", "textCursor", "(", ")", ".", "block", "(", ")", ")", "self", ".", "toggle_fold_trigger", "(", "block", ")" ]
47.5
0.010363
def aggcv(rlist): # pylint: disable=invalid-name """ Aggregate cross-validation results. If verbose_eval is true, progress is displayed in every call. If verbose_eval is an integer, progress will only be displayed every `verbose_eval` trees, tracked via trial. """ cvmap = {} idx = r...
[ "def", "aggcv", "(", "rlist", ")", ":", "# pylint: disable=invalid-name", "cvmap", "=", "{", "}", "idx", "=", "rlist", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", "for", "line", "in", "rlist", ":", "arr", "=", "line", ".", "split", "(", ...
31.633333
0.002045
def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution): """ Figure out the data, free_dims and create an Xgrid for the prediction. This is only implemented for two dimensions for now! """ #work out what the inputs are for plotting (1D or 2D) if fixed_inputs i...
[ "def", "helper_for_plot_data", "(", "self", ",", "X", ",", "plot_limits", ",", "visible_dims", ",", "fixed_inputs", ",", "resolution", ")", ":", "#work out what the inputs are for plotting (1D or 2D)", "if", "fixed_inputs", "is", "None", ":", "fixed_inputs", "=", "[",...
41.25
0.0125
def log_request_end_send(self, target_system, target_component, force_mavlink1=False): ''' Stop log transfer and resume normal logging target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' ...
[ "def", "log_request_end_send", "(", "self", ",", "target_system", ",", "target_component", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "log_request_end_encode", "(", "target_system", ",", "target_component", ")",...
48.555556
0.008989
def select_one_playlist(playlists): """Display the playlists returned by search api or user playlist. :params playlists: API['result']['playlists'] or API['playlist'] :return: a Playlist object. """ if len(playlists) == 1: select_i = 0 else: tabl...
[ "def", "select_one_playlist", "(", "playlists", ")", ":", "if", "len", "(", "playlists", ")", "==", "1", ":", "select_i", "=", "0", "else", ":", "table", "=", "PrettyTable", "(", "[", "'Sequence'", ",", "'Name'", "]", ")", "for", "i", ",", "playlist", ...
38.304348
0.002215
def _append_separations_to_results( self): """ *append angular separations to results* **Key Arguments:** # - **Return:** - None .. todo:: """ self.log.info('starting the ``_append_separations_to_results`` method') ...
[ "def", "_append_separations_to_results", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_append_separations_to_results`` method'", ")", "for", "row", "in", "self", ".", "results", ":", "if", "\"ra\"", "not", "in", "row", ":", "prin...
26
0.001951
def _get_symbols_to_logits_fn(self, max_decode_length): """Returns a decoding function that calculates logits of the next tokens.""" timing_signal = model_utils.get_position_encoding( max_decode_length + 1, self.params.hidden_size) decoder_self_attention_bias = model_utils.get_decoder_self_attentio...
[ "def", "_get_symbols_to_logits_fn", "(", "self", ",", "max_decode_length", ")", ":", "timing_signal", "=", "model_utils", ".", "get_position_encoding", "(", "max_decode_length", "+", "1", ",", "self", ".", "params", ".", "hidden_size", ")", "decoder_self_attention_bia...
40.842105
0.008811
def window(iter, pre_size=1, post_size=1): """ Given an iterable, return a new iterable which yields triples of (pre, item, post), where pre and post are the items preceeding and following the item (or None if no such item is appropriate). pre and post will always be pre_size and post_size in length. >>> example...
[ "def", "window", "(", "iter", ",", "pre_size", "=", "1", ",", "post_size", "=", "1", ")", ":", "pre_iter", ",", "iter", "=", "itertools", ".", "tee", "(", "iter", ")", "pre_iter", "=", "itertools", ".", "chain", "(", "(", "None", ",", ")", "*", "...
32.346154
0.028868
def create_cache(self, **kwargs): """ Creates an instance of the Cache Service. """ cache = predix.admin.cache.Cache(**kwargs) cache.create(**kwargs) cache.add_to_manifest(self) return cache
[ "def", "create_cache", "(", "self", ",", "*", "*", "kwargs", ")", ":", "cache", "=", "predix", ".", "admin", ".", "cache", ".", "Cache", "(", "*", "*", "kwargs", ")", "cache", ".", "create", "(", "*", "*", "kwargs", ")", "cache", ".", "add_to_manif...
29.875
0.00813
def _find_template(self, template, tree, blocks, with_filename, source, comment): """ If tree is true, then will display the track of template extend or include """ from uliweb import application from uliweb.core.template import _format_code de...
[ "def", "_find_template", "(", "self", ",", "template", ",", "tree", ",", "blocks", ",", "with_filename", ",", "source", ",", "comment", ")", ":", "from", "uliweb", "import", "application", "from", "uliweb", ".", "core", ".", "template", "import", "_format_co...
35.043478
0.002414
def del_device_notification(adr, notification_handle, user_handle): # type: (AmsAddr, int, int) -> None """Remove a device notification. :param pyads.structs.AmsAddr adr: AMS Address associated with the routing entry which is to be removed from the router. :param notification_handle: addr...
[ "def", "del_device_notification", "(", "adr", ",", "notification_handle", ",", "user_handle", ")", ":", "# type: (AmsAddr, int, int) -> None\r", "if", "port", "is", "not", "None", ":", "return", "adsSyncDelDeviceNotificationReqEx", "(", "port", ",", "adr", ",", "notif...
38.133333
0.001706
def get(self, **kwargs): """Get suggestions.""" completions = [] size = request.values.get('size', type=int) for k in self.suggesters.keys(): val = request.values.get(k) if val: # Get completion suggestions opts = copy.deepcopy(sel...
[ "def", "get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "completions", "=", "[", "]", "size", "=", "request", ".", "values", ".", "get", "(", "'size'", ",", "type", "=", "int", ")", "for", "k", "in", "self", ".", "suggesters", ".", "keys", ...
35.37037
0.001019
def expectation_sensitivity(T, a): r"""Sensitivity of expectation value of observable A=(a_i). Parameters ---------- T : (M, M) ndarray Transition matrix a : (M,) ndarray Observable, a[i] is the value of the observable at state i. Returns ------- S : (M, M) ndarray ...
[ "def", "expectation_sensitivity", "(", "T", ",", "a", ")", ":", "M", "=", "T", ".", "shape", "[", "0", "]", "S", "=", "numpy", ".", "zeros", "(", "(", "M", ",", "M", ")", ")", "for", "i", "in", "range", "(", "M", ")", ":", "S", "+=", "a", ...
23.904762
0.001916
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None): ''' .. versionadded:: 2015.5.1 Sync beacons from ``salt://_beacons`` to the minion saltenv The fileserver environment from which to sync. To sync from more than one environment, pass a comma-sep...
[ "def", "sync_beacons", "(", "saltenv", "=", "None", ",", "refresh", "=", "True", ",", "extmod_whitelist", "=", "None", ",", "extmod_blacklist", "=", "None", ")", ":", "ret", "=", "_sync", "(", "'beacons'", ",", "saltenv", ",", "extmod_whitelist", ",", "ext...
33.162162
0.001584
def _fix_call_activities_signavio(self, bpmn, filename): """ Signavio produces slightly invalid BPMN for call activity nodes... It is supposed to put a reference to the id of the called process in to the calledElement attribute. Instead it stores a string (which is the name of th...
[ "def", "_fix_call_activities_signavio", "(", "self", ",", "bpmn", ",", "filename", ")", ":", "for", "node", "in", "xpath_eval", "(", "bpmn", ")", "(", "\".//bpmn:callActivity\"", ")", ":", "calledElement", "=", "node", ".", "get", "(", "'calledElement'", ",", ...
51.4
0.000955
def _execute_trade_cmd( self, trade_cmd, users, expire_seconds, entrust_prop, send_interval ): """分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: """ for use...
[ "def", "_execute_trade_cmd", "(", "self", ",", "trade_cmd", ",", "users", ",", "expire_seconds", ",", "entrust_prop", ",", "send_interval", ")", ":", "for", "user", "in", "users", ":", "# check expire", "now", "=", "datetime", ".", "datetime", ".", "now", "(...
37.255319
0.002225
def update(self): """Update this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_update_cluster] :end-before: [END bigtable_update_cluster] .. note:: Updates the ``serve_nodes``. If you'd like to chan...
[ "def", "update", "(", "self", ")", ":", "client", "=", "self", ".", "_instance", ".", "_client", "# We are passing `None` for second argument location.", "# Location is set only at the time of creation of a cluster", "# and can not be changed after cluster has been created.", "return...
35.790698
0.001265
def stem(self, word): """ Stem an Hungarian word and return the stemmed form. :param word: The word that is stemmed. :type word: str or unicode :return: The stemmed form. :rtype: unicode """ word = word.lower() r1 = self.__r1_hungarian(word, sel...
[ "def", "stem", "(", "self", ",", "word", ")", ":", "word", "=", "word", ".", "lower", "(", ")", "r1", "=", "self", ".", "__r1_hungarian", "(", "word", ",", "self", ".", "__vowels", ",", "self", ".", "__digraphs", ")", "# STEP 1: Remove instrumental case"...
38.027972
0.000538
def do( self, params ): """Perform the underlying experiment and summarise its results. Our results are the summary statistics extracted from the results of the instances of the underlying experiment that we performed. We drop from the calculations any experiments whose completion statu...
[ "def", "do", "(", "self", ",", "params", ")", ":", "# perform the underlying experiment", "rc", "=", "self", ".", "experiment", "(", ")", ".", "run", "(", ")", "# extract the result dicts as a list", "results", "=", "rc", "[", "Experiment", ".", "RESULTS", "]"...
46.416667
0.009965
def line_cont_after_delim(ctx, s, line_len=40, delim=(',',), line_cont_token='&'): """ Insert newline (with preceeding `line_cont_token`) afer passing over a delimiter after traversing at least `line_len` number of characters Mako convenience function. E.g. fortran does no...
[ "def", "line_cont_after_delim", "(", "ctx", ",", "s", ",", "line_len", "=", "40", ",", "delim", "=", "(", "','", ",", ")", ",", "line_cont_token", "=", "'&'", ")", ":", "last", "=", "-", "1", "s", "=", "str", "(", "s", ")", "for", "i", ",", "t"...
33.75
0.0012
def send_mail(subject, message_plain, message_html, email_from, email_to, custom_headers={}, attachments=()): """ Build the email as a multipart message containing a multipart alternative for text (plain, HTML) plus all the attached files. """ if not message_plain and not message_h...
[ "def", "send_mail", "(", "subject", ",", "message_plain", ",", "message_html", ",", "email_from", ",", "email_to", ",", "custom_headers", "=", "{", "}", ",", "attachments", "=", "(", ")", ")", ":", "if", "not", "message_plain", "and", "not", "message_html", ...
31.642857
0.002191
def setShowTerritory(self, state): """ Sets the display mode for this widget to the inputed mode. :param state | <bool> """ if state == self._showTerritory: return self._showTerritory = state self.setDirty()
[ "def", "setShowTerritory", "(", "self", ",", "state", ")", ":", "if", "state", "==", "self", ".", "_showTerritory", ":", "return", "self", ".", "_showTerritory", "=", "state", "self", ".", "setDirty", "(", ")" ]
27.090909
0.012987
def three_digit(number): """ Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: >>> three_digit(1) '001' """ number = str(number) if len(number) == 1: retu...
[ "def", "three_digit", "(", "number", ")", ":", "number", "=", "str", "(", "number", ")", "if", "len", "(", "number", ")", "==", "1", ":", "return", "u'00%s'", "%", "number", "elif", "len", "(", "number", ")", "==", "2", ":", "return", "u'0%s'", "%"...
18.545455
0.002331
def _normalize_tags(chunk): """ (From textblob) Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN" """ ret = [] for word, tag in chunk: if tag == 'NP-TL' or tag == 'NP': ret.append((word, 'NNP')) continue if tag.endswith('-TL'): ret...
[ "def", "_normalize_tags", "(", "chunk", ")", ":", "ret", "=", "[", "]", "for", "word", ",", "tag", "in", "chunk", ":", "if", "tag", "==", "'NP-TL'", "or", "tag", "==", "'NP'", ":", "ret", ".", "append", "(", "(", "word", ",", "'NNP'", ")", ")", ...
24.3
0.00198
def find_file(filename=".env", project_root=None, skip_files=None, **kwargs): """Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script...
[ "def", "find_file", "(", "filename", "=", "\".env\"", ",", "project_root", "=", "None", ",", "skip_files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "search_tree", "=", "[", "]", "work_dir", "=", "os", ".", "getcwd", "(", ")", "skip_files", "=", ...
35.18
0.000553
def load_cropped_svhn(path='data', include_extra=True): """Load Cropped SVHN. The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images. Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanfo...
[ "def", "load_cropped_svhn", "(", "path", "=", "'data'", ",", "include_extra", "=", "True", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'cropped_svhn'", ")", "logging", ".",...
40.947368
0.002259
def feed(self, cube, pair): """ Feed Cube to the solver. """ self.cube = cube if pair not in ["FR", "RB", "BL", "LF"]: pair = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(pair)] self.pair = pair
[ "def", "feed", "(", "self", ",", "cube", ",", "pair", ")", ":", "self", ".", "cube", "=", "cube", "if", "pair", "not", "in", "[", "\"FR\"", ",", "\"RB\"", ",", "\"BL\"", ",", "\"LF\"", "]", ":", "pair", "=", "[", "\"FR\"", ",", "\"RB\"", ",", "...
32.25
0.011321
def create_package(self): """ Creates the package, writing the data out to the provided file-like object. """ # Check that all files exist (and calculate the longest shared path # prefix): self.input_path_prefix = None for filename in self.input_files: ...
[ "def", "create_package", "(", "self", ")", ":", "# Check that all files exist (and calculate the longest shared path", "# prefix):", "self", ".", "input_path_prefix", "=", "None", "for", "filename", "in", "self", ".", "input_files", ":", "if", "not", "os", ".", "path"...
37.177419
0.000845
def activities(self): """ Return all activites (fetch only once) """ if self._activities is None: self._activities = self._fetch_activities() return self._activities
[ "def", "activities", "(", "self", ")", ":", "if", "self", ".", "_activities", "is", "None", ":", "self", ".", "_activities", "=", "self", ".", "_fetch_activities", "(", ")", "return", "self", ".", "_activities" ]
39.4
0.00995
def speriodogram(x, NFFT=None, detrend=True, sampling=1., scale_by_freq=True, window='hamming', axis=0): """Simple periodogram, but matrices accepted. :param x: an array or matrix of data samples. :param NFFT: length of the data before FFT is computed (zero padding) :param bool detre...
[ "def", "speriodogram", "(", "x", ",", "NFFT", "=", "None", ",", "detrend", "=", "True", ",", "sampling", "=", "1.", ",", "scale_by_freq", "=", "True", ",", "window", "=", "'hamming'", ",", "axis", "=", "0", ")", ":", "x", "=", "np", ".", "array", ...
29.734043
0.008657
def create_storage_policy(profile_manager, policy_spec): ''' Creates a storage policy. profile_manager Reference to the profile manager. policy_spec Policy update spec. ''' try: profile_manager.Create(policy_spec) except vim.fault.NoPermission as exc: log.ex...
[ "def", "create_storage_policy", "(", "profile_manager", ",", "policy_spec", ")", ":", "try", ":", "profile_manager", ".", "Create", "(", "policy_spec", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "...
29.863636
0.001475
def request(self, path, method=None, data={}): """sends a request and gets a response from the Plivo REST API path: the URL (relative to the endpoint URL, after the /v1 method: the HTTP method to use, defaults to POST data: for POST or PUT, a dict of data to send returns Plivo ...
[ "def", "request", "(", "self", ",", "path", ",", "method", "=", "None", ",", "data", "=", "{", "}", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "'Invalid path parameter'", ")", "if", "method", "and", "method", "not", "in", "[", "'...
38.173913
0.002222
def classify_coupling(coupling): """Return a constant indicating the type of coupling. Depending on the type of coupling, one of the constants from :class:`.CouplingClass` is returned. Args: coupling: Tuple of minimum and maximum flux ratio """ lower, upper = coupling if lower is ...
[ "def", "classify_coupling", "(", "coupling", ")", ":", "lower", ",", "upper", "=", "coupling", "if", "lower", "is", "None", "and", "upper", "is", "None", ":", "return", "CouplingClass", ".", "Uncoupled", "elif", "lower", "is", "None", "or", "upper", "is", ...
32
0.001319
def runit(): """run things""" parser = OptionParser() parser.add_option('-s', '--server', help='The spamassassin spamd server to connect to', dest='server', type='str', default='standalone.home.topdog-software.com') ...
[ "def", "runit", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-s'", ",", "'--server'", ",", "help", "=", "'The spamassassin spamd server to connect to'", ",", "dest", "=", "'server'", ",", "type", "=", "'str'", "...
40.653846
0.000308
def hold(name=None, pkgs=None, **kwargs): # pylint: disable=W0613 ''' Version-lock packages .. note:: This function is provided primarily for compatibilty with some parts of :py:mod:`states.pkg <salt.states.pkg>`. Consider using Consider using :py:func:`pkg.lock <salt.modules.pkgng...
[ "def", "hold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "targets", "=", "[", "]", "if", "pkgs", ":", "targets", ".", "extend", "(", "pkgs", ")", "else", ":", "targets", ".", "...
33.492063
0.001381
def _freeze(self, action=None): """ Freeze this message for logging, registering it with C{action}. @param action: The L{Action} which is the context for this message. If C{None}, the L{Action} will be deduced from the current call stack. @return: A L{PMap} with...
[ "def", "_freeze", "(", "self", ",", "action", "=", "None", ")", ":", "if", "action", "is", "None", ":", "action", "=", "current_action", "(", ")", "if", "action", "is", "None", ":", "task_uuid", "=", "unicode", "(", "uuid4", "(", ")", ")", "task_leve...
35.193548
0.001784
def to_text(path, bucket_name='cloud-vision-84893', language='fr'): """Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invo...
[ "def", "to_text", "(", "path", ",", "bucket_name", "=", "'cloud-vision-84893'", ",", "language", "=", "'fr'", ")", ":", "\"\"\"OCR with PDF/TIFF as source files on GCS\"\"\"", "import", "os", "from", "google", ".", "cloud", "import", "vision", "from", "google", ".",...
35.207317
0.001685
def visit_Call(self, node): """ Visit a function call. We expect every logging statement and string format to be a function call. """ # CASE 1: We're in a logging statement if self.within_logging_statement(): if self.within_logging_argument() and self.is_for...
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "# CASE 1: We're in a logging statement", "if", "self", ".", "within_logging_statement", "(", ")", ":", "if", "self", ".", "within_logging_argument", "(", ")", "and", "self", ".", "is_format_call", "(", "n...
34.148936
0.002423
def print_one_train(client, verbosity=0): """Retrieve data for one train and print it. Returns the (data, metadata) dicts from the client. This is used by the -glimpse and -monitor command line tools. """ ts_before = time() data, meta = client.next() ts_after = time() if not data: ...
[ "def", "print_one_train", "(", "client", ",", "verbosity", "=", "0", ")", ":", "ts_before", "=", "time", "(", ")", "data", ",", "meta", "=", "client", ".", "next", "(", ")", "ts_after", "=", "time", "(", ")", "if", "not", "data", ":", "print", "(",...
31
0.000638
def get_string(self, direct=True, vasp4_compatible=False, significant_figures=6): """ Returns a string to be written as a POSCAR file. By default, site symbols are written, which means compatibility is for vasp >= 5. Args: direct (bool): Whether coordinate...
[ "def", "get_string", "(", "self", ",", "direct", "=", "True", ",", "vasp4_compatible", "=", "False", ",", "significant_figures", "=", "6", ")", ":", "# This corrects for VASP really annoying bug of crashing on lattices", "# which have triple product < 0. We will just invert the...
42.194444
0.002252
def get_parser(commands): """ Generate argument parser given a list of subcommand specifications. :type commands: list of (str, function, function) :arg commands: Each element must be a tuple ``(name, adder, runner)``. :param name: subcommand :param adder: a function takes ...
[ "def", "get_parser", "(", "commands", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "Formatter", ",", "description", "=", "__doc__", ",", "epilog", "=", "EPILOG", ",", ")", "subparsers", "=", "parser", ".", "add_sub...
34.647059
0.000826
def get_params(self, token_stack): """Get params from stack of tokens""" params = {} for token in token_stack: params.update(token.params) return params
[ "def", "get_params", "(", "self", ",", "token_stack", ")", ":", "params", "=", "{", "}", "for", "token", "in", "token_stack", ":", "params", ".", "update", "(", "token", ".", "params", ")", "return", "params" ]
31.833333
0.010204
def applications(self): """returns all the group applications to join""" url = self._url + "/applications" params = {"f" : "json"} res = self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy...
[ "def", "applications", "(", "self", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/applications\"", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "res", "=", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ","...
43.777778
0.008696
def on_sdl_keydown ( self, event ): "press ESCAPE to quit the application" key = event.key.keysym.sym if key == SDLK_ESCAPE: self.running = False
[ "def", "on_sdl_keydown", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", ".", "keysym", ".", "sym", "if", "key", "==", "SDLK_ESCAPE", ":", "self", ".", "running", "=", "False" ]
30.8
0.056962
def write(self, handle): '''Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' if not self._frames...
[ "def", "write", "(", "self", ",", "handle", ")", ":", "if", "not", "self", ".", "_frames", ":", "return", "def", "add", "(", "name", ",", "desc", ",", "bpe", ",", "format", ",", "bytes", ",", "*", "dimensions", ")", ":", "group", ".", "add_param", ...
43.333333
0.002194
def change_group(self, name, group): """Change the group of a host given the name of the host. @type name: str @type group: str """ m1 = OmapiMessage.open(b"host") m1.update_object(dict(name=name)) r1 = self.query_server(m1) if r1.opcode != OMAPI_OP_UPDATE: raise OmapiError("opening host %s failed" %...
[ "def", "change_group", "(", "self", ",", "name", ",", "group", ")", ":", "m1", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "m1", ".", "update_object", "(", "dict", "(", "name", "=", "name", ")", ")", "r1", "=", "self", ".", "query_server...
35.333333
0.029412
def flush(self): """Flush GL commands This is a wrapper for glFlush(). This also flushes the GLIR command queue. """ if hasattr(self, 'flush_commands'): context = self else: context = get_current_canvas().context context.glir.command('...
[ "def", "flush", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'flush_commands'", ")", ":", "context", "=", "self", "else", ":", "context", "=", "get_current_canvas", "(", ")", ".", "context", "context", ".", "glir", ".", "command", "(", "'...
29.916667
0.008108