content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _parallel_init(eval_func, iterable, metab_index,base_biomass,model,weight_fraction): """ This function runs the evaluation function in parallel with 3 arguments. It is used twice: first to get the metabolite that the model can produce, second to verify the solvability of the generated individuals (m...
a68c1023235ee41e782a816f49db21f9069f749e
3,595,685
def ipv4_addr_to_reverse(addr): """ Returns the string in reverse, dot as delemiter 1.2.3.4 returns 4.3.2.1 """ ip = addr.split(".") return ".".join(reversed(ip))
f471e5181082e27018a3239614f7b7ec4f6719a4
3,595,686
def cx_gate_unitary_deterministic(): """CX-gate circuits reference unitaries.""" targets = [] # CX01, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # CX10, |00> stat...
9ab07f5a08b9a8b407087f823faf49982158d6c4
3,595,687
def docopt_cmd(func): """Pass the arguments from docopt to the commands""" def fn(self, arg): try: opt = docopt(fn.__doc__, arg) except DocoptExit as e: # The DocoptExit is thrown when the args do not match. # We print a message to the user and the usage blo...
9f3781dba7c100a79a2a528b66e4e3b5e7ef634e
3,595,689
def get_dim_coord_names(cube): """ Returns an ordered list of dimension coordinate names on the cube Args: cube (iris.cube.Cube) Returns: list of str """ return [coord.name() for coord in cube.coords(dim_coords=True)]
ec742b197f02d13e067a250685438f0ed88615e5
3,595,691
def getISSNsXML(issn, base=ALEPH_DEFAULT_BASE): """ Download full XML record for given `issn` in `base`. Args: issn (str): ISSN of the books you want to get. base (str): Base on which will be search performed. Default :attr:`aleph.settings.ALEPH_DEFAULT_BASE`. Retur...
f3921d4ce322e0df0af70cd2b6cc7223d2d52b2d
3,595,692
import yaml def read_yaml(filename, logger=None): """ Read YAML file Parameters ---------- filename : `~gammapy.extern.pathlib.Path`, str File to read """ filename = make_path(filename) if logger is not None: logger.info("Reading {}".format(filename)) with open(st...
96fde1e786c6f2209b525ed38af68a4a16a093d8
3,595,693
def formaldehyde(xarr, amp=1.0, xoff_v=0.0, width=1.0, return_hyperfine_components=False, texscale=0.01, tau=0.01, **kwargs): """ Generate a model Formaldehyde spectrum based on simple gaussian parameters the "amplitude" is an essentially arbitrary parameter; we therefore define it to be Tex gi...
71e6ff9773468d316abaca4eaad944b6ca58dbbd
3,595,694
from datetime import datetime from typing import Callable def load_date_range( start_date: datetime.date, end_date: datetime.date, df_from_date: Callable, verbose: bool = False, aggregate_fun: Callable = pd.concat, ) -> pd.DataFrame: """ Take a range of dates and a callable that gives one ...
7a5e9a00e0fec46b4c6cf28a6355dbd331ef611d
3,595,695
import inspect def getargspec(func): """ Used because getargspec for python 2.7 does not accept functools.partial which is the type for pytest fixtures. getargspec excerpted from: sphinx.util.inspect ~~~~~~~~~~~~~~~~~~~ Helpers for inspecting Python modules. :copyright: Copyright 200...
59528b4203bf5c2d43bab4555c273f9e3d236349
3,595,696
def _noisepeak(amp, npk1): """ Private function intended to insert a new RR interval in the buffer. ---------- Parameters ---------- amp : int Amplitude of the peak under analysis. npk1 : int Actual value of NPK1 parameter defined in Pan-Tompkins real-time R peak detection a...
76d2fef2a78b0af4c6478d3f520784d427991e06
3,595,698
def search(query, restaurants): """Return each restaurant in restaurants that has query as a category. Arguments: query -- A string restaurants -- A sequence of restaurants """ # BEGIN Question 10 return [rest for rest in restaurants if query in restaurant_categories(rest)] # END Questi...
b62f2731caaa9a372d9584e2cb874db1ed6f10b1
3,595,699
def _validate_fields(receive:dict, model:dict, response:dict) -> dict: """ This method valid the fields of json receive through of model json passed, beyond of pass the receive json and model json, it receives a custom json response. :param receive: get the json that comes from outside :param model:...
f184e02619908bc30a2f89947b56558d3f400a6f
3,595,700
def check_output(name, arg=None, shape=None, quat=False, dtype=np.double, inplace=True, fill=None, allow_transpose=True, allow_tuple=True, **kwargs): """ Ensure that the output argument is properly aligned/shaped/typed. Check input kwargs to see if a pointer to the output a...
99277391d41d6d0d7d4db9e0d50371d65141b767
3,595,702
def atan(*args): """ atan(float x) -> float atan(IM x) -> IM atan(DM x) -> DM atan(SX x) -> SX atan(MX x) -> MX """ return _casadi.atan(*args)
ab8f788ca686cf8c97d929616d163bfb0cfc1211
3,595,703
def get_center_of_mass(centers_of_mass, masses): """Determine the center of mass of a set of objects Args centers_of_mass [*shape, num_objects, 2] masses [*shape, num_objects] Returns [*shape, 2] """ return (centers_of_mass * masses[..., None]).sum(-2) / masses.sum(-1)[..., None]
22c95024120579ed8471f093ddedd9da75b4ed0f
3,595,704
def compare_ground_truth(disparity_map, folder): """ """ print('Comparing to ground truth') ground_truth = cv.imread(f'{folder}disp0.pfm',-1) ground_truth[ground_truth==np.inf] = 0 ground_truth = ground_truth / 256 diff = np.abs(disparity_map - ground_truth) total_pixels = disparity_map.sh...
39c199aa8d54207639b86453872160d157d25d84
3,595,705
def example_pm_data(): """Example data returnd by `threshold.run_many`.""" data = pd.DataFrame.from_dict( { "p_bitflip": { 0: 0.09, 1: 0.095, 2: 0.1, 3: 0.105, 4: 0.11, 5: 0.09, 6:...
242b78c400f876a5fc2075030e0ac802c9170eb1
3,595,706
def is_pos_def(f, x): """ f: multivariable function with 1 array as parameter x : a vector where to verify if f is definite positive """ m = nd.Hessian(f)(x) return np.all(np.linalg.eigvals(m) > 0)
235204632fc6f3c95d52a05130c264bcec2ef683
3,595,707
def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }): """expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call """ if isinstance(path_cfg, str): ...
d6e325bf984fbde82f1b436d5f5665be629ff1ab
3,595,708
def is_hypernode_vagrant_directory(directory): """ Check if a directory contains a hypernode-vagrant checkout :param str directory: The directory to check :return bool contains_vagrant: Whether or not the Vagrantfile is present """ expected_vagrant_file = join(directory, 'Vagrantfile') retur...
fa604d791c8a68e4e3e2c23bcf511bf3838c4482
3,595,709
import torch def evaluate_noisy_label_7(data, model1, model2, class_no, low_rank): """ Args: data: model1: model2: class_no: low_rank: Returns: """ model1.eval() model2.eval() # test_dice = 0 test_dice_all = [] # for i, (v_images, ...
39801f184b26c8b953e7e23d8478ddb721099e3c
3,595,710
def get_resname(traj_frag_molid, frame_idx, index): """ Parse atom label and return element Parameters ---------- traj_frag_molid: int Denotes trajectory id in VMD frame_idx: int Frame of simulation in trajectory fragment index: string VMD atom index Returns ...
18b3b1960e1dd1240792ef245bef10749364d694
3,595,711
import torch def initialize_model_from_cfg(args, roidb=None, gpu_id=0): """Initialize a model from the global cfg. Loads test-time weights and set to evaluation mode. """ model = model_builder.Generalized_RCNN() model.eval() cfg.immutable(False) cfg.TEST.CLASS_SPLIT = {'source': roidb[0][...
d55b19e3474149b22b5c8131bcfee2309dfe4421
3,595,712
def unbake(image_file): """ Return the openbadges content contained in a baked image. """ image_type = check_image_type(image_file) image_file.seek(0) if image_type == 'PNG': return png_bakery.unbake(image_file) elif image_type == 'SVG': return svg_bakery.unbake(image_file)
57bd467d4e9aaee334ad6660ee0e97dbe0b60679
3,595,713
def printPath(path): """Assumes path is a list of nodes""" result = '' for i in range(len(path)): result += str(path[i]) if i != len(path) - 1: result += '->' return result
1974c31df44e89a69f8e59d3f81288fb054ae9e5
3,595,714
import copy def start_board(solution_board): """Generates an empty board from a solution board""" empty_board = copy.deepcopy(solution_board) for row in empty_board: for index in range(len(row)): row[index] = '-' return empty_board
fafa73da5867bf7ae324a0531c64c16ae5789f0d
3,595,716
def _get_request_nfo(): """ grab client info for logging, etc.. getting this information might depend on the stack, This function is designed for nginx """ return RequestInfo(ip = request.environ.get('REMOTE_ADDR', request.remote_addr), port = request.environ.get('REMO...
76672ce004b3d99f2da543d22e50d50f1940d990
3,595,717
def parse_parameters(options): """Given a dict that has configuration keys mapped to values, - If a value begins with '^', redirect to fetch the value from the secret key stored in the keyring. The keyring service name is always just an underscore (so keys must be unique in the who...
87c6818d663ba02a5dc358cc643c7a6dad5d5f78
3,595,718
def ProcessInstanceTypeAndNodes(args, instance_type): """Ensure that --instance-type and --num-nodes are consistent. If --instance-type is DEVELOPMENT, then no --cluster-num-nodes can be specified. If --instance-type is PRODUCTION, then --cluster-num-nodes must be at least 3 if specified and defaults to 3 if n...
c7e61fffe8223b9823c04305e94da68cd7ebccf0
3,595,719
def _float64_feature(value): """Wrapper for inserting float64 features into Example proto.""" if isinstance(value, np.ndarray): value = value.flatten().tolist() elif not isinstance(value, list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
3e1415911957cd62b162485c139370ad0d41a38d
3,595,720
import json def serialize_geometry(geometry): """Take a shapely.geometry.polygon.Polygon and represent it as a string of tuples (x, y) :param geometry: a polygon or polyline to extract the points from and represent as a json object :type geometry: shapely.geometry.polygon.Polygon """ if isinstanc...
638d262fdf413eec3fb19633f4e0916f06d46225
3,595,721
import inspect def get_available_holiday_lookup_countries(countries=None): """Returns list of available countries for modeling holidays :param countries: List[str] only look for available countries in this set :return: List[str] list of available countries for modeling holidays """ ...
899a31317fef1d56137d8adcf7d0a5c62444cc3b
3,595,722
def safe_get(list, index, fallback_value): """Similar to dict's .get(key, fallback) function but for lists. Returns a fallback/default value if the index is not valid for the list, otherwise returns the value at that index. Args: list (_type_): a list-like object index (_type_): an index into th...
bf799f45a04335adc7673aff155b301333ff8e26
3,595,723
def textFile(filename): """textFile("output.txt") Create a text file using the java.io.PrintWriter class for writing to an UTF-8 file.""" return jio.PrintWriter(filename, "UTF-8")
f74f59614a12dcc55205becad92a71726a0b0356
3,595,724
def db_setup(HOST: str, USER: str, dbname: str, PASSW: str, PORT: str, keep: bool): """sets up database :param HOST: OGM Graph ref :param USER: OGM Graph ref :param dbname: OGM Graph ref :param PASSW: OGM Graph ref :param PORT: OGM Graph ref :param keep: boolean value to keep or destroy data...
1959e28093e1fe14513afcdb85516c029554a582
3,595,726
def load_json_config(dut, convert_json, config_file): """ To load buffer configuration Author: Jagadish Ch (jagadish.chatrasi@broadcom.com) :param dut: :param convert_json: :param :config_file: :return: """ st.config(dut, convert_json) load_json = "config load {} -y".format(confi...
02b4be4c0754b9a62e4419a12bd91b4fd2fc8cb2
3,595,728
def charac_function_fs(old_fs, new_fs, charac_func): """ Convert the scale of a characteristic function from spec time scale to another time scale with the desired sampling rate Parameters ---------- old_fs: int Sampling frequency in Hz on which charac_func is derived. ...
b1c48b49b3a68216dfd34cb59d70abae757478c7
3,595,729
def clusters_to_labels(clusters): """ :param clusters: List of lists, each sublist contains doc ids in that cluster :return labels: Dict of [doc_id, cluster_label] where cluster_label are assigned from positive ints starting at 1 """ labels = dict() for label, cluster in enumerate(clusters): ...
4a443b729965d4632dc3ff68cb0828bcc2f4f2ff
3,595,730
def s3_get_bucket( bucket, profile_name='default', region_name='us-west-2'): """ Creates and returns a boto3 bucket object Parameters ---------- bucket : str name of S3 bucket profile_name: str profile name for credentials (default 'default' or organization-s...
fb8ae975abc3b153851c93d0862e459f841651ff
3,595,731
def new_edges(x_tr, mask_tr, x_te, mask_te, percentile, metric, weight_missingness): """ Inputs: old dataset old dataset mask of the corruption new dataset new dataset mask of the corruption percentile of connections to keep boolean, weight or not the missing elem...
fd43212ab2d2ca6cf7789cda93c84e3dfd4e3dea
3,595,732
import logging def _make_new(request, form): """Creates new issue and fill relevant fields from given form data. Sends notification about created issue (if requested with send_mail param). Returns (Issue, PatchSet) or (None, None). """ if not form.is_valid(): return (None, None) account = models.Acc...
2f861a0f4b950725ce53b23ef5c5df09d3321bac
3,595,733
import time def execute_in_hammer_mode(func): """ A decorator for automation of reconnecting. """ n_trials = 3 sleep_time = 1 sleep_factor = 1 def wrapper(*args, **kwargs): for i in range(n_trials): try: return func(*args, **kwargs) except E...
dbbbc1031181ed49587914299ba412ef40b15417
3,595,734
def get_cap_override_dict(model_name, fixed_caps): """Create an override dictionary that can be used to set fixed fixed capacities in a Calliope model run. Parameters: ----------- model_name (str) : '1_region' or '6_region' fixed_caps (pandas Series/DataFrame or dict) : the fixed capacities. ...
a068db9fe4a131a7f3803de5d7e3af952bff88d7
3,595,736
def get_network_address_from_raw_address(raw_address: str) -> str: """ Return network address from raw_address. >>> get_network_address_from_raw_address("192.168.1.15/24") '192.168.1.0' >>> get_network_address_from_raw_address("91.124.230.205/30") '91.124.230.204' """ ip_address = get_...
4b8197a22c9ccf5f3b3db7582c79c99fc1600085
3,595,737
def SmoothGaussian(tab, axis=0, window=5): """ ################################################################################# Description: Smooth 'tab' along 'axis' using gaussian moving window average ################################################################################# :param t...
4aa3c75394b5d66873a19f055ea362137ceb27b2
3,595,738
def binarySearch(arr, x): """Returns the lowest index of the element equal to `x` or NaN if not found.""" if len(arr) == 0: return 0 m = len(arr) // 2 if arr[m] < x: return m + 1 + binarySearch(arr[m + 1:], x) elif x < arr[m] or (0 < m and arr[m - 1] == x): return binarySearc...
4b2511f5e74c25c7f027281a16be703ec352fe19
3,595,739
def _set_duration(waveform): """Set duration of ecg waveform.""" if len(waveform) > LENGTH: return waveform[0:LENGTH] else: return waveform
1de715dea2ff37b313f7048e41ac83d631c3609b
3,595,740
def AskDiskList(disk_list): """Asks the user to select which disks to copy. Args: disk_list(list(DiskArtifact)): list of disks. Returns: list(DiskArtifact): a list of devices. """ valid_choice = False disk_indices_to_copy = [ i for i, disk in enumerate(disk_list) if disk.ProbablyADisk()] w...
f52ce80f21a9a8f7f950824ba45613d274fd8fe8
3,595,741
def get_leakage_feature(dataset: DataFrame): """ Leakage 特征群,就是会出现信息泄露的特征 :param dataset: :return: """ t = dataset[['user_id']].copy() t['this_month_user_receive_all_coupon_count'] = 1 t = t.groupby('user_id').agg('sum').reset_index() t1 = dataset[['user_id', 'coupon_id']].copy() ...
b70ecaadfb42b9f7a536bc2877bba1e062a186b6
3,595,743
def get_image_browse_urls(user=None): """ Recursively walks all dirs under upload dir and generates a list of thumbnail and full image URL's for each file found. """ images = [] for filename in get_image_files(user=user): images.append({ 'thumb': get_media_url(get_thumb_filen...
ff6df5f70505513a0e6b6983753c28c1c70a8770
3,595,744
import json def get_sentinelhub_config(config_file: str) -> SHConfig: """Loads sentinel hub config from file and returns it""" config = SHConfig() with open(config_file, "r") as f: config_vals = json.load(f) config.instance_id = config_vals["instance_id"] config.sh_client_id = config_val...
a5c8a5be6db26f60b4c8eed8284d7a09897766b9
3,595,745
def to_bytes(value, encoding='utf8'): """ cast string to bytes() like object, but for python2 support it's bytearray copy """ if isinstance(value, bytes): return value if isinstance(value, str): return value.encode(encoding) elif isinstance(value, bytearray): return bytes...
6c42f9787c485ab7043665f806a9e6c728b5835a
3,595,746
def is_valid(number): """Check if the number is a valid IRD number.""" try: return bool(validate(number)) except ValidationError: return False
e2f894dce35b09cd2f9221974c8878c48821db52
3,595,747
import copy def TimeCompressor(renderer: Renderer, pattern: str, **kwargs) -> str: """ Multiline Time Compressor Args: x (float): position of the time compressor ymin (float): top limit of the time compressor ymax (float): bottom limit of the time compressor """ ans = "" ...
1fed45c04667a277db615e21ecf408b716e4d68c
3,595,748
def readCameraConfig(config): """Read single camera configuration.""" cam = CameraConfig() # name try: cam.name = config["name"] except KeyError: parseError("could not read camera name") return False # path try: cam.path = config["path"] except KeyError:...
fbe335ff3e516d9ae23529d84d9ba1bd9cbfcafd
3,595,750
import ftplib def connectToFTP(host, usern, passw,verb): """ Creates an FTP Connection with the given details using FTPLib. :param host: Hostname (e.g. IP address) of the connection :param usern: Username to login with :param passw: password :param verb: print errors or not. :return: FTP ...
f6c4dabedbc400204d85cf699a7c592b38704d7d
3,595,751
def tanh(node) -> Node: """tanh of the node, using np.tanh(x)""" return Node(node, None, np.tanh(node.value), 'tanh' )
a796ec86e81e41fc0cc0785c26d0f185d95d144b
3,595,752
def get_custom_targeting_by_key_name(key_name): """ Gets a set of custom targeting values by key name Args: name (str): the name of the targeting key Returns: an array, or None: if the key exists, return an array of objects, where each object is info about a custom targeting value """ key_id...
cf0d22b7ecb65bf0a1db4c5dbe2b161bfec42f74
3,595,753
import ctypes import warnings def decon_singleview(im, psf, psf_bp=None, iters=10, device_num=0, gpu_mem_mode=0): """3D Richardson-Lucy deconvolution with GPU implementation. Compatible with unmatched back projector. Args: im (np.ndarray): input image psf (np.ndarray): forward projector (...
6b9203139815d715803f6632c5cad7c4ed67a060
3,595,754
from typing import Union def smooth(df: DFSeries_t, days: Union[int, float], idx=None) -> DFSeries_t: """Time series has 3 hour resolution""" if idx: return df.loc[idx].rolling(int(8 * days)).mean() else: return df.rolling(int(8 * days)).mean()
0fba16b904261cdf2017dd47225ca562db8dff5a
3,595,755
async def eval_invitation_progress(request: AthenianWebRequest, id: int) -> web.Response: """Return the current Athenian GitHub app installation progress.""" await get_user_account_status(request.uid, id, request.sdb, request.cache) async with request.mdb.connection() as mdb_conn: model = await fetc...
9dbfe41422ad71ecb54e99c0290f8f8c82497a55
3,595,757
def lark_to_null_value_node(tree: "Tree") -> "NullValueNode": """ Creates and returns a NullValueNode instance extracted from the parsing of the tree instance. :param tree: the Tree to parse in order to extract the proper node :type tree: Tree :return: a NullValueNode instance extracted from the...
3c37ca30dc505195b1e645174b3565bc1016c700
3,595,758
def docs(src='index.html'): """ provides access to documentation Returns: (html): documentation """ return render_template(src)
e5225d964e3a6e962968b806de3099e7f8304d98
3,595,759
import ipdb def keypoints_to_heatmap(keypoints, rois, heatmap_size): """ input: keypoint的维度为[person_num, 17, 3], "3"代表(x, y, visibility) rois的维度为[person_num, 4], "4"代表(x1, y1, x2, y2) heatmap_size的大小等于cfg.MODEL.ROI_KEYPOINT_HEAD.RESOLUTION, 配置文件中为56 output: heatmaps的维度为[per...
923a7fafa97b514ca9392bafc00256698f41f2e7
3,595,760
import struct def parse_moving_and_target(args, opt): """Parse a loss that involves a moving and a target file""" if args and not next_istag(args): opt.factor, *args = args opt.factor = float(opt.factor) while args: if not next_istag(args): break tag, *args = ...
1b812b13429f599980e58bb6f6deea6ebcd748c3
3,595,761
import yaml import json def render_yaml(value): """ Render a dictionary as formatted YAML. This filter is invoked as "yaml": {{ data_dict|yaml }} """ return yaml.dump(json.loads(json.dumps(value)))
dc90315ebc6271eec12531095214ecc24d0df9e8
3,595,762
def reverseInParentheses(inputString): """ >>> reverseInParentheses("(rab)") 'bar' >>> reverseInParentheses("foo(bar)baz(blim)") 'foorabbazmilb' >>> reverseInParentheses("foo(bar(baz))blim") 'foobazrabblim' """ return recursive_reverse(inputString, 0)[0]
c14e851d52d2c225b7f7aea5e24f9fb16e41db4f
3,595,763
def require_password(func): """Requires a password. If there is no password, the missing password notification item will be displayed in Alfred. When an user selects this item, he will be prompted to enter a new password. So it is necessary to send the arg with settings.KEEPASSXC_MASTER_PASSWORD.na...
2018efda172b798a2d6a47ddf7375b39c09170dd
3,595,764
import json def getFileList(): """ Query MVI server for the list of files matching the given query.""" files = server.files.report(args.dsid, query=args.queryString) if not server.rsp_ok(): print(f"Error: Got status code {server.status_code()} from file lookup. Reason = {json.dumps(server.json(), ...
649523fd11280cc759d83fd34d5547510423fb91
3,595,765
def dipole_moment(output_string): """ Reads the dipole moment """ pattern = app.padded( (app.LINESPACES.join([ app.escape('Dipole moment [Debye]:'), app.FLOAT])) + app.NEWLINE + app.padded('x=') + app.capturing(app.FLOAT) + app.padded('y=') + app.capturing(app...
4ee8d0d28612333fdf10c9306b091ae110f82486
3,595,766
def check_perl_version(conf, minver=None): """ Checks if perl is installed. If installed the variable PERL will be set in environment. Perl binary can be overridden by --with-perl-binary config variable """ res = True if not getattr(Options.options, 'perlbinary', None): perl = conf.find_program("perl", var...
717a9ff8a83a48adc1def348594c57a083ad0103
3,595,767
def get_or_create_template(template_dir, key, value, sequence, template_name): """ Search a sequence of dicts where a given key matches value. If found, then it returns that item. If not, then it loads the template identified by template_name, adds it ot the sequence, and returns the template ...
3e65cff493906f4787031cb5519bc25b5b00c072
3,595,768
def get_connection_str(db='db', setup_file='setup.cfg'): """ Get database connection string from configuration variables. """ config = ConfigParser.ConfigParser() config.read(setup_file) connection_str = config.get(db, 'connection_string') return connection_str
b647a90ba2054a1c4d933c9c680683f14d10ebd0
3,595,769
def get_pages_and_resources_url(course_locator): """ Gets course authoring microfrontend URL for Pages and Resources view. """ pages_and_resources_url = None if ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND.is_enabled(course_locator): mfe_base_url = get_course_authoring_url(course_locator) ...
13d8213ba1acdfd9ed1e6021e906cb76e85807b0
3,595,770
def get_gene(identifier): """ return gene for identifier """ genes = None for store in [GENES, ALIASES]: genes = store.get(identifier, None) if genes and len(genes) == 1: return genes[0] if genes is None: raise ValueError( "gene reference does not exist: '...
10b6a2a433703f2cb4305dc91d57f5909ba94ac6
3,595,771
def cluster_matrix(matrix, labels, dpi, by_cols, algorithm): """ From a matrix, generate a distance matrix & perform hierarchical clustering :param matrix: a numpy matrix of scores :param labels: the ids for all row elements or column elements :param dpi: the resolution to save the diagram at :...
7495b28f637492f1011230f5c36c5d5e13b9bf25
3,595,772
def infer_type(x): """Infer type of the input `x`. Parameters: ---------- x: tf.Tensor, tf.Variable, Scipy sparse matrix, Numpy array-like, etc. Returns: ---------- dtype: string, the converted type of `x`: 1. `graphgallery.floatx()` if `x` is floating 2. `graphgal...
6c36209c8b8a9e1c00bdd9c4695b2676befbf554
3,595,773
async def async_setup(hass, config): """Set up the Orange Pi GPIO component.""" def cleanup_gpio(event): """Stuff to do before stopping.""" GPIO.cleanup() def prepare_gpio(event): """Stuff to do when Home Assistant starts.""" hass.bus.async_listen_once(EVENT_HOMEASSISTANT_S...
9d025769d6aeb5c2d3647e43489aed158e92850a
3,595,774
def generate_images(x_norm, x_diff_encoded, directional_feature, temporal_feature, scale, stroke_width): """Generates image array from strokes. Args: x_norm: [(x', y', t), ...] Normalized points. x_diff_encoded: [(dx, dy, dt, pendown), ...] Normalized diffs. directional_feature (boolean): True when...
5b5162c1790336fe31fea8f63fc1b17886913852
3,595,775
def variance_unbiased(x): """x is a list of numbers""" xbar = mean(x) return sum([(i-xbar)**2 for i in x])/float(len(x)-1)
5ceac3ef556d61595d95ff84a32fce5ad7096bf1
3,595,776
def getHosts(args): """ Reads CSV file in """ if args.file: with open(args.file) as f: return f.read().splitlines() return args.list.split(',')
20e2150a5ac294671a7ad8cf1c47fd1b205d0de7
3,595,778
from typing import List def get_previous_instructions(vw: VivWorkspace, va: int) -> List[int]: """ collect the instructions that flow to the given address, local to the current function. args: vw (vivisect.Workspace) va (int): the virtual address to inspect returns: List[int]: the ...
fc5170081b5032745fe5ffa968c30fb9dc5afe16
3,595,779
import datasets def get_template(space="mni152_2mm", mask=None): """ Load template file. Parameters ---------- space : {'mni152_1mm', 'mni152_2mm', 'ale_2mm'}, optional Template to load. Default is 'mni152_1mm'. mask : {None, 'brain', 'gm'}, optional Whether to return the raw ...
40d723f6af4ab903ad39607f542aefb09d9e0553
3,595,780
def collate(batch): """ Generates tokenized batches """ source = [samp["question"] + " " + samp["document"] for samp in batch] target = [samp["target"] for samp in batch] tokenized_input = tokenizer.prepare_seq2seq_batch(source, target, max_length=512, ...
bb6225fb9078bed3e54d0de68cf1a63705698434
3,595,781
def call_instance_method(instance, name, args, kwargs): """indirect caller for instance methods for multiprocessing Args: instance: the instance to call method with name (str): method name to call args (tuple or None): arguments to be passed to getattr(instance, name) kwargs (di...
30831cafeab2a4f3310a21c41a03e8d3ec9a43ec
3,595,782
import numpy def fdstencil(z, x, nderiv=None): """Compute finite difference weights using recurrences for Lagrange polynomials (see Fornberg 1998)""" if nderiv is None: nderiv = len(x) x = numpy.array(x) - z k = numpy.arange(nderiv+1) c = numpy.outer(0.*k, x) c[0,0] = 1 prod = 1 ...
1e350dfefb15fc82596164d23909b027d9e14b3e
3,595,783
import math def read_rules(grammar_filename): """Read PCFG grammar rules from grammar file The grammar file is a tab-separated file of three columns: probability, left-hand-side, right-hand-side. probability is a float number between 0 and 1. left-hand-side is a string token for a non-terminal sy...
a5c489fb3f220c1f702f8e1284f1837001967a4b
3,595,784
import csv def calc_stats( arr, removes=(np.nan, np.inf, -np.inf), val_interval=None, save_path=None, title=None, compact=False): """ Calculate array statistical information (min, max, avg, std, sum, num). Args: arr (np.ndarray): The array to be inv...
7d30887fb7cba99de792b35295d4e7c2622caf5c
3,595,785
def refine(splits, sigma, n=1): """ Given some splits, refine them a step """ oldsplits = splits[:] counter = 0 n = n or np.inf while counter < n: splits = [0]+splits n = len(splits) - 2 new = [splits[0]] for i in range(n): out = bestsplit(splits[i], spli...
0c50bcccb29d35c944aa4d7e6f96398ef7513221
3,595,786
from typing import Concatenate def build_model(hype_space): """Create model according to the hyperparameter space given.""" print("Hyperspace:") print(hype_space) def super_conv_block(x): # kennt er den hype_space? conv = int(hype_space['super_conv_filter_size']) c3 = Conv1D(...
db00001e9912e8a1d42cde33e717cd47b1b597ba
3,595,787
def license_tag(value, secret, size=None): """License tag of a car.""" if not value: return value blocks = value.split(' ') for i, block in enumerate(blocks): subblocks = block.split('-') for j, subblock in enumerate(subblocks): try: int(subblock) ...
d28cafa947f1c7a44c0b21ca40a2267d8f92859d
3,595,789
from datetime import datetime def get_formatted_pubdate(time=None): """Return a properly formatted publication time. If no time is provided, this will provide the current system time. """ if time is None: time = datetime.now(dt.timezone.utc) return time.strftime('%a, %d %b %Y %H:%M:%S %...
6690cce9c4f3f72fa2afc4930e5fc1330da377a6
3,595,790
def piecewise_pulse(step_func, t_off, t_currents, currents, T, n=20, n_pulse=2): """ Computes response from double pulses (negative then positive) T: Period (e.g. 25 Hz base frequency, 0.04 s period) """ if n_pulse == 1: response = piecewise_ramp(step_func, t_off, t_currents, currents, n=n) ...
5961aad51285c22c6a469517f1a27b266a349f7c
3,595,791
def edit_filetype(request, pk): """ Edit a file type. :param request: :param pk: id of the file type. :return: """ obj = get_object_or_404(FileType, pk=pk) if request.method == 'POST': form = FileTypeModelForm(request.POST, instance=obj) if form.is_valid(): i...
42f3e7f9ae384413e1a7e15246ed2150f85e262b
3,595,792
def process_data(zip_data_path: str, zip_domain_path: str) -> (list, list): """ Processes the data into a usable list for machine learning :param zip_data_path: path to extracted data :param zip_domain_path: path to extracted domain :return: x_data and y_data """ domain_fh = open(zip_domain...
68ffb5325a19ce82df8b46bde7dad508a129684e
3,595,793
def get_leader(Na, Sa, l_prev): """ :param Na: np.array, number of pull of the different arms :param Sa: np.array, cumulative reward of the different arms :param l_prev: previous leader :return: the arm that has been pulled the most, in case of equality the arm the has the highest cumulative rew...
e158f3fb1ffad236424ebdea96723595f7f7d1ce
3,595,795
def arbitrary_particle_adder(co, particles, pos_list=[], vel_list=[], mass_list=[]): """ Adds some more particles.""" for i in range(len(pos_list)): particles.append( hal.Particle( np.array(pos_list[i]), np.array(vel_list[i]), mass_list[i], ...
fc51f4f0d369e3f29605c1eb727bcef57dd036fc
3,595,796
def isInNet(host, pattern, mask): """ Pattern and mask specification is done the same way as for SOCKS configuration. :param str host: a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. :param str pattern: an IP address pattern in th...
ce1bf819dee8f196b8bebdb59ea0193310b1743c
3,595,797
def decoder_v2( program ): """ The difference to decoder_v1 is that the mask is applied to the memory address and not the value. The mask also applies X to the memory value which indicates a floating value. A floating value can take all combinations of possible values (0,1). This generates multiple ...
a107f429b339f1b657cb3fe545a2186b9f1709d4
3,595,798