Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
371,100
def get_results(cmd): try: return subprocess.check_output(cmd) except subprocess.CalledProcessError as e: return e.output
def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters
371,101
def download(self, filename=None): tmp_file, f_suffix = download_file(self.url) if not filename is None: shutil.move(tmp_file, filename) return filename else: return tmp_file
Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters ---------- filename : string, optional Optional name for the file on local disk. Returns ------- string Path to downloaded ...
371,102
def render_revalidation_failure(self, failed_step, form, **kwargs): self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step)
When a step fails, we have to redirect the user to the first failing step.
371,103
def __start_commoncrawl_extractor(warc_download_url, callback_on_article_extracted=None, valid_hosts=None, start_date=None, end_date=None, strict_date=True, reuse_previously_downloaded_files=True, local_download_dir_wa...
Starts a single CommonCrawlExtractor :param warc_download_url: :param callback_on_article_extracted: :param valid_hosts: :param start_date: :param end_date: :param strict_date: :param reuse_previously_downloaded_files: :param local_download_dir_warc: :param continue_after_error: ...
371,104
def enable_disable(self): if self.enabled: self.data[] = False else: self.data[] = True self.update()
Enable or disable this endpoint. If enabled, it will be disabled and vice versa. :return: None
371,105
def loadSignal(self, name, start=None, end=None): entry = self._getCacheEntry(name) if entry is not None: from analyser.common.signal import loadSignalFromWav return loadSignalFromWav(entry[], start=start, end=end) else: return None
Loads the named entry from the upload cache as a signal. :param name: the name. :param start: the time to start from in HH:mm:ss.SSS format :param end: the time to end at in HH:mm:ss.SSS format. :return: the signal if the named upload exists.
371,106
def generate_key_pair(size=2048, public_exponent=65537, as_string=True): private = rsa.generate_private_key( public_exponent=public_exponent, key_size=size, backend=default_backend() ) public = private.public_key() if not as_string: return private, public pem_p...
Generate a public/private key pair. :param size: Optional. Describes how many bits long the key should be, larger keys provide more security, currently 1024 and below are considered breakable, and 2048 or 4096 are reasonable default key sizes for new keys. Defaults to 2048. :param public_expone...
371,107
def compute_curl(self, vector_field): A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0) sum_edge_dot_A = numpy.einsum("ijk, ijk->j", self.half_edge_coords, A) z = numpy.cross(self.half_edge_coords[0], self.half_edge_coords[1]) ...
Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; see <https://en.wikipedia.org/wiki/Curl_(mathema...
371,108
def __add_annotation_tier(self, docgraph, body, annotation_layer): layer_cat = annotation_layer.split()[-1] temp_tier = self.E(, {: "TIE{}".format(self.tier_count), : layer_cat, : "t", : "[{}]".format(annotation_...
adds a span-based annotation layer as a <tier> to the Exmaralda <body>. Parameter --------- docgraph : DiscourseDocumentGraph the document graph from which the chains will be extracted body : etree._Element an etree representation of the <basic_body> element (and...
371,109
def pulse_magnitude(time, magnitude, start, repeat_time=0): t = time() small = 1e-6 if repeat_time <= small: if abs(t - start) < time.step(): return magnitude * time.step() else: return 0 else: if abs((t - start) % repeat_time) < time.step(): ...
Implements xmile's PULSE function PULSE: Generate a one-DT wide pulse at the given time Parameters: 2 or 3: (magnitude, first time[, interval]) Without interval or when interval = 0, the PULSE is generated only once Example: PULSE(20, 12, 5) generate...
371,110
def interactive(proto_dataset_uri): proto_dataset = dtoolcore.ProtoDataSet.from_uri( uri=proto_dataset_uri, config_path=CONFIG_PATH) readme_template = _get_readme_template() yaml = YAML() yaml.explicit_start = True yaml.indent(mapping=2, sequence=4, offset=2) descripti...
Interactive prompting to populate the readme.
371,111
def _process_infohash_list(infohash_list): if isinstance(infohash_list, list): data = {: .join([h.lower() for h in infohash_list])} else: data = {: infohash_list.lower()} return data
Method to convert the infohash_list to qBittorrent API friendly values. :param infohash_list: List of infohash.
371,112
def status(self): return self.repository._repo.status(self._ctx.p1().node(), self._ctx.node())
Returns modified, added, removed, deleted files for current changeset
371,113
def get_longest_target_alignment_coords_by_name(self,name): longest = -1 coord = None for line in [self._lines[x] for x in self._name_to_num[name]]: if line[] & 2304 == 0: return [line[],line[]] return None sys.stderr.write("ERROR: no primary alignment set in index\n") s...
For a name get the best alignment :return: [filebyte,innerbyte] describing the to distance the zipped block start, and the distance within the unzipped block :rtype: list
371,114
def resources(self): used_resources = self._used_resources() ret = collections.defaultdict(dict) for resource, total in six.iteritems(self._resources): ret[resource][] = total if resource in used_resources: ret[resource][] = used_resources[resourc...
get total resources and available ones
371,115
def angular_distance(first, second, bidirectional=True): lon1, lat1 = first lon2, lat2 = second lon1, lat1, lon2, lat2 = np.atleast_1d(lon1, lat1, lon2, lat2) xyz1 = sph2cart(lon1, lat1) xyz2 = sph2cart(lon2, lat2) dot = np.einsum(, xyz1, xyz2) angle = np.arccos(dot) ...
Calculate the angular distance between two linear features or elementwise angular distance between two sets of linear features. (Note: a linear feature in this context is a point on a stereonet represented by a single latitude and longitude.) Parameters ---------- first : (lon, lat) 2xN array-l...
371,116
def save(self, path_or_file, strict=True, fmt=): self.validate(strict=strict) with _open(path_or_file, mode=, fmt=fmt) as fdesc: json.dump(self.__json__, fdesc, indent=2)
Serialize annotation as a JSON formatted stream to file. Parameters ---------- path_or_file : str or file-like Path to save the JAMS object on disk OR An open file descriptor to write into strict : bool Force strict schema validation ...
371,117
def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None, allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None, allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None, mode=None, columnNameOfCorruptRecord=None, dateFormat=No...
Loads JSON files and returns the results as a :class:`DataFrame`. `JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default. For JSON (one record per file), set the ``multiLine`` parameter to ``true``. If the ``schema`` parameter is not specified, this function goe...
371,118
def to_dict(self): json_dict = {"apiKey": self.api_key, "userArn": self.user_arn, "cognitoAuthenticationType": self.cognito_authentication_type, "caller": self.caller, "userAgent": self.user_agent, ...
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON :return: dict representing the object
371,119
def button_change_send(self, time_boot_ms, last_change_ms, state, force_mavlink1=False): return self.send(self.button_change_encode(time_boot_ms, last_change_ms, state), force_mavlink1=force_mavlink1)
Report button state change time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) last_change_ms : Time of last change of button state (uint32_t) state : Bitmap state of buttons (uint8_t)
371,120
def isbase(path1, path2): _path1 = forcedir(abspath(path1)) _path2 = forcedir(abspath(path2)) return _path2.startswith(_path1)
Check if ``path1`` is a base of ``path2``. Arguments: path1 (str): A PyFilesytem path. path2 (str): A PyFilesytem path. Returns: bool: `True` if ``path2`` starts with ``path1`` Example: >>> isbase('foo/bar', 'foo/bar/baz/egg.txt') True
371,121
def multicore(function, cores, multiargs, **singleargs): tblib.pickling_support.install() if sys.version_info >= (3, 0): check = inspect.getfullargspec(function) varkw = check.varkw else: check = inspect.getargspec(function) varkw = check.keywords if n...
wrapper for multicore process execution Parameters ---------- function individual function to be applied to each process item cores: int the number of subprocesses started/CPUs used; this value is reduced in case the number of subprocesses is smaller multiargs: dict ...
371,122
def __check_label_image(label_image): encountered_indices = scipy.unique(label_image) expected_indices = scipy.arange(1, label_image.max() + 1) if not encountered_indices.size == expected_indices.size or \ not (encountered_indices == expected_indices).all(): raise AttributeError()
Check the label image for consistent labelling starting from 1.
371,123
def create_job(self, builder_job, wf_job=None, is_output=False ): copied = copy.deepcopy(builder_job) relativised_input_objecttemp = {} self._relativise_files(copied) def jdefault(o):...
Generate the new job object with RO specific relative paths.
371,124
def parse_url_or_log(url, encoding=): try: url_info = URLInfo.parse(url, encoding=encoding) except ValueError as error: _logger.warning(__( _(), url=wpull.string.printable_str(url), error=error)) else: return url_info
Parse and return a URLInfo. This function logs a warning if the URL cannot be parsed and returns None.
371,125
def queryset(self, request, queryset): if self.value(): try: section = SectionPage.objects.get(id=self.value()) return queryset.child_of(section).all() except (ObjectDoesNotExist, MultipleObjectsReturned): return None
Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`.
371,126
def __make_request(self, url, method, data, auth, cookies, headers, proxies, timeout, verify): request_by_method = getattr(requests, method) return request_by_method( url=url, data=data, auth=auth, cookies=cookies, headers=headers, ...
Execute a request with the given data. Args: url (str): The URL to call. method (str): The method (e.g. `get` or `post`). data (str): The data to call the URL with. auth (obj): The authentication class. cookies (obj): The cookie dict. head...
371,127
def solar_irradiation(latitude, longitude, Z, moment, surface_tilt, surface_azimuth, T=None, P=None, solar_constant=1366.1, atmos_refract=0.5667, albedo=0.25, linke_turbidity=None, extraradiation_method=, airmass_model=, ...
r'''Calculates the amount of solar radiation and radiation reflected back the atmosphere which hits a surface at a specified tilt, and facing a specified azimuth. This functions is a wrapper for the incredibly comprehensive `pvlib library <https://github.com/pvlib/pvlib-python>`_, and requir...
371,128
def setPositionLinkedTo(self, widgets): if type(widgets) in (list, set, tuple): new_widgets = list(widgets) else: new_widgets = [] widget = widgets while widget: widget.installEventFilter(self) new_widgets....
Sets the widget that this popup will be linked to for positional changes. :param widgets | <QWidget> || [<QWidget>, ..]
371,129
def run(command, parser, cl_args, unknown_args): Log.debug("Restart Args: %s", cl_args) container_id = cl_args[] if cl_args[] == config.SERVER_MODE: dict_extra_args = {"container_id": str(container_id)} return cli_helper.run_server(command, cl_args, "restart topology", extra_args=dict_extra_args) el...
:param command: :param parser: :param cl_args: :param unknown_args: :return:
371,130
def compute_cumsum( df, id_cols: List[str], reference_cols: List[str], value_cols: List[str], new_value_cols: List[str] = None, cols_to_keep: List[str] = None ): if cols_to_keep is None: cols_to_keep = [] if new_value_cols is None: new_value_cols = value_cols if...
Compute cumsum for a group of columns. --- ### Parameters *mandatory :* - `id_cols` (*list*): the columns id to create each group - `reference_cols` (*list*): the columns to order the cumsum - `value_cols` (*list*): the columns to cumsum *optional :* - `new_value_cols` (*list*): the ...
371,131
def on_cache_changed(self, direct, which=None): for what in [direct, which]: ind_id = self.id(what) _, cache_ids = self.cached_input_ids.get(ind_id, [None, []]) for cache_id in cache_ids: self.inputs_changed[cache_id] = True
A callback funtion, which sets local flags when the elements of some cached inputs change this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here.
371,132
def byte_number_string( number, thousandsSep=True, partition=False, base1024=True, appendBytes=True ): magsuffix = "" bytesuffix = "" if partition: magnitude = 0 if base1024: while number >= 1024: magnitude += 1 number = number >> 10 ...
Convert bytes into human-readable representation.
371,133
def extend_name(suffix): def dec(cls): name = .format(cls.__name__, suffix) setattr(cls, , name) return cls return dec
A factory for class decorators that modify the class name by appending some text to it. Example: @extend_name('_Foo') class Class: pass assert Class.__name__ == 'Class_Foo'
371,134
def _write_local_data_files(self, cursor): schema = list(map(lambda schema_tuple: schema_tuple[0].replace(, ), cursor.description)) file_no = 0 tmp_file_handle = NamedTemporaryFile(delete=True) tmp_file_handles = {self.filename.format(file_no): tmp_file_handle} for row ...
Takes a cursor, and writes results to a local file. :return: A dictionary where keys are filenames to be used as object names in GCS, and values are file handles to local files that contain the data for the GCS objects.
371,135
def fsqrt(q): if q == 0: return q, 1 if q < 0: raise ValueError( % q) a, b = isqrt(q.numerator) c, d = isqrt(q.denominator) return Fraction(a, c * d), b * d
given a non-negative fraction q, return a pair (a,b) such that q = a * a * b where b is a square-free integer. if q is a perfect square, a is its square root and b is one.
371,136
def get_page_objects_by_ext_type(context, object_type): try: objects = context[][][object_type] except KeyError: raise template.TemplateSyntaxError(.format(object_type)) return objects
**Arguments** ``object_type`` object type :return selected objects
371,137
def patch_traces( self, project_id, traces, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "patch_traces" not in self._inner_api_calls: self._inner_api_calls[ ...
Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you send matches that of an existing trace, any fields in the existing trace and its spans are overwritten by the provided values, and any new fields provided are merged with the existing trace data. If t...
371,138
def check_lengths(*arrays): lengths = [len(array) for array in arrays] if len(np.unique(lengths)) > 1: raise ValueError(.format(lengths))
tool to ensure input and output data have the same number of samples Parameters ---------- *arrays : iterable of arrays to be checked Returns ------- None
371,139
def apply_update(self, doc, update_spec): if not in update_spec and not in update_spec: update_spec[] = doc[self.unique_key] return update_spec for to_set in update_spec.get("$set", []): value = update_spec[][...
Override DocManagerBase.apply_update to have flat documents.
371,140
def register(cls, use_admin=True): with app.app_context(): if getattr(current_app, , None) is None: current_app.class_references = {} if isinstance(cls, (list, tuple)): for entry in cls: register_internal_data(entry) entry.use_admin = use_...
Register with the API a :class:`sandman.model.Model` class and associated endpoint. :param cls: User-defined class derived from :class:`sandman.model.Model` to be registered with the endpoint returned by :func:`endpoint()` :type cls: :class:`sandman.model.Model` or tuple
371,141
def get_owner(self, default=True): uid, gid = self.owner if not uid and default: uid = os.getuid() if not gid and default: gid = os.getgid() return uid, gid
Return (User ID, Group ID) tuple :param bool default: Whether to return default if not set. :rtype: tuple[int, int]
371,142
def is_email(): email = ( ur ur ur ur ur ur ur ur ) regex = re.compile(email, re.IGNORECASE | re.UNICODE) def validate(value): if not regex.match(value): return e("{} is...
Validates that a fields value is a valid email address.
371,143
def update_user(self, user_id, **kwargs): properties = {} for attr, value in kwargs.items(): properties[self._underscore_to_camelcase(attr)] = value data = { "properties": properties } response = self._perform_request( url= % user_i...
Updates a user. :param user_id: The unique ID of the user. :type user_id: ``str``
371,144
def build_tree(self, *args, **kwargs): assert len(self) > 3 algorithm = kwargs.pop(kwargs, None) if algorithm is None: algorithm = if algorithm is : return self.build_tree_raxml(*args, **kwargs) if algorithm is : return self.build_tree_fast...
Dispatch a tree build call. Note that you need at least four taxa to express some evolutionary history on an unrooted tree.
371,145
def mqtt_connected(func): @asyncio.coroutine @wraps(func) def wrapper(self, *args, **kwargs): if not self._connected_state.is_set(): base_logger.warning("Client not connected, waiting for it") _, pending = yield from asyncio.wait([self._connected_state.wait(), self._no_m...
MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result
371,146
def is_dot(ip): octets = str(ip).split() if len(octets) != 4: return False for i in octets: try: val = int(i) except ValueError: return False if val > 255 or val < 0: return False return True
Return true if the IP address is in dotted decimal notation.
371,147
def export(self, file_path=None, export_format=None): with io.open(file_path, mode=, encoding="utf-8") as export_file: if export_format == : import yaml yaml.safe_dump(self.to_dict(), export_file, default_flow_style=False) elif export_format == : ...
Write the users to a file.
371,148
def _plot_histogram(series, bins=10, figsize=(6, 4), facecolor=): if base.get_vartype(series) == base.TYPE_DATE: fig = plt.figure(figsize=figsize) plot = fig.add_subplot(111) plot.set_ylabel() try: plot.hist(series.dropna().values, facecolor=facecolor, bins=...
Plot an histogram from the data and return the AxesSubplot object. Parameters ---------- series : Series The data to plot figsize : tuple The size of the figure (width, height) in inches, default (6,4) facecolor : str The color code. Returns ------- matplotlib.A...
371,149
def save_performance(db, job_id, records): rows = [(job_id, rec[], rec[], rec[], int(rec[])) for rec in records] db.insert(, .split(), rows)
Save in the database the performance information about the given job. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param records: a list of performance records
371,150
def needs_sync(self): if self.lastforce is None: self.lastforce = time.time() return time.time() - self.lastforce >= self.forceipchangedetection_sleep
Check if enough time has elapsed to perform a sync(). A call to sync() should be performed every now and then, no matter what has_state_changed() says. This is really just a safety thing to enforce consistency in case the state gets messed up. :rtype: boolean
371,151
def unique_cpx_roots(rlist,tol = 0.001): uniq = [rlist[0]] mult = [1] for k in range(1,len(rlist)): N_uniq = len(uniq) for m in range(N_uniq): if abs(rlist[k]-uniq[m]) <= tol: mult[m] += 1 uniq[m] = (uniq[m]*(mult[m]-1) + rlist[k])/fl...
The average of the root values is used when multiplicity is greater than one. Mark Wickert October 2016
371,152
def xdg_config_dir(): xdg_config = os.getenv(, os.path.expanduser()) xdg_config_directory = os.path.join(xdg_config, ) return xdg_config_directory
Check xdg locations for config files
371,153
def set_generator_training_nb(self, number): self.samples_per_epoch = number diff_to_batch = number % self.get_batch_size() if diff_to_batch > 0: self.samples_per_epoch += self.get_batch_size() - diff_to_batch
sets self.samples_per_epoch which is used in model.fit if input is a generator :param number: :return:
371,154
def get_input(prompt, check, *, redo_prompt=None, repeat_prompt=False): if isinstance(check, str): check = (check,) to_join = [] for item in check: if item: to_join.append(str(item)) else: to_join.append("") prompt += " [{}]: ".format(.join(to_join)...
Ask the user to input something on the terminal level, check their response and ask again if they didn't answer correctly
371,155
def gauge(self, name, value, rate=1): if self._should_send_metric(name, rate): if not is_numeric(value): value = float(value) self._request( Gauge( self._create_metric_name_for_request(name), value...
Send a Gauge metric with the specified value
371,156
def addElement(self,etype=,corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name=): lastelm = self.elements[-1][1] lastnode = self.nodes[-1][0] elm = [etype,lastelm+1] for i in range(old_div(len(corners),3)): ...
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
371,157
def first_produced_mesh(self): for instruction in self.instructions: if instruction.produces_meshes(): return instruction.first_produced_mesh raise IndexError("{} produces no meshes".format(self))
The first produced mesh. :return: the first produced mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is produced .. seealso:: :attr:`number_of_produced_meshes`
371,158
def pinyin_to_ipa(s): return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa, remove_apostrophes=True, separate_syllables=True)
Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed.
371,159
def pre_release(self): label = self.version_info.get(, None) pre = self.version_info.get(, None) return True if (label is not None and pre is not None) else False
Return true if version is a pre-release.
371,160
def unsubscribe(self, coro): if coro in self._notify: self._notify.remove(coro) return True return False
Unsubscribe from status updates from the Opentherm Gateway. Can only be used after connect() @coro is a coroutine which has been subscribed with subscribe() earlier. Return True on success, false if not connected or subscribed.
371,161
def send_start(remote, code, device=None, address=None): args = [, remote, code] _call(args, device, address)
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output t...
371,162
def p_parens_expr(p): p[0] = node.expr(op="parens", args=node.expr_list([p[2]]))
expr : LPAREN expr RPAREN
371,163
def get_number_of_partitions_for(self, ar): uid = api.get_uid(ar) num = self.request.get("primary", {}).get(uid) if num is None: template = ar.getTemplate() if template: num = len(template.getPartitions()) else: ...
Return the number of selected partitions
371,164
def _sort(values, axis=-1, direction=, stable=False, name=None): if direction == : pass elif direction == : values = np.negative(values) else: raise ValueError(.format(direction)) result = np.sort(values, axis, kind= if stable else ) if direction == : return np.negative(result) return r...
Numpy implementation of `tf.sort`.
371,165
def rescan(self): if not self.attached: return dprint(5, "starting rescan") newstuff = {}; self.last_scan_timestamp = time.time() for path, watcher in list(self.watchers.items()): newfiles = watcher.newFiles() ...
Checks files and directories on watchlist for updates, rescans them for new data products. If any are found, returns them. Skips those in directories whose watchingState is set to Purr.UNWATCHED.
371,166
def inspect_image(self, image_name, image_tag=): title = % self.__class__.__name__ input_fields = { : image_name, : image_tag } for key, value in input_fields.items(): if value: object_title = % (t...
a method to retrieve the settings of an image :param image_name: string with name or id of image :param image_tag: [optional] string with tag associated with image :return: dictionary of settings of image { TOO MANY TO LIST }
371,167
def _ceil(self, address): return (((address - 1) + self.page_size) & ~self.page_mask) & self.memory_mask
Returns the smallest page boundary value not less than the address. :rtype: int :param address: the address to calculate its ceil. :return: the ceil of C{address}.
371,168
def merge_with_master_config(self, config, defaults={}, delete_orphan_fields=False) -> dict: if isinstance(config, str): import json config = json.loads(config) properties = self.all_properties() config[] = config.get(, dict()) fields = config[] ...
Merge current ontology with input master config. :param config: master config, should be str or dict :param defaults: a dict that sets default color and icon :param delete_orphan_fields: if a property doesn't exist in the ontology then delete it :return: merged master config in dict
371,169
def new_workspace(self, name=None, layout=None, workspace_id=None, index=None) -> WorkspaceLayout.WorkspaceLayout: workspace = WorkspaceLayout.WorkspaceLayout() self.document_model.insert_workspace(index if index is not None else len(self.document_model.workspaces), workspace) d = creat...
Create a new workspace, insert into document_model, and return it.
371,170
def decode_list(input_props, name): val_str = input_props.get(name, None) if val_str: return val_str.split(" ") return []
Decodes a space-separated list
371,171
def shadowUpdate(self, srcJSONPayload, srcCallback, srcTimeout): self._basicJSONParserHandler.setString(srcJSONPayload) if self._basicJSONParserHandler.validateJSON(): with self._dataStructureLock: currentToken = self._tokenHandler.getNextTo...
**Description** Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Response will be ...
371,172
def secret_file(filename): filestat = os.stat(abspath(filename)) if stat.S_ISREG(filestat.st_mode) == 0 and \ stat.S_ISLNK(filestat.st_mode) == 0: e_msg = "Secret file %s must be a real file or symlink" % filename raise aomi.exceptions.AomiFile(e_msg) if platform.system() != "Wi...
Will check the permissions of things which really should be secret files
371,173
def compile_loaderplugin_entry(self, spec, entry): modname, source, target, modpath = entry handler = spec[CALMJS_LOADERPLUGIN_REGISTRY].get(modname) if handler: return handler(self, spec, modname, source, target, modpath) logger.warning( "no loaderplugi...
Generic loader plugin entry handler. The default implementation assumes that everything up to the first '!' symbol resolves to some known loader plugin within the registry. The registry instance responsible for the resolution of the loader plugin handlers must be available in t...
371,174
def define_magic(self, name, func): meth = types.MethodType(func, self.user_magics) setattr(self.user_magics, name, meth) record_magic(self.magics, , name, meth)
[Deprecated] Expose own function as magic function for IPython. Example:: def foo_impl(self, parameter_s=''): 'My very own magic!. (Use docstrings, IPython reads them).' print 'Magic function. Passed parameter is between < >:' print '<%s>' % paramete...
371,175
def hicup_filtering_chart(self): keys = OrderedDict() keys[] = { : , : } keys[] = { : , : } keys[] = { : , : } keys[] = { : , : } keys[] = { : , : } keys[] = { : , : } keys[] = { : , : ...
Generate the HiCUP filtering plot
371,176
def vhost_exists(name, runas=None): * if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() return name in list_vhosts(runas=runas)
Return whether the vhost exists based on rabbitmqctl list_vhosts. CLI Example: .. code-block:: bash salt '*' rabbitmq.vhost_exists rabbit_host
371,177
def validate(self): r try: with requests.Session() as session: result = session.get() result = session.post( , data={: self.username, : self.password} ) result_string = re...
r"""Validate user credentials. Returns ------- bool Examples -------- Validate credentials. >>> from srpenergy.client import SrpEnergyClient >>> >>> accountid = 'your account id' >>> username = 'your username' >>> p...
371,178
def clear_bucket_props(self, bucket): if not self.pb_clear_bucket_props(): return False msg_code = riak.pb.messages.MSG_CODE_RESET_BUCKET_REQ codec = self._get_codec(msg_code) msg = codec.encode_clear_bucket_props(bucket) self._request(msg, codec) ret...
Clear bucket properties, resetting them to their defaults
371,179
def close(self): self.alive = False self.rxThread.join() self.serial.close()
Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port
371,180
def fastaParseSgd(header): rePattern = ID, name, description = re.match(rePattern, header).groups() info = {:ID, :name, :description} return info
Custom parser for fasta headers in the SGD format, see www.yeastgenome.org. :param header: str, protein entry header from a fasta file :returns: dict, parsed header
371,181
def import_parms(self, args): for key, val in args.items(): self.set_parm(key, val)
Import external dict to internal dict
371,182
def as_unordered(self, inplace=False): inplace = validate_bool_kwarg(inplace, ) return self.set_ordered(False, inplace=inplace)
Set the Categorical to be unordered. Parameters ---------- inplace : bool, default False Whether or not to set the ordered attribute in-place or return a copy of this categorical with ordered set to False.
371,183
def _cast_to_type(self, value): try: return float(value) except (ValueError, TypeError): self.fail(, value=value)
Convert the value to a float and raise error on failures
371,184
def resize(self, height, width, **kwargs): self.client.exec_resize(self.exec_id, height=height, width=width)
resize pty of an execed process
371,185
def delete(block_id): _url = get_root_url() LOG.debug(, block_id) try: DB.delete_sched_block_instance(block_id) response = dict(message=.format(block_id)) response[] = { : .format(_url) } return response, HTTPStatus.OK except RuntimeError as error...
Scheduling block detail resource.
371,186
def has_key(self, key): k = self._lowerOrReturn(key) return k in self.data
Case insensitive test whether 'key' exists.
371,187
def isASLREnabled(self): return self.ntHeaders.optionalHeader.dllCharacteristics.value & consts.IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE == consts.IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE
Determines if the current L{PE} instance has the DYNAMICBASE (Use address space layout randomization) flag enabled. @see: U{http://msdn.microsoft.com/en-us/library/bb384887.aspx} @rtype: bool @return: Returns C{True} if the current L{PE} instance has the DYNAMICBASE flag enabled. Otherwise, ret...
371,188
def _cluster_hits(hits, clusters, assigned_hit_array, cluster_hit_indices, column_cluster_distance, row_cluster_distance, frame_cluster_distance, min_hit_charge, max_hit_charge, ignore_same_hits, noisy_pixels, disabled_pixels): total_hits = hits.shape[0] if total_hits == 0: return 0 max_clust...
Main precompiled function that loopes over the hits and clusters them
371,189
def phase_by_transmission(g, window_size, copy=True): g = np.asarray(g, dtype=) g = GenotypeArray(g, copy=copy) g._values = memoryview_safe(g.values) check_ploidy(g.ploidy, 2) check_min_samples(g.n_samples, 3) is_phased = _opt_phase_progeny_by_transmission(g.values) g.is_pha...
Phase genotypes in a trio or cross where possible using Mendelian transmission. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, 2) Genotype array, with parents as first two columns and progeny as remaining columns. window_size : int Number of previou...
371,190
def _bld_pab_generic(self, funcname, **kwargs): margs = {: pab, : kwargs} setattr(self, funcname, margs)
implements a generic version of an attribute based pandas function
371,191
def apply_noise(data, noise): if noise >= 1: noise = noise/100. for i in range(data.nRows()): ones = data.rowNonZeros(i)[0] replace_indices = numpy.random.choice(ones, size = int(len(ones)*noise), replace = False) for index in replace_indices: data[i, index] = 0 new_indices = ...
Applies noise to a sparse matrix. Noise can be an integer between 0 and 100, indicating the percentage of ones in the original input to move, or a float in [0, 1), indicating the same thing. The input matrix is modified in-place, and nothing is returned. This operation does not affect the sparsity of the matri...
371,192
def groups_dynamic(self): return sa.orm.relationship( "Group", secondary="users_groups", lazy="dynamic", passive_deletes=True, passive_updates=True, )
returns dynamic relationship for groups - allowing for filtering of data
371,193
def _unpack_tableswitch(bc, offset): jump = (offset % 4) if jump: offset += (4 - jump) (default, low, high), offset = _unpack(_struct_iii, bc, offset) joffs = list() for _index in range((high - low) + 1): j, offset = _unpack(_struct_i, bc, offset) joffs.append(j) ...
function for unpacking the tableswitch op arguments
371,194
def __search_iterable(self, obj, item, parent="root", parents_ids=frozenset({})): for i, thing in enumerate(obj): new_parent = "%s[%s]" % (parent, i) if self.__skip_this(thin...
Search iterables except dictionaries, sets and strings.
371,195
def identify_sep(filepath): ext = os.path.splitext(filepath)[1].lower() allowed_exts = [, , ] assert ext in [, ], "Unexpected file extension {}. \ Supported extensions {}\n filename: {}".format( ext, allowed_exts, os.path.basename(...
Identifies the separator of data in a filepath. It reads the first line of the file and counts supported separators. Currently supported separators: ['|', ';', ',','\t',':']
371,196
def Nu_x(self, L, theta, Ts, **statef): Tf = statef[] thetar = radians(theta) if self._isgas: self.Tr = Ts - 0.38 * (Ts - Tf) beta = self._fluid.beta(T=Tf) else: self.Tr = Ts - 0.5 * (Ts - Tf) beta = self._fluid.beta(T=self.Tr)...
Calculate the local Nusselt number. :param L: [m] characteristic length of the heat transfer surface :param theta: [°] angle of the surface with the vertical :param Ts: [K] heat transfer surface temperature :param Tf: [K] bulk fluid temperature :returns: float
371,197
def get_freq_map_and_normalizations(self, frequency_list, upper_freq_formula): self.frequency_map = {} self.normalization_map = {} self.upper_freq_formula = upper_freq_formula frequency_list.sort() for idx, frequency in e...
If using the --vary-fupper capability we need to store the mapping between index and frequencies in the list. We also precalculate the normalization factor at every frequency, which is used when estimating overlaps to account for abrupt changes in termination frequency. Parameters ...
371,198
def _oauth_request_parameters(self, url, access_token, parameters={}, method="GET"): consumer_token = self._oauth_consumer_token() base_args = dict( oauth_consumer_key=consumer_token["key"], oauth_token=access_token["key"], o...
Returns the OAuth parameters as a dict for the given request. parameters should include all POST arguments and query string arguments that will be sent with the request.
371,199
def unicode_to_bytes(s, encoding=, errors=): return s if isinstance(s, str) else s.encode(encoding, errors)
Helper to convert unicode strings to bytes for data that needs to be written to on output stream (i.e. terminal) For Python 3 this should be called str_to_bytes :param str s: string to encode :param str encoding: utf-8 by default :param str errors: what to do when encoding fails :return: byte s...