code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def diffPrefsPrior(priorstring): """Parses `priorstring` and returns `prior` tuple.""" assert isinstance(priorstring, str) prior = priorstring.split(',') if len(prior) == 3 and prior[0] == 'invquadratic': [c1, c2] = [float(x) for x in prior[1 : ]] assert c1 > 0 and c2 > 0, "C1 and C2 mus...
Parses `priorstring` and returns `prior` tuple.
def spherical_sum(image, binning_factor=1.0): """Sum image values over concentric annuli. Parameters ---------- image : `DiscreteLp` element Input data whose radial sum should be computed. binning_factor : positive float, optional Reduce the number of output bins by this factor. Inc...
Sum image values over concentric annuli. Parameters ---------- image : `DiscreteLp` element Input data whose radial sum should be computed. binning_factor : positive float, optional Reduce the number of output bins by this factor. Increasing this number can help reducing fluctua...
def find_host_network_interface_by_id(self, id_p): """Searches through all host network interfaces for an interface with the given GUID. The method returns an error if the given GUID does not correspond to any host network interface. in id_p of type str GUID...
Searches through all host network interfaces for an interface with the given GUID. The method returns an error if the given GUID does not correspond to any host network interface. in id_p of type str GUID of the host network interface to search for. return ...
def _init_template(self, cls, base_init_template): '''This would be better as an override for Gtk.Widget''' # TODO: could disallow using a metaclass.. but this is good enough # .. if you disagree, feel free to fix it and issue a PR :) if self.__class__ is not cls: raise TypeError("Inheritance f...
This would be better as an override for Gtk.Widget
def from_raw(self, file_names=None, **kwargs): """Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together. """ # T...
Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together.
def init_session(self): """ Defines a session object for passing requests. """ if self.session: self.session.close() self.session = make_session(self.username, self.password, self.bearer_token, ...
Defines a session object for passing requests.
def __optimize_configuration(self): """! @brief Finds quasi-optimal medoids and updates in line with them clusters in line with algorithm's rules. """ index_neighbor = 0 while (index_neighbor < self.__maxneighbor): # get random current medoid that is ...
! @brief Finds quasi-optimal medoids and updates in line with them clusters in line with algorithm's rules.
def accuracy(self): """Get accuracy numbers for each target and overall. Returns: A DataFrame with two columns: 'class' and 'accuracy'. It also contains the overall accuracy with class being '_all'. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery ...
Get accuracy numbers for each target and overall. Returns: A DataFrame with two columns: 'class' and 'accuracy'. It also contains the overall accuracy with class being '_all'. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery does not return 'targ...
def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10): """ Displays a card showing the Creators that are associated with the most Works. e.g.: {% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %} """ object_list = most_seen_creators_by_wo...
Displays a card showing the Creators that are associated with the most Works. e.g.: {% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %}
def normalize_pred_string(predstr): """ Normalize the predicate string *predstr* to a conventional form. This makes predicate strings more consistent by removing quotes and the `_rel` suffix, and by lowercasing them. Examples: >>> normalize_pred_string('"_dog_n_1_rel"') '_dog_n_1' ...
Normalize the predicate string *predstr* to a conventional form. This makes predicate strings more consistent by removing quotes and the `_rel` suffix, and by lowercasing them. Examples: >>> normalize_pred_string('"_dog_n_1_rel"') '_dog_n_1' >>> normalize_pred_string('_dog_n_1') ...
def use(self, middleware=None, path='/', method_mask=HTTPMethod.ALL): """ Use the middleware (a callable with parameters res, req, next) upon requests match the provided path. A None path matches every request. Returns the middleware so this method may be used as a decorator. ...
Use the middleware (a callable with parameters res, req, next) upon requests match the provided path. A None path matches every request. Returns the middleware so this method may be used as a decorator. Args: middleware (callable): A function with signature '(req, res)' ...
def set_offset_and_sequence_number(self, event_data): """ Updates offset based on event. :param event_data: A received EventData with valid offset and sequenceNumber. :type event_data: ~azure.eventhub.common.EventData """ if not event_data: raise Exception(ev...
Updates offset based on event. :param event_data: A received EventData with valid offset and sequenceNumber. :type event_data: ~azure.eventhub.common.EventData
def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return super(Search, self).get_template_names()
Dispatch template according to the kind of request: ajax or normal.
def getPlatformsByName(platformNames=['all'], mode=None, tags=[], excludePlatformNames=[]): """Method that recovers the names of the <Platforms> in a given list. :param platformNames: List of strings containing the possible platforms. :param mode: The mode of the search. The following can be ...
Method that recovers the names of the <Platforms> in a given list. :param platformNames: List of strings containing the possible platforms. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. :param tags: Just in case the method to select...
def load_history(self, f): """Load the history of a ``NeuralNet`` from a json file. See ``save_history`` for examples. Parameters ---------- f : file-like object or str """ # TODO: Remove warning in a future release warnings.warn( "load_histo...
Load the history of a ``NeuralNet`` from a json file. See ``save_history`` for examples. Parameters ---------- f : file-like object or str
def configuration(self, event): """Return all configurable components' schemata""" try: self.log("Schemarequest for all configuration schemata from", event.user.account.name, lvl=debug) response = { 'component': 'hfos.events.schemamanager', ...
Return all configurable components' schemata
def set_paths(etc_paths = [ "/etc/" ]): """ Sets the paths where the configuration files will be searched * You can have multiple configuration files (e.g. in the /etc/default folder and in /etc/appfolder/) """ global _ETC_PATHS _ETC_PATHS = [] for p in etc_paths: ...
Sets the paths where the configuration files will be searched * You can have multiple configuration files (e.g. in the /etc/default folder and in /etc/appfolder/)
def is_carrying_minerals(self) -> bool: """ Checks if a worker or MULE is carrying (gold-)minerals. """ return any( buff.value in self._proto.buff_ids for buff in {BuffId.CARRYMINERALFIELDMINERALS, BuffId.CARRYHIGHYIELDMINERALFIELDMINERALS} )
Checks if a worker or MULE is carrying (gold-)minerals.
def map_tree(visitor, tree): """Apply function to nodes""" newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
Apply function to nodes
def _make_lcdproc( lcd_host, lcd_port, retry_config, charset=DEFAULT_LCDPROC_CHARSET, lcdd_debug=False): """Create and connect to the LCDd server. Args: lcd_host (str): the hostname to connect to lcd_prot (int): the port to connect to charset (str): the charset to use wh...
Create and connect to the LCDd server. Args: lcd_host (str): the hostname to connect to lcd_prot (int): the port to connect to charset (str): the charset to use when sending messages to lcdproc lcdd_debug (bool): whether to enable full LCDd debug retry_attempts (int): the nu...
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
Required that the user is not logged in.
def remove_record(self, orcid_id, token, request_type, put_code): """Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token received from OAuth 2 3-legged authorization. :param request...
Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token received from OAuth 2 3-legged authorization. :param request_type: string One of 'activities', 'education', 'employment', 'fu...
def get_all_objects(self): "Return pointers to all GC tracked objects" for i, generation in enumerate(self.gc_generations): generation_head_ptr = pygc_head_ptr = generation.head.get_pointer() generation_head_addr = generation_head_ptr._value while True: ...
Return pointers to all GC tracked objects
def native(self, value, context=None): """Convert the given string into a list of substrings.""" separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator value = super().native(value, context) if value is None: return self.cast() if hasattr(value, '...
Convert the given string into a list of substrings.
def get_assessments_taken_by_query(self, assessment_taken_query): """Gets a list of ``AssessmentTaken`` elements matching the given assessment taken query. arg: assessment_taken_query (osid.assessment.AssessmentTakenQuery): the assessment taken query return: (...
Gets a list of ``AssessmentTaken`` elements matching the given assessment taken query. arg: assessment_taken_query (osid.assessment.AssessmentTakenQuery): the assessment taken query return: (osid.assessment.AssessmentTakenList) - the returned ``Assessm...
def is_transaction_invalidated(transaction, state_change): """ True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidat...
True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local trans...
def _register_namespace_and_command(self, namespace): """Add a Namespace and the corresponding command namespace.""" self._add_namespace(namespace) # Add the namespace for commands on this database cmd_name = namespace.source_name.split(".", 1)[0] + ".$cmd" dest_cmd_name = namesp...
Add a Namespace and the corresponding command namespace.
def add_arguments(parser): """ Args for the init command """ parser.add_argument('-e', '--environment', help='Environment name', required=False, nargs='+') parser.add_argument('-w', '--dont-wait', help='Skip waiting for the app to be deleted', action='store_true')
Args for the init command
def get_weather_data(filename='weather.csv', **kwargs): r""" Imports weather data from a file. The data include wind speed at two different heights in m/s, air temperature in two different heights in K, surface roughness length in m and air pressure in Pa. The file is located in the example folder ...
r""" Imports weather data from a file. The data include wind speed at two different heights in m/s, air temperature in two different heights in K, surface roughness length in m and air pressure in Pa. The file is located in the example folder of the windpowerlib. The height in m for which the data ...
def match(self, data, threshold=0.5, generator=False): # pragma: no cover """Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the...
Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the same entity and the confidence score is a measure of our confidence that all ...
def main(argv=None): '''Parse command line options and create a server/volume composite.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) ...
Parse command line options and create a server/volume composite.
def create_anisomagplot(plotman, x, y, z, alpha, options): '''Plot the data of the tomodir in one overview plot. ''' sizex, sizez = getfigsize(plotman) # create figure f, ax = plt.subplots(2, 3, figsize=(3 * sizex, 2 * sizez)) if options.title is not None: plt.suptitle(options.title, fon...
Plot the data of the tomodir in one overview plot.
def _get_area_data(self): """Get histogram list based on area type. List pattern: [type1_hel+,type2_hel+,type1_hel-,type2_hel-] where type1/2 = F/B or R/L in that order. """ if self.mode == '1n': data = [self.hist['NBMF+'].data,\ self.his...
Get histogram list based on area type. List pattern: [type1_hel+,type2_hel+,type1_hel-,type2_hel-] where type1/2 = F/B or R/L in that order.
def statistic_recommend(classes, P): """ Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list """ if imbal...
Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list
def do_alias(self, arg): """alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the param...
alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the ...
def novatel_diag_send(self, timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails, force_mavlink1=False): ''' Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMSta...
Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus ...
def serialize(self, subject, *objects_or_combinators): """ object_combinators may also be URIRefs or Literals """ ec_s = rdflib.BNode() if self.operator is not None: if subject is not None: yield subject, self.predicate, ec_s yield from oc(ec_s) ...
object_combinators may also be URIRefs or Literals
def in_telephones(objet, pattern): """ abstractSearch dans une liste de téléphones.""" objet = objet or [] if pattern == '' or not objet: return False return max(bool(re.search(pattern, t)) for t in objet)
abstractSearch dans une liste de téléphones.
def replace_greek_tex(self, name): """Replace text representing greek letters with greek letters.""" name = name.replace('gamma-delta', 'gammadelta') name = name.replace('interleukin-1 beta', 'interleukin-1beta') # greek_present = False for greek_txt, tex in self.greek2tex.items(...
Replace text representing greek letters with greek letters.
def json(self): """ return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time. """ if self.fresh(): return self.__cached_json # noinspection PyAttributeOutsideInit self._...
return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time.
def _initGP(self): """ Internal method for initialization of the GP inference objetct """ if self._inference=='GP2KronSum': signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0] gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs,...
Internal method for initialization of the GP inference objetct
def is_client_ip_address_whitelisted(request: AxesHttpRequest): """ Check if the given request refers to a whitelisted IP. """ if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_...
Check if the given request refers to a whitelisted IP.
def divide(self, layer=WORDS, by=SENTENCES): """Divide the Text into pieces by keeping references to original elements, when possible. This is not possible only, if the _element_ is a multispan. Parameters ---------- element: str The element to collect and distribut...
Divide the Text into pieces by keeping references to original elements, when possible. This is not possible only, if the _element_ is a multispan. Parameters ---------- element: str The element to collect and distribute in resulting bins. by: str Each re...
def pvfactors_timeseries( solar_azimuth, solar_zenith, surface_azimuth, surface_tilt, timestamps, dni, dhi, gcr, pvrow_height, pvrow_width, albedo, n_pvrows=3, index_observed_pvrow=1, rho_front_pvrow=0.03, rho_back_pvrow=0.05, horizon_band_angle=15., run_parallel_calculat...
Calculate front and back surface plane-of-array irradiance on a fixed tilt or single-axis tracker PV array configuration, and using the open-source "pvfactors" package. Please refer to pvfactors online documentation for more details: https://sunpower.github.io/pvfactors/ Parameters ---------- ...
def _update_state(self, change): """ Keep position and direction in sync with axis """ self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
Keep position and direction in sync with axis
def load(self, wishlist, calibration=None, resolution=None, polarization=None, level=None, generate=True, unload=True, **kwargs): """Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` ob...
Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` objects with every parameter specified or they can not provide certain parameters and the "best" parameter will be chosen. For example, if a dataset is a...
def _to_topology(self, atom_list, chains=None, residues=None): """Create a mdtraj.Topology from a Compound. Parameters ---------- atom_list : list of mb.Compound Atoms to include in the topology chains : mb.Compound or list of mb.Compound Chain types to a...
Create a mdtraj.Topology from a Compound. Parameters ---------- atom_list : list of mb.Compound Atoms to include in the topology chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Label...
async def _create_transaction(self, msg, *args, **kwargs): """ Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `r...
Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `register_transaction`
def to_dict(self): """Returns the Time instance as a usable dictionary for craftai""" return { "timestamp": int(self.timestamp), "timezone": self.timezone, "time_of_day": self.time_of_day, "day_of_week": self.day_of_week, "day_of_month": self.day_of_month, "month_of_year": se...
Returns the Time instance as a usable dictionary for craftai
def _req_rep_retry(self, request): """Returns response and number of retries""" retries_left = self.RETRIES while retries_left: self._logger.log(1, 'Sending REQ `%s`', request) self._send_request(request) socks = dict(self._poll.poll(self.TIMEOUT)) ...
Returns response and number of retries
def get_value(cls, bucket, key): """Get tag value.""" obj = cls.get(bucket, key) return obj.value if obj else None
Get tag value.
def _list_machines(self): """ Request a list of all added machines. Populates self._machines dict with mist.client.model.Machine instances """ try: req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines') machines = req.get().json() ...
Request a list of all added machines. Populates self._machines dict with mist.client.model.Machine instances
def to_timepoints(self, unit='hours', offset=None): """Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in h...
Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in hours: >>> from hydpy import Timegrid >>> timeg...
def repartition(self, num_partitions, repartition_function=None): """Return a new Streamlet containing all elements of the this streamlet but having num_partitions partitions. Note that this is different from num_partitions(n) in that new streamlet will be created by the repartition call. If repartiton_...
Return a new Streamlet containing all elements of the this streamlet but having num_partitions partitions. Note that this is different from num_partitions(n) in that new streamlet will be created by the repartition call. If repartiton_function is not None, it is used to decide which parititons (from 0 t...
def map_to_subset(self, file, outfile=None, ontology=None, subset=None, class_map=None, relations=None): """ Map a file to a subset, writing out results You can pass either a subset name (e.g. goslim_generic) or a dictionary with ready-made mappings Arguments --------- ...
Map a file to a subset, writing out results You can pass either a subset name (e.g. goslim_generic) or a dictionary with ready-made mappings Arguments --------- file: file Name or file object for input assoc file outfile: file Name or file object for out...
def merge(self, other): """ Copy properties from other into self, skipping ``None`` values. Also merges the raw data. Args: other (SkypeObj): second object to copy fields from """ for attr in self.attrs: if not getattr(other, attr, None) is None: ...
Copy properties from other into self, skipping ``None`` values. Also merges the raw data. Args: other (SkypeObj): second object to copy fields from
def get_series_episodes(self, id, page=1): """Get series episodes""" # perform the request params = {'page': page} r = self.session.get(self.base_url + '/series/{}/episodes'.format(id), params=params) if r.status_code == 404: return None r.raise_for_status() ...
Get series episodes
def _simplify(elements): """Simplifies and normalizes the list of elements removing redundant/repeated elements and normalising upper/lower case so case sensitivity is resolved here.""" simplified = [] previous = None for element in elements: if element == ".....
Simplifies and normalizes the list of elements removing redundant/repeated elements and normalising upper/lower case so case sensitivity is resolved here.
def to_kwargs(triangles): """ Convert a list of triangles to the kwargs for the Trimesh constructor. Parameters --------- triangles : (n, 3, 3) float Triangles in space Returns --------- kwargs : dict Keyword arguments for the trimesh.Trimesh constructor Includes ...
Convert a list of triangles to the kwargs for the Trimesh constructor. Parameters --------- triangles : (n, 3, 3) float Triangles in space Returns --------- kwargs : dict Keyword arguments for the trimesh.Trimesh constructor Includes keys 'vertices' and 'faces' Examp...
def infer(examples, alt_rules=None): """ Returns a datetime.strptime-compliant format string for parsing the *most likely* date format used in examples. examples is a list containing example date strings. """ date_classes = _tag_most_likely(examples) if alt_rules: date_classes = _apply_...
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format used in examples. examples is a list containing example date strings.
def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int: """Adds a column to an existing table.""" sql = "ALTER TABLE {} ADD COLUMN {}".format( tablename, self.fielddefsql_from_fieldspec(fieldspec)) log.info(sql) return self.db_exec_literal(sql)
Adds a column to an existing table.
def unicode_dict(_dict): """ Make sure keys and values of dict is unicode. """ r = {} for k, v in iteritems(_dict): r[unicode_obj(k)] = unicode_obj(v) return r
Make sure keys and values of dict is unicode.
def take(self, axis, n): """Take the first (or last) n rows or columns from the blocks Note: Axis = 0 will be equivalent to `head` or `tail` Axis = 1 will be equivalent to `front` or `back` Args: axis: The axis to extract (0 for extracting rows, 1 for extracting colum...
Take the first (or last) n rows or columns from the blocks Note: Axis = 0 will be equivalent to `head` or `tail` Axis = 1 will be equivalent to `front` or `back` Args: axis: The axis to extract (0 for extracting rows, 1 for extracting columns) n: The number of row...
def getAdjEdges(self, networkId, nodeId, verbose=None): """ Returns a list of connected edges as SUIDs for the node specified by the `nodeId` and `networkId` parameters. :param networkId: SUID of the network containing the node :param nodeId: SUID of the node :param verbose: pri...
Returns a list of connected edges as SUIDs for the node specified by the `nodeId` and `networkId` parameters. :param networkId: SUID of the network containing the node :param nodeId: SUID of the node :param verbose: print more :returns: 200: successful operation
def verify_hash_type(self): ''' Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return: ''' if self.config['hash_type'].lower() in ['md5', 'sha1']: log.warning( 'IMPORTANT: Do not use %s hashing algorithm! Please set ' ...
Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return:
def add_to_products(self, products=None, all_products=False): """ Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify produc...
Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_produ...
def _todict(cls): """ generate a dict keyed by value """ return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
generate a dict keyed by value
def model_config_from_estimator(instance_type, estimator, task_id, task_type, role=None, image=None, name=None, model_server_workers=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT): """Export Airflow model config from a SageMaker estimator Args: instance_type (st...
Export Airflow model config from a SageMaker estimator Args: instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge' estimator (sagemaker.model.EstimatorBase): The SageMaker estimator to export Airflow config from. It has to be an estimator associ...
def ChunkedTransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, chunk_selector=None, max_...
Transformer language model operating on chunks. The input to this model is a sequence presented as a list or tuple of chunks: (chunk1, chunk2, chunks3, ..., chunkN). Each chunk should have the same shape (batch, chunk-length) and together they represent a long sequence that's a concatenation chunk1,chunk2,....
def _parse_commit(self, ref): """Parse a commit command.""" lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b'commit', b'author', False) more_authors = [] while True: another_author = self._get_user_info(b'commit', b'author', ...
Parse a commit command.
def from_symmop(cls, symmop, time_reversal): """ Initialize a MagSymmOp from a SymmOp and time reversal operator. Args: symmop (SymmOp): SymmOp time_reversal (int): Time reversal operator, +1 or -1. Returns: MagSymmOp object "...
Initialize a MagSymmOp from a SymmOp and time reversal operator. Args: symmop (SymmOp): SymmOp time_reversal (int): Time reversal operator, +1 or -1. Returns: MagSymmOp object
def _cmd_up(self): """Upgrade to a revision""" revision = self._get_revision() if not self._rev: self._log(0, "upgrading current revision") else: self._log(0, "upgrading from revision %s" % revision) for rev in self._revisions[int(revision) - 1:]: ...
Upgrade to a revision
def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ ls1, ls2 = len(str1), len(str2) if str1.isdigit(): # 10 SM if str2 in ['SM', '0SM']: return True # 12 /10 if ls2 > 2 and str2[0] ...
Return True if a space shouldn't exist between two items
def _count_extra_actions(self, game_image): """Count the number of extra actions for player in this turn.""" proportional = self._bonus_tools['extra_action_region'] # Use ProportionalRegion to isolate the extra actions area t, l, b, r = proportional.region_in(game_image) token_re...
Count the number of extra actions for player in this turn.
def remove_secondary_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, assoc_with=None): """Remove all secondary linked files that match all the criteria, criterias that are ``None`` are ignored. ...
Remove all secondary linked files that match all the criteria, criterias that are ``None`` are ignored. :param str file_path: Path of the file. :param str relpath: Relative filepath. :param str mimetype: Mimetype of the file. :param int time_origin: Time origin. :param s...
def DeleteOldRuns(self, cutoff_timestamp=None): """Deletes runs that were started before the timestamp given.""" if cutoff_timestamp is None: raise ValueError("cutoff_timestamp can't be None") return data_store.REL_DB.DeleteOldCronJobRuns( cutoff_timestamp=cutoff_timestamp)
Deletes runs that were started before the timestamp given.
def getDuration(self): """Returns the time in minutes taken for this analysis. If the analysis is not yet 'ready to process', returns 0 If the analysis is still in progress (not yet verified), duration = date_verified - date_start_process Otherwise: duration = cur...
Returns the time in minutes taken for this analysis. If the analysis is not yet 'ready to process', returns 0 If the analysis is still in progress (not yet verified), duration = date_verified - date_start_process Otherwise: duration = current_datetime - date_start_process...
def compile_id_list(self, polygon_id_list, nr_of_polygons): """ sorts the polygons_id list from least to most occurrences of the zone ids (->speed up) only 4.8% of all shortcuts include polygons from more than one zone but only for about 0.4% sorting would be beneficial (zones have diffe...
sorts the polygons_id list from least to most occurrences of the zone ids (->speed up) only 4.8% of all shortcuts include polygons from more than one zone but only for about 0.4% sorting would be beneficial (zones have different frequencies) in most of those cases there are only two types of zon...
def _WsdlHasMethod(self, method_name): """Determine if a method is in the wsdl. Args: method_name: The name of the method. Returns: True if the method is in the wsdl, otherwise False. """ try: self._method_bindings.get(method_name) return True except ValueError: r...
Determine if a method is in the wsdl. Args: method_name: The name of the method. Returns: True if the method is in the wsdl, otherwise False.
def get_all_outcome_links_for_context_accounts(self, account_id, outcome_group_style=None, outcome_style=None): """ Get all outcome links for context. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" ...
Get all outcome links for context.
def connect(self): "Connect to a host on a given (SSL) port." sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) boto.log.debug("wrapping ssl socket; CA certificate file=%s", self.ca_certs) self.sock = ssl.wrap_socket(sock, keyfile=self.k...
Connect to a host on a given (SSL) port.
def get_appstruct(self): """ return list of tuples keys and values corresponding to this model's data """ result = [] for k in self._get_keys(): result.append((k, getattr(self, k))) return result
return list of tuples keys and values corresponding to this model's data
def _negotiate_SOCKS4(self, dest_addr, dest_port): """ Negotiates a connection through a SOCKS4 server. """ proxy_type, addr, port, rdns, username, password = self.proxy writer = self.makefile("wb") reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3 ...
Negotiates a connection through a SOCKS4 server.
def readGraph(edgeList, nodeList = None, directed = False, idKey = 'ID', eSource = 'From', eDest = 'To'): """Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files. This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph...
Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files. This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph()](#metaknowledge.graphHelpers.writeGraph), if this does not produce the desired results the networkx builtin [n...
def SensorShare(self, sensor_id, parameters): """ Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor...
Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor call was successful
def find_matching_builtin(self, node): """ Return matched keyword. If the node alias on a correct keyword (and only it), it matches. """ for path in EQUIVALENT_ITERATORS.keys(): correct_alias = {path_to_node(path)} if self.aliases[node.func] == correct_al...
Return matched keyword. If the node alias on a correct keyword (and only it), it matches.
def redact_http_basic_auth(output): ''' Remove HTTP user and password ''' # We can't use re.compile because re.compile(someregex).sub() doesn't # support flags even in Python 2.7. url_re = '(https?)://.*@' redacted = r'\1://<redacted>@' if sys.version_info >= (2, 7): # re.sub() s...
Remove HTTP user and password
def _load_schemas(self): """ load all schemas into schema dict """ types = ('bill', 'committee', 'person', 'vote', 'event') for type in types: schema_path = os.path.join(os.path.split(__file__)[0], '../schemas/%s.json' % type) self...
load all schemas into schema dict
def triple_apply(self, triple_apply_fn, mutated_fields, input_fields=None): ''' Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to vertex data is protected by lock. The effect on th...
Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to vertex data is protected by lock. The effect on the returned SGraph is equivalent to the following pseudocode: >>> PARALLEL FOR (...
def _set_switchport_basic(self, v, load=False): """ Setter method for switchport_basic, mapped from YANG variable /interface/ethernet/switchport_basic (container) If this variable is read-only (config: false) in the source YANG file, then _set_switchport_basic is considered as a private method. Back...
Setter method for switchport_basic, mapped from YANG variable /interface/ethernet/switchport_basic (container) If this variable is read-only (config: false) in the source YANG file, then _set_switchport_basic is considered as a private method. Backends looking to populate this variable should do so via ...
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
Return a tuple with the process' RSS and VMS size.
def contains(self, x, ctrs, kdtree=None): """Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.""" return self.overlap(x, ctrs, kdtree=kdtree) > 0
Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.
def load_edbfile(file=None): """Load the targets from a file""" import ephem,string,math if file is None: import tkFileDialog try: file=tkFileDialog.askopenfilename() except: return if file is None or file == '': return f=open(file) lines=f.readl...
Load the targets from a file
def to_CAG(self): """ Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.""" G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == ...
Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.
def run_rnaseq_ann_filter(data): """Run RNA-seq annotation and filtering. """ data = to_single_data(data) if dd.get_vrn_file(data): eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0] if eff_file: data = dd.set_vrn_file(data, eff_file) ann_file = population....
Run RNA-seq annotation and filtering.
def template(self, lambda_arn, role_arn, output=None, json=False): """ Only build the template file. """ if not lambda_arn: raise ClickException("Lambda ARN is required to template.") if not role_arn: raise ClickException("Role ARN is required to templat...
Only build the template file.
def parse_sphinx_searchindex(searchindex): """Parse a Sphinx search index Parameters ---------- searchindex : str The Sphinx search index (contents of searchindex.js) Returns ------- filenames : list of str The file names parsed from the search index. objects : dict ...
Parse a Sphinx search index Parameters ---------- searchindex : str The Sphinx search index (contents of searchindex.js) Returns ------- filenames : list of str The file names parsed from the search index. objects : dict The objects parsed from the search index.
def convert(source, ext=COMPLETE, fmt=HTML, dname=None): """Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ...
Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield to pass to conversion process f...
def get_src_or_dst_prompt(mode): """ String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed """ _words = {"read": "from", "write": "to"} # print(os.getcwd()) prompt = "Where would you like to {} your file(s) {}?\n" \ ...
String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed
def deleted_records(endpoint): """Populate the ``deleted_records`` key.""" @utils.for_each_value def _deleted_records(self, key, value): deleted_recid = maybe_int(value.get('a')) if deleted_recid: return get_record_ref(deleted_recid, endpoint) return _deleted_records
Populate the ``deleted_records`` key.