code stringlengths 1 18.2k |
|---|
we'll try again next time around else: job = None for result in self.get_finished(): yield result # Input and yielded everything? if self.closed and self._items == 0: break sleep(timeout) |
def primitive(self): """Primitive of the backbone. Notes ----- This is the average of the positions of all the CAs in frames of `sl` `Residues`. """ cas = self.get_reference_coords() primitive_coords = make_primitive_extrapolate_ends( cas, smoothing_level=self.sl) primitive = Primitive.from_coordinates(primitive_coords... |
def fasta(self): """Generates sequence data for the protein in FASTA format.""" max_line_length = 79 fasta_str = '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format( self.parent.id.upper(), self.id) seq = self.sequence split_seq = [seq[i: i + max_line_length] for i in range(0, len(seq), max_line_length)] for seq_part in split_seq... |
def centroid(self): """Calculates the centroid of the residue. Returns ------- centroid : numpy.array or None Returns a 3D coordinate for the residue unless a CB atom is not available, in which case `None` is returned. Notes ----- Uses the definition of the centroid from Huang *et al* [2]_. References ---------- .. [2]... |
def piGenLeibniz(): """A generator function that yields the digits of Pi """ k = 1 z = (1,0,0,1) while True: lft = __lfts(k) n = int(__next(z)) if __safe(z,n): z = __prod(z,n) yield n else: z = __cons(z,lft) k += 1 |
def getPiLeibniz(n): """Returns a list containing first n digits of Pi """ mypi = piGenLeibniz() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result |
def shutdown(server, graceful=True): """Shut down the application. If a graceful stop is requested, waits for all of the IO loop's handlers to finish before shutting down the rest of the process. We impose a 10 second timeout. Based on http://tornadogists.org/3428652/ """ ioloop = IOLoop.instance() logging.info("Stoppi... |
io_loop=ioloop) poller.start() # Give up after 10 seconds of waiting. ioloop.add_timeout(time.time() + 10, final_stop) else: final_stop() |
def most_similar(self, keyword, num): """ input: keyword term of top n output: keyword result in json formmat """ try: result = self.model.most_similar(keyword, topn = num) # most_similar return a list return {'key':keyword, 'value':result, 'similarity':1} except KeyError as e: kemKeyword = self.kemNgram.find(keyword) ... |
def send(self, alf): ''' Non-blocking send ''' send_alf = SendThread(self.url, alf, self.connection_timeout, self.retry_count) send_alf.start() |
def look_source(self, sourcepath, library_paths=None): """ Open a SCSS file (sourcepath) and find all involved file through imports. This will fill internal buffers ``_CHILDREN_MAP`` and ``_PARENTS_MAP``. Args: sourcepath (str): Source file path to start searching for imports. Keyword Arguments: library_paths (list): L... |
resolved path that has not # been collected yet for path in children: if path not in self._CHILDREN_MAP: self.look_source(path, library_paths=library_paths) return |
def inspect(self, *args, **kwargs): """ Recursively inspect all given SCSS files to find imported dependencies. This does not return anything. Just fill internal buffers about inspected files. Note: This will ignore orphan files (files that are not imported from any of given SCSS files). Args: *args: One or multiple ar... |
def _get_recursive_dependancies(self, dependencies_map, sourcepath, recursive=True): """ Return all dependencies of a source, recursively searching through its dependencies. This is a common method used by ``children`` and ``parents`` methods. Args: dependencies_map (dict): Internal buffer (internal buffers ``_CHILDREN... |
source to the explorated source list walkthrough.append(item) # Current item children current_item_dependancies = dependencies_map.get(item, []) for dependency in current_item_dependancies: # Allready visited item, ignore and continue to the new # item if dependency in walkthrough: continue # Unvisited item yet, add it... |
def children(self, sourcepath, recursive=True): """ Recursively find all children that are imported from the given source path. Args: sourcepath (str): Source file path to search for. Keyword Arguments: recursive (bool): Switch to enabled recursive finding (if True). Default to True. Returns: set: List of finded parent... |
def parents(self, sourcepath, recursive=True): """ Recursively find all parents that import the given source path. Args: sourcepath (str): Source file path to search for. Keyword Arguments: recursive (bool): Switch to enabled recursive finding (if True). Default to True. Returns: set: List of finded parents path. """ r... |
def selectize_tags_media(media_type='css',name=''): """ Usage: ------ To include css media: selectize_tags_media 'css' <theme> To include Selectize Scripts: selectize_tags_media 'js' To include Selectize Scripts and Jquery: selectize_tags_media 'js' 'jquery' """ if media_type=='js': str_script='<script src="{url}"></sc... |
def show_cloudwatch_logs(self, count=10, grp_name=None): """ Show ``count`` latest CloudWatch Logs entries for our lambda function. :param count: number of log entries to show :type count: int """ if grp_name is None: grp_name = '/aws/lambda/%s' % self.config.func_name logger.debug('Log Group Name: %s', grp_name) logge... |
def _show_log_stream(self, conn, grp_name, stream_name, max_count=10): """ Show up to ``max`` events from a specified log stream; return the number of events shown. :param conn: AWS Logs API connection :type conn: :py:class:`botocore:CloudWatchLogs.Client` :param grp_name: log group name :type grp_name: str :param stre... |
events from stream', shown) return shown |
def _url_for_queue(self, conn, name): """ Given a queue name, return the URL for it. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param name: queue name, or None for all queues in config. :type name: str :return: queue URL :rtype: str """ res = conn.get_queue_url(QueueName=name) return r... |
def _delete_msg(self, conn, queue_url, receipt_handle): """ Delete the message specified by ``receipt_handle`` in the queue specified by ``queue_url``. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_url: queue URL to delete the message from :type queue_url: str :param receipt_h... |
def _show_one_queue(self, conn, name, count, delete=False): """ Show ``count`` messages from the specified SQS queue. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param name: queue name, or None for all queues in config. :type name: str :param count: maximum number of messages to get fro... |
< 2 and len(all_msgs) < count: logger.debug('Polling queue %s for messages (empty_polls=%d)', name, empty_polls) msgs = conn.receive_message( QueueUrl=url, AttributeNames=['All'], MessageAttributeNames=['All'], MaxNumberOfMessages=count, VisibilityTimeout=60, WaitTimeSeconds=20 ) if 'Messages' in msgs and len(msgs['Mes... |
def _all_queue_names(self): """ Return a list of all unique queue names in our config. :return: list of all queue names (str) :rtype: :std:term:`list` """ queues = set() endpoints = self.config.get('endpoints') for e in endpoints: for q in endpoints[e]['queues']: queues.add(q) return sorted(queues) |
def show_queue(self, name=None, count=10, delete=False): """ Show up to ``count`` messages from the queue named ``name``. If ``name`` is None, show for each queue in our config. If ``delete`` is True, delete the messages after showing them. :param name: queue name, or None for all queues in config. :type name: str :par... |
def get_api_id(self): """ Return the API ID. :return: API ID :rtype: str """ logger.debug('Connecting to AWS apigateway API') conn = client('apigateway') apis = conn.get_rest_apis() api_id = None for api in apis['items']: if api['name'] == self.config.func_name: api_id = api['id'] logger.debug('Found API id: %s', api_i... |
def set_method_settings(self): """ Set the Method settings <https://docs.aws.amazon.com/apigateway/api-\ reference/resource/stage/#methodSettings> on our Deployment Stage. This is currently not supported by Terraform; see <https://github.com/\ jantman/webhook2lambda2sqs/issues/7> and <https://github.com/hashicorp\ /ter... |
continue # else update the value; note that the API doesn't actually follow # https://tools.ietf.org/html/rfc6902#section-4 and doesn't seem # to actually accept 'add' for these. op = 'replace' if k not in curr_settings: logger.debug('Adding new methodSetting "%s" value %s', k, v) else: logger.debug('Updating methodSet... |
def _add_method_setting(self, conn, api_id, stage_name, path, key, value, op): """ Update a single method setting on the specified stage. This uses the 'add' operation to PATCH the resource. :param conn: APIGateway API connection :type conn: :py:class:`botocore:APIGateway.Client` :param api_id: ReST API ID :type api_id... |
%s,' 'but instead found value as %s', key, value, res['methodSettings']['*/*'][key]) else: logger.info('Successfully updated methodSetting %s to %s', key, value) |
def initialize_repository(path, spor_dir='.spor'): """Initialize a spor repository in `path` if one doesn't already exist. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raises: ValueError: A repository already... |
def open_repository(path, spor_dir='.spor'): """Open an existing repository. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raises: ValueError: No repository is found. """ root = _find_root_dir(path, spor_dir) ... |
def _find_root_dir(path, spor_dir): """Search for a spor repo containing `path`. This searches for `spor_dir` in directories dominating `path`. If a directory containing `spor_dir` is found, then that directory is returned as a `pathlib.Path`. Returns: The dominating directory containing `spor_dir` as a `pathlib.Path`.... |
def add(self, anchor): """Add a new anchor to the repository. This will create a new ID for the anchor and provision new storage for it. Returns: The storage ID for the Anchor which can be used to retrieve the anchor later. """ anchor_id = uuid.uuid4().hex anchor_path = self._anchor_path(anchor_id) with anchor_path.ope... |
def items(self): """An iterable of all (anchor-id, Anchor) mappings in the repository. """ for anchor_id in self: try: anchor = self[anchor_id] except KeyError: assert False, 'Trying to load from missing file or something' yield (anchor_id, anchor) |
def _anchor_path(self, anchor_id): "Absolute path to the data file for `anchor_id`." file_name = '{}.yml'.format(anchor_id) file_path = self._spor_dir / file_name return file_path |
def log(**data): """RPC method for logging events Makes entry with new account creating Return None """ # Get data from request body entry = { "module": data["params"]["module"], "event": data["params"]["event"], "timestamp": data["params"]["timestamp"], "arguments": data["params"]["arguments"] } # Call create metod fo... |
def post(self): """Accepts jsorpc post request. Retrieves data from request body. Calls log method for writung data to database """ data = json.loads(self.request.body.decode()) response = dispatch([log],{'jsonrpc': '2.0', 'method': 'log', 'params': data, 'id': 1}) |
def start_optimisation(self, rounds: int, max_angle: float, max_distance: float, temp: float=298.15, stop_when=None, verbose=None): """Starts the loop fitting protocol. Parameters ---------- rounds : int The number of Monte Carlo moves to be evaluated. max_angle : float The maximum variation in rotation that can moved ... |
def _generate_initial_score(self): """Runs the evaluation function for the initial pose.""" self.current_energy = self.eval_fn(self.polypeptide, *self.eval_args) self.best_energy = copy.deepcopy(self.current_energy) self.best_model = copy.deepcopy(self.polypeptide) return |
def _mmc_loop(self, rounds, max_angle, max_distance, temp=298.15, stop_when=None, verbose=True): """The main Metropolis Monte Carlo loop.""" current_round = 0 while current_round < rounds: working_model = copy.deepcopy(self.polypeptide) random_vector = unit_vector(numpy.random.uniform(-1, 1, size=3)) mode = random.choi... |
def check_move(new, old, t): """Determines if a model will be accepted.""" if (t <= 0) or numpy.isclose(t, 0.0): return False K_BOLTZ = 1.9872041E-003 # kcal/mol.K if new < old: return True else: move_prob = math.exp(-(new - old) / (K_BOLTZ * t)) if move_prob > random.uniform(0, 1): return True return False |
def scan_backends(self, backends): """ From given backends create and return engine, filename and extension indexes. Arguments: backends (list): List of backend engines to scan. Order does matter since resulted indexes are stored in an ``OrderedDict``. So discovering will stop its job if it meets the first item. Return... |
def get_engine(self, filepath, kind=None): """ From given filepath try to discover which backend format to use. Discovering is pretty naive as it find format from file extension. Args: filepath (str): Settings filepath or filename. Keyword Arguments: kind (str): A format name to enforce a specific backend. Can be any v... |
msg = "Given settings format is unknow: {}" raise SettingsDiscoveryError(msg.format(kind)) return self.engines[kind] |
def guess_filename(self, basedir, kind=None): """ Try to find existing settings filename from base directory using default filename from available engines. First finded filename from available engines win. So registred engines order matter. Arguments: basedir (string): Directory path where to search for. Keyword Argume... |
def search(self, filepath=None, basedir=None, kind=None): """ Search for a settings file. Keyword Arguments: filepath (string): Path to a config file, either absolute or relative. If absolute set its directory as basedir (omitting given basedir argument). If relative join it to basedir. basedir (string): Directory path... |
filepath: msg = "Either basedir or filepath is required for discovering" raise SettingsDiscoveryError(msg) if kind and kind not in self.engines: msg = "Given settings format is unknow: {}" raise SettingsDiscoveryError(msg.format(kind)) # Implicit filename to find from backend if not filepath: filename, engine = self.gu... |
def create(python, env_dir, system, prompt, bare, virtualenv_py=None): """Main entry point to use this as a module. """ if not python or python == sys.executable: _create_with_this( env_dir=env_dir, system=system, prompt=prompt, bare=bare, virtualenv_py=virtualenv_py, ) else: _create_with_python( python=python, env_dir... |
def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False return True |
def filter_events(cls, client, event_data): """Filter registered events and yield them.""" for event in cls.events: # try event filters if event.matches(client, event_data): yield event |
def filter_callbacks(cls, client, event_data): """Filter registered events and yield all of their callbacks.""" for event in cls.filter_events(client, event_data): for cb in event.callbacks: yield cb |
def validate_parameters(self): """Validate that the parameters are correctly specified.""" for p in self.params: if p not in self.known_params: raise errors.UnknownParameter(p, self.known_params) |
def parse_args(argv): """ Use Argparse to parse command-line arguments. :param argv: list of arguments to parse (``sys.argv[1:]``) :type argv: :std:term:`list` :return: parsed arguments :rtype: :py:class:`argparse.Namespace` """ p = argparse.ArgumentParser( description='webhook2lambda2sqs - Generate code and manage ' '... |
subparsers.add_parser( 'generate', help='generate lambda function and terraform configs in ./' ) tf_parsers = [ ('genapply', 'generate function and terraform configs in ./, then run ' 'terraform apply'), ('plan', 'run terraform plan to show changes which will be made'), ('apply', 'run terraform apply to apply changes/c... |
= subparsers.add_parser('logs', help='show last 10 CloudWatch ' 'Logs entries for the function') logparser.add_argument('-c', '--count', dest='log_count', type=int, default=10, help='number of log entries to show ' '(default 10') queueparser = subparsers.add_parser('queuepeek', help='show messages from ' 'one or all of... |
to STDOUT and description ' 'of it to STDERR, then exit' ) args = p.parse_args(argv) if args.action is None: # for py3, which doesn't raise on this sys.stderr.write("ERROR: too few arguments\n") raise SystemExit(2) return args |
def get_base_url(config, args): """ Get the API base url. Try Terraform state first, then :py:class:`~.AWSInfo`. :param config: configuration :type config: :py:class:`~.Config` :param args: command line arguments :type args: :py:class:`argparse.Namespace` :return: API base URL :rtype: str """ try: logger.debug('Trying ... |
def get_api_id(config, args): """ Get the API ID from Terraform, or from AWS if that fails. :param config: configuration :type config: :py:class:`~.Config` :param args: command line arguments :type args: :py:class:`argparse.Namespace` :return: API Gateway ID :rtype: str """ try: logger.debug('Trying to get Terraform re... |
def main(args=None): """ Main entry point """ # parse args if args is None: args = parse_args(sys.argv[1:]) # dump example config if that action if args.action == 'example-config': conf, doc = Config.example_config() print(conf) sys.stderr.write(doc + "\n") return # set logging level if args.verbose > 1: set_log_debug(... |
args.tf_ver.split('.')] ) # if generate or genapply, generate the configs if args.action == 'generate' or args.action == 'genapply': func_gen = LambdaFuncGenerator(config) func_src = func_gen.generate() # @TODO: also write func_source to disk tf_gen = TerraformGenerator(config, tf_ver=tf_ver) tf_gen.generate(func_src) ... |
def cmdline(argv=sys.argv[1:]): """ Script for merging different collections of stop words. """ parser = ArgumentParser( description='Create and merge collections of stop words') parser.add_argument( 'language', help='The language used in the collection') parser.add_argument('sources', metavar='FILE', nargs='+', help='... |
def authenticate(api_key, api_url, **kwargs): """Returns a muddle instance, with API key and url set for requests.""" muddle = Muddle(**kwargs) # Login. muddle.authenticate(api_key, api_url) return muddle |
def get_job_config(conf): """ Extract handler names from job_conf.xml """ rval = [] root = elementtree.parse(conf).getroot() for handler in root.find('handlers'): rval.append({'service_name' : handler.attrib['id']}) return rval |
def __load_state(self): """ Read persisted state from the JSON statefile """ try: return ConfigState(json.load(open(self.config_state_path))) except (OSError, IOError) as exc: if exc.errno == errno.ENOENT: self.__dump_state({}) return json.load(open(self.config_state_path)) raise |
def _register_config_file(self, key, val): """ Persist a newly added config file, or update (overwrite) the value of a previously persisted config. """ state = self.__load_state() if 'config_files' not in state: state['config_files'] = {} state['config_files'][key] = val self.__dump_state(state) |
def _deregister_config_file(self, key): """ Deregister a previously registered config file. The caller should ensure that it was previously registered. """ state = self.__load_state() if 'remove_configs' not in state: state['remove_configs'] = {} state['remove_configs'][key] = (state['config_files'].pop(key)) self.__du... |
def _purge_config_file(self, key): """ Forget a previously deregister config file. The caller should ensure that it was previously deregistered. """ state = self.__load_state() del state['remove_configs'][key] self.__dump_state(state) |
def determine_config_changes(self): """ The magic: Determine what has changed since the last time. Caller should pass the returned config to register_config_changes to persist. """ # 'update' here is synonymous with 'add or update' instances = set() new_configs = {} meta_changes = { 'changed_instances' : set(), 'remove... |
it) new_config['update_instance_name'] = instance_name meta_changes['changed_instances'].add(instance_name) else: # instance name is dynamically generated instance_name = stored_config['instance_name'] if ini_config['attribs'] != stored_config['attribs']: # Ensure that dynamically generated virtualenv is not lost if in... |
any instances which have been deleted for instance_name in self.get_registered_instances(include_removed=True): if instance_name not in instances: meta_changes['remove_instances'].append(instance_name) return new_configs, meta_changes |
def register_config_changes(self, configs, meta_changes): """ Persist config changes to the JSON state file. When a config changes, a process manager may perform certain actions based on these changes. This method can be called once the actions are complete. """ for config_file in meta_changes['remove_configs'].keys():... |
def get_registered_configs(self, instances=None): """ Return the persisted values of all config files registered with the config manager. """ configs = self.state.get('config_files', {}) if instances is not None: for config_file, config in configs.items(): if config['instance_name'] not in instances: configs.pop(config... |
def get_registered_instances(self, include_removed=False): """ Return the persisted names of all instances across all registered configs. """ rval = [] configs = self.state.get('config_files', {}).values() if include_removed: configs.extend(self.state.get('remove_configs', {}).values()) for config in configs: if config... |
def add(self, config_files, galaxy_root=None): """ Public method to add (register) config file(s). """ for config_file in config_files: config_file = abspath(expanduser(config_file)) if self.is_registered(config_file): log.warning('%s is already registered', config_file) continue defaults = None if galaxy_root is not N... |
async def main(): """`sublemon` library example!""" for c in (1, 2, 4,): async with Sublemon(max_concurrency=c) as s: start = time.perf_counter() await asyncio.gather(one(s), two(s)) end = time.perf_counter() print('Limiting to', c, 'concurrent subprocess(es) took', end-start, 'seconds\n') |
async def one(s: Sublemon): """Spin up some subprocesses, sleep, and echo a message for this coro.""" shell_cmds = [ 'sleep 1 && echo subprocess 1 in coroutine one', 'sleep 1 && echo subprocess 2 in coroutine one'] async for line in s.iter_lines(*shell_cmds): print(line) |
async def two(s: Sublemon): """Spin up some subprocesses, sleep, and echo a message for this coro.""" subprocess_1, subprocess_2 = s.spawn( 'sleep 1 && echo subprocess 1 in coroutine two', 'sleep 1 && echo subprocess 2 in coroutine two') async for line in amerge(subprocess_1.stdout, subprocess_2.stdout): print(line.dec... |
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): try: source = loader.get... |
__main__ source = None if source is not None: source = source.splitlines() if source is None: try: f = open(filename) try: source = f.readlines() finally: f.close() except (OSError, IOError): pass if source is None: return [] encoding = 'ascii' for line in source[:2]: # File coding may be specified. Match pattern from ... |
def get_stack_info(frames): """ Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the nescesary data to lookup all of the information we want. """ __traceback_hide__ = True # NOQA r... |
1 if lineno is not None and abs_path: context = get_lines_from_file(abs_path, lineno, 3, loader, module_name) else: context = [] # Try to pull a relative file path # This changes /foo/site-packages/baz/bar.py into baz/bar.py try: base_filename = sys.modules[module_name.split('.', 1)[0]].__file__ filename = abs_path.spl... |
def catalog_to_moc(catalog, radius, order, **kwargs): """ Convert a catalog to a MOC. The catalog is given as an Astropy SkyCoord object containing multiple coordinates. The radius of catalog entries can be given as an Astropy Quantity (with units), otherwise it is assumed to be in arcseconds. Any additional keyword ar... |
def _catalog_to_cells_neighbor(catalog, radius, order): """ Convert a catalog to a list of cells. This is the original implementation of the `catalog_to_cells` function which does not make use of the Healpy `query_disc` routine. Note: this function uses a simple flood-filling approach and is very slow, especially when ... |
True: # Find new valid neighboring cells which we didn't already # consider. neighbors = np.unique(np.ravel( get_all_neighbours(nside, new_cells, nest=True))) neighbors = np.extract( [(x != -1) and (x not in cells) and (x not in rejected) for x in neighbors], neighbors) # Get the coordinates of each of these neighbors ... |
def catalog_to_cells(catalog, radius, order, include_fallback=True, **kwargs): """ Convert a catalog to a set of cells. This function is intended to be used via `catalog_to_moc` but is available for separate usage. It takes the same arguments as that function. This function uses the Healpy `query_disc` function to get ... |
default), the cell at each position is included. If the given radius is zero (or smaller) then Healpy `query_disc` is not used -- instead the fallback position is used automatically. """ nside = 2 ** order # Ensure catalog is in ICRS coordinates. catalog = catalog.icrs # Ensure radius is in radians. if isinstance(radiu... |
# Try "disc" query. vector_cells = query_disc(nside, vector, radius, nest=True, **kwargs) if vector_cells.size > 0: cells.update(vector_cells.tolist()) continue elif not include_fallback: continue # The query didn't find anything -- include the cell at the # given position at least. cell = vec2pix(nside, vector[0], vec... |
def read_ascii_catalog(filename, format_, unit=None): """ Read an ASCII catalog file using Astropy. This routine is used by pymoctool to load coordinates from a catalog file in order to generate a MOC representation. """ catalog = ascii.read(filename, format=format_) columns = catalog.columns if 'RA' in columns and 'De... |
def create_application(self, team_id, name, url=None): """ Creates an application under a given team. :param team_id: Team identifier. :param name: The name of the new application being created. :param url: The url of where the application is located. """ params = {'name': name} if url: params['url'] = url return self.... |
def get_application_by_name(self, team_name, application_name): """ Retrieves an application using the given team name and application name. :param team_name: The name of the team of the application to be retrieved. :param application_name: The name of the application to be retrieved. """ return self._request('GET', 'r... |
def set_application_parameters(self, application_id, framework_type, repository_url): """ Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality. :param application_id: Application identifier. :param framework_type: The web framework the app was built on. ('None', 'DETECT', 'JSP', 'SPRING_MVC') :param ... |
def create_manual_finding(self, application_id, vulnerability_type, description, severity, full_url=None, native_id=None, path=None): """ Creates a manual finding with given properties. :param application_id: Application identification. :param vulnerability_type: Name of CWE vulnerability. :param description: General d... |
def create_static_finding(self, application_id, vulnerability_type, description, severity, parameter=None, file_path=None, native_id=None, column=None, line_text=None, line_number=None): """ Creates a static finding with given properties. :param application_id: Application identifier number. :param vulnerability_type: ... |
line_text: params['lineText'] = line_text if line_number: params['lineNumber'] = line_number return self._request('POST', 'rest/applications/' + str(application_id) + '/addFinding', params) |
def upload_scan(self, application_id, file_path): """ Uploads and processes a scan file. :param application_id: Application identifier. :param file_path: Path to the scan file to be uploaded. """ return self._request( 'POST', 'rest/applications/' + str(application_id) + '/upload', files={'file': open(file_path, 'rb')} ... |
def create_waf(self, name, waf_type): """ Creates a WAF with the given type. :param name: Name of the WAF. :param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb') """ params = { 'name': name, 'type': waf_type } return self._request('POST', 'rest/wafs/new', params) |
def get_waf_rules_by_application(self, waf_id, application_id): """ Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get rules for all apps. If the application is a valid application id, rules will be generated for that application. :param waf_id: WAF identifie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.