Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
377,600
def _build(self, input_sequence, state): input_shape = input_sequence.get_shape() if input_shape[0] is None: raise ValueError("Time dimension of input (dim 0) must be statically" "known.") seq_length = int(input_shape[0]) forward_state, backward_state = state ...
Connects the BidirectionalRNN module into the graph. Args: input_sequence: tensor (time, batch, [feature_1, ..]). It must be time_major. state: tuple of states for the forward and backward cores. Returns: A dict with forward/backard states and output sequences: "outputs":{...
377,601
def max_cardinality_heuristic(G): adj = {v: set(G[v]) for v in G} num_nodes = len(adj) order = [0] * num_nodes upper_bound = 0 labelled_neighbors = {v: 0 for v in adj} for i in range(num_nodes): v = max(labelled_neighbors, key=lambda u: lab...
Computes an upper bound on the treewidth of graph G based on the max-cardinality heuristic for the elimination ordering. Parameters ---------- G : NetworkX graph The graph on which to compute an upper bound for the treewidth. inplace : bool If True, G will be made an empty graph in...
377,602
def getActiveSegment(self, c, i, timeStep): nSegments = len(self.cells[c][i]) bestActivation = self.activationThreshold which = -1 for j,s in enumerate(self.cells[c][i]): activity = self.getSegmentActivityLevel(s, self.activeState[timeStep], connectedSynapsesOnly = True) if a...
For a given cell, return the segment with the strongest _connected_ activation, i.e. sum up the activations of the connected synapses of the segments only. That is, a segment is active only if it has enough connected synapses.
377,603
def basemz(df): d = np.array(df.columns)[df.values.argmax(axis=1)] return Trace(d, df.index, name=)
The mz of the most abundant ion.
377,604
def shelter_get(self, **kwargs): root = self._do_api_call("shelter.get", kwargs) shelter = root.find("shelter") for field in shelter: record = {} for field in shelter: record[field.tag] = field.text return record
shelter.get wrapper. Given a shelter ID, retrieve its details in dict form. :rtype: dict :returns: The shelter's details.
377,605
def value(self): if in self._json_data and self._json_data[]: return "[Attachment: {}]".format(self._json_data[].split()[-1]) else: return None
Retrieve the data value of this attachment. Will show the filename of the attachment if there is an attachment available otherwise None Use save_as in order to download as a file. Example ------- >>> file_attachment_property = project.part('Bike').property('file_attachment') ...
377,606
def __calculate_adjacency_lists(graph): adj = {} for node in graph.get_all_node_ids(): neighbors = graph.neighbors(node) adj[node] = neighbors return adj
Builds an adjacency list representation for the graph, since we can't guarantee that the internal representation of the graph is stored that way.
377,607
def t_doublequote_end(self, t): r t.value = t.lexer.string_value t.type = t.lexer.string_value = None t.lexer.pop_state() return t
r'"
377,608
def infer_getattr(node, context=None): obj, attr = _infer_getattr_args(node, context) if ( obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, "igetattr") ): return util.Uninferable try: return next(obj.igetattr(attr, context=context)) ...
Understand getattr calls If one of the arguments is an Uninferable object, then the result will be an Uninferable object. Otherwise, the normal attribute lookup will be done.
377,609
def _send(self, msg, buffers=None): if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
Sends a message to the model in the front-end.
377,610
def display_initialize(self): echo(self.term.home + self.term.clear) echo(self.term.move_y(self.term.height // 2)) echo(self.term.center().rstrip()) flushout() if LIMIT_UCS == 0x10000: echo() echo(self.term.blink_red(self.term.center( ...
Display 'please wait' message, and narrow build warning.
377,611
async def get_entity_by_id(self, get_entity_by_id_request): response = hangouts_pb2.GetEntityByIdResponse() await self._pb_request(, get_entity_by_id_request, response) return response
Return one or more user entities. Searching by phone number only finds entities when their phone number is in your contacts (and not always even then), and can't be used to find Google Voice contacts.
377,612
def run(main=None, argv=None, **flags): import sys as _sys import inspect main = main or _sys.modules[].main if main.__doc__: docstring = main.__doc__.split()[0] _parser.usage = .format(docstring) try: a = inspect.getfullargspec(main) except AttributeEr...
:param main: main or sys.modules['__main__'].main :param argv: argument list used in argument parse :param flags: flags to define with defaults :return:
377,613
def channels_leave(self, room_id, **kwargs): return self.__call_api_post(, roomId=room_id, kwargs=kwargs)
Causes the callee to be removed from the channel.
377,614
def _array_type_std_res(self, counts, total, colsum, rowsum): if self.mr_dim_ind == 0: total = total[:, np.newaxis] rowsum = rowsum[:, np.newaxis] expected_counts = rowsum * colsum / total variance...
Return ndarray containing standard residuals for array values. The shape of the return value is the same as that of *counts*. Array variables require special processing because of the underlying math. Essentially, it boils down to the fact that the variable dimensions are mutually indep...
377,615
def gradient(self): r functional = self class GroupL1Gradient(Operator): def __init__(self): super(GroupL1Gradient, self).__init__( functional.domain, functional.domain, linear=False) def _call(self, x,...
r"""Gradient operator of the functional. The functional is not differentiable in ``x=0``. However, when evaluating the gradient operator in this point it will return 0. Notes ----- The gradient is given by .. math:: \left[ \nabla \| \|f\|_1 \|_1 \right]_i ...
377,616
def _val_to_store_info(self, val): if isinstance(val, str): return val, 0 elif isinstance(val, int): return "%d" % val, Client._FLAG_INTEGER elif isinstance(val, long): return "%d" % val, Client._FLAG_LONG return pickle.dumps(val, protocol=pic...
Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself.
377,617
def full_name(self): if self._full_name is None: fn = self.name.replace(".", "\\.") parent = self._parent if parent is not None: fn = parent.full_name + "." + fn self._full_name = fn return self._full_name
Obtains the full name of the actor. :return: the full name :rtype: str
377,618
def do_execute(self): if self.storagehandler is None: return "No storage handler available!" expr = str(self.resolve_option("expression")).replace( "{X}", str(self.storagehandler.storage[str(self.resolve_option("storage_name"))])) expr = self.storagehandler.expan...
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
377,619
def get_contract_factory(self, name: ContractName) -> Contract: validate_contract_name(name) if "contract_types" not in self.manifest: raise InsufficientAssetsError( "This package does not contain any contract type data." ) try: cont...
Return the contract factory for a given contract type, generated from the data vailable in ``Package.manifest``. Contract factories are accessible from the package class. .. code:: python Owned = OwnedPackage.get_contract_factory('owned') In cases where a contract uses a library, t...
377,620
def Run(self): try: self.stats = {} self.BeginProcessing() processed_count = 0 for client_info_batch in _IterateAllClients( recency_window=self.recency_window): for client_info in client_info_batch: self.ProcessClientFullInfo(client_info) processe...
Retrieve all the clients for the AbstractClientStatsCollectors.
377,621
def _dict_seq_locus(list_c, loci_obj, seq_obj): seqs = defaultdict(set) for c in list_c.values(): for l in c.loci2seq: [seqs[s].add(c.id) for s in c.loci2seq[l]] common = [s for s in seqs if len(seqs[s]) > 1] seqs_in_c = defaultdict(float) for c in list_c.values(): ...
return dict with sequences = [ cluster1, cluster2 ...]
377,622
def init_pop(self): pop = Pop(self.population_size) seed_with_raw_features = False if self.seed_with_ml: if (self.ml_type == or self.ml_type == ): seed_with_raw_features=True elif (hasattr(s...
initializes population of features as GP stacks.
377,623
def setMAC(self, xEUI): print % self.port address64 = try: if not xEUI: address64 = self.mac if not isinstance(xEUI, str): address64 = self.__convertLongToString(xEUI) if len(address64) < 16: ...
set the extended addresss of Thread device Args: xEUI: extended address in hex format Returns: True: successful to set the extended address False: fail to set the extended address
377,624
def _new_song(self): self.song = 0 self.dif_song = s != self.song self.pos = 0
Used internally to get a metasong index.
377,625
def xml(self, url, method=, params=None, data=None): r = self.req(url, method, params, data) return self.to_xml(r.content, base_url=r.url)
请求并返回xml :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: dict :param data: body :rtype: html.HtmlElement :return:
377,626
def complete_xml_element(self, xmlnode, doc): ns = xmlnode.ns() if self.instructions is not None: xmlnode.newTextChild(ns, "instructions", to_utf8(self.instructions)) if self.form: self.form.as_xml(xmlnode, doc) if self.remove: xmlnode.newChil...
Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the element belongs. :Types: - `xmlnode`: `libx...
377,627
def __get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any], children_on_fs: Dict[str, PersistedObject], logger: Logger) \ -> Dict[str, Any]: constructor_args_types_and_opt = get_construc...
Simply inspects the required type to find the names and types of its constructor arguments. Then relies on the inner ParserFinder to parse each of them. :param obj_on_fs: :param desired_type: :param children_on_fs: :param logger: :return:
377,628
def anomalyGetLabels(self, start, end): return self._getAnomalyClassifier().getSelf().getLabels(start, end)
Get labels from the anomaly classifier within this model. :param start: (int) index to start getting labels :param end: (int) index to end getting labels
377,629
def get_aux_files(basename): base = os.path.splitext(basename)[0] files = {"bkg": base + "_bkg.fits", "rms": base + "_rms.fits", "mask": base + ".mim", "cat": base + "_comp.fits", "psf": base + "_psf.fits"} for k in files.keys(): if not os.pa...
Look for and return all the aux files that are associated witht this filename. Will look for: background (_bkg.fits) rms (_rms.fits) mask (.mim) catalogue (_comp.fits) psf map (_psf.fits) will return filenames if they exist, or None where they do not. Parameters --...
377,630
def cmd(str, print_ret=False, usr_pwd=None, run=True): if usr_pwd: str = .format(usr_pwd[1], usr_pwd[0], str) print(.format(str)) if run: err, ret = commands.getstatusoutput(str) else: err = None ret = None if err: print(.format(ret)) raise Exception(ret) if ret and print_ret: lines = ret.split...
Executes a command and throws an exception on error. in: str - command print_ret - print command return usr_pwd - execute command as another user (user_name, password) run - really execute command? out: returns the command output
377,631
def _wait(self, objects, attr, value, wait_interval=None, wait_time=None): r objects = list(objects) if not objects: return if wait_interval is None: wait_interval = self.wait_interval if wait_time < 0: end_time = None else: ...
r""" Calls the ``fetch`` method of each object in ``objects`` periodically until the ``attr`` attribute of each one equals ``value``, yielding the final state of each object as soon as it satisfies the condition. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any ...
377,632
def next(self): try: return self.results.pop(0) except IndexError: if self.next_uri is None: raise StopIteration() else: if not self.next_uri: self.results = self.list_method(marker=self.marker, ...
Return the next available item. If there are no more items in the local 'results' list, check if there is a 'next_uri' value. If so, use that to get the next page of results from the API, and return the first item from that query.
377,633
def remove_xattr(self, path, xattr_name, **kwargs): kwargs[] = xattr_name response = self._put(path, , **kwargs) assert not response.content
Remove an xattr of a file or directory.
377,634
def add_val(self, val): if not isinstance(val, type({})): raise ValueError(type({})) self.read() self.config.update(val) self.save()
add value in form of dict
377,635
def _can_parse(self, content_type): Accept content_type, content_subtype, content_param = utils.parse_media_type(content_type) for accepted in self.headers.get(, self.DEFAULT_CONTENT_TYPE).split(): type, subtype, param = utils.parse_media_type(accepted) ...
Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default
377,636
def get_value_with_source(self, layer=None): if layer: return self._values[layer] for layer in reversed(self._layers): if layer in self._values: return self._values[layer] raise KeyError(layer)
Returns a tuple of the value's source and the value at the specified layer. If no layer is specified then the outer layer is used. Parameters ---------- layer : str Name of the layer to use. If None then the outermost where the value exists will be used. ...
377,637
def info(self, *args, **kwargs): self.lock() try: return logger.info(*args, **kwargs) finally: self.unlock()
Logs the line of the current thread owns the underlying lock, or blocks.
377,638
def group_by(resources, key): resource_map = {} parts = key.split() for r in resources: v = r for k in parts: v = v.get(k) if not isinstance(v, dict): break resource_map.setdefault(v, []).append(r) return resource_map
Return a mapping of key value to resources with the corresponding value. Key may be specified as dotted form for nested dictionary lookup
377,639
def build(self): helical_helix = Polypeptide() primitive_coords = self.curve_primitive.coordinates helices = [Helix.from_start_and_end(start=primitive_coords[i], end=primitive_coords[i + 1], helix_ty...
Builds the `HelicalHelix`.
377,640
def all_subslices(itr): assert iterable(itr), .format(itr) if not hasattr(itr, ): itr = deque(itr) len_itr = len(itr) for start,_ in enumerate(itr): d = deque() for i in islice(itr, start, len_itr): d.append(i) yield tuple(d)
generates every possible slice that can be generated from an iterable
377,641
def fill_x509_data(self, x509_data): x509_issuer_serial = x509_data.find( , namespaces=constants.NS_MAP ) if x509_issuer_serial is not None: self.fill_x509_issuer_name(x509_issuer_serial) x509_crl = x509_data.find(, namespaces=constants.NS_MAP) i...
Fills the X509Data Node :param x509_data: X509Data Node :type x509_data: lxml.etree.Element :return: None
377,642
def decode(input, fallback_encoding, errors=): fallback_encoding = _get_encoding(fallback_encoding) bom_encoding, input = _detect_bom(input) encoding = bom_encoding or fallback_encoding return encoding.codec_info.decode(input, errors)[0], encoding
Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupErr...
377,643
def _process_event(self, event): if event.get(): event.user = self.lookup_user(event.get()) if event.get(): event.channel = self.lookup_channel(event.get()) if self.user.id in event.mentions: event.mentions_me = True event.mentions = [ self...
Extend event object with User and Channel objects
377,644
def merge_wavelengths(waveset1, waveset2, threshold=1e-12): if waveset1 is None and waveset2 is None: out_wavelengths = None elif waveset1 is not None and waveset2 is None: out_wavelengths = waveset1 elif waveset1 is None and waveset2 is not None: out_wavelengths = waveset2 ...
Return the union of the two sets of wavelengths using :func:`numpy.union1d`. The merged wavelengths may sometimes contain numbers which are nearly equal but differ at levels as small as 1e-14. Having values this close together can cause problems down the line. So, here we test whether any such smal...
377,645
def update(self): result = self.api.github_api(*self._apicall_parameters()) if result is None: self._next_update = datetime.now() + timedelta(seconds=self.BACKOFF) self._cached_result = self._apiresult_error() else: ...
Connect to GitHub API endpoint specified by `_apicall_parameters()`, postprocess the result using `_apiresult_postprocess()` and trigger a cache update if the API call was successful. If an error occurs, cache the empty result generated by `_apiresult_error()`. Additionally, set up retr...
377,646
def click(self, focus=None, sleep_interval=None): focus = focus or self._focus or pos_in_percentage = self.get_position(focus) self.poco.pre_action(, self, pos_in_percentage) ret = self.poco.click(pos_in_percentage) if sleep_interval: time.sleep(sleep_inter...
Perform the click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default one. It is also possible to click another point offset by providing ``focus`` arg...
377,647
def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None, state=None, run_task=None, **kwargs): filters_set = self.filters_factory.resolve(self.message_handlers, *cust...
Register handler for message .. code-block:: python3 # This handler works only if state is None (by default). dp.register_message_handler(cmd_start, commands=['start', 'about']) dp.register_message_handler(entry_point, commands=['setup']) # This handler works o...
377,648
def get_class(kls): parts = kls.split() try: module = .join(parts[:-1]) m = __import__(module) except ImportError: module = .join(parts[:-2]) m = __import__(module) t = None starter = None for i in range(1, len(parts)): comp = parts...
:param kls - string of fully identified starter function or starter method path for instance: - workers.abstract_worker.AbstractWorker.start - workers.example_script_worker.main :return tuple (type, object, starter) for instance: - (FunctionType, <function_main>, None) - (type, <Class_...
377,649
def getCocktailSum(e0, e1, eCocktail, uCocktail): mask = (eCocktail >= e0) & (eCocktail <= e1) if np.any(mask): idx = getMaskIndices(mask) eCl, eCu = eCocktail[idx[0]], eCocktail[idx[1]] not_coinc_low, not_coinc_upp = (eCl != e0), (eCu != e1) uCocktailSum = fsum(uCocktail[mask[:-1...
get the cocktail sum for a given data bin range
377,650
def services(self): self._services = [] params = { "f" : "json" } json_dict = self._get(url=self._currentURL, param_dict=params, securityHandler=self._securityHandler, ...
returns the services in the current folder
377,651
def find_donor_catchments(self, include_subject_catchment=): if self.gauged_cachments: self.donor_catchments = self.gauged_cachments. \ most_similar_catchments(subject_catchment=self.catchment, similarity_dist_function=lambda...
Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` is set manually. The results are stored in :attr:`.donor_catchments`. The (lis...
377,652
def check_bcr_catchup(self): logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}") if peer_bcr_len == 0: peer.start_outstanding_data_request[HEARTBEAT_BLOCKS] = 0 print(f"{peer.prefix} request count: {pe...
we're exceeding data request speed vs receive + process
377,653
def _sleep(self, seconds): for _ in range(int(seconds)): if not self.force_stop: sleep(1)
Sleep between requests, but don't force asynchronous code to wait :param seconds: The number of seconds to sleep :return: None
377,654
def background_at_centroid(self): from scipy.ndimage import map_coordinates if self._background is not None: if (self._is_completely_masked or np.any(~np.isfinite(self.centroid))): return np.nan * self._background_unit ...
The value of the ``background`` at the position of the source centroid. The background value at fractional position values are determined using bilinear interpolation.
377,655
def do_lzop_get(creds, url, path, decrypt, do_retry=True): assert url.endswith(), def log_wal_fetch_failures_on_error(exc_tup, exc_processor_cxt): def standard_detail_message(prefix=): return (prefix + .format(n=exc_processor_cxt, url=url)) typ, value, tb ...
Get and decompress a S3 URL This streams the content directly to lzop; the compressed version is never stored on disk.
377,656
def render(self, progress, width=None, status=None): results = [widget.render(progress, width=self._widget_lengths[i], status=status) for i, widget in enumerate(self._widgets)] if self._file_mode: res = "" for i, result in enumerate(results): ...
Render the widget.
377,657
def p_andnode_expression(self, t): self.accu.add(Term(, ["and(\""+t[2]+"\")"])) t[0] = "and(\""+t[2]+"\")"
andnode_expression : LB identlist RB
377,658
def extract_number_oscillations(self, index, amplitude_threshold): return pyclustering.utils.extract_number_oscillations(self.__amplitude, index, amplitude_threshold);
! @brief Extracts number of oscillations of specified oscillator. @param[in] index (uint): Index of oscillator whose dynamic is considered. @param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example, when osc...
377,659
def get_authoryear_from_entry(entry, paren=False): def _format_last(person): return .join([n.strip() for n in person.last_names]) if len(entry.persons[]) > 0: persons = entry.persons[] elif len(entry.persons[]) > 0: persons = entry.persons[] else:...
Get and format author-year text from a pybtex entry to emulate natbib citations. Parameters ---------- entry : `pybtex.database.Entry` A pybtex bibliography entry. parens : `bool`, optional Whether to add parentheses around the year. Default is `False`. Returns ------- ...
377,660
def is_activated(self, images, augmenter, parents, default): if self.activator is None: return default else: return self.activator(images, augmenter, parents, default)
Returns whether an augmenter may be executed. Returns ------- bool If True, the augmenter may be executed. If False, it may not be executed.
377,661
def OPTIONS(self, *args, **kwargs): return self._handle_api(self.API_OPTIONS, args, kwargs)
OPTIONS request
377,662
def get_remove_security_group_commands(self, sg_id, profile): return self._get_interface_commands(sg_id, profile, delete=True)
Commands for removing ACL from interface
377,663
def _get_hash(self, file_obj): size = 0 hash_buider = self.hash_builder() for piece in self._get_file_iterator(file_obj): hash_buider.update(piece) size += len(piece) file_obj.seek(0) return "%s_%x" % (hash_buider.hexdigest(), size)
Compute hash for the `file_obj`. Attr: file_obj (obj): File-like object with ``.write()`` and ``.seek()``. Returns: str: Hexdigest of the hash.
377,664
def _EntriesGenerator(self): table_name = getattr(self.path_spec, , None) column_name = getattr(self.path_spec, , None) if table_name and column_name: if self._number_of_entries is None: path_spec = sqlite_blob_path_spec.SQLiteBlobPathSpec( table_na...
Retrieves directory entries. Since a directory can contain a vast number of entries using a generator is more memory efficient. Yields: SQLiteBlobPathSpec: a path specification. Raises: AccessError: if the access to list the directory was denied. BackEndError: if the directory could...
377,665
def autoargs(include=None, exclude=None, f=DECORATED ): return autoargs_decorate(f, include=include, exclude=exclude)
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing the function. In other words: ``` @autoargs def myfunc(a): print('hello') ``` will create the equivalent of ``` def myfunc(a): self.a = a ...
377,666
def deploy(remote, assets_to_s3): header("Deploying...") if assets_to_s3: for mod in get_deploy_assets2s3_list(CWD): _assets2s3(mod) remote_name = remote or "ALL" print("Pushing application's content to remote: %s " % remote_name) hosts = get_deploy_hosts_list(CWD, remote...
To DEPLOY your application
377,667
def process_cli(log_level, mets, page_id, tasks): log = getLogger() run_tasks(mets, log_level, page_id, tasks) log.info("Finished")
Process a series of tasks
377,668
def setPololuProtocol(self): self._compact = False self._log and self._log.debug("Pololu protocol has been set.")
Set the pololu protocol.
377,669
def getManagers(self): manager_ids = [] manager_list = [] for department in self.getDepartments(): manager = department.getManager() if manager is None: continue manager_id = manager.getId() if manager_id not in manager_ids...
Return all managers of responsible departments
377,670
def _normalize(self, flags): norm = None if isinstance(flags, MessageFlags): norm = flags.bytes elif isinstance(flags, bytearray): norm = binascii.hexlify(flags) elif isinstance(flags, int): norm = bytes([flags]) elif isinstance(flags,...
Take any format of flags and turn it into a hex string.
377,671
def get(key, default=-1): if isinstance(key, int): return Routing(key) if key not in Routing._member_map_: extend_enum(Routing, key, default) return Routing[key]
Backport support for original codes.
377,672
def process_result_value(self, value, dialect): if value is None: return None p = value.split("|") if len(p) == 0: return None return SourceLocation(*map(int, p))
SQLAlchemy uses this to convert a string into a SourceLocation object. We separate the fields by a |
377,673
def validate(name, value, enforce_not_none=True, equals=None, instance_of=None, subclass_of=None, is_in=None, subset_of=None, con...
A validation function for quick inline validation of `value`, with minimal capabilities: * None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False) * Type validation: `value` should be an instance of any of `var_types` if provided * Value validation: ...
377,674
def obj_to_md(self, file_path=None, title_columns=False, quote_numbers=True): return self.obj_to_mark_down(file_path=file_path, title_columns=title_columns, quote_numbers=quote_numbers)
This will return a str of a mark down tables. :param title_columns: bool if True will title all headers :param file_path: str of the path to the file to write to :param quote_numbers: bool if True will quote numbers that are strings :return: str
377,675
def unwind(self, values, backend, **kwargs): if not hasattr(self, "_unwind_value"): self._unwind_value = self._unwind(values, backend, **kwargs) return self._unwind_value
Unwind expression by applying *values* to the abstract nodes. The ``kwargs`` dictionary can contain data which can be used to override values
377,676
def remove_intra(M, contigs): N = np.copy(M) n = len(N) assert n == len(contigs) for (i, j) in itertools.product(range(n), range(n)): if contigs[i] == contigs[j]: N[i, j] = 0 return N
Remove intrachromosomal contacts Given a contact map and a list attributing each position to a given chromosome, set all contacts within each chromosome or contig to zero. Useful to perform calculations on interchromosomal contacts only. Parameters ---------- M : array_like The ini...
377,677
def flags(self, index): return Qt.ItemFlags(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)
Set flags
377,678
def _ParseHeader(self, parser_mediator, structure): _, month, day, hours, minutes, seconds, year = structure.date_time month = timelib.MONTH_DICT.get(month.lower(), 0) time_elements_tuple = (year, month, day, hours, minutes, seconds) try: date_time = dfdatetime_time_elements.TimeElements( ...
Parses a log header. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.
377,679
def _disable_prometheus_process_collector(self) -> None: logger.info("Removing prometheus process collector") try: core.REGISTRY.unregister(PROCESS_COLLECTOR) except KeyError: logger.debug("PROCESS_COLLECTOR already removed from prometheus")
There is a bug in SDC' Docker implementation and intolerable prometheus_client code, due to which its process_collector will fail. See https://github.com/prometheus/client_python/issues/80
377,680
def check(self, radl): SIMPLE_FEATURES = { "name": (str, lambda x, _: bool(x.value)), "path": (str, lambda x, _: bool(x.value)), "version": (str, is_version), "preinstalled": (str, ["YES", "NO"]) } self.check_simple(SIMPLE_FEATURES, radl)
Check the features in this application.
377,681
def reset(self): self.resetRNG() sNow = np.zeros(self.pop_size) Shk = self.RNG.rand(self.pop_size) sNow[Shk < self.p_init] = 1 self.sNow = sNow
Resets this agent type to prepare it for a new simulation run. This includes resetting the random number generator and initializing the style of each agent of this type.
377,682
def hdf5_col(self, chain=-1): return self.db._tables[chain].colinstances[self.name]
Return a pytables column object. :Parameters: chain : integer The index of the chain. .. note:: This method is specific to the ``hdf5`` backend.
377,683
def deepcopy(self, x=None, y=None): x = self.x if x is None else x y = self.y if y is None else y return Keypoint(x=x, y=y)
Create a deep copy of the Keypoint object. Parameters ---------- x : None or number, optional Coordinate of the keypoint on the x axis. If ``None``, the instance's value will be copied. y : None or number, optional Coordinate of the keypoint on the y...
377,684
def get_context_data(self, **kwargs): strain = super(StrainDetail, self).get_object() context = super(StrainDetail, self).get_context_data(**kwargs) context[] = Breeding.objects.filter(Strain=strain) context[] = Animal.objects.filter(Strain=strain).order_by(,) c...
This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages.
377,685
def _adapt_response(self, response): errors, meta = super(ServerError, self)._adapt_response(response) return errors[0], meta
Convert various error responses to standardized ErrorDetails.
377,686
def validateOneNamespace(self, doc, elem, prefix, ns, value): if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o if ns is None: ns__o = None else: ns__o = ns._o ret = libxml2mod.xmlValidateOneNamesp...
Try to validate a single namespace declaration for an element basically it does the following checks as described by the XML-1.0 recommendation: - [ VC: Attribute Value Type ] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] - [ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ...
377,687
def _get_service_keys(self, service_name): guid = self.get_instance_guid(service_name) uri = "/v2/service_instances/%s/service_keys" % (guid) return self.api.get(uri)
Return the service keys for the given service.
377,688
def tee(process, filter): lines = [] while True: line = process.stdout.readline() if line: if sys.version_info[0] >= 3: line = decode(line) stripped_line = line.rstrip() if filter(stripped_line): sys.stdout.write(line) ...
Read lines from process.stdout and echo them to sys.stdout. Returns a list of lines read. Lines are not newline terminated. The 'filter' is a callable which is invoked for every line, receiving the line as argument. If the filter returns True, the line is echoed to sys.stdout.
377,689
def _to_dict(self): _dict = {} if hasattr(self, ) and self.score is not None: _dict[] = self.score if hasattr(self, ) and self.sentence is not None: _dict[] = self.sentence if hasattr(self, ) and self.type is not None: _dict[] = self.type ...
Return a json dictionary representing this model.
377,690
def get_url_path(self, language=None): if self.is_first_root(): try: return reverse() except Exception: pass url = self.get_complete_slug(language) if not language: language = settings.PAGE_DEF...
Return the URL's path component. Add the language prefix if ``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``. :param language: the wanted url language.
377,691
def prep_directory(self, target_dir): dirname = path.dirname(target_dir) if dirname: dirname = path.join(settings.BUILD_DIR, dirname) if not self.fs.exists(dirname): logger.debug("Creating directory at {}{}".format(self.fs_name, dirname)) ...
Prepares a new directory to store the file at the provided path, if needed.
377,692
def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): env = inliner.document.settings.env r = env.get_domain().role()( , rawtext, etext, lineno, inliner, options, content) pnode = r[0][0] prefixes = get_import_prefixes_from_env(env) try: ...
Smart linking role. Expands to ':obj:`text`' if `text` is an object that can be imported; otherwise expands to '*text*'.
377,693
def ncr(n, r): r = min(r, n - r) numer = reduce(op.mul, range(n, n - r, -1), 1) denom = reduce(op.mul, range(1, r + 1), 1) return numer // denom
Calculate n choose r. :param n: n :type n : int :param r: r :type r :int :return: n choose r as int
377,694
def is_valid(self): try: request = self.get_oauth_request() client = self.get_client(request) params = self._server.verify_request(request, client, None) except Exception as e: raise e return client
Returns a Client object if this is a valid OAuth request.
377,695
def generate_insufficient_overlap_message( e, exposure_geoextent, exposure_layer, hazard_geoextent, hazard_layer, viewport_geoextent): description = tr( ) message = m.Message(description) text = m.Paragraph(tr()) mes...
Generate insufficient overlap message. :param e: An exception. :type e: Exception :param exposure_geoextent: Extent of the exposure layer in the form [xmin, ymin, xmax, ymax] in EPSG:4326. :type exposure_geoextent: list :param exposure_layer: Exposure layer. :type exposure_layer: QgsM...
377,696
def batch(self, num): self._params.pop(, None) it = iter(self) while True: chunk = list(islice(it, num)) if not chunk: return yield chunk
Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results
377,697
def write_memory(self, addr, data, transfer_size=32): assert transfer_size in (8, 16, 32) if transfer_size == 32: self._link.write_mem32(addr, conversion.u32le_list_to_byte_list([data]), self._apsel) elif transfer_size == 16: self._link.write_mem16(addr, conversi...
! @brief Write a single memory location. By default the transfer size is a word.
377,698
def hardware_flexport_id(self, **kwargs): config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") flexport = ET.SubElement(hardware, "flexport") id = ET.SubElement(flexport, "id") id.text = kwargs.pop() ...
Auto Generated Code
377,699
def download(self, path): service_get_resp = requests.get(self.location, cookies={"session": self.session}) payload = service_get_resp.json() download_get_resp = requests.get(payload["content"]) with open(path, "wb") as config_file: config_file.write(download_get_r...
downloads a config resource to the path