code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def run(self): """Delete the specified gene and solve using the desired method.""" obj_reaction = self._get_objective() genes = set() gene_assoc = {} for reaction in self._model.reactions: assoc = None if reaction.genes is None: continue ...
Delete the specified gene and solve using the desired method.
def lipisha_ipn(self): """Process lipisha IPN - Initiate/Acknowledge""" if not (self.request.POST.get('api_key') == LIPISHA_API_KEY and self.request.POST.get('api_signature') == LIPISHA_API_SIGNATURE): raise HTTPBadRequest return process_lipisha_payment(self.request)
Process lipisha IPN - Initiate/Acknowledge
def process_details(): """ Returns details about the current process """ results = {"argv": sys.argv, "working.directory": os.getcwd()} # Process ID and execution IDs (UID, GID, Login, ...) for key, method in { "pid": "getpid", "ppid": "getppid", ...
Returns details about the current process
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AwsContext for this AwsInstance :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext ...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AwsContext for this AwsInstance :rtype: twilio.rest.accounts.v1.credential.aws.AwsContext
def submit(self, password=''): """Submits the participation to the web site. The passwords is sent as plain text. :return: the evaluation results. """ url = '{}/api/submit'.format(BASE_URL) try: r = requests.post(url, data=self...
Submits the participation to the web site. The passwords is sent as plain text. :return: the evaluation results.
def save_file(fullpath, entry): """ Save a message file out, without mangling the headers """ with tempfile.NamedTemporaryFile('w', delete=False) as file: tmpfile = file.name # we can't just use file.write(str(entry)) because otherwise the # headers "helpfully" do MIME encoding normaliza...
Save a message file out, without mangling the headers
def make_list_table(headers, data, title='', columns=None): """Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the ...
Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the columns.
def version(versioninfo=False): ''' .. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.versio...
.. versionadded:: 2015.8.0 Returns the version of Git installed on the minion versioninfo : False If ``True``, return the version in a versioninfo list (e.g. ``[2, 5, 0]``) CLI Example: .. code-block:: bash salt myminion git.version
def enforce_reset(self): """enforce parameter bounds on the ensemble by resetting violating vals to bound """ ub = (self.ubnd * (1.0+self.bound_tol)).to_dict() lb = (self.lbnd * (1.0 - self.bound_tol)).to_dict() #for iname,name in enumerate(self.columns): #se...
enforce parameter bounds on the ensemble by resetting violating vals to bound
def _rtg_add_summary_file(eval_files, base_dir, data): """Parse output TP FP and FN files to generate metrics for plotting. """ out_file = os.path.join(base_dir, "validate-summary.csv") if not utils.file_uptodate(out_file, eval_files.get("tp", eval_files.get("fp", eval_files["fn"]))): with file_...
Parse output TP FP and FN files to generate metrics for plotting.
def plot_lnp(fignum, s, datablock, fpars, direction_type_key): """ plots lines and planes on a great circle with alpha 95 and mean Parameters _________ fignum : number of plt.figure() object datablock : nested list of dictionaries with keys in 3.0 or 2.5 format 3.0 keys: dir_dec, dir_i...
plots lines and planes on a great circle with alpha 95 and mean Parameters _________ fignum : number of plt.figure() object datablock : nested list of dictionaries with keys in 3.0 or 2.5 format 3.0 keys: dir_dec, dir_inc, dir_tilt_correction = [-1,0,100], direction_type_key =['p','l'] ...
def write(series, output, scale=None): """Write a `TimeSeries` to a WAV file Parameters ---------- series : `TimeSeries` the series to write output : `file`, `str` the file object or filename to write to scale : `float`, optional the factor to apply to scale the data t...
Write a `TimeSeries` to a WAV file Parameters ---------- series : `TimeSeries` the series to write output : `file`, `str` the file object or filename to write to scale : `float`, optional the factor to apply to scale the data to (-1.0, 1.0), pass `scale=1` to not a...
def command( commands: str or list, prefix: str or list = "/", separator: str = " ", case_sensitive: bool = False ): """Filter commands, i.e.: text messages starting with "/" or any other custom prefix. Args: commands (``str`` | ``list``): ...
Filter commands, i.e.: text messages starting with "/" or any other custom prefix. Args: commands (``str`` | ``list``): The command or list of commands as string the filter should look for. Examples: "start", ["start", "help", "settings"]. When a message text contain...
def get_objects_for_subject(subject=None, object_category=None, relation=None, **kwargs): """ Convenience method: Given a subject (e.g. gene, disease, variant), return all associated objects (phenotypes, functions, interacting g...
Convenience method: Given a subject (e.g. gene, disease, variant), return all associated objects (phenotypes, functions, interacting genes, etc)
def wrap_make_secure_channel(make_secure_channel_func, tracer=None): """Wrap the google.cloud._helpers.make_secure_channel.""" def call(*args, **kwargs): channel = make_secure_channel_func(*args, **kwargs) try: host = kwargs.get('host') tracer_interceptor = OpenCensusCli...
Wrap the google.cloud._helpers.make_secure_channel.
def sample_categorical(prob, rng): """Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.Ra...
Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.RandomState Returns ------- ret...
def from_zip(cls, src='/tmp/app.zip', dest='/app'): """ Unzips a zipped app project file and instantiates it. :param src: zipfile path :param dest: destination folder to extract the zipfile content Returns A project instance. """ try: zf = zipfile.ZipFile(src, 'r') except F...
Unzips a zipped app project file and instantiates it. :param src: zipfile path :param dest: destination folder to extract the zipfile content Returns A project instance.
def text_pixels(self, text, clear_screen=True, x=0, y=0, text_color='black', font=None): """ Display `text` starting at pixel (x, y). The EV3 display is 178x128 pixels - (0, 0) would be the top left corner of the display - (89, 64) would be right in the middle of the display ...
Display `text` starting at pixel (x, y). The EV3 display is 178x128 pixels - (0, 0) would be the top left corner of the display - (89, 64) would be right in the middle of the display 'text_color' : PIL says it supports "common HTML color names". There are 140 HTML color names ...
def parse( args: typing.List[str] = None, arg_parser: ArgumentParser = None ) -> dict: """Parses the arguments for the cauldron server""" parser = arg_parser or create_parser() return vars(parser.parse_args(args))
Parses the arguments for the cauldron server
def authenticate(user=None): # noqa: E501 """Authenticate Authenticate with the API # noqa: E501 :param user: The user authentication object. :type user: dict | bytes :rtype: UserAuth """ if connexion.request.is_json: user = UserAuth.from_dict(connexion.request.get_json()) # noq...
Authenticate Authenticate with the API # noqa: E501 :param user: The user authentication object. :type user: dict | bytes :rtype: UserAuth
def remove_security_group(self, name): """ Remove a security group from container """ for group in self.security_groups: if group.isc_name == name: group.delete()
Remove a security group from container
def pformat_dict_summary_html(dict): """ Briefly print the dictionary keys. """ if not dict: return ' {}' html = [] for key, value in sorted(six.iteritems(dict)): if not isinstance(value, DICT_EXPANDED_TYPES): value = '...' html.append(_format_dict_item(ke...
Briefly print the dictionary keys.
def main(): ''' entry point of the application. Parses the CLI commands and runs the actions. ''' args = CLI.parse_args(__doc__) if args['--verbose']: requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) logging.basicConfig(...
entry point of the application. Parses the CLI commands and runs the actions.
def prob_t_profiles(self, profile_pair, multiplicity, t, return_log=False, ignore_gaps=True): ''' Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions ...
Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions of the nucleotides at either end of the branch. pp[0] = parent, pp[1] = child multiplicity : numpy array ...
def normalize_lcdict_byinst( lcdict, magcols='all', normto='sdssr', normkeylist=('stf','ccd','flt','fld','prj','exp'), debugmode=False, quiet=False ): '''This is a function to normalize light curves across all instrument combinations present. Use this to norm...
This is a function to normalize light curves across all instrument combinations present. Use this to normalize a light curve containing a variety of: - HAT station IDs ('stf') - camera IDs ('ccd') - filters ('flt') - observed field names ('fld') - HAT project IDs ('prj') - exposure tim...
def get_event_timelines(self, event_ids, session=None, lightweight=None): """ Returns a list of event timelines based on event id's supplied. :param list event_ids: List of event id's to return :param requests.session session: Requests session object :param bool lightwei...
Returns a list of event timelines based on event id's supplied. :param list event_ids: List of event id's to return :param requests.session session: Requests session object :param bool lightweight: If True will return dict not a resource :rtype: list[resources.EventTimeline]
def make_if_statement(instr, queue, stack, context): """ Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. """ test_expr = make_expr(stack) if isinstance(instr, instrs.POP_JUMP_IF_TRUE): test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr) first_block = popwhile(op....
Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) # assuming the contents has been vetted for utf-8 encoding contents = contents.encode("utf-8") with o...
Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it.
def provides(self): """ A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings. """ plist = self.metadata.provides s = '%s (%s)' % (self.name, self.version) if s not in plist: plist.append(s) ...
A set of distribution names and versions provided by this distribution. :return: A set of "name (version)" strings.
def page_models(self, constructor, paging, constraints=None, *, columns=None, order_by=None): """Specialization of DataAccess.page that returns models instead of cursor objects.""" records, count = self.page(constructor.table_name, paging, constraints, columns=columns, order_by=or...
Specialization of DataAccess.page that returns models instead of cursor objects.
def insert(self, packet, **kwargs): ''' Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database ''' values = [ ] pd = packet._defn for defn in pd.fields: ...
Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database
def _get_db_version(self): """ Get the schema version of the nipap psql db. """ dbname = self._cfg.get('nipapd', 'db_name') self._execute("SELECT description FROM pg_shdescription JOIN pg_database ON objoid = pg_database.oid WHERE datname = '%s'" % dbname) comment = self._curs_p...
Get the schema version of the nipap psql db.
def slot_availability_array(events, slots): """ Return a numpy array mapping events to slots - Rows corresponds to events - Columns correspond to stags Array has value 0 if event cannot be scheduled in a given slot (1 otherwise) """ array = np.ones((len(events), len(slots))) for ro...
Return a numpy array mapping events to slots - Rows corresponds to events - Columns correspond to stags Array has value 0 if event cannot be scheduled in a given slot (1 otherwise)
def build_text_part(name, thread, struct): """ create an urwid.Text widget (wrapped in approproate Attributes) to display a plain text parts in a threadline. create an urwid.Columns widget (wrapped in approproate Attributes) to display a list of tag strings, as part of a threadline. :param name...
create an urwid.Text widget (wrapped in approproate Attributes) to display a plain text parts in a threadline. create an urwid.Columns widget (wrapped in approproate Attributes) to display a list of tag strings, as part of a threadline. :param name: id of part to build :type name: str :param th...
def mul(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to ...
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to treat the output as a PDF for any filter using ...
def EnumerateFilesystemsFromClient(args): """List all local filesystems mounted on this system.""" del args # Unused. for drive in win32api.GetLogicalDriveStrings().split("\x00"): if not drive: continue try: volume = win32file.GetVolumeNameForVolumeMountPoint(drive).rstrip("\\") label,...
List all local filesystems mounted on this system.
def DecodeValueFromAttribute(self, attribute_name, value, ts): """Given a serialized value, decode the attribute. Only attributes which have been previously defined are permitted. Args: attribute_name: The string name of the attribute. value: The serialized attribute value. ts: The ti...
Given a serialized value, decode the attribute. Only attributes which have been previously defined are permitted. Args: attribute_name: The string name of the attribute. value: The serialized attribute value. ts: The timestamp of this attribute.
def fill_tree_from_xml(tag, ar_tree, namespace): # type: (_Element, ArTree, str) -> None """Parse the xml tree into ArTree objects.""" for child in tag: # type: _Element name_elem = child.find('./' + namespace + 'SHORT-NAME') # long_name = child.find('./' + namespace + 'LONG-NAME') ...
Parse the xml tree into ArTree objects.
def tournament_selection(random, population, args): """Return a tournament sampling of individuals from the population. This function selects ``num_selected`` individuals from the population. It selects each one by using random sampling without replacement to pull ``tournament_size`` individuals a...
Return a tournament sampling of individuals from the population. This function selects ``num_selected`` individuals from the population. It selects each one by using random sampling without replacement to pull ``tournament_size`` individuals and adds the best of the tournament as its selection. If...
def delete_service(self, service_name, params=None): """ Delete the service of the given name. It may fail if there are any service keys or app bindings. Use purge() if you want to delete it all. """ if not self.space.has_service_with_name(service_name): log...
Delete the service of the given name. It may fail if there are any service keys or app bindings. Use purge() if you want to delete it all.
def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None): """ Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular...
Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular context (values) for the optimization run (default, None). :param pending_X: matrix of input conf...
def sojourn_time(p): """ Calculate sojourn time based on a given transition probability matrix. Parameters ---------- p : array (k, k), a Markov transition probability matrix. Returns ------- : array (k, ), sojourn times. Each element is th...
Calculate sojourn time based on a given transition probability matrix. Parameters ---------- p : array (k, k), a Markov transition probability matrix. Returns ------- : array (k, ), sojourn times. Each element is the expected time a Markov ...
def set_breakpoint(self, file_name, line_number, condition=None, enabled=True): """ Create a breakpoint, register it in the class's lists and returns a tuple of (error_message, break_number) """ c_file_name = self.canonic(file_name) import linecache line = linecache.getli...
Create a breakpoint, register it in the class's lists and returns a tuple of (error_message, break_number)
def setup(self, app): ''' Setup properties from parent app on the command ''' self.logger = app.logger self.shell.logger = self.logger if not self.command_name: raise EmptyCommandNameException() self.app = app self.arguments_declaration = sel...
Setup properties from parent app on the command
def pre_init(self, value, obj): """Convert a string value to JSON only if it needs to be deserialized. SubfieldBase metaclass has been modified to call this method instead of to_python so that we can check the obj state and determine if it needs to be deserialized""" try: ...
Convert a string value to JSON only if it needs to be deserialized. SubfieldBase metaclass has been modified to call this method instead of to_python so that we can check the obj state and determine if it needs to be deserialized
def bounds(self): """Finds min/max for bounds across blocks Returns: tuple(float): length 6 tuple of floats containing min/max along each axis """ bounds = [np.inf,-np.inf, np.inf,-np.inf, np.inf,-np.inf] def update_bounds(ax, nb, bounds): ...
Finds min/max for bounds across blocks Returns: tuple(float): length 6 tuple of floats containing min/max along each axis
def prior_from_config(cp, variable_params, prior_section, constraint_section): """Gets arguments and keyword arguments from a config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. variable_params : list ...
Gets arguments and keyword arguments from a config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. variable_params : list List of of model parameter names. prior_section : str Section to read prior(s) from. ...
def WriteSerialized(cls, attribute_container): """Writes an attribute container to serialized form. Args: attribute_container (AttributeContainer): attribute container. Returns: str: A JSON string containing the serialized form. """ json_dict = cls.WriteSerializedDict(attribute_contain...
Writes an attribute container to serialized form. Args: attribute_container (AttributeContainer): attribute container. Returns: str: A JSON string containing the serialized form.
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile....
Package the built app as an ipa for distribution in iOS App Store
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, d...
Default output directory.
def thaicheck(word: str) -> bool: """ Check if a word is an "authentic Thai word" :param str word: word :return: True or False """ pattern = re.compile(r"[ก-ฬฮ]", re.U) # สำหรับตรวจสอบพยัญชนะ res = re.findall(pattern, word) # ดึงพยัญชนะทัั้งหมดออกมา if res == []: return False...
Check if a word is an "authentic Thai word" :param str word: word :return: True or False
def _do_connect(self): """ Connect to the remote. """ self.load_system_host_keys() if self.username is None or self.port is None: self._configure() try: self.connect(hostname=self.hostname, port=self.port, username...
Connect to the remote.
def _unsign_data(self, data, options): '''Verify and remove signature''' if options['signature_algorithm_id'] not in self.signature_algorithms: raise Exception('Unknown signature algorithm id: %d' % options['signature_algorithm_id']) signature_algorithm ...
Verify and remove signature
def node_list_to_coordinate_lines(G, node_list, use_geom=True): """ Given a list of nodes, return a list of lines that together follow the path defined by the list of nodes. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes use_geom : bool...
Given a list of nodes, return a list of lines that together follow the path defined by the list of nodes. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes use_geom : bool if True, use the spatial geometry attribute of the edges to draw ...
def with_timeout(timeout, d, reactor=reactor): """Returns a `Deferred` that is in all respects equivalent to `d`, e.g. when `cancel()` is called on it `Deferred`, the wrapped `Deferred` will also be cancelled; however, a `Timeout` will be fired after the `timeout` number of seconds if `d` has not fired by t...
Returns a `Deferred` that is in all respects equivalent to `d`, e.g. when `cancel()` is called on it `Deferred`, the wrapped `Deferred` will also be cancelled; however, a `Timeout` will be fired after the `timeout` number of seconds if `d` has not fired by that time. When a `Timeout` is raised, `d` will be...
def reset(self): """ (re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``. """ self.config = None self.html = None self.parsed_tree = None self.tidied = False ...
(re)set all instance attributes to default. Every attribute is set to ``None``, except :attr:`author` and :attr:`failures` which are set to ``[]``.
async def getiter(self, url: str, url_vars: Dict[str, str] = {}, *, accept: str = sansio.accept_format(), jwt: Opt[str] = None, oauth_token: Opt[str] = None ) -> AsyncGenerator[Any, None]: """Return an async iterable for all...
Return an async iterable for all the items at a specified endpoint.
def serialize(ad_objects, output_format='json', indent=2, attributes_only=False): """Serialize the object to the specified format :param ad_objects list: A list of ADObjects to serialize :param output_format str: The output format, json or yaml. Defaults to json :param indent int: The number of spaces...
Serialize the object to the specified format :param ad_objects list: A list of ADObjects to serialize :param output_format str: The output format, json or yaml. Defaults to json :param indent int: The number of spaces to indent, defaults to 2 :param attributes only: Only serialize the attributes found...
def linear_trend_timewise(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parame...
Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parameters control which of the characteristics are ret...
def __build_cmd_maps(cls): """Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns:...
Build the mapping from command names to method names. One command name maps to at most one method. Multiple command names can map to the same method. Only used by __init__() to initialize self._cmd_map. MUST NOT be used elsewhere. Returns: A tuple (cmd_map, hidden_...
def load(self, filename, params=None, force=False, depthrange=None, timerange=None, output_is_dict=True, **kwargs): """ NetCDF data loader :parameter filename: file name :parameter params: a list of variables to load (default : load ALL variables). :param...
NetCDF data loader :parameter filename: file name :parameter params: a list of variables to load (default : load ALL variables). :parameter depthrange: if a depth dimension is found, subset along this dimension. :parameter timerange: if a time dimension is found, ...
def minor_releases(self, manager): """ Return all minor release line labels found in ``manager``. """ # TODO: yea deffo need a real object for 'manager', heh. E.g. we do a # very similar test for "do you have any actual releases yet?" # elsewhere. (This may be fodder for ...
Return all minor release line labels found in ``manager``.
def splitter(structured): """ Separates structured data into a list of actives or a list of decoys. actives are labeled with a '1' in their status fields, while decoys are labeled with a '0' in their status fields. :param structured: either roc_structure or score_structure. roc_structure: list [(id,...
Separates structured data into a list of actives or a list of decoys. actives are labeled with a '1' in their status fields, while decoys are labeled with a '0' in their status fields. :param structured: either roc_structure or score_structure. roc_structure: list [(id, best_score, best_query, status, fpf, ...
def scope(self, *args, **kwargs): # type: (*Any, **Any) -> Scope """Return a single scope based on the provided name. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional que...
Return a single scope based on the provided name. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :return: a single :class:`models.Scope` :raises NotF...
def get_sub_extractors_by_property(extractor, property_name, return_property_list=False): '''Divides Recording or Sorting Extractor based on the property_name (e.g. group) Parameters ---------- extractor: RecordingExtractor or SortingExtractor The extractor to be subdivided in subextractors ...
Divides Recording or Sorting Extractor based on the property_name (e.g. group) Parameters ---------- extractor: RecordingExtractor or SortingExtractor The extractor to be subdivided in subextractors property_name: str The property used to subdivide the extractor return_property_list...
def processRequest(self, arg, **kw): """ Parameters: arg -- XML Soap data string """ if self.debug: log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1) if arg is None: return for h in self.handlers: arg = h.processReque...
Parameters: arg -- XML Soap data string
def pop(self, count=1): """ Return new deque with rightmost element removed. Popping the empty queue will return the empty queue. A optional count can be given to indicate the number of elements to pop. Popping with a negative index is the same as popleft. Executes in amortized O...
Return new deque with rightmost element removed. Popping the empty queue will return the empty queue. A optional count can be given to indicate the number of elements to pop. Popping with a negative index is the same as popleft. Executes in amortized O(k) where k is the number of elements to pop...
def GetZipInfo(self): """Retrieves the ZIP info object. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect. """ if not self._zip_info: location = getattr(self.path_spec, 'location', None) if lo...
Retrieves the ZIP info object. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect.
def check_url (self): """Try to get URL data from queue and check it.""" try: url_data = self.urlqueue.get(timeout=QUEUE_POLL_INTERVALL_SECS) if url_data is not None: try: self.check_url_data(url_data) finally: ...
Try to get URL data from queue and check it.
def get_sequences_from_cluster(c1, c2, data): """get all sequences from on cluster""" seqs1 = data[c1]['seqs'] seqs2 = data[c2]['seqs'] seqs = list(set(seqs1 + seqs2)) names = [] for s in seqs: if s in seqs1 and s in seqs2: names.append("both") elif s in seqs1: ...
get all sequences from on cluster
def render(self, fname=''): """Render the circuit expression and store the result in a file Args: fname (str): Path to an image file to store the result in. Returns: str: The path to the image file """ import qnet.visualization.circuit_pyx as circuit_vis...
Render the circuit expression and store the result in a file Args: fname (str): Path to an image file to store the result in. Returns: str: The path to the image file
def _local_to_shape(self, local_x, local_y): """Translate local coordinates point to shape coordinates. Shape coordinates have the same unit as local coordinates, but are offset such that the origin of the shape coordinate system (0, 0) is located at the top-left corner of the shape bou...
Translate local coordinates point to shape coordinates. Shape coordinates have the same unit as local coordinates, but are offset such that the origin of the shape coordinate system (0, 0) is located at the top-left corner of the shape bounding box.
def modis_filename2modisdate(modis_fname): """ #+ # MODIS_FILENAME2DATE : Convert MODIS file name to MODIS date # # @author: Renaud DUSSURGET (LER PAC/IFREMER) # @history: Created by RD on 29/10/2012 # #- """ if not isinstance(modis_fname,list) : modis_fname=[modis_fname] ...
#+ # MODIS_FILENAME2DATE : Convert MODIS file name to MODIS date # # @author: Renaud DUSSURGET (LER PAC/IFREMER) # @history: Created by RD on 29/10/2012 # #-
def windyields(self, ini, end, delta, **keyw): """ This function returns the wind yields and ejected masses. X_i, E_i = data.windyields(ini, end, delta) Parameters ---------- ini : integer The starting cycle. end : integer The finishing c...
This function returns the wind yields and ejected masses. X_i, E_i = data.windyields(ini, end, delta) Parameters ---------- ini : integer The starting cycle. end : integer The finishing cycle. delta : integer The cycle interval. ...
def create_organisation(self, organisation_json): ''' Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`. ''' return trolly.organisation.Organisation( trello_client=self, ...
Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`.
def on_peer_down(self, peer): """Peer down handler. Cleans up the paths in global tables that was received from this peer. """ LOG.debug('Cleaning obsolete paths whose source/version: %s/%s', peer.ip_address, peer.version_num) # Launch clean-up for each global ...
Peer down handler. Cleans up the paths in global tables that was received from this peer.
def main(): """main Entrypoint to this script. This will execute the functionality as a standalone element """ src_dir = sys.argv[1] os.chdir(src_dir) config = get_config(src_dir) cmd = 'python -c "import f5;print(f5.__version__)"' version = \ subprocess.check_output([cmd], shell=T...
main Entrypoint to this script. This will execute the functionality as a standalone element
def key_expand(self, key): """ Derive public key and account number from **private key** :param key: Private key to generate account and public key of :type key: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.key_expand( key="781186FB9EF17DB6E3D105655...
Derive public key and account number from **private key** :param key: Private key to generate account and public key of :type key: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.key_expand( key="781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3" ...
def binary_report(self, sha256sum, apikey): """ retrieve report from file scan """ url = self.base_url + "file/report" params = {"apikey": apikey, "resource": sha256sum} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.pos...
retrieve report from file scan
def save(self): """Write changed .pth file back to disk""" if not self.dirty: return data = '\n'.join(map(self.make_relative, self.paths)) if data: log.debug("Saving %s", self.filename) data = ( "import sys; sys.__plen = len(sys.path)\...
Write changed .pth file back to disk
def encrypt(self, txt, key): """ XOR ciphering with a PBKDF2 checksum """ # log.debug("encrypt(txt='%s', key='%s')", txt, key) assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt) assert isinstance(key, six.text_type), "key: %s is not text type!"...
XOR ciphering with a PBKDF2 checksum
def gct2gctx_main(args): """ Separate from main() in order to make command-line tool. """ in_gctoo = parse_gct.parse(args.filename, convert_neg_666=False) if args.output_filepath is None: basename = os.path.basename(args.filename) out_name = os.path.splitext(basename)[0] + ".gctx" else...
Separate from main() in order to make command-line tool.
def patch_namespaced_role(self, name, namespace, body, **kwargs): """ partially update the specified Role This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_role(name, namespa...
partially update the specified Role This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_role(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req ...
def query(self): """ Main accounts query """ query = ( self.book.session.query(Account) .join(Commodity) .filter(Commodity.namespace != "template") .filter(Account.type != AccountType.root.value) ) return query
Main accounts query
def _premis_version_from_data(data): """Given tuple ``data`` encoding a PREMIS element, attempt to return the PREMIS version it is using. If none can be found, return the default PREMIS version. """ for child in data: if isinstance(child, dict): version = child.get("version") ...
Given tuple ``data`` encoding a PREMIS element, attempt to return the PREMIS version it is using. If none can be found, return the default PREMIS version.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or self.is_disable(): return ret # Max si...
Return the dict to display in the curse interface.
def write(self): '''Write signature file with signature of script, input, output and dependent files. Because local input and output files can only be determined after the execution of workflow. They are not part of the construction. ''' if not self.output_files.valid(): ...
Write signature file with signature of script, input, output and dependent files. Because local input and output files can only be determined after the execution of workflow. They are not part of the construction.
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_e...
call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save
def saelgv(vec1, vec2): """ Find semi-axis vectors of an ellipse generated by two arbitrary three-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html :param vec1: First vector used to generate an ellipse. :type vec1: 3-Element Array of floats :param v...
Find semi-axis vectors of an ellipse generated by two arbitrary three-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html :param vec1: First vector used to generate an ellipse. :type vec1: 3-Element Array of floats :param vec2: Second vector used to generate ...
def stateDict(self): """Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...} """ state = { 'duration' : self._duration, 'intensity' : self._intensity, 'risefall' : self._risefall, 'stim_t...
Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...}
def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): """ Given a 1d array, return an array of deterministic integers. .. versionadded:: 0.19.2 Parameters ---------- vals : ndarray, Categorical encoding : string, default 'utf8' encoding for data & key when strings ...
Given a 1d array, return an array of deterministic integers. .. versionadded:: 0.19.2 Parameters ---------- vals : ndarray, Categorical encoding : string, default 'utf8' encoding for data & key when strings hash_key : string key to encode, default to _default_hash_key categorize : ...
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._get_text_answer() return "{0} The correct answer was {1}. Please start a ne...
Simple method to form a start again message and give the answer in readable form.
def seqToKV(seq, strict=False): """Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes """ def...
Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: bytes
def load(patterns, full_reindex): ''' Load one or more CADA CSV files matching patterns ''' header('Loading CSV files') for pattern in patterns: for filename in iglob(pattern): echo('Loading {}'.format(white(filename))) with open(filename) as f: reader...
Load one or more CADA CSV files matching patterns
def rotation(f, line = 'fast'): """ Find rotation of the survey Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)`` The clock-wise rotation is defined as the angle in radians between line given by the first and last trace of the first line and the axis that gives increasing ...
Find rotation of the survey Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)`` The clock-wise rotation is defined as the angle in radians between line given by the first and last trace of the first line and the axis that gives increasing CDP-Y, in the direction that gives incre...
def _add_https(self, q): '''for push, pull, and other api interactions, the user can optionally define a custom registry. If the registry name doesn't include http or https, add it. Parameters ========== q: the parsed image query (names), including the or...
for push, pull, and other api interactions, the user can optionally define a custom registry. If the registry name doesn't include http or https, add it. Parameters ========== q: the parsed image query (names), including the original
def list_virtual_machine_scale_set_vm_network_interfaces(scale_set, vm_index, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 ...
.. versionadded:: 2019.2.0 Get information about all network interfaces in a specific virtual machine within a scale set. :param scale_set: The name of the scale set to query. :param vm_index: The virtual machine index. :param resource_group: The resource group name assigned to the scale set...
def remove(self, component): # type: (str) -> None """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.po...
Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component
def _get_nets_lacnic(self, *args, **kwargs): """ Deprecated. This will be removed in a future release. """ from warnings import warn warn('Whois._get_nets_lacnic() has been deprecated and will be ' 'removed. You should now use Whois.get_nets_lacnic().') retu...
Deprecated. This will be removed in a future release.
def increase_route_count(self, crawled_request): """Increase the count that determines how many times a URL of a certain route has been crawled. Args: crawled_request (:class:`nyawc.http.Request`): The request that possibly matches a route. """ for route in self.__routing_...
Increase the count that determines how many times a URL of a certain route has been crawled. Args: crawled_request (:class:`nyawc.http.Request`): The request that possibly matches a route.