code
stringlengths
1
18.2k
def wrap2stub(self, customfunc): """ Wrapping the inspector as a stub based on the type Args: customfunc: function that replaces the original Returns: function, the spy wrapper around the customfunc """ if self.args_type == "MODULE_FUNCTION": wrapper = Wrapper.wrap_spy(customfunc, self.obj) setattr(self.obj, self.prop,...
def is_op(call, op): """ :param call: The specific operator instance (a method call) :param op: The the operator we are testing against :return: isinstance(call, op), but faster """ try: return call.id == op.id except Exception as e: return False
def value_compare(left, right, ordering=1): """ SORT VALUES, NULL IS THE LEAST VALUE :param left: LHS :param right: RHS :param ordering: (-1, 0, 1) TO AFFECT SORT ORDER :return: The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ try: ltype = left.__class__ rtype = right.__class__ ...
= none_type if rtype is float and isnan(right): right = None rtype = none_type null_order = ordering*10 ltype_num = TYPE_ORDER.get(ltype, null_order) rtype_num = TYPE_ORDER.get(rtype, null_order) type_diff = ltype_num - rtype_num if type_diff != 0: return ordering if type_diff > 0 else -ordering if ltype_num == null_or...
def jx_type(column): """ return the jx_type for given column """ if column.es_column.endswith(EXISTS_TYPE): return EXISTS return es_type_to_json_type[column.es_type]
def _reload_columns(self, table_desc): """ :param alias: A REAL ALIAS (OR NAME OF INDEX THAT HAS NO ALIAS) :return: """ # FIND ALL INDEXES OF ALIAS es_last_updated = self.es_cluster.metatdata_last_updated alias = table_desc.name canonical_index = self.es_cluster.get_best_matching_index(alias).index es_metadata_update_r...
"index": "not_analyzed"} columns = self._parse_properties(alias, mapping) table_desc.timestamp = es_last_updated return columns
def get_columns(self, table_name, column_name=None, after=None, timeout=None): """ RETURN METADATA COLUMNS :param table_name: TABLE WE WANT COLUMNS FOR :param column_name: OPTIONAL NAME, IF INTERESTED IN ONLY ONE COLUMN :param after: FORCE LOAD, WAITING FOR last_updated TO BE AFTER THIS TIME :param timeout: Signal; Tru...
and Log.note("columns from reload") else: columns = self.meta.columns.find(alias, column_name) DEBUG and Log.note("columns from find()") DEBUG and Log.note("columns are {{ids}}", ids=[id(c) for c in columns]) columns = jx.sort(columns, "name") if after is None: return columns # DO NOT WAIT FOR COMPLETE COLUMNS # WAIT F...
to get columns for {{table}}", table=table_name, cause=e) return []
def _update_cardinality(self, column): """ QUERY ES TO FIND CARDINALITY AND PARTITIONS FOR A SIMPLE COLUMN """ now = Date.now() if column.es_index in self.index_does_not_exist: return if column.jx_type in STRUCT: Log.error("not supported") try: if column.es_index == "meta.columns": partitions = jx.sort([g[column.es_col...
is_text: # text IS A MULTIVALUE STRING THAT CAN ONLY BE FILTERED result = self.es_cluster.post("/" + es_index + "/_search", data={ "aggs": { "count": {"filter": {"match_all": {}}} }, "size": 0 }) count = result.hits.total cardinality = max(1001, count) multi = 1001 elif column.es_column == "_id": result = self.es_clust...
= { "aggs": { "count": _counting_query(column), "_filter": { "aggs": {"multi": {"max": {"script": "doc[" + quote(column.es_column) + "].values.size()"}}}, "filter": {"bool": {"should": [ {"range": {"etl.timestamp.~n~": {"gte": (Date.today() - WEEK)}}}, {"bool": {"must_not": {"exists": {"field": "etl.timestamp.~n~"}}}} ...
"set": { "count": count, "cardinality": cardinality, "multi": multi, "last_updated": now }, "clear": ["partitions"], "where": {"eq": {"es_index": column.es_index, "es_column": column.es_column}} }) return elif column.es_type in elasticsearch.ES_NUMERIC_TYPES and cardinality > 30: DEBUG and Log.note("{{table}}.{{field}}...
column=column, time=now) self.meta.columns.update({ "set": { "count": count, "cardinality": cardinality, "multi": multi, "partitions": parts, "last_updated": now }, "where": {"eq": {"es_index": column.es_index, "es_column": column.es_column}} }) except Exception as e: # CAN NOT IMPORT: THE TEST MODULES SETS UP LOGGING ...
"es_column": column.es_column}} }) Log.warning("Could not get {{col.es_index}}.{{col.es_column}} info", col=column, cause=e)
def query_paths(self): """ RETURN A LIST OF ALL NESTED COLUMNS """ output = self.namespace.alias_to_query_paths.get(self.name) if output: return output Log.error("Can not find index {{index|quote}}", index=self.name)
def sorted_query_paths(self): """ RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER """ return list(reversed(sorted(p[0] for p in self.namespace.alias_to_query_paths.get(self.name))))
def leaves(self, column_name): """ :param column_name: :return: ALL COLUMNS THAT START WITH column_name, NOT INCLUDING DEEPER NESTED COLUMNS """ clean_name = unnest_path(column_name) if clean_name != column_name: clean_name = column_name cleaner = lambda x: x else: cleaner = unnest_path columns = self.columns # TODO: '...
output: return set(output) return set()
def new_leaves(self, column_name): """ :param column_name: :return: ALL COLUMNS THAT START WITH column_name, INCLUDING DEEP COLUMNS """ column_name = unnest_path(column_name) columns = self.columns all_paths = self.snowflake.sorted_query_paths output = {} for c in columns: if c.name == "_id" and column_name != "_id": c...
def values(self, column_name, exclude_type=STRUCT): """ RETURN ALL COLUMNS THAT column_name REFERS TO """ column_name = unnest_path(column_name) columns = self.columns output = [] for path in self.query_path: full_path = untype_path(concat_field(path, column_name)) for c in columns: if c.jx_type in exclude_type: contin...
def map_to_es(self): """ RETURN A MAP FROM THE NAMESPACE TO THE es_column NAME """ output = {} for path in self.query_path: set_default( output, { k: c.es_column for c in self.columns if c.jx_type not in STRUCT for rel_name in [relative_field(c.name, path)] for k in [rel_name, untype_path(rel_name), unnest_path(rel_nam...
def get_decoders_by_path(query): """ RETURN MAP FROM QUERY PATH TO LIST OF DECODER ARRAYS :param query: :return: """ schema = query.frum.schema output = Data() if query.edges: if query.sort and query.format != "cube": # REORDER EDGES/GROUPBY TO MATCH THE SORT query.edges = sort_edges(query, "edges") elif query.groupby:...
in vars_] elif all(edge.domain.partitions.where): vars_ = set() for p in edge.domain.partitions: vars_ |= p.where.vars() vars_ |= edge.value.vars() depths = set(c.nested_path[0] for v in vars_ for c in schema.leaves(v.var)) if not depths: Log.error( "Do not know of column {{column}}", column=unwraplist([v for v in vars...
def aggs_iterator(aggs, es_query, decoders, give_me_zeros=False): """ DIG INTO ES'S RECURSIVE aggs DATA-STRUCTURE: RETURN AN ITERATOR OVER THE EFFECTIVE ROWS OF THE RESULTS :param aggs: ES AGGREGATE OBJECT :param es_query: THE ABSTRACT ES QUERY WE WILL TRACK ALONGSIDE aggs :param decoders: TO CONVERT PARTS INTO COORDIN...
for p in parts if p is not None), tuple(coord), c_agg, selects ) continue stack.append(gen) gen = _children(c_agg, children)
def make_default(spec): """Create an empty document that follows spec. Any field with a default will take that value, required or not. Required fields with no default will get a value of None. If your default value does not match your type or otherwise customized Field class, this can create a spec that fails validatio...
def validate(document, spec): """Validate that a document meets a specification. Returns True if validation was successful, but otherwise raises a ValueError.""" if not spec: return True missing = [] for key, field in spec.iteritems(): if field.required and key not in document: missing.append(key) failed = [] for key, ...
def typecheck(self, t): """Create a typecheck from some value ``t``. This behaves differently depending on what ``t`` is. It should take a value and return True if the typecheck passes, or False otherwise. Override ``pre_validate`` in a child class to do type coercion. * If ``t`` is a type, like basestring, int, float,...
none of these conditions are met, a TypeError is raised. """ if t is None: return lambda x: True def _isinstance(types, value): return isinstance(value, types) def _enum(values, value): return value in values if t.__class__ is type: return partial(_isinstance, t) elif isinstance(t, (tuple, list)): if all([x.__class__ i...
def validate(self, value): """Validate a value for this field. If the field is invalid, this will raise a ValueError. Runs ``pre_validate`` hook prior to validation, and returns value if validation passes.""" value = self.pre_validate(value) if not self._typecheck(value): raise ValueError('%r failed type check' % value...
def init_db(self): ''' Creates all the tables, and indexes needed for the service. :return: None ''' with self.conn.transaction() as t: t.execute(''' CREATE TABLE temporal ( tuid INTEGER, revision CHAR(12) NOT NULL, file TEXT, line INTEGER );''') t.execute(''' CREATE TABLE annotations ( revision CHAR(12) NOT NULL, file...
def get_tuids_from_revision(self, revision): """ Gets the TUIDs for the files modified by a revision. :param revision: revision to get files from :return: list of (file, list(tuids)) tuples """ result = [] URL_TO_FILES = self.hg_url / self.config.hg.branch / 'json-info' / revision try: mozobject = http.get_json(url=URL...
def _check_branch(self, revision, branch): ''' Used to find out if the revision is in the given branch. :param revision: Revision to check. :param branch: Branch to check revision on. :return: True/False - Found it/Didn't find it ''' # Get a changelog clog_url = self.hg_url / branch / 'json-log' / revision try: Log.not...
def get_tuids_from_files( self, files, revision, going_forward=False, repo=None, use_thread=True, max_csets_proc=30 ): """ Gets the TUIDs for a set of files, at a given revision. list(tuids) is an array of tuids, one tuid for each line, in order, and `null` if no tuid assigned Uses frontier updating to build and mainta...
is in the correct branch (to prevent catastrophic failures down the line) - this results in one extra changeset log call per request. If repo is set to something other than None, then we assume that the caller has already checked this and is giving a proper branch for the revision. :param files: list of files :param re...
be updated. :return: The following tuple which contains: ([list of (file, list(tuids)) tuples], True/False if completed or not) """ completed = True if repo is None: repo = self.config.hg.branch check = self._check_branch(revision, repo) if not check: # Error was already output by _check_branch return [(file, []) for f...
Go through all requested files and # either update their frontier or add # them to the DB through an initial annotation. if DEBUG: Log.note(" {{percent|percent(decimal=0)}}|{{file}}", file=file, percent=count / total) with self.conn.transaction() as t: latest_rev = self._get_latest_revision(file, transaction=t) already...
= " + quote_value(file)) new_files.append(file) Log.note( "Missing annotation for existing frontier - readding: " "{{rev}}|{{file}} ", file=file, rev=revision ) else: Log.note( "Frontier update - adding: " "{{rev}}|{{file}} ", file=file, rev=revision ) new_files.append(file) if DEBUG: Log.note( "Frontier update - alrea...
as this can take a long time. result = [] latestFileMod_inserts = {} if len(new_files) > 0: # File has never been seen before, get it's initial # annotation to work from in the future. tmp_res = self.get_tuids(new_files, revision, commit=False) if tmp_res: result.extend(tmp_res) else: Log.note("Error occured for files ...
i in inserts_list) ) # If we have files that need to have their frontier updated, do that now if len(frontier_update_list) > 0: tmp = self._update_file_frontiers( frontier_update_list, revision, going_forward=going_forward, max_csets_proc=max_csets_proc ) result.extend(tmp) if using_thread: self.pcdaemon.update_totals(...
def _apply_diff(self, transaction, annotation, diff, cset, file): ''' Using an annotation ([(tuid,line)] - array of TuidMap objects), we change the line numbers to reflect a given diff and return them. diff must be a diff object returned from get_diff(cset, file). Only for going forward in time, not back. :param annota...
lines[start-1:]] def remove_one(start, lines): return lines[:start-1] + [TuidMap(tmap.tuid, int(tmap.line) - 1) for tmap in lines[start:]] for f_proc in diff['diffs']: new_fname = f_proc['new'].name.lstrip('/') old_fname = f_proc['old'].name.lstrip('/') if new_fname != file and old_fname != file: continue if old_fname ...
temporal (tuid, revision, file, line)" " VALUES " + sql_list(quote_list(tp) for tp in inserts_list) ) return new_ann, file
def _get_tuids_from_files_try_branch(self, files, revision): ''' Gets files from a try revision. It abuses the idea that try pushes will come from various, but stable points (if people make many pushes on that revision). Furthermore, updates are generally done to a revision that should eventually have tuids already in ...
log_existing_files.append('removed|' + file) continue else: files_to_update.append(file) if len(log_existing_files) > 0: Log.note( "Try revision run - existing entries: {{count}}/{{total}} | {{percent}}", count=str(len(log_existing_files)), total=str(len(files)), percent=str(100*(len(log_existing_files)/len(files))) ) ...
url=jsonrev_url ) return [(file, []) for file in files] except Exception as e: Log.warning( "Unexpected error getting changset-log for {{url}}: {{error}}", url=jsonrev_url, error=e ) return [(file, []) for file in files] # When `phase` is public, the patch is (assumed to be) # in any repo other than try. if clog_obj['p...
cset_len12 = csets_diff['cset'] parsed_diff = csets_diff['diff']['diffs'] for f_added in parsed_diff: # Get new entries for removed files. new_name = f_added['new'].name.lstrip('/') old_name = f_added['old'].name.lstrip('/') # If we don't need this file, skip it if new_name not in files_to_update: # If the file was rem...
files_to_update: if file not in curr_annots_dict: Log.note( "WARNING: Missing annotation entry in mozilla-central branch revision {{cset}} " "for {{file}}", file=file, cset=mc_revision ) # Try getting it from the try revision anns_to_get.append(file) continue if file in added_files: Log.note("Try revision run - added: ...
annotation Log.note("Try revision run - not modified: {{file}}", file=file) ann_inserts.append((revision, file, self.stringify_tuids(curr_annots_dict[file]))) tmp_results[file] = curr_annots_dict[file] # Insert and check annotations, get all that were # added by another thread. anns_added_by_other_thread = {} if len(an...
def _update_file_frontiers( self, frontier_list, revision, max_csets_proc=30, going_forward=False ): ''' Update the frontier for all given files, up to the given revision. Built for quick continuous _forward_ updating of large sets of files of TUIDs. Backward updating should be done through get_tuids(files, revision). ...
latest revision will not be updated. :return: list of (file, list(tuids)) tuples ''' # Get the changelogs and revisions until we find the # last one we've seen, and get the modified files in # each one. # Holds the files modified up to the last frontiers. files_to_process = {} # Holds all frontiers to find remaining_fr...
Holds info on how to apply the diffs onto each frontier, # and all known frontiers. diffs_to_frontier = {cset: [] for cset in remaining_frontiers} Log.note("Searching for frontier(s): {{frontier}} ", frontier=str(list(remaining_frontiers))) Log.note( "Running on revision with HG URL: {{url}}", url=self.hg_url / self.co...
clog_cset in clog_obj_list[:-1]: nodes_cset = clog_cset['node'][:12] if remaining_frontiers: if nodes_cset in remaining_frontiers: # Found a frontier, remove it from search list. remaining_frontiers.remove(nodes_cset) if not remaining_frontiers: # Found all frontiers, get out of the loop before # we add the diff to a f...
# Go to the next log page last_entry = clog_obj_list[-1] final_rev = last_entry['node'][:12] if not remaining_frontiers: Log.note("Found all frontiers: {{frontiers_list}}", frontiers_list=str(list(diffs_to_frontier.keys()))) else: found_frontiers = [ frontier for frontier in diffs_to_frontier if frontier not in remaini...
access to the diffs, # to be used later when applying them. parsed_diffs = {diff_entry['cset']: diff_entry['diff'] for diff_entry in all_diffs} # In case the file name changes, this will map # the requested file to the new file name so # diffs can all be gathered. filenames_to_seek = {} # Parse diffs for files to proce...
\ old_name not in filenames_to_seek: # File not requested continue if new_name == 'dev/null': frontier_filename = old_name while frontier_filename in filenames_to_seek: frontier_filename = filenames_to_seek[frontier_filename] if frontier_filename not in removed_files: removed_files[frontier_filename] = 0 removed_files[...
at the frontier skip it. if file_to_frontier[frontier_filename] == '': # Previously found frontier, skip continue # At this point, file is in the database, is # asked to be processed, and we are still # searching for the last frontier. if file_to_frontier[frontier_filename] == cset_len12: file_to_frontier[frontier_file...
(file, old_frontier) in enumerate(frontier_list): if old_frontier in remaining_frontiers: # If we were still looking for the frontier by the end, get a new # annotation for this file. anns_to_get.append(file) if going_forward: # If we are always going forward, update the frontier latestFileMod_inserts[file] = (file, re...
{{rev}}|{{file}} ", count=count, total=total, file=file, rev=revision, percent=count / total, lost_frontier=old_frontier ) else: Log.note( "Frontier update - deleting: " "{{count}}/{{total}} - {{percent|percent(decimal=0)}} | {{rev}}|{{file}} ", count=count, total=total, file=file, rev=revision, percent=count / total, ...
diffs # Reverse the diff list, we always find the newest diff first csets_to_proc = files_to_process[file][::-1] tmp_res = self.destringify_tuids(tmp_ann) new_fname = file for i in csets_to_proc: tmp_res, new_fname = self._apply_diff(transaction, tmp_res, parsed_diffs[i], i, new_fname) ann_inserts.append((revision, fil...
known revision tmp_res = self.destringify_tuids(old_ann) if old_ann != '' else [] ann_inserts.append((revision, file, old_ann)) Log.note( "Frontier update - not modified: {{count}}/{{total}} - {{percent|percent(decimal=0)}} " "| {{rev}}|{{file}} ", count=count, total=total, file=file, rev=revision, percent=count / tota...
# we perform an insert or replace any way. if len(latestFileMod_inserts) > 0: for _, inserts_list in jx.groupby(latestFileMod_inserts.values(), size=SQL_BATCH_SIZE): transaction.execute( "INSERT OR REPLACE INTO latestFileMod (file, revision) VALUES " + sql_list(quote_list(i) for i in inserts_list) ) anns_added_by_other...
in annotation insertion in {{rev}} for {{file}}: {{tuids}}" , rev=rev, file=filename, tuids=str(tuid_map) ) self.insert_annotations(transaction, recomputed_inserts) except Exception as e: Log.error("Error inserting into annotations table: {{inserting}}", inserting=recomputed_inserts, cause=e) if len(anns_to_get) > 0: r...
def get_tuids(self, files, revision, commit=True, chunk=50, repo=None): ''' Wrapper for `_get_tuids` to limit the number of annotation calls to hg and separate the calls from DB transactions. Also used to simplify `_get_tuids`. :param files: :param revision: :param commit: :param chunk: :param repo: :return: ''' result...
No new annotations to get, so get next set continue # Get all the annotations in parallel and # store in annotated_files annotated_files = [None] * len(annotations_to_get) threads = [ Thread.run( str(thread_count), self._get_hg_annotate, revision, annotations_to_get[thread_count], annotated_files, thread_count, repo ) ...
def _get_tuids( self, transaction, files, revision, annotated_files, commit=True, repo=None ): ''' Returns (TUID, line) tuples for a given file at a given revision. Uses json-annotate to find all lines in this revision, then it updates the database with any missing revisions for the file changes listed in annotate. The...
[] for fcount, annotated_object in enumerate(annotated_files): file = files[fcount] # TODO: Replace old empty annotation if a new one is found # TODO: at the same revision and if it is not empty as well. # Make sure we are not adding the same thing another thread # added. tmp_ann = self._get_annotation(revision, file, ...
type got: {{ann_type}}, expecting:dict returned when getting " "annotation for: {{file}} in the revision {{cset}}", cset=revision, file=file, ann_type=type(annotated_object) ) errored = True if errored: Log.note("Inserting dummy entry...") self.insert_tuid_dummy(transaction, revision, file, commit=commit) self.insert_a...
line)): tuid for tuid, file, revision, line in transaction.query( "SELECT tuid, file, revision, line FROM temporal" " WHERE file IN " + quote_list(file_names) + " AND revision IN " + quote_list(revs_to_find) + " AND line IN " + quote_list(lines_to_find) ).data } # Recompute existing tuids based on line_origins # entry ...
> 0: try: ''' HG Annotate Bug, Issue #58: Here is where we assign the new tuids for the first time we see duplicate entries - they are left in `new_line_origins` after duplicates are found. We only remove it from the lines to insert. In future requests, `existing_tuids` above will handle duplicating tuids for the entri...
size=SQL_BATCH_SIZE): transaction.execute( "INSERT INTO temporal (tuid, file, revision, line)" " VALUES " + sql_list( sql_iso( sql_list(map(quote_value, (tuid, f, rev, line_num))) ) for tuid, f, rev, line_num in list(part_of_insert) ) ) # Format so we don't have to use [0] to get at the tuid new_line_origins = {line_nu...
def _daemon(self, please_stop, only_coverage_revisions=False): ''' Runs continuously to prefill the temporal and annotations table with the coverage revisions*. * A coverage revision is a revision which has had code coverage run on it. :param please_stop: Used to stop the daemon :return: None ''' while not please_stop:...
False coverage_revisions = None for frontier in revs: if please_stop: return files = revs[frontier] # Go through changeset logs until we find the last # known frontier for this revision group. csets = [] final_rev = '' found_last_frontier = False Log.note("Searching for frontier: {{frontier}} ", frontier=frontier) Log....
means that we are already # at the latest revisions. if len(csets) == 0: continue # Get all the latest ccov and jsdcov revisions if (not coverage_revisions) and only_coverage_revisions: active_data_url = 'http://activedata.allizom.org/query' query_json = { "limit": 1000, "from": "task", "where": {"and": [ {"in": {"buil...
DEBUG: Log.note("Moving frontier {{frontier}} forward to {{cset}}.", frontier=prev_cset, cset=cset) # Update files self.get_tuids_from_files(files, cset, going_forward=True) ran_changesets = True prev_cset = cset if not ran_changesets: (please_stop | Till(seconds=DAEMON_WAIT_AT_NEWEST.seconds)).wait()
def collapsesum(data_frame, by = None, var = None): ''' Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. ''' assert by is not None assert var is not None grouped = data_frame.groupby([by]) return grouped.apply(lambda x: weighted_sum(groupe = x, var =var))
def weighted_sum(groupe, var): ''' Fonction qui calcule la moyenne pondérée par groupe d'une variable ''' data = groupe[var] weights = groupe['pondmen'] return (data * weights).sum()
def addSubparser(subparsers, subcommand, description): """ Add a subparser with subcommand to the subparsers object """ parser = subparsers.add_parser( subcommand, description=description, help=description) return parser
def createArgumentParser(description): """ Create an argument parser """ parser = argparse.ArgumentParser( description=description, formatter_class=SortedHelpFormatter) return parser
def add_arguments(self, actions): """ Sort the flags alphabetically """ actions = sorted( actions, key=operator.attrgetter('option_strings')) super(SortedHelpFormatter, self).add_arguments(actions)
def _iter_indented_subactions(self, action): """ Sort the subcommands alphabetically """ try: get_subactions = action._get_subactions except AttributeError: pass else: self._indent() if isinstance(action, argparse._SubParsersAction): for subaction in sorted( get_subactions(), key=lambda x: x.dest): yield subaction else...
def main(argv): """Call startup.call() in your main().""" args = startup.call(argv=argv)['args'] if args.v: print('x * y = %d' % (args.x * args.y)) else: print(args.x * args.y) return 0
def resource_of_node(resources, node): """ Returns resource of node. """ for resource in resources: model = getattr(resource, 'model', None) if type(node) == model: return resource return BasePageResource
def resources_of_config(config): """ Returns all resources and models from config. """ return set( # unique values sum([ # join lists to flat list list(value) # if value is iter (ex: list of resources) if hasattr(value, '__iter__') else [value, ] # if value is not iter (ex: model or resource) for value in config.values...
def models_of_config(config): """ Return list of models from all resources in config. """ resources = resources_of_config(config) models = [] for resource in resources: if not hasattr(resource, '__table__') and hasattr(resource, 'model'): models.append(resource.model) else: models.append(resource) return models
def get_prefix(self): """ Each resource defined in config for pages as dict. This method returns key from config where located current resource. """ for key, value in self.pages_config.items(): if not hasattr(value, '__iter__'): value = (value, ) for item in value: if type(self.node) == item\ or type(self.node) == geta...
def zip2bytes(compressed): """ UNZIP DATA """ if hasattr(compressed, "read"): return gzip.GzipFile(fileobj=compressed, mode='r') buff = BytesIO(compressed) archive = gzip.GzipFile(fileobj=buff, mode='r') from pyLibrary.env.big_data import safe_size return safe_size(archive)
def bytes2zip(bytes): """ RETURN COMPRESSED BYTES """ if hasattr(bytes, "read"): buff = TemporaryFile() archive = gzip.GzipFile(fileobj=buff, mode='w') for b in bytes: archive.write(b) archive.close() buff.seek(0) from pyLibrary.env.big_data import FileString, safe_size return FileString(buff) buff = BytesIO() archive ...
def ini2value(ini_content): """ INI FILE CONTENT TO Data """ from mo_future import ConfigParser, StringIO buff = StringIO(ini_content) config = ConfigParser() config._read(buff, "dummy") output = {} for section in config.sections(): output[section]=s = {} for k, v in config.items(section): s[k]=v return wrap(output)
def table2csv(table_data): """ :param table_data: expecting a list of tuples :return: text in nice formatted csv """ text_data = [tuple(value2json(vals, pretty=True) for vals in rows) for rows in table_data] col_widths = [max(len(text) for text in cols) for cols in zip(*text_data)] template = ", ".join( "{{" + text_typ...
def tuple_in_list_always(main, sub): """ >>> main = [('a', 'b', 'c'), ('c', 'd')] >>> tuple_in_list_always(main, ('a' ,'b', 'c')) False >>> tuple_in_list_always(main, ('c', 'd')) False >>> tuple_in_list_always(main, ('a', 'c')) False >>> tuple_in_list_always(main, ('a')) False >>> tuple_in_list_always(main, ((),)) Fals...
def obj_in_list_always(target_list, obj): """ >>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False """ for item in set(target_list): if item is not obj: return False return True
def dict_partial_cmp(target_dict, dict_list, ducktype): """ Whether partial dict are in dict_list or not """ for called_dict in dict_list: # ignore invalid test case if len(target_dict) > len(called_dict): continue # get the intersection of two dicts intersection = {} for item in target_dict: dtype = ducktype(target_di...
def dict_partial_cmp_always(target_dict, dict_list, ducktype): """ Whether partial dict are always in dict_list or not """ res = [] for called_dict in dict_list: # ignore invalid test case if len(target_dict) > len(called_dict): continue # get the intersection of two dicts intersection = {} for item in target_dict: dty...
def tuple_partial_cmp(target_tuple, tuple_list, ducktype): """ Whether partial target_tuple are in tuple_list or not """ for called_tuple in tuple_list: # ignore invalid test case if len(target_tuple) > len(called_tuple): continue # loop all argument from "current arguments" dst = len(target_tuple) for idx, part_target...
def tuple_partial_cmp_always(target_tuple, tuple_list, ducktype): """ Whether partial target_tuple are always in tuple_list or not """ res = [] for called_tuple in tuple_list: # ignore invalid test case if len(target_tuple) > len(called_tuple): continue # loop all argument from "current arguments" dst = len(target_tupl...
def register_from_options(options=None, template=None, extractor=None): """Register the spec codec using the provided options""" if template is None: from noseOfYeti.plugins.support.spec_options import spec_options as template if extractor is None: from noseOfYeti.plugins.support.spec_options import extract_options_dic...
def register(self): """Register spec codec""" # Assume utf8 encoding utf8 = encodings.search_function('utf8') class StreamReader(utf_8.StreamReader): """Used by cPython to deal with a spec file""" def __init__(sr, stream, *args, **kwargs): codecs.StreamReader.__init__(sr, stream, *args, **kwargs) data = self.dealwith(s...