Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
350,300
def get_from_config_setting_cascade(self, sec_param_list, default=None, warn_on_none_level=logging.WARN): for section, param in sec_param_list: r = self.get_config_setting(section, param, default=None, warn_on_none_level=None) if r is not None: return r s...
return the first non-None setting from a series where each element in `sec_param_list` is a section, param pair suitable for a get_config_setting call. Note that non-None values for overrides for this ConfigWrapper instance will cause this call to only evaluate the first element in ...
350,301
def add_key(self, key, first=False): if first: self.keys = [key] + self.keys else: self.keys.append(key) if isinstance(key, VSpaceKey): self.space = key
Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end.
350,302
def _effective_value(self, attr_name): directly_applied_value = getattr( super(_InheritsDimensions, self), attr_name ) if directly_applied_value is not None: return directly_applied_value return self._inherited_value(attr_name)
The effective value of *attr_name* on this placeholder shape; its directly-applied value if it has one, otherwise the value on the layout placeholder it inherits from.
350,303
def _inquire(self, **kwargs): if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") if not kwargs: def...
Inspect this name for information. This method inspects the name for information. If no keyword arguments are passed, all available information is returned. Otherwise, only the keyword arguments that are passed and set to `True` are returned. Args: mech_name (bool...
350,304
def volumes_tagged(name, tag_maps, authoritative=False, region=None, key=None, keyid=None, profile=None): filtersfilterstags ret = {: name, : True, : , : {} } args = {: tag_maps, : authoritative, : region, : key, : keyid, : profile} ...
Ensure EC2 volume(s) matching the given filters have the defined tags. .. versionadded:: 2016.11.0 name State definition name. tag_maps List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the 'filters' argument of boto_ec2.get_all_volumes(), and 't...
350,305
def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64): if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError() if(batch_size < 1): raise ValueError(" must be greater than or equal to 1") if isinstance(data...
For each image, retrieve the nearest neighbors from the model's stored data. In general, the query dataset does not need to be the same as the reference data stored in the model. Parameters ---------- dataset : SFrame | SArray | turicreate.Image Query data. ...
350,306
def get_topology_info(*args): instance = tornado.ioloop.IOLoop.instance() try: return instance.run_sync(lambda: API.get_topology_info(*args)) except Exception: Log.debug(traceback.format_exc()) raise
Synced API call to get topology information
350,307
def subscribe(self, transport, data): self.add(transport, address=data.get().encode()) self.send( data[], {: "%r is listening" % transport} )
adds a transport to a channel
350,308
def get_variation_for_feature(self, feature, user_id, attributes=None): experiment = None variation = None bucketing_id = self._get_bucketing_id(user_id, attributes) if feature.groupId: group = self.config.get_group(feature.groupId) if group: experiment = self.get_experim...
Returns the experiment/variation the user is bucketed in for the given feature. Args: feature: Feature for which we are determining if it is enabled or not for the given user. user_id: ID for user. attributes: Dict representing user attributes. Returns: Decision namedtuple consisting o...
350,309
def serialize(self, buffer=bytearray(), index=Index(), **options): for item in self.values(): index = item.serialize(buffer, index, **options) return index
Serializes the `Structure` to the byte *buffer* starting at begin of the *buffer* or with the given *index* by mapping the :attr:`~Field.value` for each :class:`Field` in the `Structure` to the byte *buffer* in accordance with the encoding *byte order* for the serialization and the encod...
350,310
def _skip_frame(self): for line in self._f: if line == : break for i in range(self.num_atoms): next(self._f)
Skip the next time frame
350,311
def _upper_bound_on_event_overflow( events, slots, X, beta, summation_type=None, **kwargs ): label = for row, event in enumerate(events): for col, slot in enumerate(slots): yield Constraint( f, event.demand * X[row, col] - slot.capacity <= beta)
This is an artificial constraint that is used by the objective function aiming to minimise the maximum overflow in a slot.
350,312
def format_name(self, format_name): if format_name in self.supported_formats: self._format_name = format_name else: raise ValueError(.format( format_name))
Set the default format name. :param str format_name: The display format name. :raises ValueError: if the format is not recognized.
350,313
def except_(self, enumerable, key=lambda x: x): if not isinstance(enumerable, Enumerable3): raise TypeError( u"enumerable parameter must be an instance of Enumerable") membership = ( 0 if key(element) in enumerable.intersect(self, key).select(key) else 1 ...
Returns enumerable that subtracts given enumerable elements from self :param enumerable: enumerable object :param key: key selector as lambda expression :return: new Enumerable object
350,314
def visit_Module(self, node): self.generic_visit(node) import_alias = ast.alias(name=, asname=mangle()) if self.use_itertools: importIt = ast.Import(names=[import_alias]) node.body.insert(0, importIt) return node
Add itertools import for imap, izip or ifilter iterator.
350,315
def _lazysecret(secret, blocksize=32, padding=): if not len(secret) in (16, 24, 32): return secret + (blocksize - len(secret)) * padding return secret
Pads secret if not legal AES block size (16, 24, 32)
350,316
def parse_code_ul(self, url, ul): li_list = ul.find_all(, recursive=False) li = li_list[0] span_title = li.find(, attrs={: re.compile(r)}, recursive=False) section = Section(span_title.attrs[], span_title.text.strip()) ...
Fill the toc item
350,317
def hide_routemap_holder_route_map_content_set_metric_delta_rms(self, **kwargs): config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.SubElement(hide_routemap_holder, "route-map"...
Auto Generated Code
350,318
def excel_main(file): os.chdir(file["dir"]) name_ext = file["filename_ext"] name = file["filename_no_ext"] name = normalize_name(name) print("processing: {}".format(name_ext)) logger_excel.info("processing: {}".format(name_ext)) pending_csv = [] final = OrderedDict() ...
Parse data from Excel spreadsheets into LiPD files. :param dict file: File metadata (source, name, etc) :return str dsn: Dataset name
350,319
def _add_pos1(token): result = token.copy() result[] = _POSMAP[token[].split("(")[0]] return result
Adds a 'pos1' element to a frog token.
350,320
def unset_key(dotenv_path, key_to_unset, quote_mode=, verbose=False): key_to_unset = str(key_to_unset) if not os.path.exists(dotenv_path): if verbose: warnings.warn(f"Cant exist.") return None, key_to_unset dotenv_as_dict = dotenv_values(dotenv_path) if key_to_unset in d...
Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails :param dotenv_path: env path :param key_to_unset: value :param quote_mode: quote value in .env file :param verbose: verbosity flag, raise warning if path does n...
350,321
def adjoint(self): return MatrixOperator(self.matrix.conj().T, domain=self.range, range=self.domain, axis=self.axis)
Adjoint operator represented by the adjoint matrix. Returns ------- adjoint : `MatrixOperator`
350,322
def import_file(self, imported_format=None, progress_from=0.0, progress_to=None): if not hasattr(resolwe_runtime_utils, ): raise RuntimeError() if imported_format is None: imported_format = resolwe_runtime_utils.ImportedFormat.BOTH return resolwe_runtime_utils....
Import field source file to working directory. :param imported_format: Import file format (extracted, compressed or both) :param progress_from: Initial progress value :param progress_to: Final progress value :return: Destination file path (if extracted and compressed, extracted path giv...
350,323
def allow_bare_decorator(cls): @wraps(cls) def wrapper(*args, **kwargs): if kwargs or len(args) != 1 or not isclass(args[0]): return cls(*args, **kwargs) else: return cls()(args[0]) return wrapper
Wrapper for a class decorator which allows for bare decorator and argument syntax
350,324
def load(fp, strip_comments=False, **kw): kw[] = strip_comments return loads(fp.read(), **kw)
Load a list of trees from an open Newick formatted file. :param fp: open file handle. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. :return: List of Node objects.
350,325
def icmpv6(self): ipproto, proto_start = self.protocol if ipproto == Protocol.ICMPV6: return ICMPv6Header(self, proto_start)
- An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise.
350,326
def get_chunk_information(self, chk, lun, chunk_name): cmd = ["nvm_cmd rprt_lun", self.envs, "%d %d > %s" % (chk, lun, chunk_name)] status, _, _ = cij.ssh.command(cmd, shell=True) return status
Get chunk information
350,327
def version(self, context=None): if self.replaces_scope and self.replaces_name: if context: old_opts = context.options.for_scope(self.replaces_scope) if old_opts.get(self.replaces_name) and not old_opts.is_default(self.replaces_name): return old_opts.get(self.replaces_n...
Returns the version of the specified binary tool. If replaces_scope and replaces_name are defined, then the caller must pass in a context, otherwise no context should be passed. # TODO: Once we're migrated, get rid of the context arg. :API: public
350,328
def _dist_corr(dist, phi1, phi2, phi3): return phi1 * exp(-phi2 * dist) + (1 - phi1) * exp(-phi3 * dist)
Generic distance-decaying correlation function :param dist: Distance between catchment centrolds in km :type dist: float :param phi1: Decay function parameters 1 :type phi1: float :param phi2: Decay function parameters 2 :type phi2: float :param phi3: Decay funct...
350,329
def analogy(self, pos, neg, n=10, metric="cosine"): exclude = pos + neg pos = [(word, 1.0) for word in pos] neg = [(word, -1.0) for word in neg] mean = [] for word, direction in pos + neg: mean.append(direction * self[word]) mean = np.array(mean).mea...
Analogy similarity. Parameters ---------- pos : list neg : list Returns ------- Tuple of 2 numpy.array: 1. position in self.vocab 2. cosine similarity Example ------- `king - man + woman = queen` will be: `pos...
350,330
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): def construct_mapping(loader, node, deep=False): loader.flatten_mapping(node) if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yam...
Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally
350,331
def get_accept_license(request): publication_id = request.matchdict[] user_id = request.matchdict[] with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(, (publication_id, user_id)) user_documents = [r[...
This produces JSON data for a user (at ``uid``) to view the license(s) they have accepted or will need to accept for a publication (at ``id``).
350,332
def astar_search(problem, h=None): h = memoize(h or problem.h, ) return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search, or else in your Problem subclass.
350,333
def _executeMaltparser( input_string, maltparser_dir, maltparser_jar, model_name ): s output. Parameters ---------- input_string: string input text in CONLL format; maltparser_jar: string name of the Maltparsers jar and the model file; ...
Executes Maltparser on given (CONLL-style) input string, and returns the result. The result is an array of lines from Maltparser's output. Parameters ---------- input_string: string input text in CONLL format; maltparser_jar: string ...
350,334
def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs): install allinstall all impactn9kn7k if not isinstance(issu, bool): return si = system_image ki = kickstart_image dev = cmd = if ki is not None: cmd = cmd + .format(dev, ki, si) el...
Display upgrade impact information without actually upgrading the device. system_image (Mandatory Option) Path on bootflash: to system image upgrade file. kickstart_image Path on bootflash: to kickstart image upgrade file. (Not required if using combined system/kickstart image file) ...
350,335
def load_from_file(filename): t = None with open(filename, ) as infile: tdata = infile.read() t = Topology.unserialize(tdata) return t
Load a topology from filename and return it.
350,336
def connection(self, connection): if connection is not None: connection.subscribe("capacity", self._on_capacity_data) connection.default_return_capacity = True if self._connection is not None: connection.unsubscribe("capacity", self._on_capacity_data) ...
Change the dynamo connection
350,337
def cells(self) -> Generator[Tuple[int, int], None, None]: yield from itertools.product( range(self.row_start, self.row_end), range(self.column_start, self.column_end) )
Generate cells in span.
350,338
def get_placeholders(template_name): dummy_context.template = template.Template("") try: temp_wrapper = template.loader.get_template(template_name) except template.TemplateDoesNotExist: return [] plist, blist = [], [] temp = temp_wrapper.template _placeholders_recursif(temp...
Return a list of PlaceholderNode found in the given template. :param template_name: the name of the template file
350,339
def asZip(self): out = BytesIO() with zipfile.ZipFile( out, mode=, compression=zipfile.ZIP_DEFLATED, ) as outfile: for path, data, _ in self._iterOutFiles(): outfile.writestr(path, data) return out.getvalue(),
Return a serialised zip archive containing: - callgrind profiling statistics (cachegrind.out.pprofile) - any SQL query issued via ZMySQLDA (query_*.sql) - any persistent object load via ZODB.Connection (ZODB_setstate.txt) - any path argument given to unrestrictedTraverse (unres...
350,340
def _matrix2dict(matrix, etype=False): n = len(matrix) adj = {k: {} for k in range(n)} for k in range(n): for j in range(n): if matrix[k, j] != 0: adj[k][j] = {} if not etype else matrix[k, j] return adj
Takes an adjacency matrix and returns an adjacency list.
350,341
def jump(self, selected_number: int) -> None: self._verify_entrypoint_selected() if selected_number < 1 or selected_number > len(self.trace_tuples): raise UserError( "Trace frame number out of bounds " f"(expected 1-{len(self.trace_tuples)} but got {s...
Jump to a specific trace frame in a trace. Parameters: selected_number: int the trace frame number from trace output
350,342
def is_encodable(self, typ: TypeStr, arg: Any) -> bool: encoder = self._registry.get_encoder(typ) try: encoder.validate_value(arg) except EncodingError: return False except AttributeError: try: encoder(arg) except ...
Determines if the python value ``arg`` is encodable as a value of the ABI type ``typ``. :param typ: A string representation for the ABI type against which the python value ``arg`` will be checked e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``, etc. :param arg: The py...
350,343
def gabor(x, y, xsigma, ysigma, frequency, phase): if xsigma==0.0 or ysigma==0.0: return x*0.0 with float_error_ignore(): x_w = np.divide(x,xsigma) y_h = np.divide(y,ysigma) p = np.exp(-0.5*x_w*x_w + -0.5*y_h*y_h) return p * 0.5*np.cos(2*pi*frequency*y + phase)
Gabor pattern (sine grating multiplied by a circular Gaussian).
350,344
def _parse_pot(pot,potforactions=False,potfortorus=False): pt,pa= _parse_scf_pot(p._scf,extra_amp=p._amp) pot_type.append(pt) pot_args.extend(pa) for Sigma,hz in zip(p._Sigma_dict,p._hz_dict): npot+= 1 pot_type.append...
Parse the potential so it can be fed to C
350,345
def html(self): try: body = self.get_elm(tag_name=) except selenium_exc.NoSuchElementException: return None else: return body.get_attribute()
Returns ``innerHTML`` of whole page. On page have to be tag ``body``. .. versionadded:: 2.2
350,346
def max_order(self): combo = int(0) for iv in self._interval_set._intervals: combo |= iv[0] | iv[1] ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2) if ret < 0: ret = 0 return ret
Depth of the smallest HEALPix cells found in the MOC instance.
350,347
def macho_dependencies_list(target_path, header_magic=None): MachODeprendencies = namedtuple("MachODeprendecies", "weak strong") if isinstance(header_magic, basestring): header_magic = _MH_MAGIC_from_string(header_magic) macho = MachO(target_path) suggestions = filter(lambda t: t.header.magic == header_ma...
Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templates like @executable_path or @rpath in it). Note: I don't know ...
350,348
def get_export_configuration(self, config_id): sql = ( ) return first_from_generator( self.generators.export_configuration_generator(sql=sql, sql_args=(config_id,)))
Retrieve the ExportConfiguration with the given ID :param string config_id: ID for which to search :return: a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found.
350,349
def add_rerandomize(self, rerandomize): if not self.my_osid_object_form._is_valid_string( rerandomize, self.get_rerandomize_metadata()): raise InvalidArgument() self.my_osid_object_form._my_map[] = rerandomize
stub
350,350
def interpolate(values, value_times, sampling_rate=1000): initial_index = value_times[0] value_times = np.array(value_times) - initial_index spline = scipy.interpolate.splrep(x=value_times, y=values, k=3, s=0) x = np.arange(0, value_times[-1], 1) signal = scipy.interpolate.s...
3rd order spline interpolation. Parameters ---------- values : dataframe Values. value_times : list Time indices of values. sampling_rate : int Sampling rate (samples/second). Returns ---------- signal : pd.Series An array containing the values indexed b...
350,351
def setup_and_check(self, data, title=): self._selection_rec = False self._model = None self.layout = QGridLayout() self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0) self.setLayout(self.layout) self.setWindowIcon(ima.icon()) ...
Setup DataFrameEditor: return False if data is not supported, True otherwise. Supported types for data are DataFrame, Series and Index.
350,352
def deserialize_unicode(data): if isinstance(data, Enum): return data try: if isinstance(data, unicode): return data except NameError: return str(data) else: return str(data)
Preserve unicode objects in Python 2, otherwise return data as a string. :param str data: response string to be deserialized. :rtype: str or unicode
350,353
def format_date(value, format=, convert_tz=None): if isinstance(value, float) or isinstance(value, int): seconds = (value - 25569) * 86400.0 parsed = datetime.datetime.utcfromtimestamp(seconds) else: parsed = dateutil.parser.parse(value) if convert_tz: local_zone = dateu...
Format an Excel date or date string, returning a formatted date. To return a Python :py:class:`datetime.datetime` object, pass ``None`` as a ``format`` argument. >>> format_date(42419.82163) 'Feb. 19, 2016' .. code-block:: html+jinja {{ row.date|format_date('%Y-%m-%d') }}
350,354
def create(client, output_file, revision, paths): graph = Graph(client) outputs = graph.build(paths=paths, revision=revision) output_file.write( yaml.dump( ascwl( graph.ascwl(outputs=outputs), filter=lambda _, x: x is not None and x != [], ...
Create a workflow description for a file.
350,355
def from_int(value): if not isinstance(value, int): raise PyVLXException("value_has_to_be_int") if not Parameter.is_valid_int(value): raise PyVLXException("value_out_of_range") return bytes([value >> 8 & 255, value & 255])
Create raw out of position vlaue.
350,356
def _build_model_factories(store): result = {} for schemaname in store: schema = None try: schema = store[schemaname][] except KeyError: schemata_log("No schema found for ", schemaname, lvl=critical, exc=True) try: result[schemaname] ...
Generate factories to construct objects from schemata
350,357
def get_unicodedata(): import unicodedata fail = False uver = unicodedata.unidata_version path = os.path.join(os.path.dirname(__file__), ) fp, pathname, desc = imp.find_module(, [path]) try: unidatadownload = imp.load_module(, fp, pathname, desc) unidatadownload.get_unicod...
Download the `unicodedata` version for the given Python version.
350,358
def get_bucket(self): for attr in [, ]: if not hasattr(self, attr): bot.exit( %(attr)) self.bucket = None for bucket in self.s3.buckets.all(): if bucket.name == self.bucket_name: self.bucket = bucket r...
given a bucket name and a client that is initialized, get or create the bucket.
350,359
def nps_survey_invitation_show(self, survey_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/invitations api_path = "/api/v2/nps/surveys/{survey_id}/invitations/{id}.json" api_path = api_path.format(survey_id=survey_id, id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/nps-api/invitations#show-invitation
350,360
def _config_win32_domain(self, domain): self.domain = dns.name.from_text(str(domain))
Configure a Domain registry entry.
350,361
def every_other(pipe, how_many=1): for i,x in zip(pipe, cycle(repeater([True,False], how_many))): if x: yield i
feeding this function a pipe yields every other (or how ever many) objects you want at a time.
350,362
def media_post(self, media_file, mime_type=None, description=None, focus=None): if mime_type is None and (isinstance(media_file, str) and os.path.isfile(media_file)): mime_type = guess_type(media_file) media_file = open(media_file, ) elif isinstance(media_file, str) and ...
Post an image. `media_file` can either be image data or a file name. If image data is passed directly, the mime type has to be specified manually, otherwise, it is determined from the file name. `focus` should be a tuple of floats between -1 and 1, giving the x and y coordinates ...
350,363
def query(self, *q): params = join_params(self.parameters, {"q": q}) return self.__class__(**params)
Takes one or more strings for searching by tag and/or metadata.
350,364
def get(self): tasks = self._get_avaliable_tasks() if not tasks: return None name, data = tasks[0] self._client.kv.delete(name) return data
Get a task from the queue.
350,365
def request( self, path, args=None, post_args=None, files=None, method=None ): if args is None: args = dict() if post_args is not None: method = "POST" if self.access_token: if post_args and "ac...
Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments.
350,366
def clean_retinotopy_potential(hemi, retinotopy=Ellipsis, mask=Ellipsis, weight=Ellipsis, surface=, min_weight=Ellipsis, min_eccentricity=0.75, visual_area=None, map_visual_areas=Ellipsis, visual_area_field_signs=Ellipsis, ...
clean_retinotopy_potential(hemi) yields a retinotopic potential function for the given hemisphere that, when minimized, should yeild a cleaned/smoothed version of the retinotopic maps. The potential function f returned by clean_retinotopy_potential() is a PotentialFunction object, as defined in neu...
350,367
def get_name(key): definition_dict = definition(key) if definition_dict: return definition_dict.get(, key) return key
Given a keyword, try to get the name of it. .. versionadded:: 4.2 Definition dicts are defined in keywords.py. We try to return the name if present, otherwise we return none. keyword = 'layer_purpose' kio = safe.utilities.keyword_io.Keyword_IO() name = kio.get_name(keyword) print name ...
350,368
def BPL(self, params): label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) def BPL_func(): if not self.is_N_set(): self.register[] = self.labels[label] return BPL_func
BPL label Branch to the instruction at label if the N flag is set
350,369
def intersection_update(self, other): ivs = list(self) for iv in ivs: if iv not in other: self.remove(iv)
Removes intervals from self unless they also exist in other.
350,370
def run(self): logger = logging.getLogger(__name__) try: repo_conf = self.config[] repo = None if repo_conf[] and repo_conf[]: try: repo = Repository(repo_conf[], ...
Captures remote hosts memory
350,371
def stop(self): if self._timer: self._timer.stop() self._timer.deleteLater()
Stop the current timer if there is one and cancel the async call.
350,372
def spline_factors(u): X = np.array([(1.-u)**3 , 4-(6.*(u**2))+(3.*(u**3)) , 1.+(3.*u)+(3.*(u**2))-(3.*(u**3)) , u**3]) * (1./6) return X
u is np.array
350,373
def scale_samples(params, bounds): b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") np.add(np.multiply(params, (upper_bounds - lower_boun...
Rescale samples in 0-to-1 range to arbitrary bounds Arguments --------- bounds : list list of lists of dimensions `num_params`-by-2 params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples
350,374
def unwrap_message(self, message, signature): if not self.is_established: raise Exception("Context has not been established") if self._wrapper is None: raise Exception("Neither sealing or signing have been negotiated") else: return self._wrapper.unwra...
Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was negotiated. A SignatureException is raised if the signature cannot be parsed or the version is unsupported A SequenceException is raised if the sequence number in the signature is incorrect ...
350,375
def p_const(self, p): == p[0] = ast.Const( name=p[3], value_type=p[2], value=p[5], lineno=p.lineno(3), )
const : CONST field_type IDENTIFIER '=' const_value | CONST field_type IDENTIFIER '=' const_value sep
350,376
def set_category(self, category: str = None) -> : return self.set_internal(PygalleBaseClass.__KEYS.CATEGORY, category)
Define the category of the class. # Arguments category: The name of category. # Returns: PygalleBaseClass: An instance of :class:`PygalleBaseClass`
350,377
def author(self): r = self.site.site_config[] if in self._config: r = self._config[] return r
Return the full path of the theme used by this page.
350,378
def _specialize_curve(nodes, start, end): _, num_nodes = np.shape(nodes) weights = ((1.0 - start, start), (1.0 - end, end)) partial_vals = { (0,): de_casteljau_one_round(nodes, *weights[0]), (1,): de_casteljau_one_round(nodes, *weights[1]), } for _ in six.mov...
Specialize a curve to a re-parameterization .. note:: This assumes the curve is degree 1 or greater but doesn't check. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control points for a...
350,379
def rdheader(record_name, pb_dir=None, rd_segments=False): dir_name, base_record_name = os.path.split(record_name) dir_name = os.path.abspath(dir_name) header_lines, comment_lines = _header._read_header_lines(base_record_name, dir_name,...
Read a WFDB header file and return a `Record` or `MultiRecord` object with the record descriptors as attributes. Parameters ---------- record_name : str The name of the WFDB record to be read, without any file extensions. If the argument contains any path delimiter characters, t...
350,380
def doTransmit(self, bytes, protocol=None): if None == protocol: protocol = self.getProtocol() CardConnection.doTransmit(self, bytes, protocol) pcscprotocolheader = translateprotocolheader(protocol) if 0 == pcscprotocolheader: raise CardConnectionExceptio...
Transmit an apdu to the card and return response apdu. @param bytes: command apdu to transmit (list of bytes) @param protocol: the transmission protocol, from CardConnection.T0_protocol, CardConnection.T1_protocol, or CardConnection.RAW_protocol @return: a tuple...
350,381
def volume( self ): return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) )
The cell volume. Args: None Returns: (float): The cell volume.
350,382
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): super(Credential, self).read(input_stream, kmip_version=kmip_version) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.CREDENTIAL_TYPE, local_stream): self._c...
Read the data encoding the Credential struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion...
350,383
def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpo...
Measure time cost of running a function
350,384
def pointcut(self, value): pointcut = getattr(self, Interceptor.POINTCUT) for target in self.targets: unweave(target, pointcut=pointcut, advices=self.intercepts) weave(target, pointcut=value, advices=self.intercepts) ...
Change of pointcut.
350,385
def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, res_upload_handler=None, size=None): provider = self.bucket.connection.provider if res_upload_handler and size: ...
Store an object in GS using the name of the Key object as the key in GS and the contents of the file pointed to by 'fp' as the contents. :type fp: file :param fp: the file whose contents are to be uploaded :type headers: dict :param headers: additional HTTP headers to b...
350,386
def get_option_type(self, key, subkey): key, subkey = _lower_keys(key, subkey) _entry_must_exist(self.gc, key, subkey) return self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]["type"].values[0]
Get the type of a particular option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :return: :class:`str` - description of the type. :raise: :NotRegisteredError: If ``key`` or ``subkey`` do not define any ...
350,387
def parse(readDataInstance): nd = NetDirectory() nd.cb.value = readDataInstance.readDword() nd.majorRuntimeVersion.value= readDataInstance.readWord() nd.minorRuntimeVersion.value = readDataInstance.readWord() nd.metaData.rva.value = readDataInstance.rea...
Returns a new L{NetDirectory} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{NetDirectory} object. @rtype: L{NetDirectory} @return: A new L{NetDirectory} object.
350,388
def queue_startfile(self, cmdfile): expanded_cmdfile = os.path.expanduser(cmdfile) is_readable = Mfile.readable(expanded_cmdfile) if is_readable: self.cmd_queue.append( + expanded_cmdfile) elif is_readable is None: self.errmsg("source file doesn%s' is no...
Arrange for file of debugger commands to get read in the process-command loop.
350,389
def dayofyear(self): def _dayofyear(date): return (date.dayofyear-1 + ((date.month > 2) and (not date.leapyear))) return _dayofyear
Day of the year index (the first of January = 0...). For reasons of consistency between leap years and non-leap years, assuming a daily time step, index 59 is always associated with the 29th of February. Hence, it is missing in non-leap years: >>> from hydpy import pub >>> fro...
350,390
def send(self, data, flags=0): return self.llc.send(self._tco, data, flags)
Send data to the socket. The socket must be connected to a remote socket. Returns a boolean value that indicates success or failure. A false value is typically an indication that the socket or connection was closed.
350,391
def globals_changed(self): value = bool(lib.EnvGetGlobalsChanged(self._env)) lib.EnvSetGlobalsChanged(self._env, int(False)) return value
True if any Global has changed.
350,392
def add_git(meta, git_info): meta["hexsha"] = git_info.hexsha meta["author"] = git_info.author meta["email"] = git_info.email meta["authored_on"] = git_info.authored_on.isoformat(" ")
Enrich the result meta information with commit data.
350,393
def setp(self, name, clear_derived=True, value=None, bounds=None, free=None, errors=None): name = self._mapping.get(name, name) try: self.params[name].set( value=value, bounds=bounds, free=free, errors=erro...
Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear derived objects in this model value: The value of the parameter, if None, it is not changed bou...
350,394
def get_events(self, login=None, start_date=None, end_date=None, **kwargs): _login = kwargs.get( , login ) log_events_url = EVENTS_URL.format( login=_login, start_date=start_date, end_date=end_date, ) return se...
Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON
350,395
def escape_tex(value): newval = value for pattern, replacement in LATEX_SUBS: newval = pattern.sub(replacement, newval) return newval
Make text tex safe
350,396
def cum_percentile(series,q): total = series.sum() cum_sum = series.cumsum() return sum(cum_sum < total*q)
Takes a series of ordered frequencies and returns the value at a specified quantile Parameters: series - Series The series to analyze q - number Quantile to get the value of
350,397
def read_data(self, **kwargs): trigger_id = kwargs.get() date_triggered = kwargs.get() data = list() since = arrow.get(date_triggered).timestamp if self.token is not None: pockets = self.pocket.get(since=since, state="unre...
get the data from the service As the pocket service does not have any date in its API linked to the note, add the triggered date to the dict data thus the service will be triggered when data will be found :param kwargs: contain keyword args : trigger_id at least :type kw...
350,398
def select(self, index=0): if self._clustering: raise exceptions.InvalidClusterCommand future = self._execute( [b, ascii(index).encode()], b) def on_selected(f): self._connection.database = index self.io_loop.add_future(future, on_selected) ...
Select the DB with having the specified zero-based numeric index. New connections always use DB ``0``. :param int index: The database to select :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` :raises: :exc:`~tredis.exceptions.InvalidClusterCommand`
350,399
def _initialize(cls): op_symbols = .strip().splitlines() if HAS_MATMUL: op_symbols.append("@ matmul rmatmul") for op_line in op_symbols: symbol, names = op_line.split(None, 1) for name in names.split(): cls._insert(name, symbol)
Internal method to initialize the class by creating all the operator metadata to be used afterwards.