Search is not available for this dataset
text
stringlengths
75
104k
def CBZ(cpu, op, dest): """ Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward a constant value. It does not affect the condition flags. :param ARMv7Operand op: Specifies the register that contains the first operand. :param ...
def TBH(cpu, dest): """ Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base register provides a pointer to the table, and a second register supplies an index into the table. The branch length is twice the value of the halfword return...
def _LDM(cpu, insn_id, base, regs): """ LDM (Load Multiple) loads a non-empty subset, or possibly all, of the general-purpose registers from sequential memory locations. It is useful for block loads, stack operations and procedure exit sequences. :param int insn_id: should be one of ARM...
def _STM(cpu, insn_id, base, regs): """ STM (Store Multiple) stores a non-empty subset (or possibly all) of the general-purpose registers to sequential memory locations. :param int insn_id: should be one of ARM_INS_STM, ARM_INS_STMIB, ARM_INS_STMDA, ARM_INS_STMDB :param Armv7Ope...
def _SR(cpu, insn_id, dest, op, *rest): """ Notes on Capstone behavior: - In ARM mode, _SR reg has `rest`, but _SR imm does not, its baked into `op`. - In ARM mode, `lsr r1, r2` will have a `rest[0]` - In Thumb mode, `lsr r1, r2` will have an empty `rest` - In ARM mode, s...
def _fix_index(self, index): """ :param slice index: """ stop, start = index.stop, index.start if start is None: start = 0 if stop is None: stop = len(self) return start, stop
def _dict_diff(d1, d2): """ Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that aren't in d1. :param dict d1: First dict :param dict d2: Dict to compare with :rtype: dict """ d = {} for key in set(d1).intersection(set(d2)): ...
def locked_context(self, key=None, value_type=list): """ A context manager that provides safe parallel access to the global Manticore context. This should be used to access the global Manticore context when parallel analysis is activated. Code within the `with` block is executed ...
def context(self): """ Convenient access to shared context """ plugin_context_name = str(type(self)) if plugin_context_name not in self.manticore.context: self.manticore.context[plugin_context_name] = {} return self.manticore.context[plugin_context_name]
def add_finding(self, state, address, pc, finding, at_init, constraint=True): """ Logs a finding at specified contract and assembler line. :param state: current state :param address: contract address of the finding :param pc: program counter of the finding :param at_init:...
def add_finding_here(self, state, finding, constraint=True): """ Logs a finding in current contract and assembler line. :param state: current state :param finding: textual description of the finding :param constraint: finding is considered reproducible only when constraint is Tru...
def _save_current_location(self, state, finding, condition=True): """ Save current location in the internal locations list and returns a textual id for it. This is used to save locations that could later be promoted to a finding if other conditions hold See _get_location() :param...
def _get_location(self, state, hash_id): """ Get previously saved location A location is composed of: address, pc, finding, at_init, condition """ return state.context.setdefault('{:s}.locations'.format(self.name), {})[hash_id]
def _signed_sub_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a - b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff +80000000 False ...
def _signed_add_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a + b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff +80000000 True...
def _unsigned_sub_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a - b ffffffff bfffffff 80000001 00000000 00000001 3ffffffff 7fffffff ffffffff True ...
def _unsigned_add_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a + b ffffffff bfffffff 80000001 00000000 00000001 3ffffffff 7fffffff ffffffff True ...
def _signed_mul_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a * b +00000000000000000 +00000000000000001 +0000000003fffffff +0000000007fffffff +00000000080...
def _unsigned_mul_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a * b +00000000000000000 +00000000000000001 +0000000003fffffff +0000000007fffffff +000000000...
def _in_user_func(state): """ :param state: current state :return: whether the current execution is in a user-defined function or not. NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class. It should be fixed at some point and moved th...
def disassemble_instruction(self, code, pc): """Get next instruction using the Capstone disassembler :param str code: binary blob to be disassembled :param long pc: program counter """ return next(self.disasm.disasm(code, pc))
def istainted(arg, taint=None): """ Helper to determine whether an object if tainted. :param arg: a value or Expression :param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value. """ if not issymbolic(arg): return Fa...
def get_taints(arg, taint=None): """ Helper to list an object taints. :param arg: a value or Expression :param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value. """ if not issymbolic(arg): return for arg_taint ...
def taint_with(arg, taint, value_bits=256, index_bits=256): """ Helper to taint a value. :param arg: a value or Expression :param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value. """ from ..core.smtlib import BitVecConstan...
def interval_intersection(min1, max1, min2, max2): """ Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval, or None if they do not overlap. """ left, right = max(min1, min2), min(max1, max2) if left < right: return left, right return None
def add(self, constraint, check=False): """ Add a constraint to the set :param constraint: The constraint to add to the set. :param check: Currently unused. :return: """ if isinstance(constraint, bool): constraint = BoolConstant(constraint) as...
def _declare(self, var): """ Declare the variable `var` """ if var.name in self._declarations: raise ValueError('Variable already declared') self._declarations[var.name] = var return var
def declarations(self): """ Returns the variable expressions of this constraint set """ declarations = GetDeclarations() for a in self.constraints: try: declarations.visit(a) except RuntimeError: # TODO: (defunct) move recursion management ...
def constraints(self): """ :rtype tuple :return: All constraints represented by this and parent sets. """ if self._parent is not None: return tuple(self._constraints) + self._parent.constraints return tuple(self._constraints)
def is_declared(self, expression_var): """ True if expression_var is declared in this constraint set """ if not isinstance(expression_var, Variable): raise ValueError(f'Expression must be a Variable (not a {type(expression_var)})') return any(expression_var is x for x in self.get_dec...
def migrate(self, expression, name_migration_map=None): """ Migrate an expression created for a different constraint set to self. Returns an expression that can be used with this constraintSet All the foreign variables used in the expression are replaced by variables of this...
def new_bool(self, name=None, taint=frozenset(), avoid_collisions=False): """ Declares a free symbolic boolean in the constraint store :param name: try to assign name to internal variable representation, if not unique, a numeric nonce will be appended :param avoi...
def new_bitvec(self, size, name=None, taint=frozenset(), avoid_collisions=False): """ Declares a free symbolic bitvector in the constraint store :param size: size in bits for the bitvector :param name: try to assign name to internal variable representation, if no...
def new_array(self, index_bits=32, name=None, index_max=None, value_bits=8, taint=frozenset(), avoid_collisions=False, default=None): """ Declares a free symbolic array of value_bits long bitvectors in the constraint store. :param index_bits: size in bits for the array indexes one of [32, 64] ...
def train_encoder(X, y, fold_count, encoder): """ Defines folds and performs the data preprocessing (categorical encoding, NaN imputation, normalization) Returns a list with {X_train, y_train, X_test, y_test}, average fit_encoder_time and average score_encoder_time Note: We normalize all features (not ...
def train_model(folds, model): """ Evaluation with: Matthews correlation coefficient: represents thresholding measures AUC: represents ranking measures Brier score: represents calibration measures """ scores = [] fit_model_time = 0 # Sum of all the time spend on fitting the tr...
def fit(self, X, y=None, **kwargs): """Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-...
def fit(self, X, y=None, **kwargs): """Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-...
def inverse_transform(self, X_in): """ Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue warnings when some of those cases occur. ...
def ordinal_encoding(X_in, mapping=None, cols=None, handle_unknown='value', handle_missing='value'): """ Ordinal encoding uses a single column of integers to represent the classes. An optional mapping dict can be passed in, in this case we use the knowledge that there is some true order to the c...
def transform(self, X, override_return_df=False): """Perform the transformation to new categorical data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- p : array, shape = [n_samples, n_numeric + N] Transformed...
def reverse_dummies(self, X, mapping): """ Convert dummy variable into numerical variables Parameters ---------- X : DataFrame mapping: list-like Contains mappings of column to be transformed to it's new columns and value represented Returns ...
def get_cars_data(): """ Load the cars dataset, split it into X and y, and then call the label encoder to get an integer y column. :return: """ df = pd.read_csv('source_data/cars/car.data.txt') X = df.reindex(columns=[x for x in df.columns.values if x != 'class']) y = df.reindex(columns=['...
def get_splice_data(): """ Load the mushroom dataset, split it into X and y, and then call the label encoder to get an integer y column. :return: """ df = pd.read_csv('source_data/splice/splice.csv') X = df.reindex(columns=[x for x in df.columns.values if x != 'class']) X['dna'] = X['dna']...
def basen_to_integer(self, X, cols, base): """ Convert basen code as integers. Parameters ---------- X : DataFrame encoded data cols : list-like Column names in the DataFrame that be encoded base : int The base of transform ...
def col_transform(self, col, digits): """ The lambda body to transform the column values """ if col is None or float(col) < 0.0: return None else: col = self.number_to_base(int(col), self.base, digits) if len(col) == digits: re...
def fit(self, X, y=None, **kwargs): """Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-...
def transform(self, X, override_return_df=False): """Perform the transformation to new categorical data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- p : array, shape = [n_samples, n_numeric + N] Transformed...
def hashing_trick(X_in, hashing_method='md5', N=2, cols=None, make_copy=False): """A basic hashing implementation with configurable dimensionality/precision Performs the hashing trick on a pandas dataframe, `X`, using the hashing method from hashlib identified by `hashing_method`. The number o...
def transform(self, X, y=None, override_return_df=False): """Perform the transformation to new categorical data. Parameters ---------- X : array-like, shape = [n_samples, n_features] y : array-like, shape = [n_samples] when transform by leave one out None, when tran...
def transform_leave_one_out(self, X_in, y, mapping=None): """ Leave one out encoding uses a single column of floats to represent the means of the target variables. """ X = X_in.copy(deep=True) random_state_ = check_random_state(self.random_state) # Prepare the data ...
def get_obj_cols(df): """ Returns names of 'object' columns in the DataFrame. """ obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == 'object' or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
def convert_input(X): """ Unite data into a DataFrame. """ if not isinstance(X, pd.DataFrame): if isinstance(X, list): X = pd.DataFrame(X) elif isinstance(X, (np.generic, np.ndarray)): X = pd.DataFrame(X) elif isinstance(X, csr_matrix): X = pd....
def convert_input_vector(y, index): """ Unite target data type into a Series. If the target is a Series or a DataFrame, we preserve its index. But if the target does not contain index attribute, we use the index from the argument. """ if y is None: return None if isinstance(y, pd.Ser...
def get_generated_cols(X_original, X_transformed, to_transform): """ Returns a list of the generated/transformed columns. Arguments: X_original: df the original (input) DataFrame. X_transformed: df the transformed (current) DataFrame. to_transform: [str] ...
def fit(self, X, y, **kwargs): """Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, ...
def transform_leave_one_out(self, X_in, y, mapping=None): """ Leave one out encoding uses a single column of floats to represent the means of the target variables. """ X = X_in.copy(deep=True) random_state_ = check_random_state(self.random_state) for col, colmap in mapp...
def score_models(clf, X, y, encoder, runs=1): """ Takes in a classifier that supports multiclass classification, and X and a y, and returns a cross validation score. """ scores = [] X_test = None for _ in range(runs): X_test = encoder().fit_transform(X, y) # Some models, like...
def main(loader, name): """ Here we iterate through the datasets and score them with a classifier using different encodings. """ scores = [] raw_scores_ds = {} # first get the dataset X, y, mapping = loader() clf = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', m...
def secho(message, **kwargs): """A wrapper around click.secho that disables any coloring being used if colors have been disabled. """ # If colors are disabled, remove any color or other style data # from keyword arguments. if not settings.color: for key in ('fg', 'bg', 'bold', 'blink'): ...
def associate_notification_template(self, job_template, notification_template, status): """Associate a notification template from this job template. =====API DOCS===== Associate a notification template from this job template. :param job_template:...
def disassociate_notification_template(self, job_template, notification_template, status): """Disassociate a notification template from this job template. =====API DOCS===== Disassociate a notification template from this job template. :param j...
def callback(self, pk=None, host_config_key='', extra_vars=None): """Contact Tower and request a configuration update using this job template. =====API DOCS===== Contact Tower and request a provisioning callback using this job template. :param pk: Primary key of the job template to run...
def jt_aggregate(func, is_create=False, has_pk=False): """Decorator to aggregate unified_jt-related fields. Args: func: The CURD method to be decorated. is_create: Boolean flag showing whether this method is create. has_pk: Boolean flag showing whether this method uses pk as argument. ...
def lookup_stdout(self, pk=None, start_line=None, end_line=None, full=True): """ Internal method that lies to our `monitor` method by returning a scorecard for the workflow job where the standard out would have been expected. """ uj_res = get_resourc...
def launch(self, workflow_job_template=None, monitor=False, wait=False, timeout=None, extra_vars=None, **kwargs): """Launch a new workflow job based on a workflow job template. Creates a new workflow job in Ansible Tower, starts it, and returns back an ID in order for its status ...
def parse_args(self, ctx, args): """Parse arguments sent to this command. The code for this method is taken from MultiCommand: https://github.com/mitsuhiko/click/blob/master/click/core.py It is Copyright (c) 2014 by Armin Ronacher. See the license: https://github.com/mi...
def format_options(self, ctx, formatter): """Monkey-patch click's format_options method to support option categorization. """ field_opts = [] global_opts = [] local_opts = [] other_opts = [] for param in self.params: if param.name in SETTINGS_PARMS: ...
def list(self, **kwargs): """Return a list of objects. =====API DOCS===== Retrieve a list of Tower settings. :param category: The category slug in which to look up indevidual settings. :type category: str :param `**kwargs`: Keyword arguments list of available fields use...
def get(self, pk): """Return one and exactly one object =====API DOCS===== Return one and exactly one Tower setting. :param pk: Primary key of the Tower setting to retrieve :type pk: int :returns: loaded JSON of the retrieved Tower setting object. :rtype: dict ...
def modify(self, setting, value): """Modify an already existing object. Positional argument SETTING is the setting name and VALUE is its value, which can be provided directly or obtained from a file name if prefixed with '@'. =====API DOCS===== Modify an already existing Tower ...
def _pop_none(self, kwargs): """Remove default values (anything where the value is None). click is unfortunately bad at the way it sends through unspecified defaults.""" for key, value in copy(kwargs).items(): # options with multiple=True return a tuple if value is None o...
def _lookup(self, fail_on_missing=False, fail_on_found=False, include_debug_header=True, **kwargs): """ =====API DOCS===== Attempt to perform a lookup that is expected to return a single result, and return the record. This method is a wrapper around `get` that strips out non-unique keys...
def _convert_pagenum(self, kwargs): """ Convert next and previous from URLs to integers """ for key in ('next', 'previous'): if not kwargs.get(key): continue match = re.search(r'page=(?P<num>[\d]+)', kwargs[key]) if match is None and ke...
def read(self, pk=None, fail_on_no_results=False, fail_on_multiple_results=False, **kwargs): """ =====API DOCS===== Retrieve and return objects from the Ansible Tower API. :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read that object ...
def write(self, pk=None, create_on_missing=False, fail_on_found=False, force_on_exists=True, **kwargs): """ =====API DOCS===== Modify the given object using the Ansible Tower API. :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read that object ...
def delete(self, pk=None, fail_on_missing=False, **kwargs): """Remove the given object. If `fail_on_missing` is True, then the object's not being found is considered a failure; otherwise, a success with no change is reported. =====API DOCS===== Remove the given object. ...
def get(self, pk=None, **kwargs): """Return one and exactly one object. Lookups may be through a primary key, specified as a positional argument, and/or through filters specified through keyword arguments. If the number of results does not equal one, raise an exception. =====A...
def list(self, all_pages=False, **kwargs): """Return a list of objects. If one or more filters are provided through keyword arguments, filter the results accordingly. If no filters are provided, return all results. =====API DOCS===== Retrieve a list of objects. :param...
def _disassoc(self, url_fragment, me, other): """Disassociate the `other` record from the `me` record.""" # Get the endpoint for foreign records within this object. url = self.endpoint + '%d/%s/' % (me, url_fragment) # Attempt to determine whether the other record already is absent, fo...
def copy(self, pk=None, new_name=None, **kwargs): """Copy an object. Only the ID is used for the lookup. All provided fields are used to override the old data from the copied resource. =====API DOCS===== Copy an object. :param pk: Primary key of the resource object to ...
def modify(self, pk=None, create_on_missing=False, **kwargs): """Modify an already existing object. Fields in the resource's `identity` tuple can be used in lieu of a primary key for a lookup; in such a case, only other fields are written. To modify unique fields, you must use the prim...
def last_job_data(self, pk=None, **kwargs): """ Internal utility function for Unified Job Templates. Returns data about the last job run off of that UJT """ ujt = self.get(pk, include_debug_header=True, **kwargs) # Determine the appropriate inventory source update. if 'c...
def lookup_stdout(self, pk=None, start_line=None, end_line=None, full=True): """ Internal utility function to return standard out. Requires the pk of a unified job. """ stdout_url = '%s%s/stdout/' % (self.unified_job_type, pk) payload = {'format': 'json', 'content_encoding': 'bas...
def stdout(self, pk, start_line=None, end_line=None, outfile=sys.stdout, **kwargs): """ Print out the standard out of a unified job to the command line or output file. For Projects, print the standard out of most recent update. For Inventory Sources, print standard out of most recent syn...
def monitor(self, pk, parent_pk=None, timeout=None, interval=0.5, outfile=sys.stdout, **kwargs): """ Stream the standard output from a job, project update, or inventory udpate. =====API DOCS===== Stream the standard output from a job run to stdout. :param pk: Primary key of the...
def wait(self, pk, parent_pk=None, min_interval=1, max_interval=30, timeout=None, outfile=sys.stdout, exit_on=['successful'], **kwargs): """ Wait for a running job to finish. Blocks further input until the job completes (whether successfully or unsuccessfully) and a final status can...
def status(self, pk=None, detail=False, **kwargs): """Print the current job status. This is used to check a running job. You can look up the job with the same parameters used for a get request. =====API DOCS===== Retrieve the current job status. :param pk: Primary key of the re...
def cancel(self, pk=None, fail_if_not_running=False, **kwargs): """Cancel a currently running job. Fails with a non-zero exit status if the job cannot be canceled. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Cancel a currently running jo...
def relaunch(self, pk=None, **kwargs): """Relaunch a stopped job. Fails with a non-zero exit status if the job cannot be relaunched. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Relaunch a stopped job resource. :param pk: Primary...
def survey(self, pk=None, **kwargs): """Get the survey_spec for the job template. To write a survey, use the modify command with the --survey-spec parameter. =====API DOCS===== Get the survey specification of a resource object. :param pk: Primary key of the resource to retrieve...
def batch_update(self, pk=None, **kwargs): """Update all related inventory sources of the given inventory. Note global option --format is not available here, as the output would always be JSON-formatted. =====API DOCS===== Update all related inventory sources of the given inventory. ...
def read(self, *args, **kwargs): ''' Do extra processing so we can display the actor field as a top-level field ''' if 'actor' in kwargs: kwargs['actor'] = kwargs.pop('actor') r = super(Resource, self).read(*args, **kwargs) if 'results' in r: ...
def log(s, header='', file=sys.stderr, nl=1, **kwargs): """Log the given output to stderr if and only if we are in verbose mode. If we are not in verbose mode, this is a no-op. """ # Sanity check: If we are not in verbose mode, this is a no-op. if not settings.verbose: return # Con...
def configure_model(self, attrs, field_name): ''' Hook for ResourceMeta class to call when initializing model class. Saves fields obtained from resource class backlinks ''' self.relationship = field_name self._set_method_names(relationship=field_name) if self.res_...
def _produce_raw_method(self): ''' Returns a callable which becomes the associate or disassociate method for the related field. Method can be overridden to add additional functionality, but `_produce_method` may also need to be subclassed to decorate it appropriately. ...
def create(self, fail_on_found=False, force_on_exists=False, **kwargs): """Create a new label. There are two types of label creation: isolatedly creating a new label and creating a new label under a job template. Here the two types are discriminated by whether to provide --job-template option. ...
def version(): """Display full version information.""" # Print out the current version of Tower CLI. click.echo('Tower CLI %s' % __version__) # Print out the current API version of the current code base. click.echo('API %s' % CUR_API_VERSION) # Attempt to connect to the Ansible Tower server. ...
def _echo_setting(key): """Echo a setting to the CLI.""" value = getattr(settings, key) secho('%s: ' % key, fg='magenta', bold=True, nl=False) secho( six.text_type(value), bold=True, fg='white' if isinstance(value, six.text_type) else 'cyan', )
def config(key=None, value=None, scope='user', global_=False, unset=False): """Read or write tower-cli configuration. `tower config` saves the given setting to the appropriate Tower CLI; either the user's ~/.tower_cli.cfg file, or the /etc/tower/tower_cli.cfg file if --global is used. Writing to /...