Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
369,800
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): with tf.variable_scope(name): n = filter_size * filter_size * out_filters kernel = tf.get_variable( "DW", [filter_size, filter_size, in_filters, out_filters], tf.float32, ...
Convolution.
369,801
def get_comment_ancestors(comID, depth=None): if depth == 0: return [] res = run_sql( , (comID, )) if res: parent_comID = res[0][0] if parent_comID == 0: return [] parent_ancestors = [] if depth: depth -= 1 ...
Returns the list of ancestors of the given comment, ordered from oldest to newest ("top-down": direct parent of comID is at last position), up to given depth :param comID: the ID of the comment for which we want to retrieve ancestors :type comID: int :param depth: the maximum of levels up from the ...
369,802
def run(self): logger.info("scheduler starting...") while not self._quit: try: time.sleep(self.LOOP_INTERVAL) self.run_once() self._exceptions = 0 except KeyboardInterrupt: break except Exceptio...
Start scheduler loop
369,803
async def sentinel_monitor(self, name, ip, port, quorum): "Add a new master to Sentinel to be monitored" return await self.execute_command(, name, ip, port, quorum)
Add a new master to Sentinel to be monitored
369,804
def get_xy_from_linecol(self, line, col, offsets, factors): loff, coff = offsets lfac, cfac = factors x__ = (col - coff) / cfac * 2**16 y__ = (line - loff) / lfac * 2**16 return x__, y__
Get the intermediate coordinates from line & col. Intermediate coordinates are actually the instruments scanning angles.
369,805
def del_repo(repo, **kwargs): * _check_apt() is_ppa = False if repo.startswith() and __grains__[] in (, , ): is_ppa = True dist = __grains__[] if not HAS_SOFTWAREPROPERTIES: _warn_software_properties(repo) owner_name, ppa_name = repo[4:]....
Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo passed in must be a fully formed repository definition string. ...
369,806
def get_volumes_for_sdc(self, sdcObj): self.conn.connection._check_login() all_volumes = [] response = self.conn.connection._do_get("{}/{}{}/{}".format(self.conn.connection._api_url, , sdcObj.id, )).json() for sdc_volume in response: all_volumes.append( ...
:param sdcObj: SDC object :return: list of Volumes attached to SDC :rtyoe: ScaleIO Volume object
369,807
def _client_tagged(self, tags): name = self.client_name.lower() tags = [t.lower() for t in tags] if name not in tags: bot.error( %(name, tags)) sys.exit(1)
ensure that the client name is included in a list of tags. This is important for matching builders to the correct client. We exit on fail. Parameters ========== tags: a list of tags to look for client name in
369,808
def _get_phantom_root_catalog(self, cat_name, cat_class): catalog_map = make_catalog_map(cat_name, identifier=PHANTOM_ROOT_IDENTIFIER) return cat_class(osid_object_map=catalog_map, runtime=self._runtime, proxy=self._proxy)
Get's the catalog id corresponding to the root of all implementation catalogs.
369,809
def _validate_namespace(self, namespace): if self._namespace_regex.fullmatch(namespace) is None: LOGGER.debug(, namespace) raise _ResponseFailed(self._status.INVALID_ADDRESS)
Validates a namespace, raising a ResponseFailed error if invalid. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sent with the response.
369,810
def set_env(envName, envValue): os.environ[envName] = os.environ[envName] + + envValue
่ฎพ็ฝฎ็Žฏๅขƒๅ˜้‡ :params envName: envๅๅญ— :params envValue: ๅ€ผ
369,811
def get_neg_one_task_agent(generators, market, nOffer, maxSteps): env = pyreto.discrete.MarketEnvironment(generators, market, nOffer) task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps) agent = pyreto.util.NegOneAgent(env.outdim, env.indim) return task, agent
Returns a task-agent tuple whose action is always minus one.
369,812
def upload_job_chunk_list(self, upload_job_id, **kwargs): kwargs[] = True if kwargs.get(): return self.upload_job_chunk_list_with_http_info(upload_job_id, **kwargs) else: (data) = self.upload_job_chunk_list_with_http_info(upload_job_id, **kwargs) ...
List all metadata for uploaded chunks # noqa: E501 List all metadata for uploaded chunks # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.upload_job_chunk_list(upload_job_id, asyn...
369,813
def get_session(): if os.environ.get("OS_IDENTITY_API_VERSION") == "3": logging.info("Creating a v3 Keystone Session") auth = v3.Password( auth_url=os.environ["OS_AUTH_URL"], username=os.environ["OS_USERNAME"], password=os.environ["OS_PASSWORD"], ...
Build the session object.
369,814
def class_statistics(TP, TN, FP, FN, classes, table): TPR = {} TNR = {} PPV = {} NPV = {} FNR = {} FPR = {} FDR = {} FOR = {} ACC = {} F1_SCORE = {} MCC = {} BM = {} MK = {} PLR = {} NLR = {} DOR = {} POP = {} P = {} N = {} TOP = {} ...
Return all class statistics. :param TP: true positive dict for all classes :type TP : dict :param TN: true negative dict for all classes :type TN : dict :param FP: false positive dict for all classes :type FP : dict :param FN: false negative dict for all classes :type FN : dict :par...
369,815
def set_settings_file_path(self, settings_file_path): if not isinstance(settings_file_path, basestring): raise TypeError("settings_file_path can only be an instance of type basestring") progress = self._call("setSettingsFilePath", in_p=[settings_file_path]) ...
Currently, it is an error to change this property on any machine. Later this will allow setting a new path for the settings file, with automatic relocation of all files (including snapshots and disk images) which are inside the base directory. This operation is only allowed when there ar...
369,816
def define_options(default_conf): default = {} with open(default_conf, ) as f: exec_in(native_str(f.read()), {}, default) for name, value in default.iteritems(): if name in options: setattr(options, name, value) ...
Define the options from default.conf dynamically
369,817
def get_station_by_name(self, station_name, num_minutes=None, direction=None, destination=None, stops_at=None): url = self.api_base_url + params = { ...
Returns all trains due to serve station `station_name`. @param station_code @param num_minutes. Only trains within this time. Between 5 and 90 @param direction Filter by direction. Northbound or Southbound @param destination Filter by name of the destination stations @param stops...
369,818
def set(self): self._is_set = True scheduler.state.awoken_from_events.update(self._waiters) del self._waiters[:]
set the event to triggered after calling this method, all greenlets waiting on the event will be rescheduled, and calling :meth:`wait` will not block until :meth:`clear` has been called
369,819
def get_experiments(self, workspace_id): api_path = self.EXPERIMENTS_URI_FMT.format(workspace_id) return self._send_get_req(api_path)
Runs HTTP GET request to retrieve the list of experiments.
369,820
def remove_interface_router(self, router, body=None): return self.put((self.router_path % router) + "/remove_router_interface", body=body)
Removes an internal network interface from the specified router.
369,821
def index(self, block_start, block_end): log.debug("BEGIN Processing zonefiles discovered since last re-indexing") t1 = time.time() self.index_discovered_zonefiles(block_end) t2 = time.time() log.debug("END Processing zonefiles discovered since last re-indexing ({} secon...
Entry point for indexing: * scan the blockchain from start_block to end_block and make sure we're up-to-date * process any newly-arrived zone files and re-index the affected subdomains
369,822
def cal_dist_between_2_coord_frame_aligned_boxes(box1_pos, box1_size, box2_pos, box2_size): box1_x_min, box1_y_min = box1_pos box1_x_max, box1_y_max = (box1_pos[0] + box1_size[0], box1_pos[1] + box1_size[1]) box2_x_min, box2_y_min = box2_pos box2_x_max, box2_y_max = (box2_pos[0] + box2_size[0], box...
Calculate Euclidean distance between two boxes those edges are parallel to the coordinate axis The function decides condition based which corner to corner or edge to edge distance needs to be calculated. :param tuple box1_pos: x and y position of box 1 :param tuple box1_size: x and y size of box 1 :pa...
369,823
def p_int(self, tree): tree.value = int(tree.attr) tree.svalue = tree.attr
V ::= INTEGER
369,824
def get_object(self, id, **args): return self.request("{0}/{1}".format(self.version, id), args)
Fetches the given object from the graph.
369,825
def update_firewall_rule(self, firewall_rule, protocol=None, action=None, name=None, description=None, ip_version=None, source_ip_address=None, destination_ip_address=None, source_port=None, destination_port=None, shared=None, enable...
Update a firewall rule
369,826
def multi_label_morphology(image, operation, radius, dilation_mask=None, label_list=None, force=False): if (label_list is None) or (len(label_list) == 1): label_list = np.sort(np.unique(image[image > 0])) if (len(label_list) > 200) and (not force): raise ValueError( ...
Morphology on multi label images. Wraps calls to iMath binary morphology. Additionally, dilation and closing operations preserve pre-existing labels. The choices of operation are: Dilation: dilates all labels sequentially, but does not overwrite original labels. This reduces dependence on the ...
369,827
def _compute_missing_deps(self, src_tgt, actual_deps): analyzer = self._analyzer def must_be_explicit_dep(dep): return (dep not in analyzer.bootstrap_jar_classfiles and not dep.startswith(DistributionLocator.cached().real_home)) def target_or_java_dep_in_targets(targe...
Computes deps that are used by the compiler but not specified in a BUILD file. These deps are bugs waiting to happen: the code may happen to compile because the dep was brought in some other way (e.g., by some other root target), but that is obviously fragile. Note that in practice we're OK with reliance ...
369,828
def untranslated_policy(self, default): return self.generator.settings.get(self.info.get(, None), default)
Get the policy for untranslated content
369,829
def servicegroup_server_enable(sg_name, s_name, s_port, **connection_args): *serviceGroupNameserverNameserverPort ret = True server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args) if server is None: return False nitro = _connect(**connection_args) if nitro is None:...
Enable a server:port member of a servicegroup CLI Example: .. code-block:: bash salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort'
369,830
def as_fstring(text): for quote in (, " if quote not in text and not text.endswith(quote[0]): return + quote + text + quote pieces = split_fstring(text) if not any("finvalid expression in {pieces[idx]}{}.format(, )'
expansion with python f-string, usually ok, but with the case of ' inside expressions, adding repr will add backslash to it and cause trouble.
369,831
def getCitiesDrawingXML(points): xml = "" for p in points: x = str(p.x) z = str(p.y) xml += + x + + z + xml += + x + + z + return xml
Build an XML string that contains a square for each city
369,832
def get_legal_params(self, method): if method not in self.client.meta.method_to_api_mapping: return [] api = self.client.meta.method_to_api_mapping[method] shape = self.client.meta.service_model.operation_model(api).input_shape if shape is None: return [] return shape....
Given a API name, list all legal parameters using boto3 service model.
369,833
def wait(self): text = input( "Press return for next %d result%s (or type ):" % (self.pagesize, plural(self.pagesize)) ) if text: if text.lower() in ["a", "all"]: self._pagesize = 0 elif text.isdigit(): self...
Block for user input
369,834
def get_name_cost( db, name ): lastblock = db.lastblock namespace_id = get_namespace_from_name( name ) if namespace_id is None or len(namespace_id) == 0: log.debug("No namespace " % namespace_id) return None namespace = db.get_namespace( namespace_id ) if namespace is None: ...
Get the cost of a name, given the fully-qualified name. Do so by finding the namespace it belongs to (even if the namespace is being imported). Return {'amount': ..., 'units': ...} on success Return None if the namespace has not been declared
369,835
def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): {"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]} conn = _get_conn(region=region, key=key, keyid=keyid, pr...
Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
369,836
def paintEvent(self, event): painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
Reimplemented to paint the background panel.
369,837
def fixed_crop(src, x0, y0, w, h, size=None, interp=2): out = nd.slice(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2]))) if size is not None and (w, h) != size: sizes = (h, w, size[1], size[0]) out = imresize(out, *size, interp=_get_interp_method(interp, sizes)) return ou...
Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int Width of the cropping area h : int Height of...
369,838
def autocomplete(): if not in os.environ: return cwords = os.environ[].split()[1:] cword = int(os.environ[]) try: current = cwords[cword-1] except IndexError: current = load_all_commands() subcommands = [cmd for cmd, cls in command_dict.items() if not cls....
Command and option completion for the main option parser (and options) and its subcommands (and options). Enable by sourcing one of the completion shell scripts (bash or zsh).
369,839
def write(self, output): view_str = output.encode(, ) if (len(view_str) > 0): self.m_ser.write(view_str) self.m_ser.flush() self.m_ser.reset_input_buffer() time.sleep(self.m_force_wait) pass
Passthrough for pyserial Serial.write(). Args: output (str): Block to write to port
369,840
def _parse_urls(self, match): mat = match.group(0) domain = match.group(5) if domain[0] in : return mat if len(domain) == 5 \ and domain[-4:].lower() in (, , ) \ and not domain.lower() in IANA_ONE_LETTER_DOMAINS: ...
Parse URLs.
369,841
def via_upnp(): ssdp_list = ssdp_discover("ssdp:all", timeout=5) bridges_from_ssdp = [u for u in ssdp_list if in u.server] logger.info(, len(ssdp_list), len(bridges_from_ssdp)) found_bridges = {} for bridge in bridges_from_ssdp: serial, bri...
Use SSDP as described by the Philips guide
369,842
def create_model(cls, data: dict, fields=None): if fields is None: fields = set(cls._fields.keys()) else: if not isinstance(fields, set): fields = set(fields) new_keys = set(data.keys()) - fields if new_keys: for new_key in new...
Creates model instance from data (dict).
369,843
def get_primitives_paths(): primitives_paths = list() entry_points = pkg_resources.iter_entry_points() for entry_point in entry_points: if entry_point.name == : path = entry_point.load() primitives_paths.append(path) return _PRIMITIVES_PATHS + primitives_paths
Get the list of folders where the primitives will be looked for. This list will include the value of any `entry_point` named `jsons_path` published under the name `mlprimitives`. An example of such an entry point would be:: entry_points = { 'mlprimitives': [ 'jsons_pat...
369,844
def build_beta_part(ruleset, alpha_terminals): for rule in ruleset: if isinstance(rule[0], OR): for subrule in rule[0]: wire_rule(rule, alpha_terminals, lhs=subrule) else: wire_rule(rule, alpha_terminals, lhs=rule)
Given a set of already adapted rules, and a dictionary of patterns and alpha_nodes, wire up the beta part of the RETE network.
369,845
def vector_normalize(vector_in, decimals=18): try: if vector_in is None or len(vector_in) == 0: raise ValueError("Input vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") ...
Generates a unit vector from the input. :param vector_in: vector to be normalized :type vector_in: list, tuple :param decimals: number of significands :type decimals: int :return: the normalized vector (i.e. the unit vector) :rtype: list
369,846
def submit(self, pixels, queue=None, debug=False, configfile=None): batch = self.config[].get(,self.config[]) queue = batch[] if queue is None else queue self.batch = ugali.utils.batch.batchFactory(queue,**batch[]) self.batch.max_jobs = batch.get(,200) ...
Submit the likelihood job for the given pixel(s).
369,847
def includeme(config): settings = config.registry.settings if asbool(settings.get(, True)): LOGGER.debug() config.include() config.include() config.include() config.include() config.add_xmlrpc_endpoint(, ) ...
The callable makes it possible to include rpcinterface in a Pyramid application. Calling ``config.include(twitcher.rpcinterface)`` will result in this callable being called. Arguments: * ``config``: the ``pyramid.config.Configurator`` object.
369,848
def assignmentComplete(): a = TpPd(pd=0x6) b = MessageType(mesType=0x29) c = RrCause() packet = a / b / c return packet
ASSIGNMENT COMPLETE Section 9.1.3
369,849
def upload_jterator_project_files(self, directory): logger.info( , directory ) if not os.path.exists(directory): raise OSError(.format(directory)) pipeline_filename = os.path.join(directory, ) if not os.path.exists(pipeline_filename): ...
Uploads the *jterator* project description from files on disk in YAML format. It expects a ``pipeline.yaml`` file in `directory` and optionally ``*handles.yaml`` files in a ``handles`` subfolder of `directory`. Parameters ---------- directory: str path to the...
369,850
def get_model(name): model = MODELS.get(name.lower(), None) assert model, "Could not locate model by name " % name return model
Convert a model's verbose name to the model class. This allows us to use the models verbose name in steps.
369,851
def crop(im, r, c, sz): return im[r:r+sz, c:c+sz]
crop image into a square of size sz,
369,852
def _check_pip_installed(): try: subprocess.check_output( [sys.executable, "-m", "pip", "--version"], stderr=subprocess.STDOUT ) return True except subprocess.CalledProcessError: return False
Invoke `pip --version` and make sure it doesn't error. Use check_output to capture stdout and stderr Invokes pip by the same manner that we plan to in _call_pip() Don't bother trying to reuse _call_pip to do this... Finnicky and not worth the effort.
369,853
def _f_cash_root(x, counts, bkg, model): return np.sum(model * (counts / (x * model + bkg) - 1.0))
Function to find root of. Described in Appendix A, Stewart (2009). Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.nda...
369,854
def get_parser(): from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument(, action=, version=.format(mpu...
Get parser for mpu.
369,855
def _freeze(self, final_text, err=False): if not final_text: final_text = "" target = self.stderr if err else self.stdout if target.closed: target = sys.stderr if err else sys.stdout text = to_text(final_text) last_frame = self._compose_out(text, ...
Stop spinner, compose last frame and 'freeze' it.
369,856
def deserialize(cls, serializer, wf_spec, s_state, **kwargs): return serializer.deserialize_trigger(wf_spec, s_state, **kwargs)
Deserializes the trigger using the provided serializer.
369,857
def load_classes(cls, fail_silently=True): all_classes = itertools.chain( pkg_resources.iter_entry_points(cls.entry_point), (entry_point for identifier, entry_point in cls.extra_entry_points), ) for class_ in all_classes: try: yield (c...
Load all the classes for a plugin. Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of ...
369,858
def replace(self, **kwargs): if in kwargs: for attr in self.USAGE_KEY_ATTRS: kwargs.pop(attr, None) else: kwargs[] = self.usage_key.replace(**{ key: kwargs.pop(key) for key in self.USAGE_KEY_ATTRS ...
Return: a new :class:`AsideUsageKeyV2` with ``KEY_FIELDS`` specified in ``kwargs`` replaced with their corresponding values. Deprecation value is also preserved.
369,859
def by_chat_command(prefix=(,), separator=, pass_args=False): return by_command(lambda msg: msg[], prefix, separator, pass_args)
:param prefix: a list of special characters expected to indicate the head of a command. :param separator: a command may be followed by arguments separated by ``separator``. :type pass_args: bool :param pass_args: If ``True``, arguments following a command will be passed to the hand...
369,860
def transform(self, *axes, verbose=True): new = [] newt = "newt" in self.axis_expressions current = {a.expression: a for a in self._axes} for expression in axes: axis = current.get(expression, Axis(self, expression)) new.append(axis) ...
Transform the data. Parameters ---------- axes : strings Expressions for the new set of axes. verbose : boolean (optional) Toggle talkback. Default is True See Also -------- set_constants Similar method except for constants
369,861
def progress(self, *restrictions, display=True): todo = self._jobs_to_do(restrictions) total = len(todo) remaining = len(todo - self.target) if display: print( % self.__class__.__name__, % ( total - remaining, total, 100 - 100...
report progress of populating the table :return: remaining, total -- tuples to be populated
369,862
def parse_epcr(self): for sample in self.vtyper_object.metadata: sample[self.analysistype].result_dict = dict() with open(sample[self.analysistype].resultsfile) as epcrresults: for result in epcrresults: ...
Parse the ePCR output file. Populate dictionary of resutls. For alleles, find the best result based on the number of mismatches before populating dictionary
369,863
def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None): seq_reader_1 = sequences.file_reader(infile_1) seq_reader_2 = sequences.file_reader(infile_2) f_out = utils.open_file_write(outfile) for seq_1 in seq_reader_1: try: seq_2 = next(seq_reader_2) excep...
Makes interleaved file from two sequence files. If used, will append suffix1 onto end of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.
369,864
def make_middleware(app=None, *args, **kw): app = RaptorizeMiddleware(app, *args, **kw) return app
Given an app, return that app wrapped in RaptorizeMiddleware
369,865
def validate(cls, event_info): assert in event_info assert isinstance(event_info[], six.string_types) assert in event_info assert event_info[] in cls.EVENT_TYPES assert in event_info payload = event_info[] assert payload[] assert payload[] ...
Validate that provided event information is valid.
369,866
def transformer_encoder_layers(inputs, num_layers, hparams, attention_type=AttentionType.GLOBAL, self_attention_bias=None, q_padding="VALID", ...
Multi layer transformer encoder.
369,867
def get_last_modified_date( self, bucket: str, key: str, ) -> datetime: response = self.get_all_metadata(bucket, key) return response[]
Retrieves last modified date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the last modified date is being retrieved. :return: the last modified date
369,868
def drop_collection(request, database_name, collection_name): name = % (collection_name) if request.method == : form = ConfirmDropForm(request.POST) if form.is_valid(): name = form.cleaned_data[] if name != collection_name: messages.error(request, _(...
Drop Collection
369,869
def _readmodule(module, path, inpackage=None): if inpackage is not None: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module if fullmodule in _modules: return _modules[fullmodule] if module in sys.builtin_module_names and inpackage is None: ...
Do the hard work for readmodule[_ex]. If INPACKAGE is given, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path.
369,870
def resolve(cls, propname, objcls=None): if objcls is None: objcls = cls typemap = cls._types.get(objcls) if(typemap is not None): return typemap.get(propname, None) return None
resolve type of the class property for the class. If objcls is not set then assume that cls argument (class that the function is called from) is the class we are trying to resolve the type for :param cls: :param objcls: :param propname:
369,871
def _determine_filtered_package_requirements(self): filtered_requirements = set() try: lines = self.configuration["blacklist"]["packages"] package_lines = lines.split("\n") except KeyError: package_lines = [] for package_line in package_lines:...
Parse the configuration file for [blacklist]packages Returns ------- list of packaging.requirements.Requirement For all PEP440 package specifiers
369,872
def create_replication(self, source_db=None, target_db=None, repl_id=None, **kwargs): if source_db is None: raise CloudantReplicatorException(101) if target_db is None: raise CloudantReplicatorException(102) data = dict( _...
Creates a new replication task. :param source_db: Database object to replicate from. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. :param target_db: Database object to replicate to. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. ...
369,873
def stop(self, stopSparkContext=True, stopGraceFully=False): while self._on_stop_cb: cb = self._on_stop_cb.pop() log.debug(.format(cb)) cb() IOLoop.current().stop() StreamingContext._activeContext = None
Stop processing streams. :param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED) :param stopGracefully: stop gracefully (NOT IMPLEMENTED)
369,874
def ComputeFortranSuffixes(suffixes, ppsuffixes): assert len(suffixes) > 0 s = suffixes[0] sup = s.upper() upper_suffixes = [_.upper() for _ in suffixes] if SCons.Util.case_sensitive_suffixes(s, sup): ppsuffixes.extend(upper_suffixes) else: suffixes.extend(upper_suffixes)
suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.
369,875
def permute(self, qubits: Qubits) -> : vec = self.vec.permute(qubits) return Gate(vec.tensor, qubits=vec.qubits)
Permute the order of the qubits
369,876
def range_type_to_dtype(range_type: str) -> Optional[tf.DType]: range2dtype = { : tf.float32, : tf.int32, : tf.bool } return range2dtype[range_type]
Maps RDDL range types to TensorFlow dtypes.
369,877
def import_attr(path): module_path, attr_name = path.rsplit(".", 1) return getattr(import_module(module_path), attr_name)
Given a a Python dotted path to a variable in a module, imports the module and returns the variable in it.
369,878
def fix_config(self, options): options = super(EvaluationSummary, self).fix_config(options) opt = "title" if opt not in options: options[opt] = None if opt not in self.help: self.help[opt] = "The title for the output (string)." opt = "complexity...
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
369,879
def put_summary(self, summary): if isinstance(summary, six.binary_type): summary = tf.Summary.FromString(summary) assert isinstance(summary, tf.Summary), type(summary) for val in summary.value: if val.WhichOneof() == : val.tag = re.sub(,...
Put a `tf.Summary`.
369,880
def stations(self, *stns): self._set_query(self.spatial_query, stn=stns) return self
Specify one or more stations for the query. This modifies the query in-place, but returns `self` so that multiple queries can be chained together on one line. This replaces any existing spatial queries that have been set. Parameters ---------- stns : one or more string...
369,881
def _register_endpoints(self, providers): url_map = [] for endp_category in self.endpoints: for binding, endp in self.endpoints[endp_category].items(): valid_providers = "" for provider in providers: valid_providers = "{}|^{}".for...
Register methods to endpoints :type providers: list[str] :rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))] :param providers: A list of backend providers :return: A list of endpoint/method pairs
369,882
def _ensure_exists(name, path=None): if not exists(name, path=path): raise CommandExecutionError( {0}\.format(name) )
Raise an exception if the container does not exist
369,883
def encrypt_key(key, password): public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode()
Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPublicKey. The encrypted password is t...
369,884
def port_channel_vlag_ignore_split(self, **kwargs): name = str(kwargs.pop()) enabled = bool(kwargs.pop(, True)) callback = kwargs.pop(, self._callback) vlag_ignore_args = dict(name=name) if not pynos.utilities.valid_interface(, name): raise ValueError("`nam...
Ignore VLAG Split. Args: name (str): Port-channel number. (1, 5, etc) enabled (bool): Is ignore split enabled? (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ...
369,885
def newest(cls, session): media_type = cls.__name__.lower() p = session.session.get(u + media_type + ).text soup = utilities.get_clean_dom(p) latest_entry = soup.find(u"div", {u"class": u"hoverinfo"}) if not latest_entry: raise MalformedMediaPageError(0, p, u"No media entries found on rec...
Fetches the latest media added to MAL. :type session: :class:`myanimelist.session.Session` :param session: A valid MAL session :rtype: :class:`.Media` :return: the newest media on MAL :raises: :class:`.MalformedMediaPageError`
369,886
def _contextualize(contextFactory, contextReceiver): value = context.get(contextFactory, _NOT_SPECIFIED) if value is not _NOT_SPECIFIED: return contextReceiver(value) else: return context.call({contextFactory: contextFactory()}, _contextualize, contextFactory...
Invoke a callable with an argument derived from the current execution context (L{twisted.python.context}), or automatically created if none is yet present in the current context. This function, with a better name and documentation, should probably be somewhere in L{twisted.python.context}. Calling con...
369,887
def delete_agent_cloud(self, agent_cloud_id): route_values = {} if agent_cloud_id is not None: route_values[] = self._serialize.url(, agent_cloud_id, ) response = self._send(http_method=, location_id=, version=, ...
DeleteAgentCloud. [Preview API] :param int agent_cloud_id: :rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>`
369,888
def bench_report(results): table = Table(names=[, , , , , , ], dtype=[, bool, int, int, float, float, float], masked=True) for row in results: table.add_row(row) table[].format = if HEALPY_INSTALLED: table[] = table[] / table[] ...
Print a report for given benchmark results to the console.
369,889
def download(data_dir): tf.gfile.MakeDirs(data_dir) training_file_path = os.path.join(data_dir, TRAINING_FILE) if not tf.gfile.Exists(training_file_path): _download_and_clean_file(training_file_path, TRAINING_URL) eval_file_path = os.path.join(data_dir, EVAL_FILE) if not tf.gfile.Exists(eval_file_pat...
Download census data if it is not already present.
369,890
def generate_pdfa( pdf_pages, output_file, compression, log, threads=1, pdf_version=, pdfa_part=, ): compression_args = [] if compression == : compression_args = [ "-dAutoFilterColorImages=false", "-dColorImageFilter=/DCTEncode", "-dAu...
Generate a PDF/A. The pdf_pages, a list files, will be merged into output_file. One or more PDF files may be merged. One of the files in this list must be a pdfmark file that provides Ghostscript with details on how to perform the PDF/A conversion. By default with we pick PDF/A-2b, but this works for 1...
369,891
def add_alias(self, name, *alt_names): old_procedure = self.procedures[name] for alt in alt_names: new_procedure = copy.deepcopy(old_procedure) new_procedure.display_name = alt self.procedures[alt] = new_procedure
Add some duplicate names for a given function. The original function's implementation must already be registered. :param name: The name of the function for which an implementation is already present :param alt_names: Any number of alternate names may be passed as varargs
369,892
def _search(problem, fringe, graph_search=False, depth_limit=None, node_factory=SearchNode, graph_replace_when_better=False, viewer=None): if viewer: viewer.event() memory = set() initial_node = node_factory(state=problem.initial_state, p...
Basic search algorithm, base of all the other search algorithms.
369,893
def _process_data(*kwarg_names): def _data_decorator(func): @functools.wraps(func) def _mark_with_data(*args, **kwargs): data = kwargs.pop(, None) if data is None: return func(*args, **kwargs) else: data_args = [data[i] if hash...
Helper function to handle data keyword argument
369,894
def percent_encode_host(url): if not in url: return url parts = urlsplit(url) domain = parts.netloc.encode() try: domain = domain.decode() if six.PY2: domain = domain.encode(, ) except: ...
Convert the host of uri formatted with to_uri() to have a %-encoded host instead of punycode host The rest of url should be unchanged
369,895
def sql(self, sql: str, *qmark_params, **named_params): statement = SingleSqlStatement(sql) return self.statement(statement).execute(*qmark_params, **named_params)
:deprecated: use self.statement to execute properly-formatted sql statements
369,896
def _get_span_name(servicer_context): method_name = servicer_context._rpc_event.call_details.method[1:] if isinstance(method_name, bytes): method_name = method_name.decode() method_name = method_name.replace(, ) return .format(RECV_PREFIX, method_name)
Generates a span name based off of the gRPC server rpc_request_info
369,897
def api_retrieve(self, api_key=None): api_key = api_key or self.default_api_key return self.stripe_class.retrieve( id=self.id, api_key=api_key, expand=self.expand_fields )
Call the stripe API's retrieve operation for this model. :param api_key: The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY. :type api_key: string
369,898
def addCondition(self, *fns, **kwargs): msg = kwargs.get("message", "failed user-defined condition") exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException for fn in fns: fn = _trim_arity(fn) def pa(s,l,t): if not bool(fn...
Add a boolean predicate function to expression's list of parse actions. See :class:`setParseAction` for function call signatures. Unlike ``setParseAction``, functions passed to ``addCondition`` need to return boolean success/fail of the condition. Optional keyword arguments: - message =...
369,899
def get_next_occurrence(tx: ScheduledTransaction) -> date: ref_datum: Datum = Datum() if tx.last_occur: ref_datum.from_date(tx.last_occur) ref_datum.add_days(1) else: ref_datum.from_date(tx.recurrence.recurrence_period_start) ...
Calculates the next occurrence date for scheduled transaction. Mimics the recurrenceNextInstance() function from GnuCash. Still not fully complete but handles the main cases I use.