sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def gid(self): """Return the group id that the daemon will run with :rtype: int """ if not self._gid: if self.controller.config.daemon.group: self._gid = grp.getgrnam(self.config.daemon.group).gr_gid else: self._gid = os.getgid() ...
Return the group id that the daemon will run with :rtype: int
entailment
def uid(self): """Return the user id that the process will run as :rtype: int """ if not self._uid: if self.config.daemon.user: self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid else: self._uid = os.getuid() return ...
Return the user id that the process will run as :rtype: int
entailment
def _daemonize(self): """Fork into a background process and setup the process, copied in part from http://www.jejik.com/files/examples/daemon3x.py """ LOGGER.info('Forking %s into the background', sys.argv[0]) # Write the pidfile if current uid != final uid if os.getuid...
Fork into a background process and setup the process, copied in part from http://www.jejik.com/files/examples/daemon3x.py
entailment
def _get_exception_log_path(): """Return the normalized path for the connection log, raising an exception if it can not written to. :return: str """ app = sys.argv[0].split('/')[-1] for exception_log in ['/var/log/%s.errors' % app, '/var/tm...
Return the normalized path for the connection log, raising an exception if it can not written to. :return: str
entailment
def _get_pidfile_path(self): """Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError """ if self.config.daemon.pidfile: pidfile = path.abspath(self.config.daemon....
Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError
entailment
def _is_already_running(self): """Check to see if the process is running, first looking for a pidfile, then shelling out in either case, removing a pidfile if it exists but the process is not running. """ # Look for the pidfile, if exists determine if the process is alive ...
Check to see if the process is running, first looking for a pidfile, then shelling out in either case, removing a pidfile if it exists but the process is not running.
entailment
def _remove_pidfile(self): """Remove the pid file from the filesystem""" LOGGER.debug('Removing pidfile: %s', self.pidfile_path) try: os.unlink(self.pidfile_path) except OSError: pass
Remove the pid file from the filesystem
entailment
def _write_pidfile(self): """Write the pid file out with the process number in the pid file""" LOGGER.debug('Writing pidfile: %s', self.pidfile_path) with open(self.pidfile_path, "w") as handle: handle.write(str(os.getpid()))
Write the pid file out with the process number in the pid file
entailment
def to_camel_case(snake_case_string): """ Convert a string from snake case to camel case. For example, "some_var" would become "someVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. """ parts = snake_case_string.lstr...
Convert a string from snake case to camel case. For example, "some_var" would become "someVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string.
entailment
def to_capitalized_camel_case(snake_case_string): """ Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_...
Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string.
entailment
def to_snake_case(camel_case_string): """ Convert a string from camel case to snake case. From example, "someVar" would become "some_var". :param camel_case_string: Camel-cased string to convert to snake case. :return: Snake-cased version of camel_case_string. """ first_pass = _first_camel_case...
Convert a string from camel case to snake case. From example, "someVar" would become "some_var". :param camel_case_string: Camel-cased string to convert to snake case. :return: Snake-cased version of camel_case_string.
entailment
def keys_to_snake_case(camel_case_dict): """ Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary. :param camel_case_dict: Dictionary with the keys to convert. :type camel_case_dict: Di...
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary. :param camel_case_dict: Dictionary with the keys to convert. :type camel_case_dict: Dictionary. :return: Dictionary with the keys conv...
entailment
def list_functions(awsclient): """List the deployed lambda functions and print configuration. :return: exit_code """ client_lambda = awsclient.get_client('lambda') response = client_lambda.list_functions() for function in response['Functions']: log.info(function['FunctionName']) ...
List the deployed lambda functions and print configuration. :return: exit_code
entailment
def deploy_lambda(awsclient, function_name, role, handler_filename, handler_function, folders, description, timeout, memory, subnet_ids=None, security_groups=None, artifact_bucket=None, zipfile=None, fail_deployment_on_unsuccessfu...
Create or update a lambda function. :param awsclient: :param function_name: :param role: :param handler_filename: :param handler_function: :param folders: :param description: :param timeout: :param memory: :param subnet_ids: :param security_groups: :param artifact_bucket...
entailment
def bundle_lambda(zipfile): """Write zipfile contents to file. :param zipfile: :return: exit_code """ # TODO have 'bundle.zip' as default config if not zipfile: return 1 with open('bundle.zip', 'wb') as zfile: zfile.write(zipfile) log.info('Finished - a bundle.zip is wai...
Write zipfile contents to file. :param zipfile: :return: exit_code
entailment
def get_metrics(awsclient, name): """Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code """ metrics = ['Duration', 'Errors', 'Invocations', 'Throttles'] client_cw = awsclient.get_client('cloudwatch') for m...
Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code
entailment
def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Rollback a lambda function to a given version. :param awsclient: :param function_name: :param alias_name: :param version: :return: exit_code """ if version: log.info('rolling back to version {}'.form...
Rollback a lambda function to a given version. :param awsclient: :param function_name: :param alias_name: :param version: :return: exit_code
entailment
def delete_lambda(awsclient, function_name, events=None, delete_logs=False): """Delete a lambda function. :param awsclient: :param function_name: :param events: list of events :param delete_logs: :return: exit_code """ if events is not None: unwire(awsclient, events, function_na...
Delete a lambda function. :param awsclient: :param function_name: :param events: list of events :param delete_logs: :return: exit_code
entailment
def delete_lambda_deprecated(awsclient, function_name, s3_event_sources=[], time_event_sources=[], delete_logs=False): # FIXME: mutable default arguments! """Deprecated: please use delete_lambda! :param awsclient: :param function_name: :param s3_event_sources: :para...
Deprecated: please use delete_lambda! :param awsclient: :param function_name: :param s3_event_sources: :param time_event_sources: :param delete_logs: :return: exit_code
entailment
def cleanup_bundle(): """Deletes files used for creating bundle. * vendored/* * bundle.zip """ paths = ['./vendored', './bundle.zip'] for path in paths: if os.path.exists(path): log.debug("Deleting %s..." % path) if os.path.isdir(path): shu...
Deletes files used for creating bundle. * vendored/* * bundle.zip
entailment
def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param alias_name: :param version: :return: ping response payload """ log.debug('sending ping to lambda function: %s', function_n...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param alias_name: :param version: :return: ping response payload
entailment
def invoke(awsclient, function_name, payload, invocation_type=None, alias_name=ALIAS_NAME, version=None, outfile=None): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param payload: :param invocation_type: :param alias_name: :param version: ...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param payload: :param invocation_type: :param alias_name: :param version: :param outfile: write response to file :return: ping response payload
entailment
def logs(awsclient, function_name, start_dt, end_dt=None, tail=False): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param start_dt: :param end_dt: :param tail: :return: """ log.debug('Getting cloudwatch logs for: %s', function_name) log_g...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param start_dt: :param end_dt: :param tail: :return:
entailment
def __validate_datetime_string(self): """ This will require validating version string (such as "3.3.5"). A version string could be converted to a datetime value if this validation is not executed. """ try: try: StrictVersion(self._value) ...
This will require validating version string (such as "3.3.5"). A version string could be converted to a datetime value if this validation is not executed.
entailment
def ADR(self, params): """ ADR Ra, [PC, #imm10_4] ADR Ra, label Load the address of label or the PC offset into Ra Ra must be a low register """ # TODO may need to rethink how I do PC, may need to be byte alligned # TODO This is wrong as each address is a...
ADR Ra, [PC, #imm10_4] ADR Ra, label Load the address of label or the PC offset into Ra Ra must be a low register
entailment
def LDR(self, params): """ LDR Ra, [PC, #imm10_4] LDR Ra, label LDR Ra, =equate LDR Ra, [Rb, Rc] LDR Ra, [Rb, #imm7_4] LDR Ra, [SP, #imm10_4] Load a word from memory into Ra Ra, Rb, and Rc must be low registers """ # TODO definitio...
LDR Ra, [PC, #imm10_4] LDR Ra, label LDR Ra, =equate LDR Ra, [Rb, Rc] LDR Ra, [Rb, #imm7_4] LDR Ra, [SP, #imm10_4] Load a word from memory into Ra Ra, Rb, and Rc must be low registers
entailment
def LDRB(self, params): """ LDRB Ra, [Rb, Rc] LDRB Ra, [Rb, #imm5] Load a byte from memory into Ra Ra, Rb, and Rc must be low registers """ try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except iarm.exc...
LDRB Ra, [Rb, Rc] LDRB Ra, [Rb, #imm5] Load a byte from memory into Ra Ra, Rb, and Rc must be low registers
entailment
def LDRH(self, params): """ LDRH Ra, [Rb, Rc] LDRH Ra, [Rb, #imm6_2] Load a half word from memory into Ra Ra, Rb, and Rc must be low registers """ try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except i...
LDRH Ra, [Rb, Rc] LDRH Ra, [Rb, #imm6_2] Load a half word from memory into Ra Ra, Rb, and Rc must be low registers
entailment
def LDRSB(self, params): """ LDRSB Ra, [Rb, Rc] Load a byte from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers """ # TODO LDRSB cant use immediates Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) ...
LDRSB Ra, [Rb, Rc] Load a byte from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers
entailment
def LDRSH(self, params): """ LDRSH Ra, [Rb, Rc] Load a half word from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers """ # TODO LDRSH cant use immediates Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params)...
LDRSH Ra, [Rb, Rc] Load a half word from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers
entailment
def POP(self, params): """ POP {RPopList} Pop from the stack into the list of registers List must contain only low registers or PC """ # TODO verify pop order # TODO pop list is comma separate, right? # TODO what registeres are allowed to POP to? Low Regi...
POP {RPopList} Pop from the stack into the list of registers List must contain only low registers or PC
entailment
def PUSH(self, params): """ PUSH {RPushList} Push to the stack from a list of registers List must contain only low registers or LR """ # TODO what registers are allowed to PUSH to? Low registers and LR # TODO PUSH should reverse the list, not POP RPushLis...
PUSH {RPushList} Push to the stack from a list of registers List must contain only low registers or LR
entailment
def STM(self, params): """ STM Ra!, {RLoList} Store multiple registers into memory """ # TODO what registers can be stored? Ra, RLoList = self.get_two_parameters(r'\s*([^\s,]*)!,\s*{(.*)}(.*)', params).split(',') RLoList = RLoList.split(',') RLoList = [i....
STM Ra!, {RLoList} Store multiple registers into memory
entailment
def STR(self, params): """ STR Ra, [Rb, Rc] STR Ra, [Rb, #imm7_4] STR Ra, [SP, #imm10_4] Store Ra into memory as a word Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if...
STR Ra, [Rb, Rc] STR Ra, [Rb, #imm7_4] STR Ra, [SP, #imm10_4] Store Ra into memory as a word Ra, Rb, and Rc must be low registers
entailment
def STRB(self, params): """ STRB Ra, [Rb, Rc] STRB Ra, [Rb, #imm5] Store Ra into memory as a byte Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc): ...
STRB Ra, [Rb, Rc] STRB Ra, [Rb, #imm5] Store Ra into memory as a byte Ra, Rb, and Rc must be low registers
entailment
def STRH(self, params): """ STRH Ra, [Rb, Rc] STRH Ra, [Rb, #imm6_2] Store Ra into memory as a half word Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc):...
STRH Ra, [Rb, Rc] STRH Ra, [Rb, #imm6_2] Store Ra into memory as a half word Ra, Rb, and Rc must be low registers
entailment
def _stop_ec2_instances(awsclient, ec2_instances, wait=True): """Helper to stop ec2 instances. By default it waits for instances to stop. :param awsclient: :param ec2_instances: :param wait: waits for instances to stop :return: """ if len(ec2_instances) == 0: return client_e...
Helper to stop ec2 instances. By default it waits for instances to stop. :param awsclient: :param ec2_instances: :param wait: waits for instances to stop :return:
entailment
def _start_ec2_instances(awsclient, ec2_instances, wait=True): """Helper to start ec2 instances :param awsclient: :param ec2_instances: :param wait: waits for instances to start :return: """ if len(ec2_instances) == 0: return client_ec2 = awsclient.get_client('ec2') # get s...
Helper to start ec2 instances :param awsclient: :param ec2_instances: :param wait: waits for instances to start :return:
entailment
def _filter_db_instances_by_status(awsclient, db_instances, status_list): """helper to select dbinstances. :param awsclient: :param db_instances: :param status_list: :return: list of db_instances that match the filter """ client_rds = awsclient.get_client('rds') db_instances_with_status...
helper to select dbinstances. :param awsclient: :param db_instances: :param status_list: :return: list of db_instances that match the filter
entailment
def _stop_ecs_services(awsclient, services, template, parameters, wait=True): """Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: ...
Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: :param template: the cloudformation template :param parameters: the parameters u...
entailment
def stop_stack(awsclient, stack_name, use_suspend=False): """Stop an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = co...
Stop an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code
entailment
def _get_autoscaling_min_max(template, parameters, asg_name): """Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resourc...
Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resource name of the autoscaling group :return: MinSize, MaxSize
entailment
def _get_service_cluster_desired_count(template, parameters, service_name): """Helper to extract the configured desiredCount attribute from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param service_name: lo...
Helper to extract the configured desiredCount attribute from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param service_name: logical resource name of the ECS service :return: cluster, desiredCount
entailment
def start_stack(awsclient, stack_name, use_suspend=False): """Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = ...
Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code
entailment
def is_running(self): """Property method that returns a bool specifying if the process is currently running. This will return true if the state is active, idle or initializing. :rtype: bool """ return self._state in [self.STATE_ACTIVE, sel...
Property method that returns a bool specifying if the process is currently running. This will return true if the state is active, idle or initializing. :rtype: bool
entailment
def process_signal(self, signum): """Invoked whenever a signal is added to the stack. :param int signum: The signal that was added """ if signum == signal.SIGTERM: LOGGER.info('Received SIGTERM, initiating shutdown') self.stop() elif signum == signal.SIG...
Invoked whenever a signal is added to the stack. :param int signum: The signal that was added
entailment
def run(self): """The core method for starting the application. Will setup logging, toggle the runtime state flag, block on loop, then call shutdown. Redefine this method if you intend to use an IO Loop or some other long running process. """ LOGGER.info('%s v%s started...
The core method for starting the application. Will setup logging, toggle the runtime state flag, block on loop, then call shutdown. Redefine this method if you intend to use an IO Loop or some other long running process.
entailment
def start(self): """Important: Do not extend this method, rather redefine Controller.run """ for signum in [signal.SIGHUP, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2]: signal.signal(signum, self._on_signal) self.run()
Important: Do not extend this method, rather redefine Controller.run
entailment
def set_state(self, state): """Set the runtime state of the Controller. Use the internal constants to ensure proper state values: - :attr:`Controller.STATE_INITIALIZING` - :attr:`Controller.STATE_ACTIVE` - :attr:`Controller.STATE_IDLE` - :attr:`Controller.STATE_SLEEPING`...
Set the runtime state of the Controller. Use the internal constants to ensure proper state values: - :attr:`Controller.STATE_INITIALIZING` - :attr:`Controller.STATE_ACTIVE` - :attr:`Controller.STATE_IDLE` - :attr:`Controller.STATE_SLEEPING` - :attr:`Controller.STATE_STOP...
entailment
def stop(self): """Override to implement shutdown steps.""" LOGGER.info('Attempting to stop the process') self.set_state(self.STATE_STOP_REQUESTED) # Call shutdown for classes to add shutdown steps self.shutdown() # Wait for the current run to finish while self....
Override to implement shutdown steps.
entailment
def parse_ts(ts): """ parse timestamp. :param ts: timestamp in ISO8601 format :return: tbd!!! """ # ISO8601 = '%Y-%m-%dT%H:%M:%SZ' # ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ' # RFC1123 = '%a, %d %b %Y %H:%M:%S %Z' dt = maya.parse(ts.strip()) return dt.datetime(naive=True)
parse timestamp. :param ts: timestamp in ISO8601 format :return: tbd!!!
entailment
def get_outputs_for_stack(awsclient, stack_name): """ Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.servicediscovery get_outputs_for_stack((awsclient, stack_name) is used in many cloudformation.py templates! :param awsclient: :param stack_name: :return:...
Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.servicediscovery get_outputs_for_stack((awsclient, stack_name) is used in many cloudformation.py templates! :param awsclient: :param stack_name: :return: dictionary containing the stack outputs
entailment
def get_base_ami(awsclient, owners): """ DEPRECATED!!! return the latest version of our base AMI we can't use tags for this, so we have only the name as resource note: this functionality is deprecated since this only works for "old" baseami. """ client_ec2 = awsclient.get_client('ec2') ...
DEPRECATED!!! return the latest version of our base AMI we can't use tags for this, so we have only the name as resource note: this functionality is deprecated since this only works for "old" baseami.
entailment
def _add_default_arguments(parser): """Add the default arguments to the parser. :param argparse.ArgumentParser parser: The argument parser """ parser.add_argument('-c', '--config', action='store', dest='config', help='Path to the configuration file') parser.add_argument('-f...
Add the default arguments to the parser. :param argparse.ArgumentParser parser: The argument parser
entailment
def _str(val): """ Ensures that the val is the default str() type for python2 or 3 """ if str == bytes: if isinstance(val, str): return val else: return str(val) else: if isinstance(val, str): return val else: return str...
Ensures that the val is the default str() type for python2 or 3
entailment
def _prepare_long_request(self, url, api_query): """ Use requests.Request and requests.PreparedRequest to produce the body (and boundary value) of a multipart/form-data; POST request as detailed in https://www.mediawiki.org/wiki/API:Edit#Large_texts """ partlist = [] ...
Use requests.Request and requests.PreparedRequest to produce the body (and boundary value) of a multipart/form-data; POST request as detailed in https://www.mediawiki.org/wiki/API:Edit#Large_texts
entailment
def request(self, api_query, url=None): """ e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required function returns a python dict that resembles the api's json response """ api_query['format'] = 'json' if url is not None: api_url = url + "/api....
e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required function returns a python dict that resembles the api's json response
entailment
def dump(pif, fp, **kwargs): """ Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(s) to. :param kwargs: An...
Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(s) to. :param kwargs: Any options available to json.dump().
entailment
def load(fp, class_=None, **kwargs): """ Convert content in a JSON-encoded text file to a Physical Information Object or a list of such objects. :param fp: File-like object supporting .read() method to deserialize from. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param ...
Convert content in a JSON-encoded text file to a Physical Information Object or a list of such objects. :param fp: File-like object supporting .read() method to deserialize from. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param kwargs: Any options available to json.load(). ...
entailment
def loads(s, class_=None, **kwargs): """ Convert content in a JSON-encoded string to a Physical Information Object or a list of such objects. :param s: String to deserialize. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param kwargs: Any options available to json.loads()...
Convert content in a JSON-encoded string to a Physical Information Object or a list of such objects. :param s: String to deserialize. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param kwargs: Any options available to json.loads(). :return: Single object derived from :class:...
entailment
def loado(obj, class_=None): """ Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects. :param obj: Dictionary or list to convert to Physical Information Objects. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :re...
Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects. :param obj: Dictionary or list to convert to Physical Information Objects. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`...
entailment
def _dict_to_pio(d, class_=None): """ Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`.Pio`. """ d = keys_to_snake_case(d...
Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`.Pio`.
entailment
def get_command(arguments): """Utility function to extract command from docopt arguments. :param arguments: :return: command """ cmds = list(filter(lambda k: not (k.startswith('-') or k.startswith('<')) and arguments[k], arguments.keys())) if l...
Utility function to extract command from docopt arguments. :param arguments: :return: command
entailment
def dispatch(cls, arguments, **kwargs): """Dispatch arguments parsed by docopt to the cmd with matching spec. :param arguments: :param kwargs: :return: exit_code """ # first match wins # spec: all '-' elements must match, all others are False; # '<s...
Dispatch arguments parsed by docopt to the cmd with matching spec. :param arguments: :param kwargs: :return: exit_code
entailment
def get_att(self, parameter, as_reference=True): """Retrieves an attribute from an existing stack :param parameter: The output parameter which should be retrieved :param as_reference: Is the parameter a reference (Default) or a string :return: Value of parameter to retrieve """ ...
Retrieves an attribute from an existing stack :param parameter: The output parameter which should be retrieved :param as_reference: Is the parameter a reference (Default) or a string :return: Value of parameter to retrieve
entailment
def _get_notification_spec(self, lambda_arn): lambda_name = base.get_lambda_name(lambda_arn) notification_spec = { 'Id': self._make_notification_id(lambda_name), 'Events': [e for e in self._config['events']], 'LambdaFunctionArn': lambda_arn } # Add S3...
if 'key_filters' in self._config: filters_spec = {'Key': {'FilterRules': [] } } # I do not think this is a useful structure: for filter in self._config['key_filters']: if 'type' in filter and 'value' in filter and filter['type'] in ('prefix', 'suffix'): ...
entailment
def convert_representation(self, i): """ Return the proper representation for the given integer """ if self.number_representation == 'unsigned': return i elif self.number_representation == 'signed': if i & (1 << self.interpreter._bit_width - 1): ...
Return the proper representation for the given integer
entailment
def magic_generate_random(self, line): """ Set the generate random flag, unset registers and memory will return a random value. Usage: Call the magic by itself or with `true` to have registers and memory return a random value if they are unset and read from, much like how real h...
Set the generate random flag, unset registers and memory will return a random value. Usage: Call the magic by itself or with `true` to have registers and memory return a random value if they are unset and read from, much like how real hardware would work. Defaults to False, or to not ge...
entailment
def magic_postpone_execution(self, line): """ Postpone execution of instructions until explicitly run Usage: Call this magic with `true` or nothing to postpone execution, or call with `false` to execute each instruction when evaluated. This defaults to True. Not...
Postpone execution of instructions until explicitly run Usage: Call this magic with `true` or nothing to postpone execution, or call with `false` to execute each instruction when evaluated. This defaults to True. Note that each cell is executed only executed after all lines in ...
entailment
def magic_register(self, line): """ Print out the current value of a register Usage: Pass in the register, or a list of registers separated by spaces A list of registeres can be entered by separating them by a hyphen `%reg R1` or `%reg R0 R5 R6` ...
Print out the current value of a register Usage: Pass in the register, or a list of registers separated by spaces A list of registeres can be entered by separating them by a hyphen `%reg R1` or `%reg R0 R5 R6` or `%reg R8-R12`
entailment
def magic_memory(self, line): """ Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents can be entered by separating them by a hyphen `%mem 4 5` or `%mem 8-12` """ #...
Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents can be entered by separating them by a hyphen `%mem 4 5` or `%mem 8-12`
entailment
def magic_run(self, line): """ Run the current program Usage: Call with a numbe rto run that many steps, or call with no arguments to run to the end of the current program `%run` or `%run 1` """ i = float('inf') if line.strip(): ...
Run the current program Usage: Call with a numbe rto run that many steps, or call with no arguments to run to the end of the current program `%run` or `%run 1`
entailment
def magic_help(self, line): """ Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run """ line = line.strip() if not line: ...
Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run
entailment
def export_to_swagger(awsclient, api_name, stage_name, api_description, lambdas, custom_hostname=False, custom_base_path=False): """Export the API design as swagger file. :param api_name: :param stage_name: :param api_description: :param lambdas: :param custom_hos...
Export the API design as swagger file. :param api_name: :param stage_name: :param api_description: :param lambdas: :param custom_hostname: :param custom_base_path:
entailment
def list_apis(awsclient): """List APIs in account.""" client_api = awsclient.get_client('apigateway') apis = client_api.get_rest_apis()['items'] for api in apis: print(json2table(api))
List APIs in account.
entailment
def deploy_api(awsclient, api_name, api_description, stage_name, api_key, lambdas, cache_cluster_enabled, cache_cluster_size, method_settings=None): """Deploy API Gateway to AWS cloud. :param awsclient: :param api_name: :param api_description: :param stage_name: :param api_key: ...
Deploy API Gateway to AWS cloud. :param awsclient: :param api_name: :param api_description: :param stage_name: :param api_key: :param lambdas: :param cache_cluster_enabled: :param cache_cluster_size: :param method_settings:
entailment
def delete_api(awsclient, api_name): """Delete the API. :param api_name: """ _sleep() client_api = awsclient.get_client('apigateway') print('deleting api: %s' % api_name) api = _api_by_name(awsclient, api_name) if api is not None: print(json2table(api)) response = cli...
Delete the API. :param api_name:
entailment
def create_api_key(awsclient, api_name, api_key_name): """Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key """ _sleep() client_api = awsclient.get_client('apigateway') print('create api key: %s' % api_key_name) response = client...
Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key
entailment
def delete_api_key(awsclient, api_key): """Remove API key. :param api_key: """ _sleep() client_api = awsclient.get_client('apigateway') print('delete api key: %s' % api_key) response = client_api.delete_api_key( apiKey=api_key ) print(json2table(response))
Remove API key. :param api_key:
entailment
def list_api_keys(awsclient): """Print the defined API keys. """ _sleep() client_api = awsclient.get_client('apigateway') print('listing api keys') response = client_api.get_api_keys()['items'] for item in response: print(json2table(item))
Print the defined API keys.
entailment
def deploy_custom_domain(awsclient, api_name, api_target_stage, api_base_path, domain_name, route_53_record, cert_name, cert_arn, hosted_zone_id, ensure_cname): """Add custom domain to your API. :param api_name: :param api_target_stage: :param api_base_...
Add custom domain to your API. :param api_name: :param api_target_stage: :param api_base_path: :param domain_name: :param route_53_record: :param ssl_cert: :param cert_name: :param cert_arn: :param hosted_zone_id: :return: exit_code
entailment
def get_lambdas(awsclient, config, add_arn=False): """Get the list of lambda functions. :param config: :param add_arn: :return: list containing lambda entries """ if 'lambda' in config: client_lambda = awsclient.get_client('lambda') lambda_entries = config['lambda'].get('entries...
Get the list of lambda functions. :param config: :param add_arn: :return: list containing lambda entries
entailment
def _update_stage(awsclient, api_id, stage_name, method_settings): """Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name: :param method_settings: :return: """ # settings docs in response: https://botocore.readthedocs.io/en/latest/reference/servic...
Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name: :param method_settings: :return:
entailment
def _convert_method_settings_into_operations(method_settings=None): """Helper to handle the conversion of method_settings to operations :param method_settings: :return: list of operations """ # operations docs here: https://tools.ietf.org/html/rfc6902#section-4 operations = [] if method_set...
Helper to handle the conversion of method_settings to operations :param method_settings: :return: list of operations
entailment
def generate_settings(): """ This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to put into their settings file. """ conf_file = os.path.join(os.path.dirname(base_settings.__file__), 'example...
This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to put into their settings file.
entailment
def configure_app(**kwargs): """Builds up the settings using the same method as logan""" sys_args = sys.argv args, command, command_args = parse_args(sys_args[1:]) parser = OptionParser() parser.add_option('--config', metavar='CONFIG') (options, logan_args) = parser.parse_args(args) config_p...
Builds up the settings using the same method as logan
entailment
def _reset_changes(self): """Stores current values for comparison later""" self._original = {} if self.last_updated is not None: self._original['last_updated'] = self.last_updated
Stores current values for comparison later
entailment
def whisper_filename(self): """Build a file path to the Whisper database""" source_name = self.source_id and self.source.name or '' return get_valid_filename("{0}__{1}.wsp".format(source_name, self.name))
Build a file path to the Whisper database
entailment
def get_value_display(self): """Human friendly value output""" if self.display_as == 'percentage': return '{0}%'.format(self.latest_value) if self.display_as == 'boolean': return bool(self.latest_value) if self.display_as == 'byte': return defaultfilte...
Human friendly value output
entailment
def time_between_updates(self): """Time between current `last_updated` and previous `last_updated`""" if 'last_updated' not in self._original: return 0 last_update = self._original['last_updated'] this_update = self.last_updated return this_update - last_update
Time between current `last_updated` and previous `last_updated`
entailment
def do_transform(self): """Apply the transformation (if it exists) to the latest_value""" if not self.transform: return try: self.latest_value = utils.Transform( expr=self.transform, value=self.latest_value, timedelta=self.time_between_upda...
Apply the transformation (if it exists) to the latest_value
entailment
def do_counter_conversion(self): """Update latest value to the diff between it and the previous value""" if self.is_counter: if self._previous_counter_value is None: prev_value = self.latest_value else: prev_value = self._previous_counter_value ...
Update latest value to the diff between it and the previous value
entailment
def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from imagekit.cachefiles import ImageCacheFile source_group = sender # Ignore signals from unregistered groups. if source_gro...
Relay source group signals to the appropriate spec strategy.
entailment
def replace_variable(self, variable): """Substitute variables with numeric values""" if variable == 'x': return self.value if variable == 't': return self.timedelta raise ValueError("Invalid variable %s", variable)
Substitute variables with numeric values
entailment
def result(self): """Evaluate expression and return result""" # Module(body=[Expr(value=...)]) return self.eval_(ast.parse(self.expr).body[0].value)
Evaluate expression and return result
entailment
def get_people(self, user_alias=None): """ 获取用户信息 :param user_alias: 用户ID :return: """ user_alias = user_alias or self.api.user_alias content = self.api.req(API_PEOPLE_HOME % user_alias).content xml = self.api.to_xml(re.sub(b'<br />', b'\n', cont...
获取用户信息 :param user_alias: 用户ID :return:
entailment
def email_login(request, *, email, **kwargs): """ Given a request, an email and optionally some additional data, ensure that a user with the email address exists, and authenticate & login them right away if the user is active. Returns a tuple consisting of ``(user, created)`` upon success or ``(Non...
Given a request, an email and optionally some additional data, ensure that a user with the email address exists, and authenticate & login them right away if the user is active. Returns a tuple consisting of ``(user, created)`` upon success or ``(None, None)`` when authentication fails.
entailment
def dashboard(request): """Shows the latest results for each source""" sources = (models.Source.objects.all().prefetch_related('metric_set') .order_by('name')) metrics = SortedDict([(src, src.metric_set.all()) for src in sources]) no_source_metrics = models.Metr...
Shows the latest results for each source
entailment
def _create(self): """Create the Whisper file on disk""" if not os.path.exists(settings.SALMON_WHISPER_DB_PATH): os.makedirs(settings.SALMON_WHISPER_DB_PATH) archives = [whisper.parseRetentionDef(retentionDef) for retentionDef in settings.ARCHIVES.split(",")] ...
Create the Whisper file on disk
entailment
def _update(self, datapoints): """ This method store in the datapoints in the current database. :datapoints: is a list of tupple with the epoch timestamp and value [(1368977629,10)] """ if len(datapoints) == 1: timestamp, value = datapoints[0] ...
This method store in the datapoints in the current database. :datapoints: is a list of tupple with the epoch timestamp and value [(1368977629,10)]
entailment