code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def npz_generator(npz_path): """Generate data from an npz file.""" npz_data = np.load(npz_path) X = npz_data['X'] # Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,) y = npz_data['Y'] n = X.shape[0] while True: i = np.random.randint(0, n) yield {'X': X[i]...
Generate data from an npz file.
def version(): """ Returns a human-readable version string. For official releases, it will follow a semver style (e.g. ``1.2.7``). For dev versions, it will have the semver style first, followed by hyphenated qualifiers (e.g. ``1.2.7-dev``). Returns a string. """ short = '.'.join([str(...
Returns a human-readable version string. For official releases, it will follow a semver style (e.g. ``1.2.7``). For dev versions, it will have the semver style first, followed by hyphenated qualifiers (e.g. ``1.2.7-dev``). Returns a string.
def add_variables_from(self, linear, vartype=None): """Add variables and/or linear biases to a binary quadratic model. Args: linear (dict[variable, bias]/iterable[(variable, bias)]): A collection of variables and their linear biases to add to the model. If a ...
Add variables and/or linear biases to a binary quadratic model. Args: linear (dict[variable, bias]/iterable[(variable, bias)]): A collection of variables and their linear biases to add to the model. If a dict, keys are variables in the binary quadratic model and ...
def remove_external_references_from_roles(self): """ Removes any external references on any of the roles from the predicate """ for node_role in self.node.findall('role'): role = Crole(node_role) role.remove_external_references()
Removes any external references on any of the roles from the predicate
def nearest_overlap(self, overlap, bins): """Return nearest overlap/crop factor based on number of bins""" bins_overlap = overlap * bins if bins_overlap % 2 != 0: bins_overlap = math.ceil(bins_overlap / 2) * 2 overlap = bins_overlap / bins logger.warning('numb...
Return nearest overlap/crop factor based on number of bins
def find_bled112_devices(cls): """Look for BLED112 dongles on this computer and start an instance on each one""" found_devs = [] ports = serial.tools.list_ports.comports() for port in ports: if not hasattr(port, 'pid') or not hasattr(port, 'vid'): continue ...
Look for BLED112 dongles on this computer and start an instance on each one
def vmdk_to_ami(args): """ Calls methods to perform vmdk import :param args: :return: """ aws_importer = AWSUtilities.AWSUtils(args.directory, args.aws_profile, args.s3_bucket, args.aws_regions, args.ami_name, args.vmdk_upload_file) aws_importer.impor...
Calls methods to perform vmdk import :param args: :return:
def validate_api_call(schema, raw_request, raw_response): """ Validate the request/response cycle of an api call against a swagger schema. Request/Response objects from the `requests` and `urllib` library are supported. """ request = normalize_request(raw_request) with ErrorDict() as error...
Validate the request/response cycle of an api call against a swagger schema. Request/Response objects from the `requests` and `urllib` library are supported.
def write_from_file(library, session, filename, count): """Take data from a file and write it out synchronously. Corresponds to viWriteFromFile function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param filename:...
Take data from a file and write it out synchronously. Corresponds to viWriteFromFile function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param filename: Name of file from which data will be read. :param count: N...
def _verify( self, request, return_payload=False, verify=True, raise_missing=False, request_args=None, request_kwargs=None, *args, **kwargs ): """ If there is a "permakey", then we will verify the token by checking the d...
If there is a "permakey", then we will verify the token by checking the database. Otherwise, just do the normal verification. Typically, any method that begins with an underscore in sanic-jwt should not be touched. In this case, we are trying to break the rules a bit to handle a unique ...
def get_next_work_day(self, division=None, date=None): """ Returns the next work day, skipping weekends and bank holidays :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: datetime.date; NB...
Returns the next work day, skipping weekends and bank holidays :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: datetime.date; NB: get_next_holiday returns a dict
def _lincomb(self, a, x, b, y, out): """Linear combination ``out = a*x + b*y``.""" for space, xp, yp, outp in zip(self.spaces, x.parts, y.parts, out.parts): space._lincomb(a, xp, b, yp, outp)
Linear combination ``out = a*x + b*y``.
def _read_para_r1_counter(self, code, cbit, clen, *, desc, length, version): """Read HIP R1_COUNTER parameter. Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
Read HIP R1_COUNTER parameter. Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False): """Normalize in rows or columns. Parameters ---------- axis: int or str Along which axis to sum (numpy-sense) inplace: bool Update the object itself Returns ---...
Normalize in rows or columns. Parameters ---------- axis: int or str Along which axis to sum (numpy-sense) inplace: bool Update the object itself Returns ------- hist : Histogram2D
def get_rgb_hex(self): """ Converts the RGB value to a hex value in the form of: #RRGGBB :rtype: str """ rgb_r, rgb_g, rgb_b = self.get_upscaled_value_tuple() return '#%02x%02x%02x' % (rgb_r, rgb_g, rgb_b)
Converts the RGB value to a hex value in the form of: #RRGGBB :rtype: str
def regen_keys(): ''' Used to regenerate the minion keys. CLI Example: .. code-block:: bash salt '*' saltutil.regen_keys ''' for fn_ in os.listdir(__opts__['pki_dir']): path = os.path.join(__opts__['pki_dir'], fn_) try: os.remove(path) except os.err...
Used to regenerate the minion keys. CLI Example: .. code-block:: bash salt '*' saltutil.regen_keys
def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(ma...
Save items from list to the file.
def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None): """Convert descriptor to SQL """ # Prepare columns = [] indexes = [] fallbacks = [] constraints = [] column_mapping = {} table_name = self.convert_bucket(bucket...
Convert descriptor to SQL
def get_results(self, *, block=False, timeout=None): """Get the results of each job in the group. Parameters: block(bool): Whether or not to block until the results are stored. timeout(int): The maximum amount of time, in milliseconds, to wait for results when block is T...
Get the results of each job in the group. Parameters: block(bool): Whether or not to block until the results are stored. timeout(int): The maximum amount of time, in milliseconds, to wait for results when block is True. Defaults to 10 seconds. Raises: ...
def is_stationary(self): r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition matrix. """ # for disconnected matrices, the stationary distribution depends on the estimator, so we can't compute # it directly. Th...
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition matrix.
def get_default_config(): """ Produces a stock/out-of-the-box TidyPy configuration. :rtype: dict """ config = {} for name, cls in iteritems(get_tools()): config[name] = cls.get_default_config() try: workers = multiprocessing.cpu_count() - 1 except NotImplementedError:...
Produces a stock/out-of-the-box TidyPy configuration. :rtype: dict
def _Rzderiv(self,R,z,phi=0.,t=0.): """ NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: d2phi/dR/dz HISTORY: 2018-0...
def get_encodings_from_content(content): """ Code from: https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py Return encodings from given content string. :param content: string to extract encodings from. """ if isinstance(content, bytes): ...
Code from: https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py Return encodings from given content string. :param content: string to extract encodings from.
def __recognize_user_class(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a user-defined class in the node. This tries to recognize only exactly the specified class. It \ recurses down into the class's attributes, but not to its \ s...
Recognize a user-defined class in the node. This tries to recognize only exactly the specified class. It \ recurses down into the class's attributes, but not to its \ subclasses. See also __recognize_user_classes(). Args: node: The node to recognize. expected_ty...
def attempt_sync_with_master(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/repos/merging/#perform-a-merge """ master_sha = get_master_sha(pr.repo) remote = pr.remote_repo url = ("https://api.git...
References: https://developer.github.com/v3/repos/merging/#perform-a-merge
def rating(self, **kwargs): """ This method lets users rate a movie. A valid session id or guest session id is required. Args: session_id: see Authentication. guest_session_id: see Authentication. value: Rating value. Returns: A d...
This method lets users rate a movie. A valid session id or guest session id is required. Args: session_id: see Authentication. guest_session_id: see Authentication. value: Rating value. Returns: A dict representation of the JSON returned from the...
def twisted_absolute_path(path, request): """Hack to fix twisted not accepting absolute URIs""" parsed = urlparse.urlparse(request.uri) if parsed.scheme != '': path_parts = parsed.path.lstrip('/').split('/') request.prepath = path_parts[0:1] request.postpath = path_parts[1:] ...
Hack to fix twisted not accepting absolute URIs
def download_file(url): """ Downloads a file from the specified URL. :param str url: The URL to the file to be downloaded :returns: the downloaded file's content :rtype: str """ response = requests.get(url) if response.status_code is not 200: return None ret...
Downloads a file from the specified URL. :param str url: The URL to the file to be downloaded :returns: the downloaded file's content :rtype: str
def pdf(cls, mass, log_mode=True): """ PDF for the Salpeter IMF. Value of 'a' is set to normalize the IMF to 1 between 0.1 and 100 Msun """ alpha = 2.35 a = 0.060285569480482866 dn_dm = a * mass**(-alpha) if log_mode: # Number per logarithmic mass ...
PDF for the Salpeter IMF. Value of 'a' is set to normalize the IMF to 1 between 0.1 and 100 Msun
def ecg_wave_detector(ecg, rpeaks): """ Returns the localization of the P, Q, T waves. This function needs massive help! Parameters ---------- ecg : list or ndarray ECG signal (preferably filtered). rpeaks : list or ndarray R peaks localization. Returns ---------- e...
Returns the localization of the P, Q, T waves. This function needs massive help! Parameters ---------- ecg : list or ndarray ECG signal (preferably filtered). rpeaks : list or ndarray R peaks localization. Returns ---------- ecg_waves : dict Contains wave peaks loca...
def _get_gc2_coordinates_for_rupture(self, edge_sets): """ Calculates the GC2 coordinates for the nodes of the upper edge of the fault """ # Establish GC2 length - for use with Ry0 rup_gc2t, rup_gc2u = self.get_generalised_coordinates( edge_sets[:, 0], edge_s...
Calculates the GC2 coordinates for the nodes of the upper edge of the fault
def _maybe_append_chunk(chunk_info, line_index, column, contents, chunks): """Append chunk_info to chunks if it is set.""" if chunk_info: chunks.append(_chunk_from_ranges(contents, chunk_info[0], chunk_info[1], ...
Append chunk_info to chunks if it is set.
def parse_s2bins(s2bins): """ parse ggKbase scaffold-to-bin mapping - scaffolds-to-bins and bins-to-scaffolds """ s2b = {} b2s = {} for line in s2bins: line = line.strip().split() s, b = line[0], line[1] if 'UNK' in b: continue if len(line) > 2...
parse ggKbase scaffold-to-bin mapping - scaffolds-to-bins and bins-to-scaffolds
def _sysv_services(): ''' Return list of sysv services. ''' _services = [] output = __salt__['cmd.run'](['chkconfig', '--list'], python_shell=False) for line in output.splitlines(): comps = line.split() try: if comps[1].startswith('0:'): _services.appe...
Return list of sysv services.
def owners(self): """Legacy access to owner role. DEPRECATED: use ``policy["roles/owners"]`` instead.""" result = set() for role in self._OWNER_ROLES: for member in self._bindings.get(role, ()): result.add(member) return frozenset(result)
Legacy access to owner role. DEPRECATED: use ``policy["roles/owners"]`` instead.
def read_mrz(file, save_roi=False, extra_cmdline_params=''): """The main interface function to this module, encapsulating the recognition pipeline. Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object. :param file: A filename or a stream to read the file data from. :param...
The main interface function to this module, encapsulating the recognition pipeline. Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object. :param file: A filename or a stream to read the file data from. :param save_roi: when this is True, the .aux['roi'] field will contain the...
def eci2geodetic (x, y, z, gmst=None, ellipsoid=None): """Converts the given ECI coordinates to Geodetic coordinates at the given Greenwich Mean Sidereal Time (GMST) (defaults to now) and with the given ellipsoid (defaults to WGS84). This code was adapted from `shashwatak/satellite-js <https://github.com/sha...
Converts the given ECI coordinates to Geodetic coordinates at the given Greenwich Mean Sidereal Time (GMST) (defaults to now) and with the given ellipsoid (defaults to WGS84). This code was adapted from `shashwatak/satellite-js <https://github.com/shashwatak/satellite-js/blob/master/src/coordinate-transforms.j...
def handle(self, **options): """ Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. """ print("Starting clean up of django-defender table") now = timezone.now() cleanup_delta = timedelta(h...
Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS.
def set_cookie(cookies, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): '''Set a cookie key into the cookies dictionary *cookies*.''' cookies[key] = value if expires is not None: if isinstance(expires, datetime): now = (expi...
Set a cookie key into the cookies dictionary *cookies*.
def _add_current_quay_tag(repo, container_tags): """Lookup the current quay tag for the repository, adding to repo string. Enables generation of CWL explicitly tied to revisions. """ if ':' in repo: return repo, container_tags try: latest_tag = container_tags[repo] except KeyErr...
Lookup the current quay tag for the repository, adding to repo string. Enables generation of CWL explicitly tied to revisions.
def pprint(string, token=[WORD, POS, CHUNK, PNP], column=4): """ Pretty-prints the output of Parser.parse() as a table with outlined columns. Alternatively, you can supply a tree.Text or tree.Sentence object. """ if isinstance(string, basestring): print("\n\n".join([table(sentence, fill=colu...
Pretty-prints the output of Parser.parse() as a table with outlined columns. Alternatively, you can supply a tree.Text or tree.Sentence object.
def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None: """ Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`. :param dir_: dir to be pruned :param epochs: minimum number of finished epochs to keep the training logs :param ...
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`. :param dir_: dir to be pruned :param epochs: minimum number of finished epochs to keep the training logs :param subdirs: delete subdirs in training log dirs
def load_gene(ensembl, gene_id, de_novos=[]): """ sort out all the necessary sequences and positions for a gene Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene de_novos: list of de novo positions, so we can check they all fit in ...
sort out all the necessary sequences and positions for a gene Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene de_novos: list of de novo positions, so we can check they all fit in the gene transcript Returns: ...
def FromReadings(cls, uuid, readings, sent_timestamp=0): """Generate a broadcast report from a list of readings and a uuid.""" header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0) packed_readings = bytearray() for reading in readings: ...
Generate a broadcast report from a list of readings and a uuid.
def update_or_create(self, location, contact_addresses, with_status=False, overwrite_existing=False, **kw): """ Update or create a contact address and location pair. If the location does not exist it will be automatically created. If the server already has a location assigned...
Update or create a contact address and location pair. If the location does not exist it will be automatically created. If the server already has a location assigned with the same name, the contact address specified will be added if it doesn't already exist (Management and Log Server can ...
def child_count(self, only_direct=True): """Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node. """ if not only_direct: count = 0 for _node in self.dfs_iter(): count...
Returns how many children this node has, either only the direct children of this node or inclusive of all children nodes of this node.
def get_filestore_instance(img_dir=None, data_dir=None): """Return an instance of FileStore.""" global _filestore_instances key = "%s:%s" % (img_dir, data_dir) try: instance = _filestore_instances[key] except KeyError: instance = FileStore( img_dir=img_dir, data_dir=dat...
Return an instance of FileStore.
def _parse_ethtool_pppoe_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} for opt in _DEB_CONFIG_PP...
Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting.
def _save_to_database(url, property_name, data): """ Store `data` under `property_name` in the `url` key in REST API DB. Args: url (obj): URL of the resource to which `property_name` will be stored. property_name (str): Name of the property under which the `data` will be stored....
Store `data` under `property_name` in the `url` key in REST API DB. Args: url (obj): URL of the resource to which `property_name` will be stored. property_name (str): Name of the property under which the `data` will be stored. data (obj): Any object.
def _access_through_cftimeindex(values, name): """Coerce an array of datetime-like values to a CFTimeIndex and access requested datetime component """ from ..coding.cftimeindex import CFTimeIndex values_as_cftimeindex = CFTimeIndex(values.ravel()) if name == 'season': months = values_as_...
Coerce an array of datetime-like values to a CFTimeIndex and access requested datetime component
def Column(self, column_name): """Iterates over values of a given column. Args: column_name: A nome of the column to retrieve the values for. Yields: Values of the specified column. Raises: KeyError: If given column is not present in the table. """ column_idx = None for ...
Iterates over values of a given column. Args: column_name: A nome of the column to retrieve the values for. Yields: Values of the specified column. Raises: KeyError: If given column is not present in the table.
def unmatched_quotes_in_line(text): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped qu...
Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped quotes - Copyright (C) 2008-2011 IPython...
def _get_metrics_to_collect(self, instance_key, additional_metrics): """ Return and cache the list of metrics to collect. """ if instance_key not in self.metrics_to_collect_by_instance: self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(add...
Return and cache the list of metrics to collect.
def add_template_events_to_network(self, columns, vectors): """ Add a vector indexed """ # Just call through to the standard function self.template_events = self.template_event_dict['network'] self.add_template_network_events(columns, vectors) self.template_event_dict['network'] ...
Add a vector indexed
def press_keys(self,characters=[]): """Press a given character key.""" for character in characters: self.press_key(character) for character in characters: self.release_key(character)
Press a given character key.
def y(self, y): """Project y as x""" if y is None: return None if self._force_vertical: return super(HorizontalView, self).y(y) return super(HorizontalView, self).x(y)
Project y as x
def insertUnorderedList(self): """ Inserts an ordered list into the editor. """ cursor = self.editor().textCursor() currlist = cursor.currentList() new_style = QTextListFormat.ListDisc indent = 1 if currlist: format = currlis...
Inserts an ordered list into the editor.
def parse_link_header(link): """takes the link header as a string and returns a dictionary with rel values as keys and urls as values :param link: link header as a string :rtype: dictionary {rel_name: rel_value} """ rel_dict = {} for rels in link.split(','): rel_break = quoted_split(rels...
takes the link header as a string and returns a dictionary with rel values as keys and urls as values :param link: link header as a string :rtype: dictionary {rel_name: rel_value}
def is_trusted_subject(request): """Determine if calling subject is fully trusted.""" logging.debug('Active subjects: {}'.format(', '.join(request.all_subjects_set))) logging.debug('Trusted subjects: {}'.format(', '.join(get_trusted_subjects()))) return not request.all_subjects_set.isdisjoint(get_truste...
Determine if calling subject is fully trusted.
def _init_transformer_cache(cache, hparams, batch_size, attention_init_length, encoder_output, encoder_decoder_attention_bias, scope_prefix): """Create the initial cache for Transformer fast decoding.""" key_channels = hparams.attention_key_channels or hparams...
Create the initial cache for Transformer fast decoding.
def features_tags_parse_str_to_dict(obj): """ Parse tag strings of all features in the collection into a Python dictionary, if possible. """ features = obj['features'] for i in tqdm(range(len(features))): tags = features[i]['properties'].get('tags') if tags is not None: ...
Parse tag strings of all features in the collection into a Python dictionary, if possible.
def infer_id(self, ident, diagnostic=None): """ Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type """ # check if ID is declared #defined = self.type_node.get_by_symbol_name(ident) defined = self.infer_node.scope...
Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type
def patch(self, pid, record, **kwargs): """Modify a record. Permissions: ``update_permission_factory`` The data should be a JSON-patch, which will be applied to the record. Requires header ``Content-Type: application/json-patch+json``. Procedure description: #. The re...
Modify a record. Permissions: ``update_permission_factory`` The data should be a JSON-patch, which will be applied to the record. Requires header ``Content-Type: application/json-patch+json``. Procedure description: #. The record is deserialized using the proper loader. ...
def get_form_instance(self, request, data=None, instance=None): """ Returns an instantiated form to be used for adding or editing an object. The `instance` argument is the model instance (passed only if this form is going to be used for editing an existing object). """ d...
Returns an instantiated form to be used for adding or editing an object. The `instance` argument is the model instance (passed only if this form is going to be used for editing an existing object).
def _check_branch(self, revision, branch): ''' Used to find out if the revision is in the given branch. :param revision: Revision to check. :param branch: Branch to check revision on. :return: True/False - Found it/Didn't find it ''' # Get a changelog cl...
Used to find out if the revision is in the given branch. :param revision: Revision to check. :param branch: Branch to check revision on. :return: True/False - Found it/Didn't find it
def get_help(self): """ Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned. """ current_state = self.get_current_state() if current_state is None: return stateme...
Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned.
def _to_map_job_config(cls, mr_spec, # TODO(user): Remove this parameter after it can be # read from mr_spec. queue_name): """Converts model.MapreduceSpec back to JobConfig. This method allows our internal metho...
Converts model.MapreduceSpec back to JobConfig. This method allows our internal methods to use JobConfig directly. This method also allows us to expose JobConfig as an API during execution, despite that it is not saved into datastore. Args: mr_spec: model.MapreduceSpec. queue_name: queue n...
def get_generator(self, path, *args, **kw_args): """ Get a generator that allows convenient access to the streamed data. Elements from the dataset are returned from the generator one row at a time. Unlike the direct access queue, this generator also returns the remainder elements. ...
Get a generator that allows convenient access to the streamed data. Elements from the dataset are returned from the generator one row at a time. Unlike the direct access queue, this generator also returns the remainder elements. Additional arguments are forwarded to get_queue. See the ge...
def default_should_trace_hook(frame, filename): ''' Return True if this frame should be traced, False if tracing should be blocked. ''' # First, check whether this code object has a cached value ignored_lines = _filename_to_ignored_lines.get(filename) if ignored_lines is None: # Now, loo...
Return True if this frame should be traced, False if tracing should be blocked.
def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ octets = [] for _ in xrange(4): ...
Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.
def create(self, dataset_name, query, index_by, display_name): """ Create a Cached Dataset for a Project. Master key must be set. """ url = "{0}/{1}".format(self._cached_datasets_url, dataset_name) payload = { "query": query, "index_by": index_by, "dis...
Create a Cached Dataset for a Project. Master key must be set.
def github_gfonts_ttFont(ttFont, license): """Get a TTFont object of a font downloaded from Google Fonts git repository. """ if not license: return from fontbakery.utils import download_file from fontTools.ttLib import TTFont from urllib.request import HTTPError LICENSE_DIRECTORY = { "OFL.tx...
Get a TTFont object of a font downloaded from Google Fonts git repository.
def authenticated_request(self, endpoint, method='GET', params=None, data=None): ''' Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type Params: endpoint -- API endpoint to send req...
Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type Params: endpoint -- API endpoint to send request to Keyword Args: method -- GET, PUT, PATCH, DELETE, etc. params -- para...
def yaml_load(source, defaultdata=NO_DEFAULT): """merge YAML data from files found in source Always returns a dict. The YAML files are expected to contain some kind of key:value structures, possibly deeply nested. When merging, lists are appended and dict keys are replaced. The YAML files are read with...
merge YAML data from files found in source Always returns a dict. The YAML files are expected to contain some kind of key:value structures, possibly deeply nested. When merging, lists are appended and dict keys are replaced. The YAML files are read with the yaml.safe_load function. source can be a...
def get_path_url(path, relative=False): """ Returns an absolute or relative path url given a path """ if relative: return os.path.relpath(path) else: return 'file://%s' % os.path.abspath(path)
Returns an absolute or relative path url given a path
def distance(p1, p2): """ Cartesian distance between two PoseStamped or PoseLists :param p1: point 1 (list, Pose or PoseStamped) :param p2: point 2 (list, Pose or PoseStamped) :return: cartesian distance (float) """ def xyz(some_pose): if isinstance(some_pose, PoseStamped): ...
Cartesian distance between two PoseStamped or PoseLists :param p1: point 1 (list, Pose or PoseStamped) :param p2: point 2 (list, Pose or PoseStamped) :return: cartesian distance (float)
def visit_break(self, node, parent): """visit a Break node by returning a fresh instance of it""" return nodes.Break( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
visit a Break node by returning a fresh instance of it
def lm_tfinal(damping_times, modes): """Return the maximum t_final of the modes given, with t_final the time at which the amplitude falls to 1/1000 of the peak amplitude """ t_max = {} for lmn in modes: l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2]) for n in range(nmodes): ...
Return the maximum t_final of the modes given, with t_final the time at which the amplitude falls to 1/1000 of the peak amplitude
def nvrtcGetLoweredName(self, prog, name_expression): """ Notes the given name expression denoting a __global__ function or function template instantiation. """ lowered_name = c_char_p() code = self._lib.nvrtcGetLoweredName(prog, ...
Notes the given name expression denoting a __global__ function or function template instantiation.
def host2id(self, hostname): """return member id by hostname""" for key, value in self.server_map.items(): if value == hostname: return key
return member id by hostname
def cat_acc(y_true, y_pred): """Categorical accuracy """ return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))
Categorical accuracy
def parse_latitude(latitude, hemisphere): """Parse a NMEA-formatted latitude pair. Args: latitude (str): Latitude in DDMM.MMMM hemisphere (str): North or South Returns: float: Decimal representation of latitude """ latitude = int(latitude[:2]) + float(latitude[2:]) / 60 ...
Parse a NMEA-formatted latitude pair. Args: latitude (str): Latitude in DDMM.MMMM hemisphere (str): North or South Returns: float: Decimal representation of latitude
def _arguments_repr(self): """Representation of the arguments used to create this object.""" document_class_repr = ( 'dict' if self.document_class is dict else repr(self.document_class)) uuid_rep_repr = UUID_REPRESENTATION_NAMES.get(self.uuid_representation, ...
Representation of the arguments used to create this object.
def format_decimal(decimal): """ Formats a decimal number :param decimal: the decimal value :return: the formatted string value """ # strip trailing fractional zeros normalized = decimal.normalize() sign, digits, exponent = normalized.as_tuple() if exponent >= 1: normalized =...
Formats a decimal number :param decimal: the decimal value :return: the formatted string value
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
Remove a value from the xblock's cache, if the cache exists.
def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None): """A stack of separable convolution blocks with residual connections.""" with tf.variable_scope(name): padding_bias = None if mask is not None: padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. if p...
A stack of separable convolution blocks with residual connections.
def is_Type(tp): """Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1. """ if isinstanc...
Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1.
def get_ip_address_info(ip_address, cache=None, nameservers=None, timeout=2.0, parallel=False): """ Returns reverse DNS and country information for the given IP address Args: ip_address (str): The IP address to check cache (ExpiringDict): Cache storage namese...
Returns reverse DNS and country information for the given IP address Args: ip_address (str): The IP address to check cache (ExpiringDict): Cache storage nameservers (list): A list of one or more nameservers to use (Cloudflare's public DNS resolvers by default) timeout (float...
def __general(self): """Level-0 parser and main loop. Look for a token that matches a level-1 parser and hand over control.""" while 1: # main loop try: tok = self.__peek() # only peek, apply_parser() will consume except...
Level-0 parser and main loop. Look for a token that matches a level-1 parser and hand over control.
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) ...
Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the beginnin...
def resolve(self, cfg, addr, func_addr, block, jumpkind): """ Resolves the indirect jump in MIPS ELF binaries where all external function calls are indexed using gp. :param cfg: A CFG instance. :param int addr: IRSB address. :param int func_addr: The function address. :p...
Resolves the indirect jump in MIPS ELF binaries where all external function calls are indexed using gp. :param cfg: A CFG instance. :param int addr: IRSB address. :param int func_addr: The function address. :param pyvex.IRSB block: The IRSB. :param str jumpkind: The jumpkind. ...
def register_resources(klass, registry, resource_class): """ meta model subscriber on resource registration. We watch for new resource types being registered and if they support aws config, automatically register the jsondiff filter. """ config_type = getattr(resource_class.reso...
meta model subscriber on resource registration. We watch for new resource types being registered and if they support aws config, automatically register the jsondiff filter.
def create_service(self, name, **kwargs): """ Creates a service with a name. All other parameters are optional. They are: `note`, `hourly_rate`, `billable`, and `archived`. """ data = self._wrap_dict("service", kwargs) data["customer"]["name"] = name return self.p...
Creates a service with a name. All other parameters are optional. They are: `note`, `hourly_rate`, `billable`, and `archived`.
def sync_user_email_addresses(user): """ Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users. """ from .models import EmailAddress email = user_email...
Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users.
def get_item_at(self, *args, **kwargs): """ Return the items at the given position """ return self.proxy.get_item_at(coerce_point(*args, **kwargs))
Return the items at the given position
def flag(name=None): """ Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Flag Field' # Basic field field = pp.Regex('[YNU]') # Name field.setName...
Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field
def help(file=None): """ Print out syntax help for running ``astrodrizzle`` Parameters ---------- file : str (Default = None) If given, write out help to the filename specified by this parameter Any previously existing file with this name will be deleted before writing out t...
Print out syntax help for running ``astrodrizzle`` Parameters ---------- file : str (Default = None) If given, write out help to the filename specified by this parameter Any previously existing file with this name will be deleted before writing out the help.
def artist_top_tracks(self, spotify_id, country): """Get an artists top tracks per country with their ID. Parameters ---------- spotify_id : str The spotify_id to search by. country : COUNTRY_TP COUNTRY """ route = Route('GET', '/artists/{...
Get an artists top tracks per country with their ID. Parameters ---------- spotify_id : str The spotify_id to search by. country : COUNTRY_TP COUNTRY
def _make_cookie(self): """ Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing. """ return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC, ...
Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing.
def MaxLikeInterval(self, percentage=90): """Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite """ ...
Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite