code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def norm_proj_path(path, build_module): """Return a normalized path for the `path` observed in `build_module`. The normalized path is "normalized" (in the `os.path.normpath` sense), relative from the project root directory, and OS-native. Supports making references from project root directory by prefi...
Return a normalized path for the `path` observed in `build_module`. The normalized path is "normalized" (in the `os.path.normpath` sense), relative from the project root directory, and OS-native. Supports making references from project root directory by prefixing the path with "//". :raises Value...
def _sb_r2(self, term, r1_prefixes=None): """Return the R2 region, as defined in the Porter2 specification. Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- int ...
Return the R2 region, as defined in the Porter2 specification. Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- int Length of the R1 region
def syslog(logger_to_update=logger, facility=SysLogHandler.LOG_USER, disableStderrLogger=True): """ Setup logging to syslog and disable other internal loggers :param logger_to_update: the logger to enable syslog logging for :param facility: syslog facility to log to :param disableStderrLogger: shoul...
Setup logging to syslog and disable other internal loggers :param logger_to_update: the logger to enable syslog logging for :param facility: syslog facility to log to :param disableStderrLogger: should the default stderr logger be disabled? defaults to True :return the new SysLogHandler, which can be mo...
def writeXMLFile(filename, content): """ Used only for debugging to write out intermediate files""" xmlfile = open(filename, 'w') # pretty print content = etree.tostring(content, pretty_print=True) xmlfile.write(content) xmlfile.close()
Used only for debugging to write out intermediate files
def _instruction_to_superop(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the ...
Convert a QuantumCircuit or Instruction to a SuperOp.
def on_message(self, message_protocol_entity): """ Callback function when receiving message from whatsapp server """ logger.info("Message id %s received" % message_protocol_entity.getId()) # answer with receipt self.toLower(message_protocol_entity.ack())
Callback function when receiving message from whatsapp server
def render_to_mail(subject, template, context, recipient, fail_silently = False, headers = None): """ :param subject: The subject line of the email :param template: The name of the template to render the HTML email with :param context: The context data to pass to the template :param recipient: The e...
:param subject: The subject line of the email :param template: The name of the template to render the HTML email with :param context: The context data to pass to the template :param recipient: The email address or ``django.contrib.auth.User`` object to send the email to :param fail_silently: Set to ``Tr...
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="dual_", dual_model=None): # NOQA """ A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is a minimization problem the dual is a maximization probl...
A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is a minimization problem the dual is a maximization problem, and the optimal value of the dual is a lower bound of the optimal value of the primal. For linear problems, strong duality holds, which means ...
def accept_connection(self): """ Accept a pending connection. """ assert self.pending, "Connection is not pending." self.server_protocol = self.server.server_factory.buildProtocol(None) self._accept_d.callback( FakeServerProtocolWrapper(self, self.server_proto...
Accept a pending connection.
def get_default_queryset(self): """ looks for default groups excluding the current one overridable by openwisp-radius and other 3rd party apps """ return self.__class__.objects.exclude(pk=self.pk) \ .filter(default=True)
looks for default groups excluding the current one overridable by openwisp-radius and other 3rd party apps
def _expander(namepath): """ expand ./ ~ and ../ designators in location names """ if "~" in namepath: namepath = os.path.expanduser(namepath) else: namepath = os.path.abspath(namepath) return namepath
expand ./ ~ and ../ designators in location names
def get_timestamp(timezone_name, year, month, day, hour=0, minute=0): """Epoch timestamp from timezone, year, month, day, hour and minute.""" tz = pytz.timezone(timezone_name) tz_datetime = tz.localize(datetime(year, month, day, hour, minute)) timestamp = calendar.timegm(tz_datetime.utctimetuple()) ...
Epoch timestamp from timezone, year, month, day, hour and minute.
def addClassKey(self, klass, key, obj): """ Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore. """ d = self._getClass(kl...
Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore.
def path_safe_spec(self): """ :API: public """ return ('{safe_spec_path}.{target_name}' .format(safe_spec_path=self._spec_path.replace(os.sep, '.'), target_name=self._target_name.replace(os.sep, '.')))
:API: public
def http_method_formatter(view, context, model, name): """Wrap HTTP method value in a bs3 label.""" method_map = { 'GET': 'label-success', 'PUT': 'label-info', 'POST': 'label-primary', 'DELETE': 'label-danger', } return Markup( '<span class="label {}">{}</span>'.f...
Wrap HTTP method value in a bs3 label.
def defunct_hash_message( primitive=None, *, hexstr=None, text=None, signature_version=b'E', version_specific_data=None): ''' Convert the provided message into a message hash, to be signed. This provides the same prefix and hashing approach as :meth:`w3.et...
Convert the provided message into a message hash, to be signed. This provides the same prefix and hashing approach as :meth:`w3.eth.sign() <web3.eth.Eth.sign>`. Currently you can only specify the ``signature_version`` as following. * **Version** ``0x45`` (version ``E``): ``b'\\x19Ethereum Signed Messa...
def remove_part_files(num_parts=None): """Remove PART(#).html files and image directories from disk.""" filenames = get_part_filenames(num_parts) for filename in filenames: remove_part_images(filename) remove_file(filename)
Remove PART(#).html files and image directories from disk.
def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None): ''' Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the...
Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the error and break. CLI example:: salt myminion boto_kinesis.get_stream_when_active my_str...
def chimera_blocks(M=16, N=16, L=4): """ Generator for blocks for a chimera block quotient """ for x in xrange(M): for y in xrange(N): for u in (0, 1): yield tuple((x, y, u, k) for k in xrange(L))
Generator for blocks for a chimera block quotient
def get_fields(self): """ Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute. """ prefix = getattr(self.Meta, 'sourc...
Convert default field names for this sub-serializer into versions where the field name has the prefix removed, but each field object knows the real model field name by setting the field's `source` attribute.
def setExpressCheckout(self, params): """ Initiates an Express Checkout transaction. Optionally, the SetExpressCheckout API operation can set up billing agreements for reference transactions and recurring payments. Returns a NVP instance - check for token and payerid to continue!...
Initiates an Express Checkout transaction. Optionally, the SetExpressCheckout API operation can set up billing agreements for reference transactions and recurring payments. Returns a NVP instance - check for token and payerid to continue!
def sum(self): """Compute the sum for each group.""" if self._can_use_new_school(): self._prep_spark_sql_groupby() import pyspark.sql.functions as func return self._use_aggregation(func.sum) self._prep_pandas_groupby() myargs = self._myargs myk...
Compute the sum for each group.
def open_filechooser(title, parent=None, patterns=None, folder=None, filter=None, multiple=False, _before_run=None, action=None): """An open dialog. :param parent: window or None :param patterns: file match patterns :param folder: initial folder :param filt...
An open dialog. :param parent: window or None :param patterns: file match patterns :param folder: initial folder :param filter: file filter Use of filter and patterns at the same time is invalid.
def update_priorities(self, idxes, priorities): """Update priorities of sampled transitions. sets priority of transition at index idxes[i] in buffer to priorities[i]. Parameters ---------- idxes: [int] List of idxes of sampled transitions priorities:...
Update priorities of sampled transitions. sets priority of transition at index idxes[i] in buffer to priorities[i]. Parameters ---------- idxes: [int] List of idxes of sampled transitions priorities: [float] List of updated priorities correspondi...
def brain_post(connection, requirements=None): """ Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises AssertionError's if the brain is not ready. :param connection: <rethinkdb.net.DefaultConnection> :param requirements:<dict> keys=Requir...
Power On Self Test for the brain. Checks that the brain is appropriately seeded and ready for use. Raises AssertionError's if the brain is not ready. :param connection: <rethinkdb.net.DefaultConnection> :param requirements:<dict> keys=Required Databases, key-values=Required Tables in each database ...
def _float(self, string): """Convert string to float Take care of numbers in exponential format """ string = self._denoise(string) exp_match = re.match(r'^[-.\d]+x10-(\d)$', string) if exp_match: exp = int(exp_match.groups()[0]) fac = 10 ** -exp ...
Convert string to float Take care of numbers in exponential format
def PSUBB(cpu, dest, src): """ Packed subtract. Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed integers of the destination operand (first operand), and stores the packed integer results in the destination operand. The sourc...
Packed subtract. Performs a SIMD subtract of the packed integers of the source operand (second operand) from the packed integers of the destination operand (first operand), and stores the packed integer results in the destination operand. The source operand can be an MMX(TM) technology register...
def needle_statistics(infile): """Reads in a needle alignment file and spits out statistics of the alignment. Args: infile (str): Alignment file name Returns: dict: alignment_properties - a dictionary telling you the number of gaps, identity, etc. """ alignments = list(AlignIO.pa...
Reads in a needle alignment file and spits out statistics of the alignment. Args: infile (str): Alignment file name Returns: dict: alignment_properties - a dictionary telling you the number of gaps, identity, etc.
def take_break(minutes: hug.types.number=5): """Enables temporarily breaking concentration""" print("") print("######################################### ARE YOU SURE? #####################################") try: for remaining in range(60, -1, -1): sys.stdout.write("\r") s...
Enables temporarily breaking concentration
def upvote(self): """ Upvote the currently selected item. """ data = self.get_selected_item() if 'likes' not in data: self.term.flash() elif getattr(data['object'], 'archived'): self.term.show_notification("Voting disabled for archived post", style...
Upvote the currently selected item.
def load_elements(self, filename): """ loads the elements from file filename """ input_data = load_b26_file(filename) if isinstance(input_data, dict) and self.elements_type in input_data: return input_data[self.elements_type] else: return {}
loads the elements from file filename
def disconnect(self): """ Ends a client authentication session, performs a logout and a clean up. """ if self.r_session: self.session_logout() self.r_session = None self.clear()
Ends a client authentication session, performs a logout and a clean up.
def my_request_classifier(environ): """ Returns one of the classifiers 'dav', 'xmlpost', or 'browser', depending on the imperative logic below""" request_method = REQUEST_METHOD(environ) if request_method in _DAV_METHODS: return "dav" useragent = USER_AGENT(environ) if useragent: ...
Returns one of the classifiers 'dav', 'xmlpost', or 'browser', depending on the imperative logic below
def _get_sockets(bots): """Connects and gathers sockets for all chatrooms""" sockets = {} #sockets[sys.stdin] = 'stdio' for bot in bots: bot.connect() sockets[bot.client.Connection._sock] = bot return sockets
Connects and gathers sockets for all chatrooms
def convert_and_combine_2_to_3(dtype, map_dict, input_dir=".", output_dir=".", data_model=None): """ Read in er_*.txt file and pmag_*.txt file in working directory. Combine the data, then translate headers from 2.5 --> 3.0. Last, write out the data in 3.0. Parameters ---------- dtype : stri...
Read in er_*.txt file and pmag_*.txt file in working directory. Combine the data, then translate headers from 2.5 --> 3.0. Last, write out the data in 3.0. Parameters ---------- dtype : string for input type (specimens, samples, sites, etc.) map_dict : dictionary with format {header2_format: he...
def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw...
Sets other specific sections
def create_all_parent_directories(ase, dirs_created, timeout=None): # type: (blobxfer.models.azure.StorageEntity, dict, int) -> None """Create all parent directories for a file :param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity :param dict dirs_created: directories already created map ...
Create all parent directories for a file :param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity :param dict dirs_created: directories already created map :param int timeout: timeout
async def load_all_aldb(self, clear=True): """Read all devices ALDB.""" for addr in self.plm.devices: await self.load_device_aldb(addr, clear)
Read all devices ALDB.
def add_factors(self, *factors): """ Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which ...
Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which is to be associated with the model. Returns...
def population_variant_regions(items, merged=False): """Retrieve the variant region BED file from a population of items. If tumor/normal, return the tumor BED file. If a population, return the BED file covering the most bases. """ def _get_variant_regions(data): out = dd.get_variant_regions...
Retrieve the variant region BED file from a population of items. If tumor/normal, return the tumor BED file. If a population, return the BED file covering the most bases.
def _insertOrGetUniqueJobNoRetries( self, conn, client, cmdLine, jobHash, clientInfo, clientKey, params, minimumWorkers, maximumWorkers, jobType, priority, alreadyRunning): """ Attempt to insert a row with the given parameters into the jobs table. Return jobID of the inserted row, or of an existing row ...
Attempt to insert a row with the given parameters into the jobs table. Return jobID of the inserted row, or of an existing row with matching client/jobHash key. The combination of client and jobHash are expected to be unique (enforced by a unique index on the two columns). NOTE: It's possibe that ...
def create(alphabet_size: int): """ Vel factory function """ def instantiate(**_): return OneHotEncodingInput(alphabet_size) return ModelFactory.generic(instantiate)
Vel factory function
def ported_string(raw_data, encoding='utf-8', errors='ignore'): """ Give as input raw data and output a str in Python 3 and unicode in Python 2. Args: raw_data: Python 2 str, Python 3 bytes or str to porting encoding: string giving the name of an encoding errors: his specifies t...
Give as input raw data and output a str in Python 3 and unicode in Python 2. Args: raw_data: Python 2 str, Python 3 bytes or str to porting encoding: string giving the name of an encoding errors: his specifies the treatment of characters which are invalid in the input encodi...
def fetch_object(self, container, obj, include_meta=False, chunk_size=None, size=None, extra_info=None): """ Fetches the object from storage. If 'include_meta' is False, only the bytes representing the stored object are returned. Note: if 'chunk_size' is defined, yo...
Fetches the object from storage. If 'include_meta' is False, only the bytes representing the stored object are returned. Note: if 'chunk_size' is defined, you must fully read the object's contents before making another request. If 'size' is specified, only the first 'size' byt...
def on_click(self, event): """ Click events - left click & scroll up/down: switch between rotations - right click: apply selected rotation """ button = event["button"] if button in [1, 4, 5]: self.scrolling = True self._switch_selec...
Click events - left click & scroll up/down: switch between rotations - right click: apply selected rotation
def find_all_sift(im_source, im_search, min_match_count=4, maxcnt=0): ''' 使用sift算法进行多个相同元素的查找 Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 maxcnt: 限制匹配的数量 Returns: A tuple of found [(point, rectangle), ...] A t...
使用sift算法进行多个相同元素的查找 Args: im_source(string): 图像、素材 im_search(string): 需要查找的图片 threshold: 阈值,当相识度小于该阈值的时候,就忽略掉 maxcnt: 限制匹配的数量 Returns: A tuple of found [(point, rectangle), ...] A tuple of found [{"point": point, "rectangle": rectangle, "confidence": 0.76}, ...] ...
def _adapt_response(self, response): """Convert error responses to standardized ErrorDetails.""" if 'application/json' in response.headers['content-type']: body = response.json() status = response.status_code if body.get('error'): return self._simple_...
Convert error responses to standardized ErrorDetails.
def enqueue(self, klass, *args): """Enqueue a job into a specific queue. Make sure the class you are passing has **queue** attribute and a **perform** method on it. """ queue = getattr(klass,'queue', None) if queue: class_name = '%s.%s' % (klass.__module__, klass.__n...
Enqueue a job into a specific queue. Make sure the class you are passing has **queue** attribute and a **perform** method on it.
def facts(self, name=None, value=None, **kwargs): """Query for facts limited by either name, value and/or query. :param name: (Optional) Only return facts that match this name. :type name: :obj:`string` :param value: (Optional) Only return facts of `name` that\ match this va...
Query for facts limited by either name, value and/or query. :param name: (Optional) Only return facts that match this name. :type name: :obj:`string` :param value: (Optional) Only return facts of `name` that\ match this value. Use of this parameter requires the `name`\ p...
def _get_plotL(self, Lplot='Tot', proj='All', ind=None, multi=False): """ Get the (R,Z) coordinates of the cross-section projections """ ind = self._check_indch(ind) if ind.size>0: Ds, us = self.D[:,ind], self.u[:,ind] if ind.size==1: Ds, us = Ds.reshape((...
Get the (R,Z) coordinates of the cross-section projections
def get_prediction_results(model_dir_or_id, data, headers, img_cols=None, cloud=False, with_source=True, show_image=True): """ Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely i...
Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely in Datalab. Args: model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True. data: Can be a list of dictionaries, ...
def ensure_dtype(core, dtype, dtype_): """Ensure dtype is correct.""" core = core.copy() if dtype is None: dtype = dtype_ if dtype_ == dtype: return core, dtype for key, val in { int: chaospy.poly.typing.asint, float: chaospy.poly.typing.asfloat, ...
Ensure dtype is correct.
def apply(self, doc, clear, **kwargs): """Extract mentions from the given Document. :param doc: A document to process. :param clear: Whether or not to clear the existing database entries. """ # Reattach doc with the current session or DetachedInstanceError happens doc =...
Extract mentions from the given Document. :param doc: A document to process. :param clear: Whether or not to clear the existing database entries.
def paint(self, p, *args): ''' I have no idea why, but we need to generate the picture after painting otherwise it draws incorrectly. ''' if self.picturenotgened: self.generatePicture(self.getBoundingParents()[0].rect()) self.picturenotgened = False ...
I have no idea why, but we need to generate the picture after painting otherwise it draws incorrectly.
def _EccZmaxRperiRap(self,*args,**kwargs): """ NAME: EccZmaxRperiRap (_EccZmaxRperiRap) PURPOSE: evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation INPUT: Either: a) R,vR,vT,z,vz[,phi...
NAME: EccZmaxRperiRap (_EccZmaxRperiRap) PURPOSE: evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single obj...
def collect_blame_info(cls, matches): """Runs git blame on files, for the specified sets of line ranges. If no line range tuples are provided, it will do all lines. """ old_area = None for filename, ranges in matches: area, name = os.path.split(filename) ...
Runs git blame on files, for the specified sets of line ranges. If no line range tuples are provided, it will do all lines.
def do_bp(self, arg): """ [~process] bp <address> - set a code breakpoint """ pid = self.get_process_id_from_prefix() if not self.debug.is_debugee(pid): raise CmdError("target process is not being debugged") process = self.get_process(pid) token_li...
[~process] bp <address> - set a code breakpoint
def connectionMade(self): """ establish the address of this new connection and add it to the list of sockets managed by the dispatcher reply to the transport with a "setup_connection" notice containing the recipient's address for use by the client as a return address for...
establish the address of this new connection and add it to the list of sockets managed by the dispatcher reply to the transport with a "setup_connection" notice containing the recipient's address for use by the client as a return address for future communications
def reference_axis_from_chains(chains): """Average coordinates from a set of primitives calculated from Chains. Parameters ---------- chains : list(Chain) Returns ------- reference_axis : numpy.array The averaged (x, y, z) coordinates of the primitives for the list of Chain...
Average coordinates from a set of primitives calculated from Chains. Parameters ---------- chains : list(Chain) Returns ------- reference_axis : numpy.array The averaged (x, y, z) coordinates of the primitives for the list of Chains. In the case of a coiled coil barrel, ...
def _process_args(self, largs, rargs, values): """_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is fals...
_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumu...
def get_local_file(file): """ Get a local version of the file, downloading it from the remote storage if required. The returned value should be used as a context manager to ensure any temporary files are cleaned up afterwards. """ try: with open(file.path): yield file.path ...
Get a local version of the file, downloading it from the remote storage if required. The returned value should be used as a context manager to ensure any temporary files are cleaned up afterwards.
def _encode_resp(self, value): """Dynamically build the RESP payload based upon the list provided. :param mixed value: The list of command parts to encode :rtype: bytes """ if isinstance(value, bytes): return b''.join( [b'$', ascii(l...
Dynamically build the RESP payload based upon the list provided. :param mixed value: The list of command parts to encode :rtype: bytes
def makefile(self, tarinfo, targetpath): """Make a file called targetpath. """ source = self.fileobj source.seek(tarinfo.offset_data) target = bltn_open(targetpath, "wb") if tarinfo.sparse is not None: for offset, size in tarinfo.sparse: target...
Make a file called targetpath.
def read_model_from_config(cp, ifo, section="calibration"): """Returns an instance of the calibration model specified in the given configuration file. Parameters ---------- cp : WorflowConfigParser An open config file to read. ifo : string The detector (H1, L1) whose model will...
Returns an instance of the calibration model specified in the given configuration file. Parameters ---------- cp : WorflowConfigParser An open config file to read. ifo : string The detector (H1, L1) whose model will be loaded. section : {"calibration", string} Section n...
def _output_pins(self, pins): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ [self._validate_channel(pin) for pin in pins.keys()] # Set e...
Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values.
def on_window_losefocus(self, window, event): """Hides terminal main window when it loses the focus and if the window_losefocus gconf variable is True. """ if not HidePrevention(self.window).may_hide(): return value = self.settings.general.get_boolean('window-losefoc...
Hides terminal main window when it loses the focus and if the window_losefocus gconf variable is True.
def calc_time(self) -> None: """ Prints statistics about the the total duration of recordings in the corpus. """ def get_number_of_frames(feat_fns): """ fns: A list of numpy files which contain a number of feature frames. """ total = 0 ...
Prints statistics about the the total duration of recordings in the corpus.
def get_all_if_set(self): """Return all the addresses and opaque values set in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been set in the context. """ with self._lock: resu...
Return all the addresses and opaque values set in the context. Useful in the squash method. Returns: (dict of str to bytes): The addresses and bytes that have been set in the context.
def _must_not_custom_query(issn): """ Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como restrição "must_not". A lista de filtros é coletada do template de pesquisa customizada do periódico, quanto este templ...
Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como restrição "must_not". A lista de filtros é coletada do template de pesquisa customizada do periódico, quanto este template existir.
def _bulk_op(self, record_id_iterator, op_type, index=None, doc_type=None): """Index record in Elasticsearch asynchronously. :param record_id_iterator: Iterator that yields record UUIDs. :param op_type: Indexing operation (one of ``index``, ``create``, ``delete`` or ``update``). ...
Index record in Elasticsearch asynchronously. :param record_id_iterator: Iterator that yields record UUIDs. :param op_type: Indexing operation (one of ``index``, ``create``, ``delete`` or ``update``). :param index: The Elasticsearch index. (Default: ``None``) :param doc_type...
def print_graphic_information(self, num_curve, information): """ This function displays information about curves. Inputs ; num_curve ; The index of the curve's line that we have to display. information ; The array which contains the information, of all curves to display. ...
This function displays information about curves. Inputs ; num_curve ; The index of the curve's line that we have to display. information ; The array which contains the information, of all curves to display.
def __parse_scanned_version_info(self): """Parses the environment's formatted version info string.""" string = self.sys_version_info_formatted try: major, minor, micro, release_level, serial = string.split(",") if (release_level in ("alfa", "beta", "candidate", "fina...
Parses the environment's formatted version info string.
def refresh( self ): """ Refreshs the current user interface to match the latest settings. """ schemas = self.schemas() self.blockSignals(True) self.clear() self.addItems([schema.name() for schema in schemas]) self.blockSignals(False)
Refreshs the current user interface to match the latest settings.
def _find_block(starts, ends, cur_block, rec_num): # @NoSelf ''' Finds the block that rec_num is in if it is found. Otherwise it returns -1. It also returns the block that has the physical data either at or preceeding the rec_num. It could be -1 if the preceeding block does not...
Finds the block that rec_num is in if it is found. Otherwise it returns -1. It also returns the block that has the physical data either at or preceeding the rec_num. It could be -1 if the preceeding block does not exists.
def generate_parsers(config, paths): """ Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output fr...
Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output from :func:`.select_best_paths`. Returns: ...
def _delete(self, vid=None): """ Deletes given dataset from index. Args: vid (str): dataset vid. """ assert vid is not None query = text(""" DELETE FROM dataset_index WHERE vid = :vid; """) self.execute(query, vid=vid)
Deletes given dataset from index. Args: vid (str): dataset vid.
def delete(stack_ref: List[str], region: str, dry_run: bool, force: bool, remote: str): """Delete Cloud Formation stacks""" lizzy = setup_lizzy_client(remote) stack_refs = get_stack_refs(stack_ref) all_with_version = all(stack.version is not None for stack in stack_...
Delete Cloud Formation stacks
def evaluate_expression(dbg, frame, expression, is_exec): '''returns the result of the evaluated expression @param is_exec: determines if we should do an exec or an eval ''' if frame is None: return # Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=254...
returns the result of the evaluated expression @param is_exec: determines if we should do an exec or an eval
def __crawler_stop(self): """Mark the crawler as stopped. Note: If :attr:`__stopped` is True, the main thread will be stopped. Every piece of code that gets executed after :attr:`__stopped` is True could cause Thread exceptions and or race conditions. """ if se...
Mark the crawler as stopped. Note: If :attr:`__stopped` is True, the main thread will be stopped. Every piece of code that gets executed after :attr:`__stopped` is True could cause Thread exceptions and or race conditions.
def set(self, e, k, v, real_k=None, check_kw_name=False): """override base to handle escape case: replace \" to " """ if self.escape: v = v.strip().replace("\\" + self.quote, self.quote) return super(kv_transformer, self).set(e, k, v, real_k=real_k, check_kw_name=check_kw_name)
override base to handle escape case: replace \" to "
def _list_resource(self, resource): """ List all instances of the given resource type. Use the specific list_<resource>() methods instead: list_collections() list_experiments() list_channels() list_coordinate_frames() Args: re...
List all instances of the given resource type. Use the specific list_<resource>() methods instead: list_collections() list_experiments() list_channels() list_coordinate_frames() Args: resource (intern.resource.boss.BossResource): resource.nam...
def tags(self): """ Returns a list of tuples with key-value pairs representing tags in this todo item. """ tags = self.fields['tags'] return [(t, v) for t in tags for v in tags[t]]
Returns a list of tuples with key-value pairs representing tags in this todo item.
def delete_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, delete the event source mapping Returns {deleted: true} if t...
Given an event source mapping ID or an event source ARN and FunctionName, delete the event source mapping Returns {deleted: true} if the mapping was deleted and returns {deleted: false} if the mapping was not deleted. CLI Example: .. code-block:: bash salt myminion boto_lambda.delete_eve...
def search_metadata_sql_builder(search): """ Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given :class:`meteorpi_model.ObservatoryMetadataSearch`. This can then be used to retrieve the results of the search, materialise them into :class:`meteorpi_model.ObservatoryMetadata` in...
Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given :class:`meteorpi_model.ObservatoryMetadataSearch`. This can then be used to retrieve the results of the search, materialise them into :class:`meteorpi_model.ObservatoryMetadata` instances etc. :param ObservatoryMetadataSearch se...
def rename_tab_uuid(self, term_uuid, new_text, user_set=True): """Rename an already added tab by its UUID """ term_uuid = uuid.UUID(term_uuid) page_index, = ( index for index, t in enumerate(self.get_notebook().iter_terminals()) if t.get_uuid() == term_uuid ...
Rename an already added tab by its UUID
def _get_reference_band(self, data): """ Extract the max-ratio band from time-series The max-ratio is defined as max(NIR,SWIR1)/BLUE :param data: 4D array from which to compute the max-ratio reference band :type data: numpy array :return: 3D array containing the...
Extract the max-ratio band from time-series The max-ratio is defined as max(NIR,SWIR1)/BLUE :param data: 4D array from which to compute the max-ratio reference band :type data: numpy array :return: 3D array containing the max-ratio reference band
def fit(self, X, lengths=None): """Estimate model parameters. An initialization step is performed before entering the EM algorithm. If you want to avoid this step for a subset of the parameters, pass proper ``init_params`` keyword argument to estimator's constructor. Pa...
Estimate model parameters. An initialization step is performed before entering the EM algorithm. If you want to avoid this step for a subset of the parameters, pass proper ``init_params`` keyword argument to estimator's constructor. Parameters ---------- X : arr...
def run_cell(self, code, cell_name, filename, run_cell_copy): """Run cell in current or dedicated client.""" def norm(text): return remove_backslashes(to_text_string(text)) self.run_cell_filename = filename # Select client to execute code on it client = se...
Run cell in current or dedicated client.
def address_from_digest(digest): # type: (Digest) -> Address """ Generates an address from a private key digest. """ address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: List[int] sponge = Kerl() sponge.absorb(digest.as_trits()) sponge.squeeze(a...
Generates an address from a private key digest.
def normalize_profile(in_profile, log=False, return_offset = True): """return a normalized version of a profile matrix Parameters ---------- in_profile : np.array shape Lxq, will be normalized to one across each row log : bool, optional treat the input as log probabilities retur...
return a normalized version of a profile matrix Parameters ---------- in_profile : np.array shape Lxq, will be normalized to one across each row log : bool, optional treat the input as log probabilities return_offset : bool, optional return the log of the scale factor for ea...
def gen_random_string(str_len): """ generate random string with specified length """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str_len))
generate random string with specified length
def combinations_with_replacement(iterable, r): """ This function acts as a replacement for the itertools.combinations_with_replacement function. The original does not replace items that come earlier in the provided iterator. """ stk = [[i,] for i in iterable] pop = stk.pop while len...
This function acts as a replacement for the itertools.combinations_with_replacement function. The original does not replace items that come earlier in the provided iterator.
def make_color_legend_rects(colors, labels=None): """ Make list of rectangles and labels for making legends. Parameters ---------- colors : pandas.Series or list Pandas series whose values are colors and index is labels. Alternatively, you can provide a list with colors and provide...
Make list of rectangles and labels for making legends. Parameters ---------- colors : pandas.Series or list Pandas series whose values are colors and index is labels. Alternatively, you can provide a list with colors and provide the labels as a list. labels : list If co...
def _get_ip_public(self, queue_target, url, json=False, key=None): """Request the url service and put the result in the queue_target.""" try: response = urlopen(url, timeout=self.timeout).read().decode('utf-8') except Exception as e: logger.debug("IP plugin - Cannot open ...
Request the url service and put the result in the queue_target.
def recv(self, size): """Receive message of a size from the socket.""" return self._safe_call( True, super(SSLFileobjectMixin, self).recv, size, )
Receive message of a size from the socket.
async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could...
|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. ...
def max_sharpe(self, risk_free_rate=0.02): """ Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio, as it is the tangent to the efficient frontier curve that intercepts the risk-free rate. :param risk_free_rate: risk-free rate of borrowing/lending...
Maximise the Sharpe Ratio. The result is also referred to as the tangency portfolio, as it is the tangent to the efficient frontier curve that intercepts the risk-free rate. :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02 :type risk_free_rate: float, optiona...
def get_solr_search_url(self, use_amigo=False): """ Return solr URL to be used for lexical entity searches A solr search URL is used to search entities/concepts based on a limited set of parameters. Arguments --------- use_amigo : bool If true, get the URL f...
Return solr URL to be used for lexical entity searches A solr search URL is used to search entities/concepts based on a limited set of parameters. Arguments --------- use_amigo : bool If true, get the URL for the GO/AmiGO instance of GOlr. This is typically used for categor...
def load_json_model(filename): """ Load a cobra model from a file in JSON format. Parameters ---------- filename : str or file-like File path or descriptor that contains the JSON document describing the cobra model. Returns ------- cobra.Model The cobra model as...
Load a cobra model from a file in JSON format. Parameters ---------- filename : str or file-like File path or descriptor that contains the JSON document describing the cobra model. Returns ------- cobra.Model The cobra model as represented in the JSON document. See...
def conditionally_attach_managed_policies(role_name, sr_entry): """ If 'aws_managed_policies' key lists the names of AWS managed policies to bind to the role, attach them to the role Args: role_name: name of the role to attach the policies to sr_entry: service registry entry """ service_type = sr_en...
If 'aws_managed_policies' key lists the names of AWS managed policies to bind to the role, attach them to the role Args: role_name: name of the role to attach the policies to sr_entry: service registry entry