Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
4,400
def _create_client_impl(self, api_version): if api_version == v7_0_VERSION: from azure.keyvault.v7_0 import KeyVaultClient as ImplClient elif api_version == v2016_10_01_VERSION: from azure.keyvault.v2016_10_01 import KeyVaultClient as ImplClient else: ...
Creates the client implementation corresponding to the specifeid api_version. :param api_version: :return:
4,401
def to_array(self): array = super(InputMediaDocument, self).to_array() if self.thumb is not None: if isinstance(self.thumb, InputFile): array[] = None elif isinstance(self.thumb, str): array[] = u(self.thumb) ...
Serializes this InputMediaDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict
4,402
def vad(self, location=1, normalize=True, activity_threshold=7.0, min_activity_duration=0.25, initial_search_buffer=1.0, max_gap=0.25, initial_pad=0.0): if location not in [-1, 1]: raise ValueError("location must be -1 or 1.") if not isinstance(normalize, boo...
Voice Activity Detector. Attempts to trim silence and quiet background sounds from the ends of recordings of speech. The algorithm currently uses a simple cepstral power measurement to detect voice, so may be fooled by other things, especially music. The effect can trim only from the fr...
4,403
def run_helper_process(python_file, metadata_queue, quit_event, options): class_wrapper = import_class_with_base(python_file, BotHelperProcess) helper_class = class_wrapper.get_loaded_class() helper = helper_class(metadata_queue, quit_event, options) helper.start()
:param python_file: The absolute path of a python file containing the helper process that should be run. It must define a class which is a subclass of BotHelperProcess. :param metadata_queue: A queue from which the helper process will read AgentMetadata updates. :param quit_event: An event which should be s...
4,404
def read_segment(self, segment): log.debug("read segment {0}".format(segment)) if segment < 0 or segment > 15: raise ValueError("invalid segment number") cmd = "\x10" + chr(segment << 4) + 8 * chr(0) + self.uid rsp = self.transceive(cmd) if len(rsp) < 129: ...
Read one memory segment (128 byte).
4,405
def make_fil_file(filename,out_dir=, new_filename=None, max_load = None): fil_file = Waterfall(filename, max_load = max_load) if not new_filename: new_filename = out_dir+filename.replace(,).split()[-1] if not in new_filename: new_filename = new_filename+ fil_file.write_to_fil(ne...
Converts file to Sigproc filterbank (.fil) format. Default saves output in current dir.
4,406
def show(self): self.hidden = False window_rect = RectCalculator.set_final_window_rect(self.settings, self.window) self.window.stick() if not self.get_notebook().has_page(): self.add_tab() self.window.set_keep_below(False) ...
Shows the main window and grabs the focus on it.
4,407
def init_stash(stash_path, passphrase, passphrase_size, backend): r stash_path = stash_path or STORAGE_DEFAULT_PATH_MAPPING[backend] click.echo(.format(backend, stash_path)) storage = STORAGE_MAPPING[backend](**_parse_path_string(stash_path)) try: click.echo() if os.path.isfile(PASS...
r"""Init a stash `STASH_PATH` is the path to the storage endpoint. If this isn't supplied, a default path will be used. In the path, you can specify a name for the stash (which, if omitted, will default to `ghost`) like so: `ghost init http://10.10.1.1:8500;stash1`. After initializing a stash, don...
4,408
def resolve_to_callable(callable_name): from . import registry clean_callable_name = callable_name.replace( , ).replace(, ).strip() try: return registry.get(clean_callable_name) except KeyError: try: from zope.dottedname.resolve import resolve return ...
Resolve string :callable_name: to a callable. :param callable_name: String representing callable name as registered in ramses registry or dotted import path of callable. Can be wrapped in double curly brackets, e.g. '{{my_callable}}'.
4,409
def features(sentence, i): word = sentence[i] yield "word:{}" + word.lower() if word[0].isupper(): yield "CAP" if i > 0: yield "word-1:{}" + sentence[i - 1].lower() if i > 1: yield "word-2:{}" + sentence[i - 2].lower() if i + 1 < len(sentence): yi...
Features for i'th token in sentence. Currently baseline named-entity recognition features, but these can easily be changed to do POS tagging or chunking.
4,410
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ret = LazyLoader( _module_dirs(opts, ), opts, tag=, pack={: functions, : returners, : utils}, ) ret.pack[] = ret return ret
Returns the proxy module for this salt-proxy-minion
4,411
def p_statement_break(p): if len(p) == 3: p[0] = ast.Break(None, lineno=p.lineno(1)) else: p[0] = ast.Break(p[2], lineno=p.lineno(1))
statement : BREAK SEMI | BREAK expr SEMI
4,412
def get_top_n_action_types(self, top_n): action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action_type_to_counts[actiontype] = 1 else: ...
Returns the top N actions by count.
4,413
def create_interface_connection(interface_a, interface_b): payload = {: interface_a, : interface_b} ret = _add(, , payload) if ret: return {: {: {ret[]: payload}}} else: return ret
.. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion netbox.create_interface_connection 123 456
4,414
def _children_(self): ret = {} names = self._field_names_ def down(name, obj): if isinstance(obj, BaseObj): if not isinstance(obj, weakref.ProxyTypes): ret[name] = obj elif isinstance(obj, list): for i, v in zi...
get children objects :rtype: a dict of children {child_name: child_object}
4,415
def decrypt_file(file_path, recipient_key, *, base64=False): "Returns (filename, file_contents) if successful" crypto.assert_type_and_length(, recipient_key, crypto.UserLock) with open(file_path, "rb") as I: contents = I.read() if base64: contents = crypto.b64decode(contents) ...
Returns (filename, file_contents) if successful
4,416
def prefix(self, name): a_node = self.adapter.get_node_attribute_node(self.impl_element, name) if a_node is None: return None return a_node.prefix
:param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None.
4,417
def twitter_credential(name): credential_name = + name.upper() if hasattr(settings, credential_name): return getattr(settings, credential_name) else: raise AttributeError( + credential_name)
Grab twitter credential from settings
4,418
def _channel_loop(detection, template, min_cc, detection_id, interpolate, i, pre_lag_ccsum=None, detect_chans=0, horizontal_chans=[, , , ], vertical_chans=[], debug=0): from eqcorrscan.core.match_filter import normxcorr2 import math event = Event() ...
Inner loop for correlating and assigning picks. Utility function to take a stream of data for the detected event and write maximum correlation to absolute time as picks in an obspy.core.event.Event object. Only outputs picks for picks above min_cc. :type detection: obspy.core.stream.Stream :pa...
4,419
def forgot_password(self): form = self._get_form() if form.validate_on_submit(): self.security_service.send_reset_password_instructions(form.user) self.flash(_(, email=form.user.email), category=) if request.is_...
View function to request a password recovery email with a reset token. Supports html and json requests.
4,420
def generate(self): generated_arr = np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape) if self.noise_sampler is not None: self.noise_sampler.output_shape = generated_arr.shape generated_arr += self.noise_sampler.generate() ...
Generate noise samples. Returns: `np.ndarray` of samples.
4,421
def connect_discussion_signals(): post_save.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PS_COUNT_DISCUSSIONS) post_delete.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PD_COUNT_DISCUSSIONS) comment_was_f...
Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments.
4,422
def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options): try: sailthru_response = sailthru_client.purchase(email, [item], incomplete=purchase_incomplete, message_id=message_id, ...
Record a purchase in Sailthru Arguments: sailthru_client (object): SailthruClient email (str): user's email address item (dict): Sailthru required information about the course purchase_incomplete (boolean): True if adding item to shopping cart message_id (str): Cookie used t...
4,423
def debug_command(self, cmd, args=None, progress_callback=None): if args is None: args = {} try: self._on_progress = progress_callback return self._loop.run_coroutine(self.adapter.debug(0, cmd, args)) finally: self._on_progress = None
Send a debug command to the connected device. This generic method will send a named debug command with the given arguments to the connected device. Debug commands are typically used for things like forcible reflashing of firmware or other, debug-style, operations. Not all transport pr...
4,424
def call_actions_future( self, service_name, actions, expansions=None, raise_job_errors=True, raise_action_errors=True, timeout=None, **kwargs ): kwargs.pop(, None) if timeout: kwargs[] = timeout expected...
This method is identical in signature and behavior to `call_actions`, except that it sends the request and then immediately returns a `FutureResponse` instead of blocking waiting on a response and returning a `JobResponse`. Just call `result(timeout=None)` on the future response to block for an availabl...
4,425
def satisfy_one(self, assumptions=None, **params): verbosity = params.get(, 0) default_phase = params.get(, 2) propagation_limit = params.get(, -1) decision_limit = params.get(, -1) seed = params.get(, 1) return picosat.satisfy_one(self.nvars, self.clauses, assum...
If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None.
4,426
def _bind(self, _descriptor): self._defcode = getattr(_descriptor.method, , 200) self.content_type, self.serializer = _descriptor.serializer(self.req)
Bind a ResponseObject to a given action descriptor. This updates the default HTTP response code and selects the appropriate content type and serializer for the response.
4,427
def get_person_by_nickname(self, nickname): return next((person for person in self.get_all_people() if person.nickname.lower() == nickname.lower()), None)
Retrieves a person by nickname
4,428
def loadtxt_str(path:PathOrStr)->np.ndarray: "Return `ndarray` of `str` of lines of text from `path`." with open(path, ) as f: lines = f.readlines() return np.array([l.strip() for l in lines])
Return `ndarray` of `str` of lines of text from `path`.
4,429
def create_issues_report(self, timeout=-1): uri = "{}/issues/".format(self.data["uri"]) return self._helper.create_report(uri, timeout)
Creates an unexpected zoning report for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: list: A list of FCIssueRes...
4,430
def phone_number(self, phone_number): if phone_number is None: raise ValueError("Invalid value for `phone_number`, must not be `None`") if len(phone_number) > 16: raise ValueError("Invalid value for `phone_number`, length must be less than `16`") self._phone_nu...
Sets the phone_number of this OrderFulfillmentRecipient. The phone number of the fulfillment recipient. If provided, overrides the value from customer profile indicated by customer_id. :param phone_number: The phone_number of this OrderFulfillmentRecipient. :type: str
4,431
def errorhandler(self, code_or_exception): def decorator(fn): self._defer(lambda app: app.register_error_handler(code_or_exception, fn)) return fn return decorator
Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also regist...
4,432
def lookup(self, auth, type, mapping, defer=False): return self._call(, auth, [type, mapping], defer)
Look up a Resource ID by alias, owned Resource ID, or share activation code under the client specified in <ClientID>. Args: auth: <cik> type: Type of resource to lookup (alias | owner | shared) mapping: Based on resource type defined above.
4,433
def getOrderVector(self): incEdgesMap = self.getIncEdgesMap() sortedKeys = sorted(incEdgesMap.keys(), reverse = True) orderVector = [] print(sortedKeys) for key in sortedKeys: tier = [] cands = incEdgesMap[key]...
Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally.
4,434
def defer_function(self, callable): self._deferred_functions.append((callable, self.scope_stack[:], self.offset))
Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When 'callable' is called, the scope at the time this is called will be restored, however it will cont...
4,435
def compile_migrations(migrator, models, reverse=False): source = migrator.orm.values() if reverse: source, models = models, source migrations = diff_many(models, source, migrator, reverse=reverse) if not migrations: return False migrations = NEWLINE + NEWLINE.join(.join(migra...
Compile migrations for given models.
4,436
def get_system_uptime_input_rbridge_id(self, **kwargs): config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime input = ET.SubElement(get_system_uptime, "input") rbridge_id = ET.SubElement(input, "rbridge-id") ...
Auto Generated Code
4,437
def load_variable(self, var=None, start_date=None, end_date=None, time_offset=None, grid_attrs=None, **DataAttrs): file_set = self._generate_file_set(var=var, start_date=start_date, end_date=end_date, **DataAttrs) ds = _load_data_...
Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------- var : Var aospy Var object start_date : datetime.datetime start date for interval end_date : datet...
4,438
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = (,,) x = np.linspace(0, 1, 100) y = np.linspace(0, np.sqrt(3.0)/2.0, 100) points2d = np.transpose([np.tile(x, len(y)), np...
Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.
4,439
def cnst_A1T(self, Y1): r Y1f = sl.rfftn(Y1, None, axes=self.cri.axisN) return sl.irfftn(np.conj(self.GDf) * Y1f, self.cri.Nv, self.cri.axisN)
r"""Compute :math:`A_1^T \mathbf{y}_1` component of :math:`A^T \mathbf{y}`. In this case :math:`A_1^T \mathbf{y}_1 = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}_1`.
4,440
def _mpda(self, re_grammar, splitstring=0): cnfgrammar = CNFGenerator(re_grammar) if not self.alphabet: self._extract_alphabet(cnfgrammar) cnftopda = CnfPda(self.alphabet) productions = {} nonterminals = [] nonterminals.append(cnfgrammar.init_symbol...
Args: re_grammar (list): A list of grammar rules splitstring (bool): A boolean for enabling or disabling the splitting of symbols using a space Returns: PDA: The generated PDA
4,441
def _exec(self, cmd, url, json_data=None): assert(cmd in ("GET", "POST", "PUT", "DELETE")) assert(self.dev is not None) if json_data is None: json_data = {} url = url.format(self.dev["ipv4_internal"]) auth = HTTPBasicAuth("dev", self.dev[...
execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be attached to the command
4,442
def set_user_access(self, uid, channel=None, callback=False, link_auth=True, ipmi_msg=True, privilege_level=): if channel is None: channel = self.get_network_channel() b = 0b10000000 if callback: b |= 0b01000000 if link_auth: ...
Set user access :param uid: user number [1:16] :param channel: number [1:7] :parm callback: User Restricted to Callback False = User Privilege Limit is determined by the User Privilege Limit parameter, below, for both callback and non-callback connections. True = ...
4,443
def submit(jman, command, arguments, deps=[], array=None): logdir = os.path.join(os.path.realpath(arguments.logdir), tools.random_logdir()) jobname = os.path.splitext(os.path.basename(command[0]))[0] cmd = tools.make_shell(sys.executable, command) if arguments.dryrun: return DryRunJob(cmd, cwd=a...
An easy submission option for grid-enabled scripts. Create the log directories using random hash codes. Use the arguments as parsed by the main script.
4,444
def get_code(module): fp = open(module.path) try: return compile(fp.read(), str(module.name), ) finally: fp.close()
Compile and return a Module's code object.
4,445
def process_event(self, event_name: str, data: dict): if (isinstance(self.opt.get("learning_rate", None), float) and isinstance(self.opt.get("learning_rate_decay", None), float)): pass else: if event_name == : if (self.get_learning_rate_va...
Process event after epoch Args: event_name: whether event is send after epoch or batch. Set of values: ``"after_epoch", "after_batch"`` data: event data (dictionary) Returns: None
4,446
def parse_args(argv): base = argparse.ArgumentParser( description="Khard is a carddav address book for the console", formatter_class=argparse.RawTextHelpFormatter, add_help=False) base.add_argument("-c", "--config", default="", help="config file to use") base.add_argument("--d...
Parse the command line arguments and return the namespace that was creates by argparse.ArgumentParser.parse_args(). :returns: the namespace parsed from the command line :rtype: argparse.Namespace
4,447
def parent(self): try: return Resource(self[], uuid=self[], check=True) except KeyError: raise ResourceMissing( % self)
Return parent resource :rtype: Resource :raises ResourceNotFound: parent resource doesn't exists :raises ResourceMissing: parent resource is not defined
4,448
def fcoe_get_login_input_fcoe_login_rbridge_id(self, **kwargs): config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login input = ET.SubElement(fcoe_get_login, "input") fcoe_login_rbridge_id = ET.SubElement(input, "fcoe-login-rbr...
Auto Generated Code
4,449
def finish(self): self.cov.stop() self.cov.combine() self.cov.save()
Combines coverage data and sets the list of coverage objects to report on.
4,450
def search(self, **kwargs): return super(ApiVipRequest, self).get(self.prepare_url(, kwargs))
Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override def...
4,451
def from_pyfile(self, filename): d = types.ModuleType() d.__file__ = filename with open(filename) as config_file: exec(compile(config_file.read(), filename, ), d.__dict__) self.from_object(d) return True
在一个 Python 文件中读取配置。 :param filename: 配置文件的文件名 :return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
4,452
def __initialize_ui(self): self.viewport().installEventFilter(ReadOnlyFilter(self)) if issubclass(type(self), QListView): super(type(self), self).setUniformItemSizes(True) elif issubclass(type(self), QTreeView): super(type(self), self).setUniformRowHeights(True...
Initializes the View ui.
4,453
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False, variables=None): r if Ne > 9: comma = "," name = r"\rho" open_brace = "_{" close_brace = "}" else: comma = "" name = "rho" open_brace = "" clo...
r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$ normalized (boolean): Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$ A very simple e...
4,454
def createSubtitle(self, fps, section): matched = self._pattern.search(section) if matched is not None: matchedDict = matched.groupdict() return Subtitle( self.frametime(fps, matchedDict.get("time_from")), self.frametime(fps, matchedDict.g...
Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression.
4,455
def write(nml, nml_path, force=False, sort=False): if not isinstance(nml, Namelist) and isinstance(nml, dict): nml_in = Namelist(nml) else: nml_in = nml nml_in.write(nml_path, force=force, sort=sort)
Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is equivalent to the ``write`` function of the ``Namelist`` ...
4,456
def camel_case_to_name(name): def convert_func(val): return "_" + val.group(0).lower() return name[0].lower() + re.sub(r, convert_func, name[1:])
Used to convert a classname to a lowercase name
4,457
def is_subsequence(needle, haystack): it = iter(haystack) for element in needle: if element not in it: return False return True
Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout
4,458
def intcomma(value): orig = str(value) new = re.sub("^(-?\d+)(\d{3})", , orig) if orig == new: return new else: return intcomma(new)
Borrowed from django.contrib.humanize Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
4,459
def area(poly): if len(poly) < 3: return 0 total = [0, 0, 0] num = len(poly) for i in range(num): vi1 = poly[i] vi2 = poly[(i+1) % num] prod = np.cross(vi1, vi2) total[0] += prod[0] total[1] += prod[1] total[2] += prod[2] if total == [0, ...
Area of a polygon poly
4,460
def parse_tasks_file_header(header, input_file_param_util, output_file_param_util): job_params = [] for col in header: col_type = col_value = col if col.startswith(): col_type, col_value = split_pair(col, , 1) if col_type == : job_params.appen...
Parse the header from the tasks file into env, input, output definitions. Elements are formatted similar to their equivalent command-line arguments, but with associated values coming from the data rows. Environment variables columns are headered as "--env <name>" Inputs columns are headered as "--input <name>...
4,461
def start_module(self): try: self._main() except Exception as exp: logger.exception(, traceback.format_exc()) raise Exception(exp)
Wrapper for _main function. Catch and raise any exception occurring in the main function :return: None
4,462
def guess_rank(M_E): n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1] - S0[1:] S1_ = S1 / np.mean(S1[-10:]) r1 = 0 lam = 0.05 cost = [None] * len(S1_) wh...
Guess the rank of the incomplete matrix
4,463
def rename(old_name, new_name): app = get_app() snapshot = app.get_snapshot(old_name) if not snapshot: click.echo("Couldn't find snapshot %s" % old_name) sys.exit(1) new_snapshot = app.get_snapshot(new_name) if new_snapshot: click.echo("Snapshot with name %s already ex...
Renames a snapshot
4,464
def from_seedhex_file(path: str) -> SigningKeyType: with open(path, ) as fh: seedhex = fh.read() return SigningKey.from_seedhex(seedhex)
Return SigningKey instance from Seedhex file :param str path: Hexadecimal seed file path
4,465
def _as_chunk(self): if self._chunks_offset == 0: return self.contents return self.contents[self._chunks_offset:]
A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples.
4,466
def get_worker(self, *queues): if not queues: queues = self.queues queues = [self.get_queue(name) for name in queues] worker_cls = import_attribute(self.worker_class) worker = worker_cls( queues, connection=self.connection, job_cla...
Returns an RQ worker instance for the given queue names, e.g.:: configured_worker = rq.get_worker() default_worker = rq.get_worker('default') default_low_worker = rq.get_worker('default', 'low') :param \\*queues: Names of queues the worker should act on, falls back ...
4,467
def split_query(query): def split_assignment(a): sa = a.split(, 1) return len(sa) == 2 and tuple(sa) or (sa[0], None) assignments = query.split() return tuple([split_assignment(a) for a in assignments if a])
Handle the query as a WWW HTTP 1630 query, as this is how people usually thinks of URI queries in general. We do not decode anything in split operations, neither percent nor the terrible plus-to-space conversion. Return: >>> split_query("k1=v1&k2=v+2%12&k3=&k4&&&k5==&=k&==") (('k1', 'v1'), ('k2',...
4,468
def getXML(self, CorpNum, NTSConfirmNum, UserID=None): if NTSConfirmNum == None or len(NTSConfirmNum) != 24: raise PopbillException(-99999999, "국세청승인번호(NTSConfirmNum)가 올바르지 않습니다.") return self._httpget( + NTSConfirmNum + , CorpNum, UserID)
전자세금계산서 상세정보 확인 - XML args CorpNum : 팝빌회원 사업자번호 NTSConfirmNum : 국세청 승인번호 UserID : 팝빌회원 아이디 return 전자세금계산서 정보객체 raise PopbillException
4,469
def update_ref(profile, ref, sha): resource = "/refs/" + ref payload = {"sha": sha} data = api.patch_request(profile, resource, payload) return prepare(data)
Point a ref to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref The ref to update, e.g., ``heads/my-...
4,470
def heating_level(self): try: if self.side == : level = self.device.device_data[] elif self.side == : level = self.device.device_data[] return level except TypeError: return None
Return heating level.
4,471
def reset(self, id=None): if id is None: self.ccache.clear() else: self.ccache.pop(id, None) if DEBUG: for route in self.routes: if route[] not in self.ccache: self.ccache[route[]] = self._build_callback(route)
Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.
4,472
def treeplot(self, qlist, credible_interval): for y, _, label, values, color in self.iterator(): ntiles = np.percentile(values.flatten(), qlist) ntiles[0], ntiles[-1] = hpd(values.flatten(), credible_interval) yield y, label, ntiles, color
Get data for each treeplot for the variable.
4,473
def delete_user(self, user_id, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_user_with_http_info(user_id, **kwargs) else: (data) = self.delete_user_with_http_info(user_id, **kwargs) return data
Delete a user. # noqa: E501 An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP reque...
4,474
def log_predictive_density(self, x_test, y_test, Y_metadata=None): mu_star, var_star = self._raw_predict(x_test) fy = self.warping_function.f(y_test) ll_lpd = self.likelihood.log_predictive_density(fy, mu_star, var_star, Y_metadata=Y_metadata) return ll_lpd + np.log(self.warping...
Calculation of the log predictive density. Notice we add the jacobian of the warping function here. .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test: test observations (...
4,475
def codebox(msg="", title=" ", text=""): return tb.textbox(msg, title, text, codebox=1)
Display some text in a monospaced font, with no line wrapping. This function is suitable for displaying code and text that is formatted using spaces. The text parameter should be a string, or a list or tuple of lines to be displayed in the textbox. :param str msg: the msg to be displayed :para...
4,476
def set_timezone(tz=None, deploy=False): ** if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {: , : , : localhost.localdomain\, : .format(tz)} ret.update(__proxy__[](query)) if deploy is True: ...
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
4,477
def _create_hash_from_doc(doc: Mapping[str, Any]) -> str: doc_string = json.dumps(doc, sort_keys=True) return _create_hash(doc_string)
Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash
4,478
def decode_token(encoded_token, csrf_value=None, allow_expired=False): jwt_manager = _get_jwt_manager() unverified_claims = jwt.decode( encoded_token, verify=False, algorithms=config.algorithm ) unverified_headers = jwt.get_unverified_header(encoded_token) try: secret ...
Returns the decoded token (python dict) from an encoded JWT. This does all the checks to insure that the decoded token is valid before returning it. :param encoded_token: The encoded JWT to decode into a python dict. :param csrf_value: Expected CSRF double submit value (optional) :param allow_expired: ...
4,479
def remove_node(cls, cluster_id_label, private_dns, parameters=None): conn = Qubole.agent(version=Cluster.api_version) parameters = {} if not parameters else parameters data = {"private_dns" : private_dns, "parameters" : parameters} return conn.delete(cls.element_path(cluster_id...
Add a node to an existing cluster
4,480
def get_iterator_type(script_settings, subscripts={}): if in script_settings: if script_settings[] == : iterator_type = elif script_settings[] == : iterator_type = else: raise TypeError() else: ...
figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns:
4,481
def get_logs_multipart( w3, startBlock, stopBlock, address, topics, max_blocks): _block_ranges = block_ranges(startBlock, stopBlock, max_blocks) for from_block, to_block in _block_ranges: params = { : from_block, : to_block, ...
Used to break up requests to ``eth_getLogs`` The getLog request is partitioned into multiple calls of the max number of blocks ``max_blocks``.
4,482
def new_line(self, tokens, line_end, line_start): if _last_token_on_line_is(tokens, line_end, ";"): self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end)) line_num = tokens.start_line(line_start) line = tokens.line(line_start) if tokens.type(lin...
a new line has been encountered, process it if necessary
4,483
def set_info(self, info): idx = info.get(self.name) if idx is not None: self.__dict__.update(idx)
set my state from the passed info
4,484
def _calc_sdof_tf(self, osc_freq, damping=0.05): return (-osc_freq ** 2. / (np.square(self.freqs) - np.square(osc_freq) - 2.j * damping * osc_freq * self.freqs))
Compute the transfer function for a single-degree-of-freedom oscillator. The transfer function computes the pseudo-spectral acceleration. Parameters ---------- osc_freq : float natural frequency of the oscillator [Hz] damping : float, optional da...
4,485
def to_file(file, array): try: array.tofile(file) except (TypeError, IOError, UnsupportedOperation): file.write(array.tostring())
Wrapper around ndarray.tofile to support any file-like object
4,486
def example_lab_to_xyz(): print("=== Simple Example: Lab->XYZ ===") lab = LabColor(0.903, 16.296, -2.22) print(lab) xyz = convert_color(lab, XYZColor) print(xyz) print("=== End Example ===\n")
This function shows a simple conversion of an Lab color to an XYZ color.
4,487
def _execute(self, sql, args): sql = sql.lower().strip() args = args or () tmp = sql[:6] with (yield self._pool.Connection()) as conn: try: with conn.cursor() as cursor: yield cursor.execute(sql, args=args) if t...
执行sql语句 :param sql: sql语句 :param args: 参数 :return: 返回的都是数组对象
4,488
def find_related_modules(package, related_name_re=, ignore_exceptions=False): warnings.warn(, DeprecationWarning) package_elements = package.rsplit(".", 1) try: if len(package_elements) == 2: pkg = __import__(package_elements[0], globals(),...
Find matching modules using a package and a module name pattern.
4,489
def cli(ctx, packages, all, list, force, platform): if packages: for package in packages: Installer(package, platform, force).install() elif all: packages = Resources(platform).packages for package in packages: Installer(package, platform, force).install()...
Install packages.
4,490
def _infer_map(node, context): values = {} for name, value in node.items: if isinstance(name, nodes.DictUnpack): double_starred = helpers.safe_infer(value, context) if not double_starred: raise exceptions.InferenceError if not isinstance(double_st...
Infer all values based on Dict.items
4,491
def ploidy(args): p = OptionParser(ploidy.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x7") if len(args) != 2: sys.exit(not p.print_help()) seqidsfile, klayout = args fig = plt.figure(1, (iopts.w, iopts.h)) root = fig.add_axes([0, 0, 1, 1]) Karyotype(fig,...
%prog ploidy seqids layout Build a figure that calls graphics.karyotype to illustrate the high ploidy of B. napus genome.
4,492
def disconnect(self, connection): proto = self._protocols.pop(connection) proto.transport = None return {}
Disconnects the given protocol.
4,493
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter(.format( event.data_type)) event_values = event.CopyToDict() page_transition_type = event_values.get(, None) if page_transition_type is not None: page_transiti...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
4,494
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): title = _get_title(title) plt_ref = tc.extensions.plot(x, y, xlabel, ylabel, title) return Plot(plt_ref)
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 value...
4,495
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): if q is None: q = numpy.zeros((len(self.links), 1...
Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float toleranc...
4,496
def _is_method_retryable(self, method): if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
4,497
def assert_shape_match(shape1, shape2): shape1 = tf.TensorShape(shape1) shape2 = tf.TensorShape(shape2) if shape1.ndims is None or shape2.ndims is None: raise ValueError( % (shape1.ndims, shape2.ndims)) shape1.assert_same_rank(shape2) shape1.assert_is_compatible_with(shape2)
Ensure the shape1 match the pattern given by shape2. Ex: assert_shape_match((64, 64, 3), (None, None, 3)) Args: shape1 (tuple): Static shape shape2 (tuple): Dynamic shape (can contain None)
4,498
def update_artifact_cache(self, vts_artifactfiles_pairs): update_artifact_cache_work = self._get_update_artifact_cache_work(vts_artifactfiles_pairs) if update_artifact_cache_work: self.context.submit_background_work_chain([update_artifact_cache_work], p...
Write to the artifact cache, if we're configured to. vts_artifactfiles_pairs - a list of pairs (vts, artifactfiles) where - vts is single VersionedTargetSet. - artifactfiles is a list of absolute paths to artifacts for the VersionedTargetSet.
4,499
def parse_string_expr(self, string_expr_node): string_expr_node_value = string_expr_node[] string_expr_str = string_expr_node_value[1:-1] if string_expr_node_value[0] == "") else: string_expr_str = string_expr_str.replace(, ) raw_ast = sel...
Parse a string node content.