Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
8,400
def _service_is_sysv(name): s /lib/init/upstart-job, and anything that isn script = .format(name) return not _service_is_upstart(name) and os.access(script, os.X_OK)
A System-V style service will have a control script in /etc/init.d. We make sure to skip over symbolic links that point to Upstart's /lib/init/upstart-job, and anything that isn't an executable, like README or skeleton.
8,401
def current(self): results = self._timeline.find_withtag(tk.CURRENT) return results[0] if len(results) != 0 else None
Currently active item on the _timeline Canvas :rtype: str
8,402
def kde_peak(self, name, npoints=_npoints, **kwargs): data = self.get(name,**kwargs) return kde_peak(data,npoints)
Calculate peak of kernel density estimator
8,403
def pop_empty_columns(self, empty=None): empty = [, None] if empty is None else empty if len(self) == 0: return for col in list(self.columns): if self[0][col] in empty: if not [v for v in self.get_column(col) if v not in empty]: ...
This will pop columns from the printed columns if they only contain '' or None :param empty: list of values to treat as empty
8,404
def get_join_cols(by_entry): left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right_cols.append(col[1]) return left_cols, right_cols
helper function used for joins builds left and right join list for join function
8,405
def recarray(self): return numpy.rec.fromrecords(self.records, names=self.names)
Returns data as :class:`numpy.recarray`.
8,406
def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None): file_mask = \ \ \ \ file_volume = self.get_file_volume_details(volume_id, ...
Places an order for a replicant file volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume ...
8,407
def _lookup_user_data(self,*args,**kwargs): user_data = self.get_user_data() data_kind = kwargs.get(,) try: del(kwargs[]) except KeyError, err: pass default_value = kwargs[] result = get_dict(user_data,data_kind,*args,**kwargs) t...
Generic function for looking up values in a user-specific dictionary. Use as follows:: _lookup_user_data('path','to','desired','value','in','dictionary', default = <default value>, data_kind = 'customization'/'saved_searches')
8,408
def mv_to_pypsa(network): generators = network.mv_grid.generators loads = network.mv_grid.graph.nodes_by_attribute() branch_tees = network.mv_grid.graph.nodes_by_attribute() lines = network.mv_grid.graph.lines() lv_stations = network.mv_grid.graph.nodes_by_attribute() mv_stations = network...
Translate MV grid topology representation to PyPSA format MV grid topology translated here includes * MV station (no transformer, see :meth:`~.grid.network.EDisGo.analyze`) * Loads, Generators, Lines, Storages, Branch Tees of MV grid level as well as LV stations. LV stations do not have load and gen...
8,409
async def answer(self, text: typing.Union[base.String, None] = None, show_alert: typing.Union[base.Boolean, None] = None, url: typing.Union[base.String, None] = None, cache_time: typing.Union[base.Integer, None] = None): await self.bot.answ...
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first c...
8,410
def start(port, root_directory, bucket_depth): application = S3Application(root_directory, bucket_depth) http_server = httpserver.HTTPServer(application) http_server.listen(port) ioloop.IOLoop.current().start()
Starts the mock S3 server on the given port at the given path.
8,411
def setup_sanitize_files(self): for fname in self.get_sanitize_files(): with open(fname, ) as f: self.sanitize_patterns.update(get_sanitize_patterns(f.read()))
For each of the sanitize files that were specified as command line options load the contents of the file into the sanitise patterns dictionary.
8,412
def lookup_genome_alignment_index(index_fh, indexed_fh, out_fh=sys.stdout, key=None, verbose=False): bound_iter = functools.partial(genome_alignment_iterator, reference_species="hg19", index_friendly=True) hash_func = JustInTimeGenomeAlignment...
Load a GA index and its indexed file and extract one or more blocks. :param index_fh: the index file to load. Can be a filename or a stream-like object. :param indexed_fh: the file that the index was built for, :param key: A single key, iterable of keys, or None. This key will be ...
8,413
def _create_client(base_url: str, tls: TLSConfig=False) -> Optional[APIClient]: try: client = APIClient(base_url=base_url, tls=tls, version="auto") return client if client.ping() else None except: return None
Creates a Docker client with the given details. :param base_url: the base URL of the Docker daemon :param tls: the Docker daemon's TLS config (if any) :return: the created client else None if unable to connect the client to the daemon
8,414
def volume_percentage_used(self, volume): volume = self._get_volume(volume) if volume is not None: total = int(volume["size"]["total"]) used = int(volume["size"]["used"]) if used is not None and used > 0 and \ total is not None and tot...
Total used size in percentage for volume
8,415
def get_theme(self): xblock_settings = self.get_xblock_settings(default={}) if xblock_settings and self.theme_key in xblock_settings: return xblock_settings[self.theme_key] return self.default_theme_config
Gets theme settings from settings service. Falls back to default (LMS) theme if settings service is not available, xblock theme settings are not set or does contain mentoring theme settings.
8,416
def add_to_queue(self, series): result = self._android_api.add_to_queue(series_id=series.series_id) return result
Add a series to the queue @param crunchyroll.models.Series series @return bool
8,417
def MoveToAttributeNo(self, no): ret = libxml2mod.xmlTextReaderMoveToAttributeNo(self._o, no) return ret
Moves the position of the current instance to the attribute with the specified index relative to the containing element.
8,418
def get_family_hierarchy_session(self, proxy): if not self.supports_family_hierarchy(): raise errors.Unimplemented() return sessions.FamilyHierarchySession(proxy=proxy, runtime=self._runtime)
Gets the ``OsidSession`` associated with the family hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilyHierarchySession) - a ``FamilyHierarchySession`` for families raise: NullArgument - ``proxy`` is ``null`` raise: OperationF...
8,419
def _write(self, _new=False): pipeline = self.db.pipeline() self._create_membership(pipeline) self._update_indices(pipeline) h = {} for k, v in self.attributes.iteritems(): if isinstance(v, DateTimeField): if v.auto_now: ...
Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object.
8,420
def handle_delete(self): from intranet.apps.eighth.models import EighthScheduledActivity EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update( archived_member_count=F()+1)
Handle a graduated user being deleted.
8,421
def find_stream(self, **kwargs): found = list(self.find_streams(**kwargs).values()) if not found: raise StreamNotFoundError(kwargs) if len(found) > 1: raise MultipleStreamsFoundError(kwargs) return found[0]
Finds a single stream with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The stream found
8,422
def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype != str or y.dtype not in [int, float]): raise ValueError("turicreate.visualizat...
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the b...
8,423
def set_tolerance(self, tolerance): cairo.cairo_set_tolerance(self._pointer, tolerance) self._check_status()
Sets the tolerance used when converting paths into trapezoids. Curved segments of the path will be subdivided until the maximum deviation between the original path and the polygonal approximation is less than tolerance. The default value is 0.1. A larger value will give better pe...
8,424
def create_device_enrollment(self, enrollment_identity, **kwargs): kwargs[] = True if kwargs.get(): return self.create_device_enrollment_with_http_info(enrollment_identity, **kwargs) else: (data) = self.create_device_enrollment_with_http_info(enrollment_ident...
Place an enrollment claim for one or several devices. # noqa: E501 When the device connects to the bootstrap server and provides the enrollment ID, it will be assigned to your account. <br> **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>' \\ -H 'content-type: application/...
8,425
def workflow_get_details(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /workflow-xxxx/getDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FgetDetails
8,426
def cleanup(): for install_dir in linters.INSTALL_DIRS: try: shutil.rmtree(install_dir, ignore_errors=True) except Exception: print( "{0}\nFailed to delete {1}".format( traceback.format_exc(), install_di...
Delete standard installation directories.
8,427
def strip_lastharaka(text): if text: if is_vocalized(text): return re.sub(LASTHARAKA_PATTERN, u, text) return text
Strip the last Haraka from arabic word except Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - FATHATAN, DAMMATAN, KASRATAN @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode.
8,428
def _get_table_cells(table): sent_map = defaultdict(list) for sent in table.sentences: if sent.is_tabular(): sent_map[sent.cell].append(sent) return sent_map
Helper function with caching for table cells and the cells' sentences. This function significantly improves the speed of `get_row_ngrams` primarily by reducing the number of queries that are made (which were previously the bottleneck. Rather than taking a single mention, then its sentence, then its tab...
8,429
def load_bytes(self, bytes_data, key, bucket_name=None, replace=False, encrypt=False): if not bucket_name: (bucket_name, key) = self.parse_s3_url(key) if not replace and self.check_for_ke...
Loads bytes to S3 This is provided as a convenience to drop a string in S3. It uses the boto infrastructure to ship a file to s3. :param bytes_data: bytes to set as content for the key. :type bytes_data: bytes :param key: S3 key that will point to the file :type key: st...
8,430
def from_string(s): if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(u(s), keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params[][0] except Except...
Deserializes a token from a string like one returned by `to_string()`.
8,431
def get_ip_address_list(list_name): * payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__[](payload, False) return _convert_to_list(response, )
Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList
8,432
def _get_or_insert_async(*args, **kwds): from . import tasklets cls, name = args get_arg = cls.__get_arg app = get_arg(kwds, ) namespace = get_arg(kwds, ) parent = get_arg(kwds, ) context_options = get_arg(kwds, ) if not isinstance(name, basestring): rais...
Transactionally retrieves an existing entity or creates a new one. This is the asynchronous version of Model._get_or_insert().
8,433
def __get_container_path(self, host_path): libname = os.path.split(host_path)[1] return os.path.join(_container_lib_location, libname)
A simple helper function to determine the path of a host library inside the container :param host_path: The path of the library on the host :type host_path: str
8,434
def exec(self, *command_tokens, command_context=None, **command_env): if self.adapter().match(command_context, **command_env) is False: cmd = WCommandProto.join_tokens(*command_tokens) spec = self.adapter().specification() if spec is not None: spec = [x.context_name() for x in spec] spec.reverse()...
Execute command :param command_tokens: command tokens to execute :param command_context: command context :param command_env: command environment :return: WCommandResultProto
8,435
def main(): args = get_args() args.start = date_parser.parse(args.start) args.end = date_parser.parse(args.end) args.step = timedelta(args.step) config = Config(args.config) times = [args.start + i * args.step for i in range(int((args.end - args.start) / args.step))] for i, time in en...
process the main task
8,436
def recv(self, size = None): size = size if size is not None else 1500 return os.read(self.fd, size)
Receive a buffer. The default size is 1500, the classical MTU.
8,437
def execute_update(self, update, safe=False): assert len(update.update_data) > 0 self.queue.append(UpdateOp(self.transaction_id, self, update.query.type, safe, update)) if self.autoflush: return self.flush()
Execute an update expression. Should generally only be called implicitly.
8,438
def series(self, x: str, y: list, title: str = ) -> object: code = "proc sgplot data=" + self.libref + + self.table + self._dsopts() + ";\n" if len(title) > 0: code += + title + if isinstance(y, list): num = len(y) else: num = 1 ...
This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Ti...
8,439
def add_volume(self, hostpath, contpath, options=None): if options is None: options = [] self.volumes.append((hostpath, contpath, options))
Add a volume (bind-mount) to the docker run invocation
8,440
def forwards(apps, schema_editor): starts = timeutils.round_datetime( when=timezone.now(), precision=timedelta(days=1), rounding=timeutils.ROUND_DOWN) ends = starts + appsettings.DEFAULT_ENDS_DELTA recurrence_rules = dict( RecurrenceRule.objects.values_list(, )) dai...
Create sample events.
8,441
def PopState(self, **_): try: self.state = self.state_stack.pop() if self.verbose: logging.debug("Returned state to %s", self.state) return self.state except IndexError: self.Error("Tried to pop the state but failed - possible recursion error")
Pop the previous state from the stack.
8,442
def read_annotations(path_or_file, separator=, reset=True): annotations = OrderedDict({}) with PathOrFile(path_or_file, , reset=reset) as f: annotations[] = f.readline().strip().split(separator) for line in f: if line.startswith(): tokens = line.strip().split(sep...
Read all annotations from the specified file. >>> annotations = read_annotations(path_or_file, separator) >>> colnames = annotations['Column Name'] >>> types = annotations['Type'] >>> annot_row = annotations['Annot. row name'] :param path_or_file: Path or file-like object :param separator:...
8,443
def get_data(self) -> bytes: data = { "_class_name": self.__class__.__name__, "version": 1, "segments_bin": SegmentSequence([self.command_seg, self.tan_request]).render_bytes(), "resume_method": self.resume_method, "tan_request_structured": se...
Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
8,444
def get_remote(self, key, default=None, scope=None): return self.conversation(scope).get_remote(key, default)
Get data from the remote end(s) of the :class:`Conversation` with the given scope. In Python, this is equivalent to:: relation.conversation(scope).get_remote(key, default) See :meth:`conversation` and :meth:`Conversation.get_remote`.
8,445
def report(self): if self.logger: self.logger.info("accessed parameters:") for key in self.used_parameters: self.logger.info(" - %s %s" % (key, "(undefined)" if key in self.undefined_parameters else ""))
Report usage of training parameters.
8,446
def _add_tag(self, tag): tags = self.data.get(, None) if tags: if tag in [x[] for x in tags]: return False else: tags = list() tags.append({: tag}) self.data[] = tags return True
Add a tag Args: tag (str): Tag to add Returns: bool: True if tag added or False if tag already present
8,447
def parse_time(val, fmt=None): if isinstance(val, time): return val else: return parse_datetime(val, fmt).time()
Returns a time object parsed from :val:. :param val: a string to be parsed as a time :param fmt: a format string, a tuple of format strings, or None. If None a built in list of format strings will be used to try to parse the time.
8,448
def speed(self, factor, use_semitones=False): self.command.append("speed") self.command.append(factor if not use_semitones else str(factor) + "c") return self
speed takes 2 parameters: factor and use-semitones (True or False). When use-semitones = False, a factor of 2 doubles the speed and raises the pitch an octave. The same result is achieved with factor = 1200 and use semitones = True.
8,449
def close(self): os.close(self._fd) self._fd = -1 self._addr = -1 self._pec = 0
close() Disconnects the object from the bus.
8,450
def from_bam(pysam_samfile, loci, normalized_contig_names=True): chr loci = [to_locus(obj) for obj in loci] close_on_completion = False if typechecks.is_string(pysam_samfile): pysam_samfile = Samfile(pysam_samfile) close_on_completion = True try...
Create a PileupCollection for a set of loci from a BAM file. Parameters ---------- pysam_samfile : `pysam.Samfile` instance, or filename string to a BAM file. The BAM file must be indexed. loci : list of Locus instances Loci to collect pileups for. norm...
8,451
def get_connection_by_node(self, node): self._checkpid() self.nodes.set_node_name(node) try: connection = self._available_connections.get(node["name"], []).pop() except IndexError: connection = self.make_connection(node) self._in_us...
get a connection by node
8,452
def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]: return cast(T, self._val) if self._is_ok else op(cast(E, self._val))
Returns the sucess value in the :class:`Result` or computes a default from the error value. Args: op: The function to computes default with. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``op(E)``. ...
8,453
def _execute(self, stmt, *values): c = self._cursor() try: return c.execute(stmt, values).fetchone() finally: c.close()
Gets a cursor, executes `stmt` and closes the cursor, fetching one row afterwards and returning its result.
8,454
def optimize(self, commit=True, waitFlush=None, waitSearcher=None, maxSegments=None, handler=): if maxSegments: msg = % maxSegments else: msg = return self._update(msg, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher, handler=handler)
Tells Solr to streamline the number of segments used, essentially a defragmentation operation. Optionally accepts ``maxSegments``. Default is ``None``. Optionally accepts ``waitFlush``. Default is ``None``. Optionally accepts ``waitSearcher``. Default is ``None``. Usage:: ...
8,455
def get_broadcast_events(cls, script): events = Counter() for name, _, block in cls.iter_blocks(script): if in name: if isinstance(block.args[0], kurt.Block): events[True] += 1 else: events[block.args[0].lower(...
Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks contain a parameter that is a variable.
8,456
def mcmc_CH(self, walkerRatio, n_run, n_burn, mean_start, sigma_start, threadCount=1, init_pos=None, mpi=False): lowerLimit, upperLimit = self.lower_limit, self.upper_limit mean_start = np.maximum(lowerLimit, mean_start) mean_start = np.minimum(upperLimit, mean_start) low_star...
runs mcmc on the parameter space given parameter bounds with CosmoHammerSampler returns the chain
8,457
def sample(self, num_samples=1000, hmc_iters=20): params = np.empty((num_samples,self.p.size)) for i in range(num_samples): self.p[:] = np.random.multivariate_normal(np.zeros(self.p.size),self.M) H_old = self._computeH() theta_old = self.model.optimizer_array...
Sample the (unfixed) model parameters. :param num_samples: the number of samples to draw (1000 by default) :type num_samples: int :param hmc_iters: the number of leap-frog iterations (20 by default) :type hmc_iters: int :return: the list of parameters samples with the si...
8,458
def less_strict_bool(x): if x is None: return False elif x is True or x is False: return x else: return strict_bool(x)
Idempotent and None-safe version of strict_bool.
8,459
def invoke(self, script_hash, params, **kwargs): contract_params = encode_invocation_params(params) raw_result = self._call( JSONRPCMethods.INVOKE.value, [script_hash, contract_params, ], **kwargs) return decode_invocation_result(raw_result)
Invokes a contract with given parameters and returns the result. It should be noted that the name of the function invoked in the contract should be part of paramaters. :param script_hash: contract script hash :param params: list of paramaters to be passed in to the smart contract ...
8,460
def send(self, message): for event in message.events: self.events.append(event) reply = riemann_client.riemann_pb2.Msg() reply.ok = True return reply
Adds a message to the list, returning a fake 'ok' response :returns: A response message with ``ok = True``
8,461
def get_resource_component_children(self, resource_component_id): resource_type = self.resource_type(resource_component_id) return self.get_resource_component_and_children( resource_component_id, resource_type )
Given a resource component, fetches detailed metadata for it and all of its children. This is implemented using ArchivesSpaceClient.get_resource_component_children and uses its default options when fetching children. :param string resource_component_id: The URL of the resource component from which to ...
8,462
def buffered_read(fh, lock, offsets, bytecounts, buffersize=None): if buffersize is None: buffersize = 2**26 length = len(offsets) i = 0 while i < length: data = [] with lock: size = 0 while size < buffersize and i < length: fh.seek(of...
Return iterator over segments read from file.
8,463
def train_model( self, L_train, Y_dev=None, deps=[], class_balance=None, log_writer=None, **kwargs, ): self.config = recursive_merge_dicts(self.config, kwargs, misses="ignore") train_config = self.config["train_config"] ...
Train the model (i.e. estimate mu) in one of two ways, depending on whether source dependencies are provided or not: Args: L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k} corresponding to labels from supervision sources on the training set ...
8,464
def config_start(self): _LOGGER.info("Config start") success, _ = self._make_request( SERVICE_DEVICE_CONFIG, "ConfigurationStarted", {"NewSessionID": SESSION_ID}) self.config_started = success return success
Start a configuration session. For managing router admin functionality (ie allowing/blocking devices)
8,465
def change_host_check_timeperiod(self, host, timeperiod): host.modified_attributes |= DICT_MODATTR["MODATTR_CHECK_TIMEPERIOD"].value host.check_period = timeperiod self.send_an_element(host.get_update_status_brok())
Modify host check timeperiod Format of the line that triggers function call:: CHANGE_HOST_CHECK_TIMEPERIOD;<host_name>;<timeperiod> :param host: host to modify check timeperiod :type host: alignak.objects.host.Host :param timeperiod: timeperiod object :type timeperiod: ...
8,466
def request_time_facet(field, time_filter, time_gap, time_limit=100): start, end = parse_datetime_range(time_filter) key_range_start = "f.{0}.facet.range.start".format(field) key_range_end = "f.{0}.facet.range.end".format(field) key_range_gap = "f.{0}.facet.range.gap".format(field) key_range_m...
time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is a soft maximum; less will usually be returned. A suggested value is 100. N...
8,467
def _parse_myinfo(client, command, actor, args): _, server, version, usermodes, channelmodes = args.split(None, 5)[:5] s = client.server s.host = server s.version = version s.user_modes = set(usermodes) s.channel_modes = set(channelmodes)
Parse MYINFO and update the Host object.
8,468
def validate_reaction(self): if self.reaction not in self._reaction_valid_values: raise ValueError("reaction should be one of: {valid}".format( valid=", ".join(self._reaction_valid_values) ))
Ensure reaction is of a certain type. Mainly for future expansion.
8,469
def call(self, inpt): if inpt is Manager.NONE_INPUT: return False argument_instance = self.argument(inpt) if not argument_instance.applies: return False application = self.__apply(argument_instance, inpt) if self.negative: ...
Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` is called, with ``inpt`` as the instance an...
8,470
def get_conn(self): db = self.get_connection(getattr(self, self.conn_name_attr)) return self.connector.connect( host=db.host, port=db.port, username=db.login, schema=db.schema)
Returns a connection object
8,471
def validate_brain_requirements(connection, remote_dbs, requirements): for database in requirements: assert (database in remote_dbs), "database {} must exist".format(database) remote_tables = frozenset(rethinkdb.db(database).table_list().run(connection)) for table in requirements[databa...
validates the rethinkdb has the 'correct' databases and tables should get remote_dbs from brain.connection.validate_get_dbs :param connection: <rethinkdb.net.DefaultConnection> :param remote_dbs: <set> database names present in remote database :param requirements: <dict> example(brain.connection.SELF_T...
8,472
def _get_top_of_rupture_depth_term(self, C, imt, rup): if rup.ztor >= 20.0: return C[] else: return C[] * rup.ztor / 20.0
Compute and return top of rupture depth term. See paragraph 'Depth-to-Top of Rupture Model', page 1042.
8,473
def dropping(n): if n < 0: raise ValueError("Cannot drop fewer than zero ({}) items".format(n)) def dropping_transducer(reducer): return Dropping(reducer, n) return dropping_transducer
Create a transducer which drops the first n items
8,474
def add_filter(self, filter_or_string, *args, **kwargs): self.filters.append(build_filter(filter_or_string, *args, **kwargs)) return self
Appends a filter.
8,475
def exit_with_error(msg=, details=None, code=-1, *args, **kwargs): error(msg, details=details, *args, **kwargs) sys.exit(code)
Exit with error
8,476
def get(key, default=None): **["key1", "key2"] store = load() if isinstance(key, six.string_types): return store.get(key, default) elif default is None: return [store[k] for k in key if k in store] else: return [store.get(k, default) for k in key]
Get a (list of) value(s) from the minion datastore .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' data.get key salt '*' data.get '["key1", "key2"]'
8,477
def setContentsMargins(self, left, top, right, bottom): self._margins = (left, top, right, bottom) self.adjustTitleFont()
Sets the contents margins for this node to the inputed values. :param left | <int> top | <int> right | <int> bottom | <int>
8,478
def get_url(self, resource, params=None): pattern = r resource = re.sub(pattern, lambda t: str(params.get(t.group(1), )), resource) parts = (self.endpoint, , resource) return .join(map(lambda x: str(x).strip(), parts))
Generate url for request
8,479
def local_histogram_equalization(data, mask_to_equalize, valid_data_mask=None, number_of_bins=1000, std_mult_cutoff=3.0, do_zerotoone_normalization=True, local_radius_px=300, clip_limit=60...
Equalize the provided data (in the mask_to_equalize) using adaptive histogram equalization. tiles of width/height (2 * local_radius_px + 1) will be calculated and results for each pixel will be bilinerarly interpolated from the nearest 4 tiles when pixels fall near the edge of the image (there is no adjacent t...
8,480
def parse_inventory_category(name, info, countable=True): raw = info["data"][1:] cur = 0 if countable: count = struct.unpack("B", raw[cur])[0] cur += 1 else: count = 0 discarded = 0 entries = [] while cur < len(raw): read, cpu = categories[name]["parser...
Parses every entry in an inventory category (CPU, memory, PCI, drives, etc). Expects the first byte to be a count of the number of entries, followed by a list of elements to be parsed by a dedicated parser (below). :param name: the name of the parameter (e.g.: "cpu") :param info: a list of integer...
8,481
def as_cnpjcpf(numero): if is_cnpj(numero): return as_cnpj(numero) elif is_cpf(numero): return as_cpf(numero) return numero
Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF válidos apenas retorna o argumento sem qualquer modificação.
8,482
def loglike(self, y, f): r y, f = np.broadcast_arrays(y, f) if self.tranfcn == : g = np.exp(f) logg = f else: g = softplus(f) logg = np.log(g) return y * logg - g - gammaln(y + 1)
r""" Poisson log likelihood. Parameters ---------- y: ndarray array of integer targets f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\Phi \mathbf{w}`) Returns ------- logp: ndarray ...
8,483
def return_item(self, item, priority): conn = redis.StrictRedis(connection_pool=self.pool) self._run_expiration(conn) script = conn.register_script() if priority is None: priority = "None" result = script(keys=[self._key_available(), self._key_expiration(), ...
Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any locked items associated with this item are unlocked.
8,484
def get_description_by_type(self, type_p): if not isinstance(type_p, VirtualSystemDescriptionType): raise TypeError("type_p can only be an instance of type VirtualSystemDescriptionType") (types, refs, ovf_values, v_box_values, extra_config_values) = self._call("getDescriptionByType"...
This is the same as :py:func:`get_description` except that you can specify which types should be returned. in type_p of type :class:`VirtualSystemDescriptionType` out types of type :class:`VirtualSystemDescriptionType` out refs of type str out ovf_values of type str ...
8,485
def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True): createdcmdir = True dicomdirfile = os.path.join(self.dirpath, self.dicomdir_filename) ftype = if os.path.exists(dicomdirfile): try: dcmdirplus = misc.obj_from_file(dicomdi...
Check if exists dicomdir file and load it or cerate it dcmdir = get_dir(dirpath) dcmdir: list with filenames, SeriesNumber and SliceLocation
8,486
def build_columns(self, X, term=-1, verbose=False): if term == -1: term = range(len(self._terms)) term = list(np.atleast_1d(term)) columns = [] for term_id in term: columns.append(self._terms[term_id].build_columns(X, verbose=verbose)) return sp....
construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows
8,487
def append_from_dict(self, the_dict): m = Measurement.from_dict(the_dict) self.append(m)
Creates a ``measurement.Measurement`` object from the supplied dict and then appends it to the buffer :param the_dict: dict
8,488
def register(handler, op, safe_init = None, at_start = None, name = None, at_stop = None, static = False, root = None, replacement = None, charset ...
Register a command @handler: function to execute when the command is received @op: http method(s) @safe_init: called by the safe_init() function of this module @at_start: called once just before the server starts @at_stop: called once just before the server stops @name: name of the command (if n...
8,489
def _get_focused_item(self): focused_model = self._selection.focus if not focused_model: return None return self.canvas.get_view_for_model(focused_model)
Returns the currently focused item
8,490
def imag(self, newimag): if self.space.is_real: raise ValueError() self.tensor.imag = newimag
Set the imaginary part of this element to ``newimag``. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element. Raises ------ ValueError ...
8,491
def load(self, module_name): module_name, path = self.lookup(module_name) if path: with open(path, ) as f: return module_name, f.read().decode() return None, None
Returns source code and normalized module id of the given module. Only supports source code files encoded as UTF-8
8,492
def get_shards(self, *args, full_response=False): resp = self.request(shards=args, full_response=full_response) return resp
Get Shards
8,493
def _imm_new(cls): imm = object.__new__(cls) params = cls._pimms_immutable_data_[] for (p,dat) in six.iteritems(params): dat = dat[0] if dat: object.__setattr__(imm, p, dat[0]) _imm_clear(imm) dd = object.__getattribute__(imm, ) dd[] = True retur...
All immutable new classes use a hack to make sure the post-init cleanup occurs.
8,494
def fso_listdir(self, path): path = self.deref(path) if not stat.S_ISDIR(self._stat(path).st_mode): raise OSError(20, , path) try: ret = self.originals[](path) except Exception: ret = [] for entry in self.entries.values(): if not entry.path.startswith(path + ): ...
overlays os.listdir()
8,495
def unsubscribe(self, subscriber: ) -> None: for i, _s in enumerate(self._subscriptions): if _s is subscriber: self._subscriptions.pop(i) return raise SubscriptionError()
Unsubscribe the given subscriber :param subscriber: subscriber to unsubscribe :raises SubscriptionError: if subscriber is not subscribed (anymore)
8,496
def tag_supplementary_material_sibling_ordinal(tag): if hasattr(tag, ) and tag.name != : return None nodenames = [,,] first_parent_tag = first_parent(tag, nodenames) sibling_ordinal = 1 if first_parent_tag: for supp_tag in first_parent_tag.find_all(tag.name)...
Strategy is to count the previous supplementary-material tags having the same asset value to get its sibling ordinal. The result is its position inside any parent tag that are the same asset type
8,497
def _fake_closeenumeration(self, namespace, **params): self._validate_namespace(namespace) context_id = params[] try: context_data = self.enumeration_contexts[context_id] except KeyError: raise CIMError( CIM_ERR_INVALID_ENUMERATION_CONTE...
Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.CloseEnumeration` with data from the instance repository. If the EnumerationContext is valid it removes it from the context repository. Otherwise it returns an exception.
8,498
def main(nodes, edges): from matplotlib import pyplot as plt from matplotlib.dates import date2num from matplotlib.cm import gist_rainbow print("building DAG") G = random_dag(nodes, edges) jobs = {} pos = {} colors = {} for node in G: jobs[node] = randomwait cli...
Generate a random graph, submit jobs, then validate that the dependency order was enforced. Finally, plot the graph, with time on the x-axis, and in-degree on the y (just for spread). All arrows must point at least slightly to the right if the graph is valid.
8,499
def get_user_config(): initialconf = normpath(os.path.join(get_share_dir(), "linkcheckerrc")) userconf = normpath("~/.linkchecker/linkcheckerrc") if os.path.isfile(initialconf) and not os.path.exists(userconf) and \ not Portable: try: make_userdir(userconf)...
Get the user configuration filename. If the user configuration file does not exist, copy it from the initial configuration file, but only if this is not a portable installation. Returns path to user config file (which might not exist due to copy failures or on portable systems). @return configuratio...