content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_tdm_tree(): """Create tdm tree info""" tree_info = [ [0, 0, 0, 1, 2], [0, 1, 0, 3, 4], [0, 1, 0, 5, 6], [0, 2, 1, 7, 8], [0, 2, 1, 9, 10], [0, 2, 2, 11, 12], [0, 2, 2, 13, 0], [0, 3, 3, 14, 15], [0, 3, 3, 16, 17], [0, 3, ...
03a44baa724135b07b88f8f5bec4834262498320
3,608,400
import os import subprocess import logging import json def get_gateway_mfr_test_result(): """ Run gateway_mfr test and report back. """ direct_path = os.path.dirname(os.path.abspath(__file__)) gateway_mfr_path = os.path.join(direct_path, 'gateway_mfr') try: run_gateway_mfr_keys = subp...
7b13342190145b5fd09c86d3d81035919d5e0436
3,608,401
def find_all_key_entities(text): """ Find all key entity mentions in text, including locations, persons, and other types """ all_entities = [] try: doc = Doc(text) doc.segment(segmenter) doc.tag_morph(morph_tagger) doc.parse_syntax(syntax_parser) doc.tag_ner(n...
7efa5e9c2431638f158d1639adefb6376be7e467
3,608,402
def selftest_function(opts): """ Placeholder for selftest function. An example use would be to test package api connectivity. Suggested return values are be unimplemented, success, or failure. """ app_configs = opts.get("fn_create_zoom_meeting", {}) zoom = ZoomCommon(opts, app_configs) requ...
d18cdce7aebbf51ffc21aac988c8669f41c7c80d
3,608,403
def conv_F2C(value): """Converts degree Fahrenheit to degree Celsius. Input parameter: scalar or array """ value_c = (value-32)*(5/9) if(hasattr(value_c, 'units')): value_c.attrs.update(units='degC') return(value_c)
1f3ac169942c51b363a7ae7977890be237b95390
3,608,404
def get_db_tables_with_data() -> list: """Gets database tables. If table is empty pass""" full_dbs = [] get_tables = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") for table in get_tables: check_table_rows = cursor_2.execute(F'SELECT count(*) FROM {table[0]}') for ...
afd26c9a68c18ea547984d9b7812600e99231ff8
3,608,405
import time def inner_loop(repo, cref, clock=time): """Fetches the config ref and runs single iteration of processing. Returns: tuple (bool success status, list of synthesized commits). """ repo.fetch() cref.evaluate() return process_repo(repo, cref, clock)
2dd90ef7cdb84c3a032ba762027b42c7b4a316b1
3,608,406
def extract_yyyy_mm_dd_hh_mm_ss_from_datetime64(dt64): """ Extract separate fields for year, monday, day, hour, min, sec from a datetime64 object, or an array-like object of datetime64 objects Parameters ---------- dt64 : xarray DataArray, np.ndarray, list of, or single numpy.datetime64 ...
d41719fe92444bc4fff42c9cc496935e019409c7
3,608,407
import warnings def postelToDirCos(u, v): """Convert Postel azimuthal equidistant tangent plane projection u,v to direction cosines. Parameters ---------- u, v : float Postel tangent plane coordinates in radians. Returns ------- alpha, beta, gamma : float Direction co...
51819ce5b7d467acaf74bbb1f21895353fb46f42
3,608,408
import pandas def protocol_df_chunk_to_pandas(df): """ Convert exchange protocol chunk to ``pandas.DataFrame``. Parameters ---------- df : ProtocolDataframe Returns ------- pandas.DataFrame """ # We need a dict of columns here, with each column being a NumPy array (at # l...
99afa0e9a680da790c628d8770d1f71cf96f9828
3,608,409
def parse_dtype(s): """ Parse text as numpy dtype >>> parse_dtype('i4') dtype('int32') >>> parse_dtype("[('a', 'i4')]") dtype([('a', '<i4')]) """ if s.startswith(b'['): return np.dtype(eval(s)) # Dangerous! else: return np.dtype(s)
65dfe2331ea020a2860468029ef6318b618700d4
3,608,410
import argparse def arg_parser(): """CLI arg parser. Returns: [dict]: CLI args """ parser = argparse.ArgumentParser(description='Proxemo Runner') parser.add_argument('--settings', type=str, default='infer', metavar='s', help='config file for running the network.') ...
d211a90950374f1f1caebe31ecb8965a755b1f2b
3,608,411
import os import re def mdfile_in_dir(dire): """Judge if there is .md file in the directory i: input directory o: return Ture if there is .md file; False if not. """ for root, dirs, files in os.walk(dire): for filename in files: if re.search('.md$|.markdown$', filename): ...
880cd7a823fa4b42d8492882c48f7c5d70f4dc52
3,608,412
import re def test_custom_s3_decorator(): """Example of creating a custom decorator""" bucket = "my-bucket" prefix = "all-exceptions/" httpretty.register_uri(httpretty.PUT, re.compile(r".*amazonaws\..*"), body="") def my_exception_report(f): storage_backend = S3ErrorStorage(access_key="a...
17d8061cab2ca0b1cba50b00c8e93e4ce7b2545c
3,608,413
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username"...
9ddd7b76481f94239dee979cec44956db5aaf6cc
3,608,414
import os import time import requests def url_content(url, cache_duration=None, from_cache_on_error=False): """ Get content for the given URL :param str url: The URL to get content from :param int cache_duration: Optionally cache the content for the given duration to avoid downloading too often...
26b983daf3915839c52675b845ea203cd5588e9e
3,608,415
import os def get_checker_names(): """ Go through the config directory and figure out the checker names from the files there. """ names = [] files = os.listdir(CONFIGS_FOLDER) for fname in files: if fname.endswith(".dwmon"): names.append(fname.replace(".dwmon", "")) ...
c574367ace547f5883b0b23651d06b404da9bc3b
3,608,416
def get_cutoff(obj, r_max=units.length(1, 'nm'), r_min=0, hyperparam='default', return_mask=False, reverse=False): """get cutoff""" if obj is None or isinstance(obj, Cutoff): return obj if isinstance(obj, str): if obj not in _CUTOFF_ALIAS.keys(): raise ValueError( ...
8b1a0a104758ab9c60200cea1aad0f66b9d3283d
3,608,417
def AggFormula(formula, formulaParam, *matchPairs): """ Create a formula aggregation. :param formula: (java.lang.String) - the formula to apply to each group :param formulaParam: (java.lang.String) - the parameter name within the formula :param matchPairs: (java.lang.String...) - the columns to...
8ef974d0e1e7c0e5df8cd58a947766feb7a472b6
3,608,418
def status_in_range(value: int, lower: int = 100, upper: int = 600) -> bool: """ Validates the status code of a HTTP call is within the given boundary, inclusive. """ return value in range(lower, upper+1)
43bb6f4824b7e42b6620e3ddff853aa65713f145
3,608,419
def combine_dicts(*args, exclude=(), deep_copy=False): """Returns a new dict with entries from all dicts passed, with later dicts overriding earlier ones. :param exclude: Remove these keys from the result. :param deepcopy: Perform a deepcopy of the dicts before combining them. """ if not len(args): ...
49627b9f37c08be7f7d3f51f8a47ddb316c545d4
3,608,420
def get_FR_dev(start_time,end_time,sim_dt,spikemon,n): """ get firing rate given spikemonitor and time interval. quantify deviation as well. start_time: time of input start end_time: time of input end sim_dt: simulation time step spikemon_t: time array from spike monitor n: total number...
579ba454cdbc924cca5b4789fcc6e57cd81c977c
3,608,421
def _convert_from_roi(fname): """Convert a roi file to a numpy array [x, y, h, w]. Parameters ---------- fname : string If ends with `.roi`, we assume a full path is given """ if not fname.endswith('.roi'): fname = '%s.roi' % join(IJ_ROI_DIR, fname) with open(fname, 'rb') ...
80cc53ed8ac576100974e9d7843751fed0173141
3,608,422
def init_grid (mins=0, limits=np.array([-180, 180, -90, 90])): """ Initiates the grid variables based on the number of points wanted within the given limits gris step is in minutes, 60 min = 1 degree """ dim = limits * pi/180 if ( (mins < 1) or (mins > 600) ): size_long = 5 ...
5aaf240aa4a958e9fa6df2de5abb545647b761c4
3,608,423
def author(request, author): """ View function for author """ return render(request, 'author.html', {})
a1b713d8919d16728322dc478c1d46abb7f22ca9
3,608,424
def import_feed_from_text(text, filename=None) -> [str]: """ >>> text = "<opml> https://blog.guyskk.com/blog/1 https://blog.anyant.com" >>> expect = set(['https://blog.guyskk.com/blog/1', 'https://blog.anyant.com']) >>> set(import_feed_from_text(text)) == expect True >>> set(import_feed_from_tex...
197f3551b90f328025b46d4c0a75d3fca0028ee6
3,608,425
def create_attachment(b64_data, name): """Create a Salesforce attachment object from a jpeg.""" attachment = Attachment() attachment.update_fields({ "Body": b64_data, "Name": name, }) return attachment
a8aa9537535430a2237e569d24a28f70a710fd96
3,608,426
def getSteamAppDir(appid: int) -> str: """ A function that retrieves the folder of an app by searching in all possible libraries \t :param appid: The app's id to search for :return: path to app's folder :raises RuntimeError: raised when the app is not found """ for path in libraryFolders(): try: logger.inf...
c93736aafa5440f530a3d025cf8e92313dcb2bf0
3,608,427
def lyapunov(A, Q=None): """ Solve the equation :math:`A^T X + X A = -Q`. default Q is set to I :param A: system matrix :type A: np.ndarray | np.matrix | List[List] :param Q: matrix :type Q: np.ndarray | np.matrix :return: the matrix X if there is a solution :rtype: np.ndarray | No...
bfc65d7966e12b640b2e52e0bee28c1f23d95000
3,608,428
def _resize_cropped(image, image_size, thumbnail_display_size, thumbnail_image_size): """ Resizes the image to fit the desired size, preserving aspect ratio by cropping, if required. """ # Resize with nice filter. image_aspect = image_size.aspect if image_aspect > thumbnail_image_size.aspect...
7067c2348e6bcb35f3e6e33d2e7fe16a6b9e8855
3,608,429
def nodeOrdering(criteria = "const FieldList<%(Dimension)s, %(DataType)s>&"): """Compute the order that a given set of nodes should be stepped through given a FieldList of things to sort them by. The FieldList returned is the one to N indexing corresponding to sorting the input in increasing order.""" return "...
70af2ca0549a03e3e6bf9cfd08b6d831770c4a31
3,608,430
def xtile(lst, lo=0, hi=1, width=50, chops=[0.1, 0.3, 0.5, 0.7, 0.9], marks=[" ", ".", ".", " ", " "], bar="", star="o", show=" %5.3f"): """ Pretty print a large list of numbers. Take a list of numbers, sort them, then print them as a horizontal xt...
e9c548a3d9bdf1fd015f9e11b692afa1e35a509d
3,608,431
import six def format_decimal(decimal): """ Formats a decimal number using the same precision as Excel :param decimal: the decimal value :return: the formatted string value """ getcontext().rounding = ROUND_HALF_UP # strip trailing zeros normalized = decimal.normalize() sign, digi...
e4907e613832856802de7a2fa933877012aaaec2
3,608,432
def avg_Nc(log10mhalo,z,log10mstellar_thresh,sig_log_mstellar): """<Nc(m)>""" log10mstar = Mstellar_halo(z,log10mhalo) num = log10mstellar_thresh - log10mstar denom = np.sqrt(2.) * sig_log_mstellar return 0.5*(1. - erf(num/denom))
9575d43ba1477e697937916094345020380cbab3
3,608,433
def get_hiragana(word: str) -> str: """文字列をひらがなに変換します。 Args: word (str): 変換する文字列 Returns: str: ひらがな文字列 """ converted_word = jaconv.kata2hira(word) return converted_word
de2597a1846e8da038bcb8108fe7ca0357af3f9e
3,608,434
def get_activity_polylines(before=None, after=None, limit=None): """Gets activity polylines for user. Args: before (datetime or str): Optional. Retrieve activities before this date. Format YYYY-MM-DD. after (datetime or str): Optional. Retrieve activities after this date...
4ee542936b4dad7bca0702c1f7ea11a13fd1a125
3,608,435
import ast def processLambda(arg, exp, fail=ast.FAIL): """Destructure lambda arguments. f(λa1 a2 ... an.body) → f(λa1.f(λa2. ... f(λan.body))) f(λ[x . y].body) → λv.if pair? v then (f(λx y.body)) (head v) (tail v) else FAIL → λv.if pair? v then (λx.λy.body) (head v) (tail v) else FAIL...
c29a7a88885e4abada9c1e1ec4358875ac7b4cd7
3,608,436
def conv_1d(x, v, kernel_orientation='as-is', stride=1, mode='same', data_format='NCE'): """ Define the operator function. :param x: An input tensor of shape [num_batches, num_channels, num_elements]. :param v: A filter/kernel of shape [num_filters, num_channels, kernel_size]. :param kernel_orienta...
3df20c755b2f75d0902de954f79f52709734aca6
3,608,437
def tails_concentration(): """Calculate the possible enrichment given tails U234 concentrations """ # Split product in two parts to have a higher granularity in the # first part. size = 50 xp = np.concatenate((np.linspace(1, 20, size, endpoint=False), np.linspace(20, 9...
00463b6cc6a470ebce87e55da7cc70316071162a
3,608,438
async def crime_plot(current_city:City): """ Visualize crime information for city - see overall crime breakdown - visualize breakdown of violent crime and property crime ### Query Parameters - city ### Response JSON string to render with react-plotly.js """ city = validate_city...
477aa54ff87a6470757636a5ea3d7b2acd4f6df1
3,608,439
def _float_to_str(x): """ Converts a float to str making. For most numbers this results in a decimal representation (for xs:decimal) while for very large or very small numbers this results in an exponential representation suitable for xs:float and xs:double. """ return "%s" % x
cb795b9c4778b9a3fda7398024166d86d8458bd3
3,608,440
import argparse def parse_args(): """Argparser for command line input""" parser = argparse.ArgumentParser( description= "Utility for turning files into JavaScript-embeddable strings.", epilog=("Before using the program you have to insert " "stuff2str(\"/path/to/file\")...
6a0de612dc43baeb5f4eaefc654166de54a7326b
3,608,441
def create_ips(file1_content, file2_content): """ Creates a new Patch object based on the differences between file1 and file2 :Parameters: file1_content : bytearray Contents of the first file file2_content : bytearray Contents of the second file rtype: Patch return: The newly created Pat...
cff7e01025b93057cc952d23629f81a63ed3adc2
3,608,442
def unique_cluster_indices(cluster_indx): """ Return a unique list of cluster indices :param cluster_indx: Cluster index list of ClusterExpansionSetting """ unique_indx = [] for symmgroup in cluster_indx: for sizegroup in symmgroup: for cluster in sizegroup: ...
36bc5a287d49c6abbd552b9edc0e72675ba82eca
3,608,443
from datetime import datetime def get_slmtag_str(dbpath, timestamp=None): """Read the database and return an SLMTag string. dbpath - the path to the sqlite database. timestamp - to be used for testing only, where we want to ensure that log times are always the same. """ (authva...
5165ffc51a782b76e69a8575fc902101b0753b21
3,608,444
def makeExternalLink(url, anchor): """Function applied to wikiLinks""" if options.keepLinks: return '<a href="%s">%s</a>' % (quote(url.encode('utf-8')), anchor) else: return anchor
cf7d4895b2ca40ea780e18b95fd2aa28787ecee6
3,608,445
def _calculate_atr(atr_length, highs, lows, closes): """Calculate the average true range atr_length : time period to calculate over all_highs : list of highs all_lows : list of lows all_closes : list of closes """ if atr_length < 1: raise ValueError("Specified atr_length may not be l...
f5878eda22c09fa8c428122bd013f9c6088ea0f8
3,608,446
def combine_cdd_path(*, resp, **_): """Call function to generate combined dataframe from csv file and excel dataset, bringing only those flows from the excel file that are not in the csv file """ df_csv = write_cdd_path_from_csv() df_excel = epa_cddpath_call(resp=resp) df_excel = df_excel[~d...
752ad0305cc34b07789a019b1939726eeadb7f2f
3,608,447
def generate_handles(labels, colors, edge='k', alpha=1): """ Generate handles for the legend map :param labels: name of legend entry :param colors: color of legend box :param edge: edge colour, default is black :param alpha: transparency of legend, default is not transparent :return: handles...
0a97ec997bb0ea03b412eebedadb1617cadbb90d
3,608,448
def get_reviewers(request): """ All assigned reviewers, staff or admin """ return User.objects.filter(Q(submissions_reviewer__isnull=False) | Q(groups__name=STAFF_GROUP_NAME) | Q(is_superuser=True)).distinct()
fb0e7a7a34643ebbe02be5c5b61e01e585aaa2b9
3,608,449
import io def _load_data(fov_data, exp): """ Load a field of view dataset Parameters ---------- fov_data : pd.DataFrame Table of file locations for the spot results and mask label image corresponding to the dataset to be viewed exp : Experiment Experiment ...
95f95f9d6e9e28cec138757714d4686205f024cc
3,608,450
from typing import Any def move_file(client: Any, team_drive_id: str, file_id: str): """Moves a file from one team drive to another""" f = make_call(client.files(), "get", fileId=file_id, fields="parents", supportsTeamDrives=True) previous_parents = ",".join(f.get("parents")) return make_call( ...
6cbdd56b2898bf0c972413110cf2bd229504101e
3,608,451
from typing import Optional import asyncio def run( include_queues: Optional[str] = typer.Option( None, metavar="include-queues", help="Comma-separated list of the ONLY queues to listen on.", ), exclude_queues: Optional[str] = typer.Option( None, metavar="exclude-qu...
6a0342dd97e4a1c07f776ca558f67228e0059e00
3,608,452
def requested() -> bool: """Return whether listeners should shut down.""" return _flag.is_set()
b95736b7c1f31999c6e34828cf5d8d23fa4d16a2
3,608,453
import sh def extract_sac(data, ctable, processes): """ extract the downloaded data to the sac and pz format. """ # * get dirname thedir = dirname(data) # * mkdir for the sac and pz files sh.mkdir("-p", join(thedir, "SAC")) sh.mkdir("-p", join(thedir, "PZ")) # * extract sac win...
e58dab1eb747b9f6f727584f53598cf8f1e54b18
3,608,454
def _spin_echo_gates(idx: int) -> cirq.ops: """Outputs one of 4 single-qubit pi rotations which is used for spin echoes.""" pi_pulses = [ cirq.PhasedXPowGate(phase_exponent=0.0, exponent=1.0), cirq.PhasedXPowGate(phase_exponent=0.5, exponent=1.0), cirq.PhasedXPowGate(phase_exponent=1.0, ...
bf780d3c1de3caee4543e2eb4e5c5dfd7aaa3e08
3,608,455
def peak_normalization(spectrum, peak_range=[3.05, 4.05], verbose=False): """ Each spectrum is divided by its mean so that its median becomes 1 :param spectrum: dataframe of the spectrun values index are the cases and columns are the ppm value ...
475c4df7bc12ff6e7d32318cda104c42f66b3226
3,608,456
def get_pipelines(): """Retrieves all registered pipelines from installed modules Returns: dict: All registered pipelines. """ pipelines = {} for pipeline in iter_entry_points('pavo.deploy'): if pipeline.name not in pipelines.keys(): pipelines[pipeline.name] = pipeline.l...
3e42aaa5da8551e28cb32141e79533a633f8bf31
3,608,457
def get_node_text_tags_preserved(xml_node): """Get the body of an XML node as a string, avoiding a specific blacklist of bad tags.""" xml_node = deepcopy(xml_node) etree.strip_tags(xml_node, *_tag_black_list) # Remove the wrapping tag node_text = xml_node.text or '' node_text += ''.join(etr...
2611eea7e5fc484d9750cd420361e9ce8335c0db
3,608,458
import subprocess import json def _get_endpoint_config_id(cloud_project_prefix, cloud_project_name, endpoint_name): """Get the id of the latest endpoint configuration for the specified endpoint. There is a many-to-many relationship between endpoint names and endpoint configurations....
986a9f032d8d347372d108ce2aac6afd85afddcd
3,608,459
def _getopt_size(py_obj, option): """Gets the specified size option""" i = pynng.ffi.new('size_t []', 1) opt_as_char = pynng.nng.to_char(option) # attempt to accept floats that are exactly int obj, lib_func = _get_inst_and_func(py_obj, 'size', 'get') ret = lib_func(obj, opt_as_char, i) pynng...
90a99ec0edbbfbac7f90e65b531382756ad3761f
3,608,460
def fileFromItem(item): """ Return the file contained in an item. Raise an exception if the item doesn't contain exactly one file. """ files = Item().childFiles(item, limit=2) if files.count() != 1: raise DanesfieldWorkflowException( "Item must contain %d files, but should co...
16a86fe51f67b5df44370b247d5d7f777b2f53d9
3,608,461
def capacity_factor(pudl_out, min_cap_fact=0, max_cap_fact=1.5): """Calculate the capacity factor for each generator. Capacity Factor is calculated by using the net generation from eia923 and the nameplate capacity from eia860. The net gen and capacity are pulled into one dataframe and then run through...
87cf99cb19795e718d3cd43b76a858f27b13c61a
3,608,462
import json def get_minister_positions(minister, lang_code): """ Return all positions for the minister """ file_name = settings.MINISTER_JSON_FILE if lang_code == 'fr': status_prefix = 'Précédent ' else: status_prefix = 'Former ' positions = [] with open(file_name, 'r'...
2979ff7a59b9f47cd93fc6caa9cf5591c20e7d49
3,608,463
def home(): """Home page.""" current_app.logger.info("Hello from the home page!") return render_template("index.html")
3f9054e945eae7f377c3e3edc0fbe820aa021f59
3,608,464
def compare_interior_kaplan(obs, var_pair, rescale_kaplan=False, rescale_interior=False): """ Interior vs kaplan est for `multi_locus_analysis.finite_window.ab_window`. Compare the Kaplan-Meier estimator to the empirical distribution function (eCDF) of interior times of data...
9c53818c5fc873ae53b7a33cc57c2535898f6fbf
3,608,465
def all_intervals(text, elements, config): """From the slices of elements and units create an intervaltree. time consuming and may unnessesary to search the whole txt 1. search all elements in text 2. search all elements in paragraph! 3. links > 40: search with aho-coressio search algo for speed ...
06f4e764c74984ab71667417033331688ff5090f
3,608,466
def multigauss(x, mu, cov, norm=True): """ Evaluates multivariate Gaussian distributions, each at different data points. This code is optimised to evaluate M Gaussians of dimension N at M points. The distribution is normalised by default but there is an option to turn off normalisation. ...
036f4f7104b65a8b049839457bc43bf9b9720c97
3,608,467
import torch def preprocess(camera_value): # Preprocessing for camera format --> Network input format """ Preprocessing function for camera format --> network input format param camera_value: input from Camera type camera_value: np.ndarray """ global device, normalize x = camera_value ...
29d9ebe362172be617f609d2707daaee4abdaf69
3,608,468
def number_of_pending_jobs(): """Return the number of jobs in the slurm queue.""" cmd = ["squeue", "-u", "lstanalyzer", "-h", "-t", "pending", "-r"] output = sp.check_output(cmd) return output.count(b"\n")
054e77f553746f37d02eeeb8ed05771b263f5bb6
3,608,469
import sys def object_size(x): """Estimate the size of a reasonable python object. Parameters ---------- x : object Object to approximate the size of. Can be anything comprised of nested versions of: {dict, list, tuple, ndarray, str, bytes, float, int, None}. Returns ...
ed224cf576d464a3dc0027bd6f5fada0bd18dc07
3,608,470
import os def create_and_write_stitching_config_from_raw(raw_video_dir, stitched_dir, settings_yaml): """Create a complete stitching configuration from a raw video directory. Creates a stitching config and writes to an xml file Args: raw_video_dir: directory path containing raw video (.mp4) file...
f354a41058e9b5431529ae5233d99ea356b99f23
3,608,471
import subprocess import sys def run_command(command_to_run, _cwd=None, _exit_on_fail=False, _output_file=None): """ Runs the command. Args: command_to_run ([string]): Command to run along with arguments. _cwd (string): Current working directory. _exit_on_fail (bool): If it should exi...
b2daba8e26dd60177c8175e4a068ac978f9ce4f3
3,608,472
def copy_weights(model, source, target, num_layers, shared=False): """Copies the weight values of mixture weights and head from source to target domain. Arguments: model: a tf.keras.Model object. source: source domain name. target: target domain name. shared: whether the model is shared. num_layers: nu...
227ea9a45a3c9af2086ded56ce5f9a6c6780d2c9
3,608,473
def load_csv(file_name): """ Load a csv-file generated by Audio2LED. PARAMETER --------- file_name: str the path to the csv file RETURNS ------- led_time: ndarray the time in seconds from the start led_channel_levels: ndarray 2D array for the LED channels and fra...
f7985d6c00f7bdb8d381dcfe468f4b9e4bd39aa9
3,608,474
import hashlib import logging def hash_available(hash_method: str, fail_on_deprecated: bool = True) -> bool: """Checks if the supplied hashing algorithm is available. If fail_on_deprecated is set to True (default) it will raise an exception if the method is deprecated (md5 and sha...
f8ae7183dfc32f06eb8f3ace51c32fe108aa4133
3,608,475
def error_in_assigned_energy(predictions, ground_truth): """Compute error in assigned energy. .. math:: error^{(n)} = \\left | \\sum_t y^{(n)}_t - \\sum_t \\hat{y}^{(n)}_t \\right | Parameters ---------- predictions, ground_truth : nilmtk.MeterGroup Returns ------- er...
92891991241bfbd5d583b11e8583ac59204b4af0
3,608,476
import subprocess def bash4(text): """ Deprecated: use sh lib instead But it doesn't work on eclipse, use instead a python command line """ # text = ['/bin/bash', '-c'] + text.split(" ") text = text.split(" ") pipe = subprocess.Popen(text, stdin=subprocess.PIPE, stdout=subprocess.P...
14024bf5d1f353ab58fcd06b7c0c145aa6bf47b5
3,608,477
import torch from typing import Tuple def get_tot_objf_and_finite_mask(tot_scores: torch.Tensor, reduction: str) -> Tuple[torch.Tensor, torch.Tensor]: """Figures out the total score(log-prob) over all successful supervision segments (i.e. those for which the total score wasn't -infinity). Args: ...
d09b95056c2635be22a7db1baaa64b6667955007
3,608,478
def dct2d(a): """ Computes the 2D Normalized DCT-II. Arguments --------- X: (m, n) numpy array 2D image. Returns ------- (m, n) numpy array DCT coefficient matrix. """ return fp.dctn(a, norm='ortho')
c16c04687b060485e1a4314daae8972da86cd40f
3,608,479
def generate_embedding_mat(dict_size, emb_len, init_mat=None, extra_symbol=None, scope=None, reuse=None, trainable=False): """ generate embedding matrix for looking up :param dict_size: indices 0 and 1 corresponding to empty and unknown token :param emb_len: :param init_mat: init mat matching for [di...
c29efb8be60cb1153aa80774abf0283cd0304526
3,608,480
def user_settings(request): """ Let a user change its settings, like email preferences. :param request: :return: """ try: meta = request.user.usermeta except UserMeta.DoesNotExist: meta = UserMeta() request.user.usermeta = meta meta.save() request.use...
0233c57baf6e07d46a0214964746fb6e38b2e641
3,608,481
import os def build_matrix(path_screen, fmol, list_models): """ Builds a binary matrix. Columns are model names, indexes are id compounds :param path_screen: path to files with screening results :param fmol: .smi file with active and inactive compounds used to create the database for virtual screening...
b475b3e404c5f65e78c89b3a2d72f7aa66dd5d18
3,608,482
import graphviz # noqa: F401 def render_graph(graph_specification, render_distributions=False): """ Create a graphviz object given a graph specification. :param bool render_distributions: Show distribution of each RV in plot. """ try: except ImportError as e: raise ImportError( ...
8fd01c67423e7303e11cac613e8265e75c7cc1c2
3,608,483
import dateutil from operator import sub def donationParser(inLoc, header=True): """Takes a donation csv formatted from twitch alerts. Returns a list of lists for each entry. 0-Date (datetime object) 1-Name 2-Email 3-Amount (Decimal type) 4-Comment """ donations=[] file =open(inLoc...
59f318c4570b0ebf06102bc99b4dc37889847a75
3,608,484
def VaporPressure(tempc, phase="liquid"): """Water vapor pressure over liquid water or ice. INPUTS: tempc: (C) OR dwpt (C), if SATURATION vapour pressure is desired. phase: ['liquid'],'ice'. If 'liquid', do simple dew point. If 'ice', return saturation vapour pressure as follows: Tc>=0: es = ...
058caabe6db9c6506daa6e1fa0071c3903a2ca9a
3,608,485
def fft_detect(resultImage, hostImage, alpha): """Starting from a watermarked image, detects the watermark image embedded into the host image by using the Fast Fourier Transform.\n Arguments: resultImage (NumPy array) -- the watermarked image hostImage (NumPy array) -- the original im...
9a45d7bf0af3278071d71bda79e005ab834bc9d9
3,608,486
def get_auth_twitter() -> tweepy.OAuthHandler: """auth twitter with saved tokens. Returns: tweepy.OAuthHandler: """ return tweepy.OAuthHandler(SETTINGS['TWITTER_API_KEY'], SETTINGS['TWITTER_API_SECRET_KEY'])
2e9911a3d6f3aaf9e08a33ca7e4caff592494b01
3,608,487
def post_statistics(): """ get the data of posts """ post_statistic = dict() post_statistic['total_posts'] = len(Post.query.filter_by(post_type='post').all()) post_statistic['total_comments'] = len(Comment.query.filter_by(user_id=0).all()) post_statistic['total_pages'] = len(Post.query.filter_by(pos...
a2c125b725c5361739a6f05957a92918e6ba2911
3,608,488
import pandas def get_variant_ann_by_chrom_pos(db, chrom, start, ref, alt): """ e.g., UI: https://biobankengine.stanford.edu/variant/1-39381448 MongoDB: db.variants.find({'xpos': '1039381448'}, fields={'_id': False}) SciDB: between(vairant, 1, 39381448, 1...
19397af50d0c0ea2b871069959066c8b7e20aa83
3,608,489
def get_answers(candidate_tokens,predict_set,predict_result,dictionary): """ Build the dictionary of the selected answer for a QA-based network. :param candidate_tokens: the dictionary of the documents and their candidate KPs :param predict_set: the input of the network :param predict_result: the o...
3a6e82c34bb398c9ede673ad2e9a3c6fb672a8f3
3,608,490
def rolling_regression(returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6, nan_threshold=0.1): """ Computes rolling factor betas using a multivariate linear regression (separate linear regressions is problematic because the factors may be con...
571884d26ed16314ee996503c6ee34ca320d5357
3,608,491
def get_df_stats(df, options, num_bins=None): """get per column data stats from dataframe""" results_dict = {} num_bins = num_bins or default_num_bins if InferOptions.get_common_options(options, InferOptions.Index) and df.index.name: df = df.reset_index() for col, values in df.describe( ...
dba058b75fc880c390e310e4eedc9aaa43165d02
3,608,492
import six import os import sys def factorise(custom_settings=None): """ Return a dict of settings for Django, acquired from the environment. This is done in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ ...
d043753c5a7e73e4c6356c4b3a47989bde7fa22f
3,608,493
def find_star_info(line, column): """ For a given .STAR file line entry, extract the data at the given column index. If the column does not exist (e.g. for a header line read in), return 'False' """ # break an input line into a list data type for column-by-column indexing line_to_list = line.spl...
f1f9001710e45912cd23a8fe9f4dc2d139ef4295
3,608,494
def as_dimension(value): """Converts the given value to a Dimension. A Dimension input will be returned unmodified. An input of `None` will be converted to an unknown Dimension. An integer input will be converted to a Dimension with that value. Args: value: The value to be converted. Returns: A D...
53132111353ab7570231be9ce13ef0d92696ba9e
3,608,495
import sys def run(args:list) -> int: """ Main script """ hashes = hashes_there() fname = args[0] if args else ".gitmodules" if len(args) > 1: return -1 git_modules_fname = fname within = "git submodule add " news, astr, _ = dump_subs(hashes, """ ## Log history Original [github](h...
3305aeef850924486d6a8363b9de5a0ac1f9904b
3,608,496
def absolute_value(signal): """ Parameters ---------- signal np.ndarray a NxM numpy ndarray Returns ------- the absolute values of the input signal """ return np.abs(signal)
59660bc2b345790b14dbf7792bb6f94e45fe3ac9
3,608,497
def PolyExpansion(n_range, s): """Polynomial expansion """ basis = [s**n_range] return basis
fc76a3b3c76f7f5e12673b9e19a9ca35c3a3853c
3,608,498
def remove_ticket(request, prize_id): """Removes a user's raffle ticket from the prize.""" if request.method == "POST": prize = get_object_or_404(RafflePrize, id=prize_id) if prize.allocated_tickets(request.user) > 0: prize.remove_ticket(request.user) return HttpResponseR...
308e94c79c577d2d33cdcadeb124ac5b0e57b520
3,608,499