content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def ex12(): """ Example 12 Example with state file name: Example12.py Copyright Log Opt Co., Ltd. """ m1 = Model() n = 9 #number of activities state = m1.addState("state") state.addValue( time=0, value=0 ) state.addValue( time=7, value=0 ) state.addValue( time=14, valu...
3d497273cc7bab96e33fc881ea53c08ae20f4342
45,589
def resultados_portafolio(p,w,C): """ Dados unos pesos de colocacion para un portafolio y teniendose los rendimientos y covarianzas historicas, se obtiene el rendimiento y volatilidad del portafolio `p`: matriz con rendimientos historicos del portafolio `w`:...
d1577b0be03f31e75cb253205a8f1b8b320bfc77
45,591
def pml_prompt(): """ Reads user input given the PML prompt. """ return raw_input("pml:> ")
898dbc1ddb84a93b5c348eb3b28bcf089081a35b
45,593
def out_labels(G, q): """Returns a list of each of the labels appearing on the edges starting at `q` in `G`. Parameters ---------- G : labeled graph q : vertex in `G` Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(1, 2, label="a") >>> G.add_edge(1, 3, label="a")...
9849b96b562c74259b631907335a40f807e11709
45,594
import pathlib def get_project_root(name, context='local'): """find out where a repository lives context can be 'local' or 'remote' or a repo type ('sf', 'bb', 'git') """ is_private = name in private_repos is_private_value = name in private_repos.values() if is_private_value: value = ...
de93fde0eaa0536b77219489a101fadad2f16f3f
45,595
def IKinBody(Blist, M, T, thetalist0, eomg, ev): """Computes inverse kinematics in the body frame for an open chain robot :param Blist: The joint screw axes in the end-effector frame when the manipulator is at the home position, in the format of a matrix with axes as the colu...
18b3f411c34e897e89df5488eced6cdfedd1d80e
45,597
from typing import BinaryIO def _read_uint8(stream: BinaryIO) -> int: """Read an unsigned 8-bit integer from the given byte stream.""" return helpers.read_int(stream, 1, signed=False)
504c22e69a157127585972634205816114fd3435
45,598
def config_homepath(homepath, logpath=False, cachepath=False): """ Fix path for ini file. :param homepath: Path to ini file. :type homepath: str :param logpath: True if processing log folder, False if not. Default is False. :type logpath: bool :param cachepath: True if processing cache fo...
249e2d2bbd4a9112f6b9a5c0c307acc7a7f9da7a
45,599
import requests def get_items(access_token, env, realm_id): """ Uses access token to get Item data for Invoice API """ half_url = f"{env}/v3/company/{realm_id}/query" api_parameters = {"query": "select * from Item", "minorversion": "38"} api_headers = {"Accept": "application/json", ...
5766a0d381a75dd096e0d4800cd71d7ca3a9ff24
45,601
import torch def create_dummy_tensors_single(): """ Binary: 1 actual, 1 predicted (tp: 1, fp: 0, fn: 0) """ label = torch.tensor([1]) pred = torch.tensor([1]) return (label, pred)
25a4f5de0b9fed74a5e0ce7a62507eb9a341b385
45,602
def uniqueroots(nodes): #(1) """Returns a list of the nodes in `nodes` that are not children of any node in `nodes`.""" result = [] def handle_node(n): #(2) """If any of the ancestors of n are in realroots, just return, otherwise, append n to realroots. """ for ancestor i...
b8855a9d5bc40ae51b779662c2b4db2be149f4d3
45,603
async def get_interval_data(meta_ids: str, start: str, end: str): """ 获取某时间段内的统计数据和 :param meta_ids: 请求的 meta_ids, 以英文 , 分隔的字符串 :param day: 开始时间,例如 2020-12-01 :param end: 结束时间,例如 2020-12-01 :param db: 数据库连接,不需要传 :return: """ ...
4d07441208a68b97a85bddd41413c24d911ab4ac
45,605
def convert_tf_config_to_jax_bert(config): """Convert TF BERT model config to be compatible with JAX BERT model. Args: config: dictionary of TF model configurations Returns: dictionary of param names and values compatible with JAX BERT model """ unnecessary_keys = ['initializer_range', 'backward_com...
2e527dbdbef404ebf3015eca2aa9eea2b9d892e0
45,606
def find_sequences_before(context, strip): """ Returns a list of sequences that are before the strip in the current context """ return [s for s in context.sequences if s.frame_final_end <= strip.frame_final_start]
d49a950c06c2a92d076d9790055c21d30afdd627
45,608
import json def unpack_line_key(key): """Retrieve a model instance and options dict from a unique key created by create_line_key. """ bits = key.split(KEY_SEPARATOR) instance = unpack_instance_key(*bits[:-1]) options = json.loads(bits[-1]) return (instance, options)
c776f12eb140db242ff31a39db78990755a1d379
45,609
def profile_stgs(request): """ Display the users current settings and allow them to be modified """ user = request.user prof = get_object_or_404(Profile, user=user) if request.POST: form = SettingsForm(request.POST) if form.is_valid(): user.email = form.cleaned_data['ema...
8e48e2046b887c0d8710485363dfeeb7e4afa531
45,610
def calculate_percentages(df: pd.DataFrame, numer_columns: list, denom_column: str = 'total', column_name_add: str = 'percent_') -> pd.DataFrame: """Convenience function to calculate percentages based on counts data By default the cor...
c35b6d478691aa7a79ba4ae8da11cc0210ae14dc
45,612
def image_to_array(img_path:str): """ Convert image to numpy array Paramenter: img_path: str - Path to the image Returns: array: numpy.ndarray - The array converted from the image """ image = Image.open(str(img_path)) return np.array(image)
e4f5dd7aa7a3c6cac8f356dfd7dc0f72f9ad8f05
45,613
import json def liquidation(): """清算""" rps = {} rps["status"] = True if request.form.get("token"): token = request.form["token"] liq_date = request.form["check_date"] price_dict = {} if request.form.get("price_dict"): price_dict = request.form["price_dict"...
8ee956c6ffbecdde90a01487527b2869abd4d119
45,614
def _do_get_latest_featuregroup_version(featuregroup, featurestore_metadata): """ Utility method to get the latest version of a particular featuregroup Args: :featuregroup: the featuregroup to get the latest version of :featurestore_metadata: metadata of the featurestore Returns: ...
6370e61bdb6b4bfb3ea6d692721a8267f930100e
45,615
async def get_user_info( storage: StorageInterface = Depends(StorageInterface), ) -> models.UserInfo: """Get info about the current user""" with storage.start_transaction() as st: out: models.UserInfo = st.get_user() return out
d5a69faedbb1b7319b839bba3b4d37e4a79183dc
45,616
import math def update_one_contribute_score(user_total_click_num): """ item cf update sim contribution score by user """ return 1/math.log10(1+user_total_click_num)
3e80ae2f85a53737d0e155ff5f97910f73c9053f
45,617
def mel_spec(audio, sample_rate, window_stride=(160, 80), fft_size=512, num_filt=20): """Calculates mel spectrogram (condensed spectrogram)""" spec = power_spec(audio, window_stride, fft_size) return safe_log(np.dot(spec, filterbanks(sample_rate, num_filt, spec.shape[1]).T))
a9d85428d5bc66d64e5fd7094e03547724959bf0
45,618
def test1_feasible_actions(): """ Method for preparing the feasible actions for the movie booking data set """ # all of the request slots the agent can pick sys_request_slots = ['moviename', 'theater', 'starttime', 'date', 'numberofpeople', 'genre', 'state', 'city', 'zip', ...
13eee03f842bf76e627953a30bd766ddaf6ea50b
45,619
def get_percent_alloc(values): """ Determines a portfolio's allocations. Parameters ---------- values : pd.DataFrame Contains position values or amounts. Returns ------- allocations : pd.DataFrame Positions and their allocations. """ return values.divide( ...
7f4ec48b2adbdb812292930e7fda50038b6d5e96
45,621
def server_static(filepath): """Defina a Root para os ficheiros estaticos""" return static_file(filepath, root='/var/www/core/static')
a88cae7360f0932aa242618b81847f5fd1e174d0
45,623
def check_send_files(logger): """ Sends all queued files to the Bouldair server for the website. :param logger: logging logger to record to :return: bool, True if ran correctly, False if exit on error """ logger.info('Running check_send_files()') try: engine, session = connect_to_d...
87ec9ced8630ca2b706a94ffb11b53e822d22c02
45,624
def get_used_namespace(project_id): """通过应用实例获取使用的命名空间""" # 通过project_id查询模板集信息 all_tmpl = Template.objects.filter(project_id=project_id).values("id") tmpl_id_list = [info["id"] for info in all_tmpl] ns_id_info = VersionInstance.objects.filter( is_deleted=False, is_bcs_success=True, template...
2e9ac5f94f955bec58be029a08995991dec5ad06
45,627
def random_transform(im, gt, target_shape, saturation_range=None, value_range=None, brightness_range=None, contrast_range=None, blur_params=None, flip_lr=False, rotation_range=None, shift_range=None, zoom_range=None, ignore_label=0): """ Applies a list of transformation...
d4542d4283df85bb02d6c385adfea774a169b0ec
45,629
import json def getSurvivedStatus(survivedStatus): """ ---> Select survived passengers depending on status 0 or 1 <--- Return encoded list as a JSON payload with passengers data """ filterQuery = session.query(Titanic).filter(Titanic.Survived==survivedStatus).all() survivedList = [] for i...
4b3c06da186de46684444899eae7b1191453b4a9
45,631
import vtk def read_vertices(filename): """ Load VERTICES segment from a VTK file (actually indices to vertices). Parameters ---------- filename : string The path/filename of a VTK format file. Returns ------- indices : a list of integers Each element is an integer de...
0306df74ab5be52e413a5651a8e0a51f22c7d75d
45,632
def logout_auth(): """ This function is used for logged in user to logout. Clear all session data :return: if successful return status 1 """ session.clear() return jsonify({"status": 1})
33664d4634d9e2cfee15ccd2f6371cebff2614c1
45,633
def image_diff_threshold() -> float: """ Set default threshold differences of images. By default - 0.001 """ return 0.1
60d953425e2d33f1a075e3f223567fe6d731bf2b
45,634
from timeit import Timer from math import log def time_call(func, setup=None, maxtime=1, bestof=3): """ timeit() wrapper which tries to get as accurate a measurement as possible w/in maxtime seconds. :returns: ``(avg_seconds_per_call, log10_number_of_repetitions)`` """ timer = Timer(func,...
218f9032e02347ee58f1f2d725089d9d5a310951
45,635
def ustr(string): """ Returns the Python version relevant string type """ try: return unicode(string) except NameError: return str(string)
77ef97998215cbbee1a3db3ffe691da679878e5a
45,636
def get_blender_mesh_shape_key(me): """Return main shape deformer's key.""" return "|".join((get_blenderID_key(me), "Shape"))
3602cf4987b9ded7fc06b4b18bb9d7834682ba37
45,637
def binary_peirce_score(target_tensor, forecast_probability_tensor): """Returns binary Peirce score. :param target_tensor: See docstring for the 2 possible formats. :param forecast_probability_tensor: Same. :return: binary_peirce_score: Binary Peirce score. """ return ( binary_pod(targ...
1786cba03f31ce801d9586f564b438237bf3e4af
45,639
def addURL(g: rdflib.ConjunctiveGraph) -> rdflib.ConjunctiveGraph: """ Add a URL to the public permalink of the RKD website to each manuscript resource. Args: g: The graph object. Returns: The graph object with the URL added. """ manuscripts = g.subjects(RDF.type, SCHEMA.Manus...
dca63a8518942b20a816d3dca53a8df1bd6cf53e
45,640
from typing import Union from typing import Optional from datetime import datetime import traceback def fit_and_check_correctness(pipeline: Pipeline, data: Union[InputData, MultiModalData], logger: Log, cache: Optional[OperationsCache] = None, n_jobs=1): ...
e3a01f2be9068c090dcd700d3d46d3e5ae4267f9
45,641
def insertNodeAtPosition(head, data, position): """Function to insert a new node into a linked list at the specified index position Args: head (SinglyLinkedListNode): Head of the linked list data (int): Data to store in the linked list position (int): The position to store the new node ...
3498853d4fad38e4e345e4ef4d7194c6bc86c0da
45,642
def fase1(): """ Render the fase1 template on the /fase1 route """ pagesClassIDs = { "fase1": { "bannertitle": [], "subtitle": [], "firstText": [], "secondText": [] } } for key in pagesClassIDs["fase1"].keys(): pagesClassID...
3e62a6193a2407e23d3441ddbb945558c54ff9c3
45,643
from datetime import datetime def service( valid: datetime = Query(None), ): """Replaced above.""" df = run(valid) return deliver_df(df, "geojson")
89816044e4f23c60b70a3dbee7522ff2d2e8ee90
45,645
from typing import Type def has_bytes_component(typ: Type, py2: bool = False) -> bool: """Is this one of builtin byte types, or a union that contains it?""" typ = get_proper_type(typ) if py2: byte_types = {'builtins.str', 'builtins.bytearray'} else: byte_types = {'builtins.bytes', 'bui...
795450f0905224d2060634998236607228bf829c
45,646
from pathlib import Path def parameters(): """ Generate the platform-scenario test cases. """ exclude, include = read_skip_list() number = 0 params = [] scenarios = [p.parent.name for p in Path().glob('molecule/*/molecule.yml')] for p in PLATFORMS: for s in scenarios: ...
6e967c6ddfd291bdf1b6e303f3d861acf9bd3324
45,647
def dis(func): """ Disassemble a function into cpython_assembly format """ co = func.__code__ result = [] if func.__doc__: for line in func.__doc__.splitlines(): result.append(line) result.append(' :::asm') result.append(' .stacksize {0}'.format(co.co_stacksiz...
2013a3ba5bf3d38a42a239831f155e67a000ef5f
45,648
def cluster(distance_matrix, threshold, linkage_method='weighted', show_result=False, file_id=None, den_label_size=9, mat_label_size=7, trim_indices=[]): """Computes the clustering solution for a distance matrix and threshold Computes the linkages for a distance matrix using SciPy's hierarchical (agglomera...
74e4c00d755ac40b258d095cdb0298f81956d9b0
45,649
def get_length(token, negative=True, percentage=False): """Parse a <length> token.""" if percentage and token.type == 'percentage': if negative or token.value >= 0: return Dimension(token.value, '%') if token.type == 'dimension' and token.unit in LENGTH_UNITS: if negative or toke...
1d2de66ef2acb13b5933d321bc3f40918608e7c2
45,650
from masci_tools.vis.common import convergence_plot def test_convergence_mpl(): """ Test of the convergence_plot function with mpl backend """ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6)) convergence_plot(CONVERGENCE_ITERATIONS, CONVERGENCE_DISTANCES, ...
1cc9960dabcef7cde85e6bd70d8797e56826dbf5
45,651
from operator import gt def structure_sampling2(graph, centrality, function, retain_factor): """ Returns a graph view for the graph with close to retain_factor edges centrality should have a function .get_values that returns the values for the centrality function should be a function that takes two vector...
8c8fa2c481e54995fcd6a21e2e14cef6f76e24ca
45,653
def atcab_aes_cbcmac_finish(ctx, mac, mac_size): """ Finish a CBC-MAC operation returning the CBC-MAC value. If the data provided to the atcab_aes_cbcmac_update() function has incomplete block this function will return an error code. Args: ctx AES-128 CBC-MAC context. mac ...
b98fc024c3bf364214025e173596cd10571e3835
45,654
def make_wsgi_app(registry=REGISTRY): """Create a WSGI app which serves the metrics from a registry.""" def prometheus_app(environ, start_response): # Prepare parameters accept_header = environ.get('HTTP_ACCEPT') params = parse_qs(environ.get('QUERY_STRING', '')) if environ['PATH...
6844bd4cb89c67d82d003087756f6a38eeaeb176
45,655
def _tournament_selection(parents: Population, n: int, fitness_idx: int = 0, k: int = 2, w: int = 1, replacement: bool = False): """ Tournament selection is an operator that doesn't require any global knowledge of the population, nor a quantifiable measure of quality. In this case ...
b506f4a69c7c33eebea03b973796089e07ef62c6
45,657
def format_latex(ss): """ Formats a string so that it is compatible with Latex. :param ss: The string to format :type ss: string :return: The formatted string :rtype: string """ tt = (str(ss).replace('_', ' ') .replace('%', '\%') ) r...
5081e65375faf592f2f1fb52d11b0dcee99fa85f
45,659
from typing import Optional def get_by_ref(db_session: Session, *, ref: str) -> Optional[TriggerDB]: """Return trigger object based on trigger ref. Arguments: db_session {Session} -- SQLAlchemy Session object ref {str} -- ref string Returns: Optional[TriggerDB] -- Returns a Trigg...
66198a92e70889a824454eab5fed7d6361c1ef2e
45,661
def cross_entropy(output, labels, target=None): """ Compute the cross entropy between output and labels. Can do multiple examples at a time. Dimensions of output and labels must match and the target collapses along the row axis """ if not target: n = _cudanet.get_nonleading_dimension(outpu...
e057ea1ff9a37888d5aa37402dd7f10c6944d8d7
45,662
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text): """Similar to the one in presubmit_canned_checks except it shows an helpful status text instead. """ assert(input_api.is_committing) try: connection = input_api.urllib2.urlopen(url) status = connection.read() connection.close() ...
e442c04f95e0c8c65fadd408d3e472b3f18faac8
45,663
def temporal_split(df, start_year=2019, start_month=6, start_day=1, end_year=2019, end_month=8, end_day=1): """ Starts with client_df, returns DataFrame of clients labeled churn or not. ...
11052803980527077c79307fbc4ade927b579fa9
45,664
def _node(visuals, args, kwargs, level=0): """Recursive part of recursive Panel constructions""" B, K = _broadcast(visuals, args, kwargs) mk = _leaf if len(B) == 1 and Visual.isvisualable(B[0][0]) else _node # recursion N, L = zip(*(mk(p, a, k, level+1) for p, a, k in B)) if level+1 < max(L)-1: ...
e67d38327db993e7f37bcd5637eb57cc73cf3964
45,665
def best_solution_program(bundle: SpendBundle) -> SerializedProgram: """ This could potentially do a lot of clever and complicated compression optimizations in conjunction with choosing the set of SpendBundles to include. For now, we just quote the solutions we know. """ r = [] for coin_sol...
4a4db3e2aca61e77d6eda7620286f108014968a6
45,666
def os_aware(data: dict) -> dict: """ Makes data OS aware by changing all separators in file paths to match the current operating system. :param data: JSON data. :return: OS aware JSON data. """ for key, val in data.items(): if isinstance(val, dict): data[key] = os_aware(val...
6e8d5a0b26a2721442a4850d757867969be6641e
45,667
def mock_engine_port(sim_def, attr_ref, attr_val): """Mock Engine gRPC server fixture that handles test requests""" # define servicer that handles requests class TestEngine(EngineServiceServicer): def GetVersion(self, request, context): return GetVersionResp(commit_hash="HASH12") ...
c2392326d1d5a1629dc59c3d305d8bdd68394631
45,668
def parseX(sol, *args): """Parse a sol into plotable piece""" tX = np.reshape(sol[:25*4], (25, 4)) tU = np.reshape(sol[100: 100 + 2*24], (24, 2)) tf = sol[-1] return tX, tU, tf
b17f7cb4168bf0b0f3777997994d151adac3cb05
45,669
def MatchingFileType(file_name, extensions): """Returns true if the file name ends with one of the given extensions.""" return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
5fe5121d270cdfc13f6f9f3c72471fc3572b0efe
45,670
def get_connection_mask(a): """ Given a subset mask, return the appropriate vispy.Line connection array for the subset. Only the points in the subset are plotted, so return an array where each group of connected points in the array is terminated by a FALSE """ new_mask = [] for k,g ...
de4400a35f6a496c3629aad99022f5339c8d722f
45,672
def escape_path(value: bytes) -> str: """ Take a binary path value, and return a printable string, with special characters escaped. """ def human_readable_byte(b: int) -> str: if b < 0x20 or b >= 0x7F: return "\\x{:02x}".format(b) elif b == ord(b"\\"): return...
07a0c28cd531d8e3bd4330afe1d4d51265cd80c4
45,673
from typing import Any from typing import AnyStr from typing import Union def fdumpit(object_: Any, view_: AnyStr = 'vertical', colors: Union[bool, str] = False, all_: bool = True) -> AnyStr: """ Export object to string. :param object_: Any kind of python object. :...
07fa2eaf3f7b2c98cf23a3d492224109eb52acce
45,674
def opval_ADO(key, value): """A helper function for parse_branch.""" operation, value = value return "[%s] %s %s" % (key, cmpcasts_ADO[operation], quoted_field(value))
e1e4533e4f864574d1b0d48062b2ecd486e56d4a
45,675
import types def graphMethod(funcOrFlags=0, delegateTo=None): """Declare a GraphObject method as on-graph. Use as a decorator, for example: class Example(GraphObject): @graphMethod def X(self): return self.Y() @graphMethod(Settable) d...
11161f282097711c0f2edf400375baebb03ca939
45,676
def get_data(filters: typing.List[dict], threads=1, async=False, processor: typing.Callable = None): """ Get async data for a list of filters. Works only for the historical API :param filters: a list of filters :param threads: number of threads for data retrieval :param async: if True, return queue....
d2143195c42833c2faedb66dd8030137dc41234b
45,678
def get_row_col_matrix(row_index_set, col_index_set): """ Returns the resulting matrix when using a row and column of indices (list of tuples) row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16. col_index_set: the index set that would be ...
c16deb6d31ed3203cec9b17d0a68f9e45dee8871
45,679
def on_exam_finish(s): """ This method finishes exam when either time is up or educator requests so. :param s: It is for handling class structure. :return: """ def on_exam_finish_confirm(self, dt): """ This method changes exam's status to finished through server. :param ...
ef7b292b9e78b093cef084577299ac37102b1ba7
45,680
def temporal_centroid(alpha, bin_freqs): """Spectral centroid of the temporal spectrum. Calculated as the weighted average of analysis bin magnitudes. Note, temporal centroid depends on the spec frequency bins/scale (as well as the choice of `aggr_func` if custom spec is used). That is, temporal centr...
e9a1c263dacead40857fac442f0964aae59103ef
45,681
import warnings def _obtain_input_shape( input_shape, default_size, min_size, data_format, require_flatten): """Internal utility to compute/validate an ImageNet model's input shape. Args: input_shape: either None (will return the default network input shape), or a user-provide...
7183f9d96711f83fb94c9233ec1466f32ee82910
45,682
def get_auction_lores(auctions): """return lore for each auction, use asyncio.to_thread for this""" return [get_safe_content(i["item_lore"]) for i in auctions]
c4920ef5b8c617e83a393270c4f7343a15366227
45,683
import requests def create_update_dashboard(orgname=None, profile="grafana", **kwargs): """ Create or update a dashboard. dashboard A dict that defines the dashboard to create/update. overwrite Whether the dashboard should be overwritten if already existing. orgname Name...
c8cdc33d8e00dbf1f1bb72d08dc64c686c1fc7e7
45,684
def raw_reward_threshold(threshold): """Return a reward processor that cut off at a threshold.""" def fn(metadata): if metadata['raw_reward'] > threshold: return 1. elif metadata['raw_reward'] > 0: return -1 return metadata['raw_reward'] return fn
1efbd90c352d99c6e65b05214d8ccb82bb155606
45,685
def O2_conv(S, T, P, O2conc): """sal, temp, press, oxy conc""" sigmatheta_pri = sw.eos80.dens(s=S, t=T, p=P) density = sigmatheta_pri / 1000 O2conc = O2conc / density return O2conc
b3d72bde77d8b9125d29c2d6a7fd74c0886b6b19
45,686
def parse_input(input_): """Convert the puzzle input in a list of "Line" objects.""" lines = [] for l in input_.splitlines(): tokens = l.split('->') startpos, endpos = tokens[0], tokens[1] startpos = startpos.split(',') x1 = int(startpos[0]) y1 = int(startpos[1]) ...
50b6522991fe3a480de7983b33b1f34b82b775b9
45,687
import tqdm def generate_box(anchors, color = [], rotate = False): """ input: Anchor (n, 7) color: if true then the generated box will display red, otherwise black """ anchor_boxes = [] for anchor in tqdm(anchors): anchor[3:-1] = np.array([anchor[4],anchor[3],anchor[5]]) bo...
9cf3315dbc500f2a8dc8d7dfebd12b5b79440709
45,689
from pathlib import Path import dill import tqdm def load_xps(save_as): """Load `xps` (as a `list`) from given dir.""" save_as = Path(save_as).expanduser() files = [d / "xp" for d in uplink.list_job_dirs(save_as)] if not files: raise FileNotFoundError(f"No results found at {save_as}.") de...
3d43d9b8516e838dc135cd725e95ea489f24852b
45,690
import logging def process_target_counters(): """ This function extracts the target counters and converts them to the appropriate format using the convert_target_counters function. It then converts the "object" dtype records of the output dataframe (df2) to "numeric" dtype in order for the df2 to hav...
e1b8185fa0131176264e47438b70179e36264fdc
45,691
def build_pruned_tree(tree, cases): """ Build new tree with only the specifiied cases Parameters ---------- tree : List[...] the sidebar tree cases : List[int] the cases to keep Returns ------- tree_final : List[...] the updated sidebar tree Examples ...
78b10b1a3149d712312d3610268a3401c3a14400
45,693
import warnings def filter_median(im, filter_size): """ Abstracted media filter function that catches warnings about image type conversion (float to uint8) Args: im (ndarray): image filter_size (int): size of disk filter Returns: uint8 ndarray: filtered image """ with warnings.catch_warning...
31aeeb5a22f4e10efbea17e14c65883b715535ba
45,694
def comp_profit_inc_div_drp(price, price_bought_list, vol_list, DRP_list, admin_fee_list, div): """ return current market value - total cost of buying this stock, after deduct admin fees, with DRP and div """ vol_DRP_list = [i[0] + i[1] for i in zip(vol_list, DRP_list)] return comp_market_value(pric...
cb04957a84126542a4484badfccb2cac11d7d4e0
45,695
def get_migration_table(environment, Base): """Get the migration table for a given environment.""" class MigrationTable(Base): __tablename__ = "migrations_{}".format(environment) id = Column(String(100), primary_key=True) commit_time = Column( TIMESTAMP, onupdate...
8b66abd329ce36fe44e3d530716d3f5235e6169f
45,696
import math def get_rotation(box): """Return the rotation of a rectangle contour based on the slope of one of its long side.""" x1 = 0 x2 = 0 # Take the first three vertices and calculate side lengths of the right angle triangle they form d1 = math.sqrt(pow((box[0][0]-box[1][0]),2)+pow((...
1ed79ef8ee62a8ecf77dda6e0c7d6b6e97942937
45,697
def resample_with_sepconv(feat, target_width, target_num_filters, use_native_resize_op=False, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last', ...
06399c031f2e5dd82cfde870145015827b97bf09
45,698
def authenticate(): """Authenticate user. Since this goes via modifying the app, undo modifications afterwards. """ async def logged_in_user(token=None): # pylint: disable=unused-argument """Fake active user.""" return UserInDB(**config.fake_users_db["johndoe@example.com"]) app.d...
c24d0fdd7de27f4f7d20f49715577cfaf4dcec9d
45,699
def calculate_transit_duration_in_days(t, period, transit_times, duration): """Return estimate for transit duration in days""" # Difference between (time series duration / period) and epochs transit_duration_in_days_raw = ( duration * calculate_stretch(t, period, transit_times) * period ) ...
f894b1e2ea4957e5139015574e4378fe26a6e81d
45,700
def profile(request, user_id): """ Function that enables one to see their profile """ title = "Profile" profile = Profile.objects.get(user_id=user_id) biz = Business.objects.filter(user_id=user_id).all() hood = Neighbour.objects.filter(user_id=user_id).all() users = User.objects.get(id=u...
ed7fbbe1389d6fb924a626fb3368fc97be4c67b5
45,701
def get_binomial_filter_1d(size): """ This produces a 1d spatial filter with binomial coefficients """ assert size > 1 kernel = np.array([0.5, 0.5]) for i in range(size - 2): kernel = convolve(np.array([0.5, 0.5]), kernel) return kernel
653cf1082dc346488ae12217e674d65fa6a933f8
45,702
import socket def get_hostname() -> str: """ Get the current hostname, or fall back to localhost. """ try: return socket.getfqdn() except: return 'localhost'
c53bd9fae0fbbae0c0b4f84e64064d7bfd2fd61e
45,703
def format_design_table(designs: pd.DataFrame, minimum_detectable_iroas: float, minimum_lift_in_response_metric: float = 10.0, minimum_revenue_covered_by_treatment: float = 5.0): """Formats a table with the output designs. Args: designs: t...
e6f8b963fe85479edab40860f7f0c3784cb324bf
45,704
def SerializeEntries(entries): """Serializes given triplets of python and wire values and a descriptor.""" output = [] for python_format, wire_format, type_descriptor in entries: if wire_format is None or (python_format and type_descriptor.IsDirty(python_format)): wire_fo...
fe89382e2be003bd6dce25b973d8bd3ad403c492
45,705
from typing import List from typing import Tuple def get_anilist(username: str, **vars) -> List[Tuple[int,str]]: """ Gets an anilist list with a username. """ measure = Measure() raw = get_raw_anilist(username, **vars) data = sort_anilist(raw) logger.info(f'[get] Got data from anilist in {...
de341a40857491a00c6f9721f0bad6a20774d993
45,706
def get_metadata_wikidata(person_complete_name): """ Get birth date, gender and nationality (expressed with country name) for the given person :param person_complete_name: Person you are interested in :return: """ entities_ids = get_wikidata_entities(person_complete_name) person_metadata = {...
781583cd3e73fb55259ad4204884207a058ff774
45,707
def evaluate_general( result_paths, interactions_paths, events_paths, metrics, x_axis_name, x_axis_type, group_key, group_key_name_func, sort_keyfunc=None, xticks=[], K=10): """ Return a 3D table group_key: the legend part metrics: the y axis x_axis_name, sort...
d049aa6d3c5d77ef973ec7c88805884f1dc6e25c
45,708
def _get_group_discount_offer(basket, balance, group_items, num_items_offer, price_offer): """ Update the balance and the basket for a Group discount offer. """ group_items = [item for item in group_items if item in basket] offers_sold = sum([basket[item] for item in group_items])//num_items_offer...
509470fccb8a3d41a2e2e69129f186e06db261ef
45,709
def calculate_acc(mode: enums.GameMode, osu_score: dict, exclude_misses: bool = False): """ Calculate the accuracy using formulas from https://osu.ppy.sh/wiki/Accuracy """ # Parse data from the score: 50s, 100s, 300s, misses, katu and geki keys = ("count_300", "count_100", "count_50", "count_miss", "count_k...
1aadd86d25a5123a857f258de0f411c2385b4d89
45,710
def softmax_kernel_transformation(data, is_query, projection_matrix=None, numerical_stabilizer=0.000001): """Computes random features for the softmax kernel using FAVOR+ mechanism. Computes random features for the...
08f6ebb58d12e16c5a9b3ef8db1d8f241a1c186e
45,711