Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,300
def parse_config(args): config_path = path.expanduser(args.config_file) if not path.exists(config_path): if args.config_file != DEFAULT_JOURNAL_RC: print("journal: error: config file not found") sys.exit() else: return DEFAULT_...
Try to load config, to load other journal locations Otherwise, return default location Returns journal location
343,301
def get_md5(self): if self.md5 is None: self.md5 = self.file_hash(self.filename) return self.md5
Get or calculate MD5 value of the local file.
343,302
def ipv6_to_str(ip): if isinstance(ip, numbers.Integral): return addrconv.ipv6.bin_to_text(type_desc.Int16.from_user(ip)) else: return addrconv.ipv6.bin_to_text(ip)
Converts binary or int type representation to human readable IPv6 string. :param ip: binary or int type representation of IPv6 address :return: IPv6 address string
343,303
def com_google_fonts_check_fsselection(ttFont, style): from fontbakery.utils import check_bit_entry from fontbakery.constants import (STATIC_STYLE_NAMES, RIBBI_STYLE_NAMES, FsSelection) expected = "Regular" in style or \ (...
Checking OS/2 fsSelection value.
343,304
def temperature_effectiveness_TEMA_G(R1, NTU1, Ntp, optimal=True): r if Ntp == 1: D = exp(-NTU1*(1. - R1)/2.) if R1 != 1: B = (1. - D)/(1. - R1*D) else: B = NTU1/(2. + NTU1) A = 1./(1. + R1)*(1. - exp(-NTU1*(1. + R1)/2.)) P1 = A + B - A*B*(1. + R1)...
r'''Returns temperature effectiveness `P1` of a TEMA G type heat exchanger with a specified heat capacity ratio, number of transfer units `NTU1`, and of number of tube passes `Ntp`. For the two tube pass case, there are two possible orientations, one inefficient and one efficient controlled by the `op...
343,305
def x509_to_dict(x509): from requests.packages.urllib3.contrib.pyopenssl import get_subj_alt_name res = { : ( ((, x509.get_subject().CN),), ), : [ (, value) for value in get_subj_alt_name(x509) ] } notAf...
Parse a x509 pyopenssl object to a dictionary with keys subject, subjectAltName and optional notAfter.
343,306
def _request_one_trial_job(self): if not self.generated_hyper_configs: if self.curr_s < 0: self.curr_s = self.s_max _logger.debug(, self.curr_s) self.brackets[self.curr_s] = Bracket(self.curr_s, self.s_max, self.eta, self.R, self.optimize_mode) ...
get one trial job, i.e., one hyperparameter configuration.
343,307
def write_ticks(self, ticks): if self.first: Base.metadata.create_all(self.engine, checkfirst=True) self.first=False session=self.getWriteSession() session.add_all([self.__tickToSql(tick) for tick in ticks])
write ticks
343,308
def sync(self, since=None, timeout_ms=30000, filter=None, full_state=None, set_presence=None): request = { "timeout": int(timeout_ms) } if since: request["since"] = since if filter: request["filter"] = filter ...
Perform a sync request. Args: since (str): Optional. A token which specifies where to continue a sync from. timeout_ms (int): Optional. The time in milliseconds to wait. filter (int|str): Either a Filter ID or a JSON string. full_state (bool): Return the full sta...
343,309
def _save_message(self, stack, type_, message, context=None, from_merge=False): uid = uuid.uuid4().hex message[] = uid if message[]: if not self.supports_version(message[]): if self.instant: ...
Stores a message in the appropriate message stack.
343,310
def inject_scheme(self, b16_scheme): content_lines = self.content.splitlines() b16_scheme_lines = b16_scheme.splitlines() start_line = None for num, line in enumerate(content_lines): if not start_line: match = TEMP_NEEDLE.match(line)...
Inject string $b16_scheme into self.content.
343,311
def perf_attrib(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True): (returns, positions, factor_returns, factor_loadings) = _align_and_warn(returns, ...
Attributes the performance of a returns stream to a set of risk factors. Preprocesses inputs, and then calls empyrical.perf_attrib. See empyrical.perf_attrib for more info. Performance attribution determines how much each risk factor, e.g., momentum, the technology sector, etc., contributed to total r...
343,312
def hepatitis(return_X_y=True): hep = pd.read_csv(PATH + ).astype(float) if return_X_y: mask = (hep.total > 0).values hep = hep[mask] X = hep.age.values y = hep.hepatitis_A_positive.values / hep.total.values return _clean_X_y(X, y) return hep
hepatitis in Bulgaria dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame Notes ----- X contains ...
343,313
def get_app_name(app_name): type_ = locate(app_name) if inspect.isclass(type_): return type_.name return app_name
Returns a app name from new app config if is a class or the same app name if is not a class.
343,314
def get_object_data(obj): model = SuperModel(obj) try: data = model.to_dict() except Exception as exc: logger.error("Failed to get schema data for {}: {}" .format(repr(obj), str(exc))) data = {} return data
Get object schema data NOTE: We RAM cache this data because it should only change when the object was modified! XXX: We need to set at least the modification date when we set fields in Ajax Listing when we take a snapshot there! :param obj: Content object :returns: Dictionary of extracted sch...
343,315
def list(self, s3_folder=, full_key_data=False): if not s3_folder.startswith(): s3_folder = + s3_folder s3_prefix = self.prefix + s3_folder bucket_data = self.client.list_objects(Bucket=self.bucket, Prefix=s3_prefix) if full_key_data: return bucket_da...
Get a list of keys for the accounts
343,316
def get_sub_electrodes(self, adjacent_only=True): if adjacent_only: return [self.__class__(self._vpairs[i:i + 1], self._working_ion_entry, self._composition) for i in range(len(self._vpairs))] sub_electrodes = [] for i ...
If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be ...
343,317
def get_available_channels(header): chlist_str = header[][ ][] retv = {} for idx, char in zip(range(12), chlist_str): retv[CHANNEL_NAMES[idx + 1]] = (char == ) return retv
Get the available channels from the header information
343,318
def save_plot(self, filename, img_format="eps", **kwargs): plt = self.get_plot(**kwargs) plt.savefig(filename, format=img_format)
Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS.
343,319
def expect_invalid_resp_data(data=): try: yield except (ValueError, TypeError, IndexError, AttributeError, KeyError) as err: msg = ( % (data, six.text_type(err))) LOG.error(msg) raise exception.SDKInternalError(msg=msg)
Catch exceptions when using zvm client response data.
343,320
def instruction_BSR_JSR(self, opcode, ea): self.push_word(self.system_stack_pointer, self.program_counter.value) self.program_counter.set(ea)
Program control is transferred to the effective address after storing the return address on the hardware stack. A return from subroutine (RTS) instruction is used to reverse this process and must be the last instruction executed in a subroutine. source code forms: BSR dd; LBSR DDDD; JS...
343,321
def pprint(self, indent=, f=None): if self.arg is not None: print(indent + util.keyword_to_str(self.keyword) + " " + self.arg) else: print(indent + util.keyword_to_str(self.keyword)) if f is not None: f(self, indent) for x in self.substmts: ...
debug function
343,322
def read_transform(filename, dimension=2, precision=): filename = os.path.expanduser(filename) if not os.path.exists(filename): raise ValueError() libfn1 = utils.get_lib_fn() dimension = libfn1(filename) libfn2 = utils.get_lib_fn() transform_type = libfn2(filename) libfn3 = u...
Read a transform from file ANTsR function: `readAntsrTransform` Arguments --------- filename : string filename of transform dimension : integer spatial dimension of transform precision : string numerical precision of transform Returns ------- ANTsTran...
343,323
def view(tilesets): from .server import Server from .client import View curr_view = View() server = Server() server.start(tilesets) for ts in tilesets: if (ts.track_type is not None and ts.track_position is not None): curr_view.add_track(ts.track_type, ...
Create a higlass viewer that displays the specified tilesets Parameters: ----------- Returns ------- Nothing
343,324
def _create_class_proxy(cls, theclass): def make_method(name): def method(self, *args, **kw): return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw) return method namespace = {} for name in cls._special_names: if ha...
creates a proxy for the given class
343,325
def mode(self): self._mode, value = self.get_attr_string(self._mode, ) return value
Reading returns the currently selected mode. Writing sets the mode. Generally speaking when the mode changes any sensor or motor devices associated with the port will be removed new ones loaded, however this this will depend on the individual driver implementing this class.
343,326
def _rdf2dot_reduced(g, stream): import cgi import collections import rdflib from rdflib.tools.rdf2dot import LABEL_PROPERTIES, NODECOLOR types = collections.defaultdict(set) fields = collections.defaultdict(set) nodes = {} def node(x): return nodes.setdefault(x...
A reduced dot graph. Adapted from original source: https://rdflib.readthedocs.io/en/stable/_modules/rdflib/tools/rdf2dot.html
343,327
def decrypt_dynamodb_item(item, crypto_config): unique_actions = set([crypto_config.attribute_actions.default_action.name]) unique_actions.update(set([action.name for action in crypto_config.attribute_actions.attribute_actions.values()])) if crypto_config.attribute_actions.take_no_actions: ...
Decrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item >>> encrypted_item = { ... 'some': {'B': b'ENCRYPTED_DATA'}, ... 'more': {'B': b'ENCRYPTED_DATA'} ... } >>> decrypted_item = decrypt_python_item( ... item=encrypted_item, ... ...
343,328
def interpolate_linear(self, xi, yi, zdata): if zdata.size != self.npoints: raise ValueError() xi = np.array(xi) yi = np.array(yi) size = xi.size zi = np.empty(size) zierr = np.empty(size, dtype=np.int) zdata = self._shuffle_field(zdata) ...
Piecewise linear interpolation/extrapolation to arbitrary point(s). The method is fast, but has only C^0 continuity. Parameters ---------- xi : float / array of floats, shape (l,) x coordinates on the Cartesian plane yi : float / array of floats, shape (l,) ...
343,329
def simplex_find_tree(self): flows of arcs and converts this solution to a feasible spanning tree solution. Pre: (1) attributes represents a feasible flow solution. Post: (1) attributes may change when eliminating cycles. Return: ...
API: simplex_find_tree(self) Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs and converts this solution to a feasible spanning tree solution. Pre: (1) 'flow' attributes represents a feasible flow solution. ...
343,330
def call(self, command, params=None, expect_body=True, stream=False): if self._socket is None: raise SerfConnectionError() header = msgpack.packb({"Seq": self._counter(), "Command": command}) if params is not None: body = msgpack.packb(params) self....
Sends the provided command to Serf for evaluation, with any parameters as the message body.
343,331
def _tuple_from_list_or_tuple(bbox): if len(bbox) == 4: return tuple(map(float, bbox)) if len(bbox) == 2 and all([isinstance(point, (list, tuple)) for point in bbox]): return BBox._tuple_from_list_or_tuple(bbox[0] + bbox[1]) raise TypeError()
Converts a list or tuple representation of a bbox into a flat tuple representation. :param bbox: a list or tuple with 4 coordinates that is either flat or nested :return: tuple (min_x,min_y,max_x,max_y) :raises: TypeError
343,332
def print_locus_quals(locus_tag, locus, quals_ftypes): prot_id = None for ftype in quals_ftypes: for i, quals in enumerate(locus[locus_tag][ftype]): for elem in quals: elem_id = elem[0] if len(locus[locus_tag]["protein_id"]) > 0 and ftype in ("mRNA", "CDS...
Given a locus_tag and dict of feaures, print out 3-column output: locus_tag, qualifier, value Replace locus_tag with protein_id if processing an "mRNA" or "CDS"
343,333
def start_tracker(self, id_, **kwargs): data = None if kwargs: data = self._wrap_dict("tracker", self._wrap_dict("tracking_time_entry", kwargs)) return self.patch("/tracker/{}.json".format(id_), data=data)
Starts a tracker for the time entry identified by `id_`.
343,334
def _fullsize_link_tag(self, kwargs, title): return utils.make_tag(, { : self.get_fullsize(kwargs), : kwargs[], : title })
Render a <a href> that points to the fullsize rendition specified
343,335
def _build_bounding_box_lookup(bounding_box_file): lines = tf.gfile.FastGFile(bounding_box_file, ).readlines() images_to_bboxes = {} num_bbox = 0 num_image = 0 for l in lines: if l: parts = l.split() assert len(parts) == 5, ( % l) filename = parts[0] xmin = float(parts[1]) ...
Build a lookup from image file to bounding boxes. Args: bounding_box_file: string, path to file with bounding boxes annotations. Assumes each line of the file looks like: n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940 where each line corresponds to one bounding box annotation associated ...
343,336
def do_config(self,args): parser = CommandArgumentParser("config") subparsers = parser.add_subparsers(help=,dest=) subparsers._parser_class = argparse.ArgumentParser parserPrint = subparsers.add_parser(,help=) parserPrint.add_argument(dest=,nargs=,help...
Deal with configuration. Available subcommands: * config print - print the current configuration * config reload - reload the current configuration from disk * config set - change a setting in the configuration * config save - save the configuration to disk config -h for more d...
343,337
def store_from(self, last_level_store): assert isinstance(last_level_store, Cache), \ "last_level needs to be a Cache object." assert last_level_store.store_to is None, \ "last_level_store must be a last level cache (.store_to is None)." self.last_level_store = l...
Set level where to store to.
343,338
def write_str(self, s): self.write(s) self.room -= len(s)
Add string s to the accumulated body.
343,339
def timestamp(s): ms_s = s[6:] ms = ms_s and int(float(ms_s) * 1000000) or 0 t = datetime.time( hour=int(s[0:2]), minute=int(s[2:4]), second=int(s[4:6]), microsecond=ms) return t
Converts a timestamp given in "hhmmss[.ss]" ASCII text format to a datetime.time object
343,340
def clean_to_decimal(x, prec=28): import numpy as np import pandas as pd import decimal def proc_elem(e): try: return decimal.Decimal(e) + decimal.Decimal() except Exception as e: print(e) return None def proc_list(x): return [proc_e...
Convert an string, int or float to Decimal object Parameters ---------- x : str, list, tuple, numpy.ndarray, pandas.DataFrame A string, int or float number, or a list, array or dataframe of these. digits : int (Default prec=None) Set the getcontext precision Return...
343,341
def set(self, key, value, **kwargs): return requests.put( .format( self.master, pyconsul.__consul_api_version__, key), data=value, params=kwargs )
Store a new value at the given key kwargs can hold `cas` and `flags` params
343,342
def _process_queries(self, queries): bool_query = {} if must_q: bool_query[] = must_q if should_q: bool_query[] = should_q if must_not_q: bool_query[] = must_not_q retu...
Takes a list of queries and returns query clause value :arg queries: list of Q instances :returns: dict which is the query clause value
343,343
def sortByTotal(requestContext, seriesList): return list(sorted(seriesList, key=safeSum, reverse=True))
Takes one metric or a wildcard seriesList. Sorts the list of metrics by the sum of values across the time period specified.
343,344
async def close_websession(self): if self._supplied_websession or self._websession is None: return _LOGGER.debug() temp_websession = self._websession self._websession = None await temp_websession.close() await asyncio.sleep...
Close web session if not already closed and created by us.
343,345
def nacm_enable_external_groups(self, **kwargs): config = ET.Element("config") nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm") enable_external_groups = ET.SubElement(nacm, "enable-external-groups") enable_external_groups.text = kwargs.p...
Auto Generated Code
343,346
def nworker(data, chunk): oldlimit = set_mkl_thread_limit(1) with h5py.File(data.database.input, ) as io5: seqview = io5["bootsarr"][:] maparr = io5["bootsmap"][:, 0] smps = io5["quartets"][chunk:chunk+data._chunksize] nall_mask = seqview[:] == 78 ...
Worker to distribute work to jit funcs. Wraps everything on an engine to run single-threaded to maximize efficiency for multi-processing.
343,347
def receive_keys(keyserver=None, keys=None, user=None, gnupghome=None): s keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location where GPG keyring and related fi...
Receive key(s) from keyserver and add them to keychain keyserver Keyserver to use for searching for GPG keys, defaults to pgp.mit.edu keys The keyID(s) to retrieve from the keyserver. Can be specified as a comma separated string or a list. user Which user's keychain to ac...
343,348
def is_categorical_type(ary): "Checks whether the array is either integral or boolean." ary = np.asanyarray(ary) return is_integer_type(ary) or ary.dtype.kind ==
Checks whether the array is either integral or boolean.
343,349
def render_docstring(self): res = .format(self=self) if self.params: for group, params in self.params.items(): res += + group + for param in params.values(): res += param.render_docstring() return res
make a nice docstring for ipython
343,350
def ssh_sa_ssh_server_key_ecdsa(self, **kwargs): config = ET.Element("config") ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") ssh = ET.SubElement(ssh_sa, "ssh") server = ET.SubElement(ssh, "server") key = ET.SubElement(server,...
Auto Generated Code
343,351
def delete_downloads(): shutil.rmtree(vtki.EXAMPLES_PATH) os.makedirs(vtki.EXAMPLES_PATH) return True
Delete all downloaded examples to free space or update the files
343,352
def subcache(self, path): cache = self.clone() cache.prefix = os.path.join(cache.prefix if cache.prefix else , path) return cache
Clone this case, and extend the prefix
343,353
def from_rotation_and_translation( rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec=(0, 0, 0), tol=0.1): rotation_matrix = np.array(rotation_matrix) translation_vec = np.array(translation_vec) if rotation_matrix.shape != (3, 3): rais...
Creates a symmetry operation from a rotation matrix and a translation vector. Args: rotation_matrix (3x3 array): Rotation matrix. translation_vec (3x1 array): Translation vector. tol (float): Tolerance to determine if rotation matrix is valid. Returns: ...
343,354
def get_objective_banks_by_activity(self, *args, **kwargs): catalogs = self._get_provider_session().get_objective_banks_by_activity(*args, **kwargs) cat_list = [] for cat in catalogs: cat_list.append(ObjectiveBank(self._provider_manager, cat, self._runtime,...
Pass through to provider ActivityObjectiveBankSession.get_objective_banks_by_activity
343,355
def sort_values(expr, by, ascending=True): if not isinstance(by, list): by = [by, ] by = [it(expr) if inspect.isfunction(it) else it for it in by] return SortedCollectionExpr(expr, _sorted_fields=by, _ascending=ascending, _schema=expr._schema)
Sort the collection by values. `sort` is an alias name for `sort_values` :param expr: collection :param by: the sequence or sequences to sort :param ascending: Sort ascending vs. descending. Sepecify list for multiple sort orders. If this is a list of bools, must match the length of t...
343,356
def decrypt_assertions(self, encrypted_assertions, decr_txt, issuer=None, verified=False): res = [] for encrypted_assertion in encrypted_assertions: if encrypted_assertion.extension_elements: assertions = extension_elements_to_elements( ...
Moves the decrypted assertion from the encrypted assertion to a list. :param encrypted_assertions: A list of encrypted assertions. :param decr_txt: The string representation containing the decrypted data. Used when verifying signatures. :param issuer: The issuer of the response....
343,357
def get_plugin_icon(self): path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) return ima.icon(, icon_path=path)
Return widget icon
343,358
def on_open(self, ws): self.login(self.user, self.password, api_id=1) self.database(api_id=1) self.cancel_all_subscriptions() if len(self.on_object): self.set_subscribe_callback(self.__events__.index("on_object"), False) if len(self.on_tx)...
This method will be called once the websocket connection is established. It will * login, * register to the database api, and * subscribe to the objects defined if there is a callback/slot available for callbacks
343,359
def is_alive(self): response = self.get_monitoring_heartbeat() if response.status_code == 200 and response.content == : return True return False
Will test whether the ACS service is up and alive.
343,360
def clear(self): self.erase() output = self.output output.erase_screen() output.cursor_goto(0, 0) output.flush() self.request_absolute_cursor_position()
Clear screen and go to 0,0
343,361
def load_styles(path_or_doc): if isinstance(path_or_doc, string_types): doc = load(path_or_doc) else: if isinstance(path_or_doc, ODFDocument): doc = path_or_doc._doc else: doc = path_or_doc assert isinstance(doc, OpenDocument), doc styles...
Return a dictionary of all styles contained in an ODF document.
343,362
def get_last_param_name(url_rule) -> Union[str, None]: if not url_rule: return None match = re.search(LAST_PARAM_NAME_RE, url_rule) return match.group() if match else None
Returns the name of the last parameter in a URL rule, eg:: assert get_last_param_name('/foo/<int:id>/roles') is None url_rule = '/foo/<int:id>/bar/<any:something>/baz/<string:spam>' assert get_last_param_name(url_rule) == 'spam'
343,363
def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv=, runas=): * _create_rpmmacros(runas) tree_base = _mk_tree(runas) spec_path = _get_spec(tree_base, spec, template, saltenv) __salt__[](path=spec_path, user=runas, group=) __salt__[](path=tree_base, user=runas, group=) ...
Create a source rpm from the given spec file and sources CLI Example: .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec https://pypi.python.org/packages/source/l/lib...
343,364
def best_sell_1(self): result = self.data.value[-1] > self.data.value[-2] and \ self.data.price[-1] < self.data.openprice[-1] return result
量大收黑 :rtype: bool
343,365
def send(self): from neobolt.exceptions import ConnectionExpired if self._connection: try: self._connection.send() except ConnectionExpired as error: raise SessionExpired(*error.args)
Send all outstanding requests.
343,366
def length(string, until=None): if until is None: return sum(1 for _ in GraphemeIterator(string)) iterator = graphemes(string) count = 0 while True: try: if count >= until: break next(iterator) except StopIteration: break ...
Returns the number of graphemes in the string. Note that this functions needs to traverse the full string to calculate the length, unlike `len(string)` and it's time consumption is linear to the length of the string (up to the `until` value). Only counts up to the `until` argument, if given. This is u...
343,367
def expm1(x): if isinstance(x, UncertainFunction): mcpts = np.expm1(x._mcpts) return UncertainFunction(mcpts) else: return np.expm1(x)
Calculate exp(x) - 1
343,368
def mk_association(m, r_rel): handler = { : mk_simple_association, : mk_linked_association, : mk_subsuper_association, : mk_derived_association, } inst = subtype(r_rel, 206) fn = handler.get(type(inst).__name__) return fn(m, inst)
Create a pyxtuml association from a R_REL in ooaofooa.
343,369
def create_control_volumes(self): self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float) for k, cell in enumerate(self.cells): node_ids = cell["nodes"] self.control_volumes[node_ids] += 0.5 * self.cell_volumes[k] sum_cv = sum(self.contro...
Compute the control volumes of all nodes in the mesh.
343,370
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None, fontsize=10, **kwds): r if format is None: format = a = size/2.0 x0 = [0, 2.5*a, 0, 0] y0 = [a, 0, -a, a] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cu...
r"""Draw an arithmetic operator.
343,371
def last_name(languages=None): choices = [] languages = languages or [] for lang in languages: samples = _get_lastnames(lang) choices.extend(samples) return random.choice(choices).title()
return a random last name >>> from mock import patch >>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']): ... last_name() 'Aaa' >>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]): ... last_name(['it']) 'It_Lastname'
343,372
def validate_rule_name(self, name): if not name: raise SerializerError("Rule name is empty".format(name)) if name[0] not in RULE_ALLOWED_START: msg = "Rule name must starts with a letter" raise SerializerError(msg.format(name)) for item in name: ...
Validate rule name. Arguments: name (string): Rule name. Returns: bool: ``True`` if rule name is valid.
343,373
def copy_table_structure(self, source, destination, table): self.execute(.format(destination, wrap(table), source))
Copy a table from one database to another. :param source: Source database :param destination: Destination database :param table: Table name
343,374
def distutils_scheme(dist_name, user=False, home=None, root=None, isolated=False): from distutils.dist import Distribution scheme = {} if isolated: extra_dist_args = {"script_args": ["--no-user-cfg"]} else: extra_dist_args = {} dist_args = {: dist_name} ...
Return a distutils install scheme
343,375
def get_objective_hierarchy_design_session_for_objective_bank(self, objective_bank_id=None, *args, **kwargs): if not objective_bank_id: raise NullArgument if not self.supports_objective_hierarchy_design(): raise Unimplemented() try: from . import sess...
Gets the OsidSession associated with the objective hierarchy design service for the given objective bank. arg: objectiveBankId (osid.id.Id): the Id of the objective bank return: (osid.learning.ObjectiveHierarchyDesignSession) - an ObjectiveHierarchyDesignSessi...
343,376
def elcm_request(irmc_info, method, path, **kwargs): host = irmc_info[] port = irmc_info.get(, 443) auth_method = irmc_info.get(, ) userid = irmc_info[] password = irmc_info[] client_timeout = irmc_info.get(, 60) headers = kwargs.get(, {: }) params = kwargs.get() data = kw...
send an eLCM request to the server :param irmc_info: dict of iRMC params to access the server node { 'irmc_address': host, 'irmc_username': user_id, 'irmc_password': password, 'irmc_port': 80 or 443, default is 443, 'irmc_auth_method': 'basic' or 'digest', ...
343,377
def repl_member_add(self, params): repl_config = self.config member_id = max([member[] for member in repl_config[]]) + 1 member_config = self.member_create(params, member_id) repl_config[].append(member_config) if not self.repl_update(repl_config): self.membe...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
343,378
def is_f_connected(H, source_node, target_node): f_visited_nodes, Pv, Pe, v = f_visit(H, source_node) return target_node in f_visited_nodes
Checks if a target node is F-connected to a source node. A node t is F-connected to a node s iff s if B-connected to t. Refer to 'f_visit's or 'is_b_connected's documentation for more details. :param H: the hypergraph to check F-connectedness on. :param source_node: the node to check F-connectedness t...
343,379
def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie, cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen, codigo_localidad_destino, codigo_cosecha, peso_neto_carga, cant_horas=None, patente_vehiculo=None, cuit_transportista=None, km_a_recorrer=None,...
Solicitar CTG Desde el Inicio
343,380
def get_active_bets(self, project_id=None): url = urljoin( self.settings[], ) if project_id is not None: url += .format(project_id) bets = [] has_next_page = True while has_next_page: res = self._req(url) bets...
Returns all active bets
343,381
def favorites_getList(user_id=, per_page=, page=): method = data = _doget(method, auth=True, user_id=user_id, per_page=per_page,\ page=page) photos = [] if isinstance(data.rsp.photos.photo, list): for photo in data.rsp.photos.photo: photos.append(_parse_photo(...
Returns list of Photo objects.
343,382
def models(cls, api_version=DEFAULT_API_VERSION): if api_version == : from .v2015_06_15 import models return models elif api_version == : from .v2016_03_30 import models return models elif api_version == : from .v2016_04_30_pre...
Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.compute.v2015_06_15.models>` * 2016-03-30: :mod:`v2016_03_30.models<azure.mgmt.compute.v2016_03_30.models>` * 2016-04-30-preview: :mod:`v2016_04_30_preview.models<azure.mgmt.compute.v2016_04_30_preview...
343,383
def to_op(self): if not self._adds: return None changes = {} if self._adds: changes[] = list(self._adds) return changes
Extracts the modification operation from the Hll. :rtype: dict, None
343,384
def should_see_link(self, link_url): elements = ElementSelector( world.browser, str( % link_url), filter_displayed=True, ) if not elements: raise AssertionError("Expected link not found.")
Assert a link with the provided URL is visible on the page.
343,385
def expr_match(line, expr): if line == expr: return True if fnmatch.fnmatch(line, expr): return True try: if re.match(r.format(expr), line): return True except re.error: pass return False
Evaluate a line of text against an expression. First try a full-string match, next try globbing, and then try to match assuming expr is a regular expression. Originally designed to match minion IDs for whitelists/blacklists.
343,386
def do_mast_log_normal(self, line): self.application.master.SetLogFilters(openpal.LogFilters(opendnp3.levels.NORMAL)) _log.debug(.format(opendnp3.levels.NORMAL))
Set the master log level to NORMAL. Command syntax is: mast_log_normal
343,387
def print_title(title: str) -> None: msg = "**** {} ".format(title) print("{}{}{}{}".format(Style.BRIGHT, Fore.GREEN, msg, "*" * (80 - len(msg))))
Helper function to print a title.
343,388
def lz4f_decode(payload): ctx = lz4f.createDecompContext() data = lz4f.decompressFrame(payload, ctx) lz4f.freeDecompContext(ctx) if data[] != 0: raise RuntimeError() return data[]
Decode payload using interoperable LZ4 framing. Requires Kafka >= 0.10
343,389
def add_left_space(self, nspace=1): sp = * nspace for item in self._rows: item[0] = sp + item[0]
elem_add n cols of spaces before the first col. (for texttable 0.8.3)
343,390
def resize(self, new_size): if new_size == len(self): return else: self._saved = LimitedSizeDict(size_limit=2**5) new_arr = zeros(new_size, dtype=self.dtype) if len(self) <= new_size: new_arr[0:len(self)] = self else: ...
Resize self to new_size
343,391
async def open(self) -> : LOGGER.debug() await pool.set_protocol_version(self.protocol.indy()) LOGGER.info(, self.name, self.protocol) try: self._handle = await pool.open_pool_ledger(self.name, json.dumps(self.config)) except IndyError as x_indy: ...
Explicit entry. Opens pool as configured, for later closure via close(). Creates pool if it does not yet exist, using configured genesis transaction file. For use when keeping pool open across multiple calls. Raise any AbsentPool if node pool ledger configuration is not available. :ret...
343,392
def simple_generate_batch(klass, create, size, **kwargs): return make_factory(klass, **kwargs).simple_generate_batch(create, size)
Create a factory for the given class, and simple_generate instances.
343,393
def _add_message_info_multiple(self, msg_info): if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].appen...
add a message info multiple to self._msg_info_multiple_dict
343,394
def step(self): u = self._u if u is None: raise ValueError("the levelset function is not set " "(use set_levelset)") data = self.data inside = (u > 0) outside = (u <= 0) c0 = da...
Perform a single step of the morphological Chan-Vese evolution.
343,395
def _invoke_submit(self, iterobj, is_dict, is_itmcoll, mres, global_kw): if is_itmcoll: item, key_options = next(iterobj) key = item.key value = item.value result = item else: if is_dict: key, value = next(iterobj) ...
Internal function to invoke the actual submit_single function :param iterobj: The raw object returned as the next item of the iterator :param is_dict: True if iterator is a dictionary :param is_itmcoll: True if the iterator contains Item objects :param mres: The multi result object ...
343,396
def iter_hierarchy(self, ontology, size=None, sleep=None): for term in self.iter_terms(ontology=ontology, size=size, sleep=sleep): try: hierarchy_children_link = term[][HIERARCHICAL_CHILDREN][] except KeyError:
Iterates over parent-child relations :param str ontology: The name of the ontology :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI. :param int sleep: The amount of time to sleep between pages. Defaults to 0 seconds. :rtype: iter[tuple[str...
343,397
def assemble(code): final = [] final_operands.append(Operand( OperandTypes.CONSTANT_INDEX, operand.index )) elif isinstance(operand, dict): final_operands.append(Oper...
Assemble the given iterable of mnemonics, operands, and lables. A convienience over constructing individual Instruction and Operand objects, the output of this function can be directly piped to :class:`~jawa.attributes.code.CodeAttribute.assemble()` to produce executable bytecode. As a simple exam...
343,398
def handle_default_options(options): if options.settings: os.environ[] = options.settings if options.pythonpath: options.pythonpath = os.path.abspath(os.path.expanduser(options.pythonpath)) up_one_path = os.path.abspath(os.path.join(options.pythonpath, "..")) ...
Pass in a Values instance from OptionParser. Handle settings and pythonpath options - Values from OptionParser
343,399
def lru_cache(max_size=128): def actual_decorator(func): return _cached_func(func, caches.LRUCache, max_size) return actual_decorator
Least Recently Used cache decorator, implementing :class:`faste.caches.LRUCache` :keyword max_size: max cache size