code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _write_models_step(self, model, field=None): """ Write or update a model. """ model = get_model(model) data = guess_types(self.hashes) try: func = _WRITE_MODEL[model] except KeyError: func = partial(write_models, model) func(data, field)
Write or update a model.
def shutdown(self): """Gracefully shutdown the consumer Consumer will complete any outstanding processing, commit its current offsets (if so configured) and stop. Returns deferred which callbacks with a tuple of: (last processed offset, last committed offset) if it was able to ...
Gracefully shutdown the consumer Consumer will complete any outstanding processing, commit its current offsets (if so configured) and stop. Returns deferred which callbacks with a tuple of: (last processed offset, last committed offset) if it was able to successfully commit, or...
def _run_dnb_normalization(self, dnb_data, sza_data): """Scale the DNB data using a histogram equalization method. Args: dnb_data (ndarray): Day/Night Band data array sza_data (ndarray): Solar Zenith Angle data array """ # convert dask arrays to DataArray object...
Scale the DNB data using a histogram equalization method. Args: dnb_data (ndarray): Day/Night Band data array sza_data (ndarray): Solar Zenith Angle data array
def update_file(self, file_id, upload_id): """ Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label. :param file_id: str uuid of file :param upload_id: str uuid of the upload where all the file chunks where uploaded :param label: str shor...
Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label. :param file_id: str uuid of file :param upload_id: str uuid of the upload where all the file chunks where uploaded :param label: str short display label for the file :return: requests.Response...
def makemessages(application, locale): """ Updates the locale message files """ from django.core.management import call_command if not locale: locale = 'en' with work_in(application): call_command('makemessages', locale=(locale,))
Updates the locale message files
def _split_on_reappear(cls, df, p, id_offset): """Assign a new identity to an objects that appears after disappearing previously. Works on `df` in-place. :param df: data frame :param p: presence :param id_offset: offset added to new ids :return: """ next_...
Assign a new identity to an objects that appears after disappearing previously. Works on `df` in-place. :param df: data frame :param p: presence :param id_offset: offset added to new ids :return:
def forwarded(self) -> Tuple[Mapping[str, str], ...]: """A tuple containing all parsed Forwarded header(s). Makes an effort to parse Forwarded headers as specified by RFC 7239: - It adds one (immutable) dictionary per Forwarded 'field-value', ie per proxy. The element corresponds to ...
A tuple containing all parsed Forwarded header(s). Makes an effort to parse Forwarded headers as specified by RFC 7239: - It adds one (immutable) dictionary per Forwarded 'field-value', ie per proxy. The element corresponds to the data in the Forwarded field-value added by the firs...
def IsAllocated(self): """Determines if the file entry is allocated. Returns: bool: True if the file entry is allocated. """ if self._stat_object is None: self._stat_object = self._GetStat() return self._stat_object and self._stat_object.is_allocated
Determines if the file entry is allocated. Returns: bool: True if the file entry is allocated.
def import_generated_autoboto(self): """ Imports the autoboto package generated in the build directory (not target_dir). For example: autoboto = botogen.import_generated_autoboto() """ if str(self.config.build_dir) not in sys.path: sys.path.append(str(se...
Imports the autoboto package generated in the build directory (not target_dir). For example: autoboto = botogen.import_generated_autoboto()
def function_type(self): """returns function type. See :class:`type_t` hierarchy""" return cpptypes.free_function_type_t( return_type=self.return_type, arguments_types=[ arg.decl_type for arg in self.arguments])
returns function type. See :class:`type_t` hierarchy
def team_info(): """Returns a list of team information dictionaries""" teams = __get_league_object().find('teams').findall('team') output = [] for team in teams: info = {} for x in team.attrib: info[x] = team.attrib[x] output.append(info) return output
Returns a list of team information dictionaries
def hazard_notes(self): """Get the hazard specific notes defined in definitions. This method will do a lookup in definitions and return the hazard definition specific notes dictionary. This is a helper function to make it easy to get hazard specific notes from the definitions m...
Get the hazard specific notes defined in definitions. This method will do a lookup in definitions and return the hazard definition specific notes dictionary. This is a helper function to make it easy to get hazard specific notes from the definitions metadata. .. versionadded::...
def update_key_bundle(key_bundle, diff): """ Apply a diff specification to a KeyBundle. The keys that are to be added are added. The keys that should be deleted are marked as inactive. :param key_bundle: The original KeyBundle :param diff: The difference specification :return: An updated ke...
Apply a diff specification to a KeyBundle. The keys that are to be added are added. The keys that should be deleted are marked as inactive. :param key_bundle: The original KeyBundle :param diff: The difference specification :return: An updated key_bundle
def common_params(task_instance, task_cls): """ Grab all the values in task_instance that are found in task_cls. """ if not isinstance(task_cls, task.Register): raise TypeError("task_cls must be an uninstantiated Task") task_instance_param_names = dict(task_instance.get_params()).keys() ...
Grab all the values in task_instance that are found in task_cls.
def number_of_contacts(records, direction=None, more=0): """ The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outgoing. more...
The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'out'`` for outgoing. more : int, default is 0 Counts only contacts with more than this...
def _add_throughput(self, y, x, width, op, title, available, used): """ Write a single throughput measure to a row """ percent = float(used) / available self.win.addstr(y, x, "[") # Because we have disabled scrolling, writing the lower right corner # character in a terminal can t...
Write a single throughput measure to a row
def fetch_dictionary(name, url=None, format=None, index=0, rename=None, save=True, force_retrieve=False): ''' Retrieve a dictionary of text norms from the web or local storage. Args: name (str): The name of the dictionary. If no url is passed, this must match either one...
Retrieve a dictionary of text norms from the web or local storage. Args: name (str): The name of the dictionary. If no url is passed, this must match either one of the keys in the predefined dictionary file (see dictionaries.json), or the name assigned to a previous dictionary ...
def off(self): """Turn off the alsa_sink sink. This disconnects the sink from the relevant session events. """ spotifyconnect._session_instance.player.off( spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery) assert spotifyconnect._session_instance.pla...
Turn off the alsa_sink sink. This disconnects the sink from the relevant session events.
def bulk_upsert(self, docs, namespace, timestamp): """Upsert each document in a set of documents. This method may be overridden to upsert many documents at once. """ for doc in docs: self.upsert(doc, namespace, timestamp)
Upsert each document in a set of documents. This method may be overridden to upsert many documents at once.
def smart_query(query, filters=None, sort_attrs=None, schema=None): """ Does magic Django-ish joins like post___user___name__startswith='Bob' (see https://goo.gl/jAgCyM) Does filtering, sorting and eager loading at the same time. And if, say, filters and sorting need the same joinm it will be done ...
Does magic Django-ish joins like post___user___name__startswith='Bob' (see https://goo.gl/jAgCyM) Does filtering, sorting and eager loading at the same time. And if, say, filters and sorting need the same joinm it will be done only one. That's why all stuff is combined in single method :param que...
def sum_out(self, var, bn): "Make a factor eliminating var by summing over its values." vars = [X for X in self.vars if X != var] cpt = dict((event_values(e, vars), sum(self.p(extend(e, var, val)) for val in bn.variable_values(var))) ...
Make a factor eliminating var by summing over its values.
def pull_requested_reviewers(self, pr_number): """Get pull requested reviewers""" requested_reviewers_url = urijoin("pulls", str(pr_number), "requested_reviewers") return self.fetch_items(requested_reviewers_url, {})
Get pull requested reviewers
def propose(self): """ Proposals for positive definite matrix using random walk deviations on the Cholesky factor of the current value. """ # Locally store size of matrix dims = self.stochastic.value.shape # Add normal deviate to value and symmetrize dev...
Proposals for positive definite matrix using random walk deviations on the Cholesky factor of the current value.
async def unset_lock(self, resource, lock_identifier): """ Tries to unset the lock to all the redis instances :param resource: The resource string name to lock :param lock_identifier: The id of the lock. A unique string :return float: The elapsed time that took to lock the insta...
Tries to unset the lock to all the redis instances :param resource: The resource string name to lock :param lock_identifier: The id of the lock. A unique string :return float: The elapsed time that took to lock the instances in iseconds :raises: LockError if the lock has not matching id...
def fibs(n, m): """ Yields Fibonacci numbers starting from ``n`` and ending at ``m``. """ a = b = 1 for x in range(3, m + 1): a, b = b, a + b if x >= n: yield b
Yields Fibonacci numbers starting from ``n`` and ending at ``m``.
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]: """Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. ...
Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. offset : Optional[int] The index of the first item to return...
def add_interface_router(router, subnet, profile=None): ''' Adds an internal network interface to the specified router CLI Example: .. code-block:: bash salt '*' neutron.add_interface_router router-name subnet-name :param router: ID or name of the router :param subnet: ID or name of ...
Adds an internal network interface to the specified router CLI Example: .. code-block:: bash salt '*' neutron.add_interface_router router-name subnet-name :param router: ID or name of the router :param subnet: ID or name of the subnet :param profile: Profile to build on (Optional) :r...
def atlasdb_cache_zonefile_info( con=None, path=None ): """ Load up and cache our zonefile inventory from the database """ global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK inv = None with ZONEFILE_INV_LOCK: inv_len = atlasdb_zonefile_inv_length( con=con, path=path ) inv...
Load up and cache our zonefile inventory from the database
def update(self, ttl=values.unset): """ Update the SyncStreamInstance :param unicode ttl: Stream TTL. :returns: Updated SyncStreamInstance :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance """ return self._proxy.update(ttl=ttl, )
Update the SyncStreamInstance :param unicode ttl: Stream TTL. :returns: Updated SyncStreamInstance :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance
def concrete_emulate(self, insn): """ Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at :param capstone.CsInsn insn: The instruction object to emulate """ if not self.emu: self.emu = ConcreteUnicornEmulator(self) ...
Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at :param capstone.CsInsn insn: The instruction object to emulate
def pub(self, topic, message): '''Publish the provided message to the provided topic''' with self.random_connection() as client: client.pub(topic, message) return self.wait_response()
Publish the provided message to the provided topic
def get_bin_lookup_session(self, proxy): """Gets the bin lookup session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinLookupSession) - a ``BinLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to c...
Gets the bin lookup session. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinLookupSession) - a ``BinLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``su...
def _captcha_form(self): """ captcha form :return: """ try: last_attempt = FailedAccessAttempt.objects.get( ip_address=self._ip, is_locked=True, captcha_enabled=True, is_expired=False ) ...
captcha form :return:
def adsb_vehicle_encode(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk): ''' The location and information of an ADSB vehicle ICAO_address : ICAO address (uint32_t) ...
The location and information of an ADSB vehicle ICAO_address : ICAO address (uint32_t) lat : Latitude, expressed as degrees * 1E7 (int32_t) lon : Longitude, expressed as degrees * 1E7 (int32_t) alti...
def deprecated(message, exception=PendingDeprecationWarning): """Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a ``DeprecationWarn...
Throw a warning when a function/method will be soon deprecated Supports passing a ``message`` and an ``exception`` class (uses ``PendingDeprecationWarning`` by default). This is useful if you want to alternatively pass a ``DeprecationWarning`` exception for already deprecated functions/methods. Ex...
def _get_namedrange(book, rangename, sheetname=None): """Get range from a workbook. A workbook can contain multiple definitions for a single name, as a name can be defined for the entire book or for a particular sheet. If sheet is None, the book-wide def is searched, otherwise sheet-local def ...
Get range from a workbook. A workbook can contain multiple definitions for a single name, as a name can be defined for the entire book or for a particular sheet. If sheet is None, the book-wide def is searched, otherwise sheet-local def is looked up. Args: book: An openpyxl workbook o...
def getTotalExpectedOccurrencesTicks_2_5(ticks): """ Extract a set of tick locations and labels. The input ticks are assumed to mean "How many *other* occurrences are there of the sensed feature?" but we want to show how many *total* occurrences there are. So we add 1. We label tick 2, and then 5, 10, 15, 20...
Extract a set of tick locations and labels. The input ticks are assumed to mean "How many *other* occurrences are there of the sensed feature?" but we want to show how many *total* occurrences there are. So we add 1. We label tick 2, and then 5, 10, 15, 20, ... @param ticks A list of ticks, typically calcul...
def createSummary(self, log): """ Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.""" # If there were any warnings, make the log if lines with warnings # available if s...
Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.
def get_space(self, current_result_list, current_query, param_space, runs, result_parsing_function): """ Convert a parameter space specification to a nested array structure representing the space. In other words, if the parameter space is:: param_space = { ...
Convert a parameter space specification to a nested array structure representing the space. In other words, if the parameter space is:: param_space = { 'a': [1, 2], 'b': [3, 4] } the function will return a structure like the following:: ...
def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] ...
Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None)
def _dx(self): """Return integer width of this shape's path in local units.""" min_x = max_x = self._start_x for drawing_operation in self: if hasattr(drawing_operation, 'x'): min_x = min(min_x, drawing_operation.x) max_x = max(max_x, drawing_operation...
Return integer width of this shape's path in local units.
def search(self, query=None, args=None): '''query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES: ''' # You can optionally better parse the image uri (query), but not # necessary # names = parse_image_name(remove_uri(query)) ...
query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES:
def _try_passwordless_paramiko(server, keyfile): """Try passwordless login with paramiko.""" if paramiko is None: msg = "Paramiko unavaliable, " if sys.platform == 'win32': msg += "Paramiko is required for ssh tunneled connections on Windows." else: msg += "use Op...
Try passwordless login with paramiko.
def apply_transformation(self, structure, return_ranked_list=False): """ Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number ...
Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number of structures is returned. Returns: Depending on ret...
def rm(self, typ, id): """ remove typ by id """ return self._load(self._request(typ, id=id, method='DELETE'))
remove typ by id
def deploy(self, site=None): """ Writes entire crontab to the host. """ r = self.local_renderer self.deploy_logrotate() cron_crontabs = [] # if self.verbose: # print('hostname: "%s"' % (hostname,), file=sys.stderr) for _site, site_data in sel...
Writes entire crontab to the host.
def evaluate(self, reference_scene_list, estimated_scene_list=None, estimated_scene_probabilities=None): """Evaluate file pair (reference and estimated) Parameters ---------- reference_scene_list : list of dict or dcase_util.containers.MetaDataContainer Reference scene list...
Evaluate file pair (reference and estimated) Parameters ---------- reference_scene_list : list of dict or dcase_util.containers.MetaDataContainer Reference scene list. Default value None estimated_scene_list : list of dict or dcase_util.containers.MetaDataConta...
def resolve(self, current_file, rel_path): """Search the filesystem.""" p = path.join(path.dirname(current_file), rel_path) if p not in self.file_dict: raise RuntimeError('No such fake file: %r' % p) return p, p
Search the filesystem.
def get_datacenter(content, obj): ''' Get the datacenter to whom an object belongs ''' datacenters = content.rootFolder.childEntity for d in datacenters: dch = get_all(content, d, type(obj)) if dch is not None and obj in dch: return d
Get the datacenter to whom an object belongs
def _transform_stats(prof): """Processes collected stats for UI.""" records = [] for info, params in prof.stats.items(): filename, lineno, funcname = info cum_calls, num_calls, time_per_call, cum_time, _ = params if prof.total_tt == 0: percenta...
Processes collected stats for UI.
def udp_send(udpsock, frame, address, addrlen): """ Send zframe to UDP socket, return -1 if sending failed due to interface having disappeared (happens easily with WiFi) *** This is for CZMQ internal use only and may change arbitrarily *** """ return lib.zsys_udp_send(udpsock, frame, add...
Send zframe to UDP socket, return -1 if sending failed due to interface having disappeared (happens easily with WiFi) *** This is for CZMQ internal use only and may change arbitrarily ***
def window_size(self, value): """Set private ``_window_size`` and reset ``_block_matcher``.""" if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size ...
Set private ``_window_size`` and reset ``_block_matcher``.
def TAPQuery(query): """The __main__ part of the script""" tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync" ## Some default parameters for that TAP service queries. tapParams={'REQUEST': 'doQuery', 'LANG': 'ADQL', 'FORMAT': 'votable', 'QUERY...
The __main__ part of the script
def zoom_leftup(self, event=None): """leftup event handler for zoom mode in images""" if self.zoom_ini is None: return ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini try: dx = abs(ini_x - event.x) dy = abs(ini_y - event.y) except: d...
leftup event handler for zoom mode in images
def _string_to_byte_list(self, data): """ Creates a hex digest of the input string given to create the image, if it's not already hexadecimal Returns: Length 16 list of rgb value range integers (each representing a byte of the hex digest) """ byte...
Creates a hex digest of the input string given to create the image, if it's not already hexadecimal Returns: Length 16 list of rgb value range integers (each representing a byte of the hex digest)
def read(self,filename,datatype=None,slaext=False,**kwargs): ''' reader method. :parameter filename: name of the file to load. :keyword datatype: choose between DT/NRT/PISTACH/CTOH or other formats to call the corresponding reader. If datatype is : * D...
reader method. :parameter filename: name of the file to load. :keyword datatype: choose between DT/NRT/PISTACH/CTOH or other formats to call the corresponding reader. If datatype is : * DT or NRT or PISTACH : calls :func:`altimetry.data.alti_data.read_sla` or :func:`alt...
def append(self, station): """ Append station to database. Returns the index of the appended station. """ rec = station._pack(self) with self: _libtcd.add_tide_record(rec, self._header) return self._header.number_of_records - 1
Append station to database. Returns the index of the appended station.
def _rewrite_and_copy(src_file, dst_file, project_name): """Replace vars and copy.""" # Create temp file fh, abs_path = mkstemp() with io.open(abs_path, 'w', encoding='utf-8') as new_file: with io.open(src_file, 'r', encoding='utf-8') as old_file: for line in old_file: ...
Replace vars and copy.
def get_vaults_by_ids(self, *args, **kwargs): """Pass through to provider VaultLookupSession.get_vaults_by_ids""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_by_ids catalogs = self._get_provider_session('vault_lookup_session').get_vaults_by_ids(*ar...
Pass through to provider VaultLookupSession.get_vaults_by_ids
def calculate(self, **state): """ Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param x: [mole fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s]...
Calculate dynamic viscosity at the specified temperature and composition: :param T: [K] temperature :param x: [mole fraction] composition dictionary , e.g. \ {'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25} :returns: [Pa.s] dynamic viscosity The **state parameter ...
def _add_record(self, record_set_class, name, values, ttl=60, weight=None, region=None,set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): """ Convenience method for creating ResourceRecordSets. Most of the calls are basically the same, t...
Convenience method for creating ResourceRecordSets. Most of the calls are basically the same, this saves on repetition. :rtype: tuple :returns: A tuple in the form of ``(rrset, change_info)``, where ``rrset`` is the newly created ResourceRecordSet sub-class instance.
def get_data(self): """ Fetch the data field if it does not exist. """ try: return DocumentDataDict(self.__dict__['data']) except KeyError: self._lazy_load() return DocumentDataDict(self.__dict__['data'])
Fetch the data field if it does not exist.
def hello(environ, start_response): '''The WSGI_ application handler which returns an iterable over the "Hello World!" message.''' if environ['REQUEST_METHOD'] == 'GET': data = b'Hello World!\n' status = '200 OK' response_headers = [ ('Content-type', 'text/plain'), ...
The WSGI_ application handler which returns an iterable over the "Hello World!" message.
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ self.Y = sp.prox_l1l2(self.AX + self.U, (self.lmbda/self.rho)*self.wl1, (self.mu/self.rho), axis=self.cri.axisC) cbpdn.GenericConvBPDN.ystep(self)
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
def verify(self): """ :desc: Verifies the integrity of the database, specifically checks the values for unusedIDs and currentMax :returns: A boolean indicating whether the database is valid or not :rval: bool """ collec...
:desc: Verifies the integrity of the database, specifically checks the values for unusedIDs and currentMax :returns: A boolean indicating whether the database is valid or not :rval: bool
def install(environment, opts): """Install or reinstall Python packages within this environment Usage: datacats install [-q] [--address=IP] [ENVIRONMENT [PACKAGE ...]] datacats install -c [q] [--address=IP] [ENVIRONMENT] Options: --address=IP The address to bind to when reloading after install -c...
Install or reinstall Python packages within this environment Usage: datacats install [-q] [--address=IP] [ENVIRONMENT [PACKAGE ...]] datacats install -c [q] [--address=IP] [ENVIRONMENT] Options: --address=IP The address to bind to when reloading after install -c --clean Reinstall packages ...
def column_types(self): """ Returns the column types. Returns ------- out : list[type] Column types of the SFrame. """ if self.__type__ == VERTEX_GFRAME: return self.__graph__.__proxy__.get_vertex_field_types() elif self.__type__ =...
Returns the column types. Returns ------- out : list[type] Column types of the SFrame.
def siblingsId(self): """ Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference """ if self._next_id is False or self._prev_id is False: self._prev_id, self._next_id = self.getPrevNextUrn(reference=se...
Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference
def do_POST(self, ): """Handle POST requests When the user is redirected, this handler will respond with a website which will send a post request with the url fragment as parameters. This will get the parameters and store the original redirection url and fragments in :data:`Logi...
Handle POST requests When the user is redirected, this handler will respond with a website which will send a post request with the url fragment as parameters. This will get the parameters and store the original redirection url and fragments in :data:`LoginServer.tokenurl`. :ret...
def request_upload_token(self, file): """ Request an upload token. :param file: A file handler pointing to the file to upload. :returns: True if the file uploaded successfully, False otherwise, \ and the JSON response from the API. :rtype: tuple """ s...
Request an upload token. :param file: A file handler pointing to the file to upload. :returns: True if the file uploaded successfully, False otherwise, \ and the JSON response from the API. :rtype: tuple
def getParentTiles(self, zoom, col, row, zoomParent): """ Return the parent tile(s) for an irregular (not following quadindex) and regular tiling scheme Parameters: zoom -- the zoom level a the child tile row -- the row of the child tile col -- the col...
Return the parent tile(s) for an irregular (not following quadindex) and regular tiling scheme Parameters: zoom -- the zoom level a the child tile row -- the row of the child tile col -- the col of the child tile zoomParent -- the target zoom of the parent...
def process_auth(self): """ Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx """ r = self._reader w = self._writer pdu_size = r.get_smallint() if not self.authentication: raise tds_base.Error('Got une...
Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
def randstring(l): """ Returns a random string of length l (l >= 0) """ return b"".join(struct.pack('B', random.randint(0, 255)) for _ in range(l))
Returns a random string of length l (l >= 0)
def caffe_to_tensorflow_session(caffe_def_path, caffemodel_path, inputs, graph_name='Graph', conversion_out_dir_path=None, use_padding_same=False): """Create a TensorFlow Session from a Caffe model.""" try: # noinspection PyUnresolvedReferences from caffeflow impo...
Create a TensorFlow Session from a Caffe model.
def absl_to_standard(level): """Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging. """ if not isinstance(lev...
Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging.
def notify(title, message, retcode=None): """ adapted from https://gist.github.com/baliw/4020619 """ try: import Foundation import objc except ImportError: import sys import logging logger = logging.getLogger(__name__) if sys.platform.startswith('darw...
adapted from https://gist.github.com/baliw/4020619
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
define a new Ladder setting and save to disk file
def serialize(self, serializable: Optional[Union[SerializableType, List[SerializableType]]]) \ -> PrimitiveJsonType: """ Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serializ...
Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serialization of the given object
def get_var_type(col): """ Return var_type (for KDEMultivariate) of the column Parameters ---------- col : pandas.Series A dataframe column. Returns ------- out : str One of ['c', 'o', 'u']. See Also -------- The origin of the character codes is :class:...
Return var_type (for KDEMultivariate) of the column Parameters ---------- col : pandas.Series A dataframe column. Returns ------- out : str One of ['c', 'o', 'u']. See Also -------- The origin of the character codes is :class:`statsmodels.nonparametric.kernel_d...
def join(strings: Optional[Sequence[str]], separator: str = "") -> str: """Join strings in a given sequence. Return an empty string if it is None or empty, otherwise join all items together separated by separator if provided. """ return separator.join(s for s in strings if s) if strings else ""
Join strings in a given sequence. Return an empty string if it is None or empty, otherwise join all items together separated by separator if provided.
def create_repo_from_pip_url(pip_url, **kwargs): r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: ...
r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo_fro...
def where_entry_last(query, ref): """ Generate a where clause where this is the last entry ref -- the entry of reference """ return orm.select( e for e in query if e.local_date < ref.local_date or (e.local_date == ref.local_date and e.id <= ref.id ) )
Generate a where clause where this is the last entry ref -- the entry of reference
def load_image(self, data, quiet=None): """ Load an image that was previously saved using :py:meth:`~docker.api.image.ImageApiMixin.get_image` (or ``docker save``). Similar to ``docker load``. Args: data (binary): Image data to be loaded. quiet (boolean):...
Load an image that was previously saved using :py:meth:`~docker.api.image.ImageApiMixin.get_image` (or ``docker save``). Similar to ``docker load``. Args: data (binary): Image data to be loaded. quiet (boolean): Suppress progress details in response. Returns: ...
def findAddressCandidates(self, addressDict=None, singleLine=None, maxLocations=10, outFields="*", outSR=4326, searchExtent=None, ...
The findAddressCandidates operation is performed on a geocode service resource. The result of this operation is a resource representing the list of address candidates. This resource provides information about candidates, including the address, location, and match score. Locators publishe...
def _find_usage_api_keys(self): """ Find usage on API Keys. Update `self.limits`. """ logger.debug('Finding usage for API Keys') key_count = 0 paginator = self.conn.get_paginator('get_api_keys') for resp in paginator.paginate(): key_count += le...
Find usage on API Keys. Update `self.limits`.
def load_entities(): """Load entities from JSON file.""" path = os.path.join(TOPDIR, 'entities.json') entities = json.load(open(path)) names = [i['name'] for i in entities] try: assert len(set(names)) == len(entities) except AssertionError: raise Exception('Entities with same na...
Load entities from JSON file.
def extract_slitlet2d(self, image_2k2k): """Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy arra...
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy array Image corresponding to the slitlet reg...
def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty requ...
Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: fo...
def p_sizeof(p): """ bexpr : SIZEOF LP type RP | SIZEOF LP ID RP | SIZEOF LP ARRAY_ID RP """ if TYPE.to_type(p[3].lower()) is not None: p[0] = make_number(TYPE.size(TYPE.to_type(p[3].lower())), lineno=p.lineno(3)) else: entry = SYMBOL_...
bexpr : SIZEOF LP type RP | SIZEOF LP ID RP | SIZEOF LP ARRAY_ID RP
def parsed_function_to_ast(parsed: Parsed, parsed_key): """Create AST for top-level functions""" sub = parsed[parsed_key] subtree = { "type": "Function", "span": sub["span"], "function": { "name": sub["name"], "name_span": sub["name_span"], "pare...
Create AST for top-level functions
def clear(self): """ Clears the text for this edit and resizes the toolbar information. """ super(XTextEdit, self).clear() self.textEntered.emit('') self.htmlEntered.emit('') if self.autoResizeToContents(): self.resizeToCont...
Clears the text for this edit and resizes the toolbar information.
def plan(self, sql, timeout=10): """ :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ sql = 'explain plan for ' + sql return self.query(sql, timeout)
:param sql: string :param timeout: int :return: pydrill.client.ResultQuery
def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True): """Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. ...
Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. This must include an equality against the hash key, and optionally one of a restricted set of condit...
def process_request(): """ Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is 'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the cache this method will return None an...
Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is 'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the cache this method will return None and clear the cache (this should only happen ...
def operations(self): """ All of the operations that are done by this functions. """ return [op for block in self.blocks for op in block.vex.operations]
All of the operations that are done by this functions.
def raw_search(cls, user, token, query, page=0): """Do a raw search for github issues. :arg user: Username to use in accessing github. :arg token: Token to use in accessing github. :arg query: String query to use in searching github. :arg page=0: Numbe...
Do a raw search for github issues. :arg user: Username to use in accessing github. :arg token: Token to use in accessing github. :arg query: String query to use in searching github. :arg page=0: Number of pages to automatically paginate. ~-~-~-~-~-~-~...
def _parse_tags(tag_file): """Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information. """ tag_name = None tag_value = None # Line folding is handled by yi...
Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information.
def set_queue_metadata(self, queue_name, metadata=None, timeout=None): ''' Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: ...
Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: A dict containing name-value pairs to associate with the queue as metadat...
def _get_mod_conditions(self, mod_term): """Return a list of ModConditions given a mod term dict.""" site = mod_term.get('site') if site is not None: mods = self._parse_site_text(site) else: mods = [Site(None, None)] mcs = [] for mod in mods: ...
Return a list of ModConditions given a mod term dict.
def _set_password_attributes(self, v, load=False): """ Setter method for password_attributes, mapped from YANG variable /password_attributes (container) If this variable is read-only (config: false) in the source YANG file, then _set_password_attributes is considered as a private method. Backends lo...
Setter method for password_attributes, mapped from YANG variable /password_attributes (container) If this variable is read-only (config: false) in the source YANG file, then _set_password_attributes is considered as a private method. Backends looking to populate this variable should do so via calling th...