code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
_stack = self.stack list_compounds = _stack.keys() if compound not in _stack.keys(): list_compounds_joined = ', '.join(list_compounds) raise ValueError("Compound '{}' could not be find in {}".format(compound, list_compounds_joined)) if element == '': ...
def set_isotopic_ratio(self, compound='', element='', list_ratio=[])
defines the new set of ratio of the compound/element and trigger the calculation to update the density Parameters: =========== compound: string (default is ''). Name of compound element: string (default is ''). Name of element list_ratio: list (default is []). list of new stoich...
3.306921
3.366477
0.982309
_stack = self.stack if compound == '': _list_compounds = _stack.keys() list_all_dict = {} for _compound in _list_compounds: _list_element = _stack[_compound]['elements'] list_all_dict[_compound] = {} for _eleme...
def get_density(self, compound='', element='')
returns the list of isotopes for the element of the compound defined with their density Parameters: =========== compound: string (default is empty). If empty, all the stoichiometric will be displayed element: string (default is same as compound). Raises: ======= ...
2.92624
3.029636
0.965872
# populate stack_sigma (Sigma vs Energy for every element) self.__get_sigmas() # populate compound density (if none provided) self.__update_layer_density() # populate compound molar mass # self.__update_layer_molar_mass() ### included in __calculate_atoms_per...
def __math_on_stack(self, used_lock=False)
will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the layers....etc.
8.992779
7.203633
1.248367
if self.stack == {}: density_lock = {} else: density_lock = self.density_lock for _compound in stack.keys(): _density = stack[_compound]['density']['value'] if np.isnan(_density): density_lock[_compound] = False ...
def __lock_density_if_defined(self, stack: dict)
lock (True) the density lock if the density has been been defined during initialization Store the resulting dictionary into density_lock Parameters: =========== stack: dictionary (optional) if not provided, the entire stack will be used
3.429577
3.005262
1.141191
stack = self.stack _density_lock = self.density_lock for _name_of_compound in stack.keys(): if used_lock and _density_lock[_name_of_compound]: continue molar_mass_layer, atoms_per_cm3_layer = _utilities.get_atoms_per_cm3_of_layer( ...
def __calculate_atoms_per_cm3(self, used_lock=False)
calculate for each element, the atoms per cm3
3.023681
2.903552
1.041373
for _key in stack: _elements = stack[_key]['elements'] for _element in _elements: _dict = _utilities.get_isotope_dicts(element=_element, database=self.database) stack[_key][_element] = _dict stack = self.__fill_missing_keys(stack=stack) ...
def __update_stack_with_isotopes_infos(self, stack: dict)
retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack
4.991108
4.318051
1.155871
_stack = self.stack _density_lock = self.density_lock list_compound = _stack.keys() for _key in list_compound: if _density_lock[_key]: continue _list_ratio = _stack[_key]['stoichiometric_ratio'] _list_density = [] ...
def __update_layer_density(self)
calculate or update the layer density
3.933083
3.787156
1.038532
_density_element = 0 list_ratio = self.stack[compound][element]['isotopes']['isotopic_ratio'] list_density = self.stack[compound][element]['isotopes']['density']['value'] ratio_density = zip(list_ratio, list_density) for _ratio, _density in ratio_density: _de...
def __update_density(self, compound='', element='')
Re-calculate the density of the element given due to stoichiometric changes as well as the compound density (if density is not locked) Parameters: =========== compound: string (default is '') name of compound element: string (default is '') name of element
3.591045
3.733474
0.961851
_molar_mass_element = 0 list_ratio = self.stack[compound][element]['isotopes']['isotopic_ratio'] list_mass = self.stack[compound][element]['isotopes']['mass']['value'] ratio_mass = zip(list_ratio, list_mass) for _ratio, _mass in ratio_mass: _molar_mass_elemen...
def __update_molar_mass(self, compound='', element='')
Re-calculate the molar mass of the element given due to stoichiometric changes Parameters: ========== compound: string (default is '') name of compound element: string (default is '') name of element
2.969021
3.141878
0.944983
stack_sigma = {} _stack = self.stack _file_path = os.path.abspath(os.path.dirname(__file__)) _database_folder = os.path.join(_file_path, 'reference_data', self.database) _list_compounds = _stack.keys() for _compound in _list_compounds: _list_element...
def __get_sigmas(self)
will populate the stack_sigma dictionary with the energy and sigma array for all the compound/element and isotopes
2.42392
2.277998
1.064057
parser = argparse.ArgumentParser(description='Compose a yaml file.') parser.add_argument( 'root', type=argparse.FileType('r'), help='The root yaml file to compose.' ) args = parser.parse_args() result = yaml.load(args.root, Loader=ComposeLoader) print(yaml.dump(re...
def main()
Builds a yaml file
3.106788
2.871825
1.081816
if text is None or not text.strip(): return None # first try to parse as an ISO8601 date, if it doesn't work we'll try other options if len(text) >= 16: try: parsed = iso8601.parse_date(text, default_timezone=None) if not parsed.t...
def _parse(self, text, mode)
Returns a date, datetime or time depending on what information is available
3.38869
3.320916
1.020408
sequences = [] date_sequences = cls.DATE_SEQUENCES_DAY_FIRST if date_style == DateStyle.DAY_FIRST else cls.DATE_SEQUENCES_MONTH_FIRST if mode == Mode.DATE or mode == Mode.AUTO: for seq in date_sequences: if len(seq) == length: sequences.a...
def _get_possible_sequences(cls, mode, length, date_style)
Gets possible component sequences in the given mode :param mode: the mode :param length: the length (only returns sequences of this length) :param date_style: whether dates are usually entered day first or month first :return:
1.856449
1.786758
1.039005
token = token.lower().strip() possibilities = {} try: as_int = int(token) if mode != Mode.TIME: if 1 <= as_int <= 9999 and (len(token) == 2 or len(token) == 4): possibilities[Component.YEAR] = as_int if 1 <= as...
def _get_token_possibilities(cls, token, mode)
Returns all possible component types of a token without regard to its context. For example "26" could be year, date or minute, but can't be a month or an hour. :param token: the token to classify :param mode: the parse mode :return: the dict of possible types and values if token was of t...
2.081425
2.076298
1.00247
date = None time = None if Component.MONTH in values: year = cls._year_from_2digits(values.get(Component.YEAR, now.year), now.year) month = values[Component.MONTH] day = values.get(Component.DAY, 1) try: date = datetime.da...
def _make_result(cls, values, now, timezone)
Makes a date or datetime or time object from a map of component values :param values: the component values :param now: the current now :param timezone: the current timezone :return: the date, datetime, time or none if values are invalid
1.97906
1.943312
1.018395
if short_year < 100: short_year += current_year - (current_year % 100) if abs(short_year - current_year) >= 50: if short_year < current_year: return short_year + 100 else: return short_year - 100 ret...
def _year_from_2digits(short_year, current_year)
Converts a relative 2-digit year to an absolute 4-digit year :param short_year: the relative year :param current_year: the current year :return: the absolute year
2.141566
2.289371
0.935439
# Get Various Lists / Project Waivers lists = get_lists.GetLists() # Get file name black list and project waivers file_audit_list, file_audit_project_list = lists.file_audit_list(project) # Get file content black list and project waivers flag_list, ignore_list = lists.file_content_list(pr...
def prepare_patchset(project, patchset, binaries, ips, urls)
Create black/white lists and default / project waivers and iterates over patchset file
3.820747
3.607635
1.059073
v_api = virus_total.VirusTotal() while True: binary_report = v_api.binary_report(sha256hash, apikey) response_code = binary_report['response_code'] # report does not exist, need to scan if response_code == 0: logger.info('Performing new scan of %s.', patch_file...
def scan_binary(patch_file, project, sha256hash, apikey)
Sends Binary (sha256hash) to Virus Total API
3.148216
3.099368
1.01576
report_url = binary_report['permalink'] scan_date = binary_report['scan_date'] logger.info('File scan date for %s shows a clean status on: %s', patch_file, scan_date) logger.info('Full report avaliable here: %s', report_url) logger.info('The following sha256 hash can be used in your %s.yaml fil...
def negative_report(binary_report, sha256hash, project, patch_file)
If no match is made and file is clean
3.472249
3.439396
1.009552
failure = True report_url = binary_report['permalink'] scan_date = binary_report['scan_date'] logger.error("Virus Found!") logger.info('File scan date for %s shows a infected status on: %s', patch_file, scan_date) logger.info('Full report avaliable here: %s', report_url)
def positive_report(binary_report, sha256hash, project, patch_file)
If a Positive match is found
7.483878
7.653627
0.977821
logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr) v_api = virus_total.VirusTotal() scan_ip = v_api.send_ip(ipaddr, apikey) response_code = scan_ip['response_code'] verbose_msg = scan_ip['verbose_msg'] urls = scan_ip['detected_urls'] if urls: failure = True ...
def scan_ipaddr(ipaddr, apikey)
If an IP Address is found, scan it
4.752334
4.768679
0.996572
logger.info('Found what I believe is a URL: %s', url) v_api = virus_total.VirusTotal() while True: url_report = v_api.url_report(url, apikey) response_code = url_report['response_code'] # report does not exist, need to scan if response_code == -2: logger.inf...
def scan_url(url, apikey)
If URL is found, scan it
4.466386
4.378477
1.020078
if failure: lists = get_lists.GetLists() report_url = lists.report_url(project) if report_url: print(report_url) sys.exit(1)
def process_failure(project)
If any scan operations register a failure, sys.exit(1) is called to allow build to register a failure
6.164465
5.759452
1.070321
return np.average(np.array(np.gradient(data))**2)
def average_gradient(data, *kwargs)
Compute average gradient norm of an image
6.180676
5.755386
1.073894
av = np.average(data, *kwargs) mal = 1 / (data.shape[0] * data.shape[1]) return np.sqrt(mal * np.sum(np.square(data - av)))
def contrast_rms(data, *kwargs)
Compute RMS contrast norm of an image
3.858268
3.534426
1.091625
# Set up fast fourier transform # if not data.dtype == np.dtype(np.complex): # data = np.array(data, dtype=np.complex) # fftplan = fftw3.Plan(data.copy(), None, nthreads = _ncores, # direction="forward", flags=_fftwflags) # fftdata = np.zeros(data.shape, dtype=np.comp...
def spectral(data, lambd, *kwargs)
Compute spectral contrast of image Performs bandpass filtering in Fourier space according to optical limit of detection system, approximated by twice the wavelength. Parameters ---------- data : 2d ndarray the image to compute the norm from lambd : float wavelength of the ligh...
3.202334
3.321776
0.964043
abspath = abspath.lower() _, ext = os.path.splitext(abspath) if ext in [".gz", ".zip"]: is_gzip = True else: is_gzip = False return is_gzip
def is_gzip_file(abspath)
Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file
2.440992
2.821111
0.865259
is_gzip = is_gzip_file(path) with open(path, "wb") as f: if is_gzip: f.write(zlib.compress(s.encode(encoding))) else: f.write(s.encode(encoding))
def write(s, path, encoding="utf-8")
Write string to text file.
2.323986
2.19373
1.059376
is_gzip = is_gzip_file(path) with open(path, "rb") as f: if is_gzip: return zlib.decompress(f.read()).decode(encoding) else: return f.read().decode(encoding)
def read(path, encoding="utf-8")
Read string from text file.
2.258352
2.235574
1.010189
with open(path, "rb") as f: content = f.read() result = chardet.detect(content) return content.decode(result["encoding"])
def smartread(path)
Read text from file, automatically detect encoding. ``chardet`` required.
2.799052
2.368007
1.182029
if output_path is None: basename, ext = os.path.splitext(path) output_path = basename + "-UTF8Encode" + ext text = smartread(path) write(text, output_path)
def to_utf8(path, output_path=None)
Convert any text file to utf8 encoding.
4.118407
4.130236
0.997136
strip_method = str(strip).lower() if strip_method in _strip_method_mapping: strip_func = _strip_method_mapping[strip_method] else: raise ValueError("'strip' keyword has to be one of " "None, 'left', 'right', 'both'.") with open(path, "rb") as file: ...
def readlines(path, encoding="utf-8", skiplines=None, nlines=None, strip='right')
skip n lines and fetch the next n lines. :param skiplines: default None, skip first n lines :param nlines: default None, yield next n lines :param strip: default None, available option 'left', 'right', 'both' **中文文档** 跳过前#skiplines行, 然后读取#nlines行。可对字符串进行strip预处理。
2.322261
2.365985
0.98152
strip_method = str(strip).lower() if strip_method in _strip_method_mapping: strip_func = _strip_method_mapping[strip_method] else: raise ValueError("'strip' keyword has to be one of " "None, 'left', 'right', 'both'.") with open(path, "rb") as file: ...
def readchunks(path, encoding="utf-8", skiplines=None, chunksize=None, strip='right')
skip n lines and fetch the next n lines as a chunk, and repeat fetching. :param skiplines: default None, skip first n lines :param chunksize: default None (size-1 chunk), lines chunk size :param strip: default None, avaliable option 'left', 'right', 'both' **中文文档** 跳过前#skiplines行, 每次读...
2.620111
2.714842
0.965106
if value is None: return "" # empty string rather than none elif isinstance(value, dict): if '*' in value: return value['*'] elif '__default__' in value: return value['__default__'] else: return jso...
def _coerce_to_supported_type(cls, value)
Since we let users populate the context with whatever they want, this ensures the resolved value is something which the expression engine understands. :param value: the resolved value :return: the value converted to a supported data type
3.471275
3.423179
1.01405
input_chars = list(template) output_chars = [] errors = [] state = State.BODY current_expression_chars = [] current_expression_terminated = False parentheses_level = 0 # determines whether the given character is a word character, i.e. \w in a reg...
def evaluate_template(self, template, context, url_encode=False, strategy=EvaluationStrategy.COMPLETE)
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports" :param template: the template string :param context: the evaluation context :param url_encode: whether or not values should be URL encoded :return: a tuple of the evaluated template and a list...
2.676438
2.655185
1.008004
try: body = expression[1:] # strip prefix # if expression doesn't start with ( then check it's an allowed top level context reference if not body.startswith('('): top_level = body.split('.')[0].lower() if top_level not in self._allow...
def _resolve_expression_block(self, expression, context, url_encode, strategy, errors)
Resolves an expression block found in the template, e.g. @(...). If an evaluation error occurs, expression is returned as is.
4.845607
4.547173
1.065631
from .gen.ExcellentLexer import ExcellentLexer from .gen.ExcellentParser import ExcellentParser stream = InputStream(expression) lexer = ExcellentLexer(stream) tokens = CommonTokenStream(lexer) parser = ExcellentParser(tokens) parser._errHandler = BailE...
def evaluate_expression(self, expression, context, strategy=EvaluationStrategy.COMPLETE)
Evaluates a single expression, e.g. "contact.reports * 2" :param expression: the expression string :param context: the evaluation context :param strategy: the evaluation strategy :return: the evaluated expression value
2.800582
2.889322
0.969287
from .gen.ExcellentParser import ExcellentParser has_missing = False output_components = [] for t in range(len(tokens.tokens) - 1): # we can ignore the final EOF token token = tokens.get(t) next_token = tokens.get(t + 1) # if token is a NA...
def _resolve_available(self, tokens, context)
Checks the token stream for context references and if there are missing references - substitutes available references and returns a partially evaluated expression. :param tokens: the token stream (all tokens fetched) :param context: the evaluation context :return: the partially evaluated...
4.210867
3.839336
1.09677
func_name = ctx.fnname().getText() if ctx.parameters() is not None: parameters = self.visit(ctx.parameters()) else: parameters = [] return self._functions.invoke_function(self._eval_context, func_name, parameters)
def visitFunctionCall(self, ctx)
expression : fnname LPAREN parameters? RPAREN
4.379982
3.452696
1.268569
return -conversions.to_decimal(self.visit(ctx.expression()), self._eval_context)
def visitNegation(self, ctx)
expression: MINUS expression
18.372389
15.92514
1.153672
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context) arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context) return conversions.to_decimal(decimal_pow(arg1, arg2), ctx)
def visitExponentExpression(self, ctx)
expression: expression EXPONENT expression
3.350831
3.315067
1.010788
is_mul = ctx.TIMES() is not None arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context) arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context) if not is_mul and arg2 == Decimal(0): raise EvaluationError("Division ...
def visitMultiplicationOrDivisionExpression(self, ctx)
expression: expression (TIMES | DIVIDE) expression
3.105196
2.868244
1.082612
is_add = ctx.PLUS() is not None arg1 = self.visit(ctx.expression(0)) arg2 = self.visit(ctx.expression(1)) # first try as decimals try: _arg1 = conversions.to_decimal(arg1, self._eval_context) _arg2 = conversions.to_decimal(arg2, self._eval_contex...
def visitAdditionOrSubtractionExpression(self, ctx)
expression: expression (PLUS | MINUS) expression
2.62049
2.576759
1.016971
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context) if isinstance(arg1, str): # string comparison is case-insensitive compared = (arg1.lower() > arg2.lower()) - (arg1.lower() < arg2.lower()) else: ...
def visitComparisonExpression(self, ctx)
expression: expression (LTE | LT | GTE | GT) expression
2.492676
2.345608
1.0627
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context) if isinstance(arg1, str): # string equality is case-insensitive equal = arg1.lower() == arg2.lower() else: equal = arg1 == arg2 ...
def visitEqualityExpression(self, ctx)
expression: expression (EQ | NEQ) expression
3.681778
3.548727
1.037493
arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context) arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._eval_context) return arg1 + arg2
def visitConcatenation(self, ctx)
expression: expression AMPERSAND expression
2.99599
2.996382
0.999869
identifier = ctx.NAME().getText() return self._eval_context.resolve_variable(identifier)
def visitContextReference(self, ctx)
expression: NAME
11.335741
8.440928
1.34295
with open(self.cache_path, "rb") as f: print("Loading cached Zotero data...") cache = pickle.load(f) self._references = cache[self.CACHE_REFERENCE_LIST] self.reference_types = cache[self.CACHE_REFERENCE_TYPES] self.reference_templates = cache[...
def load_cache(self)
Load the cached Zotero data.
3.243546
2.77947
1.166965
print("Loading distant Zotero data...") self._references = self.get_references() self.reference_types = self.get_reference_types() self.reference_templates = self.get_reference_templates(self.reference_types) print("Distant Zotero data loaded.") self.cache()
def load_distant(self)
Load the distant Zotero data.
4.600725
3.427794
1.342183
with open(self.cache_path, "wb") as f: cache = {self.CACHE_REFERENCE_LIST: self._references, self.CACHE_REFERENCE_TYPES: self.reference_types, self.CACHE_REFERENCE_TEMPLATES: self.reference_templates} pickle.dump(cache, f)
def cache(self)
Cache the Zotero data.
3.425995
3.207626
1.068078
self.validate_reference_data(ref_data) creation_status = self._zotero_lib.create_items([ref_data]) try: created_item = creation_status["successful"]["0"] return created_item except KeyError as e: print(creation_status) raise Create...
def create_distant_reference(self, ref_data)
Validate and create the reference in Zotero and return the created item.
5.169957
3.681754
1.40421
self._references[index] = ref self.cache()
def update_local_reference(self, index, ref)
Replace the reference in the reference list and cache it.
11.783285
6.217421
1.895205
self.validate_reference_data(ref["data"]) self._zotero_lib.update_item(ref)
def update_distant_reference(self, ref)
Validate and update the reference in Zotero. Existing fields not present will be left unmodified.
13.725584
8.005194
1.714585
try: self._zotero_lib.check_items([ref_data]) except InvalidItemFields as e: raise InvalidZoteroItemError from e
def validate_reference_data(self, ref_data)
Validate the reference data. Zotero.check_items() caches data after the first API call.
11.624368
7.253596
1.602566
item_types = self._zotero_lib.item_types() return sorted([x["itemType"] for x in item_types])
def get_reference_types(self)
Return the reference types. Zotero.item_types() caches data after the first API call.
9.441682
4.669371
2.022046
return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types])
def get_reference_templates(self, ref_types)
Return the reference templates for the types as an ordered dictionary.
4.376011
2.899872
1.509036
template = self._zotero_lib.item_template(ref_type) return OrderedDict(sorted(template.items(), key=lambda x: x[0]))
def get_reference_template(self, ref_type)
Return the reference template for the type as an ordered dictionary. Zotero.item_template() caches data after the first API call.
6.376388
3.221708
1.979195
ref_data = self.reference_data(index) extra_fields = ref_data["extra"].split("\n") field_id = field + ":" matched = next((x for x in extra_fields if x.startswith(field_id)), None) if matched: return matched.replace(field_id, "", 1).strip() else: ...
def reference_extra_field(self, field, index)
Return the value of the field in 'extra', otherwise ''.
3.070328
2.751931
1.115699
# TODO Include ISBN and ISSN? doi = self.reference_doi(index) if doi: return doi else: pmid = self.reference_pmid(index) if pmid: return "PMID_" + pmid else: unpublished_id = self.reference_unpublish...
def reference_id(self, index)
Return the reference ID (locally defined).
3.087668
3.020347
1.022289
return self.reference_data(index).get("DOI", self.reference_extra_field("DOI", index))
def reference_doi(self, index)
Return the reference DOI.
6.975805
6.454398
1.080783
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types? # Academic books published as a collection of chapters contributed by # different authors have editors but not authors at the level of the # book (as opposed to the level of a chapter). creators = sel...
def reference_creator_surnames(self, index)
Return as a list the surnames of the reference creators (locally defined).
7.351621
6.826113
1.076985
# TODO Use meta:parsedDate field instead? ref_date = self.reference_date(index) try: # NB: datetime.year returns an int. return parse(ref_date).year except ValueError: matched = re.search(r"\d{4}", ref_date) if matched: ...
def reference_year(self, index)
Return the reference publication year.
5.685457
5.319
1.068896
# TODO Change the column name 'Journal' to an other? ref_type = self.reference_type(index) if ref_type == "journalArticle": return self.reference_data(index)["publicationTitle"] else: return "({})".format(ref_type)
def reference_journal(self, index)
Return the reference journal name.
6.485957
6.410765
1.011729
try: indexes = range(self.reference_count()) return next(i for i in indexes if self.reference_id(i) == ref_id) except StopIteration as e: raise ReferenceNotFoundError("ID: " + ref_id) from e
def reference_index(self, ref_id)
Return the first reference with this ID.
3.539359
3.075055
1.15099
# FIXME Delayed refactoring. Use an index instead of an ID. index = self.reference_index(ref_id) creators = self.reference_creator_surnames(index) creator_count = len(creators) if creator_count == 0: return "" year = self.reference_year(index) ...
def reference_creators_citation(self, ref_id)
Return for citation the creator surnames (locally defined) and the publication year.
2.726338
2.579283
1.057014
if not isPDFInDb(paperId): return None userPDF.save("temp.pdf") # check_call is blocking check_call(['pdftotext', '-enc', 'UTF-8', "temp.pdf", "temp.txt"]) os.remove("temp.pdf") a = open("temp.txt", 'r').read() b = open(join(dbPath, paperId) + ".txt", 'r').read() import n...
def computePDFSimilarity(paperId, userPDF)
remove punctuation, lowercase, stem
2.526503
2.531858
0.997885
childrenDic = {} fileName = os.path.join(os.path.dirname(__file__), "children.bin") #### CHECK FOR CASE OF BBP TAGS if root_id[:4] == "BBP_": if not alwaysFetch: try: with open(fileName, "rb") as childrenFile: childrenDic = pickle.load(chil...
def getChildren(root_id, maxDepth=100, relationshipType="subClassOf", alwaysFetch=False)
Accessing web-based ontology service is too long, so we cache the information in a pickle file and query the services only if the info has not already been cached.
3.418176
3.407807
1.003043
try: disable_plugins = config.disable_plugins if not disable_plugins: disable_plugins = [] except AttributeError: disable_plugins = [] for plugin_name in plugins: plugin_group = f'backendai_{plugin_name}_v10' registry = PluginRegistry(plugin_name) ...
def install_plugins(plugins, app, install_type, config)
Automatically install plugins to the app. :param plugins: List of plugin names to discover and install plugins :param app: Any type of app to install plugins :param install_type: The way to install plugins to app :param config: Config object to initialize plugins :return: You should note that ...
3.068902
2.823593
1.086879
''' corners - list of nodal coordinates properly ordered for element type (counter clockwise) ''' lastelm = self.elements[-1][1] lastnode = self.nodes[-1][0] elm = [etype,lastelm+1] for i in range(old_div(len(corners),3)): elm.append(lastnode+1+i) ...
def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem')
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
4.040138
3.355757
1.203943
kwargs = {'type':type, 'entail':entail, 'limit':limit, 'skip':skip, 'callback':callback} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()} param_rest = self._make_rest('type', **kwargs) url = self._basePath + ('/graph/edges/{type}').format(**kwargs) ...
def getEdges(self, type, entail='true', limit=100, skip=0, callback=None, output='application/json')
Get nodes connected by an edge type from: /graph/edges/{type} Arguments: type: The type of the edge entail: Should subproperties and equivalent properties be included limit: The number of edges to be returned skip: The number of edges to skip callb...
3.392166
3.290339
1.030947
kwargs = {'id':id, 'depth':depth, 'blankNodes':blankNodes, 'relationshipType':relationshipType, 'direction':direction, 'project':project, 'callback':callback} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()} param_rest = self._make_rest('id', **kwargs) ...
def getNeighbors(self, id, depth=1, blankNodes='false', relationshipType=None, direction='BOTH', project='*', callback=None, output='application/json')
Get neighbors from: /graph/neighbors/{id} Arguments: id: This ID should be either a CURIE or an IRI depth: How far to traverse neighbors blankNodes: Traverse blank nodes relationshipType: Which relationship to traverse direction: Which direction to...
2.929756
2.945718
0.994581
kwargs = {'sample':sample, 'ontologyClass':ontologyClass, 'path':path, 'callback':callback} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()} param_rest = self._make_rest('path', **kwargs) url = self._basePath + ('/analyzer/enrichment').format(**kwargs)...
def enrich(self, sample, ontologyClass, path, callback=None, output='application/json')
Class Enrichment Service from: /analyzer/enrichment Arguments: sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes. ontologyClass: CURIE for parent ontology class for the attribute to be tested. For example, GO biological ...
3.865273
3.73595
1.034616
kwargs = {'content':content, 'includeCat':includeCat, 'excludeCat':excludeCat, 'minLength':minLength, 'longestOnly':longestOnly, 'includeAbbrev':includeAbbrev, 'includeAcronym':includeAcronym, 'includeNumbers':includeNumbers, 'ignoreTag':ignoreTag, 'stylesheet':stylesheet, 'scripts':scripts, 'targetId...
def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None)
Annotate text from: /annotations Arguments: content: The content to annotate includeCat: A set of categories to include excludeCat: A set of categories to exclude minLength: The minimum number of characters in annotated entities longestOnly: Should...
2.367883
2.317796
1.02161
kwargs = {'text':text} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()} param_rest = self._make_rest('text', **kwargs) url = self._basePath + ('/lexical/pos').format(**kwargs) requests_params = {k:v for k, v in kwargs.items() if k != 'text'} ...
def getPos(self, text)
Tag parts of speech. from: /lexical/pos Arguments: text: The text to tag
4.946568
4.719635
1.048083
kwargs = {'term':term, 'limit':limit, 'searchSynonyms':searchSynonyms, 'searchAbbreviations':searchAbbreviations, 'searchAcronyms':searchAcronyms, 'includeDeprecated':includeDeprecated, 'category':category, 'prefix':prefix} kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.item...
def findByPrefix(self, term, limit=20, searchSynonyms='true', searchAbbreviations='false', searchAcronyms='false', includeDeprecated='false', category=None, prefix=None)
Find a concept by its prefix from: /vocabulary/autocomplete/{term} Arguments: term: Term prefix to find limit: Maximum result count searchSynonyms: Should synonyms be matched searchAbbreviations: Should abbreviations be matched searchAcronyms: Shou...
2.795872
2.472786
1.130657
"Load zip file and return complex field" here = op.dirname(op.abspath(__file__)) data = op.join(here, "data") arc = zipfile.ZipFile(op.join(data, fname)) for f in arc.filelist: with arc.open(f) as fd: if f.filename.count("imag"): imag = np.loadtxt(fd) ...
def load_cell(fname="HL60_field.zip")
Load zip file and return complex field
3.642883
3.183757
1.144209
def split(data, indices, axis): s = [] s.append(slice(0, indices[0])) for i in range(len(indices) - 1): s.append(slice(indices[i], indices[i+1])) s.append(slice(indices[-1], None)) rt = [] for ss in s: ind = [slice(None, None, N...
def bootstrap(nside, rand, nbar, *data)
This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to estimate the effective area of a pixel n...
2.762565
2.588488
1.067251
r nside, theta, phi = numpy.lib.stride_tricks.broadcast_arrays(nside, theta, phi) def equatorial(nside, tt, z): t1 = nside * (0.5 + tt) t2 = nside * z * 0.75 jp = (t1 - t2).astype('i8') jm = (t1 + t2).astype('i8') ir = nside + 1 + jp - jm # in {1, 2n + 1} ksh...
def ang2pix(nside, theta, phi)
r"""Convert angle :math:`\theta` :math:`\phi` to pixel. This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G
3.341502
3.397194
0.983607
r nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix) ncap = nside * (nside - 1) * 2 npix = 12 * nside * nside def northpole(pix, npix): iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2 iphi = (pix + 1) - 2 * iring * (iring - 1) z = 1.0 - (iring*iring) *...
def pix2ang(nside, pix)
r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G
2.650101
2.683419
0.987584
if self.loaded: return exception_file = None for item in project_exceptions: if project in item: exception_file = item.get(project) if exception_file is not None: try: with open(exception_file, 'r') as f: ...
def load_project_flag_list_file(self, project_exceptions, project)
Loads project specific lists
3.109145
3.011857
1.032302
global il exception_file = None try: project_exceptions = il.get('project_exceptions') except KeyError: logger.info('project_exceptions missing in %s for %s', ignore_list, project) for project_files in project_exceptions: if project i...
def binary_hash(self, project, patch_file)
Gathers sha256 hashes from binary lists
3.236208
3.201755
1.010761
project_list = False self.load_project_flag_list_file(il.get('project_exceptions'), project) try: default_list = set((fl['file_audits']['file_names'])) except KeyError: logger.error('Key Error processing file_names list values') try: p...
def file_audit_list(self, project)
Gathers file name lists
3.991811
3.847582
1.037486
project_list = False self.load_project_flag_list_file(il.get('project_exceptions'), project) try: flag_list = (fl['file_audits']['file_contents']) except KeyError: logger.error('Key Error processing file_contents list values') try: ig...
def file_content_list(self, project)
gathers content strings
3.936862
3.923773
1.003336
project_list = False try: ignore_directories = il['ignore_directories'] except KeyError: logger.error('Key Error processing ignore_directories list values') try: project_exceptions = il.get('project_exceptions') for item in projec...
def ignore_directories(self, project)
Gathers a list of directories to ignore
3.628042
3.50293
1.035716
project_list = False try: url_ignore = il['url_ignore'] except KeyError: logger.error('Key Error processing url_ignore list values') try: project_exceptions = il.get('project_exceptions') for item in project_exceptions: ...
def url_ignore(self, project)
Gathers a list of URLs to ignore
2.964547
2.879641
1.029485
project_list = False try: ip_ignore = il['ip_ignore'] except KeyError: logger.error('Key Error processing ip_ignore list values') try: project_exceptions = il.get('project_exceptions') for item in project_exceptions: ...
def ip_ignore(self, project)
Gathers a list of URLs to ignore
2.983652
2.902443
1.02798
base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/' # Add GitHub junk to the file name for downloading. f = fname + '?raw=true' url = base_url + f block_size = 16384 req = urlopen(url) # Get file size from header if sys.version_inf...
def download_from_github(fname, path)
Download database from GitHub :param fname: file name with extension ('.zip') of the target item :type fname: str :param path: path to save unzipped files :type path: str :return: database folder :rtype: folder
3.157312
3.184247
0.991541
_file_path = os.path.abspath(os.path.dirname(__file__)) _ref_data_folder = os.path.join(_file_path, 'reference_data') _database_folder = os.path.join(_ref_data_folder, database) if not os.path.exists(_ref_data_folder): os.makedirs(_ref_data_folder) print("Folder to store database f...
def get_list_element_from_database(database='ENDF_VII')
return a string array of all the element from the database Parameters: ========== database: string. Name of database Raises: ====== ValueError if database can not be found
2.557918
2.617043
0.977407
if element == '': return False list_entry_from_database = get_list_element_from_database(database=database) if element in list_entry_from_database: return True return False
def is_element_in_database(element='', database='ENDF_VII')
will try to find the element in the folder (database) specified Parameters: ========== element: string. Name of the element. Not case sensitive database: string (default is 'ENDF_VII'). Name of folder that has the list of elements Returns: ======= bool: True if element was found in the dat...
3.520735
5.07006
0.694417
for _keys in stack: _elements = stack[_keys]['elements'] for _element in _elements: if not is_element_in_database(element=_element, database=database): raise ValueError("Element {} can not be found in the database".format(_element)) _thickness = stack[_keys]...
def checking_stack(stack, database='ENDF_VII')
This method makes sure that all the elements from the various stacks are in the database and that the thickness has the correct format (float) Parameters: ========== stack: dictionary that defines the various stacks database: string (default is 'ENDF_VII') name of database Raises: ====...
3.17034
2.402635
1.319526
if '.' in formula: raise ValueError("formula '{}' is invalid, containing symbol '{}' !".format(formula, '.')) _formula_parsed = re.findall(r'([A-Z][a-z]*)(\d*)', formula) if len(_formula_parsed) == 0: raise ValueError("formula '{}' is invalid !".format(formula)) # _dictionary = {}...
def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII')
create dictionary based on formula given Parameters: =========== formula: string ex: 'AgCo2' ex: 'Ag' thickness: float (in mm) default is np.NaN density: float (in g/cm3) default is np.NaN database: string (default is ENDV_VIII). Database where to look for elements Ra...
2.63722
2.24903
1.172603
_file_path = os.path.abspath(os.path.dirname(__file__)) _database_folder = os.path.join(_file_path, 'reference_data', database) _element_search_path = os.path.join(_database_folder, element + '-*.csv') list_files = glob.glob(_element_search_path) if not list_files: raise ValueError("Fi...
def get_isotope_dicts(element='', database='ENDF_VII')
return a dictionary with list of isotopes found in database and name of database files Parameters: =========== element: string. Name of the element ex: 'Ag' database: string (default is ENDF_VII) Returns: ======== dictionary with isotopes and files ex: {'Ag': {'isotope...
2.414925
2.406207
1.003623
if not os.path.exists(file_name): raise IOError("File {} does not exist!".format(file_name)) df = pd.read_csv(file_name, header=1) return df
def get_database_data(file_name='')
return the energy (eV) and Sigma (barn) from the file_name Parameters: =========== file_name: string ('' by default) name of csv file Returns: ======== pandas dataframe Raises: ======= IOError if file does not exist
2.605706
2.802651
0.929729
nbr_point = int((e_max - e_min) / e_step + 1) x_axis = np.linspace(e_min, e_max, nbr_point).round(6) y_axis_function = interp1d(x=df['E_eV'], y=df['Sig_b'], kind='linear') y_axis = y_axis_function(x_axis) return {'x_axis': x_axis, 'y_axis': y_axis}
def get_interpolated_data(df: pd.DataFrame, e_min=np.nan, e_max=np.nan, e_step=np.nan)
return the interpolated x and y axis for the given x range [e_min, e_max] with step defined :param df: input data frame :type df: pandas.DataFrame :param e_min: left energy range in eV of new interpolated data :type e_min: float :param e_max: right energy range in eV of new interpolated data :t...
2.704036
2.615319
1.033922
file_extension = os.path.splitext(database_file_name)[1] if t_kelvin is None: # '.csv' files if file_extension != '.csv': raise IOError("Cross-section File type must be '.csv'") else: _df = get_database_data(file_name=database_file_name) _dict =...
def get_sigma(database_file_name='', e_min=np.NaN, e_max=np.NaN, e_step=np.NaN, t_kelvin=None)
retrieve the Energy and sigma axis for the given isotope :param database_file_name: path/to/file with extension :type database_file_name: string :param e_min: left energy range in eV of new interpolated data :type e_min: float :param e_max: right energy range in eV of new interpolated data :typ...
4.204706
4.072856
1.032373
# atoms_per_cm3 = {} _list_of_elements = compound_dict['elements'] _stoichiometric_list = compound_dict['stoichiometric_ratio'] _element_stoichio = zip(_list_of_elements, _stoichiometric_list) _molar_mass_sum = 0 for _element, _stoichio in _element_stoichio: _molar_mass_sum += _st...
def get_atoms_per_cm3_of_layer(compound_dict: dict)
calculate the atoms per cm3 of the given compound (layer) :param compound_dict: compound infomation to pass :type compound_dict: dict :return: molar mass and atom density for layer :rtype: float
2.318778
2.277063
1.01832
miu_per_cm = 1e-24 * sigma_b * atoms_per_cm3 return np.array(miu_per_cm)
def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array)
calculate the transmission signal using the formula transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b) Parameters: =========== thickness: float (in cm) atoms_per_cm3: float (number of atoms per cm3 of element/isotope) sigma_b: np.array of sigma retrieved from database R...
6.140962
5.0042
1.227162
transmission = np.exp(-thickness_cm * miu_per_cm) return np.array(transmission)
def calculate_trans(thickness_cm: np.float, miu_per_cm: np.array)
calculate the transmission signal using the formula transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b) Parameters: =========== thickness: float (in cm) atoms_per_cm3: float (number of atoms per cm3 of element/isotope) sigma_b: np.array of sigma retrieved from database R...
5.075598
5.656131
0.897362
miu_per_cm = calculate_linear_attenuation_coefficient(atoms_per_cm3=atoms_per_cm3, sigma_b=sigma_b) transmission = calculate_trans(thickness_cm=thickness_cm, miu_per_cm=miu_per_cm) return miu_per_cm, transmission
def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array)
calculate the transmission signal using the formula transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b) Parameters: =========== thickness: float (in cm) atoms_per_cm3: float (number of atoms per cm3 of element/isotope) sigma_b: np.array of sigma retrieved from databas...
2.880091
3.465829
0.830996
if from_units == to_units: return value if from_units == 'cm': if to_units == 'mm': coeff = 10 elif to_units == 'm': coeff = 0.01 else: raise ValueError("to_units not supported ['cm','m','mm']!") elif from_units == 'mm': if to...
def set_distance_units(value=np.NaN, from_units='mm', to_units='cm')
convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== converted value Raises: ======= ValueError if from_units is not a v...
1.574396
1.647216
0.955792