Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
350,900
def from_json(payload): return payload and \ Place([ (float(lon), float(lat), float(alt)) for (lon, lat, alt) in payload[]] if payload.get() else GeoPoint.from_json(payload[]), address=payload.get() and ( Place.__parse_address__(pay...
Build a ``Place`` instance from the specified JSON object. @param payload: JSON representation of a place:: { "area_id": string, "address": { component_type: string, ... } \ [ { ...
350,901
def bethe_fermi_ene(energy, quasipart, shift, hopping, beta): return energy * bethe_fermi(energy, quasipart, shift, hopping, beta)
product of the bethe lattice dos, fermi distribution an weighted by energy
350,902
def _create_x_y(l, duration=1): l = [0] + l + [0] y = [] x = [] for i, bit in enumerate(l): y.append(bit) y.append(bit) x.append((i - 1) * duration) x.append(i * duration) return x, y
Create 2 lists x: time (as unit of dot (dit) y: bits from a list of bit >>> l = [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1] >>> x, y = _create_x_y(l) >>> x [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, ...
350,903
def queue(self): if not self.include_rq: return None ctx = stack.top if ctx is not None: if not hasattr(ctx, ): ctx.redislite_queue = {} for queue_name in self.queues: ctx.redislite_queue[queue_name] = \ ...
The queue property. Return rq.Queue instance.
350,904
def parse_database_url(url): if url == : return { : DATABASE_SCHEMES[], : } config = {} url = urlparse.urlparse(url) path = url.path[1:] path = path.split(, 2)[0] if url.scheme == and path...
Parses a database URL.
350,905
def _advertisement(self): flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4) return struct.pack("<LH", self.device.iotile_id, flags)
Create advertisement data.
350,906
def is_all_field_none(self): if self._alias is not None: return False if self._user_alias_created is not None: return False if self._user_alias_revoked is not None: return False if self._counter_user_alias is not None: return F...
:rtype: bool
350,907
def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs): if busnum is None: busnum = get_default_bus() return Device(address, busnum, i2c_interface, **kwargs)
Return an I2C device for the specified address and on the specified bus. If busnum isn't specified, the default I2C bus for the platform will attempt to be detected.
350,908
def add_digital_object( self, information_object_slug, identifier=None, title=None, uri=None, location_of_originals=None, object_type=None, xlink_show="embed", xlink_actuate="onLoad", restricted=False, use_statement="", use_...
Creates a new digital object.
350,909
def _normalize_files(item, fc_dir=None): files = item.get("files") if files: if isinstance(files, six.string_types): files = [files] fastq_dir = flowcell.get_fastq_dir(fc_dir) if fc_dir else os.getcwd() files = [_file_to_abs(x, [os.getcwd(), fc_dir, fastq_dir]) for x in ...
Ensure the files argument is a list of absolute file names. Handles BAM, single and paired end fastq, as well as split inputs.
350,910
def _compute_soil_amplification(cls, C, vs30, pga_rock, imt): return AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification( C, vs30, pga_rock, imt)
Compute soil amplification (5th, 6th, and 7th terms in equation 1, page 1706) and add the B/C site condition as implemented by NSHMP. Call :meth:`AtkinsonBoore2003SInterNSHMP2008._compute_soil_amplification`
350,911
def handle_report_metric_data(self, data): if data[] == : self._handle_final_metric_data(data) elif data[] == : if self.assessor is not None: self._handle_intermediate_metric_data(data) else: pass else: rais...
data: a dict received from nni_manager, which contains: - 'parameter_id': id of the trial - 'value': metric value reported by nni.report_final_result() - 'type': report type, support {'FINAL', 'PERIODICAL'}
350,912
def head_tail_middle(src): if len(src) == 0: return None, [], None if len(src) == 1: return src[0], [], None if len(src) == 2: return src[0], [], src[1] return src[0], src[1:-1], src[-1]
Returns a tuple consisting of the head of a enumerable, the middle as a list and the tail of the enumerable. If the enumerable is 1 item, the middle will be empty and the tail will be None. >>> head_tail_middle([1, 2, 3, 4]) 1, [2, 3], 4
350,913
def login(self, response): self._state_params[] = response[] self._user_data = response[] if not self.logged_in: raise ApiLoginFailure(response)
Login using email/username and password, used to get the auth token @param str account @param str password @param int duration (optional)
350,914
def build_model(): train_data_node = tf.placeholder(tf.float32,shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)) train_labels_node = tf.placeholder(tf.float32,shape=(BATCH_SIZE, NUM_LABELS)) validation_data_node= tf.placeholder(tf.float32,shape=(VALIDATION_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS...
Builds the computation graph consisting of training/testing LeNet train data - used for learning validation data - used for printing progress (does not impact learning) test data - used for printing final test error
350,915
def get_semaphore(name, value=None, debug=False): if value is None: lock = threading.Semaphore() else: lock = threading.BoundedSemaphore(value) if debug: lock = DebugLock(lock, name) return lock
Get a new semaphore. @param value: if not None, a BoundedSemaphore will be used @ptype debug: int or None @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a semaphore object @rtype: threading.Semaphore or threading.BoundedSe...
350,916
def finalize(self): self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(SnFloatCtiEditor, self).finalize()
Called at clean up. Is used to disconnect signals.
350,917
def get_auto_credentials(self, bucket): result = {k: v(self) for k, v in self.get_unique_creds_dict().items()} if bucket: result.update(self.get_cred_bucket(bucket)) else: result.update(self.get_cred_not_bucket()) return result
:param bucket: :return: returns a dictionary of credentials for bucket/admin authentication
350,918
def remove_link(self, rel, value=None, href=None): links_node = self.metadata.find() if links_node is None: log.warning() return False counter = 0 links = links_node.xpath(.format(rel)) for link in links: if value and href: ...
Removes link nodes based on the function arguments. This can remove link nodes based on the following combinations of arguments: link/@rel link/@rel & link/text() link/@rel & link/@href link/@rel & link/text() & link/@href :param rel: link/@rel value to ...
350,919
def _update_info(self, target_id): pk = CRTPPacket() pk.set_header(0xFF, 0xFF) pk.data = (target_id, 0x10) self.link.send_packet(pk) pk = self.link.receive_packet(2) if (pk and pk.header == 0xFF and struct.unpack(, pk.data[0:2]) == ...
Call the command getInfo and fill up the information received in the fields of the object
350,920
def init(self, fle=None): if fle is None: fname = self.kwargs.get(, self.GMPE_TABLE) if fname is None: raise ValueError() elif os.path.isabs(fname): self.GMPE_TABLE = fname else: self.GMPE_T...
Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory.
350,921
def _populate_examples(self): for namespace in self.api.namespaces.values(): for data_type in namespace.data_types: for example in data_type._ast_node.examples.values(): data_type._add_example(example) for namespace in self.api.namespaces.values(...
Construct every possible example for every type. This is done in two passes. The first pass assigns examples to their associated types, but does not resolve references between examples for different types. This is because the referenced examples may not yet exist. The second pass resolv...
350,922
def load_swagger_spec(self, filepath=None): if filepath is True or filepath is None: filepath = self.file_spec.format(server=self.server) return json.load(open(filepath))
Loads the origin_spec from a local JSON file. If `filepath` is not provided, then the class `file_spec` format will be used to create the file-path value.
350,923
def add(self, error): if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError`
350,924
def requires_auth(self, roles=None): def requires_auth_inner(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return MeteorApp.authentication_failure(message=) user_id = a...
Used to impose auth constraints on requests which require a logged in user with particular roles. :param list[string] roles: A list of :class:`string` representing roles the logged in user must have to perform this action. The user and password are passed in each request in the authoriz...
350,925
def compile(conf): with errorprint(): config = ConfModule(conf) for conf in config.configurations: conf.format(do_print=True)
Compiles classic uWSGI configuration file using the default or given `uwsgiconf` configuration module.
350,926
def compute_cell_sizes(dataset, length=False, area=True, volume=True): alg = vtk.vtkCellSizeFilter() alg.SetInputDataObject(dataset) alg.SetComputeArea(area) alg.SetComputeVolume(volume) alg.SetComputeLength(length) alg.SetComputeVertexCount(False) alg.Up...
This filter computes sizes for 1D (length), 2D (area) and 3D (volume) cells. Parameters ---------- length : bool Specify whether or not to compute the length of 1D cells. area : bool Specify whether or not to compute the area of 2D cells. volume...
350,927
def zip_and_tuple(self, x): return tuple(self.space.zip_inputs(np.atleast_2d(x)).flatten())
convenient helper :param x: input configuration in the model space :return: zipped x as a tuple
350,928
def __load_unique_identity(self, uidentity, verbose): uuid = uidentity.uuid if uuid: try: api.unique_identities(self.db, uuid) self.log("-- %s already exists." % uuid, verbose) return uuid except NotFoundError as e: ...
Seek or store unique identity
350,929
def get(self, limit=None, offset=None): return self.connection.get(, limit=limit, offset=offset)
:param offset: int of the offset to use :param limit: int of max number of puzzles to return :return: list of Transfer dict
350,930
def json_data(self): return { "type": self.type, "origin_id": self.origin_id, "network_id": self.network_id, "contents": self.contents, }
The json representation of an info.
350,931
def _GetDayOfYear(self, year, month, day_of_month): if month not in range(1, 13): raise ValueError() days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError() day_of_year = day_of_month for past_month in range(1, m...
Retrieves the day of the year for a specific day of a month in a year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. Returns: int: day of year. Raises: ValueError: if ...
350,932
def fetch(self, from_time, until_time=None): until_time = until_time or datetime.now() time_info, values = whisper.fetch(self.path, from_time.strftime(), until_time.strftime()) start_time, end_t...
This method fetch data from the database according to the period given fetch(path, fromTime, untilTime=None) fromTime is an datetime untilTime is also an datetime, but defaults to now. Returns a tuple of (timeInfo, valueList) where timeInfo is itself a tuple of (fromTi...
350,933
def path_helper(self, operations, view, **kwargs): operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) app = kwargs.get(, _default_app) route = self._route_for_view(app, view) return self.bottle_path_to_openapi(route.rule)
Path helper that allows passing a bottle view function.
350,934
def neg_loglikelihood(y, mean, scale, shape, skewness): return -np.sum(ss.t.logpdf(x=y, df=shape, loc=mean, scale=scale))
Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the t distribution scale : float scale parameter for the t distribution shape : float ...
350,935
def format_plugin(plugin): type = "Other" for order, _type in {pyblish.plugin.CollectorOrder: "Collector", pyblish.plugin.ValidatorOrder: "Validator", pyblish.plugin.ExtractorOrder: "Extractor", pyblish.plugin.IntegratorOrder: "In...
Serialise `plugin` Attributes: name: Name of Python class id: Unique identifier version: Plug-in version category: Optional category requires: Plug-in requirements order: Plug-in order optional: Is the plug-in optional? doc: The plug-in documentation ...
350,936
def _read_para_ack(self, code, cbit, clen, *, desc, length, version): if clen % 4 != 0: raise ProtocolError(f) _upid = list() for _ in range(clen // 4): _upid.append(self._read_unpack(4)) ack = dict( type=desc, critical=cbit, ...
Read HIP ACK parameter. Structure of HIP ACK parameter [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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ...
350,937
async def authenticateHawk(self, *args, **kwargs): return await self._makeApiCall(self.funcinfo["authenticateHawk"], *args, **kwargs)
Authenticate Hawk Request Validate the request signature given on input and return list of scopes that the authenticating client has. This method is used by other services that wish rely on Taskcluster credentials for authentication. This way we can use Hawk without having the ...
350,938
def _s3am_with_retry(job, num_cores, file_path, s3_url, mode=, s3_key_path=None): container_key_file = None base_boto = base_aws = docker_home_dir = credentials_to_mount = {os.path.join(os.path.expanduser("~"), path): os.path.join(docker_home_dir, path) ...
Run s3am with 3 retries :param toil.job.Job job: Toil job that is calling this function :param int num_cores: Number of cores to pass to upload/download slots :param str file_path: Full path to the file :param str s3_url: S3 URL :param str mode: Mode to run s3am in. Either "upload" or "download" ...
350,939
def try_delegation(method): @functools.wraps(method) def delegator(self, *args, **kwargs): if self.try_delegation: func = getattr(inst, method_name, None) if func is not None: return func(*args, **kwargs) return meth...
This decorator wraps descriptor methods with a new method that tries to delegate to a function of the same name defined on the owner instance for convenience for dispatcher clients.
350,940
def filter_by_date( df, date_col: str, date_format: str = , start: str = None, stop: str = None, atdate: str = None ): mask = None if start is None and stop is None and atdate is None: raise TypeError() if start is not None and atdate is not None: raise TypeError...
Filter dataframe your data by date. This function will interpret `start`, `stop` and `atdate` and build the corresponding date range. The caller must specify either: - `atdate`: keep all rows matching this date exactly, - `start`: keep all rows matching this date onwards. - `stop`: keep all rows m...
350,941
def validate_type(prop, value, expected): if value is not None and not isinstance(value, expected): _validation_error(prop, type(value).__name__, None, expected)
Default validation for all types
350,942
def redirect(self, url, status=None): self.status_code = 302 if status is None else status self.headers = Headers([(, url)]) self.message = self.end()
Redirect to the specified url, optional status code defaults to 302.
350,943
def reduce(self, f): f = fail_on_stopiteration(f) def func(iterator): iterator = iter(iterator) try: initial = next(iterator) except StopIteration: return yield reduce(f, iterator, initial) vals = self.map...
Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cac...
350,944
def _dens(self,R,z,phi=0.,t=0.): if self.isNonAxi: R2= R**2. Rt2= R2*(1.-self._1m1overb2*nu.sin(phi)**2.) denom= 1./(Rt2+(z/self._q)**2.+self._core2) denom2= denom**2. return 1./4./nu.pi\ *(2.*Rt2/R2*(denom-Rt2*denom2)\ ...
NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the density HISTORY:
350,945
def ConnectHandler(*args, **kwargs): if kwargs["device_type"] not in platforms: raise ValueError( "Unsupported device_type: " "currently supported platforms are: {}".format(platforms_str) ) ConnectionClass = ssh_dispatcher(kwargs["device_type"]) return Connection...
Factory function selects the proper class and creates object based on device_type.
350,946
def _bnd(self, xloc, dist, cache): return numpy.log10(evaluation.evaluate_bound( dist, 10**xloc, cache=cache))
Distribution bounds.
350,947
def namedb_get_num_names( cur, current_block, include_expired=False ): unexpired_query = "" unexpired_args = () if not include_expired: unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block ) unexpired_query = .format(unexpired_query) query ...
Get the number of names that exist at the current block
350,948
def set_flowcontrol_receive(self, name, value=None, default=False, disable=False): return self.set_flowcontrol(name, , value, default, disable)
Configures the interface flowcontrol receive value Args: name (string): The interface identifier. It must be a full interface name (ie Ethernet, not Et) value (boolean): True if the interface should enable receiving flow control packets, otherwise False...
350,949
def create(type_dict, *type_parameters): name, values = type_parameters assert isinstance(values, (list, tuple)) for value in values: assert isinstance(value, Compatibility.stringy) return TypeMetaclass(str(name), (EnumContainer,), { : values })
EnumFactory.create(*type_parameters) expects: enumeration name, (enumeration values)
350,950
def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): if jd is not None: tdb = jd else: tdb = julian_date( _to_array(year), _to_array(month), _to_array(day), _to_array(hour), _to_array(minute), _to_ar...
Build a `Time` from a TDB calendar date. Supply the Barycentric Dynamical Time (TDB) as a proleptic Gregorian calendar date: >>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5) >>> t.tdb 2456675.56640625
350,951
def optimize_hyperparameters(self, problems, parameter_locks=None, smoothing=20, max_iterations=100, _meta_optimizer=None, ...
Optimize hyperparameters for a given problem. Args: parameter_locks: a list of strings, each corresponding to a hyperparamter that should not be optimized. problems: Either a single problem, or a list of problem instances, allowing optim...
350,952
async def component_coro_wrapper(coro_func: CoroutineFunction[T], *args: Any, commands: PipeEnd, events: PipeEnd, **kwargs: Any) -> T: try: return await coro_func(*args, commands=commands, events=events, **kwargs) except Exception as err: raise Component.Fai...
\ This function wraps a component workload to conform to the required lifecycle. The following behavior is the passed coroutine function's responsibility: - it must send `Component.EVENT_START` to its owner after the task is initialized; - it must not send EOF on the event pipe; - when `Component.C...
350,953
async def process_message(self, message, wait=True): to_check = deque([self._waiters]) ignored = True while len(to_check) > 0: context = to_check.popleft() waiters = context.get(OperationManager._LEAF, []) for waiter in waiters: if ...
Process a message to see if it wakes any waiters. This will check waiters registered to see if they match the given message. If so, they are awoken and passed the message. All matching waiters will be woken. This method returns False if the message matched no waiters so it was ...
350,954
def setup_pilotpoints_grid(ml=None,sr=None,ibound=None,prefix_dict=None, every_n_cell=4, use_ibound_zones=False, pp_dir=,tpl_dir=, shapename="pp.shp"): import flopy if ml is not None: asser...
setup grid-based pilot points. Uses the ibound to determine where to set pilot points. pilot points are given generic ``pp_`` names unless ``prefix_dict`` is passed. Write template files and a shapefile as well...hopefully this is useful to someone... Parameters ---------- ml : flopy.mbase ...
350,955
def get_top_artists(self, period=PERIOD_OVERALL, limit=None): params = self._get_params() params["period"] = period if limit: params["limit"] = limit doc = self._request(self.ws_prefix + ".getTopArtists", True, params) return _extract_top_artists(doc, self...
Returns the top artists played by a user. * period: The period of time. Possible values: o PERIOD_OVERALL o PERIOD_7DAYS o PERIOD_1MONTH o PERIOD_3MONTHS o PERIOD_6MONTHS o PERIOD_12MONTHS
350,956
def verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW, sl=None, timeout=None): otps = [] for otp in otp_list: otps.append(OTP(otp, self.translate_otp)) if len(otp_list) < 2: raise ValueError() device_ids...
Verify a provided list of OTPs. :param max_time_window: Maximum number of seconds which can pass between the first and last OTP generation for the OTP to still be considered valid. :type max_time_window: ``int``
350,957
def _send_to_destinations(self, destinations, message, header=None, **kwargs): if not isinstance(destinations, list): destinations = (destinations,) for destination in destinations: self._send_to_destination(destination, header, message, kwargs)
Send messages to a list of numbered destinations. This is an internal helper method used by the public 'send' methods.
350,958
def init_config(args): os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval) if args.db: try: db_address_reg = re.compile(r"(.*)://(.*):(.*)@(.*):(.*)/(.*)") ...
Initialize configs of the service. Do the following things: 1. automl board settings 2. database settings 3. django settings
350,959
def _update_file_args(self, file_mapping): for key, value in self.args.items(): new_value = file_mapping.get(value, value) if new_value != value: self.args[key] = new_value
Adjust the arguments to deal with staging files to the scratch area
350,960
def getDataRowCount(self): inputRowCountAfterAggregation = 0 while True: record = self.getNextRecord() if record is None: return inputRowCountAfterAggregation inputRowCountAfterAggregation += 1 if inputRowCountAfterAggregation > 10000: raise RuntimeError()
Iterates through stream to calculate total records after aggregation. This will alter the bookmark state.
350,961
def nlmsg_flags(self, value): self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0))
Message flags setter.
350,962
def rich_club_wd(CIJ, klevel=None): nr_nodes = len(CIJ) deg = np.sum((CIJ != 0), axis=0) + np.sum((CIJ.T != 0), axis=0) if klevel is None: klevel = np.max(deg) Rw = np.zeros((klevel,)) wrank = np.sort(CIJ.flat)[::-1] for k in range(klevel): SmallNodes, = np.wher...
Parameters ---------- CIJ : NxN np.ndarray weighted directed connection matrix klevel : int | None sets the maximum level at which the rich club coefficient will be calculated. If None (default), the maximum level is set to the maximum degree of the adjacency matrix Retu...
350,963
def getMaskArray(self, signature): if signature in self.masklist: mask = self.masklist[signature] else: mask = None return mask
Returns the appropriate StaticMask array for the image.
350,964
def create_cache_database(self): conn = sqlite3.connect(self.database) conn.text_factory = str c = conn.cursor() c.execute() c.execute() c.execute() conn.commit() conn.close()
Create a new SQLite3 database for use with Cache objects :raises: IOError if there is a problem creating the database file
350,965
def get_all_attributes(self): all_attributes = OrderedDict() if self.__preserve_order else dict() for attributes in self.__sections.itervalues(): for attribute, value in attributes.iteritems(): all_attributes[attribute] = value return all_attributes
Returns all sections attributes. Usage:: >>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \ "[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_parser = SectionsFileParser() >>> sections_file_parser.content = conte...
350,966
def org_find_apps(org_id, name=None, name_mode=, category=None, all_versions=None, published=None, created_by=None, developer=None, authorized_user=None, crea...
:param name: Name of the app (also see *name_mode*) :type name: string :param name_mode: Method by which to interpret the *name* field "exact": exact match, "glob": use "*" and "?" as wildcards, "regexp": interpret as a regular expression :type name_mode: string :param category: ...
350,967
def print_status(self, roles=None, state_filter="running"): if not roles: for instance in self._get_instances(self._get_cluster_group_name(), state_filter): self._print_instance("", instance) else: for role in roles: for instance in self...
Print the status of instances in the given roles, filtered by state.
350,968
def SUBS(self, params): try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params) except iarm.exceptions.ParsingError: Rb, Rc = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) Ra =...
SUBS [Ra,] Rb, Rc SUBS [Ra,] Rb, #imm3 SUBS [Ra,] Ra, #imm8 Subtract Rc or an immediate from Rb and store the result in Ra Ra, Rb, and Rc must be low registers If Ra is omitted, then it is assumed to be Rb
350,969
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): if not current_app.testing: try: from sendgrid.helpers.mail import Email, Content, Substitution, Mail from_email = Email(sender_email,...
Send email message via sendgrid-python. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text.
350,970
def process_nxml_str(nxml_str, output_fmt=, outbuf=None, cleanup=True, key=, **kwargs): tmp_fname = % (key, mp.current_process().pid) with open(tmp_fname, ) as fh: fh.write(nxml_str.encode()) try: sp = process_nxml_file(tmp_fname, output_fmt, outbuf, cleanup, ...
Return processor with Statements extracted by reading an NXML string. Parameters ---------- nxml_str : str The string value of the NXML-formatted paper to be read. output_fmt: Optional[str] The output format to obtain from Sparser, with the two options being 'json' and 'xml'. De...
350,971
def parsePyLintWarnings(warnings): warningsDict = {} for line in warnings: match = re.search(P_PYLINT_ERROR, line) if match: matchDict = match.groupdict() if not warningsDict.get(matchDict["file"]): warningsDict[matchDict["file"]] = [] ...
Turns pyLint/TwistedChecker output into something more useful. @param warnings: The warnings to process. Needs to be in pyLint's 'parseable' format. @return: L{dict} of L{list}s
350,972
def find_postgame(data, size): pos = None for i in range(size - SEARCH_MAX_BYTES, size - LOOKAHEAD): op_type, length, action_type = struct.unpack(, data[i:i + LOOKAHEAD]) if op_type == 0x01 and length == POSTGAME_LENGTH and action_type == 0xFF: LOGGER.debug("found postgame candi...
Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pattern signals the start of the pos...
350,973
def get_loci_fasta(loci, out_fa, ref): if not find_cmd("bedtools"): raise ValueError("Not bedtools installed") with make_temp_directory() as temp: bed_file = os.path.join(temp, "file.bed") for nc, loci in loci.iteritems(): for l in loci: with open(bed_fil...
get fasta from precursor
350,974
def feed(self, data): assert isinstance(data, binary_type) self.parser.feed(data) self.cli._redraw() if self.cli.is_returning: try: return_value = self.cli.return_value() except (EOFError, KeyboardInterrupt) as e: ...
Handler for incoming data. (Called by TelnetServer.)
350,975
def key_list(items=None): if items is None: items = [] ret = {} if items and isinstance(items, list): for item in items: if in item: if not in item: item[] = item[] ret[item[]] = item return ret
convert list to dictionary using the key as the identifier :param items: array to iterate over :return: dictionary
350,976
def delete_gauge(self, slug): key = self._gauge_key(slug) self.r.delete(key) self.r.srem(self._gauge_slugs_key, slug)
Removes all gauges with the given ``slug``.
350,977
def __get_lowpoints(node, dfs_data): ordering_lookup = dfs_data[] t_u = T(node, dfs_data) sorted_t_u = sorted(t_u, key=lambda a: ordering_lookup[a]) lowpoint_1 = sorted_t_u[0] lowpoint_2 = sorted_t_u[1] return lowpoint_1, lowpoint_2
Calculates the lowpoints for a single node in a graph.
350,978
def execute(self, eopatch): for feature_type, feature_name, new_feature_name in self.feature: eopatch[feature_type][new_feature_name] = self._compute_lbp(eopatch[feature_type][feature_name]) return eopatch
Execute computation of local binary patterns on input eopatch :param eopatch: Input eopatch :type eopatch: eolearn.core.EOPatch :return: EOPatch instance with new key holding the LBP image. :rtype: eolearn.core.EOPatch
350,979
def build_chain(self, **kwargs): set_defaults(self._chain_defaults, kwargs) set_defaults(self._defaults, kwargs) return Chain(self, **kwargs)
Builds a new patterns chain :param pattern: :type pattern: :param kwargs: :type kwargs: :return: :rtype:
350,980
def _send_event_task(args): endpoint = args[] json_message = args[] _consumer_impl.send(endpoint, json_message)
Actually sends the MixPanel event. Runs in a uwsgi worker process.
350,981
def _read_unparsed(self, lines): from bs4 import BeautifulSoup def filter_attributes(): attributes = {} for attribute_name, filter_name in [ ("class", gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX), ("id", gc.PPN_TASK_IS_T...
Read text fragments from an unparsed format text file. :param list lines: the lines of the unparsed text file
350,982
def get_column_listing(self, table): sql = self._grammar.compile_column_exists() database = self._connection.get_database_name() table = self._connection.get_table_prefix() + table results = self._connection.select(sql, [database, table]) return self._connection.get_po...
Get the column listing for a given table. :param table: The table :type table: str :rtype: list
350,983
def array_correlation(x, y, axis=0): if not isinstance(x, np.ndarray): x = np.asarray(x) if not isinstance(y, np.ndarray): y = np.asarray(y) if x.shape != y.shape: raise ValueError("Input arrays must be the same shape") if axis == 1: x, y = x....
Column- or row-wise Pearson correlation between two arrays Computes sample Pearson correlation between two 1D or 2D arrays (e.g., two n_TRs by n_voxels arrays). For 2D arrays, computes correlation between each corresponding column (axis=0) or row (axis=1) where axis indexes observations. If axis=0 (def...
350,984
def set_added_since(self, added): self._query_params += str(QueryParam.DAYS_OLD) + str(added)
Set this to retrieve ads that are a given number of days old. For example to retrieve listings that have been been added a week ago: set_added_since(7) :param added: int
350,985
def t(inspect_packages=False, depth=0, **kwargs): try: frames = inspect.stack() kwargs["frames"] = frames kwargs["inspect_packages"] = inspect_packages kwargs["depth"] = depth with Reflect.context(**kwargs) as r: instance = T_CLASS(r, stream, **kwarg...
print a backtrace since -- 7-6-12 inpsect_packages -- boolean -- by default, this only prints code of packages that are not in the pythonN directories, that cuts out a lot of the noise, set this to True if you want a full stacktrace depth -- integer -- how deep you want the stack trace to...
350,986
def get_register_expr(self, register_name, mode="post"): reg_info = self._arch_info.alias_mapper.get(register_name, None) if reg_info: var_base_name, offset = reg_info else: var_base_name = register_name var_name = self._get_var_name(var_base_name, mode...
Return a smt bit vector that represents an architectural (native) register.
350,987
def quit(self,verbose=False): response=api(url=self.__url+"/quit", verbose=verbose) return response
This command causes Cytoscape to exit. It is typically used at the end of a script file. :param verbose: print more
350,988
def pipe_urlbuilder(context=None, _INPUT=None, conf=None, **kwargs): pkwargs = cdicts(opts, kwargs) get_params = get_funcs(conf.get(, []), **kwargs)[0] get_paths = get_funcs(conf.get(, []), **pkwargs)[0] get_base = get_funcs(conf[], listize=False, **pkwargs)[0] parse_params = utils.parse_params...
A url module that builds a url. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : { 'PARAM': [ {'key': {'value': <'order'>}, 'value': {'value': <'desc'>}}, {'key': {'value': <'page'>}, ...
350,989
def list_assignment_submissions_sections(self, section_id, assignment_id, grouped=None, include=None): path = {} data = {} params = {} path["section_id"] = section_id path["assignment_id"] = assignment_id ...
List assignment submissions. Get all existing submissions for an assignment.
350,990
def _CompareStores(self, storage_reader, compare_storage_reader): storage_counters = self._CalculateStorageCounters(storage_reader) compare_storage_counters = self._CalculateStorageCounters( compare_storage_reader) return storage_counters == compare_storage_counters
Compares the contents of two stores. Args: storage_reader (StorageReader): storage reader. compare_storage_reader (StorageReader): storage to compare against. Returns: bool: True if the content of the stores is identical.
350,991
def _key_question(self, text): if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text) if self.is_completion_widget_visible...
Action for '?
350,992
def createUser(self, username, password, firstName, lastName, email, role="org_user", provider="arcgis", description="", idpUsername=None): ...
This operation is used to create a new user account in the portal. Inputs: username - The name of the user account. password - The password for the account. This is a required parameter only if the provider is arcgis; otherwise, the password para...
350,993
def write_file( path: str, contents, mode: str = , retry_count: int = 3, offset: int = 0 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: error = None for i in range(retry_count): error = attempt_file_write(path, contents, mode, offset) if erro...
Writes the specified contents to a file, with retry attempts if the write operation fails. This is useful to prevent OS related write collisions with files that are regularly written to and read from quickly. :param path: The path to the file that will be written :param contents: Th...
350,994
def cli(ctx, project_dir): exit_code = SCons(project_dir).clean() ctx.exit(exit_code)
Clean the previous generated files.
350,995
def verify_attr_existence(self, table_name, attr_name): self.verify_table_existence(table_name) if self.has_attr(table_name, attr_name): return raise AttributeNotFoundError( " attribute not found in table".format(attr_name, table_name) )
:param str table_name: Table name that the attribute exists. :param str attr_name: Attribute name to tested. :raises simplesqlite.AttributeNotFoundError: If attribute not found in the table :raises simplesqlite.TableNotFoundError: |raises_verify_table_existence| ...
350,996
def get(cls): return { SourceRootConfig, Reporting, Reproducer, RunTracker, Changed, BinaryUtil.Factory, Subprocess.Factory }
Subsystems used outside of any task.
350,997
def to_mesh(obj): reg:surf:reg:surf:reg:spherereg:native<name>_spherereg:<name> if is_mesh(obj): return obj elif pimms.is_vector(obj) and len(obj) == 2: (a,b) = obj if pimms.is_matrix(a, ) and pimms.is_matrix(b, ): return mesh(a, b) elif pimms.is_matrix(b, ) and pimms.is_matrix(a...
to_mesh(obj) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself a mesh object. The following objects can be converted into meshes: * a mesh object * a tuple (coords, faces) where coords is a coordinate matrix and faces is a matrix of coordinate indices tha...
350,998
def mktemplates(network_code=, publicIDs=[, , , ], plot=True): catalog = filter_picks(catalog, top_n_picks=5) for event in catalog: for pick in event.picks: if pick.phase_hint == : event.picks.remov...
Functional wrapper to make templates
350,999
def _partialParseDayStr(self, s, sourceTime): parseStr = None chunk1 = chunk2 = m = self.ptc.CRE_DAY.search(s) if m is not None: if (m.group() != s): parseStr = m.group() chunk1 = s[:m.start()] ...
test if giving C{s} matched CRE_DAY, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: tuple @return: tuple of remained date/time ...