Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,100
async def restart_stream(self): await self.response.release() await asyncio.sleep(self._error_timeout) await self.connect() logger.info("Reconnected to the stream") self._reconnecting = False return {: True}
Restart the stream on error
370,101
def ChunksExist(self, chunk_numbers): index_urns = { self.urn.Add(self.CHUNK_ID_TEMPLATE % chunk_number): chunk_number for chunk_number in chunk_numbers } res = {chunk_number: False for chunk_number in chunk_numbers} for metadata in aff4.FACTORY.Stat(index_urns): res[index_u...
Do we have this chunk in the index?
370,102
def keypress(self, size, key): key = super().keypress(size, key) num_tabs = len(self._widgets) if key == self._keys[]: self._tab_index = (self._tab_index - 1) % num_tabs self._update_tabs() elif key == self._keys[]: self._tab_index = (self._ta...
Handle keypresses for changing tabs.
370,103
def serialize_json_string(self, value): if not isinstance(value, six.string_types): return value if not value.startswith() or value.startswith(): return value try: return json.loads(value) except: retu...
Tries to load an encoded json string back into an object :param json_string: :return:
370,104
def end(target): if not isinstance(target, compat.greenlet): raise TypeError("argument must be a greenlet") if not target.dead: schedule(target) state.to_raise[target] = compat.GreenletExit()
schedule a greenlet to be stopped immediately :param target: the greenlet to end :type target: greenlet
370,105
def create_strategy(name=None): import logging from bonobo.execution.strategies.base import Strategy if isinstance(name, Strategy): return name if name is None: name = DEFAULT_STRATEGY logging.debug("Creating execution strategy {!r}...".format(name)) try: factory...
Create a strategy, or just returns it if it's already one. :param name: :return: Strategy
370,106
def etree(self, data, root=None): result = self.list() if root is None else root if isinstance(data, (self.dict, dict)): for key, value in data.items(): if isinstance(value, (self.dict, dict)): elem = self.element(key) if elem ...
Convert data structure into a list of etree.Element
370,107
def replace_from_url(self, url, **kwds): result = self._client.photo.replace_from_url(self, url, **kwds) self._replace_fields(result.get_fields())
Endpoint: /photo/<id>replace.json Import a photo from the specified URL to replace this photo.
370,108
def map(self, arg, na_action=None): new_values = super()._map_values( arg, na_action=na_action) return self._constructor(new_values, index=self.index).__finalize__(self)
Map values of Series according to input correspondence. Used for substituting each value in a Series with another value, that may be derived from a function, a ``dict`` or a :class:`Series`. Parameters ---------- arg : function, dict, or Series Mapping corre...
370,109
def huji_sample(orient_file, meths=, location_name=, samp_con="1", ignore_dip=True, data_model_num=3, samp_file="samples.txt", site_file="sites.txt", dir_path=".", input_dir_path=""): try: samp_con, Z = samp_con.split("-") except ValueError: ...
Convert HUJI sample file to MagIC file(s) Parameters ---------- orient_file : str input file name meths : str colon-delimited sampling methods, default FS-FD:SO-POM:SO-SUN for more options, see info below location : str location name, default "unknown" samp_con : s...
370,110
def matchBlocks(self, blocks, threshold=.5, *args, **kwargs): candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks)) matches = core.scoreDuplicates(candidate_records, self.data_model, self.clas...
Partitions blocked data and generates a sequence of clusters, where each cluster is a tuple of record ids Keyword arguments: blocks -- Sequence of tuples of records, where each tuple is a set of records covered by a blocking predicate threshold -- Number between 0 an...
370,111
def pre_run_cell(self, cellno, code): self.cellid = cellno import ast if findloop(ast.parse(code)): from acorn.logging.decoration import set_streamlining set_streamlining(True) ...
Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would produce lots of database entries and streamlines it to produce only a single entry. Args: cellno (int): the cell number that is about to be executed. co...
370,112
def _from_deprecated_string(cls, serialized): if serialized.count() != 2: raise InvalidKeyError(cls, serialized) return cls(*serialized.split(), deprecated=True)
Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been called to register a fallback class. Args: cls: T...
370,113
def remodel_run(self, c=None, **global_optargs): if not c: with remodel.connection.get_conn() as conn: return run(self, conn, **global_optargs) else: return run(self, c, **global_optargs)
Passes a connection from the connection pool so that we can call .run() on a query without an explicit connection
370,114
def check_variable_names(self, ds): msgs = [] count = 0 for k, v in ds.variables.items(): if in v.ncattrs(): count += 1 else: msgs.append("Variable missing standard_name attr".format(k)) return Result(BaseCheck.MEDIUM, ...
Ensures all variables have a standard_name set.
370,115
def joinRes(lstPrfRes, varPar, idxPos, inFormat=): if inFormat == : aryOut = np.zeros((0,)) for idxRes in range(0, varPar): aryOut = np.append(aryOut, lstPrfRes[idxRes][idxPos]) elif inFormat == : aryOut = np.zeros((0, lstPrfRes[0][idxPos].sh...
Join results from different processing units (here cores). Parameters ---------- lstPrfRes : list Output of results from parallelization. varPar : integer, positive Number of cores that were used during parallelization idxPos : integer, positive List position index that we e...
370,116
def ASHRAE_k(ID): rMineral fiber values = ASHRAE[ID] if values[2]: return values[2] else: R = values[3] t = values[4]/1000. return R_to_k(R, t)
r'''Returns thermal conductivity of a building or insulating material from a table in [1]_. Thermal conductivity is independent of temperature here. Many entries in the table are listed for varying densities, but the appropriate ID from the table must be selected to account for that. Parameters ---...
370,117
def add_localedir_translations(self, localedir): global _localedirs if localedir in self.localedirs: return self.localedirs.append(localedir) full_localedir = os.path.join(localedir, ) if os.path.exists(full_localedir): translation = self._new_gnu...
Merge translations from localedir.
370,118
def with_(self, *relations): if not relations: return self eagers = self._parse_relations(list(relations)) self._eager_load.update(eagers) return self
Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder
370,119
def bridge_exists(br): * cmd = .format(br) result = __salt__[](cmd) retcode = result[] return _retcode_to_bool(retcode)
Tests whether bridge exists as a real or fake bridge. Returns: True if Bridge exists, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_exists br0
370,120
def add_handler(self, message_type, handler): if message_type not in self._handlers: self._handlers[message_type] = [] if handler not in self._handlers[message_type]: self._handlers[message_type].append(handler)
Manage callbacks for message handlers.
370,121
def register_resource(mod, view, **kwargs): resource_name = view.__name__.lower()[:-8] endpoint = kwargs.get(, "{}_api".format(resource_name)) plural_resource_name = inflect.engine().plural(resource_name) path = kwargs.get(, plural_resource_name).strip() url = .format(path) setattr(view, , ...
Register the resource on the resource name or a custom url
370,122
def _write_bin(self, data, stream, byte_order): (len_t, val_t) = self.list_dtype(byte_order) data = _np.asarray(data, dtype=val_t).ravel() _write_array(stream, _np.array(data.size, dtype=len_t)) _write_array(stream, data)
Write data to a binary stream.
370,123
def _to_pypi(self, docs_base, release): url = None with self._zipped(docs_base) as handle: reply = requests.post(self.params[], auth=get_pypi_auth(), allow_redirects=False, files=dict(content=(self.cfg.project.name + , handle, )), ...
Upload to PyPI.
370,124
def create_BIP122_uri( chain_id: str, resource_type: str, resource_identifier: str ) -> URI: if resource_type != BLOCK: raise ValueError("Invalid resource_type. Must be one of ") elif not is_block_or_transaction_hash(resource_identifier): raise ValueError( "Invalid resource...
See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki
370,125
def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs): arc_node = ArcElementNode.objects.get(pk=instance.pk) logger.debug( % arc_node) if arc_node.arc_element_type == : logger.debug("root node. skipping...") else: logger.debug() ...
If an arc element is added to a story element node, add any missing elements or locations.
370,126
def httprettified(test=None, allow_net_connect=True): def decorate_unittest_TestCase_setUp(klass): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue setattr(klass, attr, decorate_c...
decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified ...
370,127
def parse_questions(raw_page): raw_questions = json.loads(raw_page) questions = raw_questions[] for question in questions: yield question
Parse a StackExchange API raw response. The method parses the API response retrieving the questions from the received items :param items: items from where to parse the questions :returns: a generator of questions
370,128
def unroll_state_saver(input_layer, name, state_shapes, template, lengths=None): state_saver = input_layer.bookkeeper.recurrent_state state_names = [STATE_NAME % name + % i for i in xrange(len(state_shapes))] if hasattr(state_saver, ): for state_name, state_shape in zip(state_names, state...
Unrolls the given function with state taken from the state saver. Args: input_layer: The input sequence. name: The name of this layer. state_shapes: A list of shapes, one for each state variable. template: A template with unbound variables for input and states that returns a RecurrentResult. ...
370,129
def mito(args): p = OptionParser(mito.__doc__) p.set_aws_opts(store="hli-mv-data-science/htang/mito-deletions") p.add_option("--realignonly", default=False, action="store_true", help="Realign only") p.add_option("--svonly", default=False, action="store_true", help=...
%prog mito chrM.fa input.bam Identify mitochondrial deletions.
370,130
def getMeta(self, uri): action = urlparse(uri).path mediaKey = self.cacheKey + + action mediaKey = mediaKey.replace(, ) meta = cache.get(mediaKey, None) if not meta: r = self.doQuery( + uri) if r.status_code == 200: ...
Return meta information about an action. Cache the result as specified by the server
370,131
def get_api_root_view(self, api_urls=None): api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) class APIRootView(views.APIView): _ignor...
Return a basic root view.
370,132
def should_skip(filename, config, path=): for skip_path in config[]: if posixpath.abspath(posixpath.join(path, filename)) == posixpath.abspath(skip_path.replace(, )): return True position = os.path.split(filename) while position[1]: if position[1] in config[]: r...
Returns True if the file should be skipped based on the passed in settings.
370,133
def p_expr_list_assign(p): p[0] = ast.ListAssignment(p[3], p[6], lineno=p.lineno(1))
expr : LIST LPAREN assignment_list RPAREN EQUALS expr
370,134
def get_parent_id(chebi_id): if len(__PARENT_IDS) == 0: __parse_compounds() return __PARENT_IDS[chebi_id] if chebi_id in __PARENT_IDS else float()
Returns parent id
370,135
def libvlc_video_get_size(p_mi, num): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,), (2,), (2,),), None, ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)) return f(p_mi, num)
Get the pixel dimensions of a video. @param p_mi: media player. @param num: number of the video (starting from, and most commonly 0). @return: px pixel width, py pixel height.
370,136
def option(self, key, value=None, **kwargs): if not isinstance(self._container, Section): raise ValueError("Options can only be added inside a section!") option = Option(key, value, container=self._container, **kwargs) option.value = value self._container.structure.i...
Creates a new option inside a section Args: key (str): key of the option value (str or None): value of the option **kwargs: are passed to the constructor of :class:`Option` Returns: self for chaining
370,137
def load_indexes(self): for collection_name in INDEXES: existing_indexes = self.indexes(collection_name) indexes = INDEXES[collection_name] for index in indexes: index_name = index.document.get() if index_name in existing_indexes: ...
Add the proper indexes to the scout instance. All indexes are specified in scout/constants/indexes.py If this method is utilised when new indexes are defined those should be added
370,138
def _stripe_object_to_subscription_items(cls, target_cls, data, subscription): items = data.get("items") if not items: return [] subscriptionitems = [] for item_data in items.get("data", []): item, _ = target_cls._get_or_create_from_stripe_object(item_data, refetch=False) subscriptionitems.append(...
Retrieves SubscriptionItems for a subscription. If the subscription item doesn't exist already then it is created. :param target_cls: The target class to instantiate per invoice item. :type target_cls: ``SubscriptionItem`` :param data: The data dictionary received from the Stripe API. :type data: dict :pa...
370,139
def get_input_list(self): inputs = [] * len(self.command[]) for key in self.command[]: inputs[self.command[][key][]] = {"key":key, "name":self.command[][key][]} return inputs
Description: Get input list Returns an ordered list of all available input keys and names
370,140
def support_in_progress_warcs(): _orig_prefix_resolver_call = pywb.warc.pathresolvers.PrefixResolver.__call__ def _prefix_resolver_call(self, filename, cdx=None): raw_results = _orig_prefix_resolver_call(self, filename, cdx) results = [] for warc_path in raw_results: res...
Monkey-patch pywb.warc.pathresolvers.PrefixResolver to include warcs still being written to (warcs having ".open" suffix). This way if a cdx entry references foo.warc.gz, pywb will try both foo.warc.gz and foo.warc.gz.open.
370,141
def get_package(self): directory = self.directory develop = self.develop scmtype = self.scmtype self.scm = self.scms.get_scm(scmtype, directory) if self.scm.is_valid_url(directory): directory = self.urlparser.abspath(directory) self.remoteurl =...
Get the URL or sandbox to release.
370,142
def nvmlDeviceGetTemperature(handle, sensor): r c_temp = c_uint() fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperature") ret = fn(handle, _nvmlTemperatureSensors_t(sensor), byref(c_temp)) _nvmlCheckReturn(ret) return bytes_to_str(c_temp.value)
r""" /** * Retrieves the current temperature readings for the device, in degrees C. * * For all products. * * See \ref nvmlTemperatureSensors_t for details on available temperature sensors. * * @param device The identifier of the target device * ...
370,143
def rangeChange(self, pw, ranges): if hasattr(ranges, ): yrange_size = ranges[1][1] - ranges[1][0] stim_x, stim_y = self.stimPlot.getData() if stim_y is not None: stim_height = yrange_size*STIM_HEIGHT stim...
Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a slot for the undocumented pyqtgraph signal sigRangeChanged. From what I can tell the arguments are: :param pw: reference to the emitting object (plot widget in my ...
370,144
def rollback(self): for p in self._moves: logging.info("Moving to %s\n from %s", *p) for new_path, path in self._moves: try: logger.debug(, new_path, path) if os.path.isfile(new_path): os.unlink(new_path) ...
Undoes the uninstall by moving stashed files back.
370,145
def add_user_js(self, js_list): if isinstance(js_list, string_types): js_list = [js_list] for js_path in js_list: if js_path and js_path not in self.user_js: if js_path.startswith("http:"): self.user_js.append({ ...
Adds supplementary user javascript files to the presentation. The ``js_list`` arg can be either a ``list`` or a string.
370,146
def install(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None): prog_name = prog_name or click.get_current_context().find_root().info_name shell = shell or get_auto_shell() if append is None and path is not None: append = True if append is not None: m...
Install the completion Parameters ---------- shell : Shell The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None) prog_name : str The program name on the command line. It will be automatically computed if the value is None (...
370,147
def _get_bnl(self, C_AMP, vs30): bnl = np.zeros_like(vs30) if np.all(vs30 >= self.CONSTS["Vref"]): return bnl bnl[vs30 < self.CONSTS["v1"]] = C_AMP["b1sa"] idx = np.logical_and(vs30 > self.CONSTS["v1"], vs30 <= ...
Gets the nonlinear term, given by equation 8 of Atkinson & Boore 2006
370,148
def from_ros_pose_msg(pose_msg, from_frame=, to_frame=): quaternion = np.array([pose_msg.orientation.w, pose_msg.orientation.x, pose_msg.orientation.y, pose_m...
Creates a RigidTransform from a ROS pose msg. Parameters ---------- pose_msg : :obj:`geometry_msgs.msg.Pose` ROS pose message
370,149
def parse_nem_file(nem_file) -> NEMFile: reader = csv.reader(nem_file, delimiter=) return parse_nem_rows(reader, file_name=nem_file)
Parse NEM file and return meter readings named tuple
370,150
def _report_problem(self, problem, level=logging.ERROR): problem = self.basename + + problem if self._logger.isEnabledFor(level): self._problematic = True if self._check_raises: raise DapInvalid(problem) self._logger.log(level, problem)
Report a given problem
370,151
def read_namespaced_pod_preset(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.read_namespaced_pod_preset_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_pod_preset_with_http_info(name, namespace, *...
read_namespaced_pod_preset # noqa: E501 read the specified PodPreset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_pod_preset(name, namespace, async_req=True) ...
370,152
def wait_for_edge(channel, trigger, timeout=-1): _check_configured(channel, direction=IN) pin = get_gpio_pin(_mode, channel) if event.blocking_wait_for_edge(pin, trigger, timeout) is not None: return channel
This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param trigger: The event to detect, one of: :py:attr:`GPIO.RIS...
370,153
def list_of_list(self): ret = [[row.get(key, ) for key in self._col_names] for row in self] return ReprListList(ret, col_names=self._col_names, col_types=self._col_types, width_limit=self._width_limit, digits=se...
This will convert the data from a list of dict to a list of list :return: list of dict
370,154
def transform(row, table): data = row._asdict() data["link"] = urljoin("https://pt.wikipedia.org", data["link"]) data["name"], data["state"] = regexp_city_state.findall(data["name"])[0] return data
Transform row "link" into full URL and add "state" based on "name"
370,155
def _create_file_if_needed(self): if not os.path.exists(self._filename): old_umask = os.umask(0o177) try: open(self._filename, ).close() finally: os.umask(old_umask)
Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created.
370,156
def push_stream(cache, user_id, stream): stack = cache.get(user_id) if stack is None: stack = [] if stream: stack.append(stream) return cache.set(user_id, stack) return None
Push a stream onto the stream stack in cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :param stream: stream object to push onto stack :return: True on successful update, False if failed to update, None if invalid input wa...
370,157
def cancel_ride(self, ride_id, cancel_confirmation_token=None): args = { "cancel_confirmation_token": cancel_confirmation_token } endpoint = .format(ride_id) return self._api_call(, endpoint, args=args)
Cancel an ongoing ride on behalf of a user. Params ride_id (str) The unique ID of the Ride Request. cancel_confirmation_token (str) Optional string containing the cancellation confirmation token. Returns (Response) A Res...
370,158
def _initialize_from_dict(self, data): self._json = data self._validate() for name, value in self._json.items(): if name in self._properties: if in self._properties[name]: if in self._properties[name][]: value = ...
Loads serializer from a request object
370,159
def create_serving_logger() -> Logger: logger = getLogger() if logger.level == NOTSET: logger.setLevel(INFO) logger.addHandler(serving_handler) return logger
Create a logger for serving. This creates a logger named quart.serving.
370,160
def listen_for_events(): import_event_modules() conn = redis_connection.get_connection() pubsub = conn.pubsub() pubsub.subscribe("eventlib") for message in pubsub.listen(): if message[] != : continue data = loads(message["data"]) if in data: even...
Pubsub event listener Listen for events in the pubsub bus and calls the process function when somebody comes to play.
370,161
def get_content_hashes(image_path, level=None, regexp=None, include_files=None, tag_root=True, level_filter=None, skip_files=None, version=None, ...
get_content_hashes is like get_image_hash, but it returns a complete dictionary of file names (keys) and their respective hashes (values). This function is intended for more research purposes and was used to generate the levels in the first place. If include_sizes is True, we include a second data structur...
370,162
def inverse_mod( a, m ): if a < 0 or m <= a: a = a % m c, d = a, m uc, vc, ud, vd = 1, 0, 0, 1 while c != 0: q, c, d = divmod( d, c ) + ( c, ) uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc assert d == 1 if ud > 0: return ud else: return ud + m
Inverse of a mod m.
370,163
def fasta(self): logging.info() for sample in self.runmetadata.samples: if GenObject.isattr(sample[self.analysistype], ): sample[self.analysistype].pointfinderfasta = \ os.path.join(sample[self.analysistype].outputdir...
Create FASTA files of the PointFinder results to be fed into PointFinder
370,164
async def addRelation(self, endpoint1, endpoint2): endpoints = [endpoint1, endpoint2] for i in range(len(endpoints)): parts = endpoints[i].split() parts[0] = self.resolve(parts[0]) endpoints[i] = .join(parts) log.info(, *endpoints) r...
:param endpoint1 string: :param endpoint2 string: Endpoint1 and Endpoint2 hold relation endpoints in the "application:interface" form, where the application is always a placeholder pointing to an application change, and the interface is optional. Examples are "$de...
370,165
def transformer_wikitext103_l4k_memory_v0(): hparams = transformer_wikitext103_l4k_v0() hparams.split_targets_chunk_length = 64 hparams.split_targets_max_chunks = 64 hparams.split_targets_strided_training = True hparams.add_hparam("memory_type", "transformer_xl") target_tokens_per_batch = 4096 ...
HParams for training languagemodel_wikitext103_l4k with memory.
370,166
def parsed_stack(self): if in self._values: return self._values[] self._values[] = copy.deepcopy(self._defaults[]) return self._values[]
The parsed_stack property. Returns: (list). the property value. (defaults to: [])
370,167
def nucmer(args): from itertools import product from jcvi.apps.grid import MakeManager from jcvi.formats.base import split p = OptionParser(nucmer.__doc__) p.add_option("--chunks", type="int", help="Split both query and subject into chunks") p.set_params(prog="nucmer", pa...
%prog nucmer ref.fasta query.fasta Run NUCMER using query against reference. Parallel implementation derived from: <https://github.com/fritzsedlazeck/sge_mummer>
370,168
def _metrics_get_endpoints(options): if bool(options.start) ^ bool(options.end): log.error() sys.exit(1) if options.start and options.end: start = options.start end = options.end else: end = datetime.utcnow() start = end - timedelta(options.days) re...
Determine the start and end dates based on user-supplied options.
370,169
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE, exportable=True, password=, saltenv=): cerpfx*salt://cert.cer cmd = list() thumbprint = None store_path = r.f...
Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12. :param str context: The name of the certificate store location context. :par...
370,170
def fit( self, df, duration_col=None, event_col=None, show_progress=False, initial_point=None, strata=None, step_size=None, weights_col=None, cluster_col=None, robust=False, batch_mode=None, ): if durati...
Fit the Cox proportional hazard model to a dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns `duration_col` and `event_col` (see below), covariates columns, and special columns (weights, strata). `duration_col` refers to ...
370,171
def _user_yes_no_query(self, question): sys.stdout.write( % question) while True: try: return strtobool(raw_input().lower()) except ValueError: sys.stdout.write(y\n\)
Helper asking if the user want to download the file Note: Dowloading huge file can take a while
370,172
def advise(self, name, f, *a, **kw): if name is None: return advice = (f, a, kw) debug = self.get(DEBUG) frame = currentframe() if frame is None: logger.debug() else: if name in self._called: self.__advice_st...
Add an advice that will be handled later by the handle method. Arguments: name The name of the advice group f A callable method or function. The rest of the arguments will be passed as arguments and keyword arguments to f when it's invoked.
370,173
def rpc_call(payload): corr_id = RPC_CLIENT.send_request(payload) while RPC_CLIENT.queue[corr_id] is None: sleep(0.1) return RPC_CLIENT.queue[corr_id]
Simple Flask implementation for making asynchronous Rpc calls.
370,174
def sparse_var(X): Xc = X.copy() Xc.data **= 2 return np.array(Xc.mean(axis=0) - np.power(X.mean(axis=0), 2))[0]
Compute variance from :param X: :return:
370,175
def _create_state_data(self, context, resp_args, relay_state): if "name_id_policy" in resp_args and resp_args["name_id_policy"] is not None: resp_args["name_id_policy"] = resp_args["name_id_policy"].to_string().decode("utf-8") return {"resp_args": resp_args, "relay_state": relay_sta...
Returns a dict containing the state needed in the response flow. :type context: satosa.context.Context :type resp_args: dict[str, str | saml2.samlp.NameIDPolicy] :type relay_state: str :rtype: dict[str, dict[str, str] | str] :param context: The current context :param re...
370,176
def Parse(self, parser_mediator): file_entry = parser_mediator.GetFileEntry() if not file_entry: raise errors.UnableToParseFile() parser_mediator.AppendToParserChain(self) try: self.ParseFileEntry(parser_mediator, file_entry) finally: parser_mediator.PopFromParserChain()
Parsers the file entry and extracts event objects. Args: parser_mediator (ParserMediator): a parser mediator. Raises: UnableToParseFile: when the file cannot be parsed.
370,177
def get_variable_groups(self, project, group_name=None, action_filter=None, top=None, continuation_token=None, query_order=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) query_parameters = {} if group_name is not No...
GetVariableGroups. [Preview API] Get variable groups. :param str project: Project ID or project name :param str group_name: Name of variable group. :param str action_filter: Action filter for the variable group. It specifies the action which can be performed on the variable groups. ...
370,178
def to_output(self, value): return {self.name: [self.inner.to_output(v)[self.name] for v in value]}
Convert value to process output format.
370,179
def comb(delay, tau=inf): alpha = e ** (-delay / tau) return 1 / (1 - alpha * z ** -delay)
Feedback comb filter for a given time constant (and delay). ``y[n] = x[n] + alpha * y[n - delay]`` Parameters ---------- delay : Feedback delay (lag), in number of samples. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples, which allows finding ``alpha = e ** (-delay / tau)`...
370,180
def update_hslice(self, blob): nmove, nreflect = blob[], blob[] ncontract = blob.get(, 0) fmove = (1. * nmove) / (nmove + nreflect + ncontract + 2) norm = max(self.fmove, 1. - self.fmove) self.scale *= math.exp((fmove - self.fmove) / norm)
Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.
370,181
def get_graphics(vm_, **kwargs): * conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics
Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to...
370,182
def parameterized_expectations(model, verbose=False, initial_dr=None, pert_order=1, with_complementarities=True, grid={}, distribution={}, maxit=100, tol=1e-8, inner_maxit=10, direct=False): ...
Find global solution for ``model`` via parameterized expectations. Controls must be expressed as a direct function of equilibrium objects. Algorithm iterates over the expectations function in the arbitrage equation. Parameters: ---------- model : NumericModel ``dtcscc`` model to be solved ...
370,183
def in_repo(self, filepath): filepath = set(filepath.replace(, ).split()) for p in (, , , , ): if p in filepath: return True return False
This excludes repository directories because they cause some exceptions occationally.
370,184
def def_linear(fun): defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs: fun(*subval(args, argnum, g), **kwargs))
Flags that a function is linear wrt all args
370,185
def start_semester_view(request): page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) semester_form = SemesterForm( data=request.POST or None, initial={ "year": year, "season":...
Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester.
370,186
def join(*paths): r paths_with_drives = map(os.path.splitdrive, paths) drives, paths = zip(*paths_with_drives) drive = next(filter(None, reversed(drives)), ) return os.path.join(drive, os.path.join(*paths))
r""" Wrapper around os.path.join that works with Windows drive letters. >>> join('d:\\foo', '\\bar') 'd:\\bar'
370,187
def get_paths_cfg( sys_file=, platform_file=.format(sys.platform), user_file= ): sys_config_dir = os.path.dirname(__file__) sys_config_path = os.path.join(sys_config_dir, sys_file) platform_config_path = os.path.join(sys_config_dir, platform_file) user_config_path = os.environ.get(, N...
>>> os.environ['HOME'] = '/tmp/test' >>> get_paths_cfg()['user'] '/tmp/test/.pythranrc' >>> os.environ['HOME'] = '/tmp/test' >>> os.environ['XDG_CONFIG_HOME'] = '/tmp/test2' >>> get_paths_cfg()['user'] '/tmp/test2/.pythranrc' >>> os.environ['HOME'] = '/tmp/test' >>> os.environ['XDG_CONFI...
370,188
def _get(self, end_point, params=None, **kwargs): return self._request(requests.get, end_point, params, **kwargs)
Send a HTTP GET request to a Todoist API end-point. :param end_point: The Todoist API end-point. :type end_point: str :param params: The required request parameters. :type params: dict :param kwargs: Any optional parameters. :type kwargs: dict :return: The HTTP r...
370,189
def transform_annotation(self, ann, duration): agree intervals, values = ann.to_interval_values() intervals, values = adjust_intervals(intervals, values, t_min=0, t_max=duration) ids, _ = index_labels(values) rate = float(s...
Apply the structure agreement transformation. Parameters ---------- ann : jams.Annotation The segment annotation duration : number > 0 The target duration Returns ------- data : dict data['agree'] : np.ndarray, shape=(n, n), ...
370,190
def get_training_image_text_data_iters(source_root: str, source: str, target: str, validation_source_root: str, validation_source: str, validation_target: str, voca...
Returns data iterators for training and validation data. :param source_root: Path to source images since the file in source contains relative paths. :param source: Path to source training data. :param target: Path to target training data. :param validation_source_root: Path to validation source images ...
370,191
def detect_worksheets(archive): content_types = read_content_types(archive) valid_sheets = dict((path, ct) for ct, path in content_types if ct == WORKSHEET_TYPE) rels = dict(read_rels(archive)) for sheet in read_sheets(archive): rel = rels[sheet[]] rel[] = sheet[...
Return a list of worksheets
370,192
def encrypt_files(selected_host, only_link, file_name): if ENCRYPTION_DISABLED: print() exit() passphrase = % random.randrange(16**30) source_filename = file_name cmd = \ .format(source_filename) encrypted_output = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, std...
Encrypts file with gpg and random generated password
370,193
def _fetch_seq_ensembl(ac, start_i=None, end_i=None): url_fmt = "http://rest.ensembl.org/sequence/id/{ac}" url = url_fmt.format(ac=ac) r = requests.get(url, headers={"Content-Type": "application/json"}) r.raise_for_status() seq = r.json()["seq"] return seq if (start_i is None or end_i is N...
Fetch the specified sequence slice from Ensembl using the public REST interface. An interbase interval may be optionally provided with start_i and end_i. However, the Ensembl REST interface does not currently accept intervals, so the entire sequence is returned and sliced locally. >> len(_fetc...
370,194
def set_locked_variable(self, key, access_key, value): return self.set_variable(key, value, per_reference=False, access_key=access_key)
Set an already locked global variable :param key: the key of the global variable to be set :param access_key: the access key to the already locked global variable :param value: the new value of the global variable
370,195
def register_task_with_maintenance_window(WindowId=None, Targets=None, TaskArn=None, ServiceRoleArn=None, TaskType=None, TaskParameters=None, Priority=None, MaxConcurrency=None, MaxErrors=None, LoggingInfo=None, ClientToken=None): pass
Adds a new task to a Maintenance Window. See also: AWS API Documentation :example: response = client.register_task_with_maintenance_window( WindowId='string', Targets=[ { 'Key': 'string', 'Values': [ 'string', ...
370,196
def init_db(sqlalchemy_url): engine = create_engine(sqlalchemy_url) start = time.time() metadata.create_all(engine) return time.time() - start
Initialize database with gsshapy tables
370,197
def invoke(self, results): args = [results.get(d) for d in self.deps] return self.component(*args)
Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration.
370,198
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True): boot_dist = [] arr = N.zeros(data.shape) for i in range(n): if symmetric: arr = N.random.randn(*data.shape)*std else: arr[:,-1] = N.random.randn(data.shape[0])*std ...
Bootstrap by adding noise
370,199
def _get_total_services_problems_unhandled(self): return sum(1 for s in self.services if s.is_problem and not s.problem_has_been_acknowledged)
Get the number of services that are a problem and that are not acknowledged :return: number of problem services which are not acknowledged :rtype: int