code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def members(self, name=None, status=None, tags=None): """ Lists members of a Serf cluster, optionally filtered by one or more filters: `name` is a string, supporting regex matching on node names. `status` is a string, supporting regex matching on node status. `tags` is a...
def function[members, parameter[self, name, status, tags]]: constant[ Lists members of a Serf cluster, optionally filtered by one or more filters: `name` is a string, supporting regex matching on node names. `status` is a string, supporting regex matching on node status. ...
keyword[def] identifier[members] ( identifier[self] , identifier[name] = keyword[None] , identifier[status] = keyword[None] , identifier[tags] = keyword[None] ): literal[string] identifier[filters] ={} keyword[if] identifier[name] keyword[is] keyword[not] keyword[None] : ...
def members(self, name=None, status=None, tags=None): """ Lists members of a Serf cluster, optionally filtered by one or more filters: `name` is a string, supporting regex matching on node names. `status` is a string, supporting regex matching on node status. `tags` is a dic...
def _add_labels(ax: Axes, h: Union[Histogram1D, Histogram2D], kwargs: dict): """Add axis and plot labels. TODO: Document kwargs """ title = kwargs.pop("title", h.title) xlabel = kwargs.pop("xlabel", h.axis_names[0]) ylabel = kwargs.pop("ylabel", h.axis_names[1] if len(h.axis_names) == 2 els...
def function[_add_labels, parameter[ax, h, kwargs]]: constant[Add axis and plot labels. TODO: Document kwargs ] variable[title] assign[=] call[name[kwargs].pop, parameter[constant[title], name[h].title]] variable[xlabel] assign[=] call[name[kwargs].pop, parameter[constant[xlabel], c...
keyword[def] identifier[_add_labels] ( identifier[ax] : identifier[Axes] , identifier[h] : identifier[Union] [ identifier[Histogram1D] , identifier[Histogram2D] ], identifier[kwargs] : identifier[dict] ): literal[string] identifier[title] = identifier[kwargs] . identifier[pop] ( literal[string] , identifie...
def _add_labels(ax: Axes, h: Union[Histogram1D, Histogram2D], kwargs: dict): """Add axis and plot labels. TODO: Document kwargs """ title = kwargs.pop('title', h.title) xlabel = kwargs.pop('xlabel', h.axis_names[0]) ylabel = kwargs.pop('ylabel', h.axis_names[1] if len(h.axis_names) == 2 els...
def main(): """ Welcome to the thellier-thellier experiment automatic chart maker. Please select desired step interval and upper bound for which it is valid. e.g., 50 500 10 600 a blank entry signals the end of data entry. which would generate steps with 50 degree in...
def function[main, parameter[]]: constant[ Welcome to the thellier-thellier experiment automatic chart maker. Please select desired step interval and upper bound for which it is valid. e.g., 50 500 10 600 a blank entry signals the end of data entry. which would g...
keyword[def] identifier[main] (): literal[string] identifier[print] ( identifier[main] . identifier[__doc__] ) keyword[if] literal[string] keyword[in] identifier[sys] . identifier[argv] : identifier[sys] . identifier[exit] () identifier[cont] , identifier[Int] , identifier[Top] = literal[int] ...
def main(): """ Welcome to the thellier-thellier experiment automatic chart maker. Please select desired step interval and upper bound for which it is valid. e.g., 50 500 10 600 a blank entry signals the end of data entry. which would generate steps with 50 degree in...
def waiter(self): """Return a :class:`~asyncio.Future` called back once the event has been fired. If the event has been fired already return a resolved future. This method is available only for one-time events """ assert self._onetime, 'One time events only can invoke wa...
def function[waiter, parameter[self]]: constant[Return a :class:`~asyncio.Future` called back once the event has been fired. If the event has been fired already return a resolved future. This method is available only for one-time events ] assert[name[self]._onetime] ...
keyword[def] identifier[waiter] ( identifier[self] ): literal[string] keyword[assert] identifier[self] . identifier[_onetime] , literal[string] keyword[if] keyword[not] identifier[self] . identifier[_waiter] : identifier[self] . identifier[_waiter] = identifier[get_event_l...
def waiter(self): """Return a :class:`~asyncio.Future` called back once the event has been fired. If the event has been fired already return a resolved future. This method is available only for one-time events """ assert self._onetime, 'One time events only can invoke waiter' ...
def _query_filter(search, urlkwargs, definitions): """Ingest query filter in query.""" filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions) for filter_ in filters: search = search.filter(filter_) return (search, urlkwargs)
def function[_query_filter, parameter[search, urlkwargs, definitions]]: constant[Ingest query filter in query.] <ast.Tuple object at 0x7da1b0342380> assign[=] call[name[_create_filter_dsl], parameter[name[urlkwargs], name[definitions]]] for taget[name[filter_]] in starred[name[filters]] begin[:]...
keyword[def] identifier[_query_filter] ( identifier[search] , identifier[urlkwargs] , identifier[definitions] ): literal[string] identifier[filters] , identifier[urlkwargs] = identifier[_create_filter_dsl] ( identifier[urlkwargs] , identifier[definitions] ) keyword[for] identifier[filter_] keyword[...
def _query_filter(search, urlkwargs, definitions): """Ingest query filter in query.""" (filters, urlkwargs) = _create_filter_dsl(urlkwargs, definitions) for filter_ in filters: search = search.filter(filter_) # depends on [control=['for'], data=['filter_']] return (search, urlkwargs)
def get_status_from_resource(self, response): """Process the latest status update retrieved from the same URL as the previous request. :param requests.Response response: latest REST call response. :raises: BadResponse if status not 200 or 204. """ self._raise_if_bad_http...
def function[get_status_from_resource, parameter[self, response]]: constant[Process the latest status update retrieved from the same URL as the previous request. :param requests.Response response: latest REST call response. :raises: BadResponse if status not 200 or 204. ] ...
keyword[def] identifier[get_status_from_resource] ( identifier[self] , identifier[response] ): literal[string] identifier[self] . identifier[_raise_if_bad_http_status_and_method] ( identifier[response] ) keyword[if] identifier[self] . identifier[_is_empty] ( identifier[response] ): ...
def get_status_from_resource(self, response): """Process the latest status update retrieved from the same URL as the previous request. :param requests.Response response: latest REST call response. :raises: BadResponse if status not 200 or 204. """ self._raise_if_bad_http_status_...
def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec): """Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AS...
def function[process_rule, parameter[edges, ast, rule, spec]]: constant[Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AST rule...
keyword[def] identifier[process_rule] ( identifier[edges] : identifier[Edges] , identifier[ast] : identifier[Function] , identifier[rule] : identifier[Mapping] [ identifier[str] , identifier[Any] ], identifier[spec] : identifier[BELSpec] ): literal[string] identifier[ast_type] = identifier[ast] . identifie...
def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec): """Process computed edge rule Recursively processes BELAst versus a single computed edge rule Args: edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs ast (Function): BEL Function AS...
def rinse_rpnexp(self, rpnexp, rpndict): """ replace valid keyword of rpnexp from rpndict e.g. rpnexp = 'b a /', rpndict = {'b': 10} then after rinsing, rpnexp = '10 a /' return rinsed rpnexp """ for wd in rpnexp.split(): if wd in rpndict: ...
def function[rinse_rpnexp, parameter[self, rpnexp, rpndict]]: constant[ replace valid keyword of rpnexp from rpndict e.g. rpnexp = 'b a /', rpndict = {'b': 10} then after rinsing, rpnexp = '10 a /' return rinsed rpnexp ] for taget[name[wd]] in starred[call[na...
keyword[def] identifier[rinse_rpnexp] ( identifier[self] , identifier[rpnexp] , identifier[rpndict] ): literal[string] keyword[for] identifier[wd] keyword[in] identifier[rpnexp] . identifier[split] (): keyword[if] identifier[wd] keyword[in] identifier[rpndict] : ...
def rinse_rpnexp(self, rpnexp, rpndict): """ replace valid keyword of rpnexp from rpndict e.g. rpnexp = 'b a /', rpndict = {'b': 10} then after rinsing, rpnexp = '10 a /' return rinsed rpnexp """ for wd in rpnexp.split(): if wd in rpndict: try: ...
def disableEffect(self, name): """Disable an effect.""" try: del self._effects[name] self.__getattribute__( '_effectdisable_%s' % name.replace("-", "_") )() except KeyError: pass except AttributeError: pass
def function[disableEffect, parameter[self, name]]: constant[Disable an effect.] <ast.Try object at 0x7da2045669e0>
keyword[def] identifier[disableEffect] ( identifier[self] , identifier[name] ): literal[string] keyword[try] : keyword[del] identifier[self] . identifier[_effects] [ identifier[name] ] identifier[self] . identifier[__getattribute__] ( literal[string] % identi...
def disableEffect(self, name): """Disable an effect.""" try: del self._effects[name] self.__getattribute__('_effectdisable_%s' % name.replace('-', '_'))() # depends on [control=['try'], data=[]] except KeyError: pass # depends on [control=['except'], data=[]] except AttributeEr...
def settle( self, channel_identifier: ChannelID, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner: Address, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmoun...
def function[settle, parameter[self, channel_identifier, transferred_amount, locked_amount, locksroot, partner, partner_transferred_amount, partner_locked_amount, partner_locksroot, given_block_identifier]]: constant[ Settle the channel. ] variable[log_details] assign[=] dictionary[[<ast.Constant object...
keyword[def] identifier[settle] ( identifier[self] , identifier[channel_identifier] : identifier[ChannelID] , identifier[transferred_amount] : identifier[TokenAmount] , identifier[locked_amount] : identifier[TokenAmount] , identifier[locksroot] : identifier[Locksroot] , identifier[partner] : identifier[Address]...
def settle(self, channel_identifier: ChannelID, transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, partner: Address, partner_transferred_amount: TokenAmount, partner_locked_amount: TokenAmount, partner_locksroot: Locksroot, given_block_identifier: BlockSpecification): """ Settle the ...
def stream(self): ''' Return the current zmqstream, creating one if necessary ''' if not hasattr(self, '_stream'): self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop) return self._stream
def function[stream, parameter[self]]: constant[ Return the current zmqstream, creating one if necessary ] if <ast.UnaryOp object at 0x7da1b1f6f4c0> begin[:] name[self]._stream assign[=] call[name[zmq].eventloop.zmqstream.ZMQStream, parameter[name[self]._socket]] retu...
keyword[def] identifier[stream] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ): identifier[self] . identifier[_stream] = identifier[zmq] . identifier[eventloop] . identifier[zmqstream] . identifier[ZMQStream] ...
def stream(self): """ Return the current zmqstream, creating one if necessary """ if not hasattr(self, '_stream'): self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop) # depends on [control=['if'], data=[]] return self._stream
def ParseRecord(self, parser_mediator, key, structure): """Parses a log record structure and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens. ...
def function[ParseRecord, parameter[self, parser_mediator, key, structure]]: constant[Parses a log record structure and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier...
keyword[def] identifier[ParseRecord] ( identifier[self] , identifier[parser_mediator] , identifier[key] , identifier[structure] ): literal[string] keyword[if] identifier[key] keyword[not] keyword[in] ( literal[string] , literal[string] , literal[string] ): keyword[raise] identifier[errors] . ide...
def ParseRecord(self, parser_mediator, key, structure): """Parses a log record structure and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens. ...
def language_model(self,verbose=True): """ builds a Tamil bigram letter model """ # use a generator in corpus p2 = None p1 = None for next_letter in self.corpus.next_tamil_letter(): # update frequency from corpus if p2: trig = p2+p1+next_le...
def function[language_model, parameter[self, verbose]]: constant[ builds a Tamil bigram letter model ] variable[p2] assign[=] constant[None] variable[p1] assign[=] constant[None] for taget[name[next_letter]] in starred[call[name[self].corpus.next_tamil_letter, parameter[]]] begin[:] ...
keyword[def] identifier[language_model] ( identifier[self] , identifier[verbose] = keyword[True] ): literal[string] identifier[p2] = keyword[None] identifier[p1] = keyword[None] keyword[for] identifier[next_letter] keyword[in] identifier[self] . identifier[corpus] . ...
def language_model(self, verbose=True): """ builds a Tamil bigram letter model """ # use a generator in corpus p2 = None p1 = None for next_letter in self.corpus.next_tamil_letter(): # update frequency from corpus if p2: trig = p2 + p1 + next_letter self.lette...
def clean_ip(ip): """ Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:...
def function[clean_ip, parameter[ip]]: constant[ Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:000...
keyword[def] identifier[clean_ip] ( identifier[ip] ): literal[string] identifier[theip] = identifier[normalize_ip] ( identifier[ip] ) identifier[segments] =[ literal[string] % identifier[int] ( identifier[s] , literal[int] ) keyword[for] identifier[s] keyword[in] identifier[theip] . identifier[spli...
def clean_ip(ip): """ Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:...
def deletegroupmember(self, group_id, user_id): """ Delete a group member :param group_id: group id to remove the member from :param user_id: user id :return: always true """ request = requests.delete( '{0}/{1}/members/{2}'.format(self.groups_url, gro...
def function[deletegroupmember, parameter[self, group_id, user_id]]: constant[ Delete a group member :param group_id: group id to remove the member from :param user_id: user id :return: always true ] variable[request] assign[=] call[name[requests].delete, paramet...
keyword[def] identifier[deletegroupmember] ( identifier[self] , identifier[group_id] , identifier[user_id] ): literal[string] identifier[request] = identifier[requests] . identifier[delete] ( literal[string] . identifier[format] ( identifier[self] . identifier[groups_url] , identifier[grou...
def deletegroupmember(self, group_id, user_id): """ Delete a group member :param group_id: group id to remove the member from :param user_id: user id :return: always true """ request = requests.delete('{0}/{1}/members/{2}'.format(self.groups_url, group_id, user_id), head...
def _from_java(cls, java_stage): """ Given a Java CrossValidator, create and return a Python wrapper of it. Used for ML persistence. """ estimator, epms, evaluator = super(CrossValidator, cls)._from_java_impl(java_stage) numFolds = java_stage.getNumFolds() seed =...
def function[_from_java, parameter[cls, java_stage]]: constant[ Given a Java CrossValidator, create and return a Python wrapper of it. Used for ML persistence. ] <ast.Tuple object at 0x7da1b20a9a20> assign[=] call[call[name[super], parameter[name[CrossValidator], name[cls]]]._fro...
keyword[def] identifier[_from_java] ( identifier[cls] , identifier[java_stage] ): literal[string] identifier[estimator] , identifier[epms] , identifier[evaluator] = identifier[super] ( identifier[CrossValidator] , identifier[cls] ). identifier[_from_java_impl] ( identifier[java_stage] ) i...
def _from_java(cls, java_stage): """ Given a Java CrossValidator, create and return a Python wrapper of it. Used for ML persistence. """ (estimator, epms, evaluator) = super(CrossValidator, cls)._from_java_impl(java_stage) numFolds = java_stage.getNumFolds() seed = java_stage.get...
def create(self, project, slug, content, **attrs): """ create a new :class:`WikiPage` :param project: :class:`Project` id :param slug: slug of the wiki page :param content: content of the wiki page :param attrs: optional attributes for the :class:`WikiPage` """ ...
def function[create, parameter[self, project, slug, content]]: constant[ create a new :class:`WikiPage` :param project: :class:`Project` id :param slug: slug of the wiki page :param content: content of the wiki page :param attrs: optional attributes for the :class:`WikiP...
keyword[def] identifier[create] ( identifier[self] , identifier[project] , identifier[slug] , identifier[content] ,** identifier[attrs] ): literal[string] identifier[attrs] . identifier[update] ({ literal[string] : identifier[project] , literal[string] : identifier[slug] , literal[string] : identif...
def create(self, project, slug, content, **attrs): """ create a new :class:`WikiPage` :param project: :class:`Project` id :param slug: slug of the wiki page :param content: content of the wiki page :param attrs: optional attributes for the :class:`WikiPage` """ a...
def register(cls, name): """ Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already registered. """ def decorate(klazz): """ Decorator. """ if name in cls._events: rai...
def function[register, parameter[cls, name]]: constant[ Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already registered. ] def function[decorate, parameter[klazz]]: constant[ Decorator. ] ...
keyword[def] identifier[register] ( identifier[cls] , identifier[name] ): literal[string] keyword[def] identifier[decorate] ( identifier[klazz] ): literal[string] keyword[if] identifier[name] keyword[in] identifier[cls] . identifier[_events] : keywor...
def register(cls, name): """ Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already registered. """ def decorate(klazz): """ Decorator. """ if name in cls._events: raise GerritError('Dupl...
def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary. """ if self.field_names is None: return dict...
def function[field_dict, parameter[self, model]]: constant[ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary. ] if compare[name[self].field...
keyword[def] identifier[field_dict] ( identifier[self] , identifier[model] ): literal[string] keyword[if] identifier[self] . identifier[field_names] keyword[is] keyword[None] : keyword[return] identifier[dict] ([( identifier[f] . identifier[name] , identifier[f] ) keyword[for] ide...
def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary. """ if self.field_names is None: return dict([(f.name, f...
def _decompose_bytes_to_bit_arr(arr): """ Unpack bytes to bits :param arr: list Byte Stream, as a list of uint8 values Returns ------- bit_arr: list Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) """ bit_arr = [] for idx in range(len(arr)): ...
def function[_decompose_bytes_to_bit_arr, parameter[arr]]: constant[ Unpack bytes to bits :param arr: list Byte Stream, as a list of uint8 values Returns ------- bit_arr: list Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) ] variable[bit_arr] a...
keyword[def] identifier[_decompose_bytes_to_bit_arr] ( identifier[arr] ): literal[string] identifier[bit_arr] =[] keyword[for] identifier[idx] keyword[in] identifier[range] ( identifier[len] ( identifier[arr] )): keyword[for] identifier[i] keyword[in] identifier[reversed] ( identifier[r...
def _decompose_bytes_to_bit_arr(arr): """ Unpack bytes to bits :param arr: list Byte Stream, as a list of uint8 values Returns ------- bit_arr: list Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) """ bit_arr = [] for idx in range(len(arr)): ...
def _extract_image_urls(arg: Message_T) -> List[str]: """Extract all image urls from a message-like object.""" arg_as_msg = Message(arg) return [s.data['url'] for s in arg_as_msg if s.type == 'image' and 'url' in s.data]
def function[_extract_image_urls, parameter[arg]]: constant[Extract all image urls from a message-like object.] variable[arg_as_msg] assign[=] call[name[Message], parameter[name[arg]]] return[<ast.ListComp object at 0x7da20c9928f0>]
keyword[def] identifier[_extract_image_urls] ( identifier[arg] : identifier[Message_T] )-> identifier[List] [ identifier[str] ]: literal[string] identifier[arg_as_msg] = identifier[Message] ( identifier[arg] ) keyword[return] [ identifier[s] . identifier[data] [ literal[string] ] keyword[for] identif...
def _extract_image_urls(arg: Message_T) -> List[str]: """Extract all image urls from a message-like object.""" arg_as_msg = Message(arg) return [s.data['url'] for s in arg_as_msg if s.type == 'image' and 'url' in s.data]
def postfix_to_optree(nodes): """Convert a list of nodes in postfix order to an Optree.""" while len(nodes) > 1: nodes = _reduce(nodes) if len(nodes) == 0: raise OperatorError("Empty node list") node = nodes[0] if isinstance(node, OperatorNode): raise OperatorError("Operator without operands") ...
def function[postfix_to_optree, parameter[nodes]]: constant[Convert a list of nodes in postfix order to an Optree.] while compare[call[name[len], parameter[name[nodes]]] greater[>] constant[1]] begin[:] variable[nodes] assign[=] call[name[_reduce], parameter[name[nodes]]] if comp...
keyword[def] identifier[postfix_to_optree] ( identifier[nodes] ): literal[string] keyword[while] identifier[len] ( identifier[nodes] )> literal[int] : identifier[nodes] = identifier[_reduce] ( identifier[nodes] ) keyword[if] identifier[len] ( identifier[nodes] )== literal[int] : keyword[raise] ...
def postfix_to_optree(nodes): """Convert a list of nodes in postfix order to an Optree.""" while len(nodes) > 1: nodes = _reduce(nodes) # depends on [control=['while'], data=[]] if len(nodes) == 0: raise OperatorError('Empty node list') # depends on [control=['if'], data=[]] node = nod...
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} ...
def function[show_current_number, parameter[parser, token]]: constant[Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django ...
keyword[def] identifier[show_current_number] ( identifier[parser] , identifier[token] ): literal[string] keyword[try] : identifier[tag_name] , identifier[args] = identifier[token] . identifier[contents] . identifier[split] ( keyword[None] , literal[int] ) keyword[except] identifier[Valu...
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} ...
def start(self): """ The main loop, run forever. """ while True: self.thread_debug("Interval starting") for thr in threading.enumerate(): self.thread_debug(" " + str(thr)) self.feed_monitors() start = time.time() ...
def function[start, parameter[self]]: constant[ The main loop, run forever. ] while constant[True] begin[:] call[name[self].thread_debug, parameter[constant[Interval starting]]] for taget[name[thr]] in starred[call[name[threading].enumerate, parameter[]]] ...
keyword[def] identifier[start] ( identifier[self] ): literal[string] keyword[while] keyword[True] : identifier[self] . identifier[thread_debug] ( literal[string] ) keyword[for] identifier[thr] keyword[in] identifier[threading] . identifier[enumerate] (): ...
def start(self): """ The main loop, run forever. """ while True: self.thread_debug('Interval starting') for thr in threading.enumerate(): self.thread_debug(' ' + str(thr)) # depends on [control=['for'], data=['thr']] self.feed_monitors() start = ti...
def policy_assignment_delete(name, scope, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a policy assignment. :param name: The name of the policy assignment to delete. :param scope: The scope of the policy assignment. CLI Example: .. code-block:: bash salt-call azurearm_resou...
def function[policy_assignment_delete, parameter[name, scope]]: constant[ .. versionadded:: 2019.2.0 Delete a policy assignment. :param name: The name of the policy assignment to delete. :param scope: The scope of the policy assignment. CLI Example: .. code-block:: bash sal...
keyword[def] identifier[policy_assignment_delete] ( identifier[name] , identifier[scope] ,** identifier[kwargs] ): literal[string] identifier[result] = keyword[False] identifier[polconn] = identifier[__utils__] [ literal[string] ]( literal[string] ,** identifier[kwargs] ) keyword[try] : ...
def policy_assignment_delete(name, scope, **kwargs): """ .. versionadded:: 2019.2.0 Delete a policy assignment. :param name: The name of the policy assignment to delete. :param scope: The scope of the policy assignment. CLI Example: .. code-block:: bash salt-call azurearm_resou...
def process_preprocessed(isi_preprocessor, num_processes=1, output_dir=None, cleanup=True, add_grounding=True): """Process a directory of abstracts and/or papers preprocessed using the specified IsiPreprocessor, to produce a list of extracted INDRA statements. Parameters ------...
def function[process_preprocessed, parameter[isi_preprocessor, num_processes, output_dir, cleanup, add_grounding]]: constant[Process a directory of abstracts and/or papers preprocessed using the specified IsiPreprocessor, to produce a list of extracted INDRA statements. Parameters ---------- is...
keyword[def] identifier[process_preprocessed] ( identifier[isi_preprocessor] , identifier[num_processes] = literal[int] , identifier[output_dir] = keyword[None] , identifier[cleanup] = keyword[True] , identifier[add_grounding] = keyword[True] ): literal[string] keyword[if] identifier[output_dir] k...
def process_preprocessed(isi_preprocessor, num_processes=1, output_dir=None, cleanup=True, add_grounding=True): """Process a directory of abstracts and/or papers preprocessed using the specified IsiPreprocessor, to produce a list of extracted INDRA statements. Parameters ---------- isi_preprocessor...
def note_hz_to_midi(annotation): '''Convert a pitch_hz annotation to pitch_midi''' annotation.namespace = 'note_midi' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, ...
def function[note_hz_to_midi, parameter[annotation]]: constant[Convert a pitch_hz annotation to pitch_midi] name[annotation].namespace assign[=] constant[note_midi] variable[data] assign[=] call[name[annotation].pop_data, parameter[]] for taget[name[obs]] in starred[name[data]] begin[:] ...
keyword[def] identifier[note_hz_to_midi] ( identifier[annotation] ): literal[string] identifier[annotation] . identifier[namespace] = literal[string] identifier[data] = identifier[annotation] . identifier[pop_data] () keyword[for] identifier[obs] keyword[in] identifier[data] : ide...
def note_hz_to_midi(annotation): """Convert a pitch_hz annotation to pitch_midi""" annotation.namespace = 'note_midi' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, value=12 * (np.log2(obs.value) - np.log2(440.0)) ...
def best_representative(d1, d2): """ Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Decimal('6.1')) Decimal('6.1')...
def function[best_representative, parameter[d1, d2]]: constant[ Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Dec...
keyword[def] identifier[best_representative] ( identifier[d1] , identifier[d2] ): literal[string] keyword[if] identifier[hasattr] ( identifier[d2] , literal[string] ) keyword[and] keyword[not] identifier[d2] . identifier[strip] (): keyword[return] identifier[d1] keyword[if] identifier[...
def best_representative(d1, d2): """ Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Decimal('6.1')) Decimal('6.1')...
def icosphere(script, radius=1.0, diameter=None, subdivisions=3, color=None): """create an icosphere mesh radius Radius of the sphere # subdivisions = Subdivision level; Number of the recursive subdivision of the # surface. Default is 3 (a sphere approximation composed by 1280 faces). # Admitted va...
def function[icosphere, parameter[script, radius, diameter, subdivisions, color]]: constant[create an icosphere mesh radius Radius of the sphere # subdivisions = Subdivision level; Number of the recursive subdivision of the # surface. Default is 3 (a sphere approximation composed by 1280 faces). ...
keyword[def] identifier[icosphere] ( identifier[script] , identifier[radius] = literal[int] , identifier[diameter] = keyword[None] , identifier[subdivisions] = literal[int] , identifier[color] = keyword[None] ): literal[string] keyword[if] identifier[diameter] keyword[is] keyword[not] keyword[None] : ...
def icosphere(script, radius=1.0, diameter=None, subdivisions=3, color=None): """create an icosphere mesh radius Radius of the sphere # subdivisions = Subdivision level; Number of the recursive subdivision of the # surface. Default is 3 (a sphere approximation composed by 1280 faces). # Admitted va...
def doi(self): """ https://es.wikipedia.org/wiki/Identificador_de_objeto_digital :return: a random Spanish CIF or NIE or NIF """ return random.choice([self.cif, self.nie, self.nif])()
def function[doi, parameter[self]]: constant[ https://es.wikipedia.org/wiki/Identificador_de_objeto_digital :return: a random Spanish CIF or NIE or NIF ] return[call[call[name[random].choice, parameter[list[[<ast.Attribute object at 0x7da18ede40d0>, <ast.Attribute object at 0x7da18ed...
keyword[def] identifier[doi] ( identifier[self] ): literal[string] keyword[return] identifier[random] . identifier[choice] ([ identifier[self] . identifier[cif] , identifier[self] . identifier[nie] , identifier[self] . identifier[nif] ])()
def doi(self): """ https://es.wikipedia.org/wiki/Identificador_de_objeto_digital :return: a random Spanish CIF or NIE or NIF """ return random.choice([self.cif, self.nie, self.nif])()
def autodiscover(cls, module_paths: List[str], subclass: 'Container' = None) -> None: """ Load all modules automatically and find bases and eggs. :param module_paths: List of paths that should be discovered :param subclass: Optional Container su...
def function[autodiscover, parameter[cls, module_paths, subclass]]: constant[ Load all modules automatically and find bases and eggs. :param module_paths: List of paths that should be discovered :param subclass: Optional Container subclass that should be used ] def funct...
keyword[def] identifier[autodiscover] ( identifier[cls] , identifier[module_paths] : identifier[List] [ identifier[str] ], identifier[subclass] : literal[string] = keyword[None] )-> keyword[None] : literal[string] keyword[def] identifier[find_base] ( identifier[bases] : identifier[set] , identi...
def autodiscover(cls, module_paths: List[str], subclass: 'Container'=None) -> None: """ Load all modules automatically and find bases and eggs. :param module_paths: List of paths that should be discovered :param subclass: Optional Container subclass that should be used """ def ...
def diff_json_files(left_files, right_files): ''' Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the...
def function[diff_json_files, parameter[left_files, right_files]]: constant[ Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in t...
keyword[def] identifier[diff_json_files] ( identifier[left_files] , identifier[right_files] ): literal[string] identifier[left_data] =[ identifier[fileio] . identifier[read_json_basis] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[left_files] ] identifier[right_data] =[ ident...
def diff_json_files(left_files, right_files): """ Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in `left_files`. Each resulting dictionary will contain only the elements/shells that exist in that entry and not in any of the...
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) Loggi...
def function[make_logging_undefined, parameter[logger, base]]: constant[Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__...
keyword[def] identifier[make_logging_undefined] ( identifier[logger] = keyword[None] , identifier[base] = keyword[None] ): literal[string] keyword[if] identifier[logger] keyword[is] keyword[None] : keyword[import] identifier[logging] identifier[logger] = identifier[logging] . identif...
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) Loggi...
def import_app_sitetree_module(app): """Imports sitetree module from a given app. :param str|unicode app: Application name :return: module|None """ module_name = settings.APP_MODULE_NAME module = import_module(app) try: sub_module = import_module('%s.%s' % (app, module_name)) ...
def function[import_app_sitetree_module, parameter[app]]: constant[Imports sitetree module from a given app. :param str|unicode app: Application name :return: module|None ] variable[module_name] assign[=] name[settings].APP_MODULE_NAME variable[module] assign[=] call[name[import_mod...
keyword[def] identifier[import_app_sitetree_module] ( identifier[app] ): literal[string] identifier[module_name] = identifier[settings] . identifier[APP_MODULE_NAME] identifier[module] = identifier[import_module] ( identifier[app] ) keyword[try] : identifier[sub_module] = identifier[imp...
def import_app_sitetree_module(app): """Imports sitetree module from a given app. :param str|unicode app: Application name :return: module|None """ module_name = settings.APP_MODULE_NAME module = import_module(app) try: sub_module = import_module('%s.%s' % (app, module_name)) ...
def uncollapse(self): """Uncollapse a private message or modmail.""" url = self.reddit_session.config['uncollapse_message'] self.reddit_session.request_json(url, data={'id': self.name})
def function[uncollapse, parameter[self]]: constant[Uncollapse a private message or modmail.] variable[url] assign[=] call[name[self].reddit_session.config][constant[uncollapse_message]] call[name[self].reddit_session.request_json, parameter[name[url]]]
keyword[def] identifier[uncollapse] ( identifier[self] ): literal[string] identifier[url] = identifier[self] . identifier[reddit_session] . identifier[config] [ literal[string] ] identifier[self] . identifier[reddit_session] . identifier[request_json] ( identifier[url] , identifier[data] =...
def uncollapse(self): """Uncollapse a private message or modmail.""" url = self.reddit_session.config['uncollapse_message'] self.reddit_session.request_json(url, data={'id': self.name})
def affine_transform_keypoints(coords_list, transform_matrix): """Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left a...
def function[affine_transform_keypoints, parameter[coords_list, transform_matrix]]: constant[Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. ...
keyword[def] identifier[affine_transform_keypoints] ( identifier[coords_list] , identifier[transform_matrix] ): literal[string] identifier[coords_result_list] =[] keyword[for] identifier[coords] keyword[in] identifier[coords_list] : identifier[coords] = identifier[np] . identifier[asarray]...
def affine_transform_keypoints(coords_list, transform_matrix): """Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left a...
def error(self, interface_id, errorcode, msg): """When some error occurs the CCU / Homegear will send it's error message here""" LOG.debug("RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % ( interface_id, int(errorcode), str(msg))) if self.systemcallback: ...
def function[error, parameter[self, interface_id, errorcode, msg]]: constant[When some error occurs the CCU / Homegear will send it's error message here] call[name[LOG].debug, parameter[binary_operation[constant[RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s] <ast.Mod object at 0x7d...
keyword[def] identifier[error] ( identifier[self] , identifier[interface_id] , identifier[errorcode] , identifier[msg] ): literal[string] identifier[LOG] . identifier[debug] ( literal[string] %( identifier[interface_id] , identifier[int] ( identifier[errorcode] ), identifier[str] ( identif...
def error(self, interface_id, errorcode, msg): """When some error occurs the CCU / Homegear will send it's error message here""" LOG.debug('RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s' % (interface_id, int(errorcode), str(msg))) if self.systemcallback: self.systemcallback('er...
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft...
def function[cc, parameter[self, chan, ctrl, val]]: constant[Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) ...
keyword[def] identifier[cc] ( identifier[self] , identifier[chan] , identifier[ctrl] , identifier[val] ): literal[string] keyword[return] identifier[fluid_synth_cc] ( identifier[self] . identifier[synth] , identifier[chan] , identifier[ctrl] , identifier[val] )
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft to ...
def _default_commands(self): """ Build the list of CLI commands by finding subclasses of the Command class Also allows commands to be installed using the "enaml_native_command" entry point. This entry point should return a Command subclass """ commands = [c() for c in...
def function[_default_commands, parameter[self]]: constant[ Build the list of CLI commands by finding subclasses of the Command class Also allows commands to be installed using the "enaml_native_command" entry point. This entry point should return a Command subclass ] ...
keyword[def] identifier[_default_commands] ( identifier[self] ): literal[string] identifier[commands] =[ identifier[c] () keyword[for] identifier[c] keyword[in] identifier[find_commands] ( identifier[Command] )] keyword[for] identifier[ep] keyword[in] identifier[pkg_resourc...
def _default_commands(self): """ Build the list of CLI commands by finding subclasses of the Command class Also allows commands to be installed using the "enaml_native_command" entry point. This entry point should return a Command subclass """ commands = [c() for c in find_co...
def get_neighbors(self, index): """! @brief Finds neighbors of the oscillator with specified index. @param[in] index (uint): index of oscillator for which neighbors should be found in the network. @return (list) Indexes of neighbors of the specified oscillator. ...
def function[get_neighbors, parameter[self, index]]: constant[! @brief Finds neighbors of the oscillator with specified index. @param[in] index (uint): index of oscillator for which neighbors should be found in the network. @return (list) Indexes of neighbors of the spe...
keyword[def] identifier[get_neighbors] ( identifier[self] , identifier[index] ): literal[string] keyword[if] (( identifier[self] . identifier[_ccore_network_pointer] keyword[is] keyword[not] keyword[None] ) keyword[and] ( identifier[self] . identifier[_osc_conn] keyword[is] keyword[None] )...
def get_neighbors(self, index): """! @brief Finds neighbors of the oscillator with specified index. @param[in] index (uint): index of oscillator for which neighbors should be found in the network. @return (list) Indexes of neighbors of the specified oscillator. ...
def get_currency(self, code): """ Returns an iterable of currency elements matching the code: <CtryNm>UNITED STATES MINOR OUTLYING ISLANDS (THE)</CtryNm> <CcyNm>US Dollar</CcyNm> <Ccy>USD</Ccy> <CcyNbr>840</CcyNbr> <CcyMnrUnts>2</CcyMnrUnts> NOTE: the curr...
def function[get_currency, parameter[self, code]]: constant[ Returns an iterable of currency elements matching the code: <CtryNm>UNITED STATES MINOR OUTLYING ISLANDS (THE)</CtryNm> <CcyNm>US Dollar</CcyNm> <Ccy>USD</Ccy> <CcyNbr>840</CcyNbr> <CcyMnrUnts>2</CcyMnrU...
keyword[def] identifier[get_currency] ( identifier[self] , identifier[code] ): literal[string] identifier[missing] = keyword[True] keyword[for] identifier[currency] keyword[in] identifier[self] . identifier[currencies] [ literal[int] ]: keyword[try] : keyw...
def get_currency(self, code): """ Returns an iterable of currency elements matching the code: <CtryNm>UNITED STATES MINOR OUTLYING ISLANDS (THE)</CtryNm> <CcyNm>US Dollar</CcyNm> <Ccy>USD</Ccy> <CcyNbr>840</CcyNbr> <CcyMnrUnts>2</CcyMnrUnts> NOTE: the currency...
def clean_draft_pages_from_space(confluence, space_key, count, date_now): """ Remove draft pages from space using datetime.now :param confluence: :param space_key: :param count: :param date_now: :return: int counter """ pages = confluence.get_all_draft_pages_from_space(space=space_ke...
def function[clean_draft_pages_from_space, parameter[confluence, space_key, count, date_now]]: constant[ Remove draft pages from space using datetime.now :param confluence: :param space_key: :param count: :param date_now: :return: int counter ] variable[pages] assign[=] call[...
keyword[def] identifier[clean_draft_pages_from_space] ( identifier[confluence] , identifier[space_key] , identifier[count] , identifier[date_now] ): literal[string] identifier[pages] = identifier[confluence] . identifier[get_all_draft_pages_from_space] ( identifier[space] = identifier[space_key] , identifi...
def clean_draft_pages_from_space(confluence, space_key, count, date_now): """ Remove draft pages from space using datetime.now :param confluence: :param space_key: :param count: :param date_now: :return: int counter """ pages = confluence.get_all_draft_pages_from_space(space=space_ke...
def unsure_pyname(pyname, unbound=True): """Return `True` if we don't know what this name references""" if pyname is None: return True if unbound and not isinstance(pyname, pynames.UnboundName): return False if pyname.get_object() == pyobjects.get_unknown(): return True
def function[unsure_pyname, parameter[pyname, unbound]]: constant[Return `True` if we don't know what this name references] if compare[name[pyname] is constant[None]] begin[:] return[constant[True]] if <ast.BoolOp object at 0x7da1b065d330> begin[:] return[constant[False]] ...
keyword[def] identifier[unsure_pyname] ( identifier[pyname] , identifier[unbound] = keyword[True] ): literal[string] keyword[if] identifier[pyname] keyword[is] keyword[None] : keyword[return] keyword[True] keyword[if] identifier[unbound] keyword[and] keyword[not] identifier[isinstanc...
def unsure_pyname(pyname, unbound=True): """Return `True` if we don't know what this name references""" if pyname is None: return True # depends on [control=['if'], data=[]] if unbound and (not isinstance(pyname, pynames.UnboundName)): return False # depends on [control=['if'], data=[]] ...
def deflate(self, value): """ Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT """ if not isinstance(value, NeomodelPoint): ...
def function[deflate, parameter[self, value]]: constant[ Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT ] if <ast.UnaryOp obje...
keyword[def] identifier[deflate] ( identifier[self] , identifier[value] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[NeomodelPoint] ): keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[type...
def deflate(self, value): """ Handles the marshalling from NeomodelPoint to Neo4J POINT :param value: The point that was assigned as value to a property in the model :type value: NeomodelPoint :return: Neo4J POINT """ if not isinstance(value, NeomodelPoint): rais...
def evaluate(self, system_id=1, rouge_args=None): """ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID...
def function[evaluate, parameter[self, system_id, rouge_args]]: constant[ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id:...
keyword[def] identifier[evaluate] ( identifier[self] , identifier[system_id] = literal[int] , identifier[rouge_args] = keyword[None] ): literal[string] identifier[self] . identifier[write_config] ( identifier[system_id] = identifier[system_id] ) identifier[options] = identifier[self] . ide...
def evaluate(self, system_id=1, rouge_args=None): """ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID whi...
def debug_process(pid): """Interrupt a running process and debug it.""" os.kill(pid, signal.SIGUSR1) # Signal process. pipe = NamedPipe(pipename(pid), 1) try: while pipe.is_open(): txt=raw_input(pipe.get()) + '\n' pipe.put(txt) except EOFError: pass # Exit. ...
def function[debug_process, parameter[pid]]: constant[Interrupt a running process and debug it.] call[name[os].kill, parameter[name[pid], name[signal].SIGUSR1]] variable[pipe] assign[=] call[name[NamedPipe], parameter[call[name[pipename], parameter[name[pid]]], constant[1]]] <ast.Try object ...
keyword[def] identifier[debug_process] ( identifier[pid] ): literal[string] identifier[os] . identifier[kill] ( identifier[pid] , identifier[signal] . identifier[SIGUSR1] ) identifier[pipe] = identifier[NamedPipe] ( identifier[pipename] ( identifier[pid] ), literal[int] ) keyword[try] : ...
def debug_process(pid): """Interrupt a running process and debug it.""" os.kill(pid, signal.SIGUSR1) # Signal process. pipe = NamedPipe(pipename(pid), 1) try: while pipe.is_open(): txt = raw_input(pipe.get()) + '\n' pipe.put(txt) # depends on [control=['while'], data=[]...
def hdd_to_pmf(hypo_depth_dist, use_default=False): """ Returns the hypocentral depth distribtuion as an instance of the :class: openquake.hazardlib.pmf. """ if isinstance(hypo_depth_dist, PMF): # Is already instance of PMF return hypo_depth_dist else: if use_default: ...
def function[hdd_to_pmf, parameter[hypo_depth_dist, use_default]]: constant[ Returns the hypocentral depth distribtuion as an instance of the :class: openquake.hazardlib.pmf. ] if call[name[isinstance], parameter[name[hypo_depth_dist], name[PMF]]] begin[:] return[name[hypo_depth_dis...
keyword[def] identifier[hdd_to_pmf] ( identifier[hypo_depth_dist] , identifier[use_default] = keyword[False] ): literal[string] keyword[if] identifier[isinstance] ( identifier[hypo_depth_dist] , identifier[PMF] ): keyword[return] identifier[hypo_depth_dist] keyword[else] : ke...
def hdd_to_pmf(hypo_depth_dist, use_default=False): """ Returns the hypocentral depth distribtuion as an instance of the :class: openquake.hazardlib.pmf. """ if isinstance(hypo_depth_dist, PMF): # Is already instance of PMF return hypo_depth_dist # depends on [control=['if'], data=...
def sort_file_tabs_alphabetically(self): """Sort open tabs alphabetically.""" while self.sorted() is False: for i in range(0, self.tabs.tabBar().count()): if(self.tabs.tabBar().tabText(i) > self.tabs.tabBar().tabText(i + 1)): ...
def function[sort_file_tabs_alphabetically, parameter[self]]: constant[Sort open tabs alphabetically.] while compare[call[name[self].sorted, parameter[]] is constant[False]] begin[:] for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[call[name[self].tabs.tabBar, ...
keyword[def] identifier[sort_file_tabs_alphabetically] ( identifier[self] ): literal[string] keyword[while] identifier[self] . identifier[sorted] () keyword[is] keyword[False] : keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[self] . identif...
def sort_file_tabs_alphabetically(self): """Sort open tabs alphabetically.""" while self.sorted() is False: for i in range(0, self.tabs.tabBar().count()): if self.tabs.tabBar().tabText(i) > self.tabs.tabBar().tabText(i + 1): self.tabs.tabBar().moveTab(i, i + 1) # depends on ...
def _initialize_context(self, trace_header): """ Create a facade segment based on environment variables set by AWS Lambda and initialize storage for subsegments. """ sampled = None if not global_sdk_config.sdk_enabled(): # Force subsequent subsegments to be di...
def function[_initialize_context, parameter[self, trace_header]]: constant[ Create a facade segment based on environment variables set by AWS Lambda and initialize storage for subsegments. ] variable[sampled] assign[=] constant[None] if <ast.UnaryOp object at 0x7da2049600...
keyword[def] identifier[_initialize_context] ( identifier[self] , identifier[trace_header] ): literal[string] identifier[sampled] = keyword[None] keyword[if] keyword[not] identifier[global_sdk_config] . identifier[sdk_enabled] (): identifier[sampled] = keyword[Fals...
def _initialize_context(self, trace_header): """ Create a facade segment based on environment variables set by AWS Lambda and initialize storage for subsegments. """ sampled = None if not global_sdk_config.sdk_enabled(): # Force subsequent subsegments to be disabled and turne...
def traverse_nodes(self, node_set, depth=0): """BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: type: String containing...
def function[traverse_nodes, parameter[self, node_set, depth]]: constant[BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: ...
keyword[def] identifier[traverse_nodes] ( identifier[self] , identifier[node_set] , identifier[depth] = literal[int] ): literal[string] identifier[tab] = literal[string] identifier[result] = identifier[list] () keyword[for] identifier[n] keyword[in] identifier[node_set] : ...
def traverse_nodes(self, node_set, depth=0): """BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: type: String containing tab...
def calcfluxscale(d, imstd_med, flagfrac_med): """ Given state dict and noise properties, estimate flux scale at the VLA imstd and flagfrac are expected to be median (typical) values from sample in merged noise pkl. """ # useful functions and VLA parameters sensitivity = lambda sefd, dt, bw, eta,...
def function[calcfluxscale, parameter[d, imstd_med, flagfrac_med]]: constant[ Given state dict and noise properties, estimate flux scale at the VLA imstd and flagfrac are expected to be median (typical) values from sample in merged noise pkl. ] variable[sensitivity] assign[=] <ast.Lambda objec...
keyword[def] identifier[calcfluxscale] ( identifier[d] , identifier[imstd_med] , identifier[flagfrac_med] ): literal[string] identifier[sensitivity] = keyword[lambda] identifier[sefd] , identifier[dt] , identifier[bw] , identifier[eta] , identifier[nbl] , identifier[npol] : identifier[sefd] /( ident...
def calcfluxscale(d, imstd_med, flagfrac_med): """ Given state dict and noise properties, estimate flux scale at the VLA imstd and flagfrac are expected to be median (typical) values from sample in merged noise pkl. """ # useful functions and VLA parameters sensitivity = lambda sefd, dt, bw, eta, ...
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow): ''' Finds interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-perio...
def function[getPointsForInterpolation, parameter[self, EndOfPrdvP, aNrmNow]]: constant[ Finds interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array ...
keyword[def] identifier[getPointsForInterpolation] ( identifier[self] , identifier[EndOfPrdvP] , identifier[aNrmNow] ): literal[string] identifier[cNrmNow] = identifier[self] . identifier[uPinv] ( identifier[EndOfPrdvP] ) identifier[mNrmNow] = identifier[cNrmNow] + identifier[aNrmNow] ...
def getPointsForInterpolation(self, EndOfPrdvP, aNrmNow): """ Finds interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-period ...
def on_trial_result(self, trial_runner, trial, result): """If bracket is finished, all trials will be stopped. If a given trial finishes and bracket iteration is not done, the trial will be paused and resources will be given up. This scheduler will not start trials but will stop trials...
def function[on_trial_result, parameter[self, trial_runner, trial, result]]: constant[If bracket is finished, all trials will be stopped. If a given trial finishes and bracket iteration is not done, the trial will be paused and resources will be given up. This scheduler will not start ...
keyword[def] identifier[on_trial_result] ( identifier[self] , identifier[trial_runner] , identifier[trial] , identifier[result] ): literal[string] identifier[bracket] , identifier[_] = identifier[self] . identifier[_trial_info] [ identifier[trial] ] identifier[bracket] . identifier[update...
def on_trial_result(self, trial_runner, trial, result): """If bracket is finished, all trials will be stopped. If a given trial finishes and bracket iteration is not done, the trial will be paused and resources will be given up. This scheduler will not start trials but will stop trials. ...
def multi_buffering(layer, radii, callback=None): """Buffer a vector layer using many buffers (for volcanoes or rivers). This processing algorithm will keep the original attribute table and will add a new one for the hazard class name according to safe.definitions.fields.hazard_value_field. radii ...
def function[multi_buffering, parameter[layer, radii, callback]]: constant[Buffer a vector layer using many buffers (for volcanoes or rivers). This processing algorithm will keep the original attribute table and will add a new one for the hazard class name according to safe.definitions.fields.hazar...
keyword[def] identifier[multi_buffering] ( identifier[layer] , identifier[radii] , identifier[callback] = keyword[None] ): literal[string] identifier[output_layer_name] = identifier[buffer_steps] [ literal[string] ] identifier[processing_step] = identifier[buffer_steps] [ literal[string] ] ...
def multi_buffering(layer, radii, callback=None): """Buffer a vector layer using many buffers (for volcanoes or rivers). This processing algorithm will keep the original attribute table and will add a new one for the hazard class name according to safe.definitions.fields.hazard_value_field. radii ...
def main(argv=sys.argv[1:]): """Parse argument and start main program.""" args = docopt(__doc__, argv=argv, version=pkg_resources.require('buienradar')[0].version) level = logging.ERROR if args['-v']: level = logging.INFO if args['-v'] == 2: level = logging.DEBUG ...
def function[main, parameter[argv]]: constant[Parse argument and start main program.] variable[args] assign[=] call[name[docopt], parameter[name[__doc__]]] variable[level] assign[=] name[logging].ERROR if call[name[args]][constant[-v]] begin[:] variable[level] assign[=] n...
keyword[def] identifier[main] ( identifier[argv] = identifier[sys] . identifier[argv] [ literal[int] :]): literal[string] identifier[args] = identifier[docopt] ( identifier[__doc__] , identifier[argv] = identifier[argv] , identifier[version] = identifier[pkg_resources] . identifier[require] ( literal[...
def main(argv=sys.argv[1:]): """Parse argument and start main program.""" args = docopt(__doc__, argv=argv, version=pkg_resources.require('buienradar')[0].version) level = logging.ERROR if args['-v']: level = logging.INFO # depends on [control=['if'], data=[]] if args['-v'] == 2: le...
def exit_hook(callable, once=True): r"""A decorator that makes the decorated function to run while ec exits. Args: callable (callable): The target callable. once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True. Note: Hooks are processedd in a LIFO order. "...
def function[exit_hook, parameter[callable, once]]: constant[A decorator that makes the decorated function to run while ec exits. Args: callable (callable): The target callable. once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True. Note: Hooks are proc...
keyword[def] identifier[exit_hook] ( identifier[callable] , identifier[once] = keyword[True] ): literal[string] keyword[if] identifier[once] keyword[and] identifier[callable] keyword[in] identifier[ExitHooks] : keyword[return] identifier[ExitHooks] . identifier[append] ( identifier[callable] )
def exit_hook(callable, once=True): """A decorator that makes the decorated function to run while ec exits. Args: callable (callable): The target callable. once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True. Note: Hooks are processedd in a LIFO order. ...
def shift(self, count=1): """ Shift the view a specified number of times. :param count: The count of times to shift the view. """ if self: self._index = (self._index + count) % len(self) else: self._index = 0
def function[shift, parameter[self, count]]: constant[ Shift the view a specified number of times. :param count: The count of times to shift the view. ] if name[self] begin[:] name[self]._index assign[=] binary_operation[binary_operation[name[self]._index + name[...
keyword[def] identifier[shift] ( identifier[self] , identifier[count] = literal[int] ): literal[string] keyword[if] identifier[self] : identifier[self] . identifier[_index] =( identifier[self] . identifier[_index] + identifier[count] )% identifier[len] ( identifier[self] ) ke...
def shift(self, count=1): """ Shift the view a specified number of times. :param count: The count of times to shift the view. """ if self: self._index = (self._index + count) % len(self) # depends on [control=['if'], data=[]] else: self._index = 0
def listdir(self, name, **kwargs): """ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters -----...
def function[listdir, parameter[self, name]]: constant[ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Paramet...
keyword[def] identifier[listdir] ( identifier[self] , identifier[name] ,** identifier[kwargs] ): literal[string] keyword[assert] identifier[self] . identifier[_is_s3] ( identifier[name] ), literal[string] keyword[if] keyword[not] identifier[name] . identifier[endswith] ( literal[strin...
def listdir(self, name, **kwargs): """ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters ---------...
def elem_match(self, value): ''' This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField the value can b...
def function[elem_match, parameter[self, value]]: constant[ This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField ...
keyword[def] identifier[elem_match] ( identifier[self] , identifier[value] ): literal[string] identifier[self] . identifier[__is_elem_match] = keyword[True] keyword[if] keyword[not] identifier[self] . identifier[__type] . identifier[is_sequence_field] : keyword[raise] iden...
def elem_match(self, value): """ This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField the value can be ei...
def calculate_colors(self, values): """Return a list (or list of lists) of colors based on input values.""" # set domain if it is not set _flattenedList = list(flatten(values)) if not self.is_domain_set: self.set_domain(_flattenedList) _flattenedColors = range(len(_f...
def function[calculate_colors, parameter[self, values]]: constant[Return a list (or list of lists) of colors based on input values.] variable[_flattenedList] assign[=] call[name[list], parameter[call[name[flatten], parameter[name[values]]]]] if <ast.UnaryOp object at 0x7da1b1224d60> begin[:] ...
keyword[def] identifier[calculate_colors] ( identifier[self] , identifier[values] ): literal[string] identifier[_flattenedList] = identifier[list] ( identifier[flatten] ( identifier[values] )) keyword[if] keyword[not] identifier[self] . identifier[is_domain_set] : i...
def calculate_colors(self, values): """Return a list (or list of lists) of colors based on input values.""" # set domain if it is not set _flattenedList = list(flatten(values)) if not self.is_domain_set: self.set_domain(_flattenedList) # depends on [control=['if'], data=[]] _flattenedColors...
def _no_mute_on_stop_playback(self): """ make sure vlc does not stop muted """ if self.ctrl_c_pressed: return if self.isPlaying(): if self.actual_volume == -1: self._get_volume() while self.actual_volume == -1: pass ...
def function[_no_mute_on_stop_playback, parameter[self]]: constant[ make sure vlc does not stop muted ] if name[self].ctrl_c_pressed begin[:] return[None] if call[name[self].isPlaying, parameter[]] begin[:] if compare[name[self].actual_volume equal[==] <ast.UnaryOp object...
keyword[def] identifier[_no_mute_on_stop_playback] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[ctrl_c_pressed] : keyword[return] keyword[if] identifier[self] . identifier[isPlaying] (): keyword[if] identifier[self] . identif...
def _no_mute_on_stop_playback(self): """ make sure vlc does not stop muted """ if self.ctrl_c_pressed: return # depends on [control=['if'], data=[]] if self.isPlaying(): if self.actual_volume == -1: self._get_volume() while self.actual_volume == -1: p...
def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELE...
def function[db_list, parameter[user, host, port, maintenance_db, password, runas]]: constant[ Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ] variable[ret] assign[=] dictionary[[], []] ...
keyword[def] identifier[db_list] ( identifier[user] = keyword[None] , identifier[host] = keyword[None] , identifier[port] = keyword[None] , identifier[maintenance_db] = keyword[None] , identifier[password] = keyword[None] , identifier[runas] = keyword[None] ): literal[string] identifier[ret] ={} id...
def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): """ Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list """ ret = {} query = 'SELECT datname as "Name", pg...
def _request(self, url, **kwargs): '''Inner :func:`requests.request` wrapper. :param url: Endpoint url :param \*\*kwargs: Keyword arguments to pass to :func:`requests.request`. ''' if self.method is None: raise NotImplementedError('method must be defined ...
def function[_request, parameter[self, url]]: constant[Inner :func:`requests.request` wrapper. :param url: Endpoint url :param \*\*kwargs: Keyword arguments to pass to :func:`requests.request`. ] if compare[name[self].method is constant[None]] begin[:] <ast.R...
keyword[def] identifier[_request] ( identifier[self] , identifier[url] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[self] . identifier[method] keyword[is] keyword[None] : keyword[raise] identifier[NotImplementedError] ( literal[string] ) identifier[resp...
def _request(self, url, **kwargs): """Inner :func:`requests.request` wrapper. :param url: Endpoint url :param \\*\\*kwargs: Keyword arguments to pass to :func:`requests.request`. """ if self.method is None: raise NotImplementedError('method must be defined on a subcl...
def _update_disks(disks_old_new): ''' Changes the disk size and returns the config spec objects in a list. The controller property cannot be updated, because controller address identifies the disk by the unit and bus number properties. disks_diffs List of old and new disk properties, the pr...
def function[_update_disks, parameter[disks_old_new]]: constant[ Changes the disk size and returns the config spec objects in a list. The controller property cannot be updated, because controller address identifies the disk by the unit and bus number properties. disks_diffs List of old ...
keyword[def] identifier[_update_disks] ( identifier[disks_old_new] ): literal[string] identifier[disk_changes] =[] keyword[if] identifier[disks_old_new] : identifier[devs] =[ identifier[disk] [ literal[string] ][ literal[string] ] keyword[for] identifier[disk] keyword[in] identifier[disks...
def _update_disks(disks_old_new): """ Changes the disk size and returns the config spec objects in a list. The controller property cannot be updated, because controller address identifies the disk by the unit and bus number properties. disks_diffs List of old and new disk properties, the pr...
def print_computation_log(self, aggregate = False): """ Print the computation log of a simulation. If ``aggregate`` is ``False`` (default), print the value of each computed vector. If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each comp...
def function[print_computation_log, parameter[self, aggregate]]: constant[ Print the computation log of a simulation. If ``aggregate`` is ``False`` (default), print the value of each computed vector. If ``aggregate`` is ``True``, only print the minimum, maximum, and average...
keyword[def] identifier[print_computation_log] ( identifier[self] , identifier[aggregate] = keyword[False] ): literal[string] keyword[for] identifier[line] keyword[in] identifier[self] . identifier[computation_log] ( identifier[aggregate] ): identifier[print] ( identifier[line] )
def print_computation_log(self, aggregate=False): """ Print the computation log of a simulation. If ``aggregate`` is ``False`` (default), print the value of each computed vector. If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed v...
def __update_membership(self): """! @brief Update membership for each point in line with current cluster centers. """ data_difference = numpy.zeros((len(self.__centers), len(self.__data))) for i in range(len(self.__centers)): data_difference[i] = numpy.sum(n...
def function[__update_membership, parameter[self]]: constant[! @brief Update membership for each point in line with current cluster centers. ] variable[data_difference] assign[=] call[name[numpy].zeros, parameter[tuple[[<ast.Call object at 0x7da1b01fcac0>, <ast.Call object at 0x7da1b01f...
keyword[def] identifier[__update_membership] ( identifier[self] ): literal[string] identifier[data_difference] = identifier[numpy] . identifier[zeros] (( identifier[len] ( identifier[self] . identifier[__centers] ), identifier[len] ( identifier[self] . identifier[__data] ))) keyword[f...
def __update_membership(self): """! @brief Update membership for each point in line with current cluster centers. """ data_difference = numpy.zeros((len(self.__centers), len(self.__data))) for i in range(len(self.__centers)): data_difference[i] = numpy.sum(numpy.square(self.__data -...
def apply(self, doc): """Generate MentionNgrams from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): ...
def function[apply, parameter[self, doc]]: constant[Generate MentionNgrams from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. ] if <ast.UnaryOp o...
keyword[def] identifier[apply] ( identifier[self] , identifier[doc] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[doc] , identifier[Document] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[for...
def apply(self, doc): """Generate MentionNgrams from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise Ty...
def upload_url(self): """ This method generates URLs which allow overwriting a file's content with new content. The output is suitable for use in the ``send_data()`` method below. Input: * None Output: * A URL (string) Example:: fil...
def function[upload_url, parameter[self]]: constant[ This method generates URLs which allow overwriting a file's content with new content. The output is suitable for use in the ``send_data()`` method below. Input: * None Output: * A URL (string) ...
keyword[def] identifier[upload_url] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[put_upload_url] : keyword[return] identifier[self] . identifier[put_upload_url] keyword[else] : identifier[response] = identifier[GettRequest] ()...
def upload_url(self): """ This method generates URLs which allow overwriting a file's content with new content. The output is suitable for use in the ``send_data()`` method below. Input: * None Output: * A URL (string) Example:: file = ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] if hasattr(self, 'pagination') and self.pagination is not None: ...
def function[_to_dict, parameter[self]]: constant[Return a json dictionary representing this model.] variable[_dict] assign[=] dictionary[[], []] if <ast.BoolOp object at 0x7da204962830> begin[:] call[name[_dict]][constant[examples]] assign[=] <ast.ListComp object at 0x7da2049605...
keyword[def] identifier[_to_dict] ( identifier[self] ): literal[string] identifier[_dict] ={} keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[examples] keyword[is] keyword[not] keyword[None] : identifier[_d...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] # depends on [control=['if'], data=[]] if hasattr(self, 'pagination') and self.pagination ...
def page_templates(mapping): """Like the *page_template* decorator but manage multiple paginations. You can map multiple templates to *querystring_keys* using the *mapping* dict, e.g.:: @page_templates({ 'page_contents1.html': None, 'page_contents2.html': 'go_to_page', ...
def function[page_templates, parameter[mapping]]: constant[Like the *page_template* decorator but manage multiple paginations. You can map multiple templates to *querystring_keys* using the *mapping* dict, e.g.:: @page_templates({ 'page_contents1.html': None, 'page_cont...
keyword[def] identifier[page_templates] ( identifier[mapping] ): literal[string] keyword[def] identifier[decorator] ( identifier[view] ): @ identifier[wraps] ( identifier[view] ) keyword[def] identifier[decorated] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] ): ...
def page_templates(mapping): """Like the *page_template* decorator but manage multiple paginations. You can map multiple templates to *querystring_keys* using the *mapping* dict, e.g.:: @page_templates({ 'page_contents1.html': None, 'page_contents2.html': 'go_to_page', ...
def _expand_path(path): """Expand both environment variables and user home in the given path.""" path = os.path.expandvars(path) path = os.path.expanduser(path) return path
def function[_expand_path, parameter[path]]: constant[Expand both environment variables and user home in the given path.] variable[path] assign[=] call[name[os].path.expandvars, parameter[name[path]]] variable[path] assign[=] call[name[os].path.expanduser, parameter[name[path]]] return[name[...
keyword[def] identifier[_expand_path] ( identifier[path] ): literal[string] identifier[path] = identifier[os] . identifier[path] . identifier[expandvars] ( identifier[path] ) identifier[path] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[path] ) keyword[return] identi...
def _expand_path(path): """Expand both environment variables and user home in the given path.""" path = os.path.expandvars(path) path = os.path.expanduser(path) return path
def compareBIMfiles(beforeFileName, afterFileName, outputFileName): """Compare two BIM files for differences. :param beforeFileName: the name of the file before modification. :param afterFileName: the name of the file after modification. :param outputFileName: the name of the output file (containing th...
def function[compareBIMfiles, parameter[beforeFileName, afterFileName, outputFileName]]: constant[Compare two BIM files for differences. :param beforeFileName: the name of the file before modification. :param afterFileName: the name of the file after modification. :param outputFileName: the name of...
keyword[def] identifier[compareBIMfiles] ( identifier[beforeFileName] , identifier[afterFileName] , identifier[outputFileName] ): literal[string] identifier[options] = identifier[Dummy] () identifier[options] . identifier[before] = identifier[beforeFileName] identifier[options] . identifier...
def compareBIMfiles(beforeFileName, afterFileName, outputFileName): """Compare two BIM files for differences. :param beforeFileName: the name of the file before modification. :param afterFileName: the name of the file after modification. :param outputFileName: the name of the output file (containing th...
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
def function[_to_enos_roles, parameter[roles]]: constant[Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` ] def function[to_host, parameter[h]]: variable[extra] assign[=]...
keyword[def] identifier[_to_enos_roles] ( identifier[roles] ): literal[string] keyword[def] identifier[to_host] ( identifier[h] ): identifier[extra] ={} keyword[for] identifier[nic] , identifier[roles] keyword[in] identifier[h] [ literal[string] ]: keyw...
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
def _deprecated_kwargs(kwargs, arg_newarg): """ arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. """ warn_for = [] for (arg, new_kw) in arg_newarg: if ...
def function[_deprecated_kwargs, parameter[kwargs, arg_newarg]]: constant[ arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. ] variable[warn_for] assign[=] ...
keyword[def] identifier[_deprecated_kwargs] ( identifier[kwargs] , identifier[arg_newarg] ): literal[string] identifier[warn_for] =[] keyword[for] ( identifier[arg] , identifier[new_kw] ) keyword[in] identifier[arg_newarg] : keyword[if] identifier[arg] keyword[in] identifier[kwargs] . ide...
def _deprecated_kwargs(kwargs, arg_newarg): """ arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. """ warn_for = [] for (arg, new_kw) in arg_newarg: if ...
def op_or(self, *elements): """Update the ``Expression`` by joining the specified additional ``elements`` using an "OR" ``Operator`` Args: *elements (BaseExpression): The ``Expression`` and/or ``Constraint`` elements which the "OR" ``Operator`` applies ...
def function[op_or, parameter[self]]: constant[Update the ``Expression`` by joining the specified additional ``elements`` using an "OR" ``Operator`` Args: *elements (BaseExpression): The ``Expression`` and/or ``Constraint`` elements which the "OR" ``Operator`` applie...
keyword[def] identifier[op_or] ( identifier[self] ,* identifier[elements] ): literal[string] identifier[expression] = identifier[self] . identifier[add_operator] ( identifier[Operator] ( literal[string] )) keyword[for] identifier[element] keyword[in] identifier[elements] : ...
def op_or(self, *elements): """Update the ``Expression`` by joining the specified additional ``elements`` using an "OR" ``Operator`` Args: *elements (BaseExpression): The ``Expression`` and/or ``Constraint`` elements which the "OR" ``Operator`` applies to...
def mark_job_as_canceling(self, job_id): """ Mark the job as requested for canceling. Does not actually try to cancel a running job. :param job_id: the job to be marked as canceling. :return: the job object """ job, _ = self._update_job_state(job_id, State.CANCELING) ...
def function[mark_job_as_canceling, parameter[self, job_id]]: constant[ Mark the job as requested for canceling. Does not actually try to cancel a running job. :param job_id: the job to be marked as canceling. :return: the job object ] <ast.Tuple object at 0x7da1b05e0d60...
keyword[def] identifier[mark_job_as_canceling] ( identifier[self] , identifier[job_id] ): literal[string] identifier[job] , identifier[_] = identifier[self] . identifier[_update_job_state] ( identifier[job_id] , identifier[State] . identifier[CANCELING] ) keyword[return] identifier[job]
def mark_job_as_canceling(self, job_id): """ Mark the job as requested for canceling. Does not actually try to cancel a running job. :param job_id: the job to be marked as canceling. :return: the job object """ (job, _) = self._update_job_state(job_id, State.CANCELING) retur...
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope("xception"): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) else: # Small image, conv cur = common_layers.co...
def function[xception_internal, parameter[inputs, hparams]]: constant[Xception body.] with call[name[tf].variable_scope, parameter[constant[xception]]] begin[:] variable[cur] assign[=] name[inputs] if compare[call[call[call[name[cur].get_shape, parameter[]].as_list, param...
keyword[def] identifier[xception_internal] ( identifier[inputs] , identifier[hparams] ): literal[string] keyword[with] identifier[tf] . identifier[variable_scope] ( literal[string] ): identifier[cur] = identifier[inputs] keyword[if] identifier[cur] . identifier[get_shape] (). identifier[as_list] ...
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope('xception'): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) # depends on [control=['if'], data=[]] ...
def deregisterkbevent(self, keys, modifiers): """ Remove callback of registered event @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @return: 1 if registration was successful, 0 ...
def function[deregisterkbevent, parameter[self, keys, modifiers]]: constant[ Remove callback of registered event @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @return: 1 if regi...
keyword[def] identifier[deregisterkbevent] ( identifier[self] , identifier[keys] , identifier[modifiers] ): literal[string] identifier[event_name] = literal[string] %( identifier[keys] , identifier[modifiers] ) keyword[if] identifier[event_name] keyword[in] identifier[_pollEvents] . id...
def deregisterkbevent(self, keys, modifiers): """ Remove callback of registered event @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @return: 1 if registration was successful, 0 if n...
def tagAttributes_while(fdef_master_list,root): '''Tag each node under root with the appropriate depth. ''' depth = 0 current = root untagged_nodes = [root] while untagged_nodes: current = untagged_nodes.pop() for x in fdef_master_list: if jsName(x.path,x.name) == current...
def function[tagAttributes_while, parameter[fdef_master_list, root]]: constant[Tag each node under root with the appropriate depth. ] variable[depth] assign[=] constant[0] variable[current] assign[=] name[root] variable[untagged_nodes] assign[=] list[[<ast.Name object at 0x7da1b27e04f0>]...
keyword[def] identifier[tagAttributes_while] ( identifier[fdef_master_list] , identifier[root] ): literal[string] identifier[depth] = literal[int] identifier[current] = identifier[root] identifier[untagged_nodes] =[ identifier[root] ] keyword[while] identifier[untagged_nodes] : i...
def tagAttributes_while(fdef_master_list, root): """Tag each node under root with the appropriate depth. """ depth = 0 current = root untagged_nodes = [root] while untagged_nodes: current = untagged_nodes.pop() for x in fdef_master_list: if jsName(x.path, x.name) == curre...
def subsample_reads(self): """ Subsampling of reads to 20X coverage of rMLST genes (roughly). To be called after rMLST extraction and read trimming, in that order. """ logging.info('Subsampling {at} reads'.format(at=self.analysistype)) with progressbar(self.runmetadata) a...
def function[subsample_reads, parameter[self]]: constant[ Subsampling of reads to 20X coverage of rMLST genes (roughly). To be called after rMLST extraction and read trimming, in that order. ] call[name[logging].info, parameter[call[constant[Subsampling {at} reads].format, parame...
keyword[def] identifier[subsample_reads] ( identifier[self] ): literal[string] identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[at] = identifier[self] . identifier[analysistype] )) keyword[with] identifier[progressbar] ( identifier[self] . identif...
def subsample_reads(self): """ Subsampling of reads to 20X coverage of rMLST genes (roughly). To be called after rMLST extraction and read trimming, in that order. """ logging.info('Subsampling {at} reads'.format(at=self.analysistype)) with progressbar(self.runmetadata) as bar: ...
def normalize(self, address, **kwargs): """Make the address more compareable.""" # TODO: normalize well-known parts like "Street", "Road", etc. # TODO: consider using https://github.com/openvenues/pypostal addresses = super(AddressType, self).normalize(address, **kwargs) return a...
def function[normalize, parameter[self, address]]: constant[Make the address more compareable.] variable[addresses] assign[=] call[call[name[super], parameter[name[AddressType], name[self]]].normalize, parameter[name[address]]] return[name[addresses]]
keyword[def] identifier[normalize] ( identifier[self] , identifier[address] ,** identifier[kwargs] ): literal[string] identifier[addresses] = identifier[super] ( identifier[AddressType] , identifier[self] ). identifier[normalize] ( identifier[address] ,** identifier[kwargs] ) ...
def normalize(self, address, **kwargs): """Make the address more compareable.""" # TODO: normalize well-known parts like "Street", "Road", etc. # TODO: consider using https://github.com/openvenues/pypostal addresses = super(AddressType, self).normalize(address, **kwargs) return addresses
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
def function[ub_to_str, parameter[string]]: constant[ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) ] if <ast.UnaryOp object at 0x7da207f032e0> begin[:] if name[six].PY2 b...
keyword[def] identifier[ub_to_str] ( identifier[string] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[string] , identifier[str] ): keyword[if] identifier[six] . identifier[PY2] : keyword[return] identifier[str] ( identifier[string] ) keyw...
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) # depends on [control=['if'], data...
def merge_dfs(dfs, resample=None, do_mean=False, do_sum=False, do_min=False, do_max=False): """ dfs is a dictionary of key => dataframe This method resamples each of the dataframes if a period is provided (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases) """ if len(dfs...
def function[merge_dfs, parameter[dfs, resample, do_mean, do_sum, do_min, do_max]]: constant[ dfs is a dictionary of key => dataframe This method resamples each of the dataframes if a period is provided (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases) ] if com...
keyword[def] identifier[merge_dfs] ( identifier[dfs] , identifier[resample] = keyword[None] , identifier[do_mean] = keyword[False] , identifier[do_sum] = keyword[False] , identifier[do_min] = keyword[False] , identifier[do_max] = keyword[False] ): literal[string] keyword[if] identifier[len] ( identifier[d...
def merge_dfs(dfs, resample=None, do_mean=False, do_sum=False, do_min=False, do_max=False): """ dfs is a dictionary of key => dataframe This method resamples each of the dataframes if a period is provided (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases) """ if len(dfs...
def cmd_karma(host): """Use the Karma service https://karma.securetia.com to check an IP against various Threat Intelligence / Reputation lists. \b $ habu.karma www.google.com www.google.com -> 64.233.190.99 [ "hphosts_fsa", "hphosts_psh", "hphosts_emd" ] Note: ...
def function[cmd_karma, parameter[host]]: constant[Use the Karma service https://karma.securetia.com to check an IP against various Threat Intelligence / Reputation lists.  $ habu.karma www.google.com www.google.com -> 64.233.190.99 [ "hphosts_fsa", "hphosts_psh", "...
keyword[def] identifier[cmd_karma] ( identifier[host] ): literal[string] identifier[URL] = literal[string] keyword[try] : identifier[resolved] = identifier[socket] . identifier[gethostbyname] ( identifier[host] ) keyword[except] identifier[Exception] : identifier[logging] . ...
def cmd_karma(host): """Use the Karma service https://karma.securetia.com to check an IP against various Threat Intelligence / Reputation lists. \x08 $ habu.karma www.google.com www.google.com -> 64.233.190.99 [ "hphosts_fsa", "hphosts_psh", "hphosts_emd" ] Note...
def get_bin(self, *args, **kwargs): """Pass through to provider BinLookupSession.get_bin""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bin return Bin( self._provider_manager, self._get_provider_session('bin_lookup_session').get_...
def function[get_bin, parameter[self]]: constant[Pass through to provider BinLookupSession.get_bin] return[call[name[Bin], parameter[name[self]._provider_manager, call[call[name[self]._get_provider_session, parameter[constant[bin_lookup_session]]].get_bin, parameter[<ast.Starred object at 0x7da1b0a64c40>]],...
keyword[def] identifier[get_bin] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[Bin] ( identifier[self] . identifier[_provider_manager] , identifier[self] . identifier[_get_provider_session] ( literal[...
def get_bin(self, *args, **kwargs): """Pass through to provider BinLookupSession.get_bin""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bin return Bin(self._provider_manager, self._get_provider_session('bin_lookup_session').get_bin(*args, **kwargs), self._runtime, self...
def _should_retry(self, context): # type: (ExponentialRetryWithMaxWait, # azure.storage.common.models.RetryContext) -> bool """Determine if retry should happen or not :param ExponentialRetryWithMaxWait self: this :param azure.storage.common.models.RetryContext context: ret...
def function[_should_retry, parameter[self, context]]: constant[Determine if retry should happen or not :param ExponentialRetryWithMaxWait self: this :param azure.storage.common.models.RetryContext context: retry context :rtype: bool :return: True if retry should happen, False ot...
keyword[def] identifier[_should_retry] ( identifier[self] , identifier[context] ): literal[string] keyword[if] identifier[context] . identifier[count] >= identifier[self] . identifier[max_attempts] : keyword[return] keyword[False] identifier[status]...
def _should_retry(self, context): # type: (ExponentialRetryWithMaxWait, # azure.storage.common.models.RetryContext) -> bool 'Determine if retry should happen or not\n :param ExponentialRetryWithMaxWait self: this\n :param azure.storage.common.models.RetryContext context: retry context\n...
def gc(args): """ %prog gc fastafile Plot G+C content distribution. """ p = OptionParser(gc.__doc__) p.add_option("--binsize", default=500, type="int", help="Bin size to use") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ...
def function[gc, parameter[args]]: constant[ %prog gc fastafile Plot G+C content distribution. ] variable[p] assign[=] call[name[OptionParser], parameter[name[gc].__doc__]] call[name[p].add_option, parameter[constant[--binsize]]] <ast.Tuple object at 0x7da1b08d2410> assign[=...
keyword[def] identifier[gc] ( identifier[args] ): literal[string] identifier[p] = identifier[OptionParser] ( identifier[gc] . identifier[__doc__] ) identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = literal[int] , identifier[type] = literal[string] , identifier[help]...
def gc(args): """ %prog gc fastafile Plot G+C content distribution. """ p = OptionParser(gc.__doc__) p.add_option('--binsize', default=500, type='int', help='Bin size to use') (opts, args) = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) # depends on [contro...
def p_substr_assignment(p): """ statement : LET ID arg_list EQ expr """ if p[3] is None or p[5] is None: return # There were errors p[0] = None entry = SYMBOL_TABLE.access_call(p[2], p.lineno(2)) if entry is None: return if entry.class_ == CLASS.unknown: entry.clas...
def function[p_substr_assignment, parameter[p]]: constant[ statement : LET ID arg_list EQ expr ] if <ast.BoolOp object at 0x7da1b0653ee0> begin[:] return[None] call[name[p]][constant[0]] assign[=] constant[None] variable[entry] assign[=] call[name[SYMBOL_TABLE].access_call, p...
keyword[def] identifier[p_substr_assignment] ( identifier[p] ): literal[string] keyword[if] identifier[p] [ literal[int] ] keyword[is] keyword[None] keyword[or] identifier[p] [ literal[int] ] keyword[is] keyword[None] : keyword[return] identifier[p] [ literal[int] ]= keyword[None] ...
def p_substr_assignment(p): """ statement : LET ID arg_list EQ expr """ if p[3] is None or p[5] is None: return # There were errors # depends on [control=['if'], data=[]] p[0] = None entry = SYMBOL_TABLE.access_call(p[2], p.lineno(2)) if entry is None: return # depends on [con...
def load_riskmodel(self): # to be called before read_exposure # NB: this is called even if there is no risk model """ Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore. ...
def function[load_riskmodel, parameter[self]]: constant[ Read the risk model and set the attribute .riskmodel. The riskmodel can be empty for hazard calculations. Save the loss ratios (if any) in the datastore. ] call[name[logging].info, parameter[constant[Reading the ris...
keyword[def] identifier[load_riskmodel] ( identifier[self] ): literal[string] identifier[logging] . identifier[info] ( literal[string] ) identifier[self] . identifier[riskmodel] = identifier[readinput] . identifier[get_risk_model] ( identifier[self] . identifier[oqparam] ) keywo...
def load_riskmodel(self): # to be called before read_exposure # NB: this is called even if there is no risk model '\n Read the risk model and set the attribute .riskmodel.\n The riskmodel can be empty for hazard calculations.\n Save the loss ratios (if any) in the datastore.\n ' ...
def biomaRtTOkegg(df): """ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_ge...
def function[biomaRtTOkegg, parameter[df]]: constant[ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the...
keyword[def] identifier[biomaRtTOkegg] ( identifier[df] ): literal[string] identifier[df] = identifier[df] . identifier[dropna] () identifier[ECcols] = identifier[df] . identifier[columns] . identifier[tolist] () identifier[df] . identifier[reset_index] ( identifier[inplace] = keyword[True] , ide...
def biomaRtTOkegg(df): """ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_ge...
def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): r""" Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :param pan...
def function[link_to_dashboard, parameter[self, dashboard_id, panel_id]]: constant[ Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :par...
keyword[def] identifier[link_to_dashboard] ( identifier[self] , identifier[dashboard_id] = keyword[None] , identifier[panel_id] = keyword[None] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[self] . identifier[_dimensions] == literal[int] : identifier[self] . identi...
def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): """ Links the sensor to a dashboard. :param dashboard_id: Id of the dashboard to link to. Enter a * if the sensor should be linked to all dashboards. :type dashboard_id: ``str`` :param panel_id...
def initial_validation(request, prefix): """ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we store their post data in their se...
def function[initial_validation, parameter[request, prefix]]: constant[ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we st...
keyword[def] identifier[initial_validation] ( identifier[request] , identifier[prefix] ): literal[string] identifier[post_data] = identifier[request] . identifier[POST] identifier[login_required_setting_name] = identifier[prefix] . identifier[upper] ()+ literal[string] identifier[posted_session...
def initial_validation(request, prefix): """ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is unauthenticated, we store their post data in their se...
def make_neurites(rdw): '''Build neurite trees from a raw data wrapper''' post_action = _NEURITE_ACTION[rdw.fmt] trunks = rdw.neurite_root_section_ids() if not trunks: return [], [] # One pass over sections to build nodes nodes = tuple(Section(section_id=i, poi...
def function[make_neurites, parameter[rdw]]: constant[Build neurite trees from a raw data wrapper] variable[post_action] assign[=] call[name[_NEURITE_ACTION]][name[rdw].fmt] variable[trunks] assign[=] call[name[rdw].neurite_root_section_ids, parameter[]] if <ast.UnaryOp object at 0x7da20...
keyword[def] identifier[make_neurites] ( identifier[rdw] ): literal[string] identifier[post_action] = identifier[_NEURITE_ACTION] [ identifier[rdw] . identifier[fmt] ] identifier[trunks] = identifier[rdw] . identifier[neurite_root_section_ids] () keyword[if] keyword[not] identifier[trunks] : ...
def make_neurites(rdw): """Build neurite trees from a raw data wrapper""" post_action = _NEURITE_ACTION[rdw.fmt] trunks = rdw.neurite_root_section_ids() if not trunks: return ([], []) # depends on [control=['if'], data=[]] # One pass over sections to build nodes nodes = tuple((Section(s...
def sum2diag(A, D, out=None): r"""Add values ``D`` to the diagonal of matrix ``A``. Args: A (array_like): Left-hand side. D (array_like or float): Values to add. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: Resulting matrix. "...
def function[sum2diag, parameter[A, D, out]]: constant[Add values ``D`` to the diagonal of matrix ``A``. Args: A (array_like): Left-hand side. D (array_like or float): Values to add. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`...
keyword[def] identifier[sum2diag] ( identifier[A] , identifier[D] , identifier[out] = keyword[None] ): literal[string] identifier[A] = identifier[asarray] ( identifier[A] , identifier[float] ) identifier[D] = identifier[asarray] ( identifier[D] , identifier[float] ) keyword[if] identifier[out] ...
def sum2diag(A, D, out=None): """Add values ``D`` to the diagonal of matrix ``A``. Args: A (array_like): Left-hand side. D (array_like or float): Values to add. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: Resulting matrix. ""...
def handle_resource_update_success(resource): """ Recover resource if its state is ERRED and clear error message. """ update_fields = [] if resource.state == resource.States.ERRED: resource.recover() update_fields.append('state') if resource.state in (resource.States.UPDATING, r...
def function[handle_resource_update_success, parameter[resource]]: constant[ Recover resource if its state is ERRED and clear error message. ] variable[update_fields] assign[=] list[[]] if compare[name[resource].state equal[==] name[resource].States.ERRED] begin[:] call[n...
keyword[def] identifier[handle_resource_update_success] ( identifier[resource] ): literal[string] identifier[update_fields] =[] keyword[if] identifier[resource] . identifier[state] == identifier[resource] . identifier[States] . identifier[ERRED] : identifier[resource] . identifier[recover] (...
def handle_resource_update_success(resource): """ Recover resource if its state is ERRED and clear error message. """ update_fields = [] if resource.state == resource.States.ERRED: resource.recover() update_fields.append('state') # depends on [control=['if'], data=[]] if resourc...
def FindAnomalies(self): """Identify anomalies in the password/shadow and group/gshadow data.""" # Find anomalous group entries. findings = [] group_entries = {g.gid for g in itervalues(self.groups)} for gid in set(self.gids) - group_entries: undefined = ",".join(self.gids.get(gid, [])) ...
def function[FindAnomalies, parameter[self]]: constant[Identify anomalies in the password/shadow and group/gshadow data.] variable[findings] assign[=] list[[]] variable[group_entries] assign[=] <ast.SetComp object at 0x7da20cabda80> for taget[name[gid]] in starred[binary_operation[call[n...
keyword[def] identifier[FindAnomalies] ( identifier[self] ): literal[string] identifier[findings] =[] identifier[group_entries] ={ identifier[g] . identifier[gid] keyword[for] identifier[g] keyword[in] identifier[itervalues] ( identifier[self] . identifier[groups] )} keyword[for] identi...
def FindAnomalies(self): """Identify anomalies in the password/shadow and group/gshadow data.""" # Find anomalous group entries. findings = [] group_entries = {g.gid for g in itervalues(self.groups)} for gid in set(self.gids) - group_entries: undefined = ','.join(self.gids.get(gid, [])) ...
def is_valid_varname(self, name, item): """ Valid variable name, checked against global context. """ check_valid_varname(name, self._custom_units, self._structs, self._constants, item) if name in self._globals: raise VariableDeclarationException( 'Invalid name "%s", p...
def function[is_valid_varname, parameter[self, name, item]]: constant[ Valid variable name, checked against global context. ] call[name[check_valid_varname], parameter[name[name], name[self]._custom_units, name[self]._structs, name[self]._constants, name[item]]] if compare[name[name] in name[sel...
keyword[def] identifier[is_valid_varname] ( identifier[self] , identifier[name] , identifier[item] ): literal[string] identifier[check_valid_varname] ( identifier[name] , identifier[self] . identifier[_custom_units] , identifier[self] . identifier[_structs] , identifier[self] . identifier[_constant...
def is_valid_varname(self, name, item): """ Valid variable name, checked against global context. """ check_valid_varname(name, self._custom_units, self._structs, self._constants, item) if name in self._globals: raise VariableDeclarationException('Invalid name "%s", previously defined as global.' % n...
def color_replace(image, color): """Replace black with other color :color: custom color (r,g,b,a) :image: image to replace color :returns: TODO """ pixels = image.load() size = image.size[0] for width in range(size): for height in range(size): r, g, b, a = pixels[wi...
def function[color_replace, parameter[image, color]]: constant[Replace black with other color :color: custom color (r,g,b,a) :image: image to replace color :returns: TODO ] variable[pixels] assign[=] call[name[image].load, parameter[]] variable[size] assign[=] call[name[image]....
keyword[def] identifier[color_replace] ( identifier[image] , identifier[color] ): literal[string] identifier[pixels] = identifier[image] . identifier[load] () identifier[size] = identifier[image] . identifier[size] [ literal[int] ] keyword[for] identifier[width] keyword[in] identifier[range] (...
def color_replace(image, color): """Replace black with other color :color: custom color (r,g,b,a) :image: image to replace color :returns: TODO """ pixels = image.load() size = image.size[0] for width in range(size): for height in range(size): (r, g, b, a) = pixels[...
def _parse_redirect(self, element): """ Parse a redirect statement :param element: The XML Element object :type element: etree._Element """ self._log.info('Parsing response as a redirect') self.redirect = True return self._parse_template(element)
def function[_parse_redirect, parameter[self, element]]: constant[ Parse a redirect statement :param element: The XML Element object :type element: etree._Element ] call[name[self]._log.info, parameter[constant[Parsing response as a redirect]]] name[self].redirec...
keyword[def] identifier[_parse_redirect] ( identifier[self] , identifier[element] ): literal[string] identifier[self] . identifier[_log] . identifier[info] ( literal[string] ) identifier[self] . identifier[redirect] = keyword[True] keyword[return] identifier[self] . identifier[_...
def _parse_redirect(self, element): """ Parse a redirect statement :param element: The XML Element object :type element: etree._Element """ self._log.info('Parsing response as a redirect') self.redirect = True return self._parse_template(element)
def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None: '''Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \ MODERATE | RUNNING_CRITICAL | COMPLETE ''' _, error = self._execute('-s', self.device_sn, '...
def function[app_trim_memory, parameter[self, pid, level]]: constant[Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | MODERATE | RUNNING_CRITICAL | COMPLETE ] <ast.Tuple object at 0x7da207f994e0> assign[=] call[name[self]._ex...
keyword[def] identifier[app_trim_memory] ( identifier[self] , identifier[pid] : identifier[int] keyword[or] identifier[str] , identifier[level] : identifier[str] = literal[string] )-> keyword[None] : literal[string] identifier[_] , identifier[error] = identifier[self] . identifier[_execute] ( lit...
def app_trim_memory(self, pid: int or str, level: str='RUNNING_LOW') -> None: """Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | MODERATE | RUNNING_CRITICAL | COMPLETE """ (_, error) = self._execute('-s', self.device_sn, 'shell', 'a...