Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,500
def _write_models_step(self, model, field=None): 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.
363,501
def shutdown(self): def _handle_shutdown_commit_success(result): self._shutdown_d, d = None, self._shutdown_d self.stop() self._shuttingdown = False d.callback((self._last_processed_offset, self._last_committed_offset...
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...
363,502
def _run_dnb_normalization(self, dnb_data, sza_data): dnb_data = xr.DataArray(dnb_data, dims=(, )) sza_data = xr.DataArray(sza_data, dims=(, )) good_mask = ~(dnb_data.isnull() | sza_data.isnull()) output_dataset = dnb_data.where(good_mask) output_datas...
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
363,503
def update_file(self, file_id, upload_id): put_data = { "upload[id]": upload_id, } return self._put("/files/" + file_id, put_data, content_type=ContentType.form)
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...
363,504
def makemessages(application, locale): from django.core.management import call_command if not locale: locale = with work_in(application): call_command(, locale=(locale,))
Updates the locale message files
363,505
def _split_on_reappear(cls, df, p, id_offset): next_id = id_offset + 1 added_ids = [] nt = p.sum(0) start = np.argmax(p, 0) end = np.argmax(np.cumsum(p, 0), 0) diff = end - start + 1 is_contiguous = np.equal(nt, diff) for id, contiguous in enumer...
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:
363,506
def forwarded(self) -> Tuple[Mapping[str, str], ...]: elems = [] for field_value in self._message.headers.getall(hdrs.FORWARDED, ()): length = len(field_value) pos = 0 need_separator = False elem = {} elems.append(types.MappingProxyT...
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...
363,507
def IsAllocated(self): 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.
363,508
def import_generated_autoboto(self): if str(self.config.build_dir) not in sys.path: sys.path.append(str(self.config.build_dir)) return importlib.import_module(self.config.target_package)
Imports the autoboto package generated in the build directory (not target_dir). For example: autoboto = botogen.import_generated_autoboto()
363,509
def function_type(self): 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
363,510
def team_info(): teams = __get_league_object().find().findall() 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
363,511
def hazard_notes(self): notes = [] hazard = definition(self.hazard.keywords.get()) if in hazard: notes += hazard[] if self.hazard.keywords[] == : if in hazard: notes += hazard[] if self.hazard.keywords[] == : if in ...
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::...
363,512
def update_key_bundle(key_bundle, diff): try: _add = diff[] except KeyError: pass else: key_bundle.extend(_add) try: _del = diff[] except KeyError: pass else: _now = time.time() for k in _del: k.inactive_since = _now
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
363,513
def common_params(task_instance, 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() task_cls_params_dict = dict(task_cls.get_params()) task_cls_param_names = t...
Grab all the values in task_instance that are found in task_cls.
363,514
def number_of_contacts(records, direction=None, more=0): if direction is None: counter = Counter(r.correspondent_id for r in records) else: counter = Counter(r.correspondent_id for r in records if r.direction == direction) return sum(1 for d in counter.values() if d > 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...
363,515
def _add_throughput(self, y, x, width, op, title, available, used): percent = float(used) / available self.win.addstr(y, x, "[") try: self.win.addstr(y, x + width - 1, "]") except curses.error: pass x += 1 ...
Write a single throughput measure to a row
363,516
def fetch_dictionary(name, url=None, format=None, index=0, rename=None, save=True, force_retrieve=False): csvtsvxls file_path = os.path.join(_get_dictionary_path(), name + ) if not force_retrieve and os.path.exists(file_path): df = pd.read_csv(file_path) index = datasets...
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 ...
363,517
def off(self): spotifyconnect._session_instance.player.off( spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery) assert spotifyconnect._session_instance.player.num_listeners( spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0 self._close()
Turn off the alsa_sink sink. This disconnects the sink from the relevant session events.
363,518
def bulk_upsert(self, docs, namespace, timestamp): 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.
363,519
def smart_query(query, filters=None, sort_attrs=None, schema=None): if not filters: filters = {} if not sort_attrs: sort_attrs = [] if not schema: schema = {} root_cls = query._joinpoint_zero().class_ attrs = list(filters.keys()) + \ list(map(lambda s: s....
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...
363,520
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.
363,521
def pull_requested_reviewers(self, pr_number): requested_reviewers_url = urijoin("pulls", str(pr_number), "requested_reviewers") return self.fetch_items(requested_reviewers_url, {})
Get pull requested reviewers
363,522
def propose(self): dims = self.stochastic.value.shape dev = rnormal( 0, self.adaptive_scale_factor * self.proposal_sd, size=dims) symmetrize(dev) self.stochastic.value = dev + self.stochastic.value
Proposals for positive definite matrix using random walk deviations on the Cholesky factor of the current value.
363,523
async def unset_lock(self, resource, lock_identifier): start_time = time.time() successes = await asyncio.gather(*[ i.unset_lock(resource, lock_identifier) for i in self.instances ], return_exceptions=True) successful_remvoes = sum(s is None for s in suc...
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...
363,524
def fibs(n, 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``.
363,525
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]: data = await self.user.http.saved_tracks(limit=limit, offset=offset) return [Track(self.__client, item[]) for item in data[]]
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...
363,526
def add_interface_router(router, subnet, profile=None): * conn = _auth(profile) return conn.add_interface_router(router, subnet)
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...
363,527
def atlasdb_cache_zonefile_info( con=None, path=None ): 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 = atlas_make_zonefile_inventory( 0, inv_len, con=con, path=path ) ...
Load up and cache our zonefile inventory from the database
363,528
def update(self, ttl=values.unset): 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
363,529
def concrete_emulate(self, insn): if not self.emu: self.emu = ConcreteUnicornEmulator(self) self.emu._stop_at = self._break_unicorn_at try: self.emu.emulate(insn) except unicorn.UcError as e: if e.errno == unicorn.UC_ERR_INSN_INVALID: ...
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
363,530
def pub(self, topic, message): with self.random_connection() as client: client.pub(topic, message) return self.wait_response()
Publish the provided message to the provided topic
363,531
def get_bin_lookup_session(self, proxy): if not self.supports_bin_lookup(): raise errors.Unimplemented() return sessions.BinLookupSession(proxy=proxy, runtime=self._runtime)
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...
363,532
def _captcha_form(self): try: last_attempt = FailedAccessAttempt.objects.get( ip_address=self._ip, is_locked=True, captcha_enabled=True, is_expired=False ) except FailedAccessAttempt.DoesNotExist: ...
captcha form :return:
363,533
def adsb_vehicle_encode(self, ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, callsign, emitter_type, tslc, flags, squawk): return MAVLink_adsb_vehicle_message(ICAO_address, lat, lon, altitude_type, altitude, heading, hor_velocity, ver_velocity, cal...
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...
363,534
def deprecated(message, exception=PendingDeprecationWarning): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.warn(message, exception, stacklevel=2) return func(*args, **kwargs) return wrapper return decorator
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...
363,535
def _get_namedrange(book, rangename, sheetname=None): def cond(namedef): if namedef.type.upper() == "RANGE": if namedef.name.upper() == rangename.upper(): if sheetname is None: if not namedef.localSheetId: return True ...
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...
363,536
def getTotalExpectedOccurrencesTicks_2_5(ticks): locs = [loc for label, loc in ticks] labels = [(str(label + 1) if (label + 1 == 2 or (label+1) % 5 == 0) else "") for label, loc in ticks] return locs, labels
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...
363,537
def createSummary(self, log): if self.warnCount: self.addCompleteLog("warnings (%d)" % self.warnCount, "\n".join(self.loggedWarnings) + "\n") warnings_stat = self.getStatistic(, 0) self.setStatistic(, warnings_stat + self.w...
Match log lines against warningPattern. Warnings are collected into another log for this step, and the build-wide 'warnings-count' is updated.
363,538
def get_space(self, current_result_list, current_query, param_space, runs, result_parsing_function): if result_parsing_function is None: result_parsing_function = CampaignManager.files_in_dictionary if not param_space: results = [...
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:: ...
363,539
def to_vobjects(self, filename, uids=None): self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add()) etag = md5() ...
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)
363,540
def _dx(self): min_x = max_x = self._start_x for drawing_operation in self: if hasattr(drawing_operation, ): min_x = min(min_x, drawing_operation.x) max_x = max(max_x, drawing_operation.x) return max_x - min_x
Return integer width of this shape's path in local units.
363,541
def search(self, query=None, args=None): if query is not None: return self._container_query(query) return self._search_all()
query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES:
363,542
def _try_passwordless_paramiko(server, keyfile): if paramiko is None: msg = "Paramiko unavaliable, " if sys.platform == : msg += "Paramiko is required for ssh tunneled connections on Windows." else: msg += "use OpenSSH." raise ImportError(msg) usernam...
Try passwordless login with paramiko.
363,543
def apply_transformation(self, structure, return_ranked_list=False): num_remove_dict = {} total_combis = 0 for indices, frac in zip(self.indices, self.fractions): num_to_remove = len(indices) * frac if abs(num_to_remove - int(round(num_to_remove))) > 1e-3: ...
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...
363,544
def rm(self, typ, id): return self._load(self._request(typ, id=id, method=))
remove typ by id
363,545
def deploy(self, site=None): r = self.local_renderer self.deploy_logrotate() cron_crontabs = [] for _site, site_data in self.iter_sites(site=site): r.env.cron_stdout_log = r.format(r.env.stdout_log_template) r.env.cron_stderr_log = r.format(r.env.stde...
Writes entire crontab to the host.
363,546
def evaluate(self, reference_scene_list, estimated_scene_list=None, estimated_scene_probabilities=None): if estimated_scene_list is None and estimated_scene_probabilities is None: raise ValueError("Nothing to evaluate, give at least estimated_scene_list or estimated_scene_probabilities") ...
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...
363,547
def resolve(self, current_file, rel_path): p = path.join(path.dirname(current_file), rel_path) if p not in self.file_dict: raise RuntimeError( % p) return p, p
Search the filesystem.
363,548
def get_datacenter(content, obj): 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
363,549
def _transform_stats(prof): 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: percentage = 0 else: ...
Processes collected stats for UI.
363,550
def udp_send(udpsock, frame, address, addrlen): return lib.zsys_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 ***
363,551
def window_size(self, value): if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size must be an odd number " "b...
Set private ``_window_size`` and reset ``_block_matcher``.
363,552
def TAPQuery(query): tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync" tapParams={: , : , : , : query} cnt=0 while True: try: print "running query" r=urllib2.urlopen(tapURL,urllib.urlencode(tapParams)) ...
The __main__ part of the script
363,553
def zoom_leftup(self, event=None): 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: dx, dy = 0, 0 t0 = time.time() self....
leftup event handler for zoom mode in images
363,554
def _string_to_byte_list(self, data): bytes_length = 16 m = self.digest() m.update(str.encode(data)) hex_digest = m.hexdigest() return list(int(hex_digest[num * 2:num * 2 + 2], bytes_length) for num in range(bytes_length))
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)
363,555
def read(self,filename,datatype=None,slaext=False,**kwargs): fname,extension = os.path.splitext(filename) if os.path.basename(filename).count() > os.path.basename(filename).count(): delim= else : delim = if datatype is None : ...
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...
363,556
def append(self, 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.
363,557
def _rewrite_and_copy(src_file, dst_file, project_name): fh, abs_path = mkstemp() with io.open(abs_path, , encoding=) as new_file: with io.open(src_file, , encoding=) as old_file: for line in old_file: new_line = line.replace(, project_name). \ ...
Replace vars and copy.
363,558
def get_vaults_by_ids(self, *args, **kwargs): catalogs = self._get_provider_session().get_vaults_by_ids(*args, **kwargs) cat_list = [] for cat in catalogs: cat_list.append(Vault(self._provider_manager, cat, self._runtime, self._proxy)) return VaultL...
Pass through to provider VaultLookupSession.get_vaults_by_ids
363,559
def calculate(self, **state): T = state[] x = state[] compounds_sio2 = [, , , ] compounds_cao = [, , , , , ] compounds_al2o3 = [] compounds_caf2 = [] compounds_na2o = [, ] compounds_all = (compounds_sio2 + compounds_cao + compounds_al2o...
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 ...
363,560
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): self._halt_if_already_deleted() rrset_kwargs = dict( connection=self.connection, ...
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.
363,561
def get_data(self): try: return DocumentDataDict(self.__dict__[]) except KeyError: self._lazy_load() return DocumentDataDict(self.__dict__[])
Fetch the data field if it does not exist.
363,562
def hello(environ, start_response): if environ[] == : data = b status = response_headers = [ (, ), (, str(len(data))) ] start_response(status, response_headers) return iter([data]) else: raise MethodNotAllowed
The WSGI_ application handler which returns an iterable over the "Hello World!" message.
363,563
def ystep(self): r 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}`.
363,564
def verify(self): collections = self.get_data_collections() allIDs = [] for coll in collections: IDs = self.noteDB[coll].find({"ID": {"$exists": True}}, {"ID": 1, "_id": 0}) for ID in IDs: allIDs.append(in...
: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
363,565
def install(environment, opts): environment.require_data() install_all(environment, opts[], verbose=not opts[], packages=opts[]) for site in environment.sites: environment = Environment.load(environment.name, site) if in environment.containers_running(): ...
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 ...
363,566
def column_types(self): if self.__type__ == VERTEX_GFRAME: return self.__graph__.__proxy__.get_vertex_field_types() elif self.__type__ == EDGE_GFRAME: return self.__graph__.__proxy__.get_edge_field_types()
Returns the column types. Returns ------- out : list[type] Column types of the SFrame.
363,567
def siblingsId(self): if self._next_id is False or self._prev_id is False: self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._prev_id, self._next_id
Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference
363,568
def do_POST(self, ): log.debug() self._set_headers() ruri = constants.REDIRECT_URI.replace(, ) self.server.set_token(ruri + self.path.replace(, ))
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...
363,569
def request_upload_token(self, file): self.kwargs[] = os.path.basename(file.name) self.kwargs[] = os.fstat(file.fileno()).st_size response = self._requester.request( , self.url, _kwargs=combine_kwargs(**self.kwargs) ) return self.upl...
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
363,570
def getParentTiles(self, zoom, col, row, zoomParent): assert zoomParent <= zoom if zoomParent == zoom: return [[zoom, col, row]] extent = self.tileBounds(zoom, col, row) minRow, minCol, maxRow, maxCol = self.getExtentAddress( zoomParent, extent=extent, co...
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...
363,571
def process_auth(self): r = self._reader w = self._writer pdu_size = r.get_smallint() if not self.authentication: raise tds_base.Error() packet = self.authentication.handle_next(readall(r, pdu_size)) if packet: w.write(packet) ...
Reads and processes SSPI stream. Stream info: http://msdn.microsoft.com/en-us/library/dd302844.aspx
363,572
def randstring(l): return b"".join(struct.pack(, random.randint(0, 255)) for _ in range(l))
Returns a random string of length l (l >= 0)
363,573
def caffe_to_tensorflow_session(caffe_def_path, caffemodel_path, inputs, graph_name=, conversion_out_dir_path=None, use_padding_same=False): try: from caffeflow import convert except ImportError: raise Exception("caffeflow package needs to be install...
Create a TensorFlow Session from a Caffe model.
363,574
def absl_to_standard(level): if not isinstance(level, int): raise TypeError(.format(type(level))) if level < ABSL_FATAL: level = ABSL_FATAL if level <= ABSL_DEBUG: return ABSL_TO_STANDARD[level] return STANDARD_DEBUG - level + 1
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.
363,575
def notify(title, message, retcode=None): try: import Foundation import objc except ImportError: import sys import logging logger = logging.getLogger(__name__) if sys.platform.startswith() and hasattr(sys, ): logger.error( "Using ...
adapted from https://gist.github.com/baliw/4020619
363,576
def addLadder(settings): ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
define a new Ladder setting and save to disk file
363,577
def serialize(self, serializable: Optional[Union[SerializableType, List[SerializableType]]]) \ -> PrimitiveJsonType: if serializable is None: return None elif isinstance(serializable, List): return [self.serialize(item) for item in serializable] ...
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
363,578
def get_var_type(col): if pdtypes.is_numeric_dtype(col): return elif pdtypes.is_categorical_dtype(col): return if col.cat.ordered else else: return
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...
363,579
def join(strings: Optional[Sequence[str]], separator: str = "") -> str: 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.
363,580
def create_repo_from_pip_url(pip_url, **kwargs): r if pip_url.startswith(): return GitRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith(): return MercurialRepo.from_pip_url(pip_url, **kwargs) elif pip_url.startswith(): return SubversionRepo.from_pip_url(pip_url, **kwar...
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...
363,581
def where_entry_last(query, ref): 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
363,582
def load_image(self, data, quiet=None): params = {} if quiet is not None: if utils.version_lt(self._version, ): raise errors.InvalidVersion( ) params[] = quiet res = self._post( self._url("/images...
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: ...
363,583
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...
363,584
def _find_usage_api_keys(self): logger.debug() key_count = 0 paginator = self.conn.get_paginator() for resp in paginator.paginate(): key_count += len(resp[]) self.limits[]._add_current_usage( key_count, aws_type= )
Find usage on API Keys. Update `self.limits`.
363,585
def load_entities(): path = os.path.join(TOPDIR, ) entities = json.load(open(path)) names = [i[] for i in entities] try: assert len(set(names)) == len(entities) except AssertionError: raise Exception( % [i for i in names if ...
Load entities from JSON file.
363,586
def extract_slitlet2d(self, image_2k2k): naxis2, naxis1 = image_2k2k.shape if naxis1 != EMIR_NAXIS1: raise ValueError() if naxis2 != EMIR_NAXIS2: raise ValueError() slitlet2d = image_2k2k[(self.bb_ns1_orig - 1):self.bb_ns2_orig, ...
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...
363,587
def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 ...
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...
363,588
def p_sizeof(p): 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_TABLE.get_id_or_make_var(p[3], p.lineno(1)) p[0] = make_number(TYPE.size(entry.type_), lineno=p.l...
bexpr : SIZEOF LP type RP | SIZEOF LP ID RP | SIZEOF LP ARRAY_ID RP
363,589
def parsed_function_to_ast(parsed: Parsed, parsed_key): sub = parsed[parsed_key] subtree = { "type": "Function", "span": sub["span"], "function": { "name": sub["name"], "name_span": sub["name_span"], "parens_span": sub.get("parens_span", []), ...
Create AST for top-level functions
363,590
def clear(self): super(XTextEdit, self).clear() self.textEntered.emit() self.htmlEntered.emit() if self.autoResizeToContents(): self.resizeToContents()
Clears the text for this edit and resizes the toolbar information.
363,591
def plan(self, sql, timeout=10): sql = + sql return self.query(sql, timeout)
:param sql: string :param timeout: int :return: pydrill.client.ResultQuery
363,592
def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True): if isinstance(model_or_index, Index): model, index = model_or_index.model, model_or_index else: model, index = model_or_index, None validate_not_abstract(model) ...
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...
363,593
def process_request(): g.request_dict = safe_load(request.get_data()) entity_type = g.request_dict[] entity_id = g.request_dict[entity_type][] ImportRequest.logger.debug("Received request, type={0}, id={1}".format(entity_type, entity_id)) entity = ImportRequest._get_enti...
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 ...
363,594
def operations(self): return [op for block in self.blocks for op in block.vex.operations]
All of the operations that are done by this functions.
363,595
def raw_search(cls, user, token, query, page=0): page = int(page) kwargs = {} if not user else {: (user, token)} my_url = cls.search_url data = {: []} while my_url: cls.sleep_if_necessary( user, token, msg= % str(query)) my_req = r...
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. ~-~-~-~-~-~-~...
363,596
def _parse_tags(tag_file): tag_name = None tag_value = None for num, line in enumerate(tag_file): if num == 0: if line.startswith(BOM): line = line.lstrip(BOM) if len(line) == 0 or line.isspace(): continue eli...
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.
363,597
def set_queue_metadata(self, queue_name, metadata=None, timeout=None): _validate_not_none(, queue_name) request = HTTPRequest() request.method = request.host_locations = self._get_host_locations() request.path = _get_path(queue_name) request.query = { ...
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...
363,598
def _get_mod_conditions(self, mod_term): site = mod_term.get() if site is not None: mods = self._parse_site_text(site) else: mods = [Site(None, None)] mcs = [] for mod in mods: mod_res, mod_pos = mod mod_type_str = mod_ter...
Return a list of ModConditions given a mod term dict.
363,599
def _set_password_attributes(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=password_attributes.password_attributes, is_container=, presence=False, yang_name="password-attributes", rest_name="password-attributes", parent=self, path_helper=self._path_...
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...