Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,200
def dump_stats(self, fdump, close=True): if self.tracker: self.tracker.stop_periodic_snapshots() if isinstance(fdump, type()): fdump = open(fdump, ) pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump(self.snapshots, fdump, proto...
Dump the logged data to a file. The argument `file` can be either a filename or an open file object that requires write access. `close` controls if the file is closed before leaving this method (the default behaviour).
363,201
def read_byte(self, address): LOGGER.debug("Reading byte from device %s!", hex(address)) return self.driver.read_byte(address)
Reads unadressed byte from a device.
363,202
def merge_translations(localization_bundle_path): logging.info("Merging translations") for lang_dir in os.listdir(localization_bundle_path): if lang_dir == DEFAULT_LANGUAGE_DIRECTORY_NAME: continue for translated_path in glob.glob(os.path.join(localization_bundle_path, lang_dir,...
Merges the new translation with the old one. The translated files are saved as '.translated' file, and are merged with old translated file. Args: localization_bundle_path (str): The path to the localization bundle.
363,203
def create_oqhazardlib_source(self, tom, mesh_spacing, use_defaults=False): if not self.mfd: raise ValueError("Cannot write to hazardlib without MFD") return ComplexFaultSource( self.id, self.name, self.trt, self.mfd, mesh_...
Creates an instance of the source model as :class: openquake.hazardlib.source.complex_fault.ComplexFaultSource
363,204
def best_model(self): if not hasattr(self, ): raise AttributeError( ) model = self.build_fn( (self.specification, self.sequences, self.parse_individual(self.halloffame[0]) )) return model
Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not been run.
363,205
def GetTagDescription(tag_name): if not DoesIDExist(tag_name): warnings.warn("WARNING- " + tag_name + " does not exist or " + "connection was dropped. Try again if tag does exist.") return None split_tag = tag_name.split(".") if len(split_ta...
Gets the current description of a point configured in a real-time eDNA service. :param tag_name: fully-qualified (site.service.tag) eDNA tag :return: tag description
363,206
def init_app(self, app, configstore): if not hasattr(app, ): app.extensions = {} self.state = _WaffleState(app, configstore) app.extensions[] = self.state
Initialize the extension for the given application and store. Parse the configuration values stored in the database obtained from the ``WAFFLE_CONFS`` value of the configuration. Arguments: app: Flask application instance configstore (WaffleStore): database store.
363,207
def buyQuestItems(self): for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.na...
Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False
363,208
def update_instance( self, model_name, pk, instance=None, version=None, update_only=False): versions = [version] if version else self.versions invalid = [] for version in versions: serializer = self.model_function(model_name, version, ) lo...
Create or update a cached instance. Keyword arguments are: model_name - The name of the model pk - The primary key of the instance instance - The Django model instance, or None to load it versions - Version to update, or None for all update_only - If False (default), the...
363,209
def get_port_profile_for_intf_input_rbridge_id(self, **kwargs): config = ET.Element("config") get_port_profile_for_intf = ET.Element("get_port_profile_for_intf") config = get_port_profile_for_intf input = ET.SubElement(get_port_profile_for_intf, "input") rbridge_id = ET....
Auto Generated Code
363,210
def _parse_bbox_grid(bbox_grid): if isinstance(bbox_grid, BBoxCollection): return bbox_grid if isinstance(bbox_grid, list): return BBoxCollection(bbox_grid) raise ValueError("Parameter should be an instance of {}".format(BBoxCollection.__name__))
Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection`
363,211
def recent(self, include=None): return self._query_zendesk(self.endpoint.recent, , id=None, include=include)
Retrieve the most recent tickets
363,212
def render(self, request, collect_render_data=True, **kwargs): assert self.render_type in self.renders render = self.renders[self.render_type] if collect_render_data: kwargs = self.get_render_data(**kwargs) return render.render(request, **kwargs)
Render this view. This will call the render method on the render class specified. :param request: The request object :param collect_render_data: If True we will call \ the get_render_data method to pass a complete context \ to the renderer. :param kwargs: Any other keywo...
363,213
def DownloadResource(url, path): import requests from six import BytesIO import zipfile print("Downloading... {} to {}".format(url, path)) r = requests.get(url, stream=True) z = zipfile.ZipFile(BytesIO(r.content)) z.extractall(path) print("Completed download and extraction.")
Downloads resources from s3 by url and unzips them to the provided path
363,214
def is_separator(self, char): if len(char) > 1: raise TypeError("Expected a char.") if char in self.separators: return True return False
Test if a character is a separator. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a separator, False otherwise.
363,215
def is_valid_url(self, url, non_blocking=True): logger.debug(str((url))) if non_blocking: method = self._is_valid_url return self._create_worker(method, url) else: return self._is_valid_url(url)
Check if url is valid.
363,216
def wcomplex(wave): r ret = copy.copy(wave) ret._dep_vector = ret._dep_vector.astype(np.complex) return ret
r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_function...
363,217
def expand(cls, match, expand): return re._expand(match.re, cls._EncodedMatch(match), expand)
If use expand directly, the url-decoded context will be decoded again, which create a security issue. Hack expand to quote the text before expanding
363,218
def get_rows_by_cols(self, matching_dict): result = [] for i in range(self.num_rows): row = self._table[i+1] matching = True for key, val in matching_dict.items(): if row[key] != val: matching = False br...
Return all rows where the cols match the elements given in the matching_dict Parameters ---------- matching_dict: :obj:'dict' Desired dictionary of col values. Returns ------- :obj:`list` A list of rows that satisfy the matching_dict
363,219
def server_factory(global_conf, host, port, **options): port = int(port) try: import paste.util.threadinglocal as pastelocal pastelocal.local = local except ImportError: pass def serve(app): runner = Runner(host, port, app, options) runner.run() return serve
Server factory for paste. Options are: * proactor: class name to use from cogen.core.proactors (default: DefaultProactor - best available proactor for current platform) * proactor_resolution: float * sched_default_priority: int (see cogen.core.util.priority) * sched_default_timeout: floa...
363,220
def sample_annealed_importance_chain( num_steps, proposal_log_prob_fn, target_log_prob_fn, current_state, make_kernel_fn, parallel_iterations=10, name=None): with tf.compat.v1.name_scope(name, "sample_annealed_importance_chain", [num_steps, current_state])...
Runs annealed importance sampling (AIS) to estimate normalizing constants. This function uses an MCMC transition operator (e.g., Hamiltonian Monte Carlo) to sample from a series of distributions that slowly interpolates between an initial "proposal" distribution: `exp(proposal_log_prob_fn(x) - proposal_log_no...
363,221
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr): kws_plt, kws_dag = self._get_kws_plt(self.grprobj.usrgos, **kws_usr) pltgosusr = self.grprobj.usrgos if exclude_hdrs is not None: pltgosusr = pltgosusr.difference(self.grprobj.get_usrgos_g_hdrg...
One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple).
363,222
def password_hash(password, password_salt=None): password_salt = password_salt or oz.settings["session_salt"] salted_password = password_salt + password return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest()
Hashes a specified password
363,223
def _plot_weights_heatmap(self, index=None, figsize=None, **kwargs): W = self.get_weights()[0] if index is None: index = np.arange(W.shape[2]) fig = heatmap(np.swapaxes(W[:, :, index], 0, 1), plot_name="filter: ", vocab=self.VOCAB, figsize=figsize, **k...
Plot weights as a heatmap index = can be a particular index or a list of indicies **kwargs - additional arguments to concise.utils.plot.heatmap
363,224
def ensure_compliance(self): for p in self.paths: if os.path.exists(p): if self.is_compliant(p): continue log( % p, level=INFO) else: if not self.always_comply: log("Non-existent path - ski...
Ensure that the all registered files comply to registered criteria.
363,225
def enter_maintenance_mode(self): cmd = self._cmd() if cmd.success: self._update(get_cluster(self._get_resource_root(), self.name)) return cmd
Put the cluster in maintenance mode. @return: Reference to the completed command. @since: API v2
363,226
def getProperty(self, prop, *args, **kwargs): f = self.__getAttrs.get(prop) if not f: raise KeyError( % prop) return f(self, *args, **kwargs)
Get the value of a property. See the corresponding method for the required arguments. For example, for the property _NET_WM_STATE, look for :meth:`getWmState`
363,227
def dispatch_event(self, event: "Event") -> None: if event.target is None: event.set_target(self) listeners: dict[types.MethodType, bool] = self._registered_listeners.get(event.type) if listeners is None: return for listener i...
Dispatches the given event. It is the duty of this method to set the target of the dispatched event by calling `event.set_target(self)`. Args: event (Event): The event to dispatch. Must not be `None`. Raises: TypeError: If the event is `None` or its ty...
363,228
def _resolve_dependencies(self, cur, dependencies): list_of_deps_ids = [] _list_of_deps_unresolved = [] _is_deps_resolved = True for k, v in dependencies.items(): pgpm.lib.utils.db.SqlScriptsHelper.set_search_path(cur, self._pgpm_schema_name) cur.execute(...
Function checks if dependant packages are installed in DB
363,229
def getHosts(filename=None, hostlist=None): if filename: return getHostsFromFile(filename) elif hostlist: return getHostsFromList(hostlist) elif getEnv() == "SLURM": return getHostsFromSLURM() elif getEnv() == "PBS": return getHostsFromPBS() elif getEnv() == "SGE...
Return a list of hosts depending on the environment
363,230
def __feed_arthur(self): with self.ARTHUR_FEED_LOCK: memory_size = self.ARTHUR_LAST_MEMORY_SIZE self.ARTHUR_LAST_MEMORY_CHECK_TIME = time.time() - self.ARTHUR_LAST_MEMORY_CHECK logger.debug("Arthur items memory size: %0.2f MB (%is to ch...
Feed Ocean with backend data collected from arthur redis queue
363,231
def title(self, category): return sum( [self.getWidth(category, x) for x in self.fields])
Return the total printed length of this category item.
363,232
def estimate_ride(api_client): try: estimate = api_client.estimate_ride( product_id=SURGE_PRODUCT_ID, start_latitude=START_LAT, start_longitude=START_LNG, end_latitude=END_LAT, end_longitude=END_LNG, seat_count=2 ) exc...
Use an UberRidesClient to fetch a ride estimate and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope.
363,233
def _reset_em(self): self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False) self.em.start() self._set_shared_instances()
Resets self.em and the shared instances.
363,234
def get_bool_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[bool]: return get_bool_raw(get_string_relative( strings, prefix1, delta, prefix2, ...
Fetches a boolean parameter via :func:`get_string_relative`.
363,235
def hostapi_info(index=None): if index is None: return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount())) else: info = _pa.Pa_GetHostApiInfo(index) if not info: raise RuntimeError("Invalid host API") assert info.structVersion == 1 return {: ffi.st...
Return a generator with information about each host API. If index is given, only one dictionary for the given host API is returned.
363,236
def _eval_call(self, node): try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(self._eval(a) for a in node.args), **dict(self._eval(k) for k in node.keywords) ) if valu...
Evaluate a function call :param node: Node to eval :return: Result of node
363,237
def _iiOfAny(instance, classes): if type(classes) not in [list, tuple]: classes = [classes] return any(map(lambda x: type(instance).__name__ == x.__name__, classes))
Returns true, if `instance` is instance of any (_iiOfAny) of the `classes`. This function doesn't use :func:`isinstance` check, it just compares the class names. This can be generally dangerous, but it is really useful when you are comparing class serialized in one module and deserialized in another. ...
363,238
def blame(self, rev=, committer=True, by=, ignore_globs=None, include_globs=None): blames = [] file_names = [x for x in self.repo.git.log(pretty=, name_only=True, diff_filter=).split() if x.strip() != ] for file in self.__check_extension({x: x for x in file_names}...
Returns the blame from the current HEAD of the repository as a DataFrame. The DataFrame is grouped by committer name, so it will be the sum of all contributions to the repository by each committer. As with the commit history method, extensions and ignore_dirs parameters can be passed to exclude certain...
363,239
def build_gemini_query(self, query, extra_info): if in query: return "{0} AND {1}".format(query, extra_info) else: return "{0} WHERE {1}".format(query, extra_info)
Append sql to a gemini query Args: query(str): The gemini query extra_info(str): The text that should be added Return: extended_query(str)
363,240
def webhoneypotbytype(date, return_format=None): uri = try: uri = .join([uri, date.strftime("%Y-%m-%d")]) except AttributeError: uri = .join([uri, date]) return _get(uri, return_format)
API data for `Webhoneypot: Attack By Type <https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set of regular expressions to determine the type of attack used to attack the honeypot. Output is the top 30 attacks for the last month. :param date: string or datetime.date() (required)
363,241
def T_sigma(self, sigma): R_sigma, Q_sigma = self.RQ_sigma(sigma) return lambda v: R_sigma + self.beta * Q_sigma.dot(v)
Given a policy `sigma`, return the T_sigma operator. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- callable The T_sigma operator.
363,242
def findnextmatch(self, startkey, find_string, flags, search_result=True): assert "UP" in flags or "DOWN" in flags assert not ("UP" in flags and "DOWN" in flags) if search_result: def is_matching(key, find_string, flags): code = self(key) if...
Returns a tuple with the position of the next match of find_string Returns None if string not found. Parameters: ----------- startkey: Start position of search find_string:String to be searched for flags: List of strings, out of ["UP" xor "DOW...
363,243
def get_flow(self, name, options=None): config = self.project_config.get_flow(name) callbacks = self.callback_class() coordinator = FlowCoordinator( self.project_config, config, name=name, options=options, skip=None, ...
Get a primed and readytogo flow coordinator.
363,244
def plot_time_freq(self, mindB=-100, maxdB=None, norm=True, yaxis_label_position="right"): from pylab import subplot, gca subplot(1, 2, 1) self.plot_window() subplot(1, 2, 2) self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm) if yaxis_label...
Plotting method to plot both time and frequency domain results. See :meth:`plot_frequencies` for the optional arguments. .. plot:: :width: 80% :include-source: from spectrum.window import Window w = Window(64, name='hamming') w.plot_time_fre...
363,245
def rsky_lhood(self,rsky,**kwargs): dist = self.rsky_distribution(**kwargs) return dist(rsky)
Evaluates Rsky likelihood at provided position(s) :param rsky: position :param **kwargs: Keyword arguments passed to :func:`BinaryPopulation.rsky_distribution`
363,246
def get_limits(self): logger.debug("Gathering %sTrails Per RegionTrails Per RegionEvent Selectors Per TrailEvent Selectors Per TrailAWS::CloudTrail::EventSelectorData Resources Per TrailData Resources Per TrailAWS::CloudTrail::DataResource' ) self.limits = limits return limits
Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict
363,247
def instr(str, substr): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.instr(_to_java_column(str), substr))
Locate the position of the first occurrence of substr column in the given string. Returns null if either of the arguments are null. .. note:: The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>...
363,248
def home(self): self._log.debug("home") self._location_cache = None self._hw_manager.hardware.home()
Homes the robot.
363,249
def read_dynamic_inasafe_field(inasafe_fields, dynamic_field, black_list=None): pattern = dynamic_field[] pattern = pattern.replace(, ) if black_list is None: black_list = [] black_list = [field[] for field in black_list] unique_exposure = [] for field_key, name_field in list(ina...
Helper to read inasafe_fields using a dynamic field. :param inasafe_fields: inasafe_fields keywords to use. :type inasafe_fields: dict :param dynamic_field: The dynamic field to use. :type dynamic_field: safe.definitions.fields :param black_list: A list of fields which are conflicting with the dy...
363,250
def init(self, left_end_needle, right_end_needle): if not isinstance(left_end_needle, int): raise TypeError(_left_end_needle_error_message(left_end_needle)) if left_end_needle < 0 or left_end_needle > 198: raise ValueError(_left_end_needle_error_message(left_end_needle)...
Initialize the StartRequest with start and stop needle. :raises TypeError: if the arguments are not integers :raises ValueError: if the values do not match the :ref:`specification <m4-01>`
363,251
def wwpn_free_if_allocated(self, wwpn): wwpn_int = int(wwpn[-4:], 16) self._wwpn_pool.free_if_allocated(wwpn_int)
Free a WWPN allocated with :meth:`wwpn_alloc`. If the WWPN is not currently allocated or not in the pool range, nothing happens. Parameters: WWPN (string): The WWPN as 16 hexadecimal digits.
363,252
def s(*members: T, meta=None) -> Set[T]: return Set(pset(members), meta=meta)
Creates a new set from members.
363,253
def calc_mean_std(c0, c1=[], nonStdZero=False): mi = calc_mean(c0, c1) std = calc_std(c0, c1) if (nonStdZero): std[std == 0] = 1 return mi, std
Calculates both the mean of the data.
363,254
def parse_otu_list(lines, precision=0.0049): for line in lines: if is_empty(line): continue tokens = line.strip().split() distance_str = tokens.pop(0) if distance_str.lstrip().lower().startswith(): distance = 0.0 elif distance_str == : ...
Parser for mothur *.list file To ensure all distances are of type float, the parser returns a distance of 0.0 for the unique groups. However, if some sequences are very similar, mothur may return a grouping at zero distance. What Mothur really means by this, however, is that the clustering is at t...
363,255
def _get_sghead(expnum): version = key = "{}{}".format(expnum, version) if key in sgheaders: return sgheaders[key] url = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHTSG/{}{}.head".format(expnum, version) logging.getLogger("requests").setLevel(logging.ERROR) logging.d...
Use the data web service to retrieve the stephen's astrometric header. :param expnum: CFHT exposure number you want the header for :rtype : list of astropy.io.fits.Header objects.
363,256
def mutate_add_connection(self, config): possible_outputs = list(iterkeys(self.nodes)) out_node = choice(possible_outputs) possible_inputs = possible_outputs + config.input_keys in_node = choice(possible_inputs) if in_node in config.output_keys and out_node in...
Attempt to add a new connection, the only restriction being that the output node cannot be one of the network input pins.
363,257
def is_bare(self): self.create() try: output = self.context.capture(, , silent=True) tokens = output.split() return int(tokens[0]) == 0 except Exception: return False
:data:`True` if the repository has no working tree, :data:`False` if it does. The value of this property is computed by running the ``hg id`` command to check whether the special global revision id ``000000000000`` is reported.
363,258
def set_time_function(self, function): if isinstance(function, types.FunctionType): self.get_time = function else: raise ValueError("Invalid value for DUT time function")
Set time function to be used. :param function: callable function :return: Nothing :raises: ValueError if function is not types.FunctionType.
363,259
def _match(names): pkgs = list_pkgs(versions_as_list=True) errors = [] full_pkg_strings = [] out = __salt__[]([], output_loglevel=, python_shell=False) for line in out.splitlines(): try: full_pkg...
Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encountered.
363,260
def CaptureVariableInternal(self, value, depth, limits, can_enqueue=True): if depth == limits.max_depth: return {: 0} if value is None: self._total_size += 4 return {: } if isinstance(value, _PRIMITIVE_TYPES): r = _TrimString(repr(value), min(limits.m...
Captures a single nameless object into Variable message. TODO(vlif): safely evaluate iterable types. TODO(vlif): safely call str(value) Args: value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. can_en...
363,261
def _new_stream(self, idx): stream_index = self.stream_idxs_[idx] self.streams_[idx] = self.streamers[stream_index].iterate() self.stream_counts_[idx] = 0
Activate a new stream, given the index into the stream pool. BaseMux's _new_stream simply chooses a new stream and activates it. For special behavior (ie Weighted streams), you must override this in a child class. Parameters ---------- idx : int, [0:n_streams - 1] ...
363,262
def validate_reference(self, reference: ReferenceDefinitionType) -> Optional[Path]: if reference is not None: if isinstance(reference, bytes): reference = reference.decode("utf-8") try: return Path(reference) except TypeError: ...
Converts reference to :class:`Path <pathlib.Path>` :raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`.
363,263
def attack_batch(self, imgs, labs): def compare(x, y): if not isinstance(x, (float, int, np.int64)): x = np.copy(x) if self.TARGETED: x[y] -= self.CONFIDENCE else: x[y] += self.CONFIDENCE x = np.argmax(x) if self.TARGETED: return x == y ...
Run the attack on a batch of instance and labels.
363,264
def write_classes(self, diagram): for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)): self.printer.emit_node(i, **self.get_values(obj)) obj.fig_id = i for rel in diagram.get_relationships("specialization"): self.printer....
write a class diagram
363,265
def interpolation_bilinear(x, y, x1, x2, y1, y2, z11, z21, z22, z12): t = (x - x1) / (x2 - x1) s = (y - y1) / (y2 - y1) v1 = (1.0 - t) * (1.0 - s) * z11 v2 = t * (1.0 - s) * z21 v3 = t * s * z22 v4 = (1.0 - t) * s * z12 ret = v1 + v2 + v3 + v4 return ret
The points (x_i, y_i) and values z_ij are connected as follows: Starting from lower left going in mathematically positive direction, i.e. counter clockwise. Therefore: (x1,y1,z11), (x2,y1,z21), (x2,y2,z22), (x1,y2,z12).
363,266
def rebind(self, column=None, brew=): self.data[] = Data.keypairs( self.raw_data, columns=[self.data_key, column]) domain = [Data.serialize(self.raw_data[column].min()), Data.serialize(self.raw_data[column].quantile(0.95))] scale = Scale(name=, type=, domai...
Bind a new column to the data map Parameters ---------- column: str, default None Pandas DataFrame column name brew: str, default None Color brewer abbreviation. See colors.py
363,267
def make_gaussian_prf_sources_image(shape, source_table): model = IntegratedGaussianPRF(sigma=1) if in source_table.colnames: sigma = source_table[] else: sigma = model.sigma.value colnames = source_table.colnames if not in colnames and in colnames: source_tabl...
Make an image containing 2D Gaussian sources. Parameters ---------- shape : 2-tuple of int The shape of the output 2D image. source_table : `~astropy.table.Table` Table of parameters for the Gaussian sources. Each row of the table corresponds to a Gaussian source whose paramet...
363,268
def list_secrets(self, secure_data_path): secure_data_path = self._add_slash(secure_data_path) secret_resp = get_with_retry(self.cerberus_url + + secure_data_path + , headers=self.HEADERS) throw_if_bad_response(secret_resp) ...
Return json secrets based on the secure_data_path, this will list keys in a folder
363,269
def run_simulations(self, parameter_list, data_folder): self.data_folder = data_folder with Pool(processes=MAX_PARALLEL_PROCESSES) as pool: for result in pool.imap_unordered(self.launch_simulation, parameter_list): yield ...
This function runs multiple simulations in parallel. Args: parameter_list (list): list of parameter combinations to simulate. data_folder (str): folder in which to create output folders.
363,270
def walk(self): if conf.core.snapshots is not None: return self.snaps[conf.core.snapshots] elif conf.core.timesteps is not None: return self.steps[conf.core.timesteps] return self.snaps[-1:]
Return view on configured steps slice. Other Parameters: conf.core.snapshots: the slice of snapshots. conf.core.timesteps: the slice of timesteps.
363,271
def get_nve_vni_switch_bindings(vni, switch_ip): LOG.debug("get_nve_vni_switch_bindings() called") session = bc.get_reader_session() try: return (session.query(nexus_models_v2.NexusNVEBinding). filter_by(vni=vni, switch_ip=switch_ip).all()) except sa_exc.NoResultFound: ...
Return the nexus nve binding(s) per switch.
363,272
def MakeSuiteFromList(t, name=): hist = MakeHistFromList(t) d = hist.GetDict() return MakeSuiteFromDict(d)
Makes a suite from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this suite Returns: Suite object
363,273
def on_slice(self, node): return slice(self.run(node.lower), self.run(node.upper), self.run(node.step))
Simple slice.
363,274
def exception_handler(exc, context): if isinstance(exc, exceptions.APIException): headers = {} if getattr(exc, , None): headers[] = exc.auth_header if getattr(exc, , None): headers[] = % exc.wait if isinstance(exc.detail, (list, dict)): data...
Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a 500 error to be raised.
363,275
def _is_compact_jws(self, jws): try: jwt = JWSig().unpack(jws) except Exception as err: logger.warning(.format(err)) return False if "alg" not in jwt.headers: return False if jwt.headers["alg"] is None: jwt.headers["a...
Check if we've got a compact signed JWT :param jws: The message :return: True/False
363,276
def serialize_parameters(self): class_params = self.class_params() instance_params = self.params() serialized = {} for name in class_params.keys(): param = class_params[name] value = instance_params[name] serialized[name] =...
Get the parameter data in its serialized form. Data is serialized by each parameter's :meth:`Parameter.serialize` implementation. :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}`` :rtype: :class:`dict`
363,277
def get_comments_are_open(instance): if not IS_INSTALLED: return False try: mod = moderator._registry[instance.__class__] except KeyError: return True return CommentModerator.allow(mod, None, instance, None)
Check if comments are open for the instance
363,278
def create_timeline(self, timeline, scope_identifier, hub_name, plan_id): route_values = {} if scope_identifier is not None: route_values[] = self._serialize.url(, scope_identifier, ) if hub_name is not None: route_values[] = self._serialize.url(, hub_name, ) ...
CreateTimeline. :param :class:`<Timeline> <azure.devops.v5_0.task.models.Timeline>` timeline: :param str scope_identifier: The project GUID to scope the request :param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server :param ...
363,279
def wait_until_done(self): wait = 1 while True: time.sleep(wait) self.get_info() if self.info[][]: break wait = min(wait * 2, 60)
This method will not return until the job is either complete or has reached an error state. This queries the server periodically to check for an update in status.
363,280
def get_config(self): config = self._kwargs.copy() config.update({ : self.__class__.__name__, : self.name, : self.output_names, : self.label_names}) return config
Save configurations of metric. Can be recreated from configs with metric.create(``**config``)
363,281
def update_name(self, force=False, create_term=False, report_unchanged=True): updates = [] self.ensure_identifier() name_term = self.find_first() if not name_term: if create_term: name_term = self[].new_term(,) else: up...
Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space
363,282
def get_container_host_config_kwargs(self, action, container_name, kwargs=None): container_map = action.container_map container_config = action.config client_config = action.client_config config_id = action.config_id map_name = config_id.map_name policy = self._p...
Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type container_na...
363,283
def delete(self, path=None, method=, **options): return self.route(path, method, **options)
Equals :meth:`route` with a ``DELETE`` method parameter.
363,284
def error_name(self) : "the error name for a DBUS.MESSAGE_TYPE_ERROR message." result = dbus.dbus_message_get_error_name(self._dbobj) if result != None : result = result.decode() return \ result
the error name for a DBUS.MESSAGE_TYPE_ERROR message.
363,285
def __create_file_name(self, message_no): cwd = os.getcwd() filename = .format(self.output_prefix, message_no) return os.path.join(cwd, filename)
Create the filename to save to
363,286
def trim_wav_sox(in_path: Path, out_path: Path, start_time: int, end_time: int) -> None: if out_path.is_file(): logger.info("Output path %s already exists, not trimming file", out_path) return start_time_secs = millisecs_to_secs(start_time) end_time_secs = millisecs_t...
Crops the wav file at in_fn so that the audio between start_time and end_time is output to out_fn. Measured in milliseconds.
363,287
def accept_moderator_invite(self, subreddit): data = {: six.text_type(subreddit)} self.user._mod_subs = None self.evict(self.config[]) return self.request_json(self.config[], data=data)
Accept a moderator invite to the given subreddit. Callable upon an instance of Subreddit with no arguments. :returns: The json response from the server.
363,288
def class_logit(layer, label): def inner(T): if isinstance(label, int): class_n = label else: class_n = T("labels").index(label) logits = T(layer) logit = tf.reduce_sum(logits[:, class_n]) return logit return inner
Like channel, but for softmax layers. Args: layer: A layer name string. label: Either a string (refering to a label in model.labels) or an int label position. Returns: Objective maximizing a logit.
363,289
def equal_set(self, a, b): "See if a and b have the same elements" if len(a) != len(b): return 0 if a == b: return 1 return self.subset(a, b) and self.subset(b, a)
See if a and b have the same elements
363,290
def _eb_env_tags(envs, session_factory, retry): client = local_session(session_factory).client() def process_tags(eb_env): try: eb_env[] = retry( client.list_tags_for_resource, ResourceArn=eb_env[])[] except client.exceptions.ResourceNotFoundExc...
Augment ElasticBeanstalk Environments with their tags.
363,291
def _encode_ids(*args): ids = [] for v in args: if isinstance(v, basestring): qv = v.encode() if isinstance(v, unicode) else v ids.append(urllib.quote(qv)) else: qv = str(v) ids.append(urllib.quote(qv)) return .join(ids)
Do url-encode resource ids
363,292
def fft_propagate(fftfield, d, nm, res, method="helmholtz", ret_fft=False): fshape = len(fftfield.shape) assert fshape in [1, 2], "Dimension of `fftfield` must be 1 or 2." if fshape == 1: func = fft_propagate_2d else: func = fft_propagate_3d names = func.__co...
Propagates a 1D or 2D Fourier transformed field Parameters ---------- fftfield : 1-dimensional or 2-dimensional ndarray Fourier transform of 1D Electric field component d : float Distance to be propagated in pixels (negative for backwards) nm : float Refractive index of med...
363,293
def bland_altman(x, y, interval=None, indep_conf=None, ax=None, c=None, **kwargs): ret = False if ax is None: fig, ax = plt.subplots(1, 1) ret = True ind = ~(np.isnan(x) | np.isnan(y)) x = x[ind] y = y[ind] xy_mean = (x + y) / 2 xy_resid = (y - x)...
Draw a Bland-Altman plot of x and y data. https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot Parameters ---------- x, y : array-like x and y data to compare. interval : float Percentile band to draw on the residuals. indep_conf : float Independently determi...
363,294
def _log_board_ports(self, ports): ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln(.format(.join(.format(p.type.value, p.tile_id, p.direction) for p in ports)))
A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects
363,295
def _get_binary_from_ipv4(self, ip_addr): return struct.unpack("!L", socket.inet_pton(socket.AF_INET, ip_addr))[0]
Converts IPv4 address to binary form.
363,296
def gru_state_tuples(num_nodes, name): if not isinstance(num_nodes, tf.compat.integral_types): raise ValueError( % num_nodes) return [(STATE_NAME % name + , tf.float32, num_nodes)]
Convenience so that the names of the vars are defined in the same file.
363,297
def register(self, src, trg, trg_mask=None, src_mask=None): ccreg = registration.CrossCorr() model = ccreg.fit(src, reference=trg) translation = [-x for x in model.toarray().tolist()[0]] warp_matrix = np.eye(2, 3) warp_matrix[...
Implementation of pair-wise registration using thunder-registration For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration This function takes two 2D single channel images and estimates a 2D translation that best aligns the pair. The estim...
363,298
def refresh_from_server(self): group = self.manager.get(id=self.id) self.__init__(self.manager, **group.data)
Refresh the group from the server in place.
363,299
def prepped_value(self): if self._prepped is None: self._prepped = self._ldap_string_prep(self[].native) return self._prepped
Returns the value after being processed by the internationalized string preparation as specified by RFC 5280 :return: A unicode string