Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,700
def add_unknown_members(self, members): if not isinstance(members, list): members = [members] if not hasattr(self, ): self.unknown_members = members else: self.unknown_members.extend(members)
Add a new member to the unknown members list :param member: member name :type member: str :return: None
361,701
def DownloadPqlResultToList(self, pql_query, values=None): results = [] self._PageThroughPqlSet(pql_query, results.append, values) return results
Downloads the results of a PQL query to a list. Args: pql_query: str a statement filter to apply (the query should not include the limit or the offset) [optional] values: A dict of python objects or a list of raw SOAP values to bind to the pql_query. Returns: ...
361,702
def extract_build(self, path=, tests=None, full_symbols=False): if self._target == : self.extract_zip(, path=os.path.join(path)) else: if self._platform.system == : self.extract_tar(, path) elif self._platform.system == : self....
Download and extract the build and requested extra artifacts @type path: @param path: @type tests: @param tests: @type full_symbols: @param full_symbols:
361,703
def write_nochr_reads(in_file, out_file, config): if not file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: samtools = config_utils.get_program("samtools", config) cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}" do.run(cmd.format...
Write a BAM file of reads that are not mapped on a reference chromosome. This is useful for maintaining non-mapped reads in parallel processes that split processing by chromosome.
361,704
def rsa_eq(key1, key2): pn1 = key1.public_numbers() pn2 = key2.public_numbers() if pn1 == pn2: return True else: return False
Only works for RSAPublic Keys :param key1: :param key2: :return:
361,705
def process_summary(summaryfile, **kwargs): logging.info("Nanoget: Collecting metrics from summary file {} for {} sequencing".format( summaryfile, kwargs["readtype"])) ut.check_existance(summaryfile) if kwargs["readtype"] == "1D": cols = ["read_id", "run_id", "channel", "start_time", "d...
Extracting information from an albacore summary file. Only reads which have a >0 length are returned. The fields below may or may not exist, depending on the type of sequencing performed. Fields 1-14 are for 1D sequencing. Fields 1-23 for 2D sequencing. Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequ...
361,706
def route_filter_get(name, resource_group, **kwargs): expand = kwargs.get() netconn = __utils__[](, **kwargs) try: route_filter = netconn.route_filters.get( route_filter_name=name, resource_group_name=resource_group, expand=expand ) result =...
.. versionadded:: 2019.2.0 Get details about a specific route filter. :param name: The name of the route table to query. :param resource_group: The resource group name assigned to the route filter. CLI Example: .. code-block:: bash salt-call azurearm_network.route_filter_get te...
361,707
def descendants(self, line_data): try: start = line_data[] except TypeError: start = self.lines[line_data][] visited_set, visited_list, queue = set(), [], [start] while queue: node = queue.pop(0) if node not in visited_set...
BFS graph algorithm :param line_data: line_data(dict) with line_data['line_index'] or line_index(int) :return: list of line_data(dict)
361,708
def set_video_pos(self, x1, y1, x2, y2): position = "%s %s %s %s" % (str(x1),str(y1),str(x2),str(y2)) self._player_interface.VideoPos(ObjectPath(), String(position))
Set the video position on the screen Args: x1 (int): Top left x coordinate (px) y1 (int): Top left y coordinate (px) x2 (int): Bottom right x coordinate (px) y2 (int): Bottom right y coordinate (px)
361,709
def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2): lat1 = math.radians(degree_lat1) lng1 = math.radians(degree_lng1) lat2 = math.radians(degree_lat2) lng2 = math.radians(degree_lng2) dlat = math.sin(0.5 * (lat2 - lat1)) dlng = math.sin(0.5 * (lng2 - lng1)) x = dlat * dla...
Compute approximate distance between two points in meters. Assumes the Earth is a sphere.
361,710
def fetchable_partitions(self): fetchable = set() for partition, state in six.iteritems(self.assignment): if state.is_fetchable(): fetchable.add(partition) return fetchable
Return set of TopicPartitions that should be Fetched.
361,711
def query_file(self, file_sha, verbose=False): if len(file_sha) not in [64, 40]: print(.format(file_sha)) return {: file_sha, : True} return self._query(, file_sha, verbose)
Query the VirusTotal Service Args: file_sha (str): The file sha1 or sha256 hash url (str): The domain/url to be queried (default=None)
361,712
def add_descendants(self, node, updateset=None): "auxiliary function: add all descendants of node to someset" someset = set() startnode = self.tab[node] defout = startnode.default[0] if defout is not None: someset.add(defout) for kwd, matchnode in startnode.n...
auxiliary function: add all descendants of node to someset
361,713
def write_files(template, destination=): os.makedirs(destination) for key, value in template.items(): with open(os.path.join(destination, key), ) as f: f.write(replace_whitespace(value, insert=False))
For a dict, write each value to destination/key
361,714
def _create_batch_runner_action(self): icon = resources_path(, , ) self.action_batch_runner = QAction( QIcon(icon), self.tr(), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr( )) self.action_batch_runner.setWhatsThis(sel...
Create action for batch runner dialog.
361,715
def _cfg_exists(self, cfg_str): ios_cfg = self._get_running_config() parse = HTParser(ios_cfg) cfg_raw = parse.find_lines("^" + cfg_str) LOG.debug("_cfg_exists(): Found lines %s", cfg_raw) return len(cfg_raw) > 0
Check a partial config string exists in the running config. :param cfg_str: config string to check :return : True or False
361,716
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): paths = tf.gfile.Glob("%s/*.jpg" % tmp_dir) if not paths: raise ValueError("Search of tmp_dir (%s) " % tmp_dir, "for subimage paths yielded an empty list, ", "can't proceed with returning training/eva...
Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for training (true) or eval (false). training_fraction: float, the ...
361,717
def set_servers(self, node_couplets): node_couplets_s = set(node_couplets) if node_couplets_s != self.__node_couplets_s: _logger.info("Servers have changed. NEW: %s REMOVED: %s", node_couplets_s - self.__node_couplets_s, self.__n...
Set the current collection of servers. The entries are 2-tuples of contexts and nodes.
361,718
def run(self): indent = int(self.tcex.playbook.read(self.args.indent)) json_data = self.tcex.playbook.read(self.args.json_data) json_data_type = self.tcex.playbook.variable_type(self.args.json_data) if json_data_type in []: json_data = js...
Run the App main logic. This method should contain the core logic of the App.
361,719
def _map_val2color(val, vmin, vmax, colorscale=None): colorscale = colorscale or colorscale_default if vmin >= vmax: raise ValueError("vmin should be < vmax") scale = list(map(float, np.array(colorscale)[:, 0])) colors = np.array(colorscale)[:, 1] colors_01 = ( np.array(list(...
Maps a value val in [vmin, vmax] to the corresponding color in the colorscale returns the rgb color code of that color
361,720
def _wrap_field(field): class WrappedField(field): def output(self, key, obj): value = _fields.get_value(key if self.attribute is None else self.attribute, obj) return None if value is None else self.format(value) return WrappedField
Improve Flask-RESTFul's original field type
361,721
def clean_old_jobs(): s return data for old jobs. Normally, hset are saved with a TTL, and will eventually get cleaned by redis.But for jobs with some very late minion return, the corresponding hsetll do manually cleaning here. ret:*load:*ret:load:clean old jobs: %s', to_remove)
Clean out minions's return data for old jobs. Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually get cleaned by redis.But for jobs with some very late minion return, the corresponding hset's TTL will be refreshed to a too late timestamp, we'll do manually cleaning here.
361,722
def __multiscale_gc_hi2lo_run(self): self.__msgc_step0_init() hard_constraints = self.__msgc_step12_low_resolution_segmentation() seg = self.__msgc_step3_discontinuity_localization() nlinks, unariesalt2, msinds = self.__msgc_step45678_hi2lo_construc...
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph. In first step is performed normal GC on low resolution data Second step construct finer grid on edges of segmentation from first step. There is no option for use without `use_boundary_penalties`
361,723
def aug_sysargv(cmdstr): import shlex argv = shlex.split(cmdstr) sys.argv.extend(argv)
DEBUG FUNC modify argv to look like you ran a command
361,724
def get_event_triggers(self): events = {} nvrflag = False event_xml = [] url = % self.root_url try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) if response.status_code == requests.codes.not_found: ...
Returns dict of supported events. Key = Event Type List = Channels that have that event activated
361,725
def Delete(self): return(clc.v2.Requests(clc.v2.API.Call(, % (self.alias,self.id),session=self.session),alias=self.alias,session=self.session))
Delete server. https://t3n.zendesk.com/entries/59220824-Delete-Server >>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete() 0
361,726
def update_travis_deploy_password(encrypted_password): config = load_yaml_config(TRAVIS_CONFIG_FILE) config["deploy"]["password"] = dict(secure=encrypted_password) save_yaml_config(TRAVIS_CONFIG_FILE, config) line = ( " " each time you run travis_pypi_setup.py\n" ) prepen...
Update the deploy section of the .travis.yml file to use the given encrypted password.
361,727
def vpn_gateways(self): api_version = self._get_api_version() if api_version == : from .v2018_04_01.operations import VpnGatewaysOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return Oper...
Instance depends on the API version: * 2018-04-01: :class:`VpnGatewaysOperations<azure.mgmt.network.v2018_04_01.operations.VpnGatewaysOperations>`
361,728
def start_poll(args): if args.type == : return "We doncorectrlchanadminrestrictpoll'): poll.accepted = 1 return "Poll else: args.send("Poll submitted for approval.", target=args.nick) args.send("New Poll: return ""
Starts a poll.
361,729
def construct_formset(self): formset = super(InlineFormSetFactory, self).construct_formset() formset.model = self.inline_model return formset
Overrides construct_formset to attach the model class as an attribute of the returned formset instance.
361,730
def _expand_group_by_fields(cls, model, fields): res = [] related = {} for field_name in fields: if in field_name: related_model = model_field.related_model res.extend(.format(...
Expand FK fields into all related object's fields to avoid future lookups. :param fields: fields to "group by" :return: expanded fields
361,731
def calculate_similar_artists(output_filename, model_name="als"): artists, users, plays = get_lastfm() model = get_model(model_name) start = time.time() logging.debug("calculating top artists") user_count = np.ediff1d(plays.indptr) to_generate = sorted(np.arange(len(artis...
generates a list of similar artists in lastfm by utiliizing the 'similar_items' api of the models
361,732
def fail(p_queue, host=None): if host is not None: return _path(_c.FSQ_FAIL, root=_path(host, root=hosts(p_queue))) return _path(p_queue, _c.FSQ_FAIL)
Construct a path to the fail dir for a queue
361,733
def _find_navigation_coefs(self): time = np.datetime64(self.prologue[][][]) intervals_tstart = self.prologue[][][][][0].astype( ) intervals_tend = self.prologue[][][][][0].astype( ) try: return np.where(np.logical_and(time >= interval...
Find navigation coefficients for the current time The navigation Chebyshev coefficients are only valid for a certain time interval. The header entry SatelliteStatus/Orbit/OrbitPolynomial contains multiple coefficients for multiple time intervals. Find the coefficients which are valid for the no...
361,734
def _wrapped_unsigned_mul(a, b): if a.bits != b.bits: logger.warning("Signed mul: two parameters have different bit length") bits = max(a.bits, b.bits) lb = a.lower_bound * b.lower_bound ub = a.upper_bound * b.upper_bound uninit_flag = a.uninitialized | b.un...
Perform wrapped unsigned multiplication on two StridedIntervals. :param a: The first operand (StridedInterval) :param b: The second operand (StridedInterval) :return: The multiplication result
361,735
def axes_grid(n, sharex=False, sharey=False, subplot_kw=None, **fig_kw): r = np.floor(np.sqrt(n)) r, c = int(r), int(np.ceil(n / r)) fig, axes = plt.subplots(nrows=r, ncols=c, figsize=(c*4, r*4), squeeze=False, sharex=sharex, sharey=sharey, subplot_kw=subpl...
Finds a reasonable arrangement of n axes. Returns (fig, axes) tuple. For keyword arguments descriptions, see matplotlib.pyplot.subplots
361,736
def _validate_filter_fields(self, filter_by): for filter_field in filter_by: if ( filter_field not in self.RESPONSE_FIELD_MAP or not self.RESPONSE_FIELD_MAP[filter_field].is_filter ): raise InvalidFilterFieldException( ...
:param filter_by: dict :raises: pybomb.exceptions.InvalidFilterFieldException
361,737
def _use_memcache(self, key, options=None): flag = ContextOptions.use_memcache(options) if flag is None: flag = self._memcache_policy(key) if flag is None: flag = ContextOptions.use_memcache(self._conn.config) if flag is None: flag = True return flag
Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached in memcache, False otherwise.
361,738
def ln_norm(x, mu, sigma=1.0): return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))
Natural log of scipy norm function truncated at zero
361,739
def friction_plate_Martin_1999(Re, plate_enlargement_factor): r phi = plate_enlargement_factor if Re < 2000.: f0 = 16./Re f1 = 149./Re + 0.9625 else: f0 = (1.56*log(Re) - 3.0)**-2 f1 = 9.75*Re**-0.289 rhs = cos(phi)*(0.045*tan(phi) + 0.09*sin(phi) + f0/c...
r'''Calculates Darcy friction factor for single-phase flow in a Chevron-style plate heat exchanger according to [1]_. .. math:: \frac{1}{\sqrt{f_f}} = \frac{\cos \phi}{\sqrt{0.045\tan\phi + 0.09\sin\phi + f_0/\cos(\phi)}} + \frac{1-\cos\phi}{\sqrt{3.8f_1}} .. math:: f...
361,740
def _find_primary_without_dot_start(self, offset): last_atom = offset offset = self._find_last_non_space_char(last_atom) while offset > 0 and self.code[offset] in : last_atom = self._find_parens_start(offset) offset = self._find_last_non_space_char(last_atom - 1)...
It tries to find the undotted primary start It is different from `self._get_atom_start()` in that it follows function calls, too; such as in ``f(x)``.
361,741
def _getStateAnomalyVector(self, state): vector = numpy.zeros(self._anomalyVectorLength) vector[state.anomalyVector] = 1 return vector
Returns a state's anomaly vertor converting it from spare to dense
361,742
def prepare_fields(fields): def process_item(value): if not isinstance(value, NUMERIC_TYPES): if isinstance(value, six.string_types): return force_text(value) else: if isinstance(value, dict): return prepare_fi...
Возвращает новый словарь с данными, подготовленными для сериализации в JSON.
361,743
def stop(self): super(Multi, self).stop() self.monitor_thread.join() logging.info("Multi-plugin health monitor: Stopping plugins") for p in self.plugins: p.stop() logging.info("Multi-plugin health monitor: Stopped")
Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop.
361,744
def description(self) -> str: return .format(self, self.context.module)
Test name in nose output (intended to be overridden).
361,745
def find_motif34(m, n=None): from scipy import io import os fname = os.path.join(os.path.dirname(__file__), motiflib) z = (0,) if n == 3: mot = io.loadmat(fname) m3 = mot[] id3 = mot[].squeeze() ix, = np.where(id3 == m) M = np.zeros((3, 3, len(ix))) ...
This function returns all motif isomorphs for a given motif id and class (3 or 4). The function also returns the motif id for a given motif matrix 1. Input: Motif_id, e.g. 1 to 13, if class is 3 Motif_class, number of nodes, 3 or 4. Output: Motif_matrices, ...
361,746
def delete_namespaced_pod_template(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_namespaced_pod_template_with_http_info(name, namespace, **kwargs) else: (data) = self.delete_namespaced_pod_template_with_http_info(name, ...
delete_namespaced_pod_template # noqa: E501 delete a PodTemplate # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_pod_template(name, namespace, async_req=True) ...
361,747
def ns(symbol): if symbol.type and symbol.type.is_primitive: return return .format(.join(symbol.module.name_parts))
generates a namespace x::y::z statement from a symbol
361,748
def _list_images(self, root): self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, 20, 22] skip_sub_idx = [21] if self._mode == : sub_idx = [ + str(i) for i in range(1, 35) \ if i not in valid_unseen_sub_idx + skip_sub...
Description : generate list for lip images
361,749
def task_postponed(self): tracker = self.task().tracker_storage() if tracker is not None and self.track_wait() is True: details = self.task().event_details(WTrackerEvents.wait) tracker.register_wait(self.task(), event_details=details) WScheduleRecord.task_postponed(self)
Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed` method do :return: None
361,750
def clone(self, **kwargs): cloneValueFlag = kwargs.pop(, False) initializers = self.readOnly.copy() initializers.update(kwargs) clone = self.__class__(**initializers) if cloneValueFlag: self._cloneComponentValues(clone, cloneValueFlag) return clon...
Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `se...
361,751
def gen_weights(self, f_target): x_track = self.cs.rollout() psi_track = self.gen_psi(x_track) for d in range(self.dmps): for b in range(self.bfs): self.w[d,b] = np.dot(psi_track[:,b], f_target[:,d]) / \ (np...
Generate a set of weights over the basis functions such that the target forcing term trajectory is matched. f_target np.array: the desired forcing term trajectory
361,752
def register_axis(key=None): def wrap(axis): name = key if key is not None else axis.__module__ + axis.__name__ BaseAxis.axis_types[name] = axis return axis return wrap
Returns a decorator registering an axis class in the axis type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot axis so that the frontend can use this key regardless of the kernel language.
361,753
def threshold(self, front_thresh=0.0, rear_thresh=100.0): data = np.copy(self._data) data[data < front_thresh] = 0.0 data[data > rear_thresh] = 0.0 return DepthImage(data, self._frame)
Creates a new DepthImage by setting all depths less than front_thresh and greater than rear_thresh to 0. Parameters ---------- front_thresh : float The lower-bound threshold. rear_thresh : float The upper bound threshold. Returns -------...
361,754
def fit(self, X, y=None): if y is not None: self.conditional_freqdist_ = {} self.classes_ = [str(label) for label in set(y)] for label in self.classes_: self.conditional_freqdist_[label] = self.count(X[y == label])...
The fit method is the primary drawing input for the frequency distribution visualization. It requires vectorized lists of documents and a list of features, which are the actual words from the original corpus (needed to label the x-axis ticks). Parameters ---------- X : n...
361,755
def _bottom_position(self, resource): image = self._get_scaled_image(resource) left = int(round(resource.size[0] // 2 - image.size[0] // 2)) upper = int(round(resource.size[1] - image.size[1])) return image, left, upper
Place watermark to bottom position :param resource: Image.Image :return: Image.Image
361,756
def cal_p(self, v, temp): if not isinstance(temp, np.ndarray): temp = np.asarray(temp) if not isinstance(v, np.ndarray): v = np.asarray(v) return self.cal_pst(v) + self.cal_pth(v, temp) + \ self.cal_pel(v, temp) + self.cal_panh(v, temp)
calculate total pressure at given volume and temperature :param v: unit-cell volume in A^3 :param temp: temperature in K :return: pressure in GPa :note: 2017/05/10 temp must be numpy array. If not, such as list, create an error.
361,757
def init_csv(movies_data, csv_file_path, delimiter): with open(csv_file_path, ) as csv_file: csv.writer(csv_file, delimiter=delimiter).writerows(movies_data)
Initialize csv movies database. :param movies_data: Data about movies :type movies_data: tuple[tuple] :param csv_file_path: Path to csv file with movies data :type csv_file_path: str :param delimiter: Csv file's delimiter :type delimiter: str
361,758
def optimize(self, graph): for center in self.centers: shortest_routes = shortest_path(graph, center)[1] for node, weight in list(shortest_routes.items()): self.nodes.setdefault(node, []).append(weight)
Build a dictionary mapping each pair of nodes to a number (the distance between them). @type graph: graph @param graph: Graph.
361,759
def set_default_option(cls, key, value): cls._default_options.update(cls._option_schema({key: value}))
Class method. Set the default value of the option `key` (string) to `value` for all future instances of the class. Note that this does not affect existing instances or the instance called from.
361,760
def run_backup(self): self.log("Starting backup at %s", now_field()) self.log("Backup config object created at %s", self.timestamp) calling_format=OrdinaryCallingFormat() ) else: conn = S3Connection(self.aws_access_key, self.aws_secret_k...
The actual backup is performed. The data for all added classes is extracted and written to a file per class where each line (terminated by a line feed character) is the JSON representing a single object. Those files are all archived in a single gzip'ed tarball which is stored in the AWS ...
361,761
def _connect_mitogen_su(spec): return { : , : { : spec.remote_user(), : spec.password(), : spec.python_path(), : spec.become_exe(), : spec.timeout(), : get_remote_name(spec), } }
Return ContextService arguments for su as a first class connection.
361,762
def match_url(self, path, method=): path = path.strip().lstrip() handler, param = self.routes.match(method + + path) if handler: return handler, param if method == : handler, param = self.routes.match( + path) if handler: return handler, param ha...
Find a callback bound to a path and a specific HTTP method. Return (callback, param) tuple or (None, {}). method: HEAD falls back to GET. HEAD and GET fall back to ALL.
361,763
def set_polygon_offset(self, factor=0., units=0.): self.glir.command(, , float(factor), float(units))
Set the scale and units used to calculate depth values Parameters ---------- factor : float Scale factor used to create a variable depth offset for each polygon. units : float Multiplied by an implementation-specific value to create a ...
361,764
def previous_visit(self): previous_visit = None if self.appointment: appointment = self.appointment while appointment.previous_by_timepoint: try: previous_visit = self.model.visit_model_cls().objects.get( appoin...
Returns the previous visit for this request or None. Requires attr `visit_model_cls`.
361,765
async def delete(self): return await self.bot.delete_message(self.chat.id, self.message_id)
Delete this message :return: bool
361,766
def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False): r if not (type(time) == int): if not (type(time) == np.int64): raise TypeError("given time (%s) is not an integer, but has type: %s" % (str(t...
r"""Compute time-correlation of obs1, or time-cross-correlation with obs2. The time-correlation at time=k is computed by the matrix-vector expression: cor(k) = obs1' diag(pi) P^k obs2 Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Transition matrix obs1 : ndarr...
361,767
def max(self): return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True))
Compute the max across records.
361,768
def reg_score_function(X, y, mean, scale, shape, skewness): return X*(y-mean)
GAS Poisson Regression Update term using gradient only - native Python function Parameters ---------- X : float datapoint for the right hand side variable y : float datapoint for the time series mean : float location parameter for the Po...
361,769
def read_array(self, dtype, count=-1, out=None): fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes count = size // dtype.itemsize else: size = count * dtype.itemsize result = nump...
Return numpy array from file in native byte order.
361,770
def genCompleteTypes( compoundSig ): i = 0 start = 0 end = len(compoundSig) def find_end( idx, b, e ): depth = 1 while idx < end: subc = compoundSig[idx] if subc == b: depth += 1 elif subc == e: depth -= 1 ...
Generator function used to iterate over each complete, top-level type contained in in a signature. Ex:: "iii" => [ 'i', 'i', 'i' ] "i(ii)i" => [ 'i', '(ii)', 'i' ] "i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
361,771
async def delete(self, *, reason=None): await self._state.http.delete_channel(self.id, reason=reason)
|coro| Deletes the channel. You must have :attr:`~.Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows up on the audit log. Raises ------...
361,772
def apply(self, doc, split, train, **kwargs): logger.debug(f"Document: {doc}") cands_list = get_cands_list_from_split( self.session, self.candidate_classes, doc, split ) feature_map = dict() all_cands = itertools.chain.from_itera...
Extract candidates from the given Context. :param doc: A document to process. :param split: Which split to use. :param train: Whether or not to insert new FeatureKeys.
361,773
def saveProfile( self ): manager = self.parent() prof = manager.currentProfile() save_prof = manager.viewWidget().saveProfile() prof.setXmlElement(save_prof.xmlElement())
Saves the current profile to the current settings from the view widget.
361,774
def check_query_data(self, query_data): for key in self.required_keys: if key not in query_data: raise ValidationError( .format(self.__class__.__name__, key) )
All items in a `querylist` must at least have `queryset` key and a `serializer_class` key. Any querylist item lacking both those keys will raise a ValidationError
361,775
def sort_elements_by_child_values(obj_pyxb, child_name_list): obj_pyxb.sort(key=lambda x: [get_auto(getattr(x, n)) for n in child_name_list])
In-place sort simple or complex elements in a PyXB object by values they contain in child elements. Args: obj_pyxb: PyXB object child_name_list: list of str List of element names that are direct children of the PyXB object.
361,776
def write_report(storage_dic, output_file, sample_id): with open(output_file, "w") as fh, open(".report.json", "w") as json_rep: fh.write("Sample,Total length,Total trimmed,%,5end Trim,3end Trim," "bad_reads\\n") for sample, vals in storage_dic.items(): ...
Writes a report from multiple samples. Parameters ---------- storage_dic : dict or :py:class:`OrderedDict` Storage containing the trimming statistics. See :py:func:`parse_log` for its generation. output_file : str Path where the output file will be generated. sample_id : str...
361,777
def kepler_lcdict_to_pkl(lcdict, outfile=None): s Kepler ID/EPIC ID will determined from the `lcdict` and used to form the filename of the output pickle file. If this is a `str`, the provided filename will be used. Returns ------- str The absolute path to the written pickle fil...
This writes the `lcdict` to a Python pickle. Parameters ---------- lcdict : lcdict This is the input `lcdict` to write to a pickle. outfile : str or None If this is None, the object's Kepler ID/EPIC ID will determined from the `lcdict` and used to form the filename of the outp...
361,778
def _extract_delta(expr, idx): from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression from qnet.algebra.core.scalar_algebra import ScalarValue sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr) delta, new_expr = _sympy_extract_delta(sympy_factor, idx) if delta is...
Extract a "simple" Kronecker delta containing `idx` from `expr`. Assuming `expr` can be written as the product of a Kronecker Delta and a `new_expr`, return a tuple of the sympy.KroneckerDelta instance and `new_expr`. Otherwise, return a tuple of None and the original `expr` (possibly converted to a :c...
361,779
def upload_from_filename( self, filename, content_type=None, client=None, predefined_acl=None ): content_type = self._get_content_type(content_type, filename=filename) with open(filename, "rb") as file_obj: total_bytes = os.fstat(file_obj.fileno()).st_size s...
Upload this blob's contents from the content of a named file. The content type of the upload will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The value given by ``mimetypes.guess_type`...
361,780
def plot_density(population, bins=100, new_fig=True, subplot=111, levels=None, plane=, colorlabel=, labelfontsize=16, color_map=, no_colorbar=False, threshold=0.01, neurite_type=NeuriteType.basal_dendrite, **kwargs): fig, ax = common.get_fig...
Plots the 2d histogram of the center coordinates of segments in the selected plane.
361,781
def get_logical_plan(cluster, environ, topology, role=None): params = dict(cluster=cluster, environ=environ, topology=topology) if role is not None: params[] = role request_url = tornado.httputil.url_concat( create_url(LOGICALPLAN_URL_FMT), params) raise tornado.gen.Return((yield fetch_url_as_json(...
Get the logical plan state of a topology in a cluster :param cluster: :param environ: :param topology: :param role: :return:
361,782
def backup_bios_config(irmc_info): try: elcm_profile_get(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) elcm_profile_delete(irmc_info=irmc_info, profile_name=PROFILE_BIOS_CONFIG) except ELCMProfileN...
backup current bios configuration This function sends a BACKUP BIOS request to the server. Then when the bios config data are ready for retrieving, it will return the data to the caller. Note that this operation may take time. :param irmc_info: node info :return: a dict with following values: ...
361,783
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
It returns breadcrumb as p
361,784
def _did_count(self, connection): self.current_connection = connection response = connection.response count = 0 callback = None if in response.headers: count = int(response.headers[]) if in connection.callbacks: callback = connection....
Called when count if finished
361,785
def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId) try: self.close_handle() except Exception: warnings.warn( "Failed to close process handle: %s" % trace...
Opens a new handle to the process. The new handle is stored in the L{hProcess} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess:...
361,786
def get_tm_session(session_factory, transaction_manager): dbsession = session_factory() zope.sqlalchemy.register( dbsession, transaction_manager=transaction_manager) return dbsession
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised. - ...
361,787
def from_raw_query(cls, query_string): try: node_tree = grammar.parse(query_string) except IncompleteParseError: query_string = cls.fix_quotes(query_string) node_tree = grammar.parse(query_string) structured_query = DictFormater().visit(node_tree) ...
Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class.
361,788
def loadNelderMeadData(name): f = open(name + ,) my_reader = csv.reader(f,delimiter=) my_shape_txt = next(my_reader) shape0 = int(my_shape_txt[0]) shape1 = int(my_shape_txt[1]) my_nums_txt = next(my_reader) iters = int(my_nums_txt[0]) evals = int(my_nums_txt[1]) simplex_flat = n...
Reads the progress of a parallel Nelder-Mead search from a text file, as created by saveNelderMeadData(). Parameters ---------- name : string Name of the txt file from which to read search progress. Returns ------- simplex : np.array The current state of the simplex of para...
361,789
def _set_ldp_sync(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ldp_sync.ldp_sync, is_container=, presence=True, yang_name="ldp-sync", rest_name="ldp-sync", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True...
Setter method for ldp_sync, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/ldp_sync (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_sync is considered as a private method. B...
361,790
def execute_setup(self): ver = execute_get_text("python setup.py --version") if not ver: return None if "UserWarning" in ver: logger.warning( "python setup.py --version won't parse, got :" + unicode(ver) ) ...
for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return:
361,791
def save(self, X=None, w=None, A=None): self.X.append(X) self.wgt.append(w) self.A.append(A)
Save one "page" of history at a given time. .. note:: This method is used internally by `SMC` to store the state of the particle system at each time t. In most cases, users should not have to call this method directly.
361,792
def disconnect(self): try: self._link.disconnect() self._protocol = None self._invalidate_cached_registers() except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
Deinitialize the DAP I/O pins
361,793
def read_url(url): logging.debug(.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers[] = % token request = Request(url, headers=headers) response = urlopen(request).read() return json.loads(response.decode("UTF-8"))
Reads given URL as JSON and returns data as loaded python object.
361,794
def _finalize_block_blob(self, ud, metadata): if not ud.entity.is_encrypted and ud.must_compute_md5: digest = blobxfer.util.base64_encode_as_string(ud.md5.digest()) else: digest = None blobxfer.operations.azure.blob.block.put_block_list( ud.e...
Finalize Block blob :param Uploader self: this :param blobxfer.models.upload.Descriptor ud: upload descriptor :param dict metadata: metadata dict
361,795
def __del_running_bp_from_all_threads(self, bp): "Auxiliary method." for (tid, bpset) in compat.iteritems(self.__runningBP): if bp in bpset: bpset.remove(bp) self.system.get_thread(tid).clear_tf()
Auxiliary method.
361,796
def content(self): return _bfd.section_get_content(self.bfd, self._ptr, 0, self.size)
Return the entire section content.
361,797
def _check_stream(stream): if not isinstance(stream, type(_sys.stderr)): raise TypeError("The stream given ({}) is not a file object.".format(stream))
Check that the stream is a file
361,798
def recurse(name, source, keep_source=True, clean=False, require=None, user=None, group=None, dir_mode=None, file_mode=None, sym_mode=None, template=None, context=None, replace...
Recurse through a subdirectory on the master and copy said subdirectory over to the specified path. name The directory to set the recursion in source The source directory, this directory is located on the salt master file server and is specified with the salt:// protocol. If the di...
361,799
def other_set_producer(socket, which_set, image_archive, patch_archive, groundtruth): patch_images = extract_patch_images(patch_archive, which_set) num_patched = 0 with tar_open(image_archive) as tar: filenames = sorted(info.name for info in tar if info.isfile()) ...
Push image files read from the valid/test set TAR to a socket. Parameters ---------- socket : :class:`zmq.Socket` PUSH socket on which to send images. which_set : str Which set of images is being processed. One of 'train', 'valid', 'test'. Used for extracting the appropriate im...