content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def zero_pad(number, padding=_DEFAULT_PADDING): """Converts an int into a zero padded string. Args: number(int): The number to convert. padding(int): The number of chars in the output. Note that if you pass for example number=23456 and padding=4, the output will still be '23456', i.e. it will n...
7045756f51c2dd66c690ea4b92081e52b6c9373b
3,601,846
def header_categories(_request=None): """ Required for header category navigation. """ categories = Category.objects.all() return {"nav_categories": list(categories)}
9276260af126e664b174d89b8cb74fcb7d823447
3,601,847
import json def get_all_cards(): """ Return all cards """ cards = [item for item in card_collection.values()] response = json.loads(models.CardResponse(cards=cards).json()) return JSONResponse(content=response)
2ab4f75b70a0344b67dbce7561cf2a73489fa6d6
3,601,848
from typing import List def contest_from(description: ContestDescription) -> PlaintextBallotContest: """ Construct a `BallotContest` from a specific `ContestDescription` with all false fields. This function is useful for filling contests and selections when a voter undervotes a ballot. :param descrip...
d42388debe7c0cb6f3025bdf1903bc2b18942767
3,601,849
def ranking_ativo_func(pa_long_ativo): """ o ranking_ativo retorna o ranking de price action dos ativos Parameters ---------- pa_long_ativo : dataframe dataframe do price action por ativo Returns ------- Retorna o ranking de retorno classificado por ativo com as seguintes colun...
89c87c7452461875fb75e5ba4948259a586e20f2
3,601,850
def createURIString(valueString, delimiter, vocab): """This function takes a delimiter separted string of values and returns a string in which every of these values is prefixed with the specified vocab URI. >>> createURIString('nl;fr;de', ';', 'http://id.loc.gov/vocabulary/languages/') 'http://id.loc.gov/vo...
6fb6898b1531b5741dd890452c9ddd9e4db6f205
3,601,851
def illustrate_shuffle(): """ Illustrate how shuffling in time changes the autocorrelation """ # Generate some data np.random.seed(2) details = sim_exp.behav_details['landau'] t = sim_behav.time_vector(details['fs'], details['t_start'], ...
56a4c0771a043381da59d33d53d98875b2333200
3,601,852
import requests from bs4 import BeautifulSoup def get_page(url, **kwargs): """Pulls in the HTML from a URL and returns the results as a BeautifulSoupt object. Parameters ---------- url : str The URL to scrape Returns ------- soup : bs4.BeautifulSoup The BeautifulSoup rep...
392c83be8b24bdeb27cf482c9df72c30b4b945dc
3,601,853
def yn_ask(msg): """Ask for a [y/n] user response returns the response """ resp=ask(msg) while not (resp=='y' or resp=='n'): pmsg="Please respond with a 'y' or 'n':" resp=ask(pmsg) if resp=='y': resp=True else: resp=False return resp
82a8b7cb70fdbee4b6fdd75d8e781c8714db98fe
3,601,854
def simple_is_valid(position, velocity, acceleration, jerk): """ Checks values against constant bounds. """ p_end = 10.0 v_max = 10.0 a_max = 10.0 j_max = 10.0 if position < 0.0 or position > p_end + traj.discrete_time_parameterization.POSITION_THRESHOLD: return False if velo...
19ad21a0d7df1bb04373d86633c3a4afe0a3ee82
3,601,855
def get_counter(given_name): """ Assuming the given name adheres to the naming convention of crab this will extract the counter element of the name. :param given_name: Name to extract from :type given_name: str or pm.nt.DependNode :return: int """ parts = given_name.split('_') for...
15cba70e0ab2c258af565026b6e04385981d74dc
3,601,856
def _get_default_attributes_dict(name, **kwargs): """ @param kwargs any initial item values can be passed in this argument @return dictionary with default properties of any attribute of CIM class, instance or instance name """ if not isinstance(name, basestring): raise TypeError("nam...
9ebe6e782235ac0f988714fb37c9d6418d3d45e9
3,601,858
def change_cm(request, cm_id, success_url='mai_main'): """ View changing used CM. """ request.session['user'].cm_id = int(cm_id) request.session.modified = True messages.success(request, _('Cluster Manager changed.')) return redirect(request.META['HTTP_REFERER'] or success_url)
807d041a131d33e7cf36df655e842baa76f11157
3,601,860
import six from datetime import datetime def obj_to_dict(obj, *filter_fields, **kwargs): """ filter_fields: 指定输出字段(默认输出所有) 示例: obj_to_dict(obj, 'field1', 'field2', filter_fields=['field3', 'field4']) exclude_fields: 指定不要输出字段 limit_deep: 限制递归深度, 默认5层. 设为0则不限制递归深度(不建议设为0!) p...
08b732094cc2408bed317400af2163beed774eb0
3,601,861
def envelope_flattop_cos(t, t_pulse, t_rise, t_start=0, normalize=True, **not_needed_kwargs): """ Envelope for a flattopped pulse with cosine-shaped edges. Parameters ---------- t : float Time at which the value of the envelope is to be returned. t_pulse : float...
ae1cad59edb6d10c6ee194424e7d706c1f475f5a
3,601,862
def parse_float(string:str) -> float: """ A function to parse string characters into float -> string: str => a string of chars, ex : "abc12a.a3" ---- => float: numbers present inside the string passed in, ex : 12.3 """ if not isinstance(string, str): raise TypeError('string must be ...
305c945979d4eb880d53207a9a1466f46cb7d981
3,601,863
def check_for_string_unmapped_values(string): """ :type string: str :rtype: str """ unmapped_values = "" for s in string: if s not in known_values: unmapped_values += s return unmapped_values
61925733563ed96dbb0c23bf7b18d53074a94ac6
3,601,864
def invert_dict(dct): """Inverts a dictionary from A -> B into one from B -> [A]""" ret = defaultdict(list) for k, v in dct.items(): ret[v].append(k) return ret
9b69709aa7c518b85ededae24877376825838169
3,601,865
from typing import List from typing import Dict def createWordsLines(wordsTable: List, col_lengths: List[int], border: Dict[str, str], centered: bool, extra_spaces: int = 2) -> str: """ Creates the part of table with the words as a multiline string. Args: wordsTable (List): The list of the words of t...
ec903ede975f832ed599ec9278465ab2ba8336fd
3,601,866
from pathlib import Path import json def read_jupyter_as_json(filepath: Path) -> Path: """ Read in rendered notebook-- read in the JSON representation that is 'under the hood' :param filepath: path to jupyter notebook. """ with open(filepath, "r") as fout: contents = fout.read() ...
d91344b1bddcd0e1078effe6dd7947f7e04ea6af
3,601,867
from typing import Dict def node_to_bel(node: Dict, graph, hgnc_manager: HgncManager, chebi_manager: ChebiManager, species) -> BaseEntity: """Convert node dictionary to BEL node object.""" node_types = node['entity_type'] identifier, name, namespace = get_valid_node_parameters(node, hgnc_manager, chebi_m...
70ea7751b94b14f9e3fe1396ac954421ebfbf0b1
3,601,868
def styled_text(text, new_styles, old_styles=None, supplement_style=False): """Return a styled text tuple that can be used within urwid.Text. .. note:: If an urwid.Text instance is passed in as the ``text`` parameter, alignment values will be lost and must be explicitly re-added by the ...
1283433859d9207bd73c512fc307b68ec781c98c
3,601,869
def cdf_function_1(cd: ChemicalDiagram): """inclusion: one of the connected components contains only C N H""" sets = [] for scd in cd.get_components(): sets.append(set(scd.get_element_list())) return {"C", "N", "H"} in sets
00b53571798fe1e086fe8df6f36fc369c2cabced
3,601,870
def _imports(graph: mapry.Graph) -> str: """ Generate the import declaration. :param graph: mapry definition of the object graph :return: generated code """ import_set = set() # type: Set[str] if graph.classes: import_set.add("fmt") if mapry.needs_type(a_type=graph, query=map...
78b983c7b0e2f30f7b0ca47fa98bed716120c69c
3,601,871
def _to_db_str(sequential_list): """Convert a list or tuple object to a string of database format.""" entry_list = [] for _entry in sequential_list: # I know only text type need to be converted by now. More types could # be added in the future when we know. if isinstance(_entry, str)...
42a4e008964c0accb3e596dc75859641e999a0f4
3,601,872
def generate_personalized_recommendations( submission_ids: list, data: list, index: str, nbrs_model: NearestNeighbors = None, ): """ Generate personalized recommendations for a given submission ids, given data, index, and nearest neighbors model submission_ids: list, list of IDs that we...
8d9cfada05de4a787e023b35afdac7c87499a2ea
3,601,873
import glob def get_file_sets(root_path, resnet_version, dlc_network_shuffle= 'shuffle2',dlc_network_iteration = '500000', filtered=False): """ function intended to fetch the proper network file sets for a given session. A session directory may have multiple predictions from unique DLC networks saved to a fol...
d7920667545dece6d6c4fccc6075a14c8eb53837
3,601,874
import time def retry(ex, tries=4, delay=3, backoff=2, logger=log): """Retry calling the decorated function using exponential backoff based on * http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ * http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ex: the excepti...
61a743b3f6260bac1ed82afe132ab94579848358
3,601,875
def parse_errors(root_dir, lines): """ Parse and add special markers to all error found in the `ERRORS` section. :param root_dir: This is the test root dir found in the pytest report. :param lines: All reported output lines from the `ERRORS` section. :returns: The original input list augmented wit...
f52cd2ab5e01330247930be88bf0bfda5654a9dd
3,601,877
def air_port_add(request): """ Add new air_port and see the list of air_ports packages """ success_message, error_message = None, None form = AirPortForm air_ports = AirPort.objects.all() if request.method=="POST": form = AirPortForm(request.POST) if form.is_valid(): ...
d8264c1265c8cb538cb7990117a9249099314ee2
3,601,878
def pull_address_data(url=None): """ Libraries with active extended wi-fi programs have their websites listed. Access websites and pull street address and zip code. If an street address intersection is given e.g., "16 Brighton First Rd. at Brighton Beach Ave." remove the int...
d17029b3a04050cfc5cc51215eb0671f59d5e5e9
3,601,879
import requests from typing import Match def get_match(match_id): """Returns Score dicts list of the recent scores of the user""" payload = {KEY_API_KEY: constants.OSU_API_KEY, KEY_MATCH: get_from_string(match_id)} request = requests.get(URL_GET_MATCH, params=payload) if request.status_code != 200: ...
5ccfc596ff87c68283bd1cd77036a052d6e2d07f
3,601,880
from typing import Tuple import logging async def test_send_custom_json(node: str) -> Tuple[str, float]: """Builds but doesn't send a custom_json not async.""" try: hive = beem.Hive(node=node, nobroadcast=True, wif=Config.posting_keys) data = {"something": "here"} start = timer() ...
12e27f679fd5cc4d62346f6f703eab44872c8b3e
3,601,881
def transform_rows_nonlinear_and_categorical02(data, **kwargs): """ Nonlinear and categorical row transformation 02. 7 numerical data sources (x^4, log, exp2, log1p, x^5, log10, log2) and 3 categorical (8, 4 and 2 categories). """ sources_transformers = [ lambda x: np.power(x, 4), lambd...
8a277a860b017766d8aa154527fc27a44ec52da5
3,601,882
def histogram(s): """to check s in string""" d={} for c in s: d[c]=1+d.get(c,0) return d
4b643a05f97ae0829235b1296e37ee73ad8807f4
3,601,883
def format_rot_dist_consts(rot_dists): """ Format the rotational distortion constants. """ # Build rotational dists string rot_dists_string = '' for i, const in enumerate(rot_dists): rot_dists_string += ' '.join(map(str, const)) if (i+1) != len(rot_dists): rot_dists_str...
dbcb285f6886f6065ddd02497d12a230e1d74dff
3,601,884
def read_get_schema(data): """Reads and parses a GSC ('Get Schema') request.""" return {"user": read(data, "S", 0), "group": read(data, "S", 2), "schema": read(data, "S", 4), "session_id": read(data, "S", 6)}
a84706b9e9fd8341c44cda718705b40839581b97
3,601,885
def svn_txdelta_send_string(*args): """svn_txdelta_send_string(svn_string_t const * string, svn_txdelta_window_handler_t handler, void * handler_baton, apr_pool_t pool) -> svn_error_t""" return _delta.svn_txdelta_send_string(*args)
630f0a58a289ff2a252f84089f94f8c2f2ab3359
3,601,886
def _to_spdx(lic): """ we are munging this stuff from conda-build d_license = {'agpl3': ['AGPL-3', 'AGPL (>= 3)', 'AGPL', 'GNU Affero General Public License'], 'artistic2': ['Artistic-2.0', 'Artistic License 2.0'], 'gpl2': ['GPL-2', 'GPL (>= 2)',...
66aaa5fa8428ec680ab347b9a33ed7f03f18281c
3,601,888
import logging def remote_ring(host: str, command: list, log: logging.Logger): """Remote ring over ssh. Returns `True` on success. """ ssh = ["/usr/bin/ssh", "-t", "-o", "ConnectTimeout=1", "-o", "StrictHostKeyChecking=no", host] return system_call(ssh + com...
a3a05e98c49ca2af9f9c10625e8d9ad9baa00536
3,601,889
def geometry2layer(dataset, geom): """ Convert geometry to a virtual-memory layer. """ # create layer layer = dataset.CreateLayer( 'geom', geom.GetSpatialReference(), geom.GetGeometryType() ) # add feature feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometry(geom) laye...
fbbc6cd5c5dee6af790113bc6297a49aa6479a0d
3,601,890
import numpy def plane_fit(coordinates, center=None): """ Compute n-dimensional plane to a series or coordinates and return the normal to that plane :param coordinates: coordinates to fit a plane to :type coordinates: :numpy:ndarray :param center: point on the plane used as origin for t...
4922b42c7c8a6c4faa7227386396ebc93bc1bafb
3,601,891
def atanh(x : float) -> float: """ Inverse trigonometric function Domain (-1 < x < 1) """ if not -1 < x < 1: raise ValueError("Math domain error not in (-1,+1)") return 0.5*functions.ln((1+x)/(1-x))
a63ac82383d90d3c790035a901fbdabfca098b3b
3,601,892
from typing import NamedTuple from typing import Optional def prepare_data_for_train( # pylint: disable=g-bare-generic input_tables: list, preprocess_metadata: dict, model_feature_columns: Optional[list] = None, # pylint: enable=g-bare-generic ) -> NamedTuple( 'Outputs', [ ('time_s...
112b340de85aee8199c528e830a76427cb3d18aa
3,601,893
from typing import Any import glob import ast import importlib def process_args(args) -> Any: """ Validates args :param args: :return: """ possible_extensions = {'.g', '.gml', '.txt', '.gml', '.mat'} graph_names = {fname[: fname.find(ext)].split('/')[-1] for ext in poss...
24432c251479b9bd3e7ad351075043ac64048d81
3,601,894
def vendor_factory(vendor_name): """ Given a full name of a vendor, retrieve or create the canonical `~trigger.netdevices.Vendor` object. Vendor instances are cached to improve startup speed. :param vendor_name: The vendor's full manufacturer name (e.g. 'CISCO SYSTEMS') """ return ...
d475c16e8c9561056564064ad0165efed9a6005b
3,601,895
def hierachical_rollout2( env, scheduler, worker, skill_horizon=1, max_path_length=np.inf, render=False, render_kwargs=None, exclude_obs_ind=None, obs_ind=None, goal_ind=None, ): """ The following value for the following keys will b...
cbe1e7162aa77e8145a880d6f62a5006c98df55a
3,601,896
def pyscv_get_widget(*args): """ pyscv_get_widget(py_this) -> TWidget * """ return _ida_kernwin.pyscv_get_widget(*args)
22633cfbe0b62785150fc7ff5c1b5dedd7a5c801
3,601,898
def linear_scale_between(x1: float, x2: float, y1: float, y2: float, x: float, *, clamp=True, easing_func=None) -> float: """Standard linear interpolation function, optionally clamped (between y1 and y2)""" pct = (x - x1) / (x2 - x1) if easing_func: pct = easing_func(pct) if clamp: pc...
f488346a4fe07b82f1281b646c3a39171b5fe757
3,601,899
def api_chart_scores(request): """ Used by report page line chart. Returns JSON in format needed for line chart. Used to load and chart a scoped set of Lighthouse runs. """ urlId = request.GET.get('urlid', None) rangeType = request.GET.get('range', None) ## Validate that...
bdf8820fa7f670ffc09fc24c058eca2b47b9b76a
3,601,900
def sel_init_cen(features, k): """ 随机选择K个初始聚类中心 :param features: [[r,g,b],[r,g,b]...] :return: centors=[cen1,cen2...] """ # 选取随机数 rands = [(int)(np.random.random() * (features.shape[0])) for _ in range(k)] # 选取初始中心 centors = [features[rands[i]] for i in range(k)] return centors
e61b3029297a610e04bca1b50067f7f32b11dad5
3,601,902
def cfgargparse( cfgspecfile, parser, parse=True, cfgfileopt="--cfgfile", cfgfile="config.cfg", exc=[], extraopts=None, args=None, getparser=False, getargs=True, **kwargs, ): """Merge configuration and commandline arguments Parameters ---------- cfgspecfile: ...
911bcfa13c1bbc5b977582b40953b4a5716bab49
3,601,903
import ast def _is_ast_str(node): """Determine whether this node represents a string.""" allowed_types = [ast.Str] if hasattr(ast, "Bytes"): allowed_types += [ast.Bytes] if hasattr(ast, "JoinedStr"): allowed_types += [ast.JoinedStr] if hasattr(ast, "FormattedValue"): allowed_types += [ast.Format...
132af7142404f885684ce6559d1472c622c9cd10
3,601,904
def as_dict(self, **kwargs): """ Convert this object in a json serializable dict (can be use in __init__). Optional keyword input parameter is for internal use only and may prevent json serializability. """ DataKeeper_dict = dict() DataKeeper_dict["name"] = self.name DataKeeper_dict["ph...
c2c9535a39d21a5946df41d67df29fd43b3f3692
3,601,905
def translate_xmile(xmile_file): """ Translate an xmile model file into a python class. Functionality is currently limited. """ py_model_file = build_python(xmile_file) return py_model_file
5740e05b91d966c6d5ea33752bb38010c522c5fe
3,601,906
def access_token_url(): """ URL for exchanging a verifier for an access token. """ return _BASE_URL_V1 % 'oauth/access_token/'
9422c7b8ceae38d9ae92a89b4dbd55c71fd32175
3,601,907
def SetSpDiff(ea, delta): """ Setup modification of SP made by the instruction @param ea: end address of the instruction i.e.the last address of the instruction+1 @param delta: the difference made by the current instruction. @return: 1-ok, 0-failed """ return idaapi.add_user...
606c7ec20dab0a5af1bb8f8d5e69f4e95163cee3
3,601,908
import itertools def score(data, synth, targets=[]): """ Compute the total variation distance between marginals of data and synth. :param data: an mbi.Dataset object :param synth: an mbi.Dataset object :param targets: A list of columns in the data domain """ workload = list(itertools.combinat...
4a8ca07b1197ca567678291cbaf3585b6f7843bf
3,601,909
import torch def create_train_and_validation_engines(train_func, val_func=None, device='cpu'): """ Helper function for creating an ignite Engine object with helpful defaults. This sets up an Engine that has four handlers attached to it: - prepare_batch: before a batch is passed to train_func or val_f...
6f0591196be25c5d1592200ac28b0317af54b22c
3,601,910
import lifelines def median_survival_times(model_or_survival_function) -> float: """ Compute the median survival time of survival function(s). Parameters ----------- model_or_survival_function: lifelines model or DataFrame This can be a univariate lifelines model, or a DataFrame of one o...
93e22de3c9673c12b9052fd2338ce2a304ba2a56
3,601,911
import random def create_bank(num_accounts=1): """Returns a new bank with the given number of accounts.""" names = ("Brandon", "Molly", "Elena", "Mark", "Tricia", "Ken", "Jill", "Jack") bank = Bank() upper_pin = num_accounts + 1000 for pin_number in range(1000, upper_pin): ...
a7c131d80520e7f8b7285fc10d24724091a75d82
3,601,912
def Linear(source, target): """ Performs basic linear interpolation in between a source and a target. """ if target.frame <= source.frame: raise ValueError("Target frame must be greater than source frame " "(source = {0}, target = {1})".format(source.frame, target.frame)) fdiff = fl...
89e6fb8ec03324cc971eee60291a1008b3834e32
3,601,913
def gaussian_mask(S): """ mask significant intensities in spectrum Parameters ---------- S : np.array, size=(m,n), dtype=complex array with spectrum, i.e.: S = np.fft.fft2(I) Returns ------- M : np.array, size=(m,n), dtype=bool frequency mask See Al...
a8cf0847dd796aead0577ce48c2511710af7546b
3,601,914
import tqdm def get_data(data_type: str, left_flank_size: int, right_flank_size: int, n_bins: int = 100, bin_value_type: str = 'mean') -> pd.DataFrame: """ Generates histone modification data by bins for each gene. :param data_type: 'seq' or 'histone' data :param left_flank_size: number ...
108fbcb77feb0734ecc564ef8bf4eaf782551c39
3,601,915
def make_dict_from_config(path, config_file): """ Function to make a dict from a configuration file Parameters --------------- path: str path dir to the config file config_file: str config file name Returns ---------- dict with the config file infos """ # open a...
fd928dde7bb9ea3d360237c34bc7c46f9f26b07a
3,601,916
def is_walrus_assignment(node: LN) -> bool: """Return True iff `node` is of the shape ( test := test )""" inner = unwrap_singleton_parenthesis(node) return inner is not None and inner.type == syms.namedexpr_test
5c9b594187d3e91330cb3089fe7bc21fafafa3f2
3,601,917
def extract_domain(email_address): """ Given an email address, extract the domain name from it. This is done by finding the @ and then splicing the email address and returning everything found after the @. If no @ is found then the entire email address string is returned. :param email_address: ...
3e09c9cef431c09d126d8de6854990dc9351ef0d
3,601,919
def get_sweep_info(pul, pgf, group_idx, series_idx): """ Find the associated record in the StimTree from the PulseTree """ pul_series = pul["ch"][group_idx]["ch"][series_idx] num_sweeps_in_recorded_data = pul_series["hd"]["SeNumberSweeps"] pul_sweep = pul_series["ch"][0] stim_idx = pul_swee...
ebb2f125f9dbf45f80e088d63314a6fd10069a06
3,601,920
def build_model(args: Namespace) -> nn.Module: """ Builds a MoleculeModel, which is a message passing neural network + feed-forward layers. :param args: Arguments. :return: A MoleculeModel containing the MPN encoder along with final linear layers with parameters initialized. """ output_size = a...
1eaa94e714f44bdaeb4afd1a71f4e5cdf876294a
3,601,921
import pandas as pd def google_scholar(root="./", download=True, full=False) -> Dataset: """Google Scholar dataset (Agrawal, et al.). The Google Scholar dataset contains an academic coauthorship graph: the nodes are authors, and two authors are connected by an edge if either author listed the other a...
87876024913826b8d9769a78f72cd944057c04ce
3,601,922
def standard_form(ich, stereo=True): """ Return an InChI string in standard form. Eventually we should just designate standard-form as standard InChI ordering for all but the hardcoded exceptions, put at the end. :param ich: InChI string :type ich: str :param stereo: parame...
554fa9d538e8b6e4f9983725f570ce28a6d6ae34
3,601,923
def check_solution(model, solution): """ Helper function. if solution is None, attempts to get it from the model. :param model: :param solution: :return: """ if solution is None: try: solution = model.solution except AttributeError: raise AttributeErr...
a03ee5e2033ee99caa0fd761f9d78d3d597a906b
3,601,924
import torch from unittest.mock import Mock def test_batch_verification_calls_custom_input_output_mappings(): """ Test that batch gradient verification can support different input and outputs with user-provided mappings. """ model = MultipleInputModel() def input_mapping(inputs): assert isinstanc...
367d7389bd09762d8059a2e66e4c7d9a64aacd76
3,601,925
def gather_files(files_in): """ Args: files_in (str): """ cubes = iris.load(files_in) cubes.sort(key=lambda x: x.name()) unify_time_units(cubes) # Add the names of custom output fields replace_names(cubes) # Remove hybrid height cubes and add as coordinates instead rep...
edf84eaf418d58fc18e90949fe87a89d4c38f5c2
3,601,926
def pose_disambiguation(x2, K, C2, R2, X_n): """ Returns the pose that minimizes reprojection error. :param x2: 2D points corresponding to X_n :param K: camera intrinsic matrix :param C2: four configurations of camera centers :param R2: four configurations of rotations :param X_n: four sets ...
a85926460e9d8a68267958977205a31f627601c4
3,601,927
import yaml def dict_from_yaml(yaml_file): """Gets the dict representation of a YAML file.""" try: yaml_dict = yaml.safe_load(yaml_file) assert isinstance(yaml_dict, dict) return yaml_dict except yaml.YAMLError as e: raise InvalidInputException(e)
94ea65e958cfb814658dfe320f4e020ae9fe338f
3,601,928
def plot_quantile_returns_violin(return_by_q, ylim_percentiles=None, ax=None): """ Plots a violin box plot of period wise returns for factor quantiles. Parameters ---------- return_by_q : pd.DataFrame - MultiIndex DataFrame w...
9c993c45a0fc655c581943ef6a99b279461fd0d8
3,601,929
def str_to_dict(value): """ Convert a newline terminated string of key=value into a dictionary. Parameters ---------- value : str The string object to convert to a dictionary Returns ------- dict Dictionary based on the string """ result_dict = {} for item ...
97a11fdbb715fad2da2e5866e30472a1b49e2c5e
3,601,930
def degTodms(ideg): """ Converts degrees to degrees:minutes:seconds :param ideg: objects coordinate in degrees :type ideg: float :return: degrees:minutes:seconds :rtype: string """ if (ideg < 0): s = -1 else: s = 1 ideg = abs(ideg) deg = int(ideg) + 0. m...
169cf4a89e7a2bd8526cf32acd1e88ec62d0237f
3,601,932
def convert_rgb565(image): """Converts the RGB image into a byte array in RGB565 format""" data = bytearray(128 * 160 * 2) i = 0 for (r, g, b) in image.getdata(): w = rgb888_to_rgb565(r, g, b) data[i] = w >> 8 i += 1 data[i] = w & 0xff i += 1 return data
e2fd92e73499a640280fa65936dd2603cade22d1
3,601,933
from datetime import datetime from typing import Tuple from typing import Dict import random def _create_new_row( table: Table, primary_key: int, parent_key: int = None, batch_id: int = None, timestamp: datetime = datetime.now(), ) -> Tuple: """ Create a new row for a table. Substitute cr...
2683930a49f33e25c97687b63687d70fcde709d4
3,601,934
def char_to_string(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.asarray(arr) kind = arr.dtype.kind if kind not in ['U', 'S']: raise ValueError('argument must be a string') return arr.view(kind + ...
c25446c0a2d028249ad7e30fe6fd70245baea617
3,601,935
import pandas import numpy def rolling_stat(stat, x, window): """ Calculate rolling statistics `stat` of `x` with sliding `window`. Parameters ---------- stat : 'snr', 'cv', 'fano', 'mean', 'median', ... Name (`str`) of the rolling statistics supported by pandas and `getstat` (e.g...
54ff5a66925390e291dc86eec60437abb4c0ecaf
3,601,937
from typing import OrderedDict def evaluate_box_proposals(dataset, roidb): """Evaluate bounding box object proposals.""" res = _empty_box_proposal_results() areas = {'all': '', 'small': 's', 'medium': 'm', 'large': 'l'} for limit in [100, 1000]: for area, suffix in areas.items(): s...
e0a5ba8bad0711f0d1285925642029c64da54fde
3,601,939
def breakbarrier(self, *qargs): """Apply :class:`~qiskit.circuit.Barrier`. If qargs is None, applies to all.""" #from .barrier import Barrier qubits = [] if not qargs: # None for qreg in self.qregs: for j in range(qreg.size): qubits.appen...
22addde668d669e9574f4f929248b16ebb0481db
3,601,940
def build_command(input_device, rates, bits, buffers, sox_effects): """ :param input_device: device index e.g. 2 :param rates: [input, output] e.g. [48000, 48000] :param bits: [input, output] e.g. [16, 16] :param buffers: [input, sox] e.g. [512, 1024] :param sox_effects: [left, right] e.g. [['eq...
8c17f55ef8ff3d0abc8ffbdbe85a2d98306a6b37
3,601,941
def filter_sparse(timestamps): """ Create a sparse set of timestamps, by keeping only 1 timestamp for every 10 minute interval. """ if len(timestamps) == 0: return [] ok = [timestamps[0]] for vis_ts, ir_ts in sorted(timestamps, key=lambda x: x[0]): if (vis_ts - ok[-1][0]) >...
12030e7f9151c2c846d4fd7f0c31bcc1c28104ae
3,601,942
from pathlib import Path def main() -> int: """ Execute the setup command.""" def data_files(*paths): """ Expand path contents for the `data_files` config variable. """ for path in map(Path, paths): if path.is_dir(): for root, _, files in walk(str(path)): ...
21538616157f4916184936c4ecf559cdb85eead7
3,601,946
from typing import Union def conditional_join( df: pd.DataFrame, right: Union[pd.DataFrame, pd.Series], *conditions, how: str = "inner", sort_by_appearance: bool = False, ) -> pd.DataFrame: """ This is a convenience function that operates similarly to ``pd.merge``, but allows joins on...
e70c1bc31111312d3c8df0b6b6556000673a923b
3,601,947
def prepare_results(cursor_description, rows): """ Generate result in JSON format with an entry consisting of key value pairs. :param cursor_description: a tuple with query result columns :param rows: list of returned sql query values :return: dictionary """ if rows is None or len(rows) == 0...
8fcc48f0a732a200c65d27817349a0de1a5f1172
3,601,948
from typing import List def merge_rgb(images: List[Image]) -> List[Image]: """Variant of images_to_stack that makes an RGB from 3 images.""" if not (len(images) == 3 and all(isinstance(x, Image) for x in images)): raise ValueError( trans._("merge_rgb requires 3 images layers", deferred=Tru...
c8dd9952a78f93720714ad8c5482fe5679ffc347
3,601,949
def signed_in_users(session=None, today=None, full_name=True): """Return list of names of currently signed in users. :param session: SQLAlchemy session through which to access the database. :param today: (optional) The current date as a `datetime.date` object. Used for testing. :param full_name: (optio...
55e394f778af9786c0ee3ba98b1bdcd20530b32e
3,601,951
def eval_hess_f(Y): """ compute the hessian of f in the forward mode of AD """ Y = algopy.UTPM.init_hessian(Y) retval = eval_f(Y) hessian = algopy.UTPM.extract_hessian(5, retval) return hessian
67272b4ae62def8cd993f77ec5751dbec71900b5
3,601,952
from typing import Tuple import re def get_name_version_from_requires_dist(string_parse: str) -> Tuple[str, str]: """Extract the name and the version from `requires_dist` present in PyPi`s metadata :param string_parse: requires_dist value from PyPi metadata :return: Name and version of a package ...
55545ec1b30a4db1944932070434d26205beefbd
3,601,954
import torch def _rescale(dat, mn_out=0, mx_out=511): """ Rescales image intensities between mn_out and mx_out. """ dtype = dat.dtype device = dat.device dat[(dat == dat.min()) | ~torch.isfinite(dat) | (dat == dat.max())] = 0 # Make scaling to set image intensities between mn_out and mx_out ...
3b502094e22fe97fadfeb4ff987774385442c52e
3,601,955
import pkg_resources def walk(module_name, dirname, topdown=True): """ Copy of :func:`os.walk`, please refer to its doc. The only difference is that we walk in a package_resource instead of a plain directory. :type module_name: basestring :param module_name: module to search in :type dirname: ...
8a001a4673b9a123f4c4260f2226eff0c360b698
3,601,956
def get_triplet_columns(data: DataFrame) -> DataFrame: """ Remove all columns except (protein, mutation, interactor) triplets. Parameters ---------- data : <DataFrame> The input dataframe whose non-triplet columns to be removed. Returns ------- triplet_data : <DataF...
9749479ea5b1fda2370541d89de33d2d9e018bbc
3,601,957
from typing import Iterable def test_alias() -> None: """Test that columns and indices can be aliased.""" class Schema(pa.SchemaModel): col_2020: Series[int] = pa.Field(alias=2020) idx: Index[int] = pa.Field(alias="_idx", check_name=True) @pa.check(2020) @classmethod ...
c83ecc20002d5e0e85be3ad168705a7adf09ede4
3,601,958
def p_methods(data, pv_index=0, alpha = 0.05): """ A summary dataframe with columns for the p-values, adjusted p-values for both Bonferroni and Benjamini-Hochberg (BH), adjusted significancelevel for Bonferroni and the critical value for BH Args: - data: dataframe or array containing at least a ...
2d7a9d6d0ff983f6fbc6811f96663b35f450754b
3,601,959
def create_client_entities(count, id_or_name=False): """Creates a list of client-style entities with random keys.""" return [ entity.to_client_entity() for entity in create_entities(count, id_or_name=id_or_name) ]
a38c0b5c16746c264fd26dcc78b90d3b35681555
3,601,960