_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56800
DataPoint.process_quantity
train
def process_quantity(self, properties): """Process the uncertainty information from a given quantity and return it """ quant = Q_(properties[0]) if len(properties) > 1: unc = properties[1] uncertainty = unc.get('uncertainty', False) upper_uncertainty =...
python
{ "resource": "" }
q56801
DataPoint.get_cantera_composition_string
train
def get_cantera_composition_string(self, species_conversion=None): """Get the composition in a string format suitable for input to Cantera. Returns a formatted string no matter the type of composition. As such, this method is not recommended for end users; instead, prefer the `get_cantera_mole_...
python
{ "resource": "" }
q56802
DataPoint.get_cantera_mole_fraction
train
def get_cantera_mole_fraction(self, species_conversion=None): """Get the mole fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when ...
python
{ "resource": "" }
q56803
DataPoint.get_cantera_mass_fraction
train
def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when ...
python
{ "resource": "" }
q56804
lockfile
train
def lockfile(lockfile_name, lock_wait_timeout=-1): """ Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LO...
python
{ "resource": "" }
q56805
get_username
train
def get_username(identifier): """Checks if a string is a email adress or not.""" pattern = re.compile('.+@\w+\..+') if pattern.match(identifier): try: user = User.objects.get(email=identifier) except: raise Http404 else: return user.username el...
python
{ "resource": "" }
q56806
Fixerio._create_payload
train
def _create_payload(self, symbols): """ Creates a payload with no none values. :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: a payload. :rtype: dict """ payload = {'access_key': self.access_key} ...
python
{ "resource": "" }
q56807
Fixerio.historical_rates
train
def historical_rates(self, date, symbols=None): """ Get historical rates for any day since `date`. :param date: a date :type date: date or str :param symbols: currency symbols to request specific exchange rates. :type symbols: list or tuple :return: the historica...
python
{ "resource": "" }
q56808
distinct
train
def distinct(l): """ Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates. """ seen = set() seen_add = seen.add return (_ for _ in l if not (_ in seen or seen_add(_)))
python
{ "resource": "" }
q56809
iter_format_modules
train
def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = [] for path in CUSTOM_FORMAT_MODULE_PATHS: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') ...
python
{ "resource": "" }
q56810
get_format_modules
train
def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list( iter_format_modules(lang))) if reverse: return list(reversed(modules)) r...
python
{ "resource": "" }
q56811
HybridView.as_view
train
def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " ...
python
{ "resource": "" }
q56812
BoxLogsStatusCodesByDate.context
train
def context(self): """Get the context.""" stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_dat...
python
{ "resource": "" }
q56813
BoxLogsMostVisitedPages.widgets
train
def widgets(self): """Get the items.""" widgets = [] for i, chart in enumerate(most_visited_pages_charts()): widgets.append(Widget(html_id='most_visited_chart_%d' % i, content=json.dumps(chart), template='meerkat/wid...
python
{ "resource": "" }
q56814
Scale.get
train
def get(self, str_representation): """Retrieves a scale representation from it's string representation :param str_representation: scale string representation to be retrieved :type str_representation: string :raises: ScaleFormatError :returns: scale representation :rt...
python
{ "resource": "" }
q56815
valid_token
train
def valid_token(token): """Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string """ is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try: Scale(token)...
python
{ "resource": "" }
q56816
extract_tokens
train
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ ...
python
{ "resource": "" }
q56817
create_random_string
train
def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will be avoided. ...
python
{ "resource": "" }
q56818
load_member
train
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
python
{ "resource": "" }
q56819
split_fqn
train
def split_fqn(fqn): """ Returns the left and right part of the import. ``fqn`` can be either a string of the form ``appname.modulename.ClassName`` or a function that returns such a string. """ if hasattr(fqn, '__call__'): fqn_string = fqn() else: fqn_string = fqn return...
python
{ "resource": "" }
q56820
Connection.send
train
def send(self, data): """ Sends data to the server. """ self.logger.debug('Send data: {}'.format(data)) if not self.connected: self.logger.warning('Connection not established. Return...') return self.websocket.send(json.dumps(data))
python
{ "resource": "" }
q56821
Connection._on_message
train
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' i...
python
{ "resource": "" }
q56822
Connection._on_close
train
def _on_close(self, socket): """ Called when the connection was closed. """ self.logger.debug('Connection closed.') for subscription in self.subscriptions.values(): if subscription.state == 'subscribed': subscription.state = 'connection_pending'
python
{ "resource": "" }
q56823
Connection.connected
train
def connected(self): """ If connected to server. """ return self.websocket is not None and \ self.websocket.sock is not None and \ self.websocket.sock.connected
python
{ "resource": "" }
q56824
Connection.find_subscription
train
def find_subscription(self, identifier): """ Finds a subscription by it's identifier. """ for subscription in self.subscriptions.values(): if subscription.identifier == identifier: return subscription
python
{ "resource": "" }
q56825
Subscription.create
train
def create(self): """ Subscribes at the server. """ self.logger.debug('Create subscription on server...') if not self.connection.connected: self.state = 'connection_pending' return data = { 'command': 'subscribe', 'identif...
python
{ "resource": "" }
q56826
Subscription.remove
train
def remove(self): """ Removes the subscription. """ self.logger.debug('Remove subscription from server...') data = { 'command': 'unsubscribe', 'identifier': self._identifier_string() } self.connection.send(data) self.state = 'unsu...
python
{ "resource": "" }
q56827
Subscription.send
train
def send(self, message): """ Sends data to the server on the subscription channel. :param data: The JSON data to send. """ self.logger.debug('Send message: {}'.format(message)) if self.state == 'pending' or self.state == 'connection_pending': self.lo...
python
{ "resource": "" }
q56828
Subscription.received
train
def received(self, data): """ API for the connection to forward information to this subscription instance. :param data: The JSON data which was received. :type data: Message """ self.logger.debug('Data received: {}'.format(data)) message_type = None ...
python
{ "resource": "" }
q56829
Subscription._subscribed
train
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
python
{ "resource": "" }
q56830
cli_opts
train
def cli_opts(): """ Handle the command line options """ parser = argparse.ArgumentParser() parser.add_argument( "--homeassistant-config", type=str, required=False, dest="config", help="Create configuration section for home assistant",) parser.add_argument( ...
python
{ "resource": "" }
q56831
Monitor._setup_signal_handler
train
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
python
{ "resource": "" }
q56832
Monitor._signal_handler
train
def _signal_handler(self, signum, frame): """ Method called when handling signals """ if self._options.config: with open(self._options.config, "w") as cfg: yaml.dump(self._home_assistant_config(), cfg) print( "Dumped home assistant configur...
python
{ "resource": "" }
q56833
Monitor.start
train
def start(self): """ Monitor the bus for events and handle them """ print("Entering monitoring mode, press CTRL-C to quit") serial = self._connection.serial while True: serial.write(b"@R") length = int(serial.read(), 16) data = serial.read(length * 2)...
python
{ "resource": "" }
q56834
Monitor._add_device
train
def _add_device(self, scs_id, ha_id, name): """ Add device to the list of known ones """ if scs_id in self._devices: return self._devices[scs_id] = { 'name': name, 'ha_id': ha_id }
python
{ "resource": "" }
q56835
Monitor._home_assistant_config
train
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': dev...
python
{ "resource": "" }
q56836
Monitor._load_filter
train
def _load_filter(self, config): """ Load the filter file and populates self._devices accordingly """ path = pathlib.Path(config) if not path.is_file(): return with open(config, 'r') as conf: devices = yaml.load(conf)['devices'] for ha_id, dev in devic...
python
{ "resource": "" }
q56837
Connection.close
train
def close(self): """ Closes the connection to the serial port and ensure no pending operatoin are left """ self._serial.write(b"@c") self._serial.read() self._serial.close()
python
{ "resource": "" }
q56838
ConfigProperty.load
train
def load(self, value): """Load a value, converting it to the proper type if validation_type exists.""" if self.property_type is None: return value elif not isinstance(self.property_type, BaseType): raise TypeError('property_type must be schematics BaseType') else:...
python
{ "resource": "" }
q56839
BaseConfig._update_property_keys
train
def _update_property_keys(cls): """Set unspecified property_keys for each ConfigProperty to the name of the class attr""" for attr_name, config_prop in cls._iter_config_props(): if config_prop.property_key is None: config_prop.property_key = attr_name
python
{ "resource": "" }
q56840
BaseConfig._set_instance_prop
train
def _set_instance_prop(self, attr_name, config_prop, value): """Set instance property to a value and add it varz if needed""" setattr(self, attr_name, value) # add to varz if it is not private if not config_prop.exclude_from_varz: self.varz[attr_name] = value
python
{ "resource": "" }
q56841
BaseConfig._load
train
def _load(self): """Load values for all ConfigProperty attributes""" for attr_name, config_prop in self._iter_config_props(): found = False for loader in self._loaders: if loader.exists(config_prop.property_key): raw_value = loader.get(config_p...
python
{ "resource": "" }
q56842
in_same_dir
train
def in_same_dir(as_file, target_file): """Return an absolute path to a target file that is located in the same directory as as_file Args: as_file: File name (including __file__) Use the directory path of this file target_file: Name of the target file """ return os.path.abspa...
python
{ "resource": "" }
q56843
compare_name
train
def compare_name(given_name, family_name, question_name): """Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer"...
python
{ "resource": "" }
q56844
OurValidator._validate_isvalid_history
train
def _validate_isvalid_history(self, isvalid_history, field, value): """Checks that the given time history is properly formatted. Args: isvalid_history (`bool`): flag from schema indicating units to be checked. field (`str`): property associated with history in question. ...
python
{ "resource": "" }
q56845
OurValidator._validate_isvalid_quantity
train
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. ...
python
{ "resource": "" }
q56846
OurValidator._validate_isvalid_uncertainty
train
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value): """Checks for valid given value and appropriate units with uncertainty. Args: isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked field (`str`): property associated with t...
python
{ "resource": "" }
q56847
OurValidator._validate_isvalid_orcid
train
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule...
python
{ "resource": "" }
q56848
OurValidator._validate_isvalid_composition
train
def _validate_isvalid_composition(self, isvalid_composition, field, value): """Checks for valid specification of composition. Args: isvalid_composition (bool): flag from schema indicating composition to be checked. field (str): 'composition' value (di...
python
{ "resource": "" }
q56849
convert_types_slow
train
def convert_types_slow(df): '''This is a slow operation.''' dtypes = get_types(df) for k, v in dtypes.items(): t = df[df['key']==k] t['value'] = t['value'].astype(v) df = df.apply(convert_row, axis=1) return df
python
{ "resource": "" }
q56850
plot_all
train
def plot_all(*args, **kwargs): ''' Read all the trial data and plot the result of applying a function on them. ''' dfs = do_all(*args, **kwargs) ps = [] for line in dfs: f, df, config = line df.plot(title=config['name']) ps.append(df) return ps
python
{ "resource": "" }
q56851
serialize
train
def serialize(v, known_modules=[]): '''Get a text representation of an object.''' tname = name(v, known_modules=known_modules) func = serializer(tname) return func(v), tname
python
{ "resource": "" }
q56852
deserialize
train
def deserialize(type_, value=None, **kwargs): '''Get an object from a text representation''' if not isinstance(type_, str): return type_ des = deserializer(type_, **kwargs) if value is None: return des return des(value)
python
{ "resource": "" }
q56853
GenericParser.content
train
def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content
python
{ "resource": "" }
q56854
GenericParser.parse_files
train
def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: ...
python
{ "resource": "" }
q56855
serialize_distribution
train
def serialize_distribution(network_agents, known_modules=[]): ''' When serializing an agent distribution, remove the thresholds, in order to avoid cluttering the YAML definition file. ''' d = deepcopy(list(network_agents)) for v in d: if 'threshold' in v: del v['threshold'] ...
python
{ "resource": "" }
q56856
_validate_states
train
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
python
{ "resource": "" }
q56857
_convert_agent_types
train
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
python
{ "resource": "" }
q56858
_agent_from_distribution
train
def _agent_from_distribution(distribution, value=-1, agent_id=None): """Used in the initialization of agents given an agent distribution.""" if value < 0: value = random.random() for d in sorted(distribution, key=lambda x: x['threshold']): threshold = d['threshold'] # Check if the de...
python
{ "resource": "" }
q56859
ModularServer.launch
train
def launch(self, port=None): """ Run the app. """ if port is not None: self.port = port url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port) print('Interface starting at {url}'.format(url=url)) self.listen(self.port) # webbrowser.open(url) t...
python
{ "resource": "" }
q56860
status_codes_by_date_stats
train
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( ...
python
{ "resource": "" }
q56861
CityPubs.enter
train
def enter(self, pub_id, *nodes): '''Agents will try to enter. The pub checks if it is possible''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) if not pub['open'] or (pub['capacity'] < (len(nodes) + pub...
python
{ "resource": "" }
q56862
CityPubs.exit
train
def exit(self, pub_id, *node_ids): '''Agents will notify the pub they want to leave''' try: pub = self['pubs'][pub_id] except KeyError: raise ValueError('Pub {} is not available'.format(pub_id)) for node_id in node_ids: node = self.get_agent(node_id) ...
python
{ "resource": "" }
q56863
Patron.looking_for_friends
train
def looking_for_friends(self): '''Look for friends to drink with''' self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_fr...
python
{ "resource": "" }
q56864
Patron.looking_for_pub
train
def looking_for_pub(self): '''Look for a pub that accepts me and my friends''' if self['pub'] != None: return self.sober_in_pub self.debug('I am looking for a pub') group = list(self.get_neighboring_agents()) for pub in self.env.available_pubs(): self.debu...
python
{ "resource": "" }
q56865
Patron.befriend
train
def befriend(self, other_agent, force=False): ''' Try to become friends with another agent. The chances of success depend on both agents' openness. ''' if force or self['openness'] > random(): self.env.add_edge(self, other_agent) self.info('Made some frien...
python
{ "resource": "" }
q56866
Patron.try_friends
train
def try_friends(self, others): ''' Look for random agents around me and try to befriend them''' befriended = False k = int(10*self['openness']) shuffle(others) for friend in islice(others, k): # random.choice >= 3.7 if friend == self: continue ...
python
{ "resource": "" }
q56867
profile_distribution
train
def profile_distribution(data): """ Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector Parameters ---------- data: array of real values Returns ------- features = dictionary containing the min, max, mean, and standard deviation """ i...
python
{ "resource": "" }
q56868
DictType.to_native
train
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, di...
python
{ "resource": "" }
q56869
ListType.to_native
train
def to_native(self, value): """Load a value as a list, converting items if necessary""" if isinstance(value, six.string_types): value_list = value.split(self.string_delim) else: value_list = value to_native = self.member_type.to_native if self.member_type is not ...
python
{ "resource": "" }
q56870
ListType.validate_member_type
train
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
python
{ "resource": "" }
q56871
ListType.validate_length
train
def validate_length(self, value): """Validate the length of value, if min_length or max_length was specified""" list_len = len(value) if value else 0 if self.max_length is not None and list_len > self.max_length: raise ValidationError( u'List has {} values; max lengt...
python
{ "resource": "" }
q56872
NetworkType.validate_resource
train
def validate_resource(self, value): """Validate the network resource with exponential backoff""" def do_backoff(*args, **kwargs): """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True: try: ...
python
{ "resource": "" }
q56873
Metafeatures.list_metafeatures
train
def list_metafeatures(cls, group="all"): """ Returns a list of metafeatures computable by the Metafeatures class. """ # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, ...
python
{ "resource": "" }
q56874
Metafeatures._sample_rows
train
def _sample_rows(self, X, Y, sample_shape, seed): """ Stratified uniform sampling of rows, according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. """ if sample_shape[0] is None or X.shape[0] <= sample_shape[0]: ...
python
{ "resource": "" }
q56875
VaultLoader._fetch_secrets
train
def _fetch_secrets(vault_url, path, token): """Read data from the vault path""" url = _url_joiner(vault_url, 'v1', path) resp = requests.get(url, headers=VaultLoader._get_headers(token)) resp.raise_for_status() data = resp.json() if data.get('errors'): raise V...
python
{ "resource": "" }
q56876
VaultLoader._fetch_app_role_token
train
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp....
python
{ "resource": "" }
q56877
VaultLoader.reload
train
def reload(self): """Reread secrets from the vault path""" self._source = self._fetch_secrets(self._vault_url, self._path, self._token)
python
{ "resource": "" }
q56878
sorted_options
train
def sorted_options(sort_options): """Sort sort options for display. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A dictionary with sorting options for Invenio-Search-JS. """ return [ { 'title': v['title'], ...
python
{ "resource": "" }
q56879
html_to_plain_text
train
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text res...
python
{ "resource": "" }
q56880
HTML2PlainParser.handle_data
train
def handle_data(self, data): """Handles data between tags.""" # Only proceed with unignored elements if self.lasttag not in self.ignored_elements: # Remove any predefined linebreaks text = data.replace('\n', '') # If there's some text left, proceed! ...
python
{ "resource": "" }
q56881
Reactor.run
train
def run(self): """ Starts the thread """ task = None monitor_task = MonitorTask( notification_endpoint=self._handle_message) while True: if self._terminate: self._logger.info("scsgate.Reactor exiting") self._connection.close() ...
python
{ "resource": "" }
q56882
mygenerator
train
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) ...
python
{ "resource": "" }
q56883
VSGProject.insert_files
train
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None): """ Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters. :param s...
python
{ "resource": "" }
q56884
encode_caveat
train
def encode_caveat(condition, root_key, third_party_info, key, ns): '''Encrypt a third-party caveat. The third_party_info key holds information about the third party we're encrypting the caveat for; the key is the public/private key pair of the party that's adding the caveat. The caveat will be enc...
python
{ "resource": "" }
q56885
_encode_caveat_v1
train
def _encode_caveat_v1(condition, root_key, third_party_pub_key, key): '''Create a JSON-encoded third-party caveat. The third_party_pub_key key represents the PublicKey of the third party we're encrypting the caveat for; the key is the public/private key pair of the party that's adding the caveat. ...
python
{ "resource": "" }
q56886
_encode_caveat_v2_v3
train
def _encode_caveat_v2_v3(version, condition, root_key, third_party_pub_key, key, ns): '''Create a version 2 or version 3 third-party caveat. The format has the following packed binary fields (note that all fields up to and including the nonce are the same as the v2 format): ...
python
{ "resource": "" }
q56887
_encode_secret_part_v2_v3
train
def _encode_secret_part_v2_v3(version, condition, root_key, ns): '''Creates a version 2 or version 3 secret part of the third party caveat. The returned data is not encrypted. The format has the following packed binary fields: version 2 or 3 [1 byte] root key length [n: uvarint] root key [n byt...
python
{ "resource": "" }
q56888
decode_caveat
train
def decode_caveat(key, caveat): '''Decode caveat by decrypting the encrypted part using key. @param key the nacl private key to decode. @param caveat bytes. @return ThirdPartyCaveatInfo ''' if len(caveat) == 0: raise VerificationError('empty third party caveat') first = caveat[:1] ...
python
{ "resource": "" }
q56889
_decode_caveat_v1
train
def _decode_caveat_v1(key, caveat): '''Decode a base64 encoded JSON id. @param key the nacl private key to decode. @param caveat a base64 encoded JSON string. ''' data = base64.b64decode(caveat).decode('utf-8') wrapper = json.loads(data) tp_public_key = nacl.public.PublicKey( base6...
python
{ "resource": "" }
q56890
_decode_caveat_v2_v3
train
def _decode_caveat_v2_v3(version, key, caveat): '''Decodes a version 2 or version 3 caveat. ''' if (len(caveat) < 1 + _PUBLIC_KEY_PREFIX_LEN + _KEY_LEN + nacl.public.Box.NONCE_SIZE + 16): raise VerificationError('caveat id too short') original_caveat = caveat caveat = caveat[1:] ...
python
{ "resource": "" }
q56891
encode_uvarint
train
def encode_uvarint(n, data): '''encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 127 n >>= 7 if n == 0: data.append(this_byte) break data.append(th...
python
{ "resource": "" }
q56892
decode_uvarint
train
def decode_uvarint(data): '''Decode a variable-length integer. Reads a sequence of unsigned integer byte and decodes them into an integer in variable-length format and returns it and the length read. ''' n = 0 shift = 0 length = 0 for b in data: if not isinstance(b, int): ...
python
{ "resource": "" }
q56893
TypeBuilder.make_enum
train
def make_enum(enum_mappings): """ Creates a type converter for an enumeration or text-to-value mapping. :param enum_mappings: Defines enumeration names and values. :return: Type converter function object for the enum/mapping. """ if (inspect.isclass(enum_mappings) and ...
python
{ "resource": "" }
q56894
TypeBuilder.make_variant
train
def make_variant(cls, converters, re_opts=None, compiled=False, strict=True): """ Creates a type converter for a number of type converter alternatives. The first matching type converter is used. REQUIRES: type_converter.pattern attribute :param converters: List of type converte...
python
{ "resource": "" }
q56895
ConversionService.isValidUnit
train
def isValidUnit(self, w): """Checks if a string represents a valid quantities unit. Args: w (str): A string to be tested against the set of valid quantities units. Returns: True if the string can be used as a unit in the quantities module. ...
python
{ "resource": "" }
q56896
ConversionService.extractUnits
train
def extractUnits(self, inp): """Collects all the valid units from an inp string. Works by appending consecutive words from the string and cross-referncing them with a set of valid units. Args: inp (str): Some text which hopefully contains descriptions of diff...
python
{ "resource": "" }
q56897
ConversionService.convert
train
def convert(self, inp): """Converts a string representation of some quantity of units into a quantities object. Args: inp (str): A textual representation of some quantity of units, e.g., "fifty kilograms". Returns: A quantities object representin...
python
{ "resource": "" }
q56898
SimpleIdentity.allow
train
def allow(self, ctx, acls): '''Allow access to any ACL members that was equal to the user name. That is, some user u is considered a member of group u and no other. ''' for acl in acls: if self._identity == acl: return True return False
python
{ "resource": "" }
q56899
expand_paths
train
def expand_paths(paths=None, predicate=None, filters=None, parent_uuid=None): """Return an unique list of resources or collections from a list of paths. Supports fq_name and wilcards resolution. >>> expand_paths(['virtual-network', 'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9']) ...
python
{ "resource": "" }