Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,900
def cli(env, identifier, uri, ibm_api_key): image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, ) result = image_mgr.export_image_to_uri(image_id, uri, ibm_api_key) if not result: raise exceptions.CLIAbort("Failed to export Image...
Export an image to object storage. The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage
11,901
def process(self, job_id): self._logger.info( .format(self._env.now, job_id) ) self._observer.notify_service(time=self._env.now, job_id=job_id) try: service_time = next(self._service_time_generator) except StopIteration: ...
Process a job by the queue
11,902
def localize_fieldnames(fields, internationalized_fields): result = [] lang = get_language() for field in fields: if field in internationalized_fields: result.append(get_real_fieldname(field, lang)) else: result.append(field) return result
Given a list of fields and a list of field names that are internationalized, will return a list with all internationalized fields properly localized. >>> from django.utils.translation import activate >>> activate('en-us') >>> localize_fieldnames(['name', 'title', 'url'], ['title']) ['name',...
11,903
def derivative(self, x): return self.scalar * self.operator.derivative(self.scalar * x)
Return the derivative at ``x``. The derivative of the right scalar operator multiplication follows the chain rule: ``OperatorRightScalarMult(op, s).derivative(y) == OperatorLeftScalarMult(op.derivative(s * y), s)`` Parameters ---------- x : `domain` `el...
11,904
def as_xml(self): self.default_capability() s = self.new_sitemap() return s.resources_as_xml(self, sitemapindex=self.sitemapindex)
Return XML serialization of this list. This code does not support the case where the list is too big for a single XML document.
11,905
def read_namespaced_pod_status(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.read_namespaced_pod_status_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_pod_status_with_http_info(name, namespace, *...
read_namespaced_pod_status # noqa: E501 read status of the specified Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_pod_status(name, namespace, async_req=True) ...
11,906
def clear_display_name(self): if (self.get_display_name_metadata().is_read_only() or self.get_display_name_metadata().is_required()): raise errors.NoAccess() self._my_map[] = self._display_name_metadata[][0]
Clears the display name. raise: NoAccess - ``display_name`` cannot be modified *compliance: mandatory -- This method must be implemented.*
11,907
def save_data(self): title = _( "Save profiler result") filename, _selfilter = getsavefilename( self, title, getcwd_or_home(), _("Profiler result")+" (*.Result)") if filename: self.datatree.save_data(filename)
Save data
11,908
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC): start = time.time() while True: found = self.find_devices(service_uuids, name) if len(found) > 0: return found[0] if time.time(...
Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all and immediately return a result. When no device is found a value of None is ...
11,909
def MI_referenceNames(self, env, objectName, resultClassName, role): logger = env.get_logger() logger.log_debug( \ % (resultClassName)) if not resu...
Return instance names of an association class. Implements the WBEM operation ReferenceNames in terms of the references method. A derived class will not normally override this method.
11,910
def _build_latex_array(self, aliases=None): columns = 1 if aliases: qregdata = {} for q in aliases.values(): if q[0] not in qregdata: qregdata[q[0]] = q[1] + 1 elif qregdata[q[0]] < q[1] + 1: ...
Returns an array of strings containing \\LaTeX for this circuit. If aliases is not None, aliases contains a dict mapping the current qubits in the circuit to new qubit names. We will deduce the register names and sizes from aliases.
11,911
def get_value(self, index): if index.column() == 0: return self.keys[ index.row() ] elif index.column() == 1: return self.types[ index.row() ] elif index.column() == 2: return self.sizes[ index.row() ] else: return self._d...
Return current value
11,912
def dot(x_gpu, y_gpu, transa=, transb=, handle=None, target=None): if handle is None: handle = _global_cublas_handle if len(x_gpu.shape) == 1 and len(y_gpu.shape) == 1: if x_gpu.size != y_gpu.size: raise ValueError( % ...
Dot product of two arrays. For 1D arrays, this function computes the inner product. For 2D arrays of shapes `(m, k)` and `(k, n)`, it computes the matrix product; the result has shape `(m, n)`. Parameters ---------- x_gpu : pycuda.gpuarray.GPUArray Input array. y_gpu : pycuda.gpuar...
11,913
def get_type(full_path): status = {: []} if os.path.ismount(full_path): status[] += [] elif os.path.islink(full_path): status[] += [] if os.path.isfile(full_path): status[] += [] elif os.path.isdir(full_path): status[] += [] if not status[]: if os.sta...
Get the type (socket, file, dir, symlink, ...) for the provided path
11,914
def start_server(app: web.Application = None, port: int = None, address: str = None, **kwargs: Any) -> HTTPServer: app = app or get_app() port = port if port is not None else config.port address = address if address is not None else config.address server = app.listen(port, address...
Start server with ``app`` on ``localhost:port``. If port is not specified, use command line option of ``--port``.
11,915
def plotGrid(self, numLines=(5,5), lineWidth=1, colour=" x1, x2, y1, y2 = mp.axis() ra1, dec0 = self.pixToSky(x1, y1) ra0, dec1 = self.pixToSky(x2, y2) xNum, yNum = numLines self.raRange, self.decRange = self.getRaDecRanges(numLines) a1 = np....
Plot NUMLINES[0] vertical gridlines and NUMLINES[1] horizontal gridlines, while keeping the initial axes bounds that were present upon its calling. Will not work for certain cases.
11,916
def prepend_string_list(self, key, value, max_length_key): max_len = self.get(max_length_key) strings = self.get_string_list(key) strings = [value] + [x for x in strings if x != value] strings = strings[:max_len] self.beginWriteArray(key) for i in range(len(stri...
Prepend a fixed-length string list with a new string. The oldest string will be removed from the list. If the string is already in the list, it is shuffled to the top. Use this to implement things like a 'most recent files' entry.
11,917
def token(cls: Type[ConditionType], left: Any, op: Optional[Any] = None, right: Optional[Any] = None) -> ConditionType: condition = cls() condition.left = left if op: condition.op = op if right: condition.right = right return conditi...
Return Condition instance from arguments and Operator :param left: Left argument :param op: Operator :param right: Right argument :return:
11,918
def missing_any(da, freq, **kwds): r c = da.notnull().resample(time=freq).sum(dim=) if in freq: pfreq, anchor = freq.split() else: pfreq = freq if pfreq.endswith(): start_time = c.indexes[] end_time = start_time.shift(1, freq=freq) else: end_time = c.in...
r"""Return a boolean DataArray indicating whether there are missing days in the resampled array. Parameters ---------- da : DataArray Input array at daily frequency. freq : str Resampling frequency. Returns ------- out : DataArray A boolean array set to True if any month ...
11,919
def get_snapshot_policies(self, view=None): return self._get("snapshots/policies", ApiSnapshotPolicy, True, params=view and dict(view=view) or None, api_version=6)
Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6
11,920
def get_placeholder_image(width, height, name=None, fg_color=get_color(), bg_color=get_color(), text=None, font=u, fontsize=42, encoding=u, mode=, fmt=u): size = (width, height) text = text if text else .format(width, height) try: font = ImageFont.truetype(font, size=fontsize, ...
Little spin-off from https://github.com/Visgean/python-placeholder that not saves an image and instead returns it.
11,921
def get_pressure(self): self._init_pressure() pressure = 0 data = self._pressure.pressureRead() if (data[0]): pressure = data[1] return pressure
Returns the pressure in Millibars
11,922
def _construct_role(self, managed_policy_map): execution_role = IAMRole(self.logical_id + , attributes=self.get_passthrough_resource_attributes()) execution_role.AssumeRolePolicyDocument = IAMRolePolicies.lambda_assume_role_policy() managed_policy_arns = [ArnGenerator.generate_aws_mana...
Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole
11,923
def CopyToProto(self, proto): if (self.file is not None and self._serialized_start is not None and self._serialized_end is not None): proto.ParseFromString(self.file.serialized_pb[ self._serialized_start:self._serialized_end]) else: raise Error()
Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldnt be serialized, due to to few constructor arguments.
11,924
def get_region_nt_counts(region, bam, stranded=False): if type(bam) == str: bam = pysam.AlignmentFile(bam, ) if type(region) is str: r = parse_region(region) if len(r) == 3: chrom, start, end = r elif len(r) == 4: chrom, start, en...
Get counts of each nucleotide from a bam file for a given region. If R1 and R2 reads both overlap a position, only one count will be added. If the R1 and R2 reads disagree at a position they both overlap, that read pair is not used for that position. Can optionally output strand-specific counts. Param...
11,925
def is_rootlevel(self): if self.is_root(): return False parent_name = None parent_dict = self._json_data.get() if parent_dict and in parent_dict: parent_name = parent_dict.get() if not parent_dict: parent_name = self._clien...
Determine if the Activity is at the root level of a project. It will look for the name of the parent which should be either ActivityRootNames.WORKFLOW_ROOT or ActivityRootNames.CATALOG_ROOT. If the name of the parent cannot be found an additional API call is made to retrieve the parent object (...
11,926
def update(self, friendly_name=values.unset, default_service_role_sid=values.unset, default_channel_role_sid=values.unset, default_channel_creator_role_sid=values.unset, read_status_enabled=values.unset, reachability_enabled=values.unset, typing...
Update the ServiceInstance :param unicode friendly_name: A string to describe the resource :param unicode default_service_role_sid: The service role assigned to users when they are added to the service :param unicode default_channel_role_sid: The channel role assigned to users when they are add...
11,927
def _load_model(self): super()._load_model() self.mujoco_robot = Baxter() if self.has_gripper_right: self.gripper_right = gripper_factory(self.gripper_right_name) if not self.gripper_visualization: self.gripper_right.hide_visualization() ...
Loads robot and optionally add grippers.
11,928
def get_default_cassandra_connection(): for alias, conn in get_cassandra_connections(): if conn.connection.default: return alias, conn return list(get_cassandra_connections())[0]
Return first default cassandra connection :return:
11,929
def _set_people(self, people): if hasattr(people, "object_type"): people = [people] elif hasattr(people, "__iter__"): people = list(people) return people
Sets who the object is sent to
11,930
def _simplify_arguments(arguments): if len(arguments.args) == 0: return arguments.kwargs elif len(arguments.kwargs) == 0: return arguments.args else: return arguments
If positional or keyword arguments are empty return only one or the other.
11,931
def add(self, new_results): for result in new_results: result.update(self.context) self.results = self.results.append(result, ignore_index=True)
Add new benchmark results.
11,932
def format_number_field(__, prec, number, locale): prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a number field.
11,933
def __ComputeEndByte(self, start, end=None, use_chunks=True): end_byte = end if start < 0 and not self.total_size: return end_byte if use_chunks: alternate = start + self.chunksize - 1 if end_byte is not None: end_byte = min(end_byte...
Compute the last byte to fetch for this request. This is all based on the HTTP spec for Range and Content-Range. Note that this is potentially confusing in several ways: * the value for the last byte is 0-based, eg "fetch 10 bytes from the beginning" would return 9 here. ...
11,934
def run_ut_python3_qemu_internal(): pkg = glob.glob()[0] logging.info("=== NOW Running inside QEMU ===") logging.info("PIP Installing %s", pkg) check_call([, , , pkg]) logging.info("PIP Installing mxnet/test_requirements.txt") check_call([, , , , ]) logging.info("Running tests in mxnet...
this runs inside the vm
11,935
def do_status(self, arg): info = self.arm.get_info() max_len = len(max(info.keys(), key=len)) print(self.style.theme()) for key, value in info.items(): print(self.style.help(key.ljust(max_len + 2), str(value))) print()
Print information about the arm.
11,936
def parse(self, buf: memoryview, params: Params) \ -> Tuple[Command, memoryview]: try: tag, buf = Tag.parse(buf, params) except NotParseable as exc: return InvalidCommand(params, exc), buf[0:0] else: params = params.copy(tag=tag.value) ...
Parse the given bytes into a command. The basic syntax is a tag string, a command name, possibly some arguments, and then an endline. If the command has a complete structure but cannot be parsed, an :class:`InvalidCommand` is returned. Args: buf: The bytes to parse. ...
11,937
def object_to_json(obj): if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.isoformat() return str(obj)
Convert object that cannot be natively serialized by python to JSON representation.
11,938
def multi_p_run(tot_num, _func, worker, params, n_process): from multiprocessing import Process, Queue out_q = Queue() procs = [] split_num = split_seq(list(range(0, tot_num)), n_process) print(tot_num, ">>", split_num) split_len = len(split_num) if n_process > split_len: n_p...
Run _func with multi-process using params.
11,939
def _get(self, uri): resp, resp_body = self.api.method_get(uri) return self.resource_class(self, resp_body, self.response_key, loaded=True)
Handles the communication with the API when getting a specific resource managed by this class.
11,940
def response(self): describe_request_params = {} if self.filter is not None: if type(self.filter) is not dict: try: filters = json.loads(self.filter) except TypeError: filters = self._parse_cli_filters(self.filt...
Dictionary of public and private, hostnames and ips. :rtype: dict
11,941
def _LinearMapByteStream( self, byte_stream, byte_offset=0, context=None, **unused_kwargs): elements_data_size = self._data_type_definition.GetByteSize() self._CheckByteStreamSize(byte_stream, byte_offset, elements_data_size) try: struct_tuple = self._operation.ReadFrom(byte_stream[byte_of...
Maps a data type sequence on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContext]): data type map context. Returns: tuple[object, ...]: mapped values. Raises: Map...
11,942
def codes2unicode(codes, composed=True): pua = u.join(unichr(code) for code in codes) return translate(pua, composed=composed)
Convert Hanyang-PUA code iterable to Syllable-Initial-Peak-Final encoded unicode string. :param codes: an iterable of Hanyang-PUA code :param composed: the result should be composed as much as possible (default True) :return: Syllable-Initial-Peak-Final encoded unicode string
11,943
def write(self, s): try: self._write_lock.acquire() self.handle.sendall(s) except socket.timeout: self._connect() except socket.error: raise IOError finally: self._write_lock.release()
Write wrapper. Parameters ---------- s : bytes Bytes to write
11,944
def _write_current_buffer_for_group_key(self, key): write_info = self.write_buffer.pack_buffer(key) self.write(write_info.get(), self.write_buffer.grouping_info[key][]) self.write_buffer.clean_tmp_files(write_info) self.write_buffer.add_new_buffer_for_group(ke...
Find the buffer for a given group key, prepare it to be written and writes it calling write() method.
11,945
def mode_string_v10(msg): if msg.autopilot == mavlink.MAV_AUTOPILOT_PX4: return interpret_px4_mode(msg.base_mode, msg.custom_mode) if not msg.base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED: return "Mode(0x%08x)" % msg.base_mode if msg.type in [ mavlink.MAV_TYPE_QUADROTOR, mavlink...
mode string for 1.0 protocol, from heartbeat
11,946
def find_features(seqs, locus_tag="all", utr_len=200): found_features = [] for seq_i in seqs: for feature in seq_i.features: if feature.type == "CDS" and (locus_tag == "all" or \ ( in feature.qualifiers and \ feature.qualifiers[][0] == locus_tag)...
Find features in sequences by locus tag
11,947
def ase(dbuser, dbpassword, args, gui): if dbuser == : dbpassword = db = CathubPostgreSQL(user=dbuser, password=dbpassword) db._connect() server_name = db.server_name subprocess.call( ("ase db {} {}".format(server_name, args)).split()) if gui: args = args.split()[0]...
Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possible ase db arguments run <ase db --help>
11,948
def update_domain_queues(self): for key in self.domain_config: final_key = "{name}:{domain}:queue".format( name=self.spider.name, domain=key) if final_key in self.queue_dict: self.queue_dict[final_key][0].windo...
Check to update existing queues already in memory new queues are created elsewhere
11,949
def search_mergedcell_value(xl_sheet, merged_range): for search_row_idx in range(merged_range[0], merged_range[1]): for search_col_idx in range(merged_range[2], merged_range[3]): if xl_sheet.cell(search_row_idx, search_col_idx).value: return xl_sheet.cell(search_row_idx, sea...
Search for a value in merged_range cells.
11,950
def _clear(self): ret = ([],[]) for q in self.queues.values(): pr = q._clear() ret[0].extend(pr[0]) ret[1].extend(pr[1]) self.totalSize = 0 del self.prioritySet[:] if self.isWaited and self.canAppend(): self.isWaited = Fals...
Actual clear
11,951
def dataframe(self): if self._away_goals is None and self._home_goals is None: return None fields_to_include = { : self.arena, : self.attendance, : self.away_assists, : self.away_even_strength_assists, : self.away_even_stre...
Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string URI that is used to instantiate the class, such as '201806070VEG'.
11,952
def GetByteSize(self): if not self.element_data_type_definition: return None if self.elements_data_size: return self.elements_data_size if not self.number_of_elements: return None element_byte_size = self.element_data_type_definition.GetByteSize() if not element_byte_size: ...
Retrieves the byte size of the data type definition. Returns: int: data type size in bytes or None if size cannot be determined.
11,953
def check_positive_flux(cls, kwargs_ps): pos_bool = True for kwargs in kwargs_ps: point_amp = kwargs[] for amp in point_amp: if amp < 0: pos_bool = False break return pos_bool
check whether inferred linear parameters are positive :param kwargs_ps: :return: bool
11,954
def load_genotypes(self): lb = self.chunk * Parser.chunk_stride + 2 ub = (self.chunk + 1) * Parser.chunk_stride + 2 buff = None self.current_file = self.archives[self.file_index] self.info_file = self.info_files[self.file_index] while buff is None: ...
Actually loads the first chunk of genotype data into memory due to \ the individual oriented format of MACH data. Due to the fragmented approach to data loading necessary to avoid running out of RAM, this function will initialize the data structures with the first chunk of loci and prep...
11,955
def _on_io_events(self, fd=None, _events=None): if fd not in self._connections: LOGGER.warning() return self._poll_connection(fd)
Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised
11,956
def __get_overall_data(self, x): if isinstance(x, dict): if "sensorGenus" in x: if x["sensorGenus"] and x["sensorGenus"] not in self.lsts_tmp["genus"]: self.lsts_tmp["genus"].append(x["sensorGenus"]) if "sensorSpecies" in x: if...
(recursive) Collect all "sensorGenus" and "sensorSpecies" fields, set data to self :param any x: Any data type :return none:
11,957
def set_sample_probability(probability): global _sample_probability if not 0.0 <= probability <= 1.0: raise ValueError() LOGGER.debug(, probability) _sample_probability = float(probability)
Set the probability that a batch will be submitted to the InfluxDB server. This should be a value that is greater than or equal to ``0`` and less than or equal to ``1.0``. A value of ``0.25`` would represent a probability of 25% that a batch would be written to InfluxDB. :param float probability: The v...
11,958
def conv_gru(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): def do_conv(args, name, bias_start, padding): return conv( args, filters, kernel_size, padding=pa...
Convolutional GRU in 1 dimension.
11,959
def run_transaction(transactor, callback): if isinstance(transactor, sqlalchemy.engine.Connection): return _txn_retry_loop(transactor, callback) elif isinstance(transactor, sqlalchemy.engine.Engine): with transactor.connect() as connection: return _txn_retry_loop(connection, cal...
Run a transaction with retries. ``callback()`` will be called with one argument to execute the transaction. ``callback`` may be called more than once; it should have no side effects other than writes to the database on the given connection. ``callback`` should not call ``commit()` or ``rollback()``; ...
11,960
def escape_identifier(text, reg=KWD_RE): if not text: return "_" if text[0].isdigit(): text = "_" + text return reg.sub(r"\1_", text)
Escape partial C identifiers so they can be used as attributes/arguments
11,961
def get(self): click_tracking = {} if self.enable is not None: click_tracking["enable"] = self.enable if self.enable_text is not None: click_tracking["enable_text"] = self.enable_text return click_tracking
Get a JSON-ready representation of this ClickTracking. :returns: This ClickTracking, ready for use in a request body. :rtype: dict
11,962
def iter_successors(self, graph, orig, branch, turn, tick, *, forward=None): if self.db._no_kc: yield from self._adds_dels_sucpred(self.successors[graph, orig], branch, turn, tick)[0] return if forward is None: forward = self.db._forward yield from se...
Iterate over successors of a given origin node at a given time.
11,963
def to_vector(np_array): if len(np_array.shape) == 1: return Vectors.dense(np_array) else: raise Exception("An MLLib Vector can only be created from a one-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
Convert numpy array to MLlib Vector
11,964
def nextindx(self): indx = 0 with s_lmdbslab.Scan(self.slab, self.db) as curs: last_key = curs.last_key() if last_key is not None: indx = s_common.int64un(last_key) + 1 return indx
Determine the next insert offset according to storage. Returns: int: The next insert offset.
11,965
def load_config(self, config=None): cfgname = (config or self.config_name) cfgname = if cfgname is None else cfgname assert isinstance(cfgname, six.string_types), config_name = cfgname if cfgname.endswith() else .format(cfgname) self.configfile = os.path.join...
loads a config file Parameters: config (str): Optional name of manual config file to load
11,966
def cleanUpdatesList(self, col, cellIdx, seg): for key, updateList in self.segmentUpdates.iteritems(): c,i = key[0], key[1] if c == col and i == cellIdx: for update in updateList: if update[1].segment == seg: self.removeSegmentUpdate(update)
Removes any update that would be for the given col, cellIdx, segIdx. NOTE: logically, we need to do this when we delete segments, so that if an update refers to a segment that was just deleted, we also remove that update from the update list. However, I haven't seen it trigger in any of the unit tests y...
11,967
def api(server, command, *args, **kwargs): ["MyGroup", "Description"] if in kwargs: arguments = kwargs[] else: arguments = args call = .format(command, arguments) try: client, key = _get_session(server) except Exception as exc: err_msg = .format(server, exc) ...
Call the Spacewalk xmlrpc api. CLI Example: .. code-block:: bash salt-run spacewalk.api spacewalk01.domain.com systemgroup.create MyGroup Description salt-run spacewalk.api spacewalk01.domain.com systemgroup.create arguments='["MyGroup", "Description"]' State Example: .. code-block:...
11,968
def get_issuer(request): if isinstance(request, etree._Element): elem = request else: if isinstance(request, Document): request = request.toxml() elem = fromstring(request, forbid_dtd=True) issuer = None issuer_nodes = OneLogi...
Gets the Issuer of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :return: The Issuer :rtype: string
11,969
def calibrate(filename): params = calibration_to(filename) with nc.loader(filename) as root: for key, value in params.items(): nc.getdim(root, , 1) nc.getdim(root, , 1) if isinstance(value, list): for i in range(len(value)): nc...
Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file.
11,970
def add_nodes_from(self, nodes, weights=None): nodes = list(nodes) if weights: if len(nodes) != len(weights): raise ValueError("The number of elements in nodes and weights" "should be equal.") for index in range(len(nodes...
Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python object). weights: list, tuple (default=None) ...
11,971
def correlate(h1, h2): r h1, h2 = __prepare_histogram(h1, h2) h1m = h1 - scipy.sum(h1) / float(h1.size) h2m = h2 - scipy.sum(h2) / float(h2.size) a = scipy.sum(scipy.multiply(h1m, h2m)) b = math.sqrt(scipy.sum(scipy.square(h1m)) * scipy.sum(scipy.square(h2m))) return 0 if 0 == b else a / b
r""" Correlation between two histograms. The histogram correlation between two histograms :math:`H` and :math:`H'` of size :math:`m` is defined as: .. math:: d_{corr}(H, H') = \frac{ \sum_{m=1}^M (H_m-\bar{H}) \cdot (H'_m-\bar{H'}) }{ \sqrt...
11,972
def update_execution_state_kernel(self): client = self.get_current_client() if client is not None: executing = client.stop_button.isEnabled() self.interrupt_action.setEnabled(executing)
Update actions following the execution state of the kernel.
11,973
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): lockslocks if self._session_lock_identifier is None: raise ProgrammerError() if priorities is None: priorities = defaultdict(int) if locks is None: ...
Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing prevents another caller from coming in an modifying data without using locks. :param m...
11,974
def get_distribute_verbatim_metadata(self): metadata = dict(self._mdata[]) metadata.update({: self._my_map[]}) return Metadata(**metadata)
Gets the metadata for the distribute verbatim rights flag. return: (osid.Metadata) - metadata for the distribution rights fields *compliance: mandatory -- This method must be implemented.*
11,975
def add(self, entry): if self.os is None: import os self.os = os nm = entry[0] pth = entry[1] pynm, ext = self.os.path.splitext(self.os.path.basename(pth)) ispkg = pynm == assert ext in (, ) self.toc[nm] = (ispkg, self.lib.tell())...
Override this to influence the mechanics of the Archive. Assumes entry is a seq beginning with (nm, pth, ...) where nm is the key by which we'll be asked for the object. pth is the name of where we find the object. Overrides of get_obj_from can make use of further elements in entry.
11,976
def create(self, handle, title=None, description=None): role = Role(handle=handle, title=title, description=description) schema = RoleSchema() valid = schema.process(role) if not valid: return valid db.session.add(role) db.session.commit() e...
Create a role
11,977
def getJobStatus(self, workers): jobInfo = self.JobStatus(self.__nupicJobID, workers) return jobInfo
Parameters: ---------------------------------------------------------------------- workers: If this job was launched outside of the nupic job engine, then this is an array of subprocess Popen instances, one for each worker retval: _NupicJob.JobStatus instance
11,978
def _quote_username(name): if not isinstance(name, six.string_types): return str(name) else: return salt.utils.stringutils.to_str(name)
Usernames can only contain ascii chars, so make sure we return a str type
11,979
def storage_type(self): nf = np.load(str(self.path), mmap_mode="c", allow_pickle=False) if np.iscomplexobj(nf): st = "field" else: st = "phase" return st
Depending on input data type, the storage type is either "field" (complex) or "phase" (real).
11,980
def cancel_job( self, project_id, region, job_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "cancel_job" not in self._inner_api_calls: self._inner_...
Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference...
11,981
def volume(self): volume = ((np.pi * self.primitive.radius ** 2) * self.primitive.height) return volume
The analytic volume of the cylinder primitive. Returns --------- volume : float Volume of the cylinder
11,982
def cli(ctx, board, fpga, pack, type, size, project_dir, verbose, verbose_yosys, verbose_arachne): exit_code = SCons(project_dir).time({ : board, : fpga, : size, : type, : pack, : { : verbose, : verbose_yosys, : v...
Bitstream timing analysis.
11,983
def autoLayout(self): try: direction = self.currentSlide().scene().direction() except AttributeError: direction = QtGui.QBoxLayout.TopToBottom size = self.size() self._slideshow.resize(size) prev = self._previousButton ...
Automatically lays out the contents for this widget.
11,984
def fileopenbox(msg=None , title=None , default="*" , filetypes=None ): if sys.platform == : _bring_to_front() localRoot = Tk() localRoot.withdraw() initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) if (initialfi...
A dialog to get a file name. About the "default" argument ============================ The "default" argument specifies a filepath that (normally) contains one or more wildcards. fileopenbox will display only files that match the default filepath. If omitted, defaults to "*" (al...
11,985
def _parse_accented_syllable(unparsed_syllable): if unparsed_syllable[0] == : return unparsed_syllable[1:], for character in unparsed_syllable: if character in _ACCENTED_VOWELS: vowel, tone = _accented_vowel_to_numbered(character) return unparsed_syllable.r...
Return the syllable and tone of an accented Pinyin syllable. Any accented vowels are returned without their accents. Implements the following algorithm: 1. If the syllable has an accent mark, convert that vowel to a regular vowel and add the tone to the end of the syllable. 2. Otherwise, assu...
11,986
def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): db_conn = db_conn or flask.g.db_conn __TABLE = models.JOBS query = sql.select([__TABLE.c.rconfiguration_id]). \ order_by(sql.desc(__TABLE.c.created_at)). \ where(sql.and_(__TABLE.c.topic_id == topic_id, ...
Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci
11,987
def string_format(data, out=, opts=None, **kwargs): *keyvalue if not opts: opts = __opts__ return salt.output.string_format(data, out, opts=opts, **kwargs)
Return the outputter formatted string, removing the ANSI escape sequences. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs ...
11,988
def _get_broadcast_shape(shape1, shape2): if shape1 == shape2: return shape1 length1 = len(shape1) length2 = len(shape2) if length1 > length2: shape = list(shape1) else: shape = list(shape2) i = max(length1, length2) - 1 for a, b in zip(shape1[::-1], shape2[::-1...
Given two shapes that are not identical, find the shape that both input shapes can broadcast to.
11,989
def small_integer(anon, obj, field, val): return anon.faker.small_integer(field=field)
Returns a random small integer (for a Django SmallIntegerField)
11,990
def set_connection_params(self, ip_address, tsap_snap7, tsap_logo): assert re.match(ipv4, ip_address), % ip_address result = self.library.Cli_SetConnectionParams(self.pointer, ip_address.encode(), c_uint16(tsap_snap7), ...
Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates. This function must be called just before Cli_Connect(). :param ip_address: IP ip_address of server :param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000) :param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000)
11,991
def compose_path(pub, uuid_url=False): if uuid_url: return join( "/", UUID_DOWNLOAD_KEY, str(pub.uuid) ) return join( "/", DOWNLOAD_KEY, basename(pub.file_pointer), basename(pub.filename) )
Compose absolute path for given `pub`. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url-path of the publication, without server's address \ and protocol. Raises: PrivatePublic...
11,992
def all(cls, include_deactivated=False): if include_deactivated: resources = yield cls.view.get(include_docs=True) else: resources = yield cls.active_view.get(include_docs=True) raise Return([cls(**resource[]) for resource in resources[]])
Get all resources :param include_deactivated: Include deactivated resources in response :returns: list of Document instances :raises: SocketError, CouchException
11,993
def isometric_build_atlased_mesh(script, BorderSize=0.1): filter_xml = .join([ , , % BorderSize, , , , , , , ]) util.write_filter(script, filter_xml) return None
Isometric parameterization: Build Atlased Mesh This actually generates the UV mapping from the isometric parameterization
11,994
def postorder(self, node=None): if node is None: node = self.ast try: first = iter(node) except TypeError: first = None if first: for kid in node: self.postorder(kid) try: name = + self.types...
Walk the tree in roughly 'postorder' (a bit of a lie explained below). For each node with typestring name *name* if the node has a method called n_*name*, call that before walking children. If there is no method define, call a self.default(node) instead. Subclasses of GenericAST...
11,995
def get_event_log(self, object_id): content = self._fetch("/event_log/%s" % object_id, method="GET") return FastlyEventLog(self, content)
Get the specified event log.
11,996
def get_action_group_names(self): return self.get_group_names( list(itertools.chain( *[self._get_array(), self._get_array(), self._get_array()])))
Return all the security group names configured in this action.
11,997
def qImageToArray(qimage, dtype = ): result_shape = (qimage.height(), qimage.width()) temp_shape = (qimage.height(), qimage.bytesPerLine() * 8 // qimage.depth()) if qimage.format() in (QtGui.QImage.Format_ARGB32_Premultiplied, QtGui.QImage.Format_ARG...
Convert QImage to numpy.ndarray. The dtype defaults to uint8 for QImage.Format_Indexed8 or `bgra_dtype` (i.e. a record array) for 32bit color images. You can pass a different dtype to use, or 'array' to get a 3D uint8 array for color images.
11,998
def _inject_target(self, target_adaptor): target_cls = self._target_types[target_adaptor.type_alias] declared_deps = target_adaptor.dependencies implicit_deps = (Address.parse(s, relative_to=target_adaptor.address.spec_path, subproj...
Inject a target, respecting all sources of dependencies.
11,999
def trace2(A, B): r A = asarray(A, float) B = asarray(B, float) layout_error = "Wrong matrix layout." if not (len(A.shape) == 2 and len(B.shape) == 2): raise ValueError(layout_error) if not (A.shape[1] == B.shape[0] and A.shape[0] == B.shape[1]): raise ValueError(layout_error)...
r"""Trace of :math:`\mathrm A \mathrm B^\intercal`. Args: A (array_like): Left-hand side. B (array_like): Right-hand side. Returns: float: Trace of :math:`\mathrm A \mathrm B^\intercal`.