_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q260500
Stash.list
validation
def list(self, key_name=None, max_suggestions=100, cutoff=0.5, locked_only=False, key_type=None): """Return a list of all keys. """ self._assert_valid_stash() key_list = [k for k in self._storage.list() ...
python
{ "resource": "" }
q260501
Stash.delete
validation
def delete(self, key_name): """Delete a key if it exists. """ self._assert_valid_stash() if key_name == 'stored_passphrase': raise GhostError( '`stored_passphrase` is a reserved ghost key name ' 'which cannot be deleted') # TODO: Opti...
python
{ "resource": "" }
q260502
Stash.purge
validation
def purge(self, force=False, key_type=None): """Purge the stash from all keys """ self._assert_valid_stash() if not force: raise GhostError( "The `force` flag must be provided to perform a stash purge. " "I mean, you don't really want to just ...
python
{ "resource": "" }
q260503
Stash.export
validation
def export(self, output_path=None, decrypt=False): """Export all keys in the stash to a list or a file """ self._assert_valid_stash() all_keys = [] for key in self.list(): # We `dict` this as a precaution as tinydb returns # a tinydb.database.Element inst...
python
{ "resource": "" }
q260504
Stash.load
validation
def load(self, origin_passphrase, keys=None, key_file=None): """Import keys to the stash from either a list of keys or a file `keys` is a list of dictionaries created by `self.export` `stash_path` is a path to a file created by `self.export` """ # TODO: Handle keys not dict or k...
python
{ "resource": "" }
q260505
Stash._encrypt
validation
def _encrypt(self, value): """Turn a json serializable value into an jsonified, encrypted, hexa string. """ value = json.dumps(value) with warnings.catch_warnings(): warnings.simplefilter("ignore") encrypted_value = self.cipher.encrypt(value.encode('utf8')...
python
{ "resource": "" }
q260506
Stash._decrypt
validation
def _decrypt(self, hexified_value): """The exact opposite of _encrypt """ encrypted_value = binascii.unhexlify(hexified_value) with warnings.catch_warnings(): warnings.simplefilter("ignore") jsonified_value = self.cipher.decrypt( encrypted_value).d...
python
{ "resource": "" }
q260507
TinyDBStorage.get
validation
def get(self, key_name): """Return a dictionary consisting of the key itself e.g. {u'created_at': u'2016-10-10 08:31:53', u'description': None, u'metadata': None, u'modified_at': u'2016-10-10 08:31:53', u'name': u'aws', u'uid': u'459f12c0-f341-413e-9...
python
{ "resource": "" }
q260508
TinyDBStorage.delete
validation
def delete(self, key_name): """Delete the key and return true if the key was deleted, else false """ self.db.remove(Query().name == key_name) return self.get(key_name) == {}
python
{ "resource": "" }
q260509
SQLAlchemyStorage._construct_key
validation
def _construct_key(self, values): """Return a dictionary representing a key from a list of columns and a tuple of values """ key = {} for column, value in zip(self.keys.columns, values): key.update({column.name: value}) return key
python
{ "resource": "" }
q260510
ConsulStorage.put
validation
def put(self, key): """Put and return the only unique identifier possible, its url """ self._consul_request('PUT', self._key_url(key['name']), json=key) return key['name']
python
{ "resource": "" }
q260511
VaultStorage.put
validation
def put(self, key): """Put and return the only unique identifier possible, its path """ self.client.write(self._key_path(key['name']), **key) return self._key_path(key['name'])
python
{ "resource": "" }
q260512
ElasticsearchStorage.init
validation
def init(self): """Create an Elasticsearch index if necessary """ # ignore 400 (IndexAlreadyExistsException) when creating an index self.es.indices.create(index=self.params['index'], ignore=400)
python
{ "resource": "" }
q260513
S3Storage.init
validation
def init(self): """Create a bucket. """ try: self.client.create_bucket( Bucket=self.db_path, CreateBucketConfiguration=self.bucket_configuration) except botocore.exceptions.ClientError as e: # If the bucket already exists ...
python
{ "resource": "" }
q260514
terminal
validation
def terminal(port=default_port(), baud='9600'): """Launch minterm from pyserial""" testargs = ['nodemcu-uploader', port, baud] # TODO: modifying argv is no good sys.argv = testargs # resuse miniterm on main function miniterm.main()
python
{ "resource": "" }
q260515
Uploader.__set_baudrate
validation
def __set_baudrate(self, baud): """setting baudrate if supported""" log.info('Changing communication to %s baud', baud) self.__writeln(UART_SETUP.format(baud=baud)) # Wait for the string to be sent before switching baud time.sleep(0.1) try: self._port.setBaudr...
python
{ "resource": "" }
q260516
Uploader.set_timeout
validation
def set_timeout(self, timeout): """Set the timeout for the communication with the device.""" timeout = int(timeout) # will raise on Error self._timeout = timeout == 0 and 999999 or timeout
python
{ "resource": "" }
q260517
Uploader.__clear_buffers
validation
def __clear_buffers(self): """Clears the input and output buffers""" try: self._port.reset_input_buffer() self._port.reset_output_buffer() except AttributeError: #pySerial 2.7 self._port.flushInput() self._port.flushOutput()
python
{ "resource": "" }
q260518
Uploader.__expect
validation
def __expect(self, exp='> ', timeout=None): """will wait for exp to be returned from nodemcu or timeout""" timeout_before = self._port.timeout timeout = timeout or self._timeout #do NOT set timeout on Windows if SYSTEM != 'Windows': # Checking for new data every 100us...
python
{ "resource": "" }
q260519
Uploader.__write
validation
def __write(self, output, binary=False): """write data on the nodemcu port. If 'binary' is True the debug log will show the intended output as hex, otherwise as string""" if not binary: log.debug('write: %s', output) else: log.debug('write binary: %s', hexify(outp...
python
{ "resource": "" }
q260520
Uploader.__exchange
validation
def __exchange(self, output, timeout=None): """Write output to the port and wait for response""" self.__writeln(output) self._port.flush() return self.__expect(timeout=timeout or self._timeout)
python
{ "resource": "" }
q260521
Uploader.close
validation
def close(self): """restores the nodemcu to default baudrate and then closes the port""" try: if self.baud != self.start_baud: self.__set_baudrate(self.start_baud) self._port.flush() self.__clear_buffers() except serial.serialutil.SerialExcepti...
python
{ "resource": "" }
q260522
Uploader.prepare
validation
def prepare(self): """ This uploads the protocol functions nessecary to do binary chunked transfer """ log.info('Preparing esp for transfer.') for func in LUA_FUNCTIONS: detected = self.__exchange('print({0})'.format(func)) if detected.find('funct...
python
{ "resource": "" }
q260523
Uploader.download_file
validation
def download_file(self, filename): """Download a file from device to local filesystem""" res = self.__exchange('send("{filename}")'.format(filename=filename)) if ('unexpected' in res) or ('stdin' in res): log.error('Unexpected error downloading file: %s', res) raise Excep...
python
{ "resource": "" }
q260524
Uploader.read_file
validation
def read_file(self, filename, destination=''): """reading data from device into local file""" if not destination: destination = filename log.info('Transferring %s to %s', filename, destination) data = self.download_file(filename) # Just in case, the filename may cont...
python
{ "resource": "" }
q260525
Uploader.write_file
validation
def write_file(self, path, destination='', verify='none'): """sends a file to the device using the transfer protocol""" filename = os.path.basename(path) if not destination: destination = filename log.info('Transferring %s as %s', path, destination) self.__writeln("r...
python
{ "resource": "" }
q260526
Uploader.verify_file
validation
def verify_file(self, path, destination, verify='none'): """Tries to verify if path has same checksum as destination. Valid options for verify is 'raw', 'sha1' or 'none' """ content = from_file(path) log.info('Verifying using %s...' % verify) if verify == 'raw': ...
python
{ "resource": "" }
q260527
Uploader.exec_file
validation
def exec_file(self, path): """execute the lines in the local file 'path'""" filename = os.path.basename(path) log.info('Execute %s', filename) content = from_file(path).replace('\r', '').split('\n') res = '> ' for line in content: line = line.rstrip('\n') ...
python
{ "resource": "" }
q260528
Uploader.__got_ack
validation
def __got_ack(self): """Returns true if ACK is received""" log.debug('waiting for ack') res = self._port.read(1) log.debug('ack read %s', hexify(res)) return res == ACK
python
{ "resource": "" }
q260529
Uploader.write_lines
validation
def write_lines(self, data): """write lines, one by one, separated by \n to device""" lines = data.replace('\r', '').split('\n') for line in lines: self.__exchange(line)
python
{ "resource": "" }
q260530
Uploader.__write_chunk
validation
def __write_chunk(self, chunk): """formats and sends a chunk of data to the device according to transfer protocol""" log.debug('writing %d bytes chunk', len(chunk)) data = BLOCK_START + chr(len(chunk)) + chunk if len(chunk) < 128: padding = 128 - len(chunk) ...
python
{ "resource": "" }
q260531
Uploader.__read_chunk
validation
def __read_chunk(self, buf): """Read a chunk of data""" log.debug('reading chunk') timeout_before = self._port.timeout if SYSTEM != 'Windows': # Checking for new data every 100us is fast enough if self._port.timeout != MINIMAL_TIMEOUT: self._port.t...
python
{ "resource": "" }
q260532
Uploader.file_list
validation
def file_list(self): """list files on the device""" log.info('Listing files') res = self.__exchange(LIST_FILES) res = res.split('\r\n') # skip first and last lines res = res[1:-1] files = [] for line in res: files.append(line.split('\t')) ...
python
{ "resource": "" }
q260533
Uploader.file_do
validation
def file_do(self, filename): """Execute a file on the device using 'do'""" log.info('Executing '+filename) res = self.__exchange('dofile("'+filename+'")') log.info(res) return res
python
{ "resource": "" }
q260534
Uploader.file_format
validation
def file_format(self): """Formats device filesystem""" log.info('Formating, can take minutes depending on flash size...') res = self.__exchange('file.format()', timeout=300) if 'format done' not in res: log.error(res) else: log.info(res) return res
python
{ "resource": "" }
q260535
Uploader.file_print
validation
def file_print(self, filename): """Prints a file on the device to console""" log.info('Printing ' + filename) res = self.__exchange(PRINT_FILE.format(filename=filename)) log.info(res) return res
python
{ "resource": "" }
q260536
Uploader.node_heap
validation
def node_heap(self): """Show device heap size""" log.info('Heap') res = self.__exchange('print(node.heap())') log.info(res) return int(res.split('\r\n')[1])
python
{ "resource": "" }
q260537
Uploader.file_compile
validation
def file_compile(self, path): """Compiles a file specified by path on the device""" log.info('Compile '+path) cmd = 'node.compile("%s")' % path res = self.__exchange(cmd) log.info(res) return res
python
{ "resource": "" }
q260538
Uploader.file_remove
validation
def file_remove(self, path): """Removes a file on the device""" log.info('Remove '+path) cmd = 'file.remove("%s")' % path res = self.__exchange(cmd) log.info(res) return res
python
{ "resource": "" }
q260539
Uploader.backup
validation
def backup(self, path): """Backup all files from the device""" log.info('Backing up in '+path) # List file to backup files = self.file_list() # then download each of then self.prepare() for f in files: self.read_file(f[0], os.path.join(path, f[0]))
python
{ "resource": "" }
q260540
operation_upload
validation
def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart): """The upload operation""" sources, destinations = destination_from_source(sources) if len(destinations) == len(sources): if uploader.prepare(): for filename, dst in zip(sources, destinations): ...
python
{ "resource": "" }
q260541
operation_download
validation
def operation_download(uploader, sources): """The download operation""" sources, destinations = destination_from_source(sources, False) print('sources', sources) print('destinations', destinations) if len(destinations) == len(sources): if uploader.prepare(): for filename, dst in ...
python
{ "resource": "" }
q260542
operation_list
validation
def operation_list(uploader): """List file on target""" files = uploader.file_list() for f in files: log.info("{file:30s} {size}".format(file=f[0], size=f[1]))
python
{ "resource": "" }
q260543
display
validation
def display(content): """ Display a widget, text or other media in a notebook without the need to import IPython at the top level. Also handles wrapping GenePattern Python Library content in widgets. :param content: :return: """ if isinstance(content, gp.GPServer): IPython.display.d...
python
{ "resource": "" }
q260544
from_timestamp
validation
def from_timestamp(ts): """ Convert a numeric timestamp to a timezone-aware datetime. A client may override this function to change the default behavior, such as to use local time or timezone-naïve times. """ return datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
python
{ "resource": "" }
q260545
DelayedCommand.at_time
validation
def at_time(cls, at, target): """ Construct a DelayedCommand to come due at `at`, where `at` may be a datetime or timestamp. """ at = cls._from_timestamp(at) cmd = cls.from_datetime(at) cmd.delay = at - now() cmd.target = target return cmd
python
{ "resource": "" }
q260546
PeriodicCommand._localize
validation
def _localize(dt): """ Rely on pytz.localize to ensure new result honors DST. """ try: tz = dt.tzinfo return tz.localize(dt.replace(tzinfo=None)) except AttributeError: return dt
python
{ "resource": "" }
q260547
PeriodicCommandFixedDelay.daily_at
validation
def daily_at(cls, at, target): """ Schedule a command to run at a specific time each day. """ daily = datetime.timedelta(days=1) # convert when to the next datetime matching this time when = datetime.datetime.combine(datetime.date.today(), at) if when < now(): ...
python
{ "resource": "" }
q260548
strftime
validation
def strftime(fmt, t): """A class to replace the strftime in datetime package or time module. Identical to strftime behavior in those modules except supports any year. Also supports datetime.datetime times. Also supports milliseconds using %s Also supports microseconds using %u""" if isinstance(t, (time.struct_ti...
python
{ "resource": "" }
q260549
strptime
validation
def strptime(s, fmt, tzinfo=None): """ A function to replace strptime in the time module. Should behave identically to the strptime function except it returns a datetime.datetime object instead of a time.struct_time object. Also takes an optional tzinfo parameter which is a time zone info object. """ res = time...
python
{ "resource": "" }
q260550
get_nearest_year_for_day
validation
def get_nearest_year_for_day(day): """ Returns the nearest year to now inferred from a Julian date. """ now = time.gmtime() result = now.tm_year # if the day is far greater than today, it must be from last year if day - now.tm_yday > 365 // 2: result -= 1 # if the day is far less than today, it must be for ne...
python
{ "resource": "" }
q260551
get_period_seconds
validation
def get_period_seconds(period): """ return the number of seconds in the specified period >>> get_period_seconds('day') 86400 >>> get_period_seconds(86400) 86400 >>> get_period_seconds(datetime.timedelta(hours=24)) 86400 >>> get_period_seconds('day + os.system("rm -Rf *")') Traceback (most recent call last): ...
python
{ "resource": "" }
q260552
divide_timedelta_float
validation
def divide_timedelta_float(td, divisor): """ Divide a timedelta by a float value >>> one_day = datetime.timedelta(days=1) >>> half_day = datetime.timedelta(days=.5) >>> divide_timedelta_float(one_day, 2.0) == half_day True >>> divide_timedelta_float(one_day, 2) == half_day True """ # td is comprised of days,...
python
{ "resource": "" }
q260553
parse_timedelta
validation
def parse_timedelta(str): """ Take a string representing a span of time and parse it to a time delta. Accepts any string of comma-separated numbers each with a unit indicator. >>> parse_timedelta('1 day') datetime.timedelta(days=1) >>> parse_timedelta('1 day, 30 seconds') datetime.timedelta(days=1, seconds=30)...
python
{ "resource": "" }
q260554
divide_timedelta
validation
def divide_timedelta(td1, td2): """ Get the ratio of two timedeltas >>> one_day = datetime.timedelta(days=1) >>> one_hour = datetime.timedelta(hours=1) >>> divide_timedelta(one_hour, one_day) == 1 / 24 True """ try: return td1 / td2 except TypeError: # Python 3.2 gets division # http://bugs.python.org/i...
python
{ "resource": "" }
q260555
date_range
validation
def date_range(start=None, stop=None, step=None): """ Much like the built-in function range, but works with dates >>> range_items = date_range( ... datetime.datetime(2005,12,21), ... datetime.datetime(2005,12,25), ... ) >>> my_range = tuple(range_items) >>> datetime.datetime(2005,12,21) in my_range Tr...
python
{ "resource": "" }
q260556
DatetimeConstructor.construct_datetime
validation
def construct_datetime(cls, *args, **kwargs): """Construct a datetime.datetime from a number of different time types found in python and pythonwin""" if len(args) == 1: arg = args[0] method = cls.__get_dt_constructor( type(arg).__module__, type(arg).__name__, ) result = method(arg) try: ...
python
{ "resource": "" }
q260557
API.get
validation
def get(self, query, responseformat="geojson", verbosity="body", build=True): """Pass in an Overpass query in Overpass QL.""" # Construct full Overpass query if build: full_query = self._construct_ql_query( query, responseformat=responseformat, verbosity=verbosity ...
python
{ "resource": "" }
q260558
get_ports_count
validation
def get_ports_count(context, filters=None): """Return the number of ports. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are valid keys...
python
{ "resource": "" }
q260559
QuarkIpam._allocate_from_v6_subnet
validation
def _allocate_from_v6_subnet(self, context, net_id, subnet, port_id, reuse_after, ip_address=None, **kwargs): """This attempts to allocate v6 addresses as per RFC2462 and RFC3041. To accomodate this, we effectively treat all v6 assignmen...
python
{ "resource": "" }
q260560
_create_flip
validation
def _create_flip(context, flip, port_fixed_ips): """Associates the flip with ports and creates it with the flip driver :param context: neutron api request context. :param flip: quark.db.models.IPAddress object representing a floating IP :param port_fixed_ips: dictionary of the structure: {"<id of p...
python
{ "resource": "" }
q260561
create_floatingip
validation
def create_floatingip(context, content): """Allocate or reallocate a floating IP. :param context: neutron api request context. :param content: dictionary describing the floating ip, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be p...
python
{ "resource": "" }
q260562
update_floatingip
validation
def update_floatingip(context, id, content): """Update an existing floating IP. :param context: neutron api request context. :param id: id of the floating ip :param content: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put' ...
python
{ "resource": "" }
q260563
delete_floatingip
validation
def delete_floatingip(context, id): """deallocate a floating IP. :param context: neutron api request context. :param id: id of the floating ip """ LOG.info('delete_floatingip %s for tenant %s' % (id, context.tenant_id)) _delete_flip(context, id, ip_types.FLOATING)
python
{ "resource": "" }
q260564
get_floatingip
validation
def get_floatingip(context, id, fields=None): """Retrieve a floating IP. :param context: neutron api request context. :param id: The UUID of the floating IP. :param fields: a list of strings that are valid keys in a floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object i...
python
{ "resource": "" }
q260565
get_floatingips
validation
def get_floatingips(context, filters=None, fields=None, sorts=['id'], limit=None, marker=None, page_reverse=False): """Retrieve a list of floating ips. :param context: neutron api request context. :param filters: a dictionary with keys that are valid keys for a floating ip as li...
python
{ "resource": "" }
q260566
get_floatingips_count
validation
def get_floatingips_count(context, filters=None): """Return the number of floating IPs. :param context: neutron api request context :param filters: a dictionary with keys that are valid keys for a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. V...
python
{ "resource": "" }
q260567
create_scalingip
validation
def create_scalingip(context, content): """Allocate or reallocate a scaling IP. :param context: neutron api request context. :param content: dictionary describing the scaling ip, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be popu...
python
{ "resource": "" }
q260568
update_scalingip
validation
def update_scalingip(context, id, content): """Update an existing scaling IP. :param context: neutron api request context. :param id: id of the scaling ip :param content: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put' as ...
python
{ "resource": "" }
q260569
delete_scalingip
validation
def delete_scalingip(context, id): """Deallocate a scaling IP. :param context: neutron api request context. :param id: id of the scaling ip """ LOG.info('delete_scalingip %s for tenant %s' % (id, context.tenant_id)) _delete_flip(context, id, ip_types.SCALING)
python
{ "resource": "" }
q260570
get_scalingip
validation
def get_scalingip(context, id, fields=None): """Retrieve a scaling IP. :param context: neutron api request context. :param id: The UUID of the scaling IP. :param fields: a list of strings that are valid keys in a scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object in ne...
python
{ "resource": "" }
q260571
get_scalingips
validation
def get_scalingips(context, filters=None, fields=None, sorts=['id'], limit=None, marker=None, page_reverse=False): """Retrieve a list of scaling ips. :param context: neutron api request context. :param filters: a dictionary with keys that are valid keys for a scaling ip as listed...
python
{ "resource": "" }
q260572
is_isonet_vif
validation
def is_isonet_vif(vif): """Determine if a vif is on isonet Returns True if a vif belongs to an isolated network by checking for a nicira interface id. """ nicira_iface_id = vif.record.get('other_config').get('nicira-iface-id') if nicira_iface_id: return True return False
python
{ "resource": "" }
q260573
partition_vifs
validation
def partition_vifs(xapi_client, interfaces, security_group_states): """Splits VIFs into three explicit categories and one implicit Added - Groups exist in Redis that have not been ack'd and the VIF is not tagged. Action: Tag the VIF and apply flows Updated - Groups exist in Redis th...
python
{ "resource": "" }
q260574
get_groups_to_ack
validation
def get_groups_to_ack(groups_to_ack, init_sg_states, curr_sg_states): """Compares initial security group rules with current sg rules. Given the groups that were successfully returned from xapi_client.update_interfaces call, compare initial and current security group rules to determine if an upd...
python
{ "resource": "" }
q260575
run
validation
def run(): """Fetches changes and applies them to VIFs periodically Process as of RM11449: * Get all groups from redis * Fetch ALL VIFs from Xen * Walk ALL VIFs and partition them into added, updated and removed * Walk the final "modified" VIFs list and apply flows to each """ groups_cl...
python
{ "resource": "" }
q260576
QuarkQuotaDriver.delete_tenant_quota
validation
def delete_tenant_quota(context, tenant_id): """Delete the quota entries for a given tenant_id. Atfer deletion, this tenant will use default quota values in conf. """ tenant_quotas = context.session.query(Quota) tenant_quotas = tenant_quotas.filter_by(tenant_id=tenant_id) ...
python
{ "resource": "" }
q260577
_validate_subnet_cidr
validation
def _validate_subnet_cidr(context, network_id, new_subnet_cidr): """Validate the CIDR for a subnet. Verifies the specified CIDR does not overlap with the ones defined for the other subnets specified for this network, or with any other CIDR if overlapping IPs are disabled. """ if neutron_cfg.cf...
python
{ "resource": "" }
q260578
get_subnet
validation
def get_subnet(context, id, fields=None): """Retrieve a subnet. : param context: neutron api request context : param id: UUID representing the subnet to fetch. : param fields: a list of strings that are valid keys in a subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object in ...
python
{ "resource": "" }
q260579
get_subnets
validation
def get_subnets(context, limit=None, page_reverse=False, sorts=['id'], marker=None, filters=None, fields=None): """Retrieve a list of subnets. The contents of the list depends on the identity of the user making the request (as indicated by the context) as well as any filters. : para...
python
{ "resource": "" }
q260580
get_subnets_count
validation
def get_subnets_count(context, filters=None): """Return the number of subnets. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are valid ...
python
{ "resource": "" }
q260581
delete_subnet
validation
def delete_subnet(context, id): """Delete a subnet. : param context: neutron api request context : param id: UUID representing the subnet to delete. """ LOG.info("delete_subnet %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): subnet = db_api.subnet_find(context...
python
{ "resource": "" }
q260582
_perform_async_update_rule
validation
def _perform_async_update_rule(context, id, db_sg_group, rule_id, action): """Updates a SG rule async and return the job information. Only happens if the security group has associated ports. If the async connection fails the update continues (legacy mode). """ rpc_reply = None sg_rpc = sg_rpc_a...
python
{ "resource": "" }
q260583
update_security_group_rule
validation
def update_security_group_rule(context, id, security_group_rule): '''Updates a rule and updates the ports''' LOG.info("update_security_group_rule for tenant %s" % (context.tenant_id)) new_rule = security_group_rule["security_group_rule"] # Only allow updatable fields new_rule = _filter_...
python
{ "resource": "" }
q260584
JSONStrategy.get_public_net_id
validation
def get_public_net_id(self): """Returns the public net id""" for id, net_params in self.strategy.iteritems(): if id == CONF.QUARK.public_net_id: return id return None
python
{ "resource": "" }
q260585
opt_args_decorator
validation
def opt_args_decorator(func): """A decorator to be used on another decorator This is done to allow separate handling on the basis of argument values """ @wraps(func) def wrapped_dec(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # actual decorate...
python
{ "resource": "" }
q260586
Plugin._fix_missing_tenant_id
validation
def _fix_missing_tenant_id(self, context, body, key): """Will add the tenant_id to the context from body. It is assumed that the body must have a tenant_id because neutron core could never have gotten here otherwise. """ if not body: raise n_exc.BadRequest(resource=k...
python
{ "resource": "" }
q260587
AllocationPools._validate_allocation_pools
validation
def _validate_allocation_pools(self): """Validate IP allocation pools. Verify start and end address for each allocation pool are valid, ie: constituted by valid and appropriately ordered IP addresses. Also, verify pools do not overlap among themselves. Finally, verify that each ...
python
{ "resource": "" }
q260588
add_job_to_context
validation
def add_job_to_context(context, job_id): """Adds job to neutron context for use later.""" db_job = db_api.async_transaction_find( context, id=job_id, scope=db_api.ONE) if not db_job: return context.async_job = {"job": v._make_job_dict(db_job)}
python
{ "resource": "" }
q260589
create_job
validation
def create_job(context, body): """Creates a job with support for subjobs. If parent_id is not in the body: * the job is considered a parent job * it will have a NULL transaction id * its transaction id == its id * all subjobs will use its transaction id as theirs Else: * the job is a s...
python
{ "resource": "" }
q260590
NVPDriver._lswitch_select_open
validation
def _lswitch_select_open(self, context, switches=None, **kwargs): """Selects an open lswitch for a network. Note that it does not select the most full switch, but merely one with ports available. """ if switches is not None: for res in switches["results"]: ...
python
{ "resource": "" }
q260591
NVPDriver._add_default_tz_bindings
validation
def _add_default_tz_bindings(self, context, switch, network_id): """Configure any additional default transport zone bindings.""" default_tz = CONF.NVP.default_tz # If there is no default tz specified it's pointless to try # and add any additional default tz bindings. if not defa...
python
{ "resource": "" }
q260592
NVPDriver._remove_default_tz_bindings
validation
def _remove_default_tz_bindings(self, context, network_id): """Deconfigure any additional default transport zone bindings.""" default_tz = CONF.NVP.default_tz if not default_tz: LOG.warn("additional_default_tz_types specified, " "but no default_tz. Skipping " ...
python
{ "resource": "" }
q260593
NVPDriver.get_lswitch_ids_for_network
validation
def get_lswitch_ids_for_network(self, context, network_id): """Public interface for fetching lswitch ids for a given network. NOTE(morgabra) This is here because calling private methods from outside the class feels wrong, and we need to be able to fetch lswitch ids for use in other driv...
python
{ "resource": "" }
q260594
QuarkAsyncServer._load_worker_plugin_with_module
validation
def _load_worker_plugin_with_module(self, module, version): """Instantiates worker plugins that have requsite properties. The required properties are: * must have PLUGIN_EP entrypoint registered (or it wouldn't be in the list) * must have class attribute versions (list) of sup...
python
{ "resource": "" }
q260595
QuarkAsyncServer._discover_via_entrypoints
validation
def _discover_via_entrypoints(self): """Looks for modules with amtching entry points.""" emgr = extension.ExtensionManager(PLUGIN_EP, invoke_on_load=False) return ((ext.name, ext.plugin) for ext in emgr)
python
{ "resource": "" }
q260596
QuarkAsyncServer.start_api_and_rpc_workers
validation
def start_api_and_rpc_workers(self): """Initializes eventlet and starts wait for workers to exit. Spawns the workers returned from serve_rpc """ pool = eventlet.GreenPool() quark_rpc = self.serve_rpc() pool.spawn(quark_rpc.wait) pool.waitall()
python
{ "resource": "" }
q260597
BaseSegmentAllocation._chunks
validation
def _chunks(self, iterable, chunk_size): """Chunks data into chunk with size<=chunk_size.""" iterator = iter(iterable) chunk = list(itertools.islice(iterator, 0, chunk_size)) while chunk: yield chunk chunk = list(itertools.islice(iterator, 0, chunk_size))
python
{ "resource": "" }
q260598
BaseSegmentAllocation._check_collisions
validation
def _check_collisions(self, new_range, existing_ranges): """Check for overlapping ranges.""" def _contains(num, r1): return (num >= r1[0] and num <= r1[1]) def _is_overlap(r1, r2): return (_contains(r1[0], r2) or _contains(r1[1], r...
python
{ "resource": "" }
q260599
BaseSegmentAllocation._try_allocate
validation
def _try_allocate(self, context, segment_id, network_id): """Find a deallocated network segment id and reallocate it. NOTE(morgabra) This locks the segment table, but only the rows in use by the segment, which is pretty handy if we ever have more than 1 segment or segment type. ...
python
{ "resource": "" }