code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def prepare_attacks(self): print_header('PREPARING ATTACKS DATA') if not self.ask_when_work_is_populated(self.attack_work): return self.attack_work = eval_lib.AttackWorkPieces( datastore_client=self.datastore_client) print_header('Initializing submissions') self.submissions.init_from_s...
Prepares all data needed for evaluation of attacks.
def make_annotation(self): annotation = dict() for item in dir(self): if len(item) > 0 and item[0] != '_' and \ not inspect.ismethod(getattr(self, item)): annotation[item] = getattr(self, item) return annotation
Returns a dictionary with all properties of the action mention.
def loaded_modules(self): with self._mutex: if not self._loaded_modules: self._loaded_modules = [] for mp in self._obj.get_loaded_modules(): self._loaded_modules.append(utils.nvlist_to_dict(mp.properties)) return self._loaded_modules
The list of loaded module profile dictionaries.
def _refresh_token_flow(self): url = '%s%s/oauth2/token' % (self.scheme, self.host) options = { 'grant_type': 'refresh_token', 'client_id': self.options.get('client_id'), 'client_secret': self.options.get('client_secret'), 'refresh_token': self.options.get...
Given a refresh token, obtain a new access token.
def read(cls, filename, offset=None, encoding="iso-8859-1"): with fileutil.opened(filename, "rb") as file: if offset is None: file.seek(-128, 2) else: file.seek(offset) data = file.read(128) return cls.decode(data, encoding=encoding...
Read an ID3v1 tag from a file.
def stored_version(self, name): link_path = self._link_path(name) if not _path_exists(link_path): return None return _file_version(link_path)
Returns the version of file `name` or None if it doesn't exist.
def _readlines(fname, fpointer1=open, fpointer2=open): try: with fpointer1(fname, "r") as fobj: return fobj.readlines() except UnicodeDecodeError: with fpointer2(fname, "r", encoding="utf-8") as fobj: return fobj.readlines()
Read all lines from file.
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01): counts = SparseMatrix() size = 128*128 counts.resize(1, size) sparseBitmap = SparseMatrix() sparseBitmap.resize(1, size) random.seed(42) numWords=0 for term in xrange(numTerms): bitmap = random.sample(xrange(size), int(size*pe...
Create a uniformly random counts matrix through sampling.
def process_minion_update(self, event_data): tag = event_data['tag'] event_info = event_data['data'] mid = tag.split('/')[-1] if not self.minions.get(mid, None): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) ...
Associate grains data with a minion and publish minion update
def asDictionary(self): template = { "type" : "simple", "symbol" : self._symbol.asDictionary, "label" : self._label, "description" : self._description, "rotationType": self._rotationType, "rotationExpression": self._rotationExpression ...
provides a dictionary representation of the object
def make_path_func (*baseparts): from os.path import join base = join (*baseparts) def path_func (*args): return join (base, *args) return path_func
Return a function that joins paths onto some base directory.
def __WaitForInstance(instance, desired_state): print 'Waiting for instance %s to change to %s' % (instance.id, desired_state) while True: try: instance.update() state = instance.state sys.stdout.write('.') sys.stdout.flush() if state == desired_state: ...
Blocks until instance is in desired_state.
def fixed(ctx, number, decimals=2, no_commas=False): value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
Formats the given number in decimal format using a period and commas
def parallel_multiplier(items): multiplier = 1 for data in (x[0] for x in items): if (tz.get_in(["config", "algorithm", "align_split_size"], data) is not False and tz.get_in(["algorithm", "align_split_size"], data) is not False): multiplier += 50 return multiplier
Determine if we will be parallelizing items during processing.
def _get_sync_model_vars_op(self): ops = [] for (shadow_v, local_v) in self._shadow_model_vars: ops.append(shadow_v.assign(local_v.read_value())) assert len(ops) return tf.group(*ops, name='sync_{}_model_variables_to_ps'.format(len(ops)))
Get the op to sync local model_variables to PS.
def safe_int_conv(number): try: return int(np.array(number).astype(int, casting='safe')) except TypeError: raise ValueError('cannot safely convert {} to integer'.format(number))
Safely convert a single number to integer.
def triggerLogicToStr(self): try: import json except ImportError: return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n"+json.dumps(self._allTriggers, indent=3) retval += "\nDEPENDENCIES:\n"+json.dumps(self._allDepdcs, indent=3) ...
Print all the trigger logic to a string and return it.
def bfd_parse(data): pkt = packet.Packet(data) i = iter(pkt) eth_pkt = next(i) assert isinstance(eth_pkt, ethernet.ethernet) ipv4_pkt = next(i) assert isinstance(ipv4_pkt, ipv4.ipv4) udp_pkt = next(i) assert isinstance(udp_pkt, udp.udp) udp_payload...
Parse raw packet and return BFD class from packet library.
def validate_root_vertex_directives(root_ast): directives_present_at_root = set() for directive_obj in root_ast.directives: directive_name = directive_obj.name.value if is_filter_with_outer_scope_vertex_field_operator(directive_obj): raise GraphQLCompilationError(u'Found a filter dir...
Validate the directives that appear at the root vertex field.
def entity_delete(args): msg = "WARNING: this will delete {0} {1} in {2}/{3}".format( args.entity_type, args.entity, args.project, args.workspace) if not (args.yes or _confirm_prompt(msg)): return json_body=[{"entityType": args.entity_type, "entityName": args.entity}] r =...
Delete entity in a workspace.
def markdown_to_notebook(infile, outfile): with open(infile, 'r') as fin: str = fin.read() str = '' nb = py2jn.py_string_to_notebook(str) py2jn.tools.write_notebook(nb, outfile, nbver=4)
Convert a markdown file to a notebook file.
def profile_list(self, provider, lookup='all'): data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: ...
Return a mapping of all configured profiles
def precision_at_proportions(self): return plot.precision_at_proportions(self.y_true, self.y_score, ax=_gen_ax())
Precision at proportions plot
def draw(self): sizes = self._get_cluster_sizes() self.ax.scatter( self.embedded_centers_[:,0], self.embedded_centers_[:,1], s=sizes, c=self.facecolor, edgecolor=self.edgecolor, linewidth=1, ) for i, pt in enumerate(self.embedded_centers_): self.ax.tex...
Draw the embedded centers with their sizes on the visualization.
def update(self, other): if isinstance(other, self.__class__): return self.client.sunionstore(self.name, [self.name, other.name]) else: return map(self.add, other)
Update this set with the union of itself and others.
def update(self): self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data and (time.time() - self.__manual_update_time > 60): if data['charging_state'] != "Charging": self.__charger_state = False ...
Update the charging state of the Tesla Vehicle.
def version_check(self): try: version_info = self['Version'] except KeyError: raise ValidateError('Config file has to have a Version section') try: float(version_info['version']) except KeyError: raise ValidateError('Config file has to have...
Check if the version entry is in the proper format
def channels_delete(self, room_id=None, channel=None, **kwargs): if room_id: return self.__call_api_post('channels.delete', roomId=room_id, kwargs=kwargs) elif channel: return self.__call_api_post('channels.delete', roomName=channel, kwargs=kwargs) else: raise...
Delete a public channel.
def subsets(self, nid, contract=True): n = self.node(nid) subsets = [] meta = self._meta(nid) if 'subsets' in meta: subsets = meta['subsets'] else: subsets = [] if contract: subsets = [self._contract_subset(s) for s in subsets] ...
Retrieves subset ids for a class or ontology object
def plot_convergence(Xdata,best_Y, filename = None): n = Xdata.shape[0] aux = (Xdata[1:n,:]-Xdata[0:n-1,:])**2 distances = np.sqrt(aux.sum(axis=1)) plt.figure(figsize=(10,5)) plt.subplot(1, 2, 1) plt.plot(list(range(n-1)), distances, '-ro') plt.xlabel('Iteration') plt.ylabel('d(x[n], x[n...
Plots to evaluate the convergence of standard Bayesian optimization algorithms
def assert_string(self, string): fact = lib.EnvAssertString(self._env, string.encode()) if fact == ffi.NULL: raise CLIPSError(self._env) return new_fact(self._env, fact)
Assert a fact as string.
def _check_and_flip(arr): if hasattr(arr, 'ndim'): if arr.ndim >= 2: return arr.T else: return arr elif not is_string_like(arr) and iterable(arr): return tuple(_check_and_flip(a) for a in arr) else: return arr
Transpose array or list of arrays if they are 2D.
def data_filler_company(self, number_of_rows, pipe): try: for i in range(number_of_rows): pipe.hmset('company:%s' % i, { 'id': rnd_id_generator(self), 'name': self.faker.company(), 'date': self.faker.date(pattern="%d-%m-%Y")...
creates keys with company data
def import_dashboards(path, recursive): p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.json')) elif p.exists() and recursive: files.extend(p.rglob('*.json')) for f in files: logging.info('Importi...
Import dashboards from JSON
def create_csr(key_file, organization_name, common_name, serial_number, file_): key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_file.read()) req = crypto.X509Req() subj = req.get_subject() subj.O = organization_name subj.CN = common_name subj.serialNumber = serial_number req.set_pubkey...
Create a CSR for a key, and save it into ``file``.
def class_parameters(decorator): def decorate(the_class): if not isclass(the_class): raise TypeError( 'class_parameters(the_class=%s) you must pass a class' % ( the_class ) ) for attr in the_class.__dict__: if ca...
To wrap all class methods with static_parameters decorator
def _remove_last(votes, fpl, cl, ranking): for v in votes: for r in v: if r == fpl[-1]: v.remove(r) for c in cl: if c == fpl[-1]: if c not in ranking: ranking.append((c, len(ranking) + 1))
Remove last candidate in IRV voting.
def tear_down_instances(self): self.info_log('Tearing down all instances...') for instance in self.alive_instances: instance.tear_down() self.info_log('[Done]Tearing down all instances')
Tear down all instances
def dict_isect_combine(dict1, dict2, combine_op=op.add): keys3 = set(dict1.keys()).intersection(set(dict2.keys())) dict3 = {key: combine_op(dict1[key], dict2[key]) for key in keys3} return dict3
Intersection of dict keys and combination of dict values
def _name_things(self): edges = {} nodes = {None: 'root'} for n in self._tree.postorder_node_iter(): nodes[n] = '.'.join([str(x.taxon) for x in n.leaf_nodes()]) for e in self._tree.preorder_edge_iter(): edges[e] = ' ---> '.join([nodes[e.tail_node], nodes[e.head_no...
Easy names for debugging
def group(self): split_count = self._url.lower().find("/content/") len_count = len('/content/') gURL = self._url[:self._url.lower().find("/content/")] + \ "/community/" + self._url[split_count+ len_count:] return CommunityGroup(url=gURL, security...
returns the community.Group class for the current group
def _extract_html_hex(string): try: hex_string = string and _hex_regexp().search(string).group(0) or '' except AttributeError: return None if len(hex_string) == 3: hex_string = hex_string[0] * 2 + hex_string[1] * 2 + hex_string[2] * 2 return hex_string
Get the first 3 or 6 hex digits in the string
def _login_snmp(self): logger.info("Trying to grab stats by SNMP...") from glances.stats_client_snmp import GlancesStatsClientSNMP self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) if not self.stats.check_snmp(): self.log_and_exit("Connection to SNMP ser...
Login to a SNMP server
def compute_gmfs(rupgetter, srcfilter, param, monitor): getter = GmfGetter(rupgetter, srcfilter, param['oqparam']) with monitor('getting ruptures'): getter.init() return getter.compute_gmfs_curves(monitor)
Compute GMFs and optionally hazard curves
def _rotate(pair, step): step = Step(step) movement = { "U": "RFLB", "D": "LFRB", "R": "FUBD", "L": "FDBU", "F": "URDL", "B": "ULDR", }[step.face] movement = { movement[i]: movement[(i + step.is...
Simulate the cube rotation by updating the pair.
def schema(self): if not hasattr(self, "_schema"): ret = None o = self._type if isinstance(o, type): ret = getattr(o, "schema", None) elif isinstance(o, Schema): ret = o else: module, klass = utils.get_ob...
return the schema instance if this is reference to another table
def reference(self, tkn: str): return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn)
Return the element that tkn represents
def compare_arrays(left, right): "Eq check with a short-circuit for identical objects." return ( left is right or ((left.shape == right.shape) and (left == right).all()) )
Eq check with a short-circuit for identical objects.
def etree(A): assert isinstance(A,spmatrix), "A must be a sparse matrix" assert A.size[0] == A.size[1], "A must be a square matrix" n = A.size[0] cp,ri,_ = A.CCS parent = matrix(0,(n,1)) w = matrix(0,(n,1)) for k in range(n): parent[k] = k w[k] = -1 for p in range(cp[...
Compute elimination tree from upper triangle of A.
def config_cython(): if not with_cython: return [] if os.name == 'nt': print("WARNING: Cython is not supported on Windows, will compile without cython module") return [] try: from Cython.Build import cythonize if sys.version_info >= (3, 0): subdir = "_cy3"...
Try to configure cython and return cython configuration
async def _get_user(self): if self._cache is None: try: self._cache = \ await self.facebook.get_user(self.fbid, self.page_id) except PlatformOperationError: self._cache = {} return self._cache
Get the user dict from cache or query it from the platform if missing.
def __visit_index_model_instance(self, models, p, k, v): cp = p + (k,) for model in models: try: if model.validator(v): if cp in self.path_index: self.path_index[cp].add_model(model, v) else: ...
Called during model research on merged data
def list_ikepolicies(self, retrieve_all=True, **_params): return self.list('ikepolicies', self.ikepolicies_path, retrieve_all, **_params)
Fetches a list of all configured IKEPolicies for a project.
def join(self): self._root_state.join() if len(self._execution_histories) > 0: if self._execution_histories[-1].execution_history_storage is not None: set_read_and_writable_for_all = global_config.get_config_value("EXECUTION_LOG_SET_READ_AND_WRITABLE_FOR_ALL", False) ...
Wait for root state to finish execution
def parse_restriction_dist(self, f): parsed_data = dict() firstline = True for l in f['f']: if firstline: firstline = False continue s = l.split("\t") if len(s) > 1: nuc = float(s[0].strip()) v1 =...
Parse HOMER tagdirectory petagRestrictionDistribution file.
def emergency(self): self.send(at.REF(at.REF.input.select))
Sends the emergency command.
def build_service(name=None, **kwargs): if name is not None: for kw, value in iteritems(SERVICES[name]): kwargs.setdefault(kw, value) return apiclient.discovery.build(**kwargs)
Return a service endpoint for interacting with a Google API.
def _is_kpoint(line): toks = line.split() if len(toks) != 4: return False try: xs = [float(x) for x in toks[:3]] w = float(toks[3]) return all(abs(x) <= 0.5 for x in xs) and w >= 0.0 and w <= 1.0 except ValueError: return False
Is this line the start of a new k-point block
def tab_change(self, event): self.remove_error() if event.new == 1: self.widget.disabled = False
When tab changes remove error, and enable widget if on url tab
def write_ply(self, output_file): points = np.hstack([self.coordinates, self.colors]) with open(output_file, 'w') as outfile: outfile.write(self.ply_header.format( vertex_count=len(self.coordinates))) np.savetxt(outfile, points, '%f %f ...
Export ``PointCloud`` to PLY file for viewing in MeshLab.
def firstAttr(self, *attrs): for attr in attrs: value = self.__dict__.get(attr) if value is not None: return value
Return the first attribute in attrs that is not None.
def export(outfile): if not nav: sys.exit(1) ecode = 0 savelist = list() for imageId in imagelist: try: record = {} record['image'] = {} record['image']['imageId'] = imageId record['image']['imagedata'] = contexts['anchore_db'].load_image_n...
Export image anchore data to a JSON file.
def visdom_send_metrics(vis, metrics, update='replace'): visited = {} sorted_metrics = sorted(metrics.columns, key=_column_original_name) for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name): metric_list = list(metric_list) for metric in metric_list: ...
Send set of metrics to visdom
def create_module(module, target): module_x = module.split('.') cur_path = '' for path in module_x: cur_path = os.path.join(cur_path, path) if not os.path.isdir(os.path.join(target, cur_path)): os.mkdir(os.path.join(target, cur_path)) if not os.path.exists(os.path.join(ta...
Create a module directory structure into the target directory.
def analysis(self): if self._analysis is None: with open(self.path, 'rb') as f: self.read_analysis(f) return self._analysis
Get ANALYSIS segment of the FCS file.
def _read(name): logging.debug("Reading config-file: %s" % name) try: with open(name, "r") as config_file: prm_dict = yaml.load(config_file) except yaml.YAMLError: raise yaml.YAMLErrorr else: return prm_dict
read the yml file
def next_intent_handler(request): message = "Sorry, couldn't find anything in your next queue" end_session = True if True: user_queue = twitter_cache.user_queue(request.access_token()) if not user_queue.is_finished(): message = user_queue.read_out_next(MAX_RESPONSE_TWEETS) ...
Takes care of things whenver the user says 'next'
def _point_estimate(X_val, XM_val, M_val, y_val, idx, n_mediator, mtype='linear'): beta_m = [] for j in range(n_mediator): if mtype == 'linear': beta_m.append(linear_regression(X_val[idx], M_val[idx, j], coef_only=True)[1]) ...
Point estimate of indirect effect based on bootstrap sample.
def make_empty(self, axes=None): if axes is None: axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]] if self.ndim == 1: blocks = np.array([], dtype=self.array_dtype) else: blocks = [] return se...
return an empty BlockManager with the items axis of len 0
def _filter_by_statement(self, statement): self.__class__._check_conditional_statement(statement, 1) _filt_values, _filt_datetimes = [], [] for i, a in enumerate(self._values): if eval(statement, {'a': a}): _filt_values.append(a) _filt_datetimes.append...
Filter the data collection based on a conditional statement.
def representCleanOpenAPIOperation(dumper, data): dct = _orderedCleanDict(data) if '_extended' in dct: for k, ext in list(data._extended.items()): dct[k] = ext del dct['_extended'] return dumper.yaml_representers[type(dct)](dumper, dct)
Unpack nonstandard attributes while representing an OpenAPIOperation
def calmarnorm(sharpe, T, tau = 1.0): return calmar(sharpe,tau)/calmar(sharpe,T)
Multiplicator for normalizing calmar ratio to period tau
def error_response(response): if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exceptions.GeocodioDataError(response.json()["error"]) else: rai...
Raises errors matching the response code
def _init_record(self, record_type_idstr): record_type_data = self._all_supported_record_type_data_sets[Id(record_type_idstr).get_identifier()] module = importlib.import_module(record_type_data['module_path']) record = getattr(module, record_type_data['query_record_class_name']) self._re...
Initializes a query record
def add_posts(self, path='posts'): path = os.path.join(self.root_path, path) self.cm.add_posts([ self.cm.Post.from_file(file) for file in _listfiles(path) ])
Look through a directory for markdown files and add them as posts.
def _register_extensions(self, namespace): extmanager = ExtensionManager( 'extensions.classes.{}'.format(namespace), propagate_map_exceptions=True ) if extmanager.extensions: extmanager.map(util.register_extension_class, base=self) extmanager = Extensi...
Register any extensions under the given namespace.
def add(self, items): for item in items: if item.ack_id not in self._leased_messages: self._leased_messages[item.ack_id] = _LeasedMessage( added_time=time.time(), size=item.byte_size ) self._bytes += item.byte_size else:...
Add messages to be managed by the leaser.
def _set_time(self, time): if len(self.time) == 0 : self.time = np.array(time) if self.h5 is not None: self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression="gzip", shuffle=True, scaleoffset=3) else: if(len(...
Set time in both class and hdf5 file
def remove_device(self, path): "Remove a device from the daemon's internal search list." if self.__get_control_socket(): self.sock.sendall("-%s\r\n\x00" % path) self.sock.recv(12) self.sock.close()
Remove a device from the daemon's internal search list.
def list_commands(self, ctx): config = load_config(**self.load_config_kwargs) services = self._get_services_config(config) return sorted(services.keys())
list the services that can be configured
def _from_dict(self, obj_dict): self._n_folds = obj_dict["param"]["n_folds"] self._n_rows = obj_dict["param"]["n_rows"] self._use_stored_folds = obj_dict["param"]["use_stored_folds"] self._concise_model = Concise.from_dict(obj_dict["init_model"]) if obj_dict["trained_global_model...
Initialize a model from the dictionary
def _log(code, message, level, domain): entry = LogEntry(level, domain, code, message) Logger.journal.append(entry) if Logger.silent: return if level >= Logger._verbosity: _print_entry(entry)
Call this to add an entry in the journal
def setBranch(self, *args, **kwargs): try: branch = self.mambubranchclass(entid=self['assignedBranchKey'], *args, **kwargs) except AttributeError as ae: from .mambubranch import MambuBranch self.mambubranchclass = MambuBranch branch = self.mambubranchclass...
Adds the branch to which the client belongs.
def astral(msg): utf32 = msg.encode("utf32")[4:] code_points = struct.unpack("%dI" % (len(utf32) / 4), utf32) return any(cp > 0xFFFF for cp in code_points)
Does `msg` have characters outside the Basic Multilingual Plane?
def AsPrimitiveProto(self): if self.protobuf: result = self.protobuf() result.ParseFromString(self.SerializeToString()) return result
Return an old style protocol buffer object.
def getRawIdent(self, node): if node is self: return node ident = getattr(node, 'graphident', None) return ident
Get the identifier for a node object
def parse(self): try: self.parsed_data = json.loads(self.data) except UnicodeError as e: self.parsed_data = json.loads(self.data.decode('latin1')) except Exception as e: raise Exception('Error while converting response from JSON to python. %s' % e) if ...
parse geojson and ensure is collection
def diskdata(): p = os.popen("/bin/df -l -P") ddata = {} tsize = 0 for line in p.readlines(): d = line.split() if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]): tsize = tsize + int(d[1]) ddata["Disk_GB"] = int(tsize)/1000000 p.close() return dd...
Get total disk size in GB.
def _check_stringify_year_column(self, column_index): table_column = TableTranspose(self.table)[column_index] prior_year = None for row_index in range(self.start[0]+1, self.end[0]): current_year = table_column[row_index] if not self._check_years(current_year, prior_year):...
Same as _check_stringify_year_row but for columns.
def validate_commits(repo_dir, commits): log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir)) repo = Repo(repo_dir) for commit in commits: try: commit = repo.commit(commit) except Exception: msg = ("Commit {commit} could not be found in repo {repo}. ...
Test if a commit is valid for the repository.
def mold_id_to_path(self, mold_id, default=_marker): def handle_default(debug_msg=None): if debug_msg: logger.debug('mold_id_to_path:' + debug_msg, mold_id) if default is _marker: raise KeyError( 'Failed to lookup mold_id %s to a path' ...
Lookup the filesystem path of a mold identifier.
def press_button(self, value): button = find_button(world.browser, value) if not button: raise AssertionError( "Cannot find a button named '{}'.".format(value)) button.click()
Click the button with the given label.
def _update_mean_coords(self, dig, N, centers_sum, **paircoords): if N is None or centers_sum is None: return N.flat[:] += utils.bincount(dig, 1., minlength=N.size) for i, dim in enumerate(self.dims): size = centers_sum[i].size centers_sum[i].flat[:] += utils.bincount(dig...
Update the mean coordinate sums
def from_file(self, vasprun_file): vrun_obj = Vasprun(vasprun_file, parse_projected_eigen=True) return VasprunLoader(vrun_obj)
Get a vasprun.xml file and return a VasprunLoader
def remove_callback(self, callback): if callback in self.callbacks: self.callbacks.remove(callback)
Remove callback from the list of callbacks if it exists
def add_tag(self, tag): if tag not in self._tags: self._tags[tag] = dict()
add a tag to the tag list
def dirty(self): return not os.path.exists(self.cachename) or \ (os.path.getmtime(self.filename) > os.path.getmtime(self.cachename))
True if the cache needs to be updated, False otherwise
def filter_content_types(self, content_type_qs): valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, EventBase): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
Filter the content types selectable to only event subclasses
def _set_mask(self, mask): self.mask = mask.copy() if self.h5 is not None: if 'mask' in self.h5: self.h5.pop('mask') self.h5.create_dataset('mask', mask.shape, dtype=self.mask.dtype, data=mask, compression="gzip", shuffle=True)
Set mask array in both class and hdf5 file
def _iter_texts(self, tree): skip = ( not isinstance(tree, lxml.html.HtmlElement) or tree.tag in self.skipped_tags ) if not skip: if tree.text: yield Text(tree.text, tree, 'text') for child in tree: for text in self....
Iterates over texts in given HTML tree.