Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
377,100
def match_column_labels(self, match_value_or_fct, levels=None, max_matches=0, empty_res=1): allmatches = self.parent._find_column_label_positions(match_value_or_fct, levels) matches = [m for m in allmatches if m in self.col_ilocs] if max_matches and len(matches) > max_matches: ...
Check the original DataFrame's column labels to find a subset of the current region :param match_value_or_fct: value or function(hdr_value) which returns True for match :param levels: [None, scalar, indexer] :param max_matches: maximum number of columns to return :return:
377,101
def begin(self, *args, **kwargs): self._transaction = True try: begin = self._con.begin except AttributeError: pass else: begin(*args, **kwargs)
Indicate the beginning of a transaction. During a transaction, connections won't be transparently replaced, and all errors will be raised to the application. If the underlying driver supports this method, it will be called with the given parameters (e.g. for distributed transactions).
377,102
def run(self, records): self_name = type(self).__name__ for i, batch in enumerate(grouper(records, self.BATCH_SIZE, skip_missing=True), 1): self.logger.info(, self_name, i) try: for j, proc_batch in enumerate(grouper( process_recor...
Runs the batch upload :param records: an iterable containing queue entries
377,103
def get_logging_file_handler(logger=None, file=None, formatter=LOGGING_DEFAULT_FORMATTER): logger = LOGGER if logger is None else logger file = tempfile.NamedTemporaryFile().name if file is None else file logging_file_handler = logging.FileHandler(file) logging_file_handler.setFormatter(formatter)...
Adds a logging file handler to given logger or default logger using given file. :param logger: Logger to add the handler to. :type logger: Logger :param file: File to verbose into. :type file: unicode :param formatter: Handler formatter. :type formatter: Formatter :return: Added handler. ...
377,104
def absent( name, region=None, key=None, keyid=None, profile=None, ): ret = {: name, : True, : , : {}} r = __salt__[]( name, region=region, key=key, keyid=keyid, profile=profile, ) if in r: ret[] = False ...
Ensure the named sqs queue is deleted. name Name of the SQS queue. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with r...
377,105
def _validate_string(self, input_string, path_to_root, object_title=): rules_path_to_root = re.sub(, , path_to_root) input_criteria = self.keyMap[rules_path_to_root] error_dict = { : object_title, : self.schema, : input_criteria, : , ...
a helper method for validating properties of a string :return: input_string
377,106
def savePkeyPem(self, pkey, path): with s_common.genfile(path) as fd: fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
Save a private key in PEM format to a file outside the certdir.
377,107
def imshow(image, backend=IMSHOW_BACKEND_DEFAULT): do_assert(backend in ["matplotlib", "cv2"], "Expected backend or , got %s." % (backend,)) if backend == "cv2": image_bgr = image if image.ndim == 3 and image.shape[2] in [3, 4]: image_bgr = image[..., 0:3][..., ::-1] ...
Shows an image in a window. dtype support:: * ``uint8``: yes; not tested * ``uint16``: ? * ``uint32``: ? * ``uint64``: ? * ``int8``: ? * ``int16``: ? * ``int32``: ? * ``int64``: ? * ``float16``: ? * ``float32``: ? * ``float64`...
377,108
def describe_role(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role[] = ...
Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole
377,109
def _get_view_method(self, request): if hasattr(self, ): return self.action if self.action else None return request.method.lower()
Get view method.
377,110
def get_arr_desc(arr): type_ = type(arr).__name__ shape = getattr(arr, , None) if shape is not None: desc = else: desc = return desc.format(type_=type_, shape=shape)
Get array description, in the form '<array type> <array shape>
377,111
def coinc(self, s0, s1, slide, step): rstat = s0[]**2. + s1[]**2. cstat = rstat + 2. * self.logsignalrate(s0, s1, slide, step) cstat[cstat < 0] = 0 return cstat ** 0.5
Calculate the coincident detection statistic. Parameters ---------- s0: numpy.ndarray Single detector ranking statistic for the first detector. s1: numpy.ndarray Single detector ranking statistic for the second detector. slide: numpy.ndarray A...
377,112
def put(self, obj): self._queue.put(obj, block=True, timeout=self._queue_put_timeout) if obj is _SHUTDOWNREQUEST: return
Put request into queue. Args: obj (cheroot.server.HTTPConnection): HTTP connection waiting to be processed
377,113
def copy(self, filename=None): dst = os.path.join(self.dst_path, filename) src = os.path.join(self.src_path, filename) dst_tmp = os.path.join(self.dst_tmp, filename) self.put(src=src, dst=dst_tmp, callback=self.update_progress, confirm=True) self.rename(src=dst_tmp, dst=...
Puts on destination as a temp file, renames on the destination.
377,114
def put(self, pid, record): try: ids = [data[] for data in json.loads( request.data.decode())] except KeyError: raise WrongFile() record.files.sort_by(*ids) record.commit() db.session.commit() return self.make_response(obj...
Handle the sort of the files through the PUT deposit files. Expected input in body PUT: .. code-block:: javascript [ { "id": 1 }, { "id": 2 }, ... } ...
377,115
def unperturbed_hamiltonian(states): r Ne = len(states) H0 = np.zeros((Ne, Ne), complex) for i in range(Ne): H0[i, i] = hbar*states[i].omega return H0
r"""Return the unperturbed atomic hamiltonian for given states. We calcualte the atomic hamiltonian in the basis of the ground states of \ rubidium 87 (in GHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2)) >>> magnetic_states = make_list_of_states([g], "magnetic") >>> print(np.diag(unperturbed_hamil...
377,116
def __cost(self, params, phase, X): params = self.__roll(params) a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) calculated_a = [a] calculated_z = [0] for i, theta in enumerate(params): z = calculated_a[-1] * theta.transpose() a...
Computes activation, cost function, and derivative.
377,117
def command_for_func(func): class FuncCommand(BaseCommand): def run(self): func() update_package_data(self.distribution) return FuncCommand
Create a command that calls the given function.
377,118
def evaluateplanarR2derivs(Pot,R,phi=None,t=0.): from .Potential import _isNonAxi isList= isinstance(Pot,list) nonAxi= _isNonAxi(Pot) if nonAxi and phi is None: raise PotentialError("The (list of) planarPotential instances is non-axisymmetric, but you did not provide phi") if isinstance...
NAME: evaluateplanarR2derivs PURPOSE: evaluate the second radial derivative of a (list of) planarPotential instance(s) INPUT: Pot - (list of) planarPotential instance(s) R - Cylindrical radius (can be Quantity) phi= azimuth (optional; can be Quantity) t= time (o...
377,119
def view_focused_activity(self) -> str: output, _ = self._execute( , self.device_sn, , , , ) return re.findall(r, output)[0]
View focused activity.
377,120
def movie(args): p = OptionParser(movie.__doc__) p.add_option("--gapsize", default=100, type="int", help="Insert gaps of size between scaffolds") add_allmaps_plot_options(p) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) inputbed, ...
%prog movie input.bed scaffolds.fasta chr1 Visualize history of scaffold OO. The history is contained within the tourfile, generated by path(). For each historical scaffold OO, the program plots a separate PDF file. The plots can be combined to show the progression as a little animation. The third argu...
377,121
def order_transforms(transforms): outputs = set().union(*[t.outputs for t in transforms]) out = [] remaining = [t for t in transforms] while remaining: leftover = [] for t in remaining: if t.inputs.isdisjoint(outputs): out.append(t) ...
Orders transforms to ensure proper chaining. For example, if `transforms = [B, A, C]`, and `A` produces outputs needed by `B`, the transforms will be re-rorderd to `[A, B, C]`. Parameters ---------- transforms : list List of transform instances to order. Outputs ------- list :...
377,122
def remove_option(self, section, name, value=None): if self._is_live(): raise RuntimeError() removed = 0 for option in list(self._data[]): if value is None or option[] == value: ...
Remove an option from a unit Args: section (str): The section to remove from. name (str): The item to remove. value (str, optional): If specified, only the option matching this value will be removed If not specified, all options with ``name...
377,123
def stub_request(self, expected_url, filename, status=None, body=None): self.fake_web = True self.faker = get_faker(expected_url, filename, status, body)
Stub a web request for testing.
377,124
def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None): if hasattr(packet, "time"): if sec is None: sec = int(packet.time) usec = int(round((packet.time - sec) * (1000000000 if se...
Writes a single packet to the pcap file. :param packet: Packet, or bytes for a single packet :type packet: Packet or bytes :param sec: time the packet was captured, in seconds since epoch. If not supplied, defaults to now. :type sec: int or long :param usec: ...
377,125
def conference_mute(self, call_params): path = + self.api_version + method = return self.request(path, method, call_params)
REST Conference Mute helper
377,126
def get_window_forecasts(self): for model_name in self.model_names: self.window_forecasts[model_name] = {} for size_threshold in self.size_thresholds: self.window_forecasts[model_name][size_threshold] = \ np.array([self.raw_forecasts[model_nam...
Aggregate the forecasts within the specified time windows.
377,127
def create_asset(self, ): name = self.name_le.text() if not name: self.name_le.setPlaceholderText("Please enter a name!") return desc = self.desc_pte.toPlainText() if not self.atype: atypei = self.atype_cb.currentIndex() assert aty...
Create a asset and store it in the self.asset :returns: None :rtype: None :raises: None
377,128
def enable_global_typelogged_profiler(flag = True): global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typelogged_profiler = flag if flag and typelogging_enabled: if _global_type_agent is None: _global_type_agent = TypeAgent() _glob...
Enables or disables global typelogging mode via a profiler. See flag global_typelogged_profiler. Does not work if typelogging_enabled is false.
377,129
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"): if self._config.isQuickstart(): self.logger.warning("QuickStart applications do not support commands") return 0 topic = "iot-2/type/%s/id/%s/cmd/%s/fmt/%s" % (typeId, deviceId, ...
Subscribe to device command messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard) commandId (string): comman...
377,130
def remove(self, child): try: self.children.remove(child) if isinstance(child, String): child._parent = None except ValueError: pass
Remove a ``child`` from the list of :attr:`children`.
377,131
def visit_keyword(self, node): if node.arg is None: return "**%s" % node.value.accept(self) return "%s=%s" % (node.arg, node.value.accept(self))
return an astroid.Keyword node as string
377,132
def setup(service_manager, conf, reload_method="reload"): conf.register_opts(service_opts) _load_service_manager_options(service_manager, conf) def _service_manager_reload(): _configfile_reload(conf, reload_method) _load_service_manager_options(service_manager, conf) if os.n...
Load services configuration from oslo config object. It reads ServiceManager and Service configuration options from an oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to reload the configuration file on reload in the master process and in all children. And then when each child ...
377,133
def rts_smoother(cls,state_dim, p_dynamic_callables, filter_means, filter_covars): no_steps = filter_covars.shape[0]-1 M = np.empty(filter_means.shape) P = np.empty(filter_covars.shape) M[-1,:] = filter_means[-1,:] P[-1,:,:] = filt...
This function implements Rauch–Tung–Striebel(RTS) smoother algorithm based on the results of kalman_filter_raw. These notations are the same: x_{k} = A_{k} * x_{k-1} + q_{k-1}; q_{k-1} ~ N(0, Q_{k-1}) y_{k} = H_{k} * x_{k} + r_{k}; r_{k-1} ~ N(0, R_{k}) ...
377,134
def runblast(self, assembly, allele, sample): genome = os.path.split(assembly)[1].split()[0] make_path(sample[self.analysistype].reportdir) try: report = glob(.format(sample[self.analysistype].reportdir, genome))[0] size = os.path.getsize(report...
Run the BLAST analyses :param assembly: assembly path/file :param allele: combined allele file :param sample: sample object :return:
377,135
def job_status(job_id, show_job_key=False, ignore_auth=False): s data :statuscode 404: job id not found :statuscode 409: an error occurred errorjob_id not founderrornot authorizedapi_keyjob_keyapplication/json')
Show a specific job. **Results:** :rtype: A dictionary with the following keys :param status: Status of job (complete, error) :type status: string :param sent_data: Input data for job :type sent_data: json encodable data :param job_id: An identifier for the job :type job_id: string ...
377,136
def read_config(self, correlation_id, parameters): value = self._read_object(correlation_id, parameters) return ConfigParams.from_value(value)
Reads configuration and parameterize it with given values. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration or null to skip parameterization. :return: ConfigParams configuration.
377,137
def register_callback_subscribed(self, callback): return self.__client.register_callback_created(partial(self.__callback_subscribed_filter, callback), serialised=False)
Register a callback for new subscription. This gets called whenever one of *your* things subscribes to something else. `Note` it is not called when whenever something else subscribes to your thing. The payload passed to your callback is either a [RemoteControl](RemotePoint.m.html#Iotic...
377,138
def parse_line(self, line, lineno): if not line.strip(): return if self.state == self.STATES[] and self.RE_HEADER_LINE.match(line): return step_marker_match ...
Parse a single line of the log. We have to handle both buildbot style logs as well as Taskcluster logs. The latter attempt to emulate the buildbot logs, but don't accurately do so, partly due to the way logs are generated in Taskcluster (ie: on the workers themselves). Buildbot logs: ...
377,139
def _intersection_with_dsis(self, dsis): new_si_set = set() for si in dsis._si_set: r = self._intersection_with_si(si) if isinstance(r, StridedInterval): if not r.is_empty: new_si_set.add(r) else: new_si...
Intersection with another :class:`DiscreteStridedIntervalSet`. :param dsis: The other operand. :return:
377,140
def build_managers(app, conf): default_options = _get_default_options(conf) manager_descriptions = ManagerDescriptions() if "job_managers_config" in conf: job_managers_config = conf.get("job_managers_config", None) _populate_manager_descriptions_from_ini(manager_descriptions,...
Takes in a config file as outlined in job_managers.ini.sample and builds a dictionary of job manager objects from them.
377,141
def _init_objaartall(self): kws = { :lambda nt: [nt.NS, nt.dcnt], :( ), :( ), } return AArtGeneProductSetsA...
Get background database info for making ASCII art.
377,142
def get_program(name, config, ptype="cmd", default=None): config = config.get("config", config) try: pconfig = config.get("resources", {})[name] except KeyError: pconfig = {} old_config = config.get("program", {}).get(name, None) if old_config: for key in [...
Retrieve program information from the configuration. This handles back compatible location specification in input YAML. The preferred location for program information is in `resources` but the older `program` tag is also supported.
377,143
def _get_error_message(response): try: data = response.json() if "error_description" in data: return data[] if "error" in data: return data[] except Exception: pass return "Unknown error"
Attempt to extract an error message from response body
377,144
def p_annotation_spdx_id_1(self, p): try: if six.PY2: value = p[2].decode(encoding=) else: value = p[2] self.builder.set_annotation_spdx_id(self.document, value) except CardinalityError: self.more_than_one_error(, p...
annotation_spdx_id : ANNOTATION_SPDX_ID LINE
377,145
def track_time(self, name, description=, max_rows=None): if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE self.register_table(name, self.uuid, , description) self._tables[name...
Create a Timer object in the Tracker.
377,146
def save_as_pil(self, fname, pixel_array=None): if pixel_array is None: pixel_array = self.numpy from PIL import Image as pillow pil_image = pillow.fromarray(pixel_array.astype()) pil_image.save(fname) return True
This method saves the image from a numpy array using Pillow (PIL fork) :param fname: Location and name of the image file to be saved. :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value This method will return True if successful
377,147
def get_opener(self, protocol): protocol = protocol or self.default_opener if self.load_extern: entry_point = next( pkg_resources.iter_entry_points("fs.opener", protocol), None ) else: entry_point = None ...
Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProtocol: If no opener could be found for the given protocol. ...
377,148
def delete_all_but(self, prefix, name): if prefix == name: Log.note("{{index_name}} will not be deleted", {"index_name": prefix}) for a in self.get_aliases(): if re.match(re.escape(prefix) + "\\d{8}_\\d{6}", a.index) and a.index != name: self...
:param prefix: INDEX MUST HAVE THIS AS A PREFIX AND THE REMAINDER MUST BE DATE_TIME :param name: INDEX WITH THIS NAME IS NOT DELETED :return:
377,149
def get_undefined_namespaces(graph: BELGraph) -> Set[str]: return { exc.namespace for _, exc, _ in graph.warnings if isinstance(exc, UndefinedNamespaceWarning) }
Get all namespaces that are used in the BEL graph aren't actually defined.
377,150
def cons(self, i): if self.b[i] in : return False elif self.b[i] == : return True if i == 0 else not self.cons(i-1) return True
True iff b[i] is a consonant
377,151
def load(ctx, variant_source, family_file, family_type, root): root = root or ctx.obj.get() or os.path.expanduser("~/.puzzle") if os.path.isfile(root): logger.error(" canpuzzle_db.sqlite3puzzle initunknowngeminiSet puzzle backend to {0}Set variant type to {0}'.format(variant_type)) cases ...
Load a variant source into the database. If no database was found run puzzle init first. 1. VCF: If a vcf file is used it can be loaded with a ped file 2. GEMINI: Ped information will be retreived from the gemini db
377,152
def parse(text): rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub(, value.strip()) rv[key] = value text = text[len(m.group(0)):] m = META.match(text) return rv, text
Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed
377,153
def allFileExists(fileList): allExists = True for fileName in fileList: allExists = allExists and os.path.isfile(fileName) return allExists
Check that all file exists. :param fileList: the list of file to check. :type fileList: list Check if all the files in ``fileList`` exists.
377,154
def rpc_name(rpc_id): name = _RPC_NAME_MAP.get(rpc_id) if name is None: name = % rpc_id return name
Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of the RPC that we wish to look...
377,155
def _handshake(self): session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: if osx_version_info < (10, 8): ...
Perform an initial TLS handshake
377,156
def reorderChild(self, parent, newitem): source = self.getItem(parent).childItems target = newitem.childItems i = 0 while i < len(source): if source[i] == target[i]: i += 1 continue else: i0 = i ...
Reorder a list to match target by moving a sequence at a time. Written for QtAbstractItemModel.moveRows.
377,157
def set_duplicated_flag(self): package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_name = package1.package_name param_list = self._config.get_fails(, {}) params1 =...
For all package set flag duplicated, if it's not unique package :return:
377,158
def theme_color(self): color = self._color if color is None or color.themeColor is None: return None return color.themeColor
A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of this property will always be a member of :ref:`MsoThemeColorIndex`. When :attr:`type` has any other value, the value of this property is |None|. ...
377,159
def add_program(self, name=None): if name is None: name = + str(self._next_prog_id) self._next_prog_id += 1 if name in self._programs: raise KeyError("Program named already exists." % name) prog = ModularProgram(se...
Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes.
377,160
def _coerce_dtype(self, other_dtype): if self._dtype is None: new_dtype = np.dtype(other_dtype) else: new_dtype = np.find_common_type([self._dtype, np.dtype(other_dtype)], []) if new_dtype != self.dtype: self.set_dtype(new_dtype)
Possibly change the bin content type to allow correct operations with other operand. Parameters ---------- other_dtype : np.dtype or type
377,161
def check_overlap(self, other, wavelengths=None, threshold=0.01): if not isinstance(other, BaseSpectrum): raise exceptions.SynphotError( ) if wavelengths is None: if other.waveset is None: return if self.wav...
Check for wavelength overlap between two spectra. Only wavelengths where ``self`` throughput is non-zero are considered. Example of full overlap:: |---------- other ----------| |------ self ------| Examples of partial overlap:: |---------- self...
377,162
def pyeapi_config(commands=None, config_file=None, template_engine=, context=None, defaults=None, saltenv=, **kwargs): *ntp server 1.2.3.4 pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs) return __salt_...
.. versionadded:: 2019.2.0 Configures the Arista switch with the specified commands, via the ``pyeapi`` library. This function forwards the existing connection details to the :mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>` execution function. commands The list of config...
377,163
def show_xticklabels(self, row, column): subplot = self.get_subplot_at(row, column) subplot.show_xticklabels()
Show the x-axis tick labels for a subplot. :param row,column: specify the subplot.
377,164
def env_string(name, required=False, default=empty): value = get_env_value(name, default=default, required=required) if value is empty: value = return value
Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable i...
377,165
def load_spectrum(path, smoothing=181, DF=-8.): try: ang, lflam = np.loadtxt(path, usecols=(0,1)).T except ValueError: with open(path, ) as f: def lines(): for line in f: yield line.replace(b, b) ang, lfl...
Load a Phoenix model atmosphere spectrum. path : string The file path to load. smoothing : integer Smoothing to apply. If None, do not smooth. If an integer, smooth with a Hamming window. Otherwise, the variable is assumed to be a different smoothing window, and the data will be convolv...
377,166
def get_bool(_bytearray, byte_index, bool_index): index_value = 1 << bool_index byte_value = _bytearray[byte_index] current_value = byte_value & index_value return current_value == index_value
Get the boolean value from location in bytearray
377,167
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): if width is None: width = shutil.get_terminal_size()[0] if label_width is None: label_width = len(self.lab...
Generate the formatted status bar string.
377,168
def split_address(address): invalid = None, None if not address and address != 0: return invalid components = str(address).split() if len(components) > 2: return invalid if components[0] and not valid_hostname(components[0]): return invalid if len(components) == ...
Returns (host, port) with an integer port from the specified address string. (None, None) is returned if the address is invalid.
377,169
def send_terrain_data(self): for bit in range(56): if self.current_request.mask & (1<<bit) and self.sent_mask & (1<<bit) == 0: self.send_terrain_data_bit(bit) return self.current_request = None self.sent_mask = 0
send some terrain data
377,170
def capture_termination_signal(please_stop): def worker(please_stop): seen_problem = False while not please_stop: request_time = (time.time() - timer.START)/60 try: response = requests.get("http://169.254.169.254/latest/meta-data/spot/termination-time")...
WILL SIGNAL please_stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN
377,171
def MACRO_DEFINITION(self, cursor): if (not hasattr(cursor, ) or cursor.location is None or cursor.location.file is None): return False name = self.get_unique_name(cursor) comment = None tokens = s...
Parse MACRO_DEFINITION, only present if the TranslationUnit is used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
377,172
def get_persistent_boot_device(self): sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) if ((sushy_system. boot.enabled) == sushy.BOOT_SOURCE_ENABLED_CONTINUOUS): return PERSISTENT_BOOT_MAP.get(sushy_system.boot.target) if not ...
Get current persistent boot device set for the host :returns: persistent boot device for the system :raises: IloError, on an error from iLO.
377,173
def libvlc_video_get_adjust_float(p_mi, option): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,),), None, ctypes.c_float, MediaPlayer, ctypes.c_uint) return f(p_mi, option)
Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later.
377,174
def port_profile_domain_profile_profile_name(self, **kwargs): config = ET.Element("config") port_profile_domain = ET.SubElement(config, "port-profile-domain", xmlns="urn:brocade.com:mgmt:brocade-port-profile") port_profile_domain_name_key = ET.SubElement(port_profile_domain, "port-profi...
Auto Generated Code
377,175
def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric=, numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): if log: sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwar...
Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_...
377,176
def set_attribute(self, key, value): if isinstance(key, int): self.children[key] = value elif isinstance(key, basestring): self.attributes[key] = value else: raise TypeError( )
Add or update the value of an attribute.
377,177
def get_voltage(self, channel): ret = self.ask("V%dO?" % channel) if ret[-1] != "V": print("ttiQl355tp.get_voltage() format error", ret) return None return float(ret[:-1])
channel: 1=OP1, 2=OP2, AUX is not supported
377,178
def dialog_mode(self, dialog_mode): if not self.is_soundbar: message = raise NotSupportedException(message) self.renderingControl.SetEQ([ (, 0), (, ), (, int(dialog_mode)) ])
Switch on/off the speaker's dialog mode. :param dialog_mode: Enable or disable dialog mode :type dialog_mode: bool :raises NotSupportedException: If the device does not support dialog mode.
377,179
def n_point_crossover(random, mom, dad, args): crossover_rate = args.setdefault(, 1.0) num_crossover_points = args.setdefault(, 1) children = [] if random.random() < crossover_rate: num_cuts = min(len(mom)-1, num_crossover_points) cut_points = random.sample(range(1, len(mom)), num_c...
Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: random -- the random number generator object mom -- ...
377,180
def _get_function_transitions(self, expression: Union[str, List], expected_type: PredicateType) -> Tuple[List[str], PredicateType, ...
A helper method for ``_get_transitions``. This gets the transitions for the predicate itself in a function call. If we only had simple functions (e.g., "(add 2 3)"), this would be pretty straightforward and we wouldn't need a separate method to handle it. We split it out into its own method b...
377,181
def scan(self, string): w = (constraint.words for constraint in self.sequence if not constraint.optional) w = itertools.chain(*w) w = [w.strip(WILDCARD) for w in w if WILDCARD not in w[1:-1]] if w and not an...
Returns True if search(Sentence(string)) may yield matches. If is often faster to scan prior to creating a Sentence and searching it.
377,182
def replace(state, host, name, match, replace, flags=None): yield sed_replace(name, match, replace, flags=flags)
A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed
377,183
async def georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): return await self._georadiusgeneric(, ...
Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. The units must be one of the follow...
377,184
def create_file_combobox(self, text, choices, option, default=NoDefault, tip=None, restart=False, filters=None, adjust_to_contents=False, default_line_edit=False): combobox = FileComboBox(self, adjust_to_content...
choices: couples (name, key)
377,185
def address_from_public_key(pk_bytes): final_bytes = bytearray() final_bytes.append(6 << 3) final_bytes.extend(pk_bytes) final_bytes.extend(struct.pack("<H", _crc16_checksum(final_bytes))) return base64.b32encode(final_bytes).decode()
Returns the base32-encoded version of pk_bytes (G...)
377,186
def get_metrics(self): if(self.sloc == 0): if(self.comments == 0): ratio_comment_to_code = 0.00 else: ratio_comment_to_code = 1.00 else: ratio_comment_to_code = float(self.comments) / self.sloc metrics = OrderedDict([(,...
Calculate ratio_comment_to_code and return with the other values
377,187
def write_backreferences(seen_backrefs, gallery_conf, target_dir, fname, snippet): if gallery_conf[] is None: return example_file = os.path.join(target_dir, fname) backrefs = scan_used_functions(example_file, gallery_conf) for backref in backrefs: include_p...
Writes down back reference files, which include a thumbnail list of examples using a certain module
377,188
def DeregisterMountPoint(cls, mount_point): if mount_point not in cls._mount_points: raise KeyError(.format(mount_point)) del cls._mount_points[mount_point]
Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set.
377,189
def f_add_parameter(self, *args, **kwargs): return self._nn_interface._add_generic(self, type_name=PARAMETER, group_type_name=PARAMETER_GROUP, args=args, kwargs=kwargs)
Adds a parameter under the current node. There are two ways to add a new parameter either by adding a parameter instance: >>> new_parameter = Parameter('group1.group2.myparam', data=42, comment='Example!') >>> traj.f_add_parameter(new_parameter) Or by passing the values directly to th...
377,190
def load_file(folder_path, idx, corpus): xml_path = os.path.join(folder_path, .format(idx)) wav_paths = glob.glob(os.path.join(folder_path, .format(idx))) if len(wav_paths) == 0: return [] xml_file = open(xml_path, , encoding=) soup = BeautifulSoup(xml_file...
Load speaker, file, utterance, labels for the file with the given id.
377,191
def get_gene_disease(self, direct_evidence=None, inference_chemical_name=None, inference_score=None, gene_name=None, gene_symbol=None, gene_id=None, disease_name=None, disease_id=None, disease_definition=None, limit=None, as_df=False): q = self.session....
Get gene–disease associations :param bool as_df: if set to True result returns as `pandas.DataFrame` :param int gene_id: gene identifier :param str gene_symbol: gene symbol :param str gene_name: gene name :param str direct_evidence: direct evidence :param str inference_...
377,192
def replace(old, new): parent = old.getparent() parent.replace(old, new)
A simple way to replace one element node with another.
377,193
def order_vertices(self): ordered = False while ordered == False: for i in range(len(self.vertices)): ordered = True for parent in self.vertices[i].parents: if parent>i: ordered = False ...
Order vertices in the graph such that parents always have a lower index than children.
377,194
def auth_user_remote_user(self, username): user = self.find_user(username=username) if user is None and self.auth_user_registration: user = self.add_user( username=username, first_name=username, ...
REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model
377,195
def zip_file(fn, mode="r"): if isdir(fn): return ExplodedZipFile(fn) elif is_zipfile(fn): return ZipFile(fn, mode) else: raise Exception("cannot treat as an archive: %r" % fn)
returns either a zipfile.ZipFile instance or an ExplodedZipFile instance, depending on whether fn is the name of a valid zip file, or a directory.
377,196
def next_except_jump(self, start): if self.code[start] == self.opc.DUP_TOP: except_match = self.first_instr(start, len(self.code), self.opc.POP_JUMP_IF_FALSE) if except_match: jmp = self.prev_op[self.get_target(except_match)] self.ignore_if.add(e...
Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found.
377,197
def request_data(key, url, file, string_content, start, end, fix_apple): data = [] try: data += events(url=url, file=file, string_content=string_content, start=start, end=end, fix_apple=fix_apple) finally: update_events(key, data) request_finished(key)
Request data, update local data cache and remove this Thread form queue. :param key: key for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as string :param start: start date :param end: end date :param fix_apple: fix kno...
377,198
def get_stp_mst_detail_output_msti_port_configured_root_guard(self, **kwargs): config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") msti = ET.SubElement(output...
Auto Generated Code
377,199
def get_compounds(identifier, namespace=, searchtype=None, as_dataframe=False, **kwargs): results = get_json(identifier, namespace, searchtype=searchtype, **kwargs) compounds = [Compound(r) for r in results[]] if results else [] if as_dataframe: return compounds_to_frame(compounds) return c...
Retrieve the specified compound records from PubChem. :param identifier: The compound identifier to use as a search query. :param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula. :param searchtype: (optional) The advanced search type, one of substructure...