code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def crypto_box_seal_open(ciphertext, pk, sk): """ Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender...
def function[crypto_box_seal_open, parameter[ciphertext, pk, sk]]: constant[ Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's p...
keyword[def] identifier[crypto_box_seal_open] ( identifier[ciphertext] , identifier[pk] , identifier[sk] ): literal[string] identifier[ensure] ( identifier[isinstance] ( identifier[ciphertext] , identifier[bytes] ), literal[string] , identifier[raising] = identifier[TypeError] ) identifier[...
def crypto_box_seal_open(ciphertext, pk, sk): """ Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender...
def nt2aa(ntseq): """Translate a nucleotide sequence into an amino acid sequence. Parameters ---------- ntseq : str Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase) Returns ------- aaseq : str Amino acid sequence Example -------- >>> n...
def function[nt2aa, parameter[ntseq]]: constant[Translate a nucleotide sequence into an amino acid sequence. Parameters ---------- ntseq : str Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase) Returns ------- aaseq : str Amino acid sequence ...
keyword[def] identifier[nt2aa] ( identifier[ntseq] ): literal[string] identifier[nt2num] ={ literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] , literal[string] :...
def nt2aa(ntseq): """Translate a nucleotide sequence into an amino acid sequence. Parameters ---------- ntseq : str Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase) Returns ------- aaseq : str Amino acid sequence Example -------- >>> n...
def setNeutral(self, aMathObject, deltaName="origin"): """Set the neutral object.""" self._neutral = aMathObject self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True)
def function[setNeutral, parameter[self, aMathObject, deltaName]]: constant[Set the neutral object.] name[self]._neutral assign[=] name[aMathObject] call[name[self].addDelta, parameter[call[name[Location], parameter[]], binary_operation[name[aMathObject] - name[aMathObject]], name[deltaName]]]
keyword[def] identifier[setNeutral] ( identifier[self] , identifier[aMathObject] , identifier[deltaName] = literal[string] ): literal[string] identifier[self] . identifier[_neutral] = identifier[aMathObject] identifier[self] . identifier[addDelta] ( identifier[Location] (), identifier[aMa...
def setNeutral(self, aMathObject, deltaName='origin'): """Set the neutral object.""" self._neutral = aMathObject self.addDelta(Location(), aMathObject - aMathObject, deltaName, punch=False, axisOnly=True)
def _collect_data(self): """ Returns a list of all the data gathered from the engine iterable. """ all_data = [] for line in self.engine.run_engine(): logging.debug("Adding {} to all_data".format(line)) all_data.append(line.copy()) logg...
def function[_collect_data, parameter[self]]: constant[ Returns a list of all the data gathered from the engine iterable. ] variable[all_data] assign[=] list[[]] for taget[name[line]] in starred[call[name[self].engine.run_engine, parameter[]]] begin[:] cal...
keyword[def] identifier[_collect_data] ( identifier[self] ): literal[string] identifier[all_data] =[] keyword[for] identifier[line] keyword[in] identifier[self] . identifier[engine] . identifier[run_engine] (): identifier[logging] . identifier[debug] ( literal[string] . ide...
def _collect_data(self): """ Returns a list of all the data gathered from the engine iterable. """ all_data = [] for line in self.engine.run_engine(): logging.debug('Adding {} to all_data'.format(line)) all_data.append(line.copy()) logging.debug('all_data is n...
def cdot(L, out=None): r"""Product of a Cholesky matrix with itself transposed. Args: L (array_like): Cholesky matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: :math:`\mathrm L\mathrm L^\intercal`. """ L = asarray(L, float) ...
def function[cdot, parameter[L, out]]: constant[Product of a Cholesky matrix with itself transposed. Args: L (array_like): Cholesky matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: :math:`\mathrm L\mathrm L^\intercal`. ] ...
keyword[def] identifier[cdot] ( identifier[L] , identifier[out] = keyword[None] ): literal[string] identifier[L] = identifier[asarray] ( identifier[L] , identifier[float] ) identifier[layout_error] = literal[string] keyword[if] identifier[L] . identifier[ndim] != literal[int] : keywo...
def cdot(L, out=None): """Product of a Cholesky matrix with itself transposed. Args: L (array_like): Cholesky matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: :math:`\\mathrm L\\mathrm L^\\intercal`. """ L = asarray(L, float) ...
def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
def function[safe_format_sh, parameter[s]]: constant[ :type s str ] variable[to_replace] assign[=] binary_operation[call[name[set], parameter[call[name[kwargs].keys, parameter[]]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[set], parameter[call[name[FORMAT_RE].findall, parameter[name[s]]]]]] ...
keyword[def] identifier[safe_format_sh] ( identifier[s] ,** identifier[kwargs] ): literal[string] identifier[to_replace] = identifier[set] ( identifier[kwargs] . identifier[keys] ())& identifier[set] ( identifier[FORMAT_RE] . identifier[findall] ( identifier[s] )) keyword[for] identifier[item] keyword[i...
def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace('{{' + item + '}}', kwargs[item]) # depends on [control=['for'], data=['item']] return s
def compile_mof_file(self, mof_file, namespace=None, search_paths=None, verbose=None): """ Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the mock repository. ...
def function[compile_mof_file, parameter[self, mof_file, namespace, search_paths, verbose]]: constant[ Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the mock repository. If the names...
keyword[def] identifier[compile_mof_file] ( identifier[self] , identifier[mof_file] , identifier[namespace] = keyword[None] , identifier[search_paths] = keyword[None] , identifier[verbose] = keyword[None] ): literal[string] identifier[namespace] = identifier[namespace] keyword[or] identifier[se...
def compile_mof_file(self, mof_file, namespace=None, search_paths=None, verbose=None): """ Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the mock repository. If the namespace does not ex...
def leaf_bus(self, df=False): """ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame """ # leafs - leaf bus idx # lines - line idx # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking...
def function[leaf_bus, parameter[self, df]]: constant[ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame ] <ast.Tuple object at 0x7da20e9b3520> assign[=] tuple[[<ast.Call object at 0x7da20e9b3b20>, <ast.Call ...
keyword[def] identifier[leaf_bus] ( identifier[self] , identifier[df] = keyword[False] ): literal[string] identifier[leafs] , identifier[lines] , identifier[fkeys] = identifier[list] (), identifier[list] (), identifier[list] () identifier[buses] = iden...
def leaf_bus(self, df=False): """ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame """ # leafs - leaf bus idx # lines - line idx # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus (le...
async def get(self, public_key): """Receives public key, looking up document at storage, sends document id to the balance server """ if settings.SIGNATURE_VERIFICATION: super().verify() response = await self.account.getnews(public_key=public_key) # If we`ve got a empty or list with news if isinstan...
<ast.AsyncFunctionDef object at 0x7da1b23459c0>
keyword[async] keyword[def] identifier[get] ( identifier[self] , identifier[public_key] ): literal[string] keyword[if] identifier[settings] . identifier[SIGNATURE_VERIFICATION] : identifier[super] (). identifier[verify] () identifier[response] = keyword[await] identifier[self] . identifier[account] ...
async def get(self, public_key): """Receives public key, looking up document at storage, sends document id to the balance server """ if settings.SIGNATURE_VERIFICATION: super().verify() # depends on [control=['if'], data=[]] response = await self.account.getnews(public_key=public_key) # If w...
def to_json(self): """ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile) """ ...
def function[to_json, parameter[self]]: constant[ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_js...
keyword[def] identifier[to_json] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[indicator_variable] keyword[is] keyword[None] : identifier[indicator] = keyword[None] keyword[else] : identifier[indicator] = identifier[self] . id...
def to_json(self): """ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile) """ ...
def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME): """ Run a JS script within the context.\ All code is ran synchronously,\ there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param ident...
def function[run_script, parameter[self, script, identifier]]: constant[ Run a JS script within the context. All code is ran synchronously, there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param ide...
keyword[def] identifier[run_script] ( identifier[self] , identifier[script] , identifier[identifier] = identifier[_DEFAULT_SCRIPT_NAME] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[script] , identifier[six] . identifier[text_type] ) keyword[or] identifier[_is_utf_8] ( id...
def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME): """ Run a JS script within the context. All code is ran synchronously, there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param identifier: u...
def _spikes_per_cluster(spike_clusters, spike_ids=None): """Return a dictionary {cluster: list_of_spikes}.""" if spike_clusters is None or not len(spike_clusters): return {} if spike_ids is None: spike_ids = np.arange(len(spike_clusters)).astype(np.int64) # NOTE: this sort method is stab...
def function[_spikes_per_cluster, parameter[spike_clusters, spike_ids]]: constant[Return a dictionary {cluster: list_of_spikes}.] if <ast.BoolOp object at 0x7da1b26adb70> begin[:] return[dictionary[[], []]] if compare[name[spike_ids] is constant[None]] begin[:] variable[s...
keyword[def] identifier[_spikes_per_cluster] ( identifier[spike_clusters] , identifier[spike_ids] = keyword[None] ): literal[string] keyword[if] identifier[spike_clusters] keyword[is] keyword[None] keyword[or] keyword[not] identifier[len] ( identifier[spike_clusters] ): keyword[return] {} ...
def _spikes_per_cluster(spike_clusters, spike_ids=None): """Return a dictionary {cluster: list_of_spikes}.""" if spike_clusters is None or not len(spike_clusters): return {} # depends on [control=['if'], data=[]] if spike_ids is None: spike_ids = np.arange(len(spike_clusters)).astype(np.int...
def browser_authorize(self): """ Open a browser to the authorization url and spool up a CherryPy server to accept the response """ url = self.authorize_url() # Open the web browser in a new thread for command-line browser support threading.Timer(1, webbrowser.open...
def function[browser_authorize, parameter[self]]: constant[ Open a browser to the authorization url and spool up a CherryPy server to accept the response ] variable[url] assign[=] call[name[self].authorize_url, parameter[]] call[call[name[threading].Timer, parameter[const...
keyword[def] identifier[browser_authorize] ( identifier[self] ): literal[string] identifier[url] = identifier[self] . identifier[authorize_url] () identifier[threading] . identifier[Timer] ( literal[int] , identifier[webbrowser] . identifier[open] , identifier[args] =( identifier[...
def browser_authorize(self): """ Open a browser to the authorization url and spool up a CherryPy server to accept the response """ url = self.authorize_url() # Open the web browser in a new thread for command-line browser support threading.Timer(1, webbrowser.open, args=(url,)).s...
def read_requirements(*parts): """ Given a requirements.txt (or similar style file), returns a list of requirements. Assumes anything after a single '#' on a line is a comment, and ignores empty lines. """ requirements = [] for line in read(*parts).splitlines(): new_line = re.sub(r'...
def function[read_requirements, parameter[]]: constant[ Given a requirements.txt (or similar style file), returns a list of requirements. Assumes anything after a single '#' on a line is a comment, and ignores empty lines. ] variable[requirements] assign[=] list[[]] for taget[na...
keyword[def] identifier[read_requirements] (* identifier[parts] ): literal[string] identifier[requirements] =[] keyword[for] identifier[line] keyword[in] identifier[read] (* identifier[parts] ). identifier[splitlines] (): identifier[new_line] = identifier[re] . identifier[sub] ( literal[st...
def read_requirements(*parts): """ Given a requirements.txt (or similar style file), returns a list of requirements. Assumes anything after a single '#' on a line is a comment, and ignores empty lines. """ requirements = [] for line in read(*parts).splitlines(): # the space immediately bef...
def preview(self, request): """ Return a occurrences in JSON format up until the configured limit. """ recurrence_rule = request.POST.get('recurrence_rule') limit = int(request.POST.get('limit', 10)) try: rruleset = rrule.rrulestr( recurrence_r...
def function[preview, parameter[self, request]]: constant[ Return a occurrences in JSON format up until the configured limit. ] variable[recurrence_rule] assign[=] call[name[request].POST.get, parameter[constant[recurrence_rule]]] variable[limit] assign[=] call[name[int], paramet...
keyword[def] identifier[preview] ( identifier[self] , identifier[request] ): literal[string] identifier[recurrence_rule] = identifier[request] . identifier[POST] . identifier[get] ( literal[string] ) identifier[limit] = identifier[int] ( identifier[request] . identifier[POST] . identifier[...
def preview(self, request): """ Return a occurrences in JSON format up until the configured limit. """ recurrence_rule = request.POST.get('recurrence_rule') limit = int(request.POST.get('limit', 10)) try: rruleset = rrule.rrulestr(recurrence_rule, dtstart=djtz.now(), forceset=Tru...
def run(app, argv=sys.argv, extra_args=None): """ Run commands in a plain django environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments """ if app not in argv[:2]: # app is automatically added if not present ...
def function[run, parameter[app, argv, extra_args]]: constant[ Run commands in a plain django environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments ] if compare[name[app] <ast.NotIn object at 0x7da2590d7190> call[...
keyword[def] identifier[run] ( identifier[app] , identifier[argv] = identifier[sys] . identifier[argv] , identifier[extra_args] = keyword[None] ): literal[string] keyword[if] identifier[app] keyword[not] keyword[in] identifier[argv] [: literal[int] ]: identifier[argv] . identifier[insert]...
def run(app, argv=sys.argv, extra_args=None): """ Run commands in a plain django environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments """ if app not in argv[:2]: # app is automatically added if not present ...
def sort_and_print_entries(entries, args): """Sort the entries, applying the filters first if necessary.""" # Extract the proper number type. is_float = args.number_type in ("float", "real", "f", "r") signed = args.signed or args.number_type in ("real", "r") alg = ( natsort.ns.FLOAT * is_fl...
def function[sort_and_print_entries, parameter[entries, args]]: constant[Sort the entries, applying the filters first if necessary.] variable[is_float] assign[=] compare[name[args].number_type in tuple[[<ast.Constant object at 0x7da1b0b4bfd0>, <ast.Constant object at 0x7da1b0b497e0>, <ast.Constant objec...
keyword[def] identifier[sort_and_print_entries] ( identifier[entries] , identifier[args] ): literal[string] identifier[is_float] = identifier[args] . identifier[number_type] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] ) identifier[signed] = identifier[arg...
def sort_and_print_entries(entries, args): """Sort the entries, applying the filters first if necessary.""" # Extract the proper number type. is_float = args.number_type in ('float', 'real', 'f', 'r') signed = args.signed or args.number_type in ('real', 'r') alg = natsort.ns.FLOAT * is_float | natso...
def handle(cls, value, **kwargs): """Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list c...
def function[handle, parameter[cls, value]]: constant[Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets`...
keyword[def] identifier[handle] ( identifier[cls] , identifier[value] ,** identifier[kwargs] ): literal[string] keyword[try] : identifier[delimiter] , identifier[text] = identifier[value] . identifier[split] ( literal[string] , literal[int] ) keyword[except] identifier[Value...
def handle(cls, value, **kwargs): """Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list consi...
def serialize_task_spec(self, spec, elem): """ Serializes common attributes of :meth:`SpiffWorkflow.specs.TaskSpec`. """ if spec.id is not None: SubElement(elem, 'id').text = str(spec.id) SubElement(elem, 'name').text = spec.name if spec.description: ...
def function[serialize_task_spec, parameter[self, spec, elem]]: constant[ Serializes common attributes of :meth:`SpiffWorkflow.specs.TaskSpec`. ] if compare[name[spec].id is_not constant[None]] begin[:] call[name[SubElement], parameter[name[elem], constant[id]]].text assi...
keyword[def] identifier[serialize_task_spec] ( identifier[self] , identifier[spec] , identifier[elem] ): literal[string] keyword[if] identifier[spec] . identifier[id] keyword[is] keyword[not] keyword[None] : identifier[SubElement] ( identifier[elem] , literal[string] ). identifier[...
def serialize_task_spec(self, spec, elem): """ Serializes common attributes of :meth:`SpiffWorkflow.specs.TaskSpec`. """ if spec.id is not None: SubElement(elem, 'id').text = str(spec.id) # depends on [control=['if'], data=[]] SubElement(elem, 'name').text = spec.name if spec.de...
def case_variants(*elements): """ For configs which take case-insensitive options, it is necessary to extend the list with various common case variants (all combinations are not practical). In the future, this should be removed, when parser filters are made case-insensitive. Args: *elements...
def function[case_variants, parameter[]]: constant[ For configs which take case-insensitive options, it is necessary to extend the list with various common case variants (all combinations are not practical). In the future, this should be removed, when parser filters are made case-insensitive. A...
keyword[def] identifier[case_variants] (* identifier[elements] ): literal[string] identifier[expanded_list] =[] keyword[for] identifier[element] keyword[in] identifier[elements] : identifier[low] = identifier[element] . identifier[lower] () identifier[up] = identifier[element] . i...
def case_variants(*elements): """ For configs which take case-insensitive options, it is necessary to extend the list with various common case variants (all combinations are not practical). In the future, this should be removed, when parser filters are made case-insensitive. Args: *elements...
def wait_until(func, wait_for=None, sleep_for=0.5): """Test for a function and wait for it to return a truth value or to timeout. Returns the value or None if a timeout is given and the function didn't return inside time timeout Args: func (callable): a function to be evaluated, use lambda if pa...
def function[wait_until, parameter[func, wait_for, sleep_for]]: constant[Test for a function and wait for it to return a truth value or to timeout. Returns the value or None if a timeout is given and the function didn't return inside time timeout Args: func (callable): a function to be evalu...
keyword[def] identifier[wait_until] ( identifier[func] , identifier[wait_for] = keyword[None] , identifier[sleep_for] = literal[int] ): literal[string] identifier[res] = identifier[func] () keyword[if] identifier[res] : keyword[return] identifier[res] keyword[if] identifier[wait_fo...
def wait_until(func, wait_for=None, sleep_for=0.5): """Test for a function and wait for it to return a truth value or to timeout. Returns the value or None if a timeout is given and the function didn't return inside time timeout Args: func (callable): a function to be evaluated, use lambda if pa...
def _validate_interface_option(attr, value, addrfam='inet'): '''lookup the validation function for a [addrfam][attr] and return the results :param attr: attribute name :param value: raw setting value :param addrfam: address family (inet, inet6, ''' valid, _value, errmsg = False, value, 'Unk...
def function[_validate_interface_option, parameter[attr, value, addrfam]]: constant[lookup the validation function for a [addrfam][attr] and return the results :param attr: attribute name :param value: raw setting value :param addrfam: address family (inet, inet6, ] <ast.Tuple objec...
keyword[def] identifier[_validate_interface_option] ( identifier[attr] , identifier[value] , identifier[addrfam] = literal[string] ): literal[string] identifier[valid] , identifier[_value] , identifier[errmsg] = keyword[False] , identifier[value] , literal[string] identifier[attrmaps] = identifier[AT...
def _validate_interface_option(attr, value, addrfam='inet'): """lookup the validation function for a [addrfam][attr] and return the results :param attr: attribute name :param value: raw setting value :param addrfam: address family (inet, inet6, """ (valid, _value, errmsg) = (False, value, '...
def on_install(self, editor): """ Add the folding menu to the editor, on install. :param editor: editor instance on which the mode has been installed to. """ super(FoldingPanel, self).on_install(editor) self.context_menu = QtWidgets.QMenu(_('Folding'), self.editor) ...
def function[on_install, parameter[self, editor]]: constant[ Add the folding menu to the editor, on install. :param editor: editor instance on which the mode has been installed to. ] call[call[name[super], parameter[name[FoldingPanel], name[self]]].on_install, parameter[name[edi...
keyword[def] identifier[on_install] ( identifier[self] , identifier[editor] ): literal[string] identifier[super] ( identifier[FoldingPanel] , identifier[self] ). identifier[on_install] ( identifier[editor] ) identifier[self] . identifier[context_menu] = identifier[QtWidgets] . identifier[Q...
def on_install(self, editor): """ Add the folding menu to the editor, on install. :param editor: editor instance on which the mode has been installed to. """ super(FoldingPanel, self).on_install(editor) self.context_menu = QtWidgets.QMenu(_('Folding'), self.editor) action = self...
def _connected(cm, nodes, connection): """Test connectivity for the connectivity matrix.""" if nodes is not None: cm = cm[np.ix_(nodes, nodes)] num_components, _ = connected_components(cm, connection=connection) return num_components < 2
def function[_connected, parameter[cm, nodes, connection]]: constant[Test connectivity for the connectivity matrix.] if compare[name[nodes] is_not constant[None]] begin[:] variable[cm] assign[=] call[name[cm]][call[name[np].ix_, parameter[name[nodes], name[nodes]]]] <ast.Tuple ob...
keyword[def] identifier[_connected] ( identifier[cm] , identifier[nodes] , identifier[connection] ): literal[string] keyword[if] identifier[nodes] keyword[is] keyword[not] keyword[None] : identifier[cm] = identifier[cm] [ identifier[np] . identifier[ix_] ( identifier[nodes] , identifier[nodes]...
def _connected(cm, nodes, connection): """Test connectivity for the connectivity matrix.""" if nodes is not None: cm = cm[np.ix_(nodes, nodes)] # depends on [control=['if'], data=['nodes']] (num_components, _) = connected_components(cm, connection=connection) return num_components < 2
def getScales(self,term_i=None): """ Returns the Parameters Args: term_i: index of the term we are interested in if term_i==None returns the whole vector of parameters """ if term_i==None: RV = self.vd.getScales() ...
def function[getScales, parameter[self, term_i]]: constant[ Returns the Parameters Args: term_i: index of the term we are interested in if term_i==None returns the whole vector of parameters ] if compare[name[term_i] equal[==] cons...
keyword[def] identifier[getScales] ( identifier[self] , identifier[term_i] = keyword[None] ): literal[string] keyword[if] identifier[term_i] == keyword[None] : identifier[RV] = identifier[self] . identifier[vd] . identifier[getScales] () keyword[else] : keyword[a...
def getScales(self, term_i=None): """ Returns the Parameters Args: term_i: index of the term we are interested in if term_i==None returns the whole vector of parameters """ if term_i == None: RV = self.vd.getScales() # depends on ...
def Carcinogen(CASRN, AvailableMethods=False, Method=None): r'''Looks up if a chemical is listed as a carcinogen or not according to either a specifc method or with all methods. Returns either the status as a string for a specified method, or the status of the chemical in all available data sources, in...
def function[Carcinogen, parameter[CASRN, AvailableMethods, Method]]: constant[Looks up if a chemical is listed as a carcinogen or not according to either a specifc method or with all methods. Returns either the status as a string for a specified method, or the status of the chemical in all availab...
keyword[def] identifier[Carcinogen] ( identifier[CASRN] , identifier[AvailableMethods] = keyword[False] , identifier[Method] = keyword[None] ): literal[string] identifier[methods] =[ identifier[COMBINED] , identifier[IARC] , identifier[NTP] ] keyword[if] identifier[AvailableMethods] : keywor...
def Carcinogen(CASRN, AvailableMethods=False, Method=None): """Looks up if a chemical is listed as a carcinogen or not according to either a specifc method or with all methods. Returns either the status as a string for a specified method, or the status of the chemical in all available data sources, in ...
def from_packed(cls, packed): """Unpack diploid genotypes that have been bit-packed into single bytes. Parameters ---------- packed : ndarray, uint8, shape (n_variants, n_samples) Bit-packed diploid genotype array. Returns ------- g : Genotyp...
def function[from_packed, parameter[cls, packed]]: constant[Unpack diploid genotypes that have been bit-packed into single bytes. Parameters ---------- packed : ndarray, uint8, shape (n_variants, n_samples) Bit-packed diploid genotype array. Returns ...
keyword[def] identifier[from_packed] ( identifier[cls] , identifier[packed] ): literal[string] identifier[packed] = identifier[np] . identifier[asarray] ( identifier[packed] ) identifier[check_ndim] ( identifier[packed] , literal[int] ) identifier[check_dtype] ( identifi...
def from_packed(cls, packed): """Unpack diploid genotypes that have been bit-packed into single bytes. Parameters ---------- packed : ndarray, uint8, shape (n_variants, n_samples) Bit-packed diploid genotype array. Returns ------- g : GenotypeArr...
def lookup(self, hostname): """ Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostname: the hostname (or IP) to ...
def function[lookup, parameter[self, hostname]]: constant[ Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostnam...
keyword[def] identifier[lookup] ( identifier[self] , identifier[hostname] ): literal[string] keyword[class] identifier[SubDict] ( identifier[UserDict] . identifier[DictMixin] ): keyword[def] identifier[__init__] ( identifier[self] , identifier[hostname] , identifier[entries] , identi...
def lookup(self, hostname): """ Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostname: the hostname (or IP) to look...
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None): """Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates ...
def function[abbreviated_interface_name, parameter[interface, addl_name_map, addl_reverse_map]]: constant[Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/valu...
keyword[def] identifier[abbreviated_interface_name] ( identifier[interface] , identifier[addl_name_map] = keyword[None] , identifier[addl_reverse_map] = keyword[None] ): literal[string] identifier[name_map] ={} identifier[name_map] . identifier[update] ( identifier[base_interfaces] ) identifier[...
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None): """Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates ...
def gibson(seq_list, linear=False, homology=10, tm=63.0): '''Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear:...
def function[gibson, parameter[seq_list, linear, homology, tm]]: constant[Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. ...
keyword[def] identifier[gibson] ( identifier[seq_list] , identifier[linear] = keyword[False] , identifier[homology] = literal[int] , identifier[tm] = literal[int] ): literal[string] identifier[seq_list] = identifier[list] ( identifier[set] ( identifier[seq_list] )) keyword[fo...
def gibson(seq_list, linear=False, homology=10, tm=63.0): """Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear:...
def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """ assert version not in self.versions, 'Will not overwrite a version name.' if not msg: feat, targ = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) ...
def function[commit_version, parameter[self, version, msg]]: constant[ Add tag, commit, and push changes ] assert[compare[name[version] <ast.NotIn object at 0x7da2590d7190> name[self].versions]] if <ast.UnaryOp object at 0x7da18bccb850> begin[:] <ast.Tuple object at 0x7da18bccb730> a...
keyword[def] identifier[commit_version] ( identifier[self] , identifier[version] , identifier[msg] = keyword[None] ): literal[string] keyword[assert] identifier[version] keyword[not] keyword[in] identifier[self] . identifier[versions] , literal[string] keyword[if] keyword[not] ide...
def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """ assert version not in self.versions, 'Will not overwrite a version name.' if not msg: (feat, targ) = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) (feat, targ) = self...
def update_task(deadline, label, task_id): """ Executor for `globus task update` """ client = get_client() task_doc = assemble_generic_doc("task", label=label, deadline=deadline) res = client.update_task(task_id, task_doc) formatted_print(res, simple_text="Success")
def function[update_task, parameter[deadline, label, task_id]]: constant[ Executor for `globus task update` ] variable[client] assign[=] call[name[get_client], parameter[]] variable[task_doc] assign[=] call[name[assemble_generic_doc], parameter[constant[task]]] variable[res] assi...
keyword[def] identifier[update_task] ( identifier[deadline] , identifier[label] , identifier[task_id] ): literal[string] identifier[client] = identifier[get_client] () identifier[task_doc] = identifier[assemble_generic_doc] ( literal[string] , identifier[label] = identifier[label] , identifier[deadli...
def update_task(deadline, label, task_id): """ Executor for `globus task update` """ client = get_client() task_doc = assemble_generic_doc('task', label=label, deadline=deadline) res = client.update_task(task_id, task_doc) formatted_print(res, simple_text='Success')
async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **permissions): r"""|coro| Sets the channel specific permission overwrites for a target in the channel. The ``target`` parameter should either be a :class:`Member` or a :class:`Role` that belongs to g...
<ast.AsyncFunctionDef object at 0x7da1b20caef0>
keyword[async] keyword[def] identifier[set_permissions] ( identifier[self] , identifier[target] ,*, identifier[overwrite] = identifier[_undefined] , identifier[reason] = keyword[None] ,** identifier[permissions] ): literal[string] identifier[http] = identifier[self] . identifier[_state] . identif...
async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **permissions): """|coro| Sets the channel specific permission overwrites for a target in the channel. The ``target`` parameter should either be a :class:`Member` or a :class:`Role` that belongs to guild....
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: """Format condition lambda function as reST.""" lambda_ast_node = lambda_inspection.node assert isinstance(lambda_ast_node, ast.Lambda) body_node = lambda_ast_node.body text = None # type: Optional[s...
def function[_condition_as_text, parameter[lambda_inspection]]: constant[Format condition lambda function as reST.] variable[lambda_ast_node] assign[=] name[lambda_inspection].node assert[call[name[isinstance], parameter[name[lambda_ast_node], name[ast].Lambda]]] variable[body_node] assign[=...
keyword[def] identifier[_condition_as_text] ( identifier[lambda_inspection] : identifier[icontract] . identifier[_represent] . identifier[ConditionLambdaInspection] )-> identifier[str] : literal[string] identifier[lambda_ast_node] = identifier[lambda_inspection] . identifier[node] keyword[assert] id...
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: """Format condition lambda function as reST.""" lambda_ast_node = lambda_inspection.node assert isinstance(lambda_ast_node, ast.Lambda) body_node = lambda_ast_node.body text = None # type: Optional[str...
def check_chain(chain): """Verify a merkle chain to see if the Merkle root can be reproduced. """ link = chain[0][0] for i in range(1, len(chain) - 1): if chain[i][1] == 'R': link = hash_function(link + chain[i][0]).digest() elif chain[i][1] == 'L': link = hash_fu...
def function[check_chain, parameter[chain]]: constant[Verify a merkle chain to see if the Merkle root can be reproduced. ] variable[link] assign[=] call[call[name[chain]][constant[0]]][constant[0]] for taget[name[i]] in starred[call[name[range], parameter[constant[1], binary_operation[call[n...
keyword[def] identifier[check_chain] ( identifier[chain] ): literal[string] identifier[link] = identifier[chain] [ literal[int] ][ literal[int] ] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[chain] )- literal[int] ): keyword[if] id...
def check_chain(chain): """Verify a merkle chain to see if the Merkle root can be reproduced. """ link = chain[0][0] for i in range(1, len(chain) - 1): if chain[i][1] == 'R': link = hash_function(link + chain[i][0]).digest() # depends on [control=['if'], data=[]] elif chain[...
def handle_debug_break(self, call_id, payload): """Handle responses `DebugBreakEvent`.""" line = payload['line'] config = self.launcher.config # TODO: make an attribute of client path = os.path.relpath(payload['file'], config['root-dir']) self.editor.raw_message(feedback['notif...
def function[handle_debug_break, parameter[self, call_id, payload]]: constant[Handle responses `DebugBreakEvent`.] variable[line] assign[=] call[name[payload]][constant[line]] variable[config] assign[=] name[self].launcher.config variable[path] assign[=] call[name[os].path.relpath, param...
keyword[def] identifier[handle_debug_break] ( identifier[self] , identifier[call_id] , identifier[payload] ): literal[string] identifier[line] = identifier[payload] [ literal[string] ] identifier[config] = identifier[self] . identifier[launcher] . identifier[config] identifier[pa...
def handle_debug_break(self, call_id, payload): """Handle responses `DebugBreakEvent`.""" line = payload['line'] config = self.launcher.config # TODO: make an attribute of client path = os.path.relpath(payload['file'], config['root-dir']) self.editor.raw_message(feedback['notify_break'].format(line...
def ensure_ajax(valid_request_methods, error_response_context=None): """ Intends to ensure the received the request is ajax request and it is included in the valid request methods :param valid_request_methods: list: list of valid request methods, such as 'GET', 'POST' :param error_response_co...
def function[ensure_ajax, parameter[valid_request_methods, error_response_context]]: constant[ Intends to ensure the received the request is ajax request and it is included in the valid request methods :param valid_request_methods: list: list of valid request methods, such as 'GET', 'POST' ...
keyword[def] identifier[ensure_ajax] ( identifier[valid_request_methods] , identifier[error_response_context] = keyword[None] ): literal[string] keyword[def] identifier[real_decorator] ( identifier[view_func] ): keyword[def] identifier[wrap_func] ( identifier[request] ,* identifier[args] ,** ide...
def ensure_ajax(valid_request_methods, error_response_context=None): """ Intends to ensure the received the request is ajax request and it is included in the valid request methods :param valid_request_methods: list: list of valid request methods, such as 'GET', 'POST' :param error_response_co...
def _cli_check_data_dir(data_dir): '''Checks that the data dir exists and contains METADATA.json''' if data_dir is None: return None data_dir = os.path.expanduser(data_dir) data_dir = os.path.expandvars(data_dir) if not os.path.isdir(data_dir): raise RuntimeError("Data directory '{...
def function[_cli_check_data_dir, parameter[data_dir]]: constant[Checks that the data dir exists and contains METADATA.json] if compare[name[data_dir] is constant[None]] begin[:] return[constant[None]] variable[data_dir] assign[=] call[name[os].path.expanduser, parameter[name[data_dir]]]...
keyword[def] identifier[_cli_check_data_dir] ( identifier[data_dir] ): literal[string] keyword[if] identifier[data_dir] keyword[is] keyword[None] : keyword[return] keyword[None] identifier[data_dir] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[data_dir] ) ...
def _cli_check_data_dir(data_dir): """Checks that the data dir exists and contains METADATA.json""" if data_dir is None: return None # depends on [control=['if'], data=[]] data_dir = os.path.expanduser(data_dir) data_dir = os.path.expandvars(data_dir) if not os.path.isdir(data_dir): ...
def author_id_normalize_and_schema(uid, schema=None): """Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the UID normalized to comply wi...
def function[author_id_normalize_and_schema, parameter[uid, schema]]: constant[Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the U...
keyword[def] identifier[author_id_normalize_and_schema] ( identifier[uid] , identifier[schema] = keyword[None] ): literal[string] keyword[def] identifier[_get_uid_normalized_in_schema] ( identifier[_uid] , identifier[_schema] ): identifier[regex] , identifier[template] = identifier[_RE_AUTHORS_UI...
def author_id_normalize_and_schema(uid, schema=None): """Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the UID normalized to comply wi...
def _stream(self): """ Returns a generator of lines instead of a list of lines. """ if self._exception: raise self._exception try: if self._content: yield self._content else: args = self.create_args() ...
def function[_stream, parameter[self]]: constant[ Returns a generator of lines instead of a list of lines. ] if name[self]._exception begin[:] <ast.Raise object at 0x7da2046208e0> <ast.Try object at 0x7da2046208b0>
keyword[def] identifier[_stream] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_exception] : keyword[raise] identifier[self] . identifier[_exception] keyword[try] : keyword[if] identifier[self] . identifier[_content] : ...
def _stream(self): """ Returns a generator of lines instead of a list of lines. """ if self._exception: raise self._exception # depends on [control=['if'], data=[]] try: if self._content: yield self._content # depends on [control=['if'], data=[]] else: ...
def get(self, value): """ Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does not match any known enumeration value. :rtype: EnumItem """ _nothing = object() item = s...
def function[get, parameter[self, value]]: constant[ Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does not match any known enumeration value. :rtype: EnumItem ] variable[_n...
keyword[def] identifier[get] ( identifier[self] , identifier[value] ): literal[string] identifier[_nothing] = identifier[object] () identifier[item] = identifier[self] . identifier[_values] . identifier[get] ( identifier[value] , identifier[_nothing] ) keyword[if] identifier[item...
def get(self, value): """ Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does not match any known enumeration value. :rtype: EnumItem """ _nothing = object() item = self._values....
def _has_tag(version, debug=False): """ Determine a version is a local git tag name or not. :param version: A string containing the branch/tag/sha to be determined. :param debug: An optional bool to toggle debug output. :return: bool """ cmd = sh.git.bake('show-ref', '--verify', '--quiet', ...
def function[_has_tag, parameter[version, debug]]: constant[ Determine a version is a local git tag name or not. :param version: A string containing the branch/tag/sha to be determined. :param debug: An optional bool to toggle debug output. :return: bool ] variable[cmd] assign[=] ca...
keyword[def] identifier[_has_tag] ( identifier[version] , identifier[debug] = keyword[False] ): literal[string] identifier[cmd] = identifier[sh] . identifier[git] . identifier[bake] ( literal[string] , literal[string] , literal[string] , literal[string] . identifier[format] ( identifier[version] )) ...
def _has_tag(version, debug=False): """ Determine a version is a local git tag name or not. :param version: A string containing the branch/tag/sha to be determined. :param debug: An optional bool to toggle debug output. :return: bool """ cmd = sh.git.bake('show-ref', '--verify', '--quiet', ...
def map_to_adjust(self, strain, **params): """Map an input dictionary of sampling parameters to the adjust_strain function by filtering the dictionary for the calibration parameters, then calling adjust_strain. Parameters ---------- strain : FrequencySeries T...
def function[map_to_adjust, parameter[self, strain]]: constant[Map an input dictionary of sampling parameters to the adjust_strain function by filtering the dictionary for the calibration parameters, then calling adjust_strain. Parameters ---------- strain : FrequencySer...
keyword[def] identifier[map_to_adjust] ( identifier[self] , identifier[strain] ,** identifier[params] ): literal[string] identifier[arg_names] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , ...
def map_to_adjust(self, strain, **params): """Map an input dictionary of sampling parameters to the adjust_strain function by filtering the dictionary for the calibration parameters, then calling adjust_strain. Parameters ---------- strain : FrequencySeries The s...
async def get_txn(self, seq_no: int) -> str: """ Find a transaction on the distributed ledger by its sequence number. :param seq_no: transaction number :return: json sequence number of transaction, null for no match """ LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', ...
<ast.AsyncFunctionDef object at 0x7da20c6c75b0>
keyword[async] keyword[def] identifier[get_txn] ( identifier[self] , identifier[seq_no] : identifier[int] )-> identifier[str] : literal[string] identifier[LOGGER] . identifier[debug] ( literal[string] , identifier[seq_no] ) identifier[rv_json] = identifier[json] . identifier[dumps] ({})...
async def get_txn(self, seq_no: int) -> str: """ Find a transaction on the distributed ledger by its sequence number. :param seq_no: transaction number :return: json sequence number of transaction, null for no match """ LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', seq_no) ...
def make_encoder(activation, latent_size, base_depth): """Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images t...
def function[make_encoder, parameter[activation, latent_size, base_depth]]: constant[Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callabl...
keyword[def] identifier[make_encoder] ( identifier[activation] , identifier[latent_size] , identifier[base_depth] ): literal[string] identifier[conv] = identifier[functools] . identifier[partial] ( identifier[tf] . identifier[keras] . identifier[layers] . identifier[Conv2D] , identifier[padding] = literal[s...
def make_encoder(activation, latent_size, base_depth): """Creates the encoder function. Args: activation: Activation function in hidden layers. latent_size: The dimensionality of the encoding. base_depth: The lowest depth for a layer. Returns: encoder: A `callable` mapping a `Tensor` of images...
def readout(self, *args, **kwargs): ''' Running the FIFO readout while executing other statements. Starting and stopping of the FIFO readout is synchronized between the threads. ''' timeout = kwargs.pop('timeout', 10.0) self.start_readout(*args, **kwargs) try: ...
def function[readout, parameter[self]]: constant[ Running the FIFO readout while executing other statements. Starting and stopping of the FIFO readout is synchronized between the threads. ] variable[timeout] assign[=] call[name[kwargs].pop, parameter[constant[timeout], constant[10.0]]] ...
keyword[def] identifier[readout] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[timeout] = identifier[kwargs] . identifier[pop] ( literal[string] , literal[int] ) identifier[self] . identifier[start_readout] (* identifier[args] ,** identifier[kw...
def readout(self, *args, **kwargs): """ Running the FIFO readout while executing other statements. Starting and stopping of the FIFO readout is synchronized between the threads. """ timeout = kwargs.pop('timeout', 10.0) self.start_readout(*args, **kwargs) try: yield # depends o...
def keywords(s, top=10, **kwargs): """ Returns a sorted list of keywords in the given string. """ return parser.find_keywords(s, top=top, frequency=parser.frequency)
def function[keywords, parameter[s, top]]: constant[ Returns a sorted list of keywords in the given string. ] return[call[name[parser].find_keywords, parameter[name[s]]]]
keyword[def] identifier[keywords] ( identifier[s] , identifier[top] = literal[int] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[parser] . identifier[find_keywords] ( identifier[s] , identifier[top] = identifier[top] , identifier[frequency] = identifier[parser] . identifier[frequenc...
def keywords(s, top=10, **kwargs): """ Returns a sorted list of keywords in the given string. """ return parser.find_keywords(s, top=top, frequency=parser.frequency)
def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the sentences in an individual CONLL formatted file. """ for document in self.dataset_document_iterator(file_path): for sentence in document: yield sentence
def function[sentence_iterator, parameter[self, file_path]]: constant[ An iterator over the sentences in an individual CONLL formatted file. ] for taget[name[document]] in starred[call[name[self].dataset_document_iterator, parameter[name[file_path]]]] begin[:] for taget[n...
keyword[def] identifier[sentence_iterator] ( identifier[self] , identifier[file_path] : identifier[str] )-> identifier[Iterator] [ identifier[OntonotesSentence] ]: literal[string] keyword[for] identifier[document] keyword[in] identifier[self] . identifier[dataset_document_iterator] ( identifier[...
def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the sentences in an individual CONLL formatted file. """ for document in self.dataset_document_iterator(file_path): for sentence in document: yield sentence # depends on [control...
def target(self, request, key, limit, ttl): """this will only run the request if the key has a value, if you want to fail if the key doesn't have a value, then normalize_key() should raise an exception :param request: Request, the request instance :param key: string, the unique ...
def function[target, parameter[self, request, key, limit, ttl]]: constant[this will only run the request if the key has a value, if you want to fail if the key doesn't have a value, then normalize_key() should raise an exception :param request: Request, the request instance :par...
keyword[def] identifier[target] ( identifier[self] , identifier[request] , identifier[key] , identifier[limit] , identifier[ttl] ): literal[string] identifier[ret] = keyword[True] keyword[if] identifier[key] : ...
def target(self, request, key, limit, ttl): """this will only run the request if the key has a value, if you want to fail if the key doesn't have a value, then normalize_key() should raise an exception :param request: Request, the request instance :param key: string, the unique key ...
def moment(p, v, order=1): """ Calculates the moments of the probability distribution p with vector v """ if order == 1: return (v*p).sum() elif order == 2: return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )
def function[moment, parameter[p, v, order]]: constant[ Calculates the moments of the probability distribution p with vector v ] if compare[name[order] equal[==] constant[1]] begin[:] return[call[binary_operation[name[v] * name[p]].sum, parameter[]]]
keyword[def] identifier[moment] ( identifier[p] , identifier[v] , identifier[order] = literal[int] ): literal[string] keyword[if] identifier[order] == literal[int] : keyword[return] ( identifier[v] * identifier[p] ). identifier[sum] () keyword[elif] identifier[order] == literal[int] : ...
def moment(p, v, order=1): """ Calculates the moments of the probability distribution p with vector v """ if order == 1: return (v * p).sum() # depends on [control=['if'], data=[]] elif order == 2: return np.sqrt((v ** 2 * p).sum() - (v * p).sum() ** 2) # depends on [control=['if'], data=[...
def fetch(self, url, open_graph=None, twitter_card=None, touch_icon=None, favicon=None, all_images=None, parser=None, handle_file_content=None, canonical=None): """Retrieves content from the specified url, parses it, and returns a beautifully crafted dictionary of important i...
def function[fetch, parameter[self, url, open_graph, twitter_card, touch_icon, favicon, all_images, parser, handle_file_content, canonical]]: constant[Retrieves content from the specified url, parses it, and returns a beautifully crafted dictionary of important information about that web page. ...
keyword[def] identifier[fetch] ( identifier[self] , identifier[url] , identifier[open_graph] = keyword[None] , identifier[twitter_card] = keyword[None] , identifier[touch_icon] = keyword[None] , identifier[favicon] = keyword[None] , identifier[all_images] = keyword[None] , identifier[parser] = keyword[None] , identi...
def fetch(self, url, open_graph=None, twitter_card=None, touch_icon=None, favicon=None, all_images=None, parser=None, handle_file_content=None, canonical=None): """Retrieves content from the specified url, parses it, and returns a beautifully crafted dictionary of important information about that we...
def date_time_this_month(): """ 获取当前月的随机时间 :return: * date_this_month: (datetime) 当前月份的随机时间 举例如下:: print('--- GetRandomTime.date_time_this_month demo ---') print(GetRandomTime.date_time_this_month()) print('---') 执行结果:: ...
def function[date_time_this_month, parameter[]]: constant[ 获取当前月的随机时间 :return: * date_this_month: (datetime) 当前月份的随机时间 举例如下:: print('--- GetRandomTime.date_time_this_month demo ---') print(GetRandomTime.date_time_this_month()) print('---...
keyword[def] identifier[date_time_this_month] (): literal[string] identifier[now] = identifier[datetime] . identifier[now] () identifier[this_month_start] = identifier[now] . identifier[replace] ( identifier[day] = literal[int] , identifier[hour] = literal[int] , identifier[minute...
def date_time_this_month(): """ 获取当前月的随机时间 :return: * date_this_month: (datetime) 当前月份的随机时间 举例如下:: print('--- GetRandomTime.date_time_this_month demo ---') print(GetRandomTime.date_time_this_month()) print('---') 执行结果:: ...
def reload_list(self): '''Press R in home view to retrieve quiz list''' self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.home_view = self.make_listview(self.leetcode.quizzes) self.view_stack = [] self.goto_view(self.home_v...
def function[reload_list, parameter[self]]: constant[Press R in home view to retrieve quiz list] call[name[self].leetcode.load, parameter[]] if <ast.BoolOp object at 0x7da1b0cf7070> begin[:] name[self].home_view assign[=] call[name[self].make_listview, parameter[name[self].leetco...
keyword[def] identifier[reload_list] ( identifier[self] ): literal[string] identifier[self] . identifier[leetcode] . identifier[load] () keyword[if] identifier[self] . identifier[leetcode] . identifier[quizzes] keyword[and] identifier[len] ( identifier[self] . identifier[leetcode] . ide...
def reload_list(self): """Press R in home view to retrieve quiz list""" self.leetcode.load() if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0: self.home_view = self.make_listview(self.leetcode.quizzes) self.view_stack = [] self.goto_view(self.home_view) # depends on [cont...
def terminate_process(self, idf): """ Terminate a process by id """ try: p = self.q.pop(idf) p.terminate() return p except: return None
def function[terminate_process, parameter[self, idf]]: constant[ Terminate a process by id ] <ast.Try object at 0x7da207f985b0>
keyword[def] identifier[terminate_process] ( identifier[self] , identifier[idf] ): literal[string] keyword[try] : identifier[p] = identifier[self] . identifier[q] . identifier[pop] ( identifier[idf] ) identifier[p] . identifier[terminate] () keyword[return] i...
def terminate_process(self, idf): """ Terminate a process by id """ try: p = self.q.pop(idf) p.terminate() return p # depends on [control=['try'], data=[]] except: return None # depends on [control=['except'], data=[]]
def save_data(self,session, exp_id, content): '''save data will obtain the current subid from the session, and save it depending on the database type.''' from expfactory.database.models import ( Participant, Result ) subid = session.get('subid') bot.info('Saving data for subi...
def function[save_data, parameter[self, session, exp_id, content]]: constant[save data will obtain the current subid from the session, and save it depending on the database type.] from relative_module[expfactory.database.models] import module[Participant], module[Result] variable[subid] assig...
keyword[def] identifier[save_data] ( identifier[self] , identifier[session] , identifier[exp_id] , identifier[content] ): literal[string] keyword[from] identifier[expfactory] . identifier[database] . identifier[models] keyword[import] ( identifier[Participant] , identifier[Result] ) i...
def save_data(self, session, exp_id, content): """save data will obtain the current subid from the session, and save it depending on the database type.""" from expfactory.database.models import Participant, Result subid = session.get('subid') bot.info('Saving data for subid %s' % subid) # We ...
def _triage_error(self, e, nofail): """ Print a message and decide what to do about an error. """ if not nofail: self.fail_pipeline(e) elif self._failed: print("This is a nofail process, but the pipeline was terminated for other reasons, so we fail.") raise e...
def function[_triage_error, parameter[self, e, nofail]]: constant[ Print a message and decide what to do about an error. ] if <ast.UnaryOp object at 0x7da1b0340220> begin[:] call[name[self].fail_pipeline, parameter[name[e]]]
keyword[def] identifier[_triage_error] ( identifier[self] , identifier[e] , identifier[nofail] ): literal[string] keyword[if] keyword[not] identifier[nofail] : identifier[self] . identifier[fail_pipeline] ( identifier[e] ) keyword[elif] identifier[self] . identifier[_failed...
def _triage_error(self, e, nofail): """ Print a message and decide what to do about an error. """ if not nofail: self.fail_pipeline(e) # depends on [control=['if'], data=[]] elif self._failed: print('This is a nofail process, but the pipeline was terminated for other reasons, so we fail.')...
def set_window_size(self, width, height): """Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: ...
def function[set_window_size, parameter[self, width, height]]: constant[Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height,...
keyword[def] identifier[set_window_size] ( identifier[self] , identifier[width] , identifier[height] ): literal[string] identifier[self] . identifier[_imgwin_wd] = identifier[int] ( identifier[width] ) identifier[self] . identifier[_imgwin_ht] = identifier[int] ( identifier[height] ) ...
def set_window_size(self, width, height): """Report the size of the window to display the image. **Callbacks** Will call any callbacks registered for the ``'configure'`` event. Callbacks should have a method signature of:: (viewer, width, height, ...) .. note:: ...
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dat...
def function[_get_processed_dataframe, parameter[self, dataframe]]: constant[Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: d...
keyword[def] identifier[_get_processed_dataframe] ( identifier[self] , identifier[dataframe] ): literal[string] identifier[dataframe] . identifier[index] = identifier[pd] . identifier[to_datetime] ( identifier[dataframe] [ literal[string] ], identifier[unit] = literal[string] , identifier[utc] = ke...
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dataframe.i...
def attach_list(filepaths, notes): ''' all the arguments are lists returns a list of dictionaries; each dictionary "represent" an attachment ''' assert type(filepaths) in (list, tuple) assert type(notes) in (list, tuple) # this if clause means "if those lists are not of the same length" ...
def function[attach_list, parameter[filepaths, notes]]: constant[ all the arguments are lists returns a list of dictionaries; each dictionary "represent" an attachment ] assert[compare[call[name[type], parameter[name[filepaths]]] in tuple[[<ast.Name object at 0x7da1b26d4a60>, <ast.Name object at...
keyword[def] identifier[attach_list] ( identifier[filepaths] , identifier[notes] ): literal[string] keyword[assert] identifier[type] ( identifier[filepaths] ) keyword[in] ( identifier[list] , identifier[tuple] ) keyword[assert] identifier[type] ( identifier[notes] ) keyword[in] ( identifier[list] , ...
def attach_list(filepaths, notes): """ all the arguments are lists returns a list of dictionaries; each dictionary "represent" an attachment """ assert type(filepaths) in (list, tuple) assert type(notes) in (list, tuple) # this if clause means "if those lists are not of the same length" ...
def get_hdrs_len(self): # type: () -> int """ get_hdrs_len computes the length of the hdrs field To do this computation, the length of the padlen field, reserved, stream_id and the actual padding is subtracted to the string that was provided to the pre_dissect fun of the pkt par...
def function[get_hdrs_len, parameter[self]]: constant[ get_hdrs_len computes the length of the hdrs field To do this computation, the length of the padlen field, reserved, stream_id and the actual padding is subtracted to the string that was provided to the pre_dissect fun of the pkt pa...
keyword[def] identifier[get_hdrs_len] ( identifier[self] ): literal[string] identifier[fld] , identifier[padding_len] = identifier[self] . identifier[getfield_and_val] ( literal[string] ) identifier[padding_len_len] = identifier[fld] . identifier[i2len] ( identifier[self] , identifier[pad...
def get_hdrs_len(self): # type: () -> int ' get_hdrs_len computes the length of the hdrs field\n\n To do this computation, the length of the padlen field, reserved,\n stream_id and the actual padding is subtracted to the string that was\n provided to the pre_dissect fun of the pkt parameter...
def getKeplerFov(fieldnum): """Returns a `fov.KeplerFov` object for a given campaign. Parameters ---------- fieldnum : int K2 Campaign number. Returns ------- fovobj : `fov.KeplerFov` object Details the footprint of the requested K2 campaign. """ info = getFieldInfo...
def function[getKeplerFov, parameter[fieldnum]]: constant[Returns a `fov.KeplerFov` object for a given campaign. Parameters ---------- fieldnum : int K2 Campaign number. Returns ------- fovobj : `fov.KeplerFov` object Details the footprint of the requested K2 campaign. ...
keyword[def] identifier[getKeplerFov] ( identifier[fieldnum] ): literal[string] identifier[info] = identifier[getFieldInfo] ( identifier[fieldnum] ) identifier[ra] , identifier[dec] , identifier[scRoll] = identifier[info] [ literal[string] ], identifier[info] [ literal[string] ], identifier[info] [ li...
def getKeplerFov(fieldnum): """Returns a `fov.KeplerFov` object for a given campaign. Parameters ---------- fieldnum : int K2 Campaign number. Returns ------- fovobj : `fov.KeplerFov` object Details the footprint of the requested K2 campaign. """ info = getFieldInfo...
def fetchThreadInfo(self, *thread_ids): """ Get threads' info from IDs, unordered .. warning:: Sends two requests if users or pages are present, to fetch all available info! :param thread_ids: One or more thread ID(s) to query :return: :class:`models.Thread` objects...
def function[fetchThreadInfo, parameter[self]]: constant[ Get threads' info from IDs, unordered .. warning:: Sends two requests if users or pages are present, to fetch all available info! :param thread_ids: One or more thread ID(s) to query :return: :class:`models.T...
keyword[def] identifier[fetchThreadInfo] ( identifier[self] ,* identifier[thread_ids] ): literal[string] identifier[queries] =[] keyword[for] identifier[thread_id] keyword[in] identifier[thread_ids] : identifier[params] ={ literal[string] : identifier[thread_id...
def fetchThreadInfo(self, *thread_ids): """ Get threads' info from IDs, unordered .. warning:: Sends two requests if users or pages are present, to fetch all available info! :param thread_ids: One or more thread ID(s) to query :return: :class:`models.Thread` objects, la...
def expand_path(path): """Expands directories and globs in given path.""" paths = [] path = os.path.expanduser(path) path = os.path.expandvars(path) if os.path.isdir(path): for (dir, dirs, files) in os.walk(path): for file in files: paths.append(os.path.join(di...
def function[expand_path, parameter[path]]: constant[Expands directories and globs in given path.] variable[paths] assign[=] list[[]] variable[path] assign[=] call[name[os].path.expanduser, parameter[name[path]]] variable[path] assign[=] call[name[os].path.expandvars, parameter[name[path...
keyword[def] identifier[expand_path] ( identifier[path] ): literal[string] identifier[paths] =[] identifier[path] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[path] ) identifier[path] = identifier[os] . identifier[path] . identifier[expandvars] ( identifier[path] ) ...
def expand_path(path): """Expands directories and globs in given path.""" paths = [] path = os.path.expanduser(path) path = os.path.expandvars(path) if os.path.isdir(path): for (dir, dirs, files) in os.walk(path): for file in files: paths.append(os.path.join(dir, ...
def knn_impute_reference( X, missing_mask, k, verbose=False, print_interval=100): """ Reference implementation of kNN imputation logic. """ n_rows, n_cols = X.shape X_result, D, effective_infinity = \ knn_initialize(X, missing_mask, verbose=verbose) ...
def function[knn_impute_reference, parameter[X, missing_mask, k, verbose, print_interval]]: constant[ Reference implementation of kNN imputation logic. ] <ast.Tuple object at 0x7da18c4ced70> assign[=] name[X].shape <ast.Tuple object at 0x7da18c4ce3b0> assign[=] call[name[knn_initialize],...
keyword[def] identifier[knn_impute_reference] ( identifier[X] , identifier[missing_mask] , identifier[k] , identifier[verbose] = keyword[False] , identifier[print_interval] = literal[int] ): literal[string] identifier[n_rows] , identifier[n_cols] = identifier[X] . identifier[shape] identifier[X_...
def knn_impute_reference(X, missing_mask, k, verbose=False, print_interval=100): """ Reference implementation of kNN imputation logic. """ (n_rows, n_cols) = X.shape (X_result, D, effective_infinity) = knn_initialize(X, missing_mask, verbose=verbose) for i in range(n_rows): for j in np.w...
def cleanup(self, force=False): """Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. @retu...
def function[cleanup, parameter[self, force]]: constant[Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for sel...
keyword[def] identifier[cleanup] ( identifier[self] , identifier[force] = keyword[False] ): literal[string] identifier[manager] = identifier[self] . identifier[getManager] ( identifier[force] = identifier[force] ) keyword[if] identifier[manager] keyword[is] keyword[not] keyword[None] :...
def cleanup(self, force=False): """Clean up Yadis-related services in the session and return the most-recently-attempted service from the manager, if one exists. @param force: True if the manager should be deleted regardless of whether it's a manager for self.url. @return: ...
def get_constrained_fc2(supercell, dataset_second_atoms, atom1, reduced_site_sym, symprec): """ dataset_second_atoms: [{'number': 7, 'displacement': [], 'delta_...
def function[get_constrained_fc2, parameter[supercell, dataset_second_atoms, atom1, reduced_site_sym, symprec]]: constant[ dataset_second_atoms: [{'number': 7, 'displacement': [], 'delta_forces': []}, ...] ] variable[lattice] assign[=] call...
keyword[def] identifier[get_constrained_fc2] ( identifier[supercell] , identifier[dataset_second_atoms] , identifier[atom1] , identifier[reduced_site_sym] , identifier[symprec] ): literal[string] identifier[lattice] = identifier[supercell] . identifier[get_cell] (). identifier[T] identifier[posit...
def get_constrained_fc2(supercell, dataset_second_atoms, atom1, reduced_site_sym, symprec): """ dataset_second_atoms: [{'number': 7, 'displacement': [], 'delta_forces': []}, ...] """ lattice = supercell.get_cell().T positions = supercell.get_sc...
def generate_public_and_private(): """ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: ...
def function[generate_public_and_private, parameter[]]: constant[ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respect...
keyword[def] identifier[generate_public_and_private] (): literal[string] identifier[seed] = identifier[os] . identifier[urandom] ( literal[int] ) identifier[public] = keyword[None] keyword[try] : identifier[nacl_key] = identifier[nacl] . identifier[signing] . identifier[Signi...
def generate_public_and_private(): """ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: ...
def append_index_id(id, ids): """ add index to id to make it unique wrt ids """ index = 1 mod = '%s_%s' % (id, index) while mod in ids: index += 1 mod = '%s_%s' % (id, index) ids.append(mod) return mod, ids
def function[append_index_id, parameter[id, ids]]: constant[ add index to id to make it unique wrt ids ] variable[index] assign[=] constant[1] variable[mod] assign[=] binary_operation[constant[%s_%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b2411f90>, <ast.Name...
keyword[def] identifier[append_index_id] ( identifier[id] , identifier[ids] ): literal[string] identifier[index] = literal[int] identifier[mod] = literal[string] %( identifier[id] , identifier[index] ) keyword[while] identifier[mod] keyword[in] identifier[ids] : identifier[index] += ...
def append_index_id(id, ids): """ add index to id to make it unique wrt ids """ index = 1 mod = '%s_%s' % (id, index) while mod in ids: index += 1 mod = '%s_%s' % (id, index) # depends on [control=['while'], data=['mod']] ids.append(mod) return (mod, ids)
def send_file(request, filename, content_type='image/jpeg'): """ Send a file through Django without loading the whole file into memory at once. The FileWrapper will turn the file object into an iterator for...
def function[send_file, parameter[request, filename, content_type]]: constant[ Send a file through Django without loading the whole file into memory at once. The FileWrapper will turn the file object into an ...
keyword[def] identifier[send_file] ( identifier[request] , identifier[filename] , identifier[content_type] = literal[string] ): literal[string] identifier[wrapper] = identifier[FixedFileWrapper] ( identifier[file] ( identifier[filename] , literal[string] )) identifier[response] = identifier[HttpRespon...
def send_file(request, filename, content_type='image/jpeg'): """ Send a file through Django without loading the whole file into memory at once. The FileWrapper will turn the file object into an iterator for...
def validate_version_pragma(version_str: str, start: ParserPosition) -> None: """ Validates a version pragma directive against the current compiler version. """ from vyper import ( __version__, ) version_arr = version_str.split('@version') file_version = version_arr[1].strip() ...
def function[validate_version_pragma, parameter[version_str, start]]: constant[ Validates a version pragma directive against the current compiler version. ] from relative_module[vyper] import module[__version__] variable[version_arr] assign[=] call[name[version_str].split, parameter[constant...
keyword[def] identifier[validate_version_pragma] ( identifier[version_str] : identifier[str] , identifier[start] : identifier[ParserPosition] )-> keyword[None] : literal[string] keyword[from] identifier[vyper] keyword[import] ( identifier[__version__] , ) identifier[version_arr] = identifi...
def validate_version_pragma(version_str: str, start: ParserPosition) -> None: """ Validates a version pragma directive against the current compiler version. """ from vyper import __version__ version_arr = version_str.split('@version') file_version = version_arr[1].strip() (file_major, file_m...
def stop(cls): """Change back the normal stdout after the end""" if any(cls.streams): sys.stdout = cls.streams.pop(-1) else: sys.stdout = sys.__stdout__
def function[stop, parameter[cls]]: constant[Change back the normal stdout after the end] if call[name[any], parameter[name[cls].streams]] begin[:] name[sys].stdout assign[=] call[name[cls].streams.pop, parameter[<ast.UnaryOp object at 0x7da207f02710>]]
keyword[def] identifier[stop] ( identifier[cls] ): literal[string] keyword[if] identifier[any] ( identifier[cls] . identifier[streams] ): identifier[sys] . identifier[stdout] = identifier[cls] . identifier[streams] . identifier[pop] (- literal[int] ) keyword[else] : ...
def stop(cls): """Change back the normal stdout after the end""" if any(cls.streams): sys.stdout = cls.streams.pop(-1) # depends on [control=['if'], data=[]] else: sys.stdout = sys.__stdout__
def parse_track_header(self, fp): """Return the size of the track chunk.""" # Check the header try: h = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track header from file. Byte %d." % self.bytes_read) ...
def function[parse_track_header, parameter[self, fp]]: constant[Return the size of the track chunk.] <ast.Try object at 0x7da1b13069e0> if compare[name[h] not_equal[!=] constant[MTrk]] begin[:] <ast.Raise object at 0x7da1b26af3d0> <ast.Try object at 0x7da1b26ad150> variable[chunk...
keyword[def] identifier[parse_track_header] ( identifier[self] , identifier[fp] ): literal[string] keyword[try] : identifier[h] = identifier[fp] . identifier[read] ( literal[int] ) identifier[self] . identifier[bytes_read] += literal[int] keyword[except]...
def parse_track_header(self, fp): """Return the size of the track chunk.""" # Check the header try: h = fp.read(4) self.bytes_read += 4 # depends on [control=['try'], data=[]] except: raise IOError("Couldn't read track header from file. Byte %d." % self.bytes_read) # depends on...
def run(self): """ Creates new permissions. """ from pyoko.lib.utils import get_object_from_path from zengine.config import settings model = get_object_from_path(settings.PERMISSION_MODEL) perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER) ...
def function[run, parameter[self]]: constant[ Creates new permissions. ] from relative_module[pyoko.lib.utils] import module[get_object_from_path] from relative_module[zengine.config] import module[settings] variable[model] assign[=] call[name[get_object_from_path], parameter[nam...
keyword[def] identifier[run] ( identifier[self] ): literal[string] keyword[from] identifier[pyoko] . identifier[lib] . identifier[utils] keyword[import] identifier[get_object_from_path] keyword[from] identifier[zengine] . identifier[config] keyword[import] identifier[settings] ...
def run(self): """ Creates new permissions. """ from pyoko.lib.utils import get_object_from_path from zengine.config import settings model = get_object_from_path(settings.PERMISSION_MODEL) perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER) existing_perms = [] ...
def domain_of_validity(self): """ Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] """ # TODO: Generalise interface to return a polyg...
def function[domain_of_validity, parameter[self]]: constant[ Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] ] variable[domain] assi...
keyword[def] identifier[domain_of_validity] ( identifier[self] ): literal[string] identifier[domain] = identifier[self] . identifier[element] . identifier[find] ( identifier[GML_NS] + literal[string] ) identifier[domain_href] = identifier[domain] . identifier[attrib] [ id...
def domain_of_validity(self): """ Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] """ # TODO: Generalise interface to return a polygon? (Can...
def get_job(self): """Get the Streams job that owns this view. Returns: Job: Streams Job owning this view. """ return Job(self.rest_client.make_request(self.job), self.rest_client)
def function[get_job, parameter[self]]: constant[Get the Streams job that owns this view. Returns: Job: Streams Job owning this view. ] return[call[name[Job], parameter[call[name[self].rest_client.make_request, parameter[name[self].job]], name[self].rest_client]]]
keyword[def] identifier[get_job] ( identifier[self] ): literal[string] keyword[return] identifier[Job] ( identifier[self] . identifier[rest_client] . identifier[make_request] ( identifier[self] . identifier[job] ), identifier[self] . identifier[rest_client] )
def get_job(self): """Get the Streams job that owns this view. Returns: Job: Streams Job owning this view. """ return Job(self.rest_client.make_request(self.job), self.rest_client)
def M(self, t, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t) with scipy.errstate(under='ignore'): # don't worry if some values 0 if ('expD', t) not in self._cached: se...
def function[M, parameter[self, t, tips, gaps]]: constant[See docs for method in `Model` abstract base class.] assert[<ast.BoolOp object at 0x7da1b26ad900>] with call[name[scipy].errstate, parameter[]] begin[:] if compare[tuple[[<ast.Constant object at 0x7da1b26afa60>, <ast.Name obje...
keyword[def] identifier[M] ( identifier[self] , identifier[t] , identifier[tips] = keyword[None] , identifier[gaps] = keyword[None] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[t] , identifier[float] ) keyword[and] identifier[t] > literal[int] , literal[string] . identif...
def M(self, t, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" assert isinstance(t, float) and t > 0, 'Invalid t: {0}'.format(t) with scipy.errstate(under='ignore'): # don't worry if some values 0 if ('expD', t) not in self._cached: self._cached['expD', ...
def read_turbomole(basis_lines, fname): '''Reads turbomole-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank ''' skipchars = '*#$' basis_lines = [l for l...
def function[read_turbomole, parameter[basis_lines, fname]]: constant[Reads turbomole-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank ] variable[ski...
keyword[def] identifier[read_turbomole] ( identifier[basis_lines] , identifier[fname] ): literal[string] identifier[skipchars] = literal[string] identifier[basis_lines] =[ identifier[l] keyword[for] identifier[l] keyword[in] identifier[basis_lines] keyword[if] identifier[l] keyword[and] keyw...
def read_turbomole(basis_lines, fname): """Reads turbomole-formatted file data and converts it to a dictionary with the usual BSE fields Note that the turbomole format does not store all the fields we have, so some fields are left blank """ skipchars = '*#$' basis_lines = [l for l ...
def parallel_bulk( client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, queue_size=4, expand_action_callback=expand_action, *args, **kwargs ): """ Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of...
def function[parallel_bulk, parameter[client, actions, thread_count, chunk_size, max_chunk_bytes, queue_size, expand_action_callback]]: constant[ Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: ...
keyword[def] identifier[parallel_bulk] ( identifier[client] , identifier[actions] , identifier[thread_count] = literal[int] , identifier[chunk_size] = literal[int] , identifier[max_chunk_bytes] = literal[int] * literal[int] * literal[int] , identifier[queue_size] = literal[int] , identifier[expand_action_callb...
def parallel_bulk(client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, queue_size=4, expand_action_callback=expand_action, *args, **kwargs): """ Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch`...
def add_group(self, number, name, led_type): """ Add a group. :param number: Group number (1-4). :param name: Group name. :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`. :returns: Added group. """ group = group_factory(self, nu...
def function[add_group, parameter[self, number, name, led_type]]: constant[ Add a group. :param number: Group number (1-4). :param name: Group name. :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`. :returns: Added group. ] varia...
keyword[def] identifier[add_group] ( identifier[self] , identifier[number] , identifier[name] , identifier[led_type] ): literal[string] identifier[group] = identifier[group_factory] ( identifier[self] , identifier[number] , identifier[name] , identifier[led_type] ) identifier[self] . ident...
def add_group(self, number, name, led_type): """ Add a group. :param number: Group number (1-4). :param name: Group name. :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`. :returns: Added group. """ group = group_factory(self, number, na...
def _get_current_migration_state(self, loader, apps): """ Extract the most recent migrations from the relevant apps. If no migrations have been performed, return 'zero' as the most recent migration for the app. This should only be called from list_migrations(). """ # Onl...
def function[_get_current_migration_state, parameter[self, loader, apps]]: constant[ Extract the most recent migrations from the relevant apps. If no migrations have been performed, return 'zero' as the most recent migration for the app. This should only be called from list_migrations()...
keyword[def] identifier[_get_current_migration_state] ( identifier[self] , identifier[loader] , identifier[apps] ): literal[string] identifier[apps] = identifier[set] ( identifier[apps] ) identifier[relevant_applied] =[ identifier[migration] keyword[for] identifier[migration] k...
def _get_current_migration_state(self, loader, apps): """ Extract the most recent migrations from the relevant apps. If no migrations have been performed, return 'zero' as the most recent migration for the app. This should only be called from list_migrations(). """ # Only care a...
def disable_host_svc_checks(self, host): """Disable service checks for a host Format of the line that triggers function call:: DISABLE_HOST_SVC_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ for servi...
def function[disable_host_svc_checks, parameter[self, host]]: constant[Disable service checks for a host Format of the line that triggers function call:: DISABLE_HOST_SVC_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None ...
keyword[def] identifier[disable_host_svc_checks] ( identifier[self] , identifier[host] ): literal[string] keyword[for] identifier[service_id] keyword[in] identifier[host] . identifier[services] : keyword[if] identifier[service_id] keyword[in] identifier[self] . identifier[daemon]...
def disable_host_svc_checks(self, host): """Disable service checks for a host Format of the line that triggers function call:: DISABLE_HOST_SVC_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ for service_id in...
def dzip(items1, items2, cls=dict): """ Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequence of equal ...
def function[dzip, parameter[items1, items2, cls]]: constant[ Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequ...
keyword[def] identifier[dzip] ( identifier[items1] , identifier[items2] , identifier[cls] = identifier[dict] ): literal[string] keyword[try] : identifier[len] ( identifier[items1] ) keyword[except] identifier[TypeError] : identifier[items1] = identifier[list] ( identifier[items1] ) ...
def dzip(items1, items2, cls=dict): """ Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequence of equal ...
def log_pdf(self, y, mu, weights=None): """ computes the log of the pdf or pmf of the values under the current distribution Parameters ---------- y : array-like of length n target values mu : array-like of length n expected values weights ...
def function[log_pdf, parameter[self, y, mu, weights]]: constant[ computes the log of the pdf or pmf of the values under the current distribution Parameters ---------- y : array-like of length n target values mu : array-like of length n expected v...
keyword[def] identifier[log_pdf] ( identifier[self] , identifier[y] , identifier[mu] , identifier[weights] = keyword[None] ): literal[string] keyword[if] identifier[weights] keyword[is] keyword[None] : identifier[weights] = identifier[np] . identifier[ones_like] ( identifier[mu] ) ...
def log_pdf(self, y, mu, weights=None): """ computes the log of the pdf or pmf of the values under the current distribution Parameters ---------- y : array-like of length n target values mu : array-like of length n expected values weights : ar...
def dataReceived(self, data): """ Translates bytes into lines, and calls lineReceived. Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using str.splitlines() to split on ``\r\n``, ``\n``, and ``\r``. """ self.resetTimeout() lines = (self._buffer + da...
def function[dataReceived, parameter[self, data]]: constant[ Translates bytes into lines, and calls lineReceived. Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using str.splitlines() to split on `` ``, `` ``, and `` ``. ] call[name[self].resetTimeout, par...
keyword[def] identifier[dataReceived] ( identifier[self] , identifier[data] ): literal[string] identifier[self] . identifier[resetTimeout] () identifier[lines] =( identifier[self] . identifier[_buffer] + identifier[data] ). identifier[splitlines] () ...
def dataReceived(self, data): """ Translates bytes into lines, and calls lineReceived. Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using str.splitlines() to split on ``\r ``, `` ``, and ``\r``. """ self.resetTimeout() lines = (self._buffer + data).splitlines...
def two_phase_dP(m, x, rhol, D, L=1, rhog=None, mul=None, mug=None, sigma=None, P=None, Pc=None, roughness=0, angle=0, Method=None, AvailableMethods=False): r'''This function handles calculation of two-phase liquid-gas pressure drop for flow inside channels. 23 calculation met...
def function[two_phase_dP, parameter[m, x, rhol, D, L, rhog, mul, mug, sigma, P, Pc, roughness, angle, Method, AvailableMethods]]: constant[This function handles calculation of two-phase liquid-gas pressure drop for flow inside channels. 23 calculation methods are available, with varying input requireme...
keyword[def] identifier[two_phase_dP] ( identifier[m] , identifier[x] , identifier[rhol] , identifier[D] , identifier[L] = literal[int] , identifier[rhog] = keyword[None] , identifier[mul] = keyword[None] , identifier[mug] = keyword[None] , identifier[sigma] = keyword[None] , identifier[P] = keyword[None] , identifi...
def two_phase_dP(m, x, rhol, D, L=1, rhog=None, mul=None, mug=None, sigma=None, P=None, Pc=None, roughness=0, angle=0, Method=None, AvailableMethods=False): """This function handles calculation of two-phase liquid-gas pressure drop for flow inside channels. 23 calculation methods are available, with varying...
def update_config_from_dockerfile(self, config): """Updates build config with values from the Dockerfile Updates: * set "name" from LABEL com.redhat.component (if exists) * set "version" from LABEL version (if exists) :param config: ConfigParser object """ l...
def function[update_config_from_dockerfile, parameter[self, config]]: constant[Updates build config with values from the Dockerfile Updates: * set "name" from LABEL com.redhat.component (if exists) * set "version" from LABEL version (if exists) :param config: ConfigParser o...
keyword[def] identifier[update_config_from_dockerfile] ( identifier[self] , identifier[config] ): literal[string] identifier[labels] = identifier[Labels] ( identifier[df_parser] ( identifier[self] . identifier[workflow] . identifier[builder] . identifier[df_path] ). identifier[labels] ) ke...
def update_config_from_dockerfile(self, config): """Updates build config with values from the Dockerfile Updates: * set "name" from LABEL com.redhat.component (if exists) * set "version" from LABEL version (if exists) :param config: ConfigParser object """ labels = ...
def get_menu(self, name): """Return or create a menu.""" if name not in self._menus: self._menus[name] = self.menuBar().addMenu(name) return self._menus[name]
def function[get_menu, parameter[self, name]]: constant[Return or create a menu.] if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self]._menus] begin[:] call[name[self]._menus][name[name]] assign[=] call[call[name[self].menuBar, parameter[]].addMenu, parameter[name[name]]...
keyword[def] identifier[get_menu] ( identifier[self] , identifier[name] ): literal[string] keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_menus] : identifier[self] . identifier[_menus] [ identifier[name] ]= identifier[self] . identifier[menuBar...
def get_menu(self, name): """Return or create a menu.""" if name not in self._menus: self._menus[name] = self.menuBar().addMenu(name) # depends on [control=['if'], data=['name']] return self._menus[name]
def next(self): """Pops and returns the first outgoing message from the list. If message list currently has no messages, the calling thread will be put to sleep until we have at-least one message in the list that can be popped and returned. """ # We pick the first outgoi...
def function[next, parameter[self]]: constant[Pops and returns the first outgoing message from the list. If message list currently has no messages, the calling thread will be put to sleep until we have at-least one message in the list that can be popped and returned. ] v...
keyword[def] identifier[next] ( identifier[self] ): literal[string] identifier[outgoing_msg] = identifier[self] . identifier[outgoing_msg_list] . identifier[pop_first] () keyword[if] identifier[outgoing_msg] keyword[is] keyword[None] : identifier[self] . i...
def next(self): """Pops and returns the first outgoing message from the list. If message list currently has no messages, the calling thread will be put to sleep until we have at-least one message in the list that can be popped and returned. """ # We pick the first outgoing avail...
def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
def function[iso_to_gregorian, parameter[iso_year, iso_week, iso_day]]: constant[Gregorian calendar date for the given ISO year, week and day] variable[year_start] assign[=] call[name[iso_year_start], parameter[name[iso_year]]] return[binary_operation[name[year_start] + call[name[datetime].timedelta...
keyword[def] identifier[iso_to_gregorian] ( identifier[iso_year] , identifier[iso_week] , identifier[iso_day] ): literal[string] identifier[year_start] = identifier[iso_year_start] ( identifier[iso_year] ) keyword[return] identifier[year_start] + identifier[datetime] . identifier[timedelta] ( identif...
def iso_to_gregorian(iso_year, iso_week, iso_day): """Gregorian calendar date for the given ISO year, week and day""" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
def _generate_base_namespace_module(self, api, namespace): """Creates a module for the namespace. All data types and routes are represented as Python classes.""" self.cur_namespace = namespace generate_module_header(self) if namespace.doc is not None: self.emit('"""...
def function[_generate_base_namespace_module, parameter[self, api, namespace]]: constant[Creates a module for the namespace. All data types and routes are represented as Python classes.] name[self].cur_namespace assign[=] name[namespace] call[name[generate_module_header], parameter[name[...
keyword[def] identifier[_generate_base_namespace_module] ( identifier[self] , identifier[api] , identifier[namespace] ): literal[string] identifier[self] . identifier[cur_namespace] = identifier[namespace] identifier[generate_module_header] ( identifier[self] ) keyword[if] ide...
def _generate_base_namespace_module(self, api, namespace): """Creates a module for the namespace. All data types and routes are represented as Python classes.""" self.cur_namespace = namespace generate_module_header(self) if namespace.doc is not None: self.emit('"""') self.emit_r...
def open(self, bus): """Open the smbus interface on the specified bus.""" # Close the device if it's already open. if self._device is not None: self.close() # Try to open the file for the specified bus. Must turn off buffering # or else Python 3 fails (see: https://b...
def function[open, parameter[self, bus]]: constant[Open the smbus interface on the specified bus.] if compare[name[self]._device is_not constant[None]] begin[:] call[name[self].close, parameter[]] name[self]._device assign[=] call[name[open], parameter[call[constant[/dev/i2c-{0}]...
keyword[def] identifier[open] ( identifier[self] , identifier[bus] ): literal[string] keyword[if] identifier[self] . identifier[_device] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[close] () identifier[self] . i...
def open(self, bus): """Open the smbus interface on the specified bus.""" # Close the device if it's already open. if self._device is not None: self.close() # depends on [control=['if'], data=[]] # Try to open the file for the specified bus. Must turn off buffering # or else Python 3 fails...
def coindex_around_coords(self, lat, lon, start=None, interval=None): """ Queries the OWM Weather API for Carbon Monoxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *COIndex* object instance is returned, encapsulating a...
def function[coindex_around_coords, parameter[self, lat, lon, start, interval]]: constant[ Queries the OWM Weather API for Carbon Monoxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *COIndex* object instance is returned...
keyword[def] identifier[coindex_around_coords] ( identifier[self] , identifier[lat] , identifier[lon] , identifier[start] = keyword[None] , identifier[interval] = keyword[None] ): literal[string] identifier[geo] . identifier[assert_is_lon] ( identifier[lon] ) identifier[geo] . identifier[a...
def coindex_around_coords(self, lat, lon, start=None, interval=None): """ Queries the OWM Weather API for Carbon Monoxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *COIndex* object instance is returned, encapsulating a ...
def retrieve_netting_set(self, asset_manager_id, transaction_id): """ Returns all the transaction_ids associated with a single netting set. Pass in the ID for any transaction in the set. :param asset_manager_id: The asset_manager_id for the netting set owner. :param transaction...
def function[retrieve_netting_set, parameter[self, asset_manager_id, transaction_id]]: constant[ Returns all the transaction_ids associated with a single netting set. Pass in the ID for any transaction in the set. :param asset_manager_id: The asset_manager_id for the netting set owner....
keyword[def] identifier[retrieve_netting_set] ( identifier[self] , identifier[asset_manager_id] , identifier[transaction_id] ): literal[string] identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[asset_manager_id] , identifier[transaction_id] ) ...
def retrieve_netting_set(self, asset_manager_id, transaction_id): """ Returns all the transaction_ids associated with a single netting set. Pass in the ID for any transaction in the set. :param asset_manager_id: The asset_manager_id for the netting set owner. :param transaction_id:...
def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base**lsb for lsb, l in enumerate(s) ))
def function[_string_to_int, parameter[self, s]]: constant[Read an integer in s, in Little Indian. ] variable[base] assign[=] call[name[len], parameter[name[self].alphabet]] return[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da18dc04700>]]]
keyword[def] identifier[_string_to_int] ( identifier[self] , identifier[s] ): literal[string] identifier[base] = identifier[len] ( identifier[self] . identifier[alphabet] ) keyword[return] identifier[sum] (( identifier[self] . identifier[_letter_to_int] ( identifier[l] )* identifier[base]...
def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base ** lsb for (lsb, l) in enumerate(s)))
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attrib...
def function[get_custom_views, parameter[name]]: constant[ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dict...
keyword[def] identifier[get_custom_views] ( identifier[name] = keyword[None] ): literal[string] keyword[if] identifier[auth] keyword[is] keyword[None] keyword[or] identifier[url] keyword[is] keyword[None] : identifier[set_imc_creds] () keyword[if] identifier[name] keyword[is] keywor...
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attrib...
def subnet2block(subnet): """Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0', '127.255.255.255') >>> sub...
def function[subnet2block, parameter[subnet]]: constant[Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0',...
keyword[def] identifier[subnet2block] ( identifier[subnet] ): literal[string] keyword[if] keyword[not] identifier[validate_subnet] ( identifier[subnet] ): keyword[return] keyword[None] identifier[ip] , identifier[netmask] = identifier[subnet] . identifier[split] ( literal[string] ) ...
def subnet2block(subnet): """Convert a dotted-quad ip address including a netmask into a tuple containing the network block start and end addresses. >>> subnet2block('127.0.0.1/255.255.255.255') ('127.0.0.1', '127.0.0.1') >>> subnet2block('127/255') ('127.0.0.0', '127.255.255.255') >>> sub...
def memorized_datetime(seconds): '''Create only one instance of each distinct datetime''' try: return _datetime_cache[seconds] except KeyError: # NB. We can't just do datetime.utcfromtimestamp(seconds) as this # fails with negative values under Windows (Bug #90096) dt = _epoc...
def function[memorized_datetime, parameter[seconds]]: constant[Create only one instance of each distinct datetime] <ast.Try object at 0x7da18f812bf0>
keyword[def] identifier[memorized_datetime] ( identifier[seconds] ): literal[string] keyword[try] : keyword[return] identifier[_datetime_cache] [ identifier[seconds] ] keyword[except] identifier[KeyError] : identifier[dt] = identifier[_epoch] + identifier[timedelta] ( ide...
def memorized_datetime(seconds): """Create only one instance of each distinct datetime""" try: return _datetime_cache[seconds] # depends on [control=['try'], data=[]] except KeyError: # NB. We can't just do datetime.utcfromtimestamp(seconds) as this # fails with negative values unde...
def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): ''' Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
def function[get_data_csv, parameter[file_name, encoding, file_contents, on_demand]]: constant[ Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file...
keyword[def] identifier[get_data_csv] ( identifier[file_name] , identifier[encoding] = literal[string] , identifier[file_contents] = keyword[None] , identifier[on_demand] = keyword[False] ): literal[string] keyword[def] identifier[yield_csv] ( identifier[csv_contents] , identifier[csv_file] ): ke...
def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): """ Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
def process(self, pq): """ :arg PlaceQuery pq: PlaceQuery instance :returns: modified PlaceQuery, or ``False`` if country is not acceptable. """ # Map country, but don't let map overwrite if pq.country not in self.acceptable_countries and pq.country in self.country_map: ...
def function[process, parameter[self, pq]]: constant[ :arg PlaceQuery pq: PlaceQuery instance :returns: modified PlaceQuery, or ``False`` if country is not acceptable. ] if <ast.BoolOp object at 0x7da20c794490> begin[:] name[pq].country assign[=] call[name[self].c...
keyword[def] identifier[process] ( identifier[self] , identifier[pq] ): literal[string] keyword[if] identifier[pq] . identifier[country] keyword[not] keyword[in] identifier[self] . identifier[acceptable_countries] keyword[and] identifier[pq] . identifier[country] keyword[in] identi...
def process(self, pq): """ :arg PlaceQuery pq: PlaceQuery instance :returns: modified PlaceQuery, or ``False`` if country is not acceptable. """ # Map country, but don't let map overwrite if pq.country not in self.acceptable_countries and pq.country in self.country_map: pq.co...
def analyze(self, file, filename): """ :param file: The File object itself. :param filename: string; filename of File object, used for creating PotentialSecret objects :returns dictionary representation of set (for random access by hash) ...
def function[analyze, parameter[self, file, filename]]: constant[ :param file: The File object itself. :param filename: string; filename of File object, used for creating PotentialSecret objects :returns dictionary representation of set (for random ac...
keyword[def] identifier[analyze] ( identifier[self] , identifier[file] , identifier[filename] ): literal[string] identifier[potential_secrets] ={} keyword[for] identifier[line_num] , identifier[line] keyword[in] identifier[enumerate] ( identifier[file] . identifier[readlines] (), identi...
def analyze(self, file, filename): """ :param file: The File object itself. :param filename: string; filename of File object, used for creating PotentialSecret objects :returns dictionary representation of set (for random access by hash) ...