content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def query_title_bar_text(shared_state): """return text for title bar, updated when screen changes.""" coll_name = shared_state["active_collection"].name str_value = f"QUERY SOURCE: {coll_name}" return str_value
2ce051cc8d6a87d3c964fba1abb502125b227717
17,673
def input_handler2(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This s...
d9b3887f82b2a9ef19449d58e40ca18b642a2bf4
17,674
import requests def create_upload_record(env, source_id, headers, cookies): """Creates an upload resource via the G.h Source API.""" post_api_url = f"{get_source_api_url(env)}/sources/{source_id}/uploads" print(f"Creating upload via {post_api_url}") res = requests.post(post_api_url, ...
7d8bcebec30be7ccba5406f1afc6a1b267e8e398
17,675
def get_versions(sys): """Import stuff and get versions if module Parameters ---------- sys : module The sys module object. Returns ------- module_versions : dict The module names and corresponding versions. """ module_versions = {} for name, module in sys.modul...
172103da6d6f476080a1c1a33b34ebb4d028df05
17,676
def day05_part1(file: str) -> int: """ Solves advent of code: day05 part1 """ with open(file) as fid: seats = [Seat(line.strip()) for line in fid] highest_seat_num = max(seat.number for seat in seats) return highest_seat_num
5ba399053d3a7e855ded402cea60f59c9d79d9a4
17,677
def GetInput(): """Get player inputs and lower-case the input""" Input = str(input("{:>20s}".format(""))) print("\n \n \n \n \n") return Input.lower()
9d8626a9c9f0615a0453d0804b6b37244ec373c3
17,678
def ldns_fskipcs_l(*args): """LDNS buffer.""" return _ldns.ldns_fskipcs_l(*args)
44e357adf381e11aaccb78441c543438abe75ba1
17,679
def specific_parser(parser, log=False, run_folder=None, mode=None, tot_epochs=None, restoring_rep_path=None, start_from_epoch=None, pretrained_GAN=None, GAN_epoch=None, data_dir_train=None, data_dir_train2=None, data_dir_test=None, data_dir_test2=None, images_log_freq=None, batch...
cbce4c086da986a3232d40ae2d917b921ff64ff2
17,680
import re def to_identifier(text): """Converts text to a valid Python identifier by replacing all whitespace and punctuation and adding a prefix if starting with a digit""" if text[:1].isdigit(): text = '_' + text return re.sub('_+', '_', str(text).translate(TRANS_TABLE))
8c8ca0c52c13a7d78aa9ec2288ef86ec7e10f84a
17,681
def estimate_next_pos(measurement, OTHER = None): """Estimate the next (x, y) position of the wandering Traxbot based on noisy (x, y) measurements.""" if OTHER is None: # Setup Kalman Filter [u, P, H, R] = setup_kalman_filter() # OTHER = {'x': x, 'P': P, 'u': u, 'matrices':[H, R]} ...
a6b6eba0aa7e71a986bc5bed68cc6fb955c02383
17,682
def AutoBusList(*args): """List of Buses or (File=xxxx) syntax for the AutoAdd solution mode.""" # Getter if len(args) == 0: return get_string(lib.Settings_Get_AutoBusList()) # Setter Value, = args if type(Value) is not bytes: Value = Value.encode(codec) lib.Settings_Set_Au...
aab4ae15dd7b12c46eb5a75bb780ac78609273ae
17,683
from typing import Tuple from typing import Optional def validate_inputs(*, input_data: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[dict]]: """Check model inputs for unprocessable values.""" # convert syntax error field names (beginning with numbers) # input_data.rename(columns=config.model_config.vari...
b03e616dc10c734af282d71a650da822e961e93f
17,684
def create_env(n_envs, eval_env=False, no_log=False): """ Create the environment and wrap it if necessary :param n_envs: (int) :param eval_env: (bool) Whether is it an environment used for evaluation or not :param no_log: (bool) Do not log training when doing hyperparameter optim (issue with...
c0d1355cb1ea4446370a71cb49bfb6855799b4b3
17,685
def ellipse(pts, pc=None, ab=None): """ Distance function for the ellipse centered at pc = [xc, yc], with a, b = [a, b] """ if pc is None: pc = [0, 0] if ab is None: ab = [1., 2.] return dist((pts - pc)/ab) - 1.0
7ff99b98aa09d86223afe97a987176f4dc0e0f3d
17,686
def _transform( parsed_date_data: ParsedDate, parsed_output_format_data: ParsedTargetFormat, output_format: str, output_timezone: str, ) -> str: """ This function transform parsed result into target format Parameters ---------- parsed_date_data generated year, month, day, hou...
cc51f2776165bf05af1d97bcc6eb70bd6f03702f
17,687
def stop_next_turn(): """ Dirty way to stop the MCTS in a clean way (without SIGINT or SIGTERM)... the mcts finish current turn save data and stop (if you are using dft it can take some time...) write "stop" in the file MCTS/stop_mcts :return: None """ with open(p.f_stop) as f: stop...
eb76187f25f49ae674fefe7969277122bd18e5c8
17,689
from datetime import datetime def pull_request_average_time_between_responses(self, repo_group_id, repo_id=None, group_by='month', time_unit='hours', begin_date=None, end_date=None): """ Avegage time between responeses with merged_status and the time frame :param repo_group_id: The repository's repo_group_id...
8834586b1e761c8ba6033140f753a3ac99780da7
17,690
def create_money(request): """Create money object.""" if request.method == 'POST': form = MoneyForm(request.POST, request.FILES) if form.is_valid(): money = form.save(commit=False) money.owner = request.user money.save() return redirect(money) ...
483eea12a1c2f49dd63fe2a37a529dafe3a4c6c3
17,691
def stripper(reply: str, prefix=None, suffix=None) -> str: """This is a helper function used to strip off reply prefix and terminator. Standard Python str.strip() doesn't work reliably because it operates on character-by-character basis, while prefix/terminator is usually a group of characters. Arg...
b48281a0dedd5d7f3d476943f12ac49720e67476
17,692
def resnet_50_generator(block_fn, lst_layers, num_classes, pruning_method=None, data_format='channels_first', name=None): """Generator for ResNet v1 models. Args: block_fn: String that define...
5f471b7cc3608c11515d0efb088c3c9bee0e20e6
17,693
def bracketBalanced(expression): """Check if an expression is balanced. An expression is balanced if all the opening brackets(i.e. '(, {, [') have a corresponding closing bracket(i.e. '), }, ]'). Args: expression (str) : The expression to be checked. Returns: bool: True if express...
bb6ebeb681fb9425c923a4fdcc41c6158ece332a
17,694
def Leq(pressure, reference_pressure=REFERENCE_PRESSURE, axis=-1): """ Time-averaged sound pressure level :math:`L_{p,T}` or equivalent-continious sound pressure level :math:`L_{p,eqT}` in dB. :param pressure: Instantaneous sound pressure :math:`p`. :param reference_pressure: Reference value :math:`p_0...
bf7c640a361f3c07aef70310a213f2603a441664
17,695
import re def trimBody(body): """ Quick function for trimming away the fat from emails """ # Cut away "On $date, jane doe wrote: " kind of texts body = re.sub( r"(((?:\r?\n|^)((on .+ wrote:[\r\n]+)|(sent from my .+)|(>+[ \t]*[^\r\n]*\r?\n[^\n]*\n*)+)+)+)", "", body, flags=r...
19fcb7313e66d7e710781cf195a7550d050b4848
17,696
def fit_ellipses(contours): """ Fit ellipses to contour(s). Parameters ---------- contours : ndarray or list Contour(s) to fit ellipses to. Returns ------- ellipses : ndarray or list An array or list corresponding to dimensions to ellipses fitted. """ if isinst...
9246182a1f96ca1691bcddf34271586be93dcf41
17,698
def get_argument_parser() -> ArgumentParser: """ Get command line arguments. """ parser = ArgumentParser( description="Say Hello") subparsers = parser.add_subparsers(title="subcommands") parser_count_above_below = subparsers.add_parser("say-hello") parser_count_above_below.add_argu...
f799991025283bf4ce2dbcceed845662312cd6d0
17,699
from typing import List def parse_mint_studies_response(xml_raw) -> List[MintStudy]: """Parse the xml response to a MINT find DICOM studies call Raises ------ DICOMTrolleyError If parsing fails """ try: studies = ElementTree.fromstring(xml_raw).findall( MintStudy.x...
465d9156be75144bacd1c84316660ea48a3f276e
17,701
def lookup_no_interp(x, dx, xi, y, dy, yi): """ Return the indices for the closest values for a look-up table Choose the closest point in the grid x ... range of x values xi ... interpolation value on x-axis dx ... grid width of x ( dx = x[1]-x[0]) (same for y) re...
cdee658cc50af9ba25902bdbe4274cd49a5c5d89
17,702
def advertisement_data_complete_builder(list_of_ad_entries): """ Generate a finalized advertisement data value from a list of AD entries that can be passed to the BLEConnectionManager to set the advertisement data that is sent during advertising. :param list_of_ad_entries: List of AD entries (can be bu...
c0f9040c36216cb519706c347d6644405fae0b7f
17,703
def process_vocab_table(vocab, vocab_size, vocab_threshold, vocab_lookup, unk, pad): """process vocab table""" default_vocab = [unk, pad] if unk in vocab: del vocab[unk] i...
fa4860aac095d531e39008da99d42059e38716ec
17,704
def get_mag_msg(stamp, mag): """ Get magnetometer measurement as ROS sensor_msgs::MagneticField """ # init: mag_msg = MagneticField() # a. set header: mag_msg.header.stamp = stamp mag_msg.header.frame_id = '/imu_link' # b. mag: ( mag_msg.magnetic_field.x, mag_ms...
ffa661ae168136fcbf626e08f85e19ba356a2e26
17,705
async def UserMeAPI( current_user: User = Depends(User.getCurrentUser), ): """ 現在ログイン中のユーザーアカウントの情報を取得する。<br> JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセスできない。 """ # 一番よく使う API なので、リクエスト時に twitter_accounts テーブルに仮のアカウントデータが残っていたらすべて消しておく ## Twitter 連携では途中で連携をキャンセルした場合に仮のア...
0a884c54d1e01b5ae9a31848b081566d35830de6
17,706
def midpt(pt1, pt2): """ Get the midpoint for two arbitrary points in space. """ return rg.Point3d((pt1[0] + pt2[0])/2, (pt1[1] + pt2[1])/2, (pt1[2] + pt2[2])/2 )
324e9fd6fe6ea257a130fcfe51eb73bf0957e57c
17,707
from collections import defaultdict from astropy.io import fits import siteUtils from bot_eo_analyses import make_file_prefix, glob_pattern,\ from bot_data_handling import most_common_dark_files def dark_current_jh_task(det_name): """JH version of single sensor execution of the dark current task.""" get_a...
a2d627b21340382018826bb583ad31c8509f9bbe
17,708
def tweetnacl_crypto_box_open(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_box_curve25519xsalsa2...
5b69127c70d3286c2c54b898d541db9f90c1ff51
17,710
def balanced_parentheses_checker(symbol_string): """Verify that a set of parentheses is balanced.""" opening_symbols = '{[(' closing_symbols = '}])' opening_symbols_stack = data_structures.Stack() symbol_count = len(symbol_string) counter = 0 while counter < symbol_count: current_...
04624d403f5af94c42122258df28363cb8bcf20d
17,711
from typing import Optional def _wrap_outcoming( store_cls: type, wrapped_method: str, trans_func: Optional[callable] = None ): """Output-transforming wrapping of the wrapped_method of store_cls. The transformation is given by trans_func, which could be a one (trans_func(x) or two (trans_func(self...
5ea4782f528c7822d8906cde415cc318353b54ba
17,712
import math def quantize(x): """convert a float in [0,1] to an int in [0,255]""" y = math.floor(x*255) return y if y<256 else 255
b941a11d0d6af3162c964568e2d97c8d81cd1442
17,713
import logging def initialize_logger(prefix): """ Initialization of logging subsystem. Two logging handlers are brought up: 'fh' which logs to a log file and 'ch' which logs to standard output. :param prefix: prefix that is added to the filename :return logger: return a logger instance """ ...
a6883736b17b9dc213bf4d26fd153fc8d0e11025
17,714
from typing import Optional import pickle def login(token_path: str) -> Optional[Credentials]: """ Trigger the authentication so that we can store a new token.pickle. """ flow = InstalledAppFlow.from_client_secrets_file( 'gcal/credentials.json', SCOPES) creds = flow.run_local_server(port=0...
72c7164297cfc17c661253f9496f8323cc3f217c
17,716
import requests def get_auth_token(context, scope): """ Get a token from the auth service to allow access to a service :param context: context of the test :return: the token """ secret = get_client_secret(context) data = { 'grant_type': 'client_credentials', 'scope': scope...
d36e66ed08f637f93b2f9226e7ccaeb9cbe07a2c
17,717
def getDefaultFontFamily(): """Returns the default font family of the application""" return qt.QApplication.instance().font().family()
408aa406d09dcc788bff46c3346307713f5b0fdf
17,718
def result(a, b, operator): """This function return result""" lambda_ops = { "+": (lambda x,y: x+y), "-": (lambda x,y: x-y), "*": (lambda x,y: x*y), "/": (lambda x,y: x/y), "//": (lambda x,y: x//y), "%": (lambda x,y: x%y), } r = False error = '' ...
febfacf3aa94bc15931cf79979329b3b1a5c7bc5
17,719
def get_deconv_filter(f_shape): """ reference: https://github.com/MarvinTeichmann/tensorflow-fcn """ width = f_shape[0] heigh = f_shape[0] f = ceil(width/2.0) c = (2 * f - 1 - f % 2) / (2.0 * f) bilinear = np.zeros([f_shape[0], f_shape[1]]) for x in range(width): for y in range...
ec0a5617ad149708d195ab4701860f12ef695de1
17,721
def twitter_split_handle_from_txt(tweet): """ Looks for RT @twitterhandle: or just @twitterhandle in the beginning of the tweet. The handle is split off and returned as two separate strings. :param tweet: (str) The tweet text to split. :return: (str, str) twitter_handle, rest_of_t...
1f98e5e5f2c1369ca673e6b15114f379786d1e8f
17,722
def points(piece_list): """Calculating point differential for the given board state""" # Args: (1) piece list # Returns: differential (white points - black points) # The points are calculated via the standard chess value system: # Pawn = 1, King = 3, Bishop = 3, Rook = 5, Queen = 9 # King = 100 (arbitrarily la...
d8f36fd887a846a20999a0a99ad672d2902473d4
17,723
def grid_sampler(x, grid, name=None): """ :alias_main: paddle.nn.functional.grid_sampler :alias: paddle.nn.functional.grid_sampler,paddle.nn.functional.vision.grid_sampler :old_api: paddle.fluid.layers.grid_sampler This operation samples input X by using bilinear interpolation based on flow field gri...
06c57d6e6d0a476b42b2472284368352fbd48bc3
17,724
def SpecSwitch(spec_id): """ Create hotkey function that switches hotkey spec. :param spec_id: Hotkey spec ID or index. :return: Hotkey function. """ # Create hotkey function that switches hotkey spec func = partial(spec_switch, spec_id) # Add `call in main thread` tag func = tag_...
20ba2ae59d717866474c236d0d97273755a035c8
17,726
def get_package_version() -> str: """Returns the package version.""" metadata = importlib_metadata.metadata(PACKAGE_NAME) # type: ignore version = metadata["Version"] return version
a24286ef2a69f60871b41eda8e5ab39ba7f756c0
17,727
def safe_name(dbname): """Returns a database name with non letter, digit, _ characters removed.""" char_list = [c for c in dbname if c.isalnum() or c == '_'] return "".join(char_list)
2ce4978c3467abaddf48c1d1ab56ed773b335652
17,728
def _parse_mro(mro_file_name): """Parse an MRO file into python objects.""" # A few helpful pyparsing constants EQUALS, SEMI, LBRACE, RBRACE, LPAREN, RPAREN = map(pp.Suppress, '=;{}()') mro_label = pp.Word(pp.alphanums + '_') mro_modifier = pp.oneOf(["in", "out", "src"]) mro_type = pp.oneOf([ ...
cf2561d1b72c2899fa495c2e83b683b7980b47ab
17,729
import math def tabulate_stats(stats: rl_common.Stats) -> str: """Pretty-prints the statistics in `stats` in a table.""" res = [] for (env_name, (reward_type, reward_path)), vs in stats.items(): for seed, (x, _log_dir) in enumerate(vs): row = { "env_name": env_name, ...
e853de6ac15e639d7348ee5a423afbdbbf296e7f
17,730
def LLR_binom(k, n, p0, EPS=1E-15): """ Log likelihood ratio test statistic for the single binomial pdf. Args: k : number of counts (numpy array) n : number of trials p0 : null hypothesis parameter value Returns: individual log-likelihood ratio values """ phat = ...
a423b81a374398b88881ee45a665e7f9a648c4c1
17,731
def concatenate_shifts(shifts): """ Take the shifts, which are relative to the previous shift, and sum them up so that all of them are relative to the first.""" # the first shift is 0,0,0 for i in range(2, len(shifts)): # we start at the third s0 = shifts[i-1] s1 = shifts[i] s1.x += s0.x s1.y +=...
f4b0a41db1db78e3b5f25ca198fdb6cebd6476ca
17,732
import json import hashlib def users(user_id=None, serialize=True): """ The method returns users in a json responses. The json is hashed to increase security. :param serialize: Serialize helps indicate the format of the response :param user_id: user id intended to be searched :return: Json forma...
b939860a7e8794f8e53f63594a3000a0425cb319
17,733
def get_namenode_setting(namenode): """Function for getting the namenode in input as parameter setting from the configuration file. Parameters ---------- namenode --> str, the namenode for which you want to get the setting info Returns ------- conf['namenodes_setting'][namenode] --...
e389d7a20a7b0ef7f32b51c7bb31068cb152fc2b
17,736
from typing import Tuple def cds(identity: str, sequence: str, **kwargs) -> Tuple[sbol3.Component, sbol3.Sequence]: """Creates a Coding Sequence (CDS) Component and its Sequence. :param identity: The identity of the Component. The identity of Sequence is also identity with the suffix '_seq'. :param seque...
15d99917b840cf2881e1a90c1835c356622511a7
17,737
import math def calc_innovation(xEst, PEst, y, LMid): """ Compute innovation and Kalman gain elements """ # Compute predicted observation from state lm = get_landmark_position_from_state(xEst, LMid) delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] y_angle = math.atan2(delta[1, 0], d...
146695c107c46d2736d0e4ecc191d9a399ca8159
17,739
from typing import Any def next_key(basekey: str, keys: dict[str, Any]) -> str: """Returns the next unused key for basekey in the supplied dictionary. The first try is `basekey`, followed by `basekey-2`, `basekey-3`, etc until a free one is found. """ if basekey not in keys: return baseke...
e1da51c79fd465088294e053fdc970934268211b
17,740
import yaml def load_mmio_overhead_elimination_map(yaml_path): """ Load a previously dumped mmio overhead elimination map """ with open(yaml_path, "r") as yaml_file: res = yaml.safe_load(yaml_file.read()) res_map = { 'overall': res[0]['overall'], 'per_model': res[1]['per_m...
ae0ead1aa8c9f26acad9a23a35791592efbfe47e
17,741
from MoinMoin.util import diff_html from MoinMoin.util import diff_text def execute(pagename, request): """ Handle "action=diff" checking for either a "rev=formerrevision" parameter or rev1 and rev2 parameters """ if not request.user.may.read(pagename): Page(request, pagename).send...
7305385a84c561fc6c5a8b0e8c52635cf19c77d6
17,742
def SetBmaskName(enum_id, bmask, name): """ Set bitmask name (only for bitfields) @param enum_id: id of enum @param bmask: bitmask of the constant @param name: name of bitmask @return: 1-ok, 0-failed """ return idaapi.set_bmask_name(enum_id, bmask, name)
2a134b496214d7f8e8887dc5a3ca93264da08f5b
17,743
import math def angle_to(x: int, y: int) -> int: """Return angle for given vector pointing from orign (0,0), adjusted for north=0""" #xt,yt = y,x #rad = math.atan2(yt,xt) rad = math.atan2(x,y) if rad < 0.0: rad = math.pi + (math.pi + rad) return rad
545cfa3769da10eea2138132295e3387c4556b39
17,744
import torch def adj(triples, num_nodes, num_rels, cuda=False, vertical=True): """ Computes a sparse adjacency matrix for the given graph (the adjacency matrices of all relations are stacked vertically). :param edges: List representing the triples :param i2r: list of relations :param i2n...
8531170c20c39011efcc7a2223c4da49c41ffabb
17,746
def join_b2_path(b2_dir, b2_name): """ Like os.path.join, but for B2 file names where the root directory is called ''. :param b2_dir: a directory path :type b2_dir: str :param b2_name: a file name :type b2_name: str """ if b2_dir == '': return b2_name else: return b2...
20f4e6e54f7f3b4a1583b503d4aa2d8995318978
17,747
def actual_line_flux(wavelength,flux, center=None,pass_it=True): """Measure actual line flux: parameters ---------- wavelength: float array flux: float array center: float wavelength to center plot on output parameters ----------------- flux in line integrated over ...
6d4d36e6e632e605158da704cc1e3462cdc173e1
17,748
def _too_many_contigs(ref_file): """Check for more contigs than the maximum samblaster deduplication supports. """ max_contigs = 32768 return len(list(ref.file_contigs(ref_file))) >= max_contigs
03a01719b634d6eea143306f96cae6ea26e3f1f9
17,749
def survival_regression_metric(metric, outcomes_train, outcomes_test, predictions, times): """Compute metrics to assess survival model performance. Parameters ----------- metric: string Measure used to assess the survival regression model performance. Options include:...
244767ca0533af2fe792fe226fb2a9eb5e166201
17,750
import signal def _get_all_valid_corners(img_arr, crop_size, l_thresh, corner_thresh): """Get all valid corners for random cropping""" valid_pix = img_arr >= l_thresh kernel = np.ones((crop_size, crop_size)) conv = signal.correlate2d(valid_pix, kernel, mode='valid') return conv > (corner_thresh...
6e357a6585e8485de74e01ced62eedcbfe33bdec
17,751
def remove_dup(a): """ remove duplicates using extra array """ res = [] count = 0 for i in range(0, len(a)-1): if a[i] != a[i+1]: res.append(a[i]) count = count + 1 res.append(a[len(a)-1]) print('Total count of unique elements: {}'.format(count + 1)) return ...
8286c07098c078cd61d4890cd120723b9e9f04e7
17,752
def mjd2crnum(mjd): """ Converts MJD to Carrington Rotation number Mathew Owens, 16/10/20 """ return 1750 + ((mjd-45871.41)/27.2753)
233f91e6de4c5105732fc2c8f9f33d054491e1d2
17,753
def poly_print_simple(poly,pretty=False): """Show the polynomial in descending form as it would be written""" # Get the degree of the polynomial in case it is in non-normal form d = poly.degree() if d == -1: return f"0" out = "" # Step through the ascending list of co...
903f9d4a703e3f625da5f13f6fe084e8894d723b
17,754
def parse_file_(): """ Retrieves the parsed information by specifying the file, the timestamp and latitude + longitude. Don't forget to encode the plus sign '+' = %2B! Example: GET /parse/data/ecmwf/an-2017-09-14.grib?timestamp=2017-09-16T15:21:20%2B00:00&lat=48.398400&lon=9.591550 :param fileName:...
be54ab0dc3b9ec0a0f5462684f66d209e6e72728
17,755
def make_model(drc_csv: str, sat_tables: list, sector_info_csv: str, ia_tables=None, units_csv='', compartments_csv='', locations_csv='') -> model.Model: """ Creates a full EE-IO model with all information required for calculations, JSON-LD export, validation, etc. :param ...
f990f1617de29f75e4f86acc7647f7d9a06bfa53
17,756
def newNXentry(parent, name): """Create new NXentry group. Args: parent (h5py.File or h5py.Group): hdf5 file handle or group group (str): group name without extension (str) Returns: hdf5.Group: new NXentry group """ grp = parent.create_group(name) grp.attrs["NX_class"]...
1529fbe80ca8a23f8cd7717c5df5d7d239840149
17,757
from datetime import datetime def _build_europe_gas_day_tzinfo(): """ Build the Europe/Gas_Day based on the CET time. :raises ValueError: When something is wrong with the CET/CEST definition """ zone = 'Europe/Gas_Day' transitions = _get_transitions() transition_info_cet = _get_transition...
abc83bc3096c0dacfb7d9be88fdf4043ee328cf1
17,758
from typing import Set from typing import Optional from typing import List from typing import Dict def prepare_variants_relations_data( queryset: "QuerySet", fields: Set[str], attribute_ids: Optional[List[int]], warehouse_ids: Optional[List[int]], ) -> Dict[int, Dict[str, str]]: """Prepare data ab...
37c275898bb69fc61cbdddf2f4914ac77f22e7ed
17,759
import torch def vnorm(velocity, window_size): """ Normalize velocity with latest window data. - Note that std is not divided. Only subtract mean - data should have dimension 3. """ v = velocity N = v.shape[1] if v.dim() != 3: print("velocity's dim must be 3 for ba...
69f3c8cd6a5628d09a7fd78f3b5b779611a68411
17,760
import torch def valid_collate_fn(data): """Build mini-batch tensors from a list of (image, caption) tuples. Args: data: list of (image, caption) tuple. - image: torch tensor of shape (3, 256, 256). - caption: torch tensor of shape (?); variable length. Returns: im...
3eabc71d3ae68d4ca24d1a146be4fab8543c8566
17,761
def parse_statement(tokens): """ statement: | 'while' statement_list 'do' statement_list 'end' | 'while' statement_list 'do' 'end' | 'if' if_body | num_literal | string_literal | builtin | identifier """ if tokens.consume_maybe("while"): condition = parse_...
dfa26e4b834104a85b7266628fb6635c86e64b09
17,762
def vector_to_pytree_fun(func): """Make a pytree -> pytree function from a vector -> vector function.""" def wrapper(state): return func(Vector(state)).pytree return wrapper
79cc16c0e9187fc3bb944f40433ba1bd7850cb6e
17,763
def _filter_contacts(people_filter, maillist_filter, qs, values): """Helper for filtering based on subclassed contacts. Runs the filter on separately on each subclass (field defined by argument, the same values are used), then filters the queryset to only keep items that have matching. """ peop...
704396156370596433e78be1bb7bf5b4a77f284d
17,764
def viz_property(statement, properties): """Create properties for graphviz element""" if not properties: return statement + ";"; return statement + "[{}];".format(" ".join(properties))
518d4a662830737359a8b3cb9cec651394823785
17,765
def create_fsl_fnirt_nonlinear_reg(name='fsl_fnirt_nonlinear_reg'): """ Performs non-linear registration of an input file to a reference file using FSL FNIRT. Parameters ---------- name : string, optional Name of the workflow. Returns ------- nonlinear_register : nipype.pip...
dcb723e8fc33df2c8cc167c2bedc72f802d124c5
17,766
def _subspace_plot( inputs, output, *, input_names, output_name, scatter_args=None, histogram_args=None, min_output=None, max_output=None ): """ Do actual plotting """ if scatter_args is None: scatter_args = {} if histogram_args is None: histogram_args = {} if min_output ...
720092b24f1675f4f4c64c206cd7cad8b3a6dee6
17,767
def install_microcode_filter(*args): """ install_microcode_filter(filter, install=True) register/unregister non-standard microcode generator @param filter: - microcode generator object (C++: microcode_filter_t *) @param install: - TRUE - register the object, FALSE - unregister (C++: ...
e51c4f5bcc749692bd69c0d9024e6e004da9e9ac
17,770
def get_marvel_character_embed(attribution_text, result): """Parses a given JSON object that contains a result of a Marvel character and turns it into an Embed :param attribution_text: The attributions to give to Marvel for using the API :param result: A JSON object of a Marvel API call result :r...
ed315c2581de86f539c7a08ff6c37e9a889f2670
17,771
def get_or_create_dfp_targeting_key(name, key_type='FREEFORM'): """ Get or create a custom targeting key by name. Args: name (str) Returns: an integer: the ID of the targeting key """ key_id = dfp.get_custom_targeting.get_key_id_by_name(name) if key_id is None: key_id = dfp.create_custom_targ...
36211d5a383d54fde3e42d30d81778008343c676
17,772
def positive(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in positive") return Array._new(np.positive(x...
2caa9b1714c549e390dba494a748aa86d5077d67
17,773
import csv def read_loss_file(path): """Read the given loss csv file and process its data into lists that can be plotted by matplotlib. Args: path (string): The path to the file to be read. Returns: A list of lists, one list for each subnetwork containing the loss values over ti...
8e861f0bf46db5085ea2f30a7e70a4bdfa0b9697
17,774
from typing import Union def number2human(n: Union[int, float]) -> str: """ Format large number into readable string for a human Examples: >>> number2human(1000) '1.0K' >>> number2human(1200000) '1.2M' """ # http://code.activestate.com/recipes/578019 # >>> by...
26e99ca6b3cf51bf554018e1c97a1c8bebd51811
17,775
def binomial_confidence_interval(successes, trials, error_rate): """Computes a confidence interval on the true p of a binomial. Assumes: - The given `successes` count outcomes of an iid Bernoulli trial with unknown probability p, that was repeated `trials` times. Guarantees: - The probability (over the ...
03caf19e30a4b280c6b060b7ba4b1166b526feec
17,776
def try_parse_func_decl(start, end): """Parse a function declarator between start and end. Expects that tokens[end-1] is a close parenthesis. If a function declarator is successfully parsed, returns the decl_node.Function object. Otherwise, returns None. """ open_paren = find_pair_backward(end ...
1bcdce513fdaf6e28e034ba1578bd271a00c31a5
17,777
import contextlib def eth_getBlockTransactionCountByNumber(block_number: int) -> int: """ See EthereumAPI#get_block_transaction_count_by_number. """ with contextlib.closing(EthereumAPI()) as api: return api.get_block_transaction_count_by_number(block_number)
d4fbd368bb49854ceee589ba20c956275ece95c6
17,778
from typing import List from typing import Any from typing import NamedTuple def day(db: Database, site: str = 'test', tag: str = '', search_body: str = '') -> List[Any]: """ 戻り値 名前付きタプルのリスト # xxx List[DayCount] するにはclass DayCount(NamedTuple) 必要 pypy… """ tag_where = '' body_where = '' param = [site] # type: L...
c60a4a8aabc546a2dc7b412d73c1d0a97d7ccc25
17,779
import math def ppv2( aim_stars=None, speed_stars=None, max_combo=None, nsliders=None, ncircles=None, nobjects=None, base_ar=5.0, base_od=5.0, mode=MODE_STD, mods=MODS_NOMOD, combo=None, n300=None, n100=0, n50=0, nmiss=0, score_version=1, bmap=None ): """ calculates ppv2 returns (pp, aim_...
c4cc793b7eb2acc45ca83762f946a476452a5e34
17,781
def p_portail_home(request): """ Portail d'accueil de CRUDY """ crudy = Crudy(request, "portail") title = crudy.application["title"] crudy.folder_id = None crudy.layout = "portail" return render(request, 'p_portail_home.html', locals())
a883cafd84b1ce24ead37ebbe6c0e3a15ea476c6
17,783
def A_norm(freqs,eta): """Calculates the constant scaling factor A_0 Parameters ---------- freqs : array The frequencies in Natural units (Mf, G=c=1) of the waveform eta : float The reduced mass ratio """ const = np.sqrt(2*eta/3/np.pi**(1/3)) return const*freqs**-(7/6)
74947e34efd7b6b0bb31aac35c9932623d4a28aa
17,785
from typing import IO from typing import Counter from operator import sub def task1(input_io: IO) -> int: """ Solve task 1. Parameters ---------- input_io: IO Day10 stream of adapters joltage. Return ------ int number of differentes of 1 times number of diferences...
b566a79013f442b7216118458958212186e57f07
17,786
def get_total_balance(view_currency='BTC') -> float: """ Shows total balance for account in chosen currency :param view_currency: currency for total balance :return: total balance amount for account """ result = pay.get_balance() balance_dict = result.get('balance') total = 0 for cur...
9e595eceac7df63779cd8c8e6d155092ec76a36e
17,788
import binascii def bin_hex(binary): """ Convert bytes32 to string Parameters ---------- input: bytes object Returns ------- str """ return binascii.hexlify(binary).decode('utf-8')
41f9c8a498aa3628f64cf59c93896f42d8dfd56a
17,789