Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
356,700
def copy_public_vars(self): vars = self.get_vars() vars = dict([k for k in list(vars.items()) if not k[0].startswith()]) return deepcopy(vars)
Like get_vars(), but does not include any private variables and deep copies each variable.
356,701
def square_sum(list_vector): square_sum = 0.0; list_representation = (type(list_vector[0]) == list); for index_element in range(0, len(list_vector)): if (list_representation is True): square_sum += sum(list_math_multiplication(list_vector[index_element], list_v...
! @brief Calculates square sum of vector that is represented by list, each element can be represented by list - multidimensional elements. @param[in] list_vector (list): Input vector. @return (double) Square sum of vector.
356,702
def is_admin(self): for ur in self.roleusers: if ur.role.code == : return True return False
Check that the user has a role with the code 'admin'
356,703
def cortex_rgba_plot_2D(the_map, rgba, axes=None, triangulation=None): cmap = colors_to_cmap(rgba) zs = np.linspace(0.0, 1.0, the_map.vertex_count) return cortex_cmap_plot_2D(the_map, zs, cmap, axes=axes, triangulation=triangulation)
cortex_rgba_plot_2D(map, rgba, axes) plots the given cortical map on the given axes using the given (n x 4) matrix of vertex colors and yields the resulting polygon collection object. cortex_rgba_plot_2D(map, rgba) uses matplotlib.pyplot.gca() for the axes. The option triangulation may also be passed if ...
356,704
def ensure_text(s, encoding=, errors=): if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type " % type(s))
Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
356,705
def configure_discover(self, ns, definition): @self.add_route(ns.singleton_path, Operation.Discover, ns) def discover(): swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns)) g.hide_body = True return make_response(swagger)
Register a swagger endpoint for a set of operations.
356,706
def starting_offset(source_code, offset): word_finder = worder.Worder(source_code, True) expression, starting, starting_offset = \ word_finder.get_splitted_primary_before(offset) return starting_offset
Return the offset in which the completion should be inserted Usually code assist proposals should be inserted like:: completion = proposal.name result = (source_code[:starting_offset] + completion + source_code[offset:]) Where starting_offset is the offset returned by this f...
356,707
def get_example_extractions(fname): "Get extractions from one of the examples in `cag_examples`." with open(fname, ) as f: sentences = f.read().splitlines() rdf_xml_dict = {} for sentence in sentences: logger.info("Reading \"%s\"..." % sentence) html = tc.send_query(sentence, ) ...
Get extractions from one of the examples in `cag_examples`.
356,708
def _recolumn(tmy3_dataframe): raw_columns = new_columns = [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,...
Rename the columns of the TMY3 DataFrame. Parameters ---------- tmy3_dataframe : DataFrame inplace : bool passed to DataFrame.rename() Returns ------- Recolumned DataFrame.
356,709
def import_ed25519_privatekey_from_file(filepath, password=None, prompt=False): securesystemslib.formats.PATH_SCHEMA.check_match(filepath) if password and prompt: raise ValueError("Passing and True is not allowed.") if password is not None: securesystemslib.formats.PASSWORD_SCHEMA.c...
<Purpose> Import the encrypted ed25519 key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ED25519KEY_SCHEMA' format. The private key (may also contain the public part) is encrypted with AES 256 and CTR the mode of operation. The password is strengthened with ...
356,710
def t_intnumber(self, t): r t.value = int(t.value) t.type = return t
r'-?\d+
356,711
def def_alignment(self, year): scheme_text = self._year_info_pq(year, ).text() m = re.search(r, scheme_text, re.I) if m: return m.group(1) else: return None
Returns the name of the defensive alignment the team ran in the given year. :year: Int representing the season year. :returns: A string representing the defensive alignment.
356,712
def unzip_data(): with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), ) as zf: zf.extractall(path=CACHE_FOLDER)
Extract all files from downloaded FEH data zip file.
356,713
def load(self): import h5py no_detectors_message = False with h5py.File(self.filename, ) as h5f: self.band_names = [b.decode() for b in h5f.attrs[].tolist()] self.description = h5f.attrs[].decode() if not self.platform_name: try: ...
Read the internally formatet hdf5 relative spectral response data
356,714
def start_channels(self, shell=True, sub=True, stdin=True, hb=True): if shell: self.shell_channel.start() if sub: self.sub_channel.start() if stdin: self.stdin_channel.start() self.shell_channel.allow_stdin = True else: ...
Starts the channels for this kernel. This will create the channels if they do not exist and then start them. If port numbers of 0 are being used (random ports) then you must first call :method:`start_kernel`. If the channels have been stopped and you call this, :class:`RuntimeError` wil...
356,715
def get(self, value): _nothing = object() item = self._values.get(value, _nothing) if item is _nothing: raise InvalidEnumItem(value) return item
Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does not match any known enumeration value. :rtype: EnumItem
356,716
def check_config_mode(self, check_string=") return super(CalixB6Base, self).check_config_mode(check_string=check_string)
Checks if the device is in configuration mode
356,717
def add_output_option(parser): parser.add_argument("-o", "--outdir", dest="outdir", type=str, default=, metavar=, action="store", help="The GSEApy output directory. Default: the current working directory") parser.add_argument("-f", "--format", dest="format",...
output option
356,718
def run(self): self._logger.info(, self) try: with self._lock: assert not self.running.is_set() and self._stopped.is_set(), % self self.running.set() self._stopped.clear() self._run() except Exception: ...
Execute all current and future payloads Blocks and executes payloads until :py:meth:`stop` is called. It is an error for any orphaned payload to return or raise.
356,719
def csv_to_num_matrix(csv_file_path): mtx = [] with open(csv_file_path) as csv_data_file: for row in csv_data_file: mtx.append([float(val) for val in row.split()]) return mtx
Load a CSV file consisting only of numbers into a Python matrix of floats. Args: csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
356,720
def search(self, keyword, source_in=None, **kwargs): for provider in self._providers: if source_in is not None: if provider.identifier not in source_in: continue try: result = provider.search(keyword=keyword) excep...
search song/artist/album by keyword TODO: search album or artist
356,721
def tajima_d(ac, pos=None, start=None, stop=None, min_sites=3): if not hasattr(ac, ): ac = AlleleCountsArray(ac, copy=False) if pos is not None and (start is not None or stop is not None): if not isinstance(pos, SortedIndex): pos = SortedIndex(pos, copy=False) ...
Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant positions, using 1-based coordinates, in ascending order. start : int, opti...
356,722
def to_json(self): if self._key_ranges is None: key_ranges_json = None else: key_ranges_json = [] for k in self._key_ranges: if k: key_ranges_json.append(k.to_json()) else: key_ranges_json.append(None) if self._ns_range is None: namespace_ran...
Serializes all the data in this query range into json form. Returns: all the data in json-compatible map.
356,723
def rotate(x, y, degree): radian = float(degree) * 2 * math.pi / 360.0 newx = math.cos(radian) * x - math.sin(radian) * y newy = math.sin(radian) * x + math.cos(radian) * y return (newx, newy)
Rotate a coordinate around point (0,0). - x and y specify the coordinate. - degree is a number from 0 to 360. Returns a new coordinate.
356,724
def disconnect(self): "Disconnects from the Redis server" self._parser.on_disconnect() if self._sock is None: return if self._selector is not None: self._selector.close() self._selector = None try: if os.getpid() == self.pid: ...
Disconnects from the Redis server
356,725
def instance_ik_model_receiver(fn): @wraps(fn) def receiver(self, sender, **kwargs): if not inspect.isclass(sender): return for src in self._source_groups: if issubclass(sender, src.model_class): fn(self, sender=sender, **kwargs) ...
A method decorator that filters out sign_original_specals coming from models that don't have fields that function as ImageFieldSourceGroup sources.
356,726
def entry(argv): command_dic = { : run_migrate, : run_init, : run_send_nologin, : run_send_all, : run_review, : run_sitemap, : run_editmap, : run_check_kind, : run_init_tables, : run_drop_tables, : run_gen_category, ...
Command entry
356,727
def decode_body(body, content_type): if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) except: return body if content_type == : try: return...
Decode event body
356,728
def run(configObj, wcsmap=None): if configObj[][-5:] != : configObj[] += if not util.is_blank(configObj[]) and configObj[][-5:] != : configObj[] += if not util.is_blank(configObj[]) and configObj[][-5:] != : configObj[] += in_sci_handle = None in_wht_handle = None out_sci_han...
Interface for running `wdrizzle` from TEAL or Python command-line. This code performs all file ``I/O`` to set up the use of the drizzle code for a single exposure to replicate the functionality of the original `wdrizzle`.
356,729
def add_existence(self, rev): if len(self.constraints) == 1 and ( self.constraints[0].op.is_exists() or self.constraints[0].op.is_equality()): return value = not rev constraint = Constraint(self._field, ConstraintOperator.EXISTS, v...
Add existence constraint for the field. This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present. Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent. Of course, if the constraint is already about existence, nothing is done. :...
356,730
def _onerror(cls, kmsg, result): logger.error( "{}.Failed: {}[{}]: {}".format( cls.__name__, kmsg.entrypoint, kmsg.uuid, result ), extra=dict( kmsg=kmsg.dump(), kresult=ResultSchema().dump(result) if result else dict() ...
To execute on execution failure :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result
356,731
def next_image_partname(self, ext): def first_available_image_idx(): image_idxs = sorted([ part.partname.idx for part in self.iter_parts() if part.partname.startswith() and part.partname.idx is not None ]) for i, image_...
Return a |PackURI| instance representing the next available image partname, by sequence number. *ext* is used as the extention on the returned partname.
356,732
def merge_version(self, merge_id, version_id): path = urijoin(self.base_url, GitLabClient.PROJECTS, self.owner + + self.repository, GitLabClient.MERGES, merge_id, GitLabClient.VERSIONS, version_id) response = self.fetch(path) return resp...
Get merge version detail
356,733
def init(): print(yellow(" virtualenv.init() virtualenv.update_requirements() print(green("\n print(green("Type ") + green("activate", True) + green(" to enable your virtual environment."))
Execute init tasks for all components (virtualenv, pip).
356,734
def _safe_str_cmp(a, b): if len(a) != len(b): return False rv = 0 for x, y in zip(a, b): rv |= ord(x) ^ ord(y) return rv == 0
Internal function to efficiently iterate over the hashes Regular string compare will bail at the earliest opportunity which allows timing attacks
356,735
def get_webhook(self, id, **data): return self.get("/webhooks/{0}/".format(id), data=data)
GET /webhooks/:id/ Returns a :format:`webhook` for the specified webhook as ``webhook``.
356,736
def get_models(self, columns=None): results = self.apply_scopes().get_query().get(columns).all() connection = self._model.get_connection_name() models = self._model.hydrate(results, connection) return models
Get the hydrated models without eager loading. :param columns: The columns to get :type columns: list :return: A list of models :rtype: orator.orm.collection.Collection
356,737
def report_server_init_errors(address=None, port=None, **kwargs): try: yield except EnvironmentError as e: if e.errno == errno.EADDRINUSE: log.critical("Cannot start Bokeh server, port %s is already in use", port) elif e.errno == errno.EADDRNOTAVAIL: log.crit...
A context manager to help print more informative error messages when a ``Server`` cannot be started due to a network problem. Args: address (str) : network address that the server will be listening on port (int) : network address that the server will be listening on Example: .. c...
356,738
def commit(self, index_update=True, label_guesser_update=True): logger.info("Index: Commiting changes") self.docsearch.index.commit(index_update=index_update, label_guesser_update=label_guesser_update)
Apply the changes to the index
356,739
def eval_image(image, height, width, scope=None): with tf.name_scope(values=[image, height, width], name=scope, default_name=): image = tf.image.central_crop(image, central_fraction=0.875) image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear(image, [hei...
Prepare one image for evaluation. Args: image: 3-D float Tensor height: integer width: integer scope: Optional scope for name_scope. Returns: 3-D float Tensor of prepared image.
356,740
def size(self, type=None, failed=False): return len(self.nodes(type=type, failed=failed))
How many nodes in a network. type specifies the class of node, failed can be True/False/all.
356,741
def getParamFromEnv(self, var, default=): if self.getParam(var): return self.getParam(var) if self.hostgroup: if self.hostgroup.getParam(var): return self.hostgroup.getParam(var) if self.domain.getParam(): return self.domain.getParam()...
Function getParamFromEnv Search a parameter in the host environment @param var: the var name @param hostgroup: the hostgroup item linked to this host @param default: default value @return RETURN: the value
356,742
def get_imported_modules(cells, nb_module_name=): "Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority" module_names = get_top_level_modules() nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell[])...
Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority
356,743
def plot_centres(array, centres, units, kpc_per_arcsec, zoom_offset_arcsec): if centres is not None: colors = itertools.cycle(["m", "y", "r", "w", "c", "b", "g", "k"]) for centres_of_galaxy in centres: color = next(colors) for centre in centres_of_galaxy: ...
Plot the (y,x) centres (e.g. of a mass profile) on the array as an 'x'. Parameters ----------- array : data.array.scaled_array.ScaledArray The 2D array of data which is plotted. centres : [[tuple]] The list of centres; centres in the same list entry are colored the same. units : str...
356,744
def _filters_pb(self): num_filters = len(self._field_filters) if num_filters == 0: return None elif num_filters == 1: return _filter_pb(self._field_filters[0]) else: composite_filter = query_pb2.StructuredQuery.CompositeFilter( ...
Convert all the filters into a single generic Filter protobuf. This may be a lone field filter or unary filter, may be a composite filter or may be :data:`None`. Returns: google.cloud.firestore_v1beta1.types.\ StructuredQuery.Filter: A "generic" filter representing the ...
356,745
def export(self): with open(self.export_url, , encoding=) as file: file.write(self.build()) if self.open_browser: webbrowser.open_new_tab(self.export_url)
return the object in a file
356,746
def polar_histogram(xdata, ydata, radial_bins="numpy", phi_bins=16, transformed=False, *args, **kwargs): dropna = kwargs.pop("dropna", True) data = np.concatenate([xdata[:, np.newaxis], ydata[:, np.newaxis]], axis=1) data = _prepare_data(data, transformed=transformed, klass=PolarHis...
Facade construction function for the PolarHistogram. Parameters ---------- transformed : bool phi_range : Optional[tuple] range
356,747
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None): if data is None and self.data is not None: data = self.data else: self.data = data self.ax = ax if data is None: ...
Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that shall be visualized. - If not None and `plot` is True, the given data is visualized. - If None and the :attr:`data` attribute is not Non...
356,748
def done(self): return self._exception != self._SENTINEL or self._result != self._SENTINEL
Return True the future is done, False otherwise. This still returns True in failure cases; checking :meth:`result` or :meth:`exception` is the canonical way to assess success or failure.
356,749
def hide_virtual_ip_holder_chassis_virtual_ip(self, **kwargs): config = ET.Element("config") hide_virtual_ip_holder = ET.SubElement(config, "hide-virtual-ip-holder", xmlns="urn:brocade.com:mgmt:brocade-chassis") chassis = ET.SubElement(hide_virtual_ip_holder, "chassis") virtual_...
Auto Generated Code
356,750
def _get_content(self, response): method = response.request.method self.last_response = response server_error = { : None, : None } try: content_json = response.json() if in content_json: e = content_json[...
Checks for errors in the response. Returns response content, in bytes. :param response: response object :raise: :UnexpectedResponse: if the server responded with an unexpected response :return: - ServiceNow response content
356,751
def addPriority(self, objectName): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { "name": "errorMes...
添加聊天室消息优先级方法 方法 @param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
356,752
def loader_cls(self): cls = self.app.config[] if isinstance(cls, six.string_types): return import_string(cls) return cls
Loader class used in `JsonRef.replace_refs`.
356,753
def gather_callbacks(self, optimizer) -> list: callbacks = [FrameTracker(self.total_frames), TimeTracker()] if self.scheduler_factory is not None: callbacks.append(self.scheduler_factory.instantiate(optimizer)) callbacks.extend(self.callbacks) callbacks.extend(self...
Gather all the callbacks to be used in this training run
356,754
def clear(self, job_id=None, force=False): s = self.sessionmaker() q = self._ns_query(s) if job_id: q = q.filter_by(id=job_id) if not force: q = q.filter( or_(ORMJob.state == State.COMPLETED, ORMJob.state == State.FAILED)) ...
Clear the queue and the job data. If job_id is not given, clear out all jobs marked COMPLETED. If job_id is given, clear out the given job's data. This function won't do anything if the job's state is not COMPLETED or FAILED. :type job_id: NoneType or str :param job_id: the job_id to cle...
356,755
def step3(expnums, ccd, version, rate_min, rate_max, angle, width, field=None, prefix=None, dry_run=False, maximum_flux_ratio=3, minimum_area=5, minimum_median_flux=1000.0): jmp_args = [] matt_args = [] idx = 0 cmd_args = [] for expnum in expnums: idx += 1 ...
run the actual step3 on the given exp/ccd combo
356,756
def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None): fbs = if use_frameborder else dstyle = % (ratio*100) istyle = cache_id = store_initial_arguments(context[], initial_arguments) da, app = _locate_daapp(name, slug, da, cache...
Insert a dash application using a html iframe
356,757
def process_pair(self, key, value): old_key = key old_value = value keyparts = self.bspacere.split(key) strippable = False lastpart = keyparts[-1] if lastpart.find() != -1: keyparts[-1] = lastpart.replace(,) ...
Process a (key, value) pair
356,758
async def create_lease_if_not_exists_async(self, partition_id): return_lease = None try: return_lease = AzureBlobLease() return_lease.partition_id = partition_id serializable_lease = return_lease.serializable() json_lease = json.dumps(serializable...
Create in the store the lease info for the given partition, if it does not exist. Do nothing if it does exist in the store already. :param partition_id: The ID of a given parition. :type partition_id: str :return: the existing or newly-created lease info for the partition. :rtyp...
356,759
def GWP(CASRN, AvailableMethods=False, Method=None): rs Global Warming Potential, relative to CO2. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns the GWP for the 100yr outlook by default. Pa...
r'''This function handles the retrieval of a chemical's Global Warming Potential, relative to CO2. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns the GWP for the 100yr outlook by default. Parame...
356,760
def give(self, terrain, num=1): for _ in range(num): logging.debug(.format(terrain)) self._give.append(terrain)
Add a certain number of resources to the trade from giver->getter :param terrain: resource type, models.Terrain :param num: number to add, int :return: None
356,761
def run(self, graminit_h, graminit_c): self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off()
Load the grammar tables from the text files written by pgen.
356,762
def _from_jwt(cls, headers, payload, key=None): jwt = Jwt( secret_key=key, issuer=payload.get(, None), subject=payload.get(, None), algorithm=headers.get(, None), valid_until=payload.get(, None), nbf=payload.get(, None), ) ...
Class specific implementation of from_jwt which should take jwt components and return and instance of this Class with jwt information loaded. :return: Jwt object containing the headers, payload and key
356,763
def exportData(self, datfile): def ampl_set(name, values): def format_entry(e): return repr(e).replace(, ) return .format( name, .join(format_entry(e) for e in values) ) def ampl_param(name, values): def format_e...
Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute).
356,764
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites): base_vals = np.zeros(num_sites) if mag <= 4.5: base_vals += C["f1"] elif mag >= 5.5: base_vals += C["f2"] else: base_vals += (C["f1"] + (C["f2"] - C["f1"]) * (mag - 4.5)) ...
Returns the intra-event standard deviation (phi), dependent on magnitude, distance and vs30
356,765
def convert_args_to_dict(call, with_lambda=False): keys, values = list(), list() for arg in call.args: if type(arg) in [ast.Str, ast.Num]: arg_value = arg else: arg_value = astor.to_source(arg).strip() arg_value = ast.Str(str(arg_value)) ...
Convert all args to a dict such that every key and value in the dict is the same as the value of the arg. Return the AST Call node with only one arg that is the dictionary
356,766
def fit_proba(clf, X, y_proba, expand_factor=10, sample_weight=None, shuffle=True, random_state=None, **fit_params): X, y, sample_weight = expanded_X_y_sample_weights(X, y_proba, expand_factor=expand_factor, sample_weight=sample_weight, shuffle=shuffle, ...
Fit classifier ``clf`` to return probabilities close to ``y_proba``. scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workaround this function expands the dataset according to target probabilities. Use expand_factor=None to turn it off ...
356,767
def login_handler(self, config=None, prefix=None, **args): params = { : , : self.google_api_client_id, : self.scheme_host_port_prefix( , config.host, config.port, prefix) + , : self.google_api_scope, : self.request_args_get(, d...
OAuth starts here, redirect user to Google.
356,768
def read_image(filename): with Image.open(filename) as image_source: data = [list(pixel) for pixel in image_source.getdata()] return data
! @brief Returns image as N-dimension (depends on the input image) matrix, where one element of list describes pixel. @param[in] filename (string): Path to image. @return (list) Pixels where each pixel described by list of RGB-values.
356,769
def pages(self): rev = self.db.get() if int(rev) != self.revision: self.reload_site() return self._pages
Get pages, reloading the site if needed.
356,770
def get_metadata(self): metadata_path = "{}/{}/{}".format(self.url, self.metadata_dir, self.metadata_file) metadata_sig_path = "{}/{}/{}.sig".format(self.url.rstrip(), ...
Fetch repository repomd.xml file
356,771
def get_initial(self, form, name): if hasattr(form, ): return form.initial.get(name, None) return None
Get the initial data that got passed into the superform for this composite field. It should return ``None`` if no initial values where given.
356,772
def register(self, name, function, plugin, description=None): if name in self.threads.keys(): raise ThreadExistsException("Thread %s was already registered by %s" % (name, self.threads[name].plugin.name)) self.threads[name] = Thread(name, fun...
Registers a new document. .. warning: You can not use any relative links inside a given document. For instance, sphinx's toctree, image, figure or include statements do not work. :param function: Function, which gets called for the new thread :type function: function ...
356,773
def rst(filename): content = open(filename).read() return re.sub(r, , content)
Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive
356,774
def unpack_apply_message(bufs, g=None, copy=True): bufs = list(bufs) assert len(bufs) >= 2, "not enough buffers!" pf = buffer_to_bytes_py2(bufs.pop(0)) f = uncan(pickle.loads(pf), g) pinfo = buffer_to_bytes_py2(bufs.pop(0)) info = pickle.loads(pinfo) arg_bufs, kwarg_bufs = bufs[:info[...
Unpack f,args,kwargs from buffers packed by pack_apply_message(). Returns: original f,args,kwargs
356,775
def process_input(self, encoded_stream, value): if not self.enabled: return if isinstance(encoded_stream, str): stream = DataStream.FromString(encoded_stream) encoded_stream = stream.encode() elif isinstance(encoded_stream, DataStream): ...
Process or drop a graph input. This method asynchronously queued an item to be processed by the sensorgraph worker task in _reset_vector. It must be called from inside the emulation loop and returns immediately before the input is processed.
356,776
def __Autostart_TCP_Server_checkBox_set_ui(self): autostart_tcp_server)) self.Autostart_TCP_Server_checkBox.setCheckState(autostart_tcp_server)
Sets the **Autostart_TCP_Server_checkBox** Widget.
356,777
def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull): if fname is None or not os.path.exists(fname): run_cmd(cmd, out, err) return True else: return False
Runs an external command if file is absent. :param list cmd: Command to run. :param str fname: Path to the file, which existence is being checked. :param str out: Output file :param str err: Error file :return: True if cmd was executed, False otherwise :rtype: boolean
356,778
def _ReadFileHeader(self, file_object): data_type_map = self._GetDataTypeMap() file_header, _ = self._ReadStructureFromFileObject( file_object, 0, data_type_map) if file_header.signature != self._FILE_SIGNATURE: raise errors.ParseError() if (file_header.major_format_version != self...
Reads the file header. Args: file_object (file): file-like object. Returns: keychain_file_header: file header. Raises: ParseError: if the file header cannot be read.
356,779
def analytical(src, rec, res, freqtime, solution=, signal=None, ab=11, aniso=None, epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2): r printstartfinish(verb, t0) return EM
r"""Return the analytical full- or half-space solution. Calculate the electromagnetic frequency- or time-domain field due to infinitesimal small electric or magnetic dipole source(s), measured by infinitesimal small electric or magnetic dipole receiver(s); sources and receivers are directed along the p...
356,780
def extract(self, destdir, decompress=): for e in self.mardata.index.entries: name = e.name entry_path = safejoin(destdir, name) entry_dir = os.path.dirname(entry_path) mkdir(entry_dir) with open(entry_path, ) as f: write_to_fi...
Extract the entire MAR file into a directory. Args: destdir (str): A local directory on disk into which the contents of this MAR file will be extracted. Required parent directories will be created as necessary. decompress (obj, optional): Controls whether...
356,781
def Q_srk(self, k): ind = self.index[self.Q_time_var_index, k] Q = self.Q[:, :, ind] if (Q.shape[0] == 1): square_root = np.sqrt(Q) else: if self.svd_each_time: (U, S, Vh) = sp.linalg.svd(Q, full_matrices=False, ...
function (k). Returns the square root of noise matrix of dynamic model on iteration k. k (iteration number). starts at 0 This function is implemented to use SVD prediction step.
356,782
def robust_partition_all(n, iterable): it = iter(iterable) while True: x = [] for _ in range(n): try: x.append(next(it)) except StopIteration: yield x raise StopIteration yield x
replaces partition_all with a more robust version. Workaround for a segfault in pybedtools when using a BedTool as an iterator: https://github.com/daler/pybedtools/issues/88 for the discussion
356,783
def last(self, node): return self._nodes.index(node) == len(self._nodes) - 1
Returns True if node is the last node in the route Parameters ---------- nodes : type Desc Returns ------- bool True if node is the last node in the route
356,784
def _required_args(fn): spec = getargspec(fn) if not spec.defaults: return [] arg_names = spec.args[-len(spec.defaults):] return [name for name, val in zip(arg_names, spec.defaults) if val is REQUIRED_ARG]
Returns arguments of fn with default=REQUIRED_ARG.
356,785
def send_message(source_jid, password, target_jid, body, subject = None, message_type = "chat", message_thread = None, settings = None): if sys.version_info.major < 3: from locale import getpreferredencoding encoding = getpreferredencoding() if isinstance(s...
Star an XMPP session and send a message, then exit. :Parameters: - `source_jid`: sender JID - `password`: sender password - `target_jid`: recipient JID - `body`: message body - `subject`: message subject - `message_type`: message type - `message_thread`: mess...
356,786
def lag(expr, offset, default=None, sort=None, ascending=True): return _shift_op(expr, Lag, offset, default=default, sort=sort, ascending=ascending)
Get value in the row ``offset`` rows prior to the current row. :param offset: the offset value :param default: default value for the function, when there are no rows satisfying the offset :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort ...
356,787
def annotate(self, out, filename=None, commandline=None, relative_path=False): file_dict = self._mergeFileTiming() total_time = self.total_time if commandline is not None: print(u, commandline, file=out) print(u % total_time, file=out) if not total_time: ...
Dump annotated source code with current profiling statistics to "out" file. Time unit: second. out (file-ish opened for writing) Destination of annotated sources. filename (str, collection of str) If provided, dump stats for given source file(s) only. ...
356,788
def _generate_report_all(self): assert self.workbook is not None count = 0 for sid in self.folders.subfolders(self.folder_id, self.user): count += 1 self._generate_for_subfolder(sid) if count == 0: print("I: empty workbook created: ...
Generate report for all subfolders contained by self.folder_id.
356,789
async def query_pathing( self, start: Union[Unit, Point2, Point3], end: Union[Point2, Point3] ) -> Optional[Union[int, float]]: assert isinstance(start, (Point2, Unit)) assert isinstance(end, Point2) if isinstance(start, Point2): result = await self._execute( ...
Caution: returns 0 when path not found
356,790
def build_tree_parser(patterns): def output(): for pattern in patterns: yield (pattern.build_full_tree(), pattern.regex) return list(output())
This parser_type simply outputs an array of [(tree, regex)] for use in another language.
356,791
def create_dataset(self, name, x_img_size, y_img_size, z_img_size, x_vox_res, y_vox_res, z_vox_res, x_offset=0, y...
Creates a dataset. Arguments: name (str): Name of dataset x_img_size (int): max x coordinate of image size y_img_size (int): max y coordinate of image size z_img_size (int): max z coordinate of image size x_vox_res (float): x voxel resolution ...
356,792
def plot(self, normed=False, scale_errors_by=1.0, scale_histogram_by=1.0, plt=plt, errors=False, **kwargs): if not CAN_PLOT: raise ValueError("matplotlib did not import, so canlinestylenone.linestylesteps-mid') plt.plot(self.bin_centers, self.histogram, **kwargs)
Plots the histogram with Poisson (sqrt(n)) error bars - scale_errors_by multiplies the error bars by its argument - scale_histogram_by multiplies the histogram AND the error bars by its argument - plt thing to call .errorbar on (pylab, figure, axes, whatever the matplotlib guys come up wit...
356,793
def find_near_matches_substitutions_ngrams(subsequence, sequence, max_substitutions): _check_arguments(subsequence, sequence, max_substitutions) match_starts = set() matches = [] for match in _find_near_matches_substitutions_ngrams(subsequence, sequence, ...
search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the number of character substitutions must be less than max_substitutions * no deletions or insertions...
356,794
def current_version(self, object, relations_as_of=None, check_db=False): if object.version_end_date is None and not check_db: current = object else: current = self.current.filter(identity=object.identity).first() return self.adjust_version_as_of(current, relatio...
Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current version available. In this case the function returns None. ...
356,795
def get_pos(self, sector): if not self.sector_is_valid(sector): raise ByteNotInFile166("Sector %d out of range" % sector) pos = sector * self.sector_size + self.header_offset size = self.sector_size return pos, size
Get index (into the raw data of the disk image) of start of sector This base class method assumes the sectors are one after another, in order starting from the beginning of the raw data.
356,796
def close(self): if self.tabix_file and not self.tabix_file.closed: self.tabix_file.close() if self.stream: self.stream.close()
Close underlying stream
356,797
def __create_matcher(self, match_class, **keywds): matcher_args = keywds.copy() del matcher_args[] del matcher_args[] if in matcher_args: del matcher_args[] decl_matcher = decl_matcher = match_class(**matcher_args) if keywds[]: self._log...
implementation details
356,798
def focus_widget(self, checked=None, w=None): if w is None: return if w.isMinimized(): w.showNormal() else: w.show() w.activateWindow() w.setFocus()
Focus the given widget. Checked is ignored and only used as a slot for QAbstractButton.clicked. :param checked: The checked state of the button that was clicked :type checked: bool :param w: the widget to focus :type w: QtGui.QWidget :returns: None :raises: None
356,799
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList: _tag = tag.upper() return getElementsBy(start_node, lambda node: node.tagName == _tag)
Get child nodes which tag name is ``tag``.