code
stringlengths
1
18.2k
def upload_waf_log(self, waf_id, file_path): """ Uploads and processes a WAF log. :param waf_id: WAF identifier. :param file_path: Path to the WAF log file to be uploaded. """ return self._request('POST', 'rest/wafs/' + str(waf_id) + '/uploadLog', files={'file': open(file_path, 'rb')})
def get_vulnerabilities(self, teams=None, applications=None, channel_types=None, start_date=None, end_date=None, generic_severities=None, generic_vulnerabilities=None, number_merged=None, number_vulnerabilities=None, parameter=None, path=None, show_open=None, show_closed=None, show_defect_open=None, show_defect_closed=...
to show any vulnerabilities with open defects. :param show_defect_closed: Flag to show any vulnerabilities with closed defects. :param show_defect_present: Flag to show any vulnerabilities with a defect. :param show_defect_not_present: Flag to show any vulnerabilities without a defect. :param show_false_positive: Flag ...
if show_defect_open: params['showDefectOpen'] = show_defect_open if show_defect_closed: params['showDefectClosed'] = show_defect_closed if show_defect_present: params['showDefectPresent'] = show_defect_present if show_defect_not_present: params['showDefectNotPresent'] = show_defect_not_present if show_false_positive: p...
def _build_list_params(param_name, key, values): """Builds a list of POST parameters from a list or single value.""" params = {} if hasattr(values, '__iter__'): index = 0 for value in values: params[str(param_name) + '[' + str(index) + '].' + str(key)] = str(value) index += 1 else: params[str(param_name) + '[0].' + str...
def _request(self, method, url, params=None, files=None): """Common handler for all HTTP requests.""" if not params: params = {} params['apiKey'] = self.api_key headers = { 'User-Agent': self.user_agent, 'Accept': 'application/json' } try: if self.debug: print(method + ' ' + url) print(params) response = requests.reque...
success=False)
def data_json(self, pretty=False): """Returns the data as a valid JSON string.""" if pretty: return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': ')) else: return json.dumps(self.data)
def get_anchor_diff(anchor): """Get the get_anchor_diff between an anchor and the current state of its source. Returns: A tuple of get_anchor_diff lines. If there is not different, then this returns an empty tuple. """ new_anchor = make_anchor( file_path=anchor.file_path, offset=anchor.context.offset, width=len(anchor....
def make_anchor(file_path: pathlib.Path, offset: int, width: int, context_width: int, metadata, encoding: str = 'utf-8', handle=None): """Construct a new `Anchor`. Args: file_path: The absolute path to the target file for the anchor. offset: The offset of the anchored text in codepoints in `file_path`'s contents. width...
is not absolute. """ @contextmanager def get_handle(): if handle is None: with file_path.open(mode='rt', encoding=encoding) as fp: yield fp else: yield handle with get_handle() as fp: context = _make_context(fp, offset, width, context_width) return Anchor( file_path=file_path, encoding=encoding, context=context, metada...
def rgba_to_int(cls, red, green, blue, alpha): """ Encodes the color as an Integer in RGBA encoding Returns None if any of red, green or blue are None. If alpha is None we use 255 by default. :return: Integer :rtype: int """ red = unwrap(red) green = unwrap(green) blue = unwrap(blue) alpha = unwrap(alpha) if red is Non...
async def amerge(*agens) -> AsyncGenerator[Any, None]: """Thin wrapper around aiostream.stream.merge.""" xs = stream.merge(*agens) async with xs.stream() as streamer: async for x in streamer: yield x
def crossplat_loop_run(coro) -> Any: """Cross-platform method for running a subprocess-spawning coroutine.""" if sys.platform == 'win32': signal.signal(signal.SIGINT, signal.SIG_DFL) loop = asyncio.ProactorEventLoop() else: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) with contextlib.closing(loop): retu...
def quantiles(xs, qs=None, step=25, width=None, cellspacing=3): ''' Use stats.quantiles to get quantile-value pairs, and then print them to fit. >>> import numpy as np >>> quantiles(np.random.normal(size=10000), qs=[0, 5, 50, 95, 100]) 0% < -3.670 5% < -1.675 50% < -0.002 95% < 1.6500 100% < 3.4697 (Or something like t...
def parse_args(args): ''' Parse an argument string http://stackoverflow.com/questions/18160078/ how-do-you-write-tests-for-the-argparse-portion-of-a-python-module ''' parser = argparse.ArgumentParser() parser.add_argument('config_file', nargs='?', help='Configuration yaml file', default=None) parser.add_argument( '--lo...
def _factory(importname, base_class_type, path=None, *args, **kargs): ''' Load a module of a given base class type Parameter -------- importname: string Name of the module, etc. converter base_class_type: class type E.g converter path: Absoulte path of the module Neede for extensions. If not given module is in online_m...
name indendend clsmembers = getmembers(module, is_base_class) if not len(clsmembers): raise ValueError('Found no matching class in %s.' % importname) else: cls = clsmembers[0][1] return cls(*args, **kargs)
def json_numpy_obj_hook(dct): """Decodes a previously encoded numpy ndarray with proper shape and dtype. And decompresses the data with blosc :param dct: (dict) json encoded ndarray :return: (ndarray) if input was an encoded ndarray """ if isinstance(dct, dict) and '__ndarray__' in dct: array = dct['__ndarray__'] # htt...
def default(self, obj): """If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded and blosc compressed. """ if isinstance(obj, np.ndarray): if obj.flags['C_CONTIGUOUS']: obj_data = obj.data else: cont_obj = np.ascontiguousarray(obj) assert(cont_obj.flags['C_CONT...
def run_dssp(pdb, path=True): """Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. Returns ------- dssp_out : str Std out from DSSP. """ if not path: if isinstance(pdb, str):...
def extract_all_ss_dssp(in_dssp, path=True): """Uses DSSP to extract secondary structure information on every residue. Parameters ---------- in_dssp : str Path to DSSP file. path : bool, optional Indicates if pdb is a path or a string. Returns ------- dssp_residues : [tuple] Each internal list contains: [0] int Residue...
chain, residue, phi, psi, acc)) except ValueError: pass else: if line[2] == '#': active = True return dssp_residues
def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')): """Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered into a separate list, and ...
is None: fragment.append(ele) elif ele[2] != previous_ele[2]: fragments.append(fragment) fragment = [ele] elif previous_ele[1] in loops: if ele[1] in loops: fragment.append(ele) else: fragments.append(fragment) fragment = [ele] else: if ele[1] == previous_ele[1]: fragment.append(ele) else: fragments.append(fragment) fr...
def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')): """Adds output data from DSSP to an Assembly. A dictionary will be added to the `tags` dictionary of each residue called `dssp_data`, which contains the secondary structure definition, solvent accessibility phi and psi values from DSSP. A list of regio...
'solvent_accessibility': sacc, 'phi': phi, 'psi': psi } ss_regions = find_ss_regions(dssp_data, loop_assignments) for region in ss_regions: chain = region[0][2] ss_type = ' ' if region[0][1] in loop_assignments else region[0][1] first_residue = str(region[0][0]) last_residue = str(region[-1][0]) if not 'ss_regions' in ...
def get_ss_regions(assembly, ss_types): """Returns an Assembly containing Polymers for each region of structure. Parameters ---------- assembly : ampal.Assembly `Assembly` object to be searched secondary structure regions. ss_types : list List of secondary structure tags to be separate i.e. ['H'] would return helices, ...
secondary structure type' ' have been found. Use standard DSSP labels.') return fragments
def extract(query_dict, prefix=""): """ Extract the *order_by*, *per_page*, and *page* parameters from `query_dict` (a Django QueryDict), and return a dict suitable for instantiating a preconfigured Table object. """ strs = ['order_by'] ints = ['per_page', 'page'] extracted = { } for key in (strs + ints): if (prefix + ...
def _copy(query_dict): """ Return a mutable copy of `query_dict`. This is a workaround to Django bug #13572, which prevents QueryDict.copy from working. """ memo = { } result = query_dict.__class__('', encoding=query_dict.encoding, mutable=True) memo[id(query_dict)] = result for key, value in dict.items(query_dict): di...
def snaql_migration(ctx, db_uri, migrations, app, config): """ Lightweight SQL Schema migration tool based on Snaql queries """ if config: migrations_config = _parse_config(config) else: if db_uri and migrations and app: migrations_config = _generate_config(db_uri, migrations, app) else: raise click.ClickException('If ...
def show(ctx): """ Show migrations list """ for app_name, app in ctx.obj['config']['apps'].items(): click.echo(click.style(app_name, fg='green', bold=True)) for migration in app['migrations']: applied = ctx.obj['db'].is_migration_applied(app_name, migration) click.echo(' {0} {1}'.format(migration, click.style('(applied...
def apply(ctx, name, verbose): """ Apply migration """ if name != 'all': # specific migration try: app_name, target_migration = name.split('/', 2) except ValueError: raise click.ClickException("NAME format is <app>/<migration> or 'all'") apps = ctx.obj['config']['apps'] if app_name not in apps.keys(): raise click.Click...
in ctx.obj['config']['apps'].items(): click.echo(click.style('Migrating {0}...'.format(click.style(app_name, bold=True)), fg='blue')) for migration in app['migrations']: click.echo(' Applying {0}...'.format(click.style(migration, bold=True))) if ctx.obj['db'].is_migration_applied(app_name, migration): click.echo(click....
def revert(ctx, name, verbose): """ Revert migration """ try: app_name, target_migration = name.split('/', 2) except ValueError: raise click.ClickException('NAME format is <app>/<migration>') apps = ctx.obj['config']['apps'] if app_name not in apps.keys(): raise click.ClickException('unknown app "{0}"'.format(app_name)...
def bundle(self, name: str) -> models.Bundle: """Fetch a bundle from the store.""" return self.Bundle.filter_by(name=name).first()
def version(self, bundle: str, date: dt.datetime) -> models.Version: """Fetch a version from the store.""" return (self.Version.query .join(models.Version.bundle) .filter(models.Bundle.name == bundle, models.Version.created_at == date) .first())
def tag(self, name: str) -> models.Tag: """Fetch a tag from the database.""" return self.Tag.filter_by(name=name).first()
def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle: """Create a new file bundle.""" new_bundle = self.Bundle(name=name, created_at=created_at) return new_bundle
def new_version(self, created_at: dt.datetime, expires_at: dt.datetime=None) -> models.Version: """Create a new bundle version.""" new_version = self.Version(created_at=created_at, expires_at=expires_at) return new_version
def new_file(self, path: str, checksum: str=None, to_archive: bool=False, tags: List[models.Tag]=None) -> models.File: """Create a new file.""" new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags) return new_file
def new_tag(self, name: str, category: str=None) -> models.Tag: """Create a new tag.""" new_tag = self.Tag(name=name, category=category) return new_tag
def files(self, *, bundle: str=None, tags: List[str]=None, version: int=None, path: str=None) -> models.File: """Fetch files from the store.""" query = self.File.query if bundle: query = (query.join(self.File.version, self.Version.bundle) .filter(self.Bundle.name == bundle)) if tags: # require records to match ALL tags...
def files_before(self, *, bundle: str=None, tags: List[str]=None, before: str=None) -> models.File: """Fetch files before date from store""" query = self.files(tags=tags, bundle=bundle) if before: before_dt = parse_date(before) query = query.join(models.Version).filter(models.Version.created_at < before_dt) return quer...
def files_ondisk(self, file_objs: models.File) -> set: """Returns a list of files that are not on disk.""" return set([ file_obj for file_obj in file_objs if Path(file_obj.full_path).is_file() ])
def _unquote_c_string(s): """replace C-style escape sequences (\n, \", etc.) with real chars.""" # doing a s.encode('utf-8').decode('unicode_escape') can return an # incorrect output with unicode string (both in py2 and py3) the safest way # is to match the escape sequences and decoding them alone. def decode_match(mat...
def readline(self): """Get the next line including the newline or '' on EOF.""" self.lineno += 1 if self._buffer: return self._buffer.pop() else: return self.input.readline()
def push_line(self, line): """Push line back onto the line buffer. :param line: the line with no trailing newline """ self.lineno -= 1 self._buffer.append(line + b'\n')
def read_bytes(self, count): """Read a given number of bytes from the input stream. Throws MissingBytes if the bytes are not found. Note: This method does not read from the line buffer. :return: a string """ result = self.input.read(count) found = len(result) self.lineno += result.count(b'\n') if found != count: self.a...
def read_until(self, terminator): """Read the input stream until the terminator is found. Throws MissingTerminator if the terminator is not found. Note: This method does not read from the line buffer. :return: the bytes read up to but excluding the terminator. """ lines = [] term = terminator + b'\n' while True: line =...
def iter_commands(self): """Iterator returning ImportCommand objects.""" while True: line = self.next_line() if line is None: if b'done' in self.features: raise errors.PrematureEndOfStream(self.lineno) break elif len(line) == 0 or line.startswith(b'#'): continue # Search for commands in order of likelihood elif line.st...
def iter_file_commands(self): """Iterator returning FileCommand objects. If an invalid file command is found, the line is silently pushed back and iteration ends. """ while True: line = self.next_line() if line is None: break elif len(line) == 0 or line.startswith(b'#'): continue # Search for file commands in order of ...
def _parse_blob(self): """Parse a blob command.""" lineno = self.lineno mark = self._get_mark_if_any() data = self._get_data(b'blob') return commands.BlobCommand(mark, data, lineno)
def _parse_commit(self, ref): """Parse a commit command.""" lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b'commit', b'author', False) more_authors = [] while True: another_author = self._get_user_info(b'commit', b'author', False) if another_author is not None: more_authors.append(ano...
def _parse_feature(self, info): """Parse a feature command.""" parts = info.split(b'=', 1) name = parts[0] if len(parts) > 1: value = self._path(parts[1]) else: value = None self.features[name] = value return commands.FeatureCommand(name, value, lineno=self.lineno)
def _parse_file_modify(self, info): """Parse a filemodify command within a commit. :param info: a string in the format "mode dataref path" (where dataref might be the hard-coded literal 'inline'). """ params = info.split(b' ', 2) path = self._path(params[2]) mode = self._mode(params[0]) if params[1] == b'inline': datar...
def _parse_reset(self, ref): """Parse a reset command.""" from_ = self._get_from() return commands.ResetCommand(ref, from_)
def _parse_tag(self, name): """Parse a tag command.""" from_ = self._get_from(b'tag') tagger = self._get_user_info(b'tag', b'tagger', accept_just_who=True) message = self._get_data(b'tag', b'message') return commands.TagCommand(name, from_, tagger, message)
def _get_mark_if_any(self): """Parse a mark section.""" line = self.next_line() if line.startswith(b'mark :'): return line[len(b'mark :'):] else: self.push_line(line) return None
def _get_from(self, required_for=None): """Parse a from section.""" line = self.next_line() if line is None: return None elif line.startswith(b'from '): return line[len(b'from '):] elif required_for: self.abort(errors.MissingSection, required_for, 'from') else: self.push_line(line) return None
def _get_merge(self): """Parse a merge section.""" line = self.next_line() if line is None: return None elif line.startswith(b'merge '): return line[len(b'merge '):] else: self.push_line(line) return None
def _get_property(self): """Parse a property section.""" line = self.next_line() if line is None: return None elif line.startswith(b'property '): return self._name_value(line[len(b'property '):]) else: self.push_line(line) return None
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_who) elif required: self.abort(errors.MissingSection, cmd, sec...
def _get_data(self, required_for, section=b'data'): """Parse a data section.""" line = self.next_line() if line.startswith(b'data '): rest = line[len(b'data '):] if rest.startswith(b'<<'): return self.read_until(rest[2:]) else: size = int(rest) read_bytes = self.read_bytes(size) # optional LF after data. next_line = se...
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) if match: datestr = match.group(3).lstrip() if self.d...
name = s email = None when = dates.DATE_PARSERS_BY_NAME['now']('now') if len(name) > 0: if name.endswith(b' '): name = name[:-1] # While it shouldn't happen, some datasets have email addresses # which contain unicode characters. See bug 338186. We sanitize # the data at this level just in case. if self.user_mapper: nam...
def _name_value(self, s): """Parse a (name,value) tuple from 'name value-length value'.""" parts = s.split(b' ', 2) name = parts[0] if len(parts) == 1: value = None else: size = int(parts[1]) value = parts[2] still_to_read = size - len(value) if still_to_read > 0: read_bytes = self.read_bytes(still_to_read) value += b'...
def _path(self, s): """Parse a path.""" if s.startswith(b'"'): if not s.endswith(b'"'): self.abort(errors.BadFormat, '?', '?', s) else: return _unquote_c_string(s[1:-1]) return s
def _path_pair(self, s): """Parse two paths separated by a space.""" # TODO: handle a space in the first path if s.startswith(b'"'): parts = s[1:].split(b'" ', 1) else: parts = s.split(b' ', 1) if len(parts) != 2: self.abort(errors.BadFormat, '?', '?', s) elif parts[1].startswith(b'"') and parts[1].endswith(b'"'): part...
def _mode(self, s): """Check file mode format and parse into an int. :return: mode as integer """ # Note: Output from git-fast-export slightly different to spec if s in [b'644', b'100644', b'0100644']: return 0o100644 elif s in [b'755', b'100755', b'0100755']: return 0o100755 elif s in [b'040000', b'0040000']: return 0...
def common_directory(paths): """Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned. """ import posixpath def get_dir_with_slash(path): if path == b'' or p...
def is_inside(directory, fname): """True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tree and matches everythi...
def is_inside_any(dir_list, fname): """True if fname is inside any of given dirs.""" for dirname in dir_list: if is_inside(dirname, fname): return True return False
def utf8_bytes_string(s): """Convert a string to a bytes string (if necessary, encode in utf8)""" if sys.version_info[0] == 2: if isinstance(s, str): return s else: return s.encode('utf8') else: if isinstance(s, str): return bytes(s, encoding='utf8') else: return s
def binary_stream(stream): """Ensure a stream is binary on Windows. :return: the stream """ try: import os if os.name == 'nt': fileno = getattr(stream, 'fileno', None) if fileno: no = fileno() if no >= 0: # -1 means we're working as subprocess import msvcrt msvcrt.setmode(no, os.O_BINARY) except ImportError: pass retur...
def invert_dictset(d): """Invert a dictionary with keys matching a set of values, turned into lists.""" # Based on recipe from ASPN result = {} for k, c in d.items(): for v in c: keys = result.setdefault(v, []) keys.append(k) return result
def invert_dict(d): """Invert a dictionary with keys matching each value turned into a list.""" # Based on recipe from ASPN result = {} for k, v in d.items(): keys = result.setdefault(v, []) keys.append(k) return result
def defines_to_dict(defines): """Convert a list of definition strings to a dictionary.""" if defines is None: return None result = {} for define in defines: kv = define.split('=', 1) if len(kv) == 1: result[define.strip()] = 1 else: result[kv[0].strip()] = kv[1].strip() return result
def start(self, instance_names): """ If start is called from the root of a Galaxy source directory with no args, automatically add this instance. """ if not instance_names: configs = (os.path.join('config', 'galaxy.ini'), os.path.join('config', 'galaxy.ini.sample')) for config in configs: if os.path.exists(config): if ...
def crypt(self, data, crypt_type): """Crypt the data in blocks, running it through des_crypt()""" # Error check the data if not data: return '' if len(data) % self.block_size != 0: if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks raise ValueError("Invalid data length, data must be a multiple of " +...
ciphering") # Split the data into blocks, crypting each one seperately i = 0 result = [] while i < len(data): block = self.__String_to_BitList(data[i:i+8]) # Xor with IV if using CBC mode if self.getMode() == CBC: if crypt_type == des.ENCRYPT: block = list(map(lambda x, y: x ^ y, block, iv)) processed_block = self.__de...
def setQuery(self, query): """ Set the SPARQL query text and set the VIVO custom authentication parameters. Set here because this is called immediately before any query is sent to the triple store. """ self.queryType = self._parseQueryType(query) self.queryString = self.injectPrefixes(query) self.addParameter('email', ...
def post_process(self, settings): """ Perform post processing methods on settings according to their definition in manifest. Post process methods are implemented in their own method that have the same signature: * Get arguments: Current settings, item name and item value; * Return item value possibly patched; Args: set...
def _patch_expand_path(self, settings, name, value): """ Patch a path to expand home directory and make absolute path. Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to patch. Returns: str: Patched path to an absolute path. """ if os.path.isabs(value): return os.path.normpath(value...
def _patch_expand_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Returns: list: Patched path list to an absolute path. """ return [self._patch_exp...
def _validate_path(self, settings, name, value): """ Validate path exists Args: settings (dict): Current settings. name (str): Setting name. value (str): Path to validate. Raises: boussole.exceptions.SettingsInvalidError: If path does not exists. Returns: str: Validated path. """ if not os.path.exists(value): raise Set...
def _validate_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._validate_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Raises: boussole.exceptions.SettingsInvalidError: Once a path does not exists. Returns: l...
def _validate_required(self, settings, name, value): """ Validate a required setting (value can not be empty) Args: settings (dict): Current settings. name (str): Setting name. value (str): Required value to validate. Raises: boussole.exceptions.SettingsInvalidError: If value is empty. Returns: str: Validated value. ""...
def render(template, **kwargs): """ Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions. """ import jinja2 import os.path as path searchpath = path.join(...
def summarize(urls): """ Calls extract for each of the URLs, Returns the list of Extracted instances as summaries, the result of the process, and the speed. """ import time from summary import Summary fails = 0 err = lambda e: e.__class__.__name__ summaries = [] start = time.time() for url in urls: try: print "-> %s" %...
result, speed
def initMazeFromJSON(jsonString, cellClass=Cell, gridClass=Grid): '''Init a maze from JSON string.''' jsonObj = json.loads(jsonString) rows=jsonObj["rows"] columns=jsonObj["columns"] grid=gridClass(rows,columns,cellClass) grid.algorithm=jsonObj["algorithm"] grid.algorithm_key=jsonObj["algorithm_key"] grid.braid=jsonObj...
def read_json_file(fpath): """ Read a JSON file from ``fpath``; raise an exception if it doesn't exist. :param fpath: path to file to read :type fpath: str :return: deserialized JSON :rtype: dict """ if not os.path.exists(fpath): raise Exception('ERROR: file %s does not exist.' % fpath) with open(fpath, 'r') as fh: raw...
def run_cmd(args, stream=False, shell=True): """ Execute a command via :py:class:`subprocess.Popen`; return its output (string, combined STDOUT and STDERR) and exit code (int). If stream is True, also stream the output to STDOUT in realtime. :param args: the command to run and arguments, as a list or string :param stre...
if stream: sys.stdout.write(c) p.poll() # set returncode logger.info('Command exited with code %d', p.returncode) logger.debug("Command output:\n%s", outbuf) return outbuf, p.returncode
def _load(self, titles=[], descriptions=[], images=[], urls=[], **kwargs): """ Loads extracted data into Summary. Performs validation and filtering on-the-fly, and sets the non-plural fields to the best specific item so far. If GET_ALL_DATA is False, it gets only the first valid item. """ enough = lambda items: items #...
images)) self.images.extend(images) elif not enough(self.images): for i in images: image = self._filter_image(i) if image: self.images.append(image) if enough(self.images): break
def _clean_url(self, url): """ Canonicalizes the url, as it is done in Scrapy. And keeps only USEFUL_QUERY_KEYS. It also strips the trailing slash to help identifying dupes. """ # TODO: Turn this into regex if not url.startswith('http') or url.endswith('}}') or 'nojs_router' in url: return None if site(norm(url).lower(...
def _filter_image(self, url): "The param is the image URL, which is returned if it passes all the filters." return reduce(lambda f, g: f and g(f), [ filters.AdblockURLFilter()(url), filters.NoImageFilter(), filters.SizeImageFilter(), filters.MonoImageFilter(), filters.FormatImageFilter(), ])