text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def merge_tree(cwd, ref1, ref2, base=None, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionadded:: 2015.8.0 Interface to `git-merge-tree(1)`_, shows the merge result...
[ "def", "merge_tree", "(", "cwd", ",", "ref1", ",", "ref2", ",", "base", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ")", ":", "cwd", "=", "_expand_path",...
31.654321
0.000756
def string_matches_sans_whitespace(self, str1, str2_fuzzy_whitespace): """Check if two strings match, modulo their whitespace.""" str2_fuzzy_whitespace = re.sub('\s+', '\s*', str2_fuzzy_whitespace) return re.search(str2_fuzzy_whitespace, str1) is not None
[ "def", "string_matches_sans_whitespace", "(", "self", ",", "str1", ",", "str2_fuzzy_whitespace", ")", ":", "str2_fuzzy_whitespace", "=", "re", ".", "sub", "(", "'\\s+'", ",", "'\\s*'", ",", "str2_fuzzy_whitespace", ")", "return", "re", ".", "search", "(", "str2_...
69
0.014337
def eigs_s(infile="", dir_path='.'): """ Converts eigenparamters format data to s format Parameters ___________________ Input: file : input file name with eigenvalues (tau) and eigenvectors (V) with format: tau_1 V1_dec V1_inc tau_2 V2_dec V2_inc tau_3 V3_dec V3_inc Output ...
[ "def", "eigs_s", "(", "infile", "=", "\"\"", ",", "dir_path", "=", "'.'", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "infile", ")", "eigs_data", "=", "np", ".", "loadtxt", "(", "file", ")", "Ss", "=", "[", "]", ...
31.12
0.002494
def _fit_bmr_model(self, X, y): """Private function used to fit the BayesMinimumRisk model.""" self.f_bmr = BayesMinimumRiskClassifier() X_bmr = self.predict_proba(X) self.f_bmr.fit(y, X_bmr) return self
[ "def", "_fit_bmr_model", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "f_bmr", "=", "BayesMinimumRiskClassifier", "(", ")", "X_bmr", "=", "self", ".", "predict_proba", "(", "X", ")", "self", ".", "f_bmr", ".", "fit", "(", "y", ",", "X_bmr"...
39.666667
0.00823
def persist_upstream_structure(self): """Persist json file with the upstream steps structure, that is step names and their connections.""" persist_dir = os.path.join(self.experiment_directory, '{}_upstream_structure.json'.format(self.name)) logger.info('Step {}, saving upstream pipeline structur...
[ "def", "persist_upstream_structure", "(", "self", ")", ":", "persist_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "experiment_directory", ",", "'{}_upstream_structure.json'", ".", "format", "(", "self", ".", "name", ")", ")", "logger", ".", "...
82.8
0.011962
def move_rally(self, key): '''move a rally point''' a = key.split(' ') if a[0] != 'Rally' or len(a) != 2: print("Bad rally object %s" % key) return i = int(a[1]) self.moving_rally = i
[ "def", "move_rally", "(", "self", ",", "key", ")", ":", "a", "=", "key", ".", "split", "(", "' '", ")", "if", "a", "[", "0", "]", "!=", "'Rally'", "or", "len", "(", "a", ")", "!=", "2", ":", "print", "(", "\"Bad rally object %s\"", "%", "key", ...
30
0.008097
def boot_priority(self, boot_priority): """ Sets the boot priority for this QEMU VM. :param boot_priority: QEMU boot priority """ self._boot_priority = boot_priority log.info('QEMU VM "{name}" [{id}] has set the boot priority to {boot_priority}'.format(name=self._name, ...
[ "def", "boot_priority", "(", "self", ",", "boot_priority", ")", ":", "self", ".", "_boot_priority", "=", "boot_priority", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the boot priority to {boot_priority}'", ".", "format", "(", "name", "=", "self", ".",...
49.818182
0.008961
def delete_folder(self, folder_id, folder_etag=None, recursive=None): '''Delete specified folder. Pass folder_etag to avoid race conditions (raises error 412). recursive keyword does just what it says on the tin.''' return self( join('folders', folder_id), dict(recursive=recursive), method='delete', hea...
[ "def", "delete_folder", "(", "self", ",", "folder_id", ",", "folder_etag", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "self", "(", "join", "(", "'folders'", ",", "folder_id", ")", ",", "dict", "(", "recursive", "=", "recursive", ")",...
53.285714
0.029024
def smart_unicode_decode(encoded_string): """ Given an encoded string of unknown format, detect the format with chardet and return the unicode version. Example input from bug #11: ('\xfe\xff\x00I\x00n\x00s\x00p\x00e\x00c\x00t\x00i\x00o\x00n\x00' '\x00R\x00e\x00p\x00o...
[ "def", "smart_unicode_decode", "(", "encoded_string", ")", ":", "if", "not", "encoded_string", ":", "return", "u''", "# optimization -- first try ascii\r", "try", ":", "return", "encoded_string", ".", "decode", "(", "'ascii'", ")", "except", "UnicodeDecodeError", ":",...
37.69697
0.002351
def list_ikepolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IKEPolicies for a project.""" return self.list('ikepolicies', self.ikepolicies_path, retrieve_all, **_params)
[ "def", "list_ikepolicies", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'ikepolicies'", ",", "self", ".", "ikepolicies_path", ",", "retrieve_all", ",", "*", "*", "_params", ")" ]
60.25
0.008197
def save_forensic_reports_to_splunk(self, forensic_reports): """ Saves forensic DMARC reports to Splunk Args: forensic_reports (list): A list of forensic report dictionaries to save in Splunk """ logger.debug("Saving forensic reports to Splunk") ...
[ "def", "save_forensic_reports_to_splunk", "(", "self", ",", "forensic_reports", ")", ":", "logger", ".", "debug", "(", "\"Saving forensic reports to Splunk\"", ")", "if", "type", "(", "forensic_reports", ")", "==", "dict", ":", "forensic_reports", "=", "[", "forensi...
36.285714
0.001534
def projected_inverse(L): """ Supernodal multifrontal projected inverse. The routine computes the projected inverse .. math:: Y = P(L^{-T}L^{-1}) where :math:`L` is a Cholesky factor. On exit, the argument :math:`L` contains the projected inverse :math:`Y`. :param L: ...
[ "def", "projected_inverse", "(", "L", ")", ":", "assert", "isinstance", "(", "L", ",", "cspmatrix", ")", "and", "L", ".", "is_factor", "is", "True", ",", "\"L must be a cspmatrix factor\"", "n", "=", "L", ".", "symb", ".", "n", "snpost", "=", "L", ".", ...
33.619718
0.037444
def _get_serv(ret=None, commit=False): ''' Return a Pg cursor ''' _options = _get_options(ret) try: conn = psycopg2.connect(host=_options.get('host'), user=_options.get('user'), password=_options.get('passwd'), ...
[ "def", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "False", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "try", ":", "conn", "=", "psycopg2", ".", "connect", "(", "host", "=", "_options", ".", "get", "(", "'host'", ")", ...
30.225806
0.002068
def generichash_blake2b_salt_personal(data, digest_size=crypto_generichash_BYTES, key=b'', salt=b'', person=b''): """One shot hash interface :param data: the input data to the hash function :param digest_size: must be at most ...
[ "def", "generichash_blake2b_salt_personal", "(", "data", ",", "digest_size", "=", "crypto_generichash_BYTES", ",", "key", "=", "b''", ",", "salt", "=", "b''", ",", "person", "=", "b''", ")", ":", "_checkparams", "(", "digest_size", ",", "key", ",", "salt", "...
39.591837
0.000503
def order_categories(unordered_cats): ''' If categories are strings, then simple ordering is fine. If categories are values then I'll need to order based on their values. The final ordering is given as the original categories (including titles) in a ordered list. ''' no_titles = remove_titles(unordered_c...
[ "def", "order_categories", "(", "unordered_cats", ")", ":", "no_titles", "=", "remove_titles", "(", "unordered_cats", ")", "all_are_numbers", "=", "check_all_numbers", "(", "no_titles", ")", "if", "all_are_numbers", ":", "ordered_cats", "=", "order_cats_based_on_values"...
29.222222
0.014733
def bovy_print(fig_width=5,fig_height=5,axes_labelsize=16, text_fontsize=11,legend_fontsize=12, xtick_labelsize=10,ytick_labelsize=10, xtick_minor_size=2,ytick_minor_size=2, xtick_major_size=4,ytick_major_size=4): """ NAME: bovy_print PURP...
[ "def", "bovy_print", "(", "fig_width", "=", "5", ",", "fig_height", "=", "5", ",", "axes_labelsize", "=", "16", ",", "text_fontsize", "=", "11", ",", "legend_fontsize", "=", "12", ",", "xtick_labelsize", "=", "10", ",", "ytick_labelsize", "=", "10", ",", ...
27.380952
0.009513
def _restore_clipboard_selection(self, backup: str): """Restore the selection clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard ...
[ "def", "_restore_clipboard_selection", "(", "self", ",", "backup", ":", "str", ")", ":", "# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before", "# the pasting happens, causing the backup to be pasted instead of the desired clipboard conte...
69.555556
0.009464
def fetch_messages(self): """Fetch messages from the specified pull-queue. This should only be called a single time by a given MessageIterator object. If the MessageIterator is iterated over again, it should return the originally leased messages. """ if self._fetched: ...
[ "def", "fetch_messages", "(", "self", ")", ":", "if", "self", ".", "_fetched", ":", "return", "start", "=", "time", ".", "time", "(", ")", "loaded_messages", "=", "self", ".", "queue", ".", "lease_tasks_by_tag", "(", "self", ".", "duration", ",", "self",...
39.266667
0.001657
def moments(data,cntr): """ Returns (height, x, y, width_x, width_y) the gaussian parameters of a 2D distribution by calculating its moments. """ total = data.sum() #X, Y = np.indices(data.shape) #x = (X*data).sum()/total #y = (Y*data).sum()/total x,y = cntr xi = int(x) ...
[ "def", "moments", "(", "data", ",", "cntr", ")", ":", "total", "=", "data", ".", "sum", "(", ")", "#X, Y = np.indices(data.shape)", "#x = (X*data).sum()/total", "#y = (Y*data).sum()/total", "x", ",", "y", "=", "cntr", "xi", "=", "int", "(", "x", ")", "yi", ...
30.454545
0.008683
def try_int(o:Any)->Any: "Try to convert `o` to int, default to `o` if not possible." # NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o) if isinstance(o, collections.Sized) or getattr(o,'__arra...
[ "def", "try_int", "(", "o", ":", "Any", ")", "->", "Any", ":", "# NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this", "if", "isinstance", "(", "o", ",", "(", "np", ".", "ndarray", ",", "Tensor", ")", ")", ":", "return", "o",...
55.571429
0.032911
def new(cls, password, rounds): """Creates a PasswordHash from the given password.""" if isinstance(password, str): password = password.encode('utf-8') return cls(cls._new(password, rounds))
[ "def", "new", "(", "cls", ",", "password", ",", "rounds", ")", ":", "if", "isinstance", "(", "password", ",", "str", ")", ":", "password", "=", "password", ".", "encode", "(", "'utf-8'", ")", "return", "cls", "(", "cls", ".", "_new", "(", "password",...
44.4
0.00885
def visit_field(self, _, children): """A simple field. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``FILTERS``: list of instances of ``.resources.Field``. Returns ------- .resources.Field An in...
[ "def", "visit_field", "(", "self", ",", "_", ",", "children", ")", ":", "filters", "=", "children", "[", "0", "]", "return", "self", ".", "Field", "(", "getattr", "(", "filters", "[", "0", "]", ",", "'name'", ",", "None", ")", ",", "filters", "=", ...
28.851852
0.002484
def in_(self, *values): ''' A query to check if this query field is one of the values in ``values``. Produces a MongoDB ``$in`` expression. ''' return QueryExpression({ self : { '$in' : [self.get_type().wrap_value(value) for value in values] } })
[ "def", "in_", "(", "self", ",", "*", "values", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$in'", ":", "[", "self", ".", "get_type", "(", ")", ".", "wrap_value", "(", "value", ")", "for", "value", "in", "values", "]", "}", ...
42.428571
0.023102
def draw(self): """ Draws the submenu and its background. Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings. """ if not self.visible: # Simple visibility check, has to be tested to see if it works properly ...
[ "def", "draw", "(", "self", ")", ":", "if", "not", "self", ".", "visible", ":", "# Simple visibility check, has to be tested to see if it works properly", "return", "if", "not", "isinstance", "(", "self", ".", "submenu", ",", "Container", ")", ":", "glEnable", "("...
32.611111
0.016556
def _evaluate_field(self, record_dict, field_name, field_criteria): ''' a helper method for evaluating record values based upon query criteria :param record_dict: dictionary with model valid data to evaluate :param field_name: string with path to root of query field :param field_criter...
[ "def", "_evaluate_field", "(", "self", ",", "record_dict", ",", "field_name", ",", "field_criteria", ")", ":", "# determine value existence criteria", "value_exists", "=", "True", "if", "'value_exists'", "in", "field_criteria", ".", "keys", "(", ")", ":", "if", "n...
38.398907
0.001248
def nx_contracted_nodes(G, u, v, self_loops=True, inplace=False): """ copy of networkx function with inplace modification TODO: commit to networkx """ import itertools as it if G.is_directed(): in_edges = ((w, u, d) for w, x, d in G.in_edges(v, data=True) if self_loop...
[ "def", "nx_contracted_nodes", "(", "G", ",", "u", ",", "v", ",", "self_loops", "=", "True", ",", "inplace", "=", "False", ")", ":", "import", "itertools", "as", "it", "if", "G", ".", "is_directed", "(", ")", ":", "in_edges", "=", "(", "(", "w", ","...
33.206897
0.001009
def ensure_trafaret(trafaret): """ Helper for complex trafarets, takes trafaret instance or class and returns trafaret instance """ if isinstance(trafaret, Trafaret): return trafaret elif isinstance(trafaret, type): if issubclass(trafaret, Trafaret): return trafaret()...
[ "def", "ensure_trafaret", "(", "trafaret", ")", ":", "if", "isinstance", "(", "trafaret", ",", "Trafaret", ")", ":", "return", "trafaret", "elif", "isinstance", "(", "trafaret", ",", "type", ")", ":", "if", "issubclass", "(", "trafaret", ",", "Trafaret", "...
35.5
0.001524
def pyprf_sim(strPrior, strStmApr, lgcNoise=False, lgcRtnNrl=True, lstRat=None, lgcTest=False): """ Simulate pRF response given pRF parameters and stimulus apertures. Parameters ---------- strPrior : str Absolute file path of config file used for pRF fitting. strStmApr : s...
[ "def", "pyprf_sim", "(", "strPrior", ",", "strStmApr", ",", "lgcNoise", "=", "False", ",", "lgcRtnNrl", "=", "True", ",", "lstRat", "=", "None", ",", "lgcTest", "=", "False", ")", ":", "# %% Load configuration settings that were used for fitting", "# Load config par...
43.222857
0.000129
def delete(self): """ Deletes all layers within this LayeredWidget before deleting itself. Recommended to call if you are removing the widget, but not yet exiting the interpreter. """ for layer,_ in self.layers: layer.delete() self.layers = [] ...
[ "def", "delete", "(", "self", ")", ":", "for", "layer", ",", "_", "in", "self", ".", "layers", ":", "layer", ".", "delete", "(", ")", "self", ".", "layers", "=", "[", "]", "self", ".", "_layers", "=", "{", "}", "super", "(", "LayeredWidget", ",",...
33.727273
0.015748
def update(tgt, tgt_type='glob', clear=False, mine_functions=None): ''' .. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear...
[ "def", "update", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "clear", "=", "False", ",", "mine_functions", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'salt.execute'", "]", "(", "tgt", ",", "'mine.update'", ",", "tgt_type", "=", "tgt_type",...
30
0.000828
def register(self, event, fn): """ Tell the object to run `fn` whenever a message of type `event` is received. """ self._callbacks.setdefault(event, []).append(fn) return fn
[ "def", "register", "(", "self", ",", "event", ",", "fn", ")", ":", "self", ".", "_callbacks", ".", "setdefault", "(", "event", ",", "[", "]", ")", ".", "append", "(", "fn", ")", "return", "fn" ]
30.714286
0.00905
def _from_arrays(self, x, y, z): """ Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. Paramete...
[ "def", "_from_arrays", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "x", "=", "np", ".", "unique", "(", "x", ".", "ravel", "(", ")", ")", "y", "=", "np", ".", "unique", "(", "y", ".", "ravel", "(", ")", ")", "z", "=", "np", ".", ...
34.807692
0.002151
def connect(self, host, port): ''' Connect to a host and port. ''' # Clear the connect state immediately since we're no longer connected # at this point. self._connected = False # Only after the socket has connected do we clear this state; closed # must b...
[ "def", "connect", "(", "self", ",", "host", ",", "port", ")", ":", "# Clear the connect state immediately since we're no longer connected", "# at this point.", "self", ".", "_connected", "=", "False", "# Only after the socket has connected do we clear this state; closed", "# must...
49.632653
0.000806
def trim_data_uber(arrays, conditions): """ Non-destructively selects data from the supplied list of arrays based on the supplied list of conditions. Importantly, if any of the conditions are not met for the n'th data point, the n'th data point is rejected for all supplied arrays. Example ...
[ "def", "trim_data_uber", "(", "arrays", ",", "conditions", ")", ":", "# dumb conditions", "if", "len", "(", "conditions", ")", "==", "0", ":", "return", "arrays", "if", "len", "(", "arrays", ")", "==", "0", ":", "return", "[", "]", "# find the indices to k...
35.612903
0.014991
def partial_derivative(f, x, n, nargs, delta=DELTA): """ Calculate partial derivative using central finite difference approximation. :param f: function :param x: sequence of arguments :param n: index of argument derivateve is with respect to :param nargs: number of arguments :param ...
[ "def", "partial_derivative", "(", "f", ",", "x", ",", "n", ",", "nargs", ",", "delta", "=", "DELTA", ")", ":", "dx", "=", "np", ".", "zeros", "(", "(", "nargs", ",", "len", "(", "x", "[", "n", "]", ")", ")", ")", "# scale delta by (|x| + 1.0) to av...
44.117647
0.001305
def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return Tru...
[ "def", "set_warndays", "(", "name", ",", "warndays", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "warndays", "==", "pre_info", "[", "'warn'", "]", ":", "return", "True", "cmd", "=", "'passwd -w {0} {1}'", ".", "format", "(", "warndays", ",...
26.95
0.001792
def set_context(self, cell_type): """Set protein expression data and mutational status as node attribute This method uses :py:mod:`indra.databases.context_client` to get protein expression levels and mutational status for a given cell type and set a node attribute for proteins according...
[ "def", "set_context", "(", "self", ",", "cell_type", ")", ":", "node_names", "=", "[", "node", "[", "'n'", "]", "for", "node", "in", "self", ".", "cx", "[", "'nodes'", "]", "]", "res_expr", "=", "context_client", ".", "get_protein_expression", "(", "node...
42.537037
0.000851
def config_prefix(prefix): """contextmanager for multiple invocations of API with a common prefix supported API functions: (register / get / set )__option Warning: This is not thread - safe, and won't work properly if you import the API functions into your module using the "from x import y" construct....
[ "def", "config_prefix", "(", "prefix", ")", ":", "# Note: reset_option relies on set_option, and on key directly", "# it does not fit in to this monkey-patching scheme", "global", "register_option", ",", "get_option", ",", "set_option", ",", "reset_option", "def", "wrap", "(", ...
30.195652
0.000697
def external_system_identifiers2marc(self, key, value): """Populate the ``035`` MARC field. Also populates the ``970`` MARC field through side effects and an extra ``id_dict`` dictionary that holds potentially duplicate IDs that are post-processed in a filter. """ def _is_scheme_cernkey(id_, sc...
[ "def", "external_system_identifiers2marc", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_is_scheme_cernkey", "(", "id_", ",", "schema", ")", ":", "return", "schema", "==", "'CERNKEY'", "def", "_is_scheme_spires", "(", "id_", ",", "schema", ")", "...
28.621622
0.000913
def delete_zone(zone, restart=True): ''' Delete an existing zone CLI Example: .. code-block:: bash salt '*' firewalld.delete_zone my_zone By default firewalld will be reloaded. However, to avoid reloading you need to specify the restart as False .. code-block:: bash sal...
[ "def", "delete_zone", "(", "zone", ",", "restart", "=", "True", ")", ":", "out", "=", "__mgmt", "(", "zone", ",", "'zone'", ",", "'delete'", ")", "if", "restart", ":", "if", "out", "==", "'success'", ":", "return", "__firewall_cmd", "(", "'--reload'", ...
19.8
0.001927
async def echo_all(app, message): """Send and recieve a message from all running echo servers""" # Loop through all registered server addresses for address in app.kv.get_prefix('address.').values(): # Parse the host and port from the stored address host, port = address.decode().split(':') ...
[ "async", "def", "echo_all", "(", "app", ",", "message", ")", ":", "# Loop through all registered server addresses", "for", "address", "in", "app", ".", "kv", ".", "get_prefix", "(", "'address.'", ")", ".", "values", "(", ")", ":", "# Parse the host and port from t...
43.7
0.002242
def build_cpp(build_context, target, compiler_config, workspace_dir): """Compile and link a C++ binary for `target`.""" rmtree(workspace_dir) binary = join(*split(target.name)) objects = link_cpp_artifacts(build_context, target, workspace_dir, True) buildenv_workspace = build_context.conf.host_to_bu...
[ "def", "build_cpp", "(", "build_context", ",", "target", ",", "compiler_config", ",", "workspace_dir", ")", ":", "rmtree", "(", "workspace_dir", ")", "binary", "=", "join", "(", "*", "split", "(", "target", ".", "name", ")", ")", "objects", "=", "link_cpp_...
50.105263
0.001031
def show_offload(devname): ''' Queries the specified network device for the state of protocol offload and other features CLI Example: .. code-block:: bash salt '*' ethtool.show_offload <devname> ''' try: sg = ethtool.get_sg(devname) and "on" or "off" except IOError: ...
[ "def", "show_offload", "(", "devname", ")", ":", "try", ":", "sg", "=", "ethtool", ".", "get_sg", "(", "devname", ")", "and", "\"on\"", "or", "\"off\"", "except", "IOError", ":", "sg", "=", "\"not supported\"", "try", ":", "tso", "=", "ethtool", ".", "...
21.974359
0.002235
def middleware(self, *args, **kwargs): """ Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. """ ...
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "register_middleware", "(", "_middleware", ")", ":", "future_middleware", "=", "FutureMiddleware", "(", "_middleware", ",", "args", ",", "kwargs", ")", "self", "....
37.607143
0.001852
def from_dict(input_dict): """ Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the de...
[ "def", "from_dict", "(", "input_dict", ")", ":", "import", "copy", "input_dict", "=", "copy", ".", "deepcopy", "(", "input_dict", ")", "mapping_class", "=", "input_dict", ".", "pop", "(", "'class'", ")", "input_dict", "[", "\"name\"", "]", "=", "str", "(",...
47.368421
0.002179
def pad_img(im, pad): """Pad positively with 0 or negatively (cut) Parameters ---------- im: 2d array The image pad: 4 numbers (ytop, ybottom, xleft, xright) or (imin, imax, jmin, jmax) Returns ------- im: 2d array The padded (or cropped) image offset: 2 num...
[ "def", "pad_img", "(", "im", ",", "pad", ")", ":", "im", "=", "np", ".", "asarray", "(", "im", ")", "pad", "=", "np", ".", "asarray", "(", "pad", ")", "# get shape", "shape", "=", "im", ".", "shape", "# extract offset from padding", "offset", "=", "-...
25.8125
0.000778
def export_distributions(region=None, key=None, keyid=None, profile=None): ''' Get details of all CloudFront distributions. Produces results that can be used to create an SLS file. CLI Example: .. code-block:: bash salt-call boto_cloudfront.export_distributions --out=txt |\ se...
[ "def", "export_distributions", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "results", "=", "OrderedDict", "(", ")", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", ...
32.244444
0.000669
def set_port_info(self, webport, mediaport, httpsport, onvifport, callback=None): ''' Set http port and media port of camera. ''' params = {'webPort' : webport, 'mediaPort' : mediaport, 'httpsPort' : httpsport, ...
[ "def", "set_port_info", "(", "self", ",", "webport", ",", "mediaport", ",", "httpsport", ",", "onvifport", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'webPort'", ":", "webport", ",", "'mediaPort'", ":", "mediaport", ",", "'httpsPort'", ":...
40.727273
0.017467
def select(self, *column_names, **kwargs): ''' Select the provided column names from the model, do not return an entity, do not involve the rom session, just get the raw and/or processed column data from Redis. Keyword-only arguments: * *include_pk=False* - whether ...
[ "def", "select", "(", "self", ",", "*", "column_names", ",", "*", "*", "kwargs", ")", ":", "include_pk", "=", "kwargs", ".", "pop", "(", "'include_pk'", ",", "False", ")", "decode", "=", "kwargs", ".", "pop", "(", "'decode'", ",", "True", ")", "ff", ...
43.621622
0.002424
def resolve_file_name(fname, dir_path='.'): """ Parse file name information and output full path. Allows input as: fname == /path/to/file.txt or fname == file.txt, dir_path == /path/to Either way, returns /path/to/file.txt. Used in conversion scripts. Parameters ---------- f...
[ "def", "resolve_file_name", "(", "fname", ",", "dir_path", "=", "'.'", ")", ":", "if", "not", "fname", ":", "return", "''", "file_dir_path", ",", "file_name", "=", "os", ".", "path", ".", "split", "(", "fname", ")", "if", "(", "not", "file_dir_path", "...
24.833333
0.001292
def send_stderr(self, s): """ Send data to the channel on the "stderr" stream. This is normally only used by servers to send output from shell commands -- clients won't use this. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsib...
[ "def", "send_stderr", "(", "self", ",", "s", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_EXTENDED_DATA", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "m", ".", "add_int", "(", "1", ")", "retu...
38.130435
0.002225
def from_onnx(self, graph): """Construct symbol from onnx graph. The inputs from onnx graph is vague, only providing "1", "2"... For convenience, we rename the `real` input names to "input_0", "input_1"... And renaming parameters to "param_0", "param_1"... Parameters ---...
[ "def", "from_onnx", "(", "self", ",", "graph", ")", ":", "# parse network inputs, aka parameters", "for", "init_tensor", "in", "graph", ".", "initializer", ":", "if", "not", "init_tensor", ".", "name", ".", "strip", "(", ")", ":", "raise", "ValueError", "(", ...
45.774194
0.002069
def disqus_sso_script(context): """ Provides a generic context variable which adds single-sign-on support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and ``COMMENTS_DISQUS_API_SECRET_KEY`` are specified. """ settings = context["settings"] public_key = getattr(settings, "COMMENTS_DISQUS_A...
[ "def", "disqus_sso_script", "(", "context", ")", ":", "settings", "=", "context", "[", "\"settings\"", "]", "public_key", "=", "getattr", "(", "settings", ",", "\"COMMENTS_DISQUS_API_PUBLIC_KEY\"", ",", "\"\"", ")", "secret_key", "=", "getattr", "(", "settings", ...
45.285714
0.001546
def bind_unix_socket(self, bind_addr): """Create (or recreate) a UNIX socket object.""" if IS_WINDOWS: """ Trying to access socket.AF_UNIX under Windows causes an AttributeError. """ raise ValueError( # or RuntimeError? 'AF_UNI...
[ "def", "bind_unix_socket", "(", "self", ",", "bind_addr", ")", ":", "if", "IS_WINDOWS", ":", "\"\"\"\n Trying to access socket.AF_UNIX under Windows\n causes an AttributeError.\n \"\"\"", "raise", "ValueError", "(", "# or RuntimeError?", "'AF_UNIX soc...
30.539683
0.001007
def authenticate_server(self, response): """ Uses GSSAPI to authenticate the server. Returns True on success, False on failure. """ log.debug("authenticate_server(): Authenticate header: {0}".format( _negotiate_value(response))) host = urlparse(response.url...
[ "def", "authenticate_server", "(", "self", ",", "response", ")", ":", "log", ".", "debug", "(", "\"authenticate_server(): Authenticate header: {0}\"", ".", "format", "(", "_negotiate_value", "(", "response", ")", ")", ")", "host", "=", "urlparse", "(", "response",...
38.125
0.002398
def list_math_subtraction(a, b): """! @brief Calculates subtraction of two lists. @details Each element from list 'a' is subtracted by element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematical subtraction. @param[in] b (list): List of elements tha...
[ "def", "list_math_subtraction", "(", "a", ",", "b", ")", ":", "return", "[", "a", "[", "i", "]", "-", "b", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", "]" ]
39.416667
0.016529
def ram2disk(self): """Move internal data from RAM to disk.""" values = self.series self.deactivate_ram() self.diskflag = True self._save_int(values) self.update_fastaccess()
[ "def", "ram2disk", "(", "self", ")", ":", "values", "=", "self", ".", "series", "self", ".", "deactivate_ram", "(", ")", "self", ".", "diskflag", "=", "True", "self", ".", "_save_int", "(", "values", ")", "self", ".", "update_fastaccess", "(", ")" ]
30.857143
0.009009
def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False): ''' Execute an arbitrary action on a module. module name of the module to be executed action name of the module's action to be run module_parameter additional params passed to ...
[ "def", "exec_action", "(", "module", ",", "action", ",", "module_parameter", "=", "None", ",", "action_parameter", "=", "None", ",", "state_only", "=", "False", ")", ":", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'eselect --brief --colour=no {0} {1} {...
24.688889
0.001732
def get_int(byte_array, signed=True): """ Gets the specified integer from its byte array. This should be used by this module alone, as it works with big endian. :param byte_array: the byte array representing th integer. :param signed: whether the number is signed or not. :return: the integer re...
[ "def", "get_int", "(", "byte_array", ",", "signed", "=", "True", ")", ":", "return", "int", ".", "from_bytes", "(", "byte_array", ",", "byteorder", "=", "'big'", ",", "signed", "=", "signed", ")" ]
42.1
0.002326
def delete_user_favorite(self, series_id): """ Deletes the series of the provided id from the favorites list of the current user. :param series_id: The TheTVDB id of the series. :return: a python dictionary with either the result of the search or an error from TheTVDB. """ ...
[ "def", "delete_user_favorite", "(", "self", ",", "series_id", ")", ":", "return", "self", ".", "parse_raw_response", "(", "requests_util", ".", "run_request", "(", "'delete'", ",", "self", ".", "API_BASE_URL", "+", "'/user/favorites/%d'", "%", "series_id", ",", ...
54.909091
0.009772
def pdhg_stepsize(L, tau=None, sigma=None): r"""Default step sizes for `pdhg`. Parameters ---------- L : `Operator` or float Operator or norm of the operator that are used in the `pdhg` method. If it is an `Operator`, the norm is computed with ``Operator.norm(estimate=True)``. ...
[ "def", "pdhg_stepsize", "(", "L", ",", "tau", "=", "None", ",", "sigma", "=", "None", ")", ":", "if", "tau", "is", "not", "None", "and", "sigma", "is", "not", "None", ":", "return", "float", "(", "tau", ")", ",", "float", "(", "sigma", ")", "L_no...
29.75
0.000508
def guess_saves(zone, data): """Return types with guessed DST saves""" saves = {} details = {} for (time0, type0), (time1, type1) in pairs(data.times): is_dst0 = bool(data.types[type0][1]) is_dst1 = bool(data.types[type1][1]) if (is_dst0, is_dst1) == (False, True): sh...
[ "def", "guess_saves", "(", "zone", ",", "data", ")", ":", "saves", "=", "{", "}", "details", "=", "{", "}", "for", "(", "time0", ",", "type0", ")", ",", "(", "time1", ",", "type1", ")", "in", "pairs", "(", "data", ".", "times", ")", ":", "is_ds...
40.162162
0.000657
def _exception_handler(self, e): """This exception handler catches should only be invoked when we need to quit the workflow prematurely. It takes in an `ApiException` which will contain the error, details of the error and status code. When the application is in testing mode, it...
[ "def", "_exception_handler", "(", "self", ",", "e", ")", ":", "if", "isinstance", "(", "e", ".", "message", ",", "dict", ")", ":", "return", "self", ".", "_prep_response", "(", "e", ".", "message", "[", "'msg'", "]", ",", "status", "=", "e", ".", "...
52.5625
0.002336
def _find_install_targets(name=None, version=None, pkgs=None, sources=None, skip_suggestions=False, pkg_verify=False, normalize=True, igno...
[ "def", "_find_install_targets", "(", "name", "=", "None", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "skip_suggestions", "=", "False", ",", "pkg_verify", "=", "False", ",", "normalize", "=", "True", ",", "ign...
41.385965
0.000897
def exists(self, file_path, check_link=False): """Return true if a path points to an existing file system object. Args: file_path: The path to examine. Returns: (bool) True if the corresponding object exists. Raises: TypeError: if file_path is None...
[ "def", "exists", "(", "self", ",", "file_path", ",", "check_link", "=", "False", ")", ":", "if", "check_link", "and", "self", ".", "islink", "(", "file_path", ")", ":", "return", "True", "file_path", "=", "make_string_path", "(", "file_path", ")", "if", ...
32.189189
0.00163
def guess_encoding(self): """Guess encoding using the language, falling back on chardet. :return: the guessed encoding. :rtype: str """ logger.info('Guessing encoding for language %s', self.language) # always try utf-8 first encodings = ['utf-8'] # add...
[ "def", "guess_encoding", "(", "self", ")", ":", "logger", ".", "info", "(", "'Guessing encoding for language %s'", ",", "self", ".", "language", ")", "# always try utf-8 first", "encodings", "=", "[", "'utf-8'", "]", "# add language-specific encodings", "if", "self", ...
33.509804
0.001137
def delete_service_key(self, service_name, key_name): """ Delete a service key for the given service. """ key = self.get_service_key(service_name, key_name) logging.info("Deleting service key %s for service %s" % (key, service_name)) return self.api.delete(key['metadata']...
[ "def", "delete_service_key", "(", "self", ",", "service_name", ",", "key_name", ")", ":", "key", "=", "self", ".", "get_service_key", "(", "service_name", ",", "key_name", ")", "logging", ".", "info", "(", "\"Deleting service key %s for service %s\"", "%", "(", ...
46
0.009146
def _IsType(clean_lines, nesting_state, expr): """Check if expression looks like a type name, returns true if so. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks b...
[ "def", "_IsType", "(", "clean_lines", ",", "nesting_state", ",", "expr", ")", ":", "# Keep only the last token in the expression", "last_word", "=", "Match", "(", "r'^.*(\\b\\S+)$'", ",", "expr", ")", "if", "last_word", ":", "token", "=", "last_word", ".", "group"...
34.803279
0.010994
def has_override(self, addr): """Test if device has data from a device override setting.""" override = False if self._overrides.get(addr, None) is not None: override = True return override
[ "def", "has_override", "(", "self", ",", "addr", ")", ":", "override", "=", "False", "if", "self", ".", "_overrides", ".", "get", "(", "addr", ",", "None", ")", "is", "not", "None", ":", "override", "=", "True", "return", "override" ]
37.833333
0.008621
def side_effect(func, iterable, chunk_size=None, before=None, after=None): """Invoke *func* on each item in *iterable* (or on each *chunk_size* group of items) before yielding the item. `func` must be a function that takes a single argument. Its return value will be discarded. *before* and *after*...
[ "def", "side_effect", "(", "func", ",", "iterable", ",", "chunk_size", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "try", ":", "if", "before", "is", "not", "None", ":", "before", "(", ")", "if", "chunk_size", "is", ...
30.491525
0.000539
def clear_old_backups(self, block_id): """ If we limit the number of backups we make, then clean out old ones older than block_id - backup_max_age (given in the constructor) This method does nothing otherwise. Return None on success Raise exception on error """ ...
[ "def", "clear_old_backups", "(", "self", ",", "block_id", ")", ":", "assert", "self", ".", "setup", ",", "\"Not set up yet. Call .db_setup() first!\"", "if", "self", ".", "backup_max_age", "is", "None", ":", "# never delete backups", "return", "# find old backups ", ...
33.369565
0.010127
def find(self, txt): """ returns a list of records containing text """ result = [] for d in self.data: if txt in d: result.append(d) return result
[ "def", "find", "(", "self", ",", "txt", ")", ":", "result", "=", "[", "]", "for", "d", "in", "self", ".", "data", ":", "if", "txt", "in", "d", ":", "result", ".", "append", "(", "d", ")", "return", "result" ]
23.777778
0.009009
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
[ "def", "get_model_classes", "(", "self", ")", ":", "self", ".", "_import_plugins", "(", ")", "return", "[", "plugin", ".", "model", "for", "plugin", "in", "self", ".", "plugins", ".", "values", "(", ")", "]" ]
42
0.011673
def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None): """Return the length of a variant Args: alt_len(int) ref_len(int) category(str) svtype(str) svlen(int) """ # -1 would indicate uncertain length length = -1 if category in ('snv...
[ "def", "get_length", "(", "alt_len", ",", "ref_len", ",", "category", ",", "pos", ",", "end", ",", "svtype", "=", "None", ",", "svlen", "=", "None", ")", ":", "# -1 would indicate uncertain length", "length", "=", "-", "1", "if", "category", "in", "(", "...
26.758621
0.001244
def _run_cwltool(args): """Run with cwltool -- reference implementation. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cwltool_work")) tmp_dir = utils.safe_makedir(os.path.join(work_dir, "tmpcwl")) log_file = ...
[ "def", "_run_cwltool", "(", "args", ")", ":", "main_file", ",", "json_file", ",", "project_name", "=", "_get_main_and_json", "(", "args", ".", "directory", ")", "work_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "os", ...
54.266667
0.002415
def autodiscover(): ''' Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want. ''' from .compat import importlib # Bail out if autodiscover didn't finish loading from...
[ "def", "autodiscover", "(", ")", ":", "from", ".", "compat", "import", "importlib", "# Bail out if autodiscover didn't finish loading from a previous call so", "# that we avoid running autodiscover again when the URLconf is loaded by", "# the exception handler to resolve the handler500 view....
35.305882
0.001945
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base ...
[ "def", "_get_backend_base", "(", ")", ":", "base_class_name", "=", "getattr", "(", "settings", ",", "'POSTGRES_EXTRA_DB_BACKEND_BASE'", ",", "'django.db.backends.postgresql'", ")", "base_class_module", "=", "importlib", ".", "import_module", "(", "base_class_name", "+", ...
36.805556
0.000735
def insert_recording(hw): """Insert recording `hw` into database.""" mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], ...
[ "def", "insert_recording", "(", "hw", ")", ":", "mysql", "=", "utils", ".", "get_mysql_cfg", "(", ")", "connection", "=", "pymysql", ".", "connect", "(", "host", "=", "mysql", "[", "'host'", "]", ",", "user", "=", "mysql", "[", "'user'", "]", ",", "p...
41.155556
0.000527
def submit_fatjar(cl_args, unknown_args, tmp_dir): ''' We use the packer to make a package for the jar and dump it to a well-known location. We then run the main method of class with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS. This will run the jar file with the topol...
[ "def", "submit_fatjar", "(", "cl_args", ",", "unknown_args", ",", "tmp_dir", ")", ":", "# execute main of the topology to create the topology definition", "topology_file", "=", "cl_args", "[", "'topology-file-name'", "]", "main_class", "=", "cl_args", "[", "'topology-class-...
34.641026
0.010079
def signature_cert_chain_url(url): """Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl header value sent by request. Returns: bool: True if valid, False otherwise. """ r = urlparse(url) if no...
[ "def", "signature_cert_chain_url", "(", "url", ")", ":", "r", "=", "urlparse", "(", "url", ")", "if", "not", "r", ".", "scheme", ".", "lower", "(", ")", "==", "'https'", ":", "warnings", ".", "warn", "(", "'Certificate URL scheme is invalid.'", ")", "retur...
32.64
0.00119
def is_loop_helper(node): """ Returns True is node is a loop helper e.g. {{ loop.index }} or {{ loop.first }} """ return hasattr(node, 'node') and isinstance(node.node, nodes.Name) and node.node.name == 'loop'
[ "def", "is_loop_helper", "(", "node", ")", ":", "return", "hasattr", "(", "node", ",", "'node'", ")", "and", "isinstance", "(", "node", ".", "node", ",", "nodes", ".", "Name", ")", "and", "node", ".", "node", ".", "name", "==", "'loop'" ]
44.2
0.013333
def InsertFloatArg(self, string="", **_): """Inserts a Float argument.""" try: float_value = float(string) return self.InsertArg(float_value) except (TypeError, ValueError): raise ParseError("%s is not a valid float." % string)
[ "def", "InsertFloatArg", "(", "self", ",", "string", "=", "\"\"", ",", "*", "*", "_", ")", ":", "try", ":", "float_value", "=", "float", "(", "string", ")", "return", "self", ".", "InsertArg", "(", "float_value", ")", "except", "(", "TypeError", ",", ...
35.857143
0.015564
def setup_environment(chip, args_file=None): """Setup the SCons environment for compiling arm cortex code. This will return an env that has all of the correct settings and create a command line arguments file for GCC that contains all of the required flags. The use of a command line argument file passe...
[ "def", "setup_environment", "(", "chip", ",", "args_file", "=", "None", ")", ":", "config", "=", "ConfigManager", "(", ")", "# Make sure we never get MSVC settings for windows since that has the wrong command line flags for gcc", "if", "platform", ".", "system", "(", ")", ...
38.402985
0.002274
def dropEvent( self, event ): """ Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDropEvent> """ filt = self.dragDropFilter() if ( filt and not filt(self, event) ): return su...
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "filt", "=", "self", ".", "dragDropFilter", "(", ")", "if", "(", "filt", "and", "not", "filt", "(", "self", ",", "event", ")", ")", ":", "return", "super", "(", "XTableWidget", ",", "self", "...
29.083333
0.022222
def kruskal_mst(graph): """Implements Kruskal's Algorithm for finding minimum spanning trees. Assumes a non-empty, connected graph. """ edges_accepted = 0 ds = DisjointSet() pq = PriorityQueue() accepted_edges = [] label_lookup = {} nodes = graph.get_all_node_ids() num_vertices ...
[ "def", "kruskal_mst", "(", "graph", ")", ":", "edges_accepted", "=", "0", "ds", "=", "DisjointSet", "(", ")", "pq", "=", "PriorityQueue", "(", ")", "accepted_edges", "=", "[", "]", "label_lookup", "=", "{", "}", "nodes", "=", "graph", ".", "get_all_node_...
25.432432
0.001024
def post_soup(self, *args, **kwargs): """ Shortcut for ``post`` which returns a ``BeautifulSoup`` element """ return BeautifulSoup(self.post(*args, **kwargs).text)
[ "def", "post_soup", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "BeautifulSoup", "(", "self", ".", "post", "(", "*", "args", ",", "*", "*", "kwargs", ")", ".", "text", ")" ]
38.2
0.010256
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ self.Y = sp.prox_l1l2(self.AX + self.U, (self.lmbda/self.rho)*self.wl1, (self.mu/self.rho), axis=self.cri.axisC) cbpdn.GenericConvBPDN.ystep(self)
[ "def", "ystep", "(", "self", ")", ":", "self", ".", "Y", "=", "sp", ".", "prox_l1l2", "(", "self", ".", "AX", "+", "self", ".", "U", ",", "(", "self", ".", "lmbda", "/", "self", ".", "rho", ")", "*", "self", ".", "wl1", ",", "(", "self", "....
37.5
0.009772
def _get_place_details(place_id, api_key, sensor=False, language=lang.ENGLISH): """Gets a detailed place response. keyword arguments: place_id -- The unique identifier for the required place. """ url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL, ...
[ "def", "_get_place_details", "(", "place_id", ",", "api_key", ",", "sensor", "=", "False", ",", "language", "=", "lang", ".", "ENGLISH", ")", ":", "url", ",", "detail_response", "=", "_fetch_remote_json", "(", "GooglePlaces", ".", "DETAIL_API_URL", ",", "{", ...
47
0.00149
def renderContent(self): """ Walk from outputs to inputs for each public signal register port of wrap node if required lazy load all operator and statement nodes for signals """ stm = self.stm portCtx = self.portCtx # for each inputs and outputs render exp...
[ "def", "renderContent", "(", "self", ")", ":", "stm", "=", "self", ".", "stm", "portCtx", "=", "self", ".", "portCtx", "# for each inputs and outputs render expression trees", "# walk statements and render muxs and memories", "for", "o", "in", "stm", ".", "_outputs", ...
36.341463
0.001961
def _mpda(self, re_grammar, splitstring=0): """ Args: re_grammar (list): A list of grammar rules splitstring (bool): A boolean for enabling or disabling the splitting of symbols using a space Returns: PDA: The generated PDA ...
[ "def", "_mpda", "(", "self", ",", "re_grammar", ",", "splitstring", "=", "0", ")", ":", "cnfgrammar", "=", "CNFGenerator", "(", "re_grammar", ")", "if", "not", "self", ".", "alphabet", ":", "self", ".", "_extract_alphabet", "(", "cnfgrammar", ")", "cnftopd...
39.5
0.001235
def UV_H(self): """ UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets This is UV_H function, but the returned implications are respected by all attribute sets of this context. This corresponds to a multiplication or & ...
[ "def", "UV_H", "(", "self", ")", ":", "h", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "&", "y", ",", "(", "H", "(", "g", ",", "self", ".", "width", "-", "1", ")", "for", "g", "in", "self", ")", ")", "return", "UV_H", "(", "h",...
45.2
0.019523
def insert_child(self, child, index): """ Inserts given child at given index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> no...
[ "def", "insert_child", "(", "self", ",", "child", ",", "index", ")", ":", "if", "index", "<", "0", "or", "index", ">", "len", "(", "self", ".", "__children", ")", ":", "return", "False", "self", ".", "__children", ".", "insert", "(", "index", ",", ...
31.413793
0.00213
def analyse(content, splitlines=True, format=None, **kwargs): ''' Japanese text > tokenize/txt/html ''' sents = DekoText.parse(content, splitlines=splitlines, **kwargs) doc = [] final = sents # Generate output if format == 'html': for sent in sents: doc.append(sent.to_ruby())...
[ "def", "analyse", "(", "content", ",", "splitlines", "=", "True", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sents", "=", "DekoText", ".", "parse", "(", "content", ",", "splitlines", "=", "splitlines", ",", "*", "*", "kwargs", ")...
34.529412
0.001658
def namespace(namespace): """Context manager for stacking the current thread-local default namespace. Exiting the context sets the thread-local default namespace back to the previously-set namespace. If there is no previous namespace, then the thread-local namespace is cleared. Example: >>>...
[ "def", "namespace", "(", "namespace", ")", ":", "try", ":", "current_namespace", "=", "_namespace", ".", "current", "except", "AttributeError", ":", "current_namespace", "=", "None", "set_namespace", "(", "namespace", ")", "try", ":", "yield", "finally", ":", ...
26.935484
0.001156
def _verify_filters(self, kwargs, obj, encode=False): """Legacy entrypoint with 'encode' flag""" return (filters.legacy_filter_formatter if encode else filters.filter_formatter)( kwargs, obj._get_attributes_map() )
[ "def", "_verify_filters", "(", "self", ",", "kwargs", ",", "obj", ",", "encode", "=", "False", ")", ":", "return", "(", "filters", ".", "legacy_filter_formatter", "if", "encode", "else", "filters", ".", "filter_formatter", ")", "(", "kwargs", ",", "obj", "...
42.833333
0.01145
def read_pod_security_policy(self, name, **kwargs): # noqa: E501 """read_pod_security_policy # noqa: E501 read the specified PodSecurityPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "read_pod_security_policy", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "r...
53.125
0.001541
def serialise(self, obj): """ Take an object from the project or the runner and serialise it into a dictionary. Parameters ---------- obj : object An object to serialise. Returns ------- object A serialised version of the ...
[ "def", "serialise", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "VariableCollection", ",", "StepCollection", ")", ")", ":", "return", "[", "self", ".", "serialise", "(", "element", ")", "for", "element", "i...
29.571429
0.002339
def _iparam_classname(classname, arg_name): """ Convert a class name specified in an operation method into a CIM object that can be passed to imethodcall(). """ if isinstance(classname, CIMClassName): classname = classname.copy() classname.host = None ...
[ "def", "_iparam_classname", "(", "classname", ",", "arg_name", ")", ":", "if", "isinstance", "(", "classname", ",", "CIMClassName", ")", ":", "classname", "=", "classname", ".", "copy", "(", ")", "classname", ".", "host", "=", "None", "classname", ".", "na...
38.238095
0.00243
def compute_rarity_scores(exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)] """ scores = defaultd...
[ "def", "compute_rarity_scores", "(", "exemplars", ")", ":", "scores", "=", "defaultdict", "(", "lambda", ":", "0.", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "score", "=", "1.", "/", "len", "(", "followers", ")", "for", ...
39.833333
0.002045
def add(self, obj): """ Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid. """ obj.controller = self.controller # Is the track already loaded or created? track = se...
[ "def", "add", "(", "self", ",", "obj", ")", ":", "obj", ".", "controller", "=", "self", ".", "controller", "# Is the track already loaded or created?", "track", "=", "self", ".", "tracks", ".", "get", "(", "obj", ".", "name", ")", "if", "track", ":", "if...
35.727273
0.002478