content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def shib_ds_context(context): """ Creates a dictionary with information: * ServiceProvider login handler * IdPs from cookie """ shib_ds = get_context(context.request) return shib_ds
952b844bce2fc85777f4ebd4ba8c963dc7f10d3a
51,943
import warnings def __getattr__(name): # noqa: N807 """Get attribute.""" deprecated = __deprecated__.get(name) if deprecated: warnings.warn( "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]), category=DeprecationWarning, stacklevel=(3 if PY37...
629e1981c0a000e358fcb9d8f55799c5e2302307
51,944
async def hub_pod(kube_client, kube_ns): """Create and return a pod running jupyterhub""" return await create_hub_pod(kube_client, kube_ns)
b6dbb291a988a351857aa7e41b6e53324d8ecd55
51,945
import hashlib def _hash_file(fpath, chunk_size=65535): """ Calculates the md5 hash of a file :param fpath: path to the file being validated :param chunk_size: Bytes to read at a time (leave unless large files) :return: The file hash """ hasher = hashlib.md5() with open(fpath, 'rb') ...
9f17f13f487f95620ad705a6f2b23d57407e640e
51,947
def GetIcon(name, module=None): """ wx.Icon GetIcon(iconName, module=None) Get an icon from a file, possibly prepending the module's path """ name=modPath(name, module) return wx.Icon(name + ".ico")
1dec574112375ff7ec6d3a0ac4f438a3135e37dd
51,948
def midpoint(start, end): """Find the mid-point between two points.""" x0, y0 = start x1, y1 = end return (x0+x1)/2, (y0+y1)/2
dab5a66b8af759998a295d64ba3711b6e99e4c27
51,949
def scatterplot(custom_x, custom_y, xlabel=None, ylabel=None, **kwargs): """ Custom x-y plotting using VESIcal's built-in plot() function, built on Matplotlib's plot and scatter functions. Parameters ---------- custom_x: list List of groups of x-values to plot as points or lines custom_y: list List of group...
ca543f9c0e834a9caf353b17005e3056a9d75a3d
51,950
def presale_crowdsale_miletstoned(chain, presale_fund_collector, uncapped_flatprice, presale_milestone_pricing, team_multisig): """ICO associated with the presale where funds will be moved to a presale. We set a special milestone pricing that allows us to control the pricing for the presale participants. "...
2ae798f0e28944625fa7724218ab52132a385a20
51,951
def dict_populate_loop(pattern): """ Args: pattern: array of tokens that represents the tokens. Returns: updated_dic: a dictionary that contains all the keywords from docstrings. """ updated_dic = {} for token in pattern: if isinstance(token, docopt_util.Branch): ...
81f1d38eba5d1e65721c15d6f9178c8568440c83
51,952
def visualize_farm( plane, nr_points, size_x, size_y, title="", ax=None, vmax=False): """ Function to plot flow-field around a wind farm. Args: plane (2d numpy array): Flow field of wind farm nr_points (list or np array): List of nr of points in x and y size_x (int): Size o...
9c7dfa1bc211b31d5dcdd3b882b5c848a3e8c7a0
51,953
from typing import Tuple def oov_rate( targets: jnp.ndarray, oov_values: Tuple[int, ...], mask_values: Tuple[int, ...] = ()) -> MeanMetric: """Computes proportion of non masked tokens that are out of vocabulary. Args: targets: Target values of shape [batch_size, sequence_length, ...]. oov_val...
33c35004dfbfab02b4c95d9c73b0c8d447828a19
51,954
import pathlib def hash_to_path(kind: str, rep: str) -> pathlib.Path: """Derive path from content rep hash and create any folder required.""" if kind not in KINDS.values(): raise ValueError(f'unknown {kind=} for {rep=}') folder = DB_OUT_ROOT / kind / rep[:2] folder.mkdir(parents=True, exist_ok...
cbe7c25a46c42711d8a77fcc034f5c1191a692fc
51,957
def mirror_edges(img, psf=3): """Given a 2D image, boundaries are padded by mirroring so that the dimensions of the image are multiples for the width of the point spread function. Args: img (np.array): Image to mirror edges. psf (int): Size of point spread function in pixels. Retur...
1d9d85bf32a3a5cf560c4add866a053057fb5b72
51,960
def _srg_rhs_old(s, potential, kinetic, potential_weight, weights, flow, verbose): """Old implementation of SRG flow equation. New implementation is more efficient and reflects actual form better. Keeping this for documentation and as reference for analytic evaluation of flow equation ...
c4ee5fdafa7a11c95d3e5d0e3c83058b862a3ba9
51,961
def compute_taproot_address(pubkey, scripts): """Compute the address for a taproot output with given inner key and scripts.""" tap = taproot_construct(pubkey, scripts) assert tap.scriptPubKey[0] == 0x51 assert tap.scriptPubKey[1] == 0x20 return encode_segwit_address("bcrt", 1, tap.scriptPubKey[2:])
709a83f131a7de4bbdaad790a96561074d7cfdae
51,962
def perplexity_w_prior(probabilites, smi, d_prior, remove_end=True): """ Compute the perplexity of a SMILES given a list of probabilities. probabilites: (list) of probabilities smi: (str) a SMILES d_prior: (dict) with keys: SMILES characters, and value the prior probability to sample the...
cfb33fa8f031c0c323cb62ca7c1639c97a2c903f
51,963
def plot_model_timing(title, data_sizes, fit_scores, predict_scores, ylim=None): """ Generate a simple plot of the given model timing data Parameters ---------- title : string Title for the chart. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues pl...
3e59c3e6ee354568ae37366ded944c2646acf152
51,964
def _get_int64(data, position, dummy0, dummy1, dummy2): """Decode a BSON int64 to bson.int64.Int64.""" end = position + 8 return Int64(_UNPACK_LONG(data[position:end])[0]), end
7f2d8f1939fc20848a1323aaa29210dbeaa39451
51,965
import click def set_pin(ctx, pin, new_pin, u2f): """ Set or change the PIN code. The FIDO2 PIN must be at least 4 characters long, and supports any type of alphanumeric characters. On YubiKey FIPS, a PIN can be set for FIDO U2F. That PIN must be at least 6 characters long. """ cont...
50a4a64fa22c2b8d416bf65d1bd0e7eb5fb226c1
51,966
def verify_proof(db_contract, proof, received): """This queries the DB to retrieve the heartbeat, state and challenge for the contract id, and then checks the given proof. Returns true if the proof is valid. Can also return false if the contract is expired or if an ip address change has been rejected ...
c0b31202425c8f0ee600e056353386f17cfbacb4
51,967
import signal def low_pass_butter4(freqs, tod, fc): """4th-order low-pass filter with f3db at fc (Hz). """ b, a = signal.butter(4, 2*np.pi*fc, 'lowpass', analog=True) return np.abs(signal.freqs(b, a, 2*np.pi*freqs)[1])
df7bc610fd57c4af287bee310175e84868123ab7
51,968
def get_functions(funcset=None): """ Return a dict of variables """ c0 = funcset in _DFUNC.keys() if c0 is not True: lstr = [ "\t- '{}': {}".format(k0, sorted(v0.keys())) for k0, v0 in _DFUNC.items() ] msg = ( "Arg varset must be a valid key to an ...
5313ffd9768952acd16f9da503679ff537541827
51,969
import re def replace_pair(pair, content): """ Uses regex to locate a pair. First element of the tuple is the original error token. Second element of the tuple is the replacement token. """ return re.sub(pair[0], ' {} '.format(pair[1]), content)
022633d417393959a94629117a1e664709770571
51,971
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, hvd=None, manual_fp16=False, use_fp16=False, num_accumulation_steps=1, optimizer_type="adam", allreduce_post_accumulation=False): """Creates an optimizer training op.""" global_step = tf.train.get_or_create_global_step() ...
9a1b889cf6346fc5220c7b7c63dc20363b841765
51,972
def load_positions_from_timepoints_file(path): """Load a text file of timepoint pseudo-paths into a list of Positions. The file is expected to be lines of pseudo-paths of the form: /path/to/experiment_root/position_name/timepoint_name where: /path/to/experiment_root/position_name is a valid pat...
0e39b7fd2159e2b664c237920fc378a44d7c9240
51,974
def trace_condition_function(condition: ConditionCheckerType) -> ConditionCheckerType: """Wrap a condition function to enable basic tracing.""" @ft.wraps(condition) def wrapper(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Trace condition.""" with trace_condition(vari...
629f6d2a17dd48167da2ce4a04747d35b47d0ee2
51,976
from datetime import datetime import requests def log_me_in(base_url, username=None): """ :param username: :returns cookies :param base_url: :return: """ add_url = "/geo/init" if username is None: user_data = {"userName": "python " + str(datetime.now())} else: user_...
ed6e767548a61f0c7086db5fe45b12ac75df5498
51,977
from niworkflows.interfaces.reportlets.registration import ( SimpleBeforeAfterRPT as SimpleBeforeAfter, ) from niworkflows.interfaces.reportlets.masks import ROIsPlot from smriprep.interfaces.templateflow import TemplateFlowSelect from smriprep.workflows.outputs import ( _fmt, _empty_report, _rpt_ma...
df39d46731213a8313b5eaa1701f302df3d14a94
51,978
from datetime import datetime def extract_sitename_date(directory_path, sitename_location, datetime_location): """Extract sitename and datetime from directory path name. Parameters ----------- directory_path : string A path to the directory ...
86a2085ba68b234585ef9855da64fa1fdd5459ce
51,979
from typing import List from typing import Optional def make_blanks(spans: List[Span], length: Optional[int] = None, fill: str = TokenFunction.OUTSIDE) -> List[str]: """Create a list of outside tags that we can populate with tags generated from spans. Args: spans: The list of spans that will eventual...
36e6b225ff55da66c9192c87e6697bf75af842ad
51,980
from datetime import datetime def month_holidays(year, month): """ その月の祝日日、祝日名を返します。 """ date = datetime.date(year, month, 1) output = [] while date.month == month: name = is_holiday_name(date) if name is not None: output.append((date, name)) date = date +...
f74bd3f6600b9c82140808ba5061e20a46619b33
51,982
def collection_test(in_dim1, in_dim2, channels, out_dim): """ Return a small collection of models and their names """ names = [] for a in range(1, 3): for b in range(3): n1 = a * 8 n2 = b * 8 m_str = str(n1) if n...
d46033bc26acf02a1faacc8b37a314d2b0e58ea2
51,983
def favourites_add(request): """ Function to add recipe to favourites. This function is used via AJAX. """ user = request.user title = request.POST.get('title') recipe_id = request.POST.get('recipe_id') image_url = request.POST.get('image_url') favourite, created = Recipe.objects.get...
315773153f1135b7ef677a1c84d3371e9114cb5a
51,984
def read_chain_header(line): """ Convenience wrapper to parse chain header information :param line: :return: """ _, score, tName, tSize, tStrand, tStart, tEnd, qName, qSize, qStrand, qStart, qEnd, chainid = line.strip().split() return Chain(tName, int(tSize), tStrand, int(tStart), int(tEnd),...
f2d43234d26d61d90995a0cb8ab741734fbf1c4b
51,985
async def get_host_by_slug(host_slug: constr(strip_whitespace=True)): """Retrieve a Host object, based on Host slug string, containing: Host ID, name, slug string, and gender.""" try: host = Host(database_connection=_database_connection) host_info = host.retrieve_by_slug(host_slug) i...
d05319f9e8224584b54210d0a78ee7649d881cca
51,986
def cleanup_text(line: str) -> str: """ Args: line: text line of the opinion Returns: text line where not alphabetical characters removed """ corrections = {"&quot": "", "&amp": ""} line_lower = line.lower() for wrong, cor in corrections.items(): line_lower = lin...
3414fb429ea76aabcfc06ae57aca9c2cadfcc96f
51,988
def send_mail(to_mail, mail_subject, mail_body): """ Function to send a mail using Sendgrid API Parameters: arg1 (string): The recipient's email address. arg2 (string): The subject of the mail. arg3 (string): The body of the mail. """ message = Mail( from_email=current_app.con...
c8f2a1796bbb0584ae4370af8af2d7eb7c6b5bbd
51,989
from run4it.api.scripts import script_token_registry_purge as script_func def token_cleanup(): """Removes revoked and expired tokens from database""" return script_func('token_cleanup')
ec2876a20cca14e271b7036ec35b7f64af8e6021
51,991
import requests import json def get_vlans(ip, port, username, password) -> list: """Gets device components /restconf/data/openconfig-platform:components""" data = [] uri = f"https://{ip}:{port}/restconf/data/Cisco-IOS-XE-vlan-oper:vlans" response = requests.get(uri, headers=headers, verify=False, au...
72130eac7fb103956e97b9e8dd09e54034f9075e
51,992
import time import random import traceback def _run_work_order_fn(zap_id, work_order_i): """ Wrap the function to handle args, kwargs, capture exceptions, and re-seed RNG. Note: This may run in the sub-process or thread and therefore should not use stdio. """ start_time = time.time() try: ...
38c2b705fc8a38d04d18670e746c0edb550c6612
51,993
def head(path, lines=10): """ Get the first lines of a file. Args: path (str): Path to the file to read. lines (int): Number of lines to read. Returns: :obj:`list` of :obj:`str`: The lines found. """ with open(path) as f: return list(islice(f, lines))
829c7c910798e967cea0d40aef43ed21ee4ff421
51,994
def ntg_collate(data): """Creates mini-batch tensors from the list of tuples (src_seq, trg_seq).""" # separate source and target sequences src_sent,tgt_sent = list(zip(*data)) # t2i _inputs = [batch_sentences(src_sent), batch_sentences(tgt_sent), ] return _inputs
ea2a9900bdc3e1cdc5dc3889a8c6bfb8d8f232db
51,995
def FnutoFlambda(Fnu, wavelength): """ Converts F_nu to F_lambda. :param Fnu: Fnu [ers/s/cm**2/Hz] :type Fnu: float or ndarray :param wavelength: wavelength [AA] :type wavelength: float or ndarray :return: Flambda [ergs/s/cm**2/AA] """ return Fnu / wavelength / wavelength * C
78b1775aa391c5cc9441684f109203be0af41ce9
51,996
import torch def PSNR(gt, img, drange): """ Computes the highest PSNR by affine rescaling of x, such that the mean squared error to gt is minimal. :param gt: ground truth :param img: image :param drange: data range :return: PSNR """ img = normalize_minmse(img, gt) mse = torch....
69296c1b563371cf4dfc5b8a59bff50f922088b5
51,997
def get_postgres_connection_url() -> str: """ Собирает ссылку для подключения к БД и возращает её. """ db = POSTGRES_DB host = POSTGRES_HOST port = POSTGRES_PORT user = POSTGRES_USER password = POSTGRES_PASSWORD if not all([db, host, port, user, password]): raise DatabaseSetting...
a637f5a108ec7b1a0f696a41d457d284b2a28eae
51,998
def check_if_string_in_file(file_name, string_to_search): #string checker """ Check if any line in the file contains given string """ # Open the file in read only mode with open(file_name, 'r') as read_obj: # Read all lines in the file one by one for line in read_obj: # For each ...
9cc958279cbfab75273ef122603df378ffa55038
51,999
import torch from typing import Tuple def count_per_domain_statistics( domain_idxs: torch.Tensor ) -> Tuple[np.ndarray, np.ndarray]: """ Args: - domain_idxs: Pytorch tensor of shape (N,) showing assignment of each example to each particular domain Returns: -...
4e900e1f611e942a07efc17481462e025bfa4e10
52,000
def handler500(request): """ This is a Django handler function for the 500 server error page. Because a server error can imply an serious issue such as corrupted database, a nice render of the 500 page may be impossible. So the server first attemps to nicely render the page with all the dynamic element,...
5e818aa9ab9d3ebaef2d843e8b32cfd3da90941c
52,001
def featurenet_backbone(input_tensor=None, input_shape=None, n_filters=32, **kwargs): """Construct the deepcell backbone with five convolutional units Args: input_tensor (tensor): Input tensor to specify input size n_filters (int): Defaults to 32. Number of filters for ...
653646aa594c174ea3f0050401dbca176315fc49
52,002
from typing import Optional def call_somewhat_forgivingly( func, args, kwargs, enforce_sig: Optional[SignatureAble] = None ): """Call function on given args and kwargs, but with controllable argument leniency. By default, the function will only pick from args and kwargs what matches it's signature, ig...
c2c32cd0b1e8cedc3bcdf030e81d90777a303a54
52,003
from typing import List def _get_list_of_layers( input_dim: int, hidden_dim: int, output_dim: int, num_layers: int ) -> List[nn.Module]: """Utility function to get a list of layers. This assumes all the hidden layers are using the same dimensionality. Args: input_dim (int): input dimension. ...
9d30258aa06c39e76ddb1b9d96fb699d85b48d22
52,005
import scipy import numpy def LagrangeMultiplierMethod(H, f): """ LEXMIN Solve the multi-objective minimization problem: min {E1(x), E2(x), ... , Ek(x)} x where Ei = 0.5 * x.T * H[i] * x + x.T * f[i] and Ei is deemed "more important" than Ei+1 (lexicographical ordering): ...
6a557dc153e3b291eb8b2c9f1c85e3baf1eff091
52,006
def rescale_to_11bits(im_float): """Rescale a float image in [0, 1] to integers in [0, 2047]. This operation makes rank filtering much faster. Parameters ---------- im_float : array of float in [0, 1] The float image. The range and type are *not* checked prior to conversion! R...
ec15a3599b03184ee520f61e29f40bb0cbb24581
52,007
import re def get_data(session_id, n_intervals): """Query Database and prepare data as DataFrame. Parameters ---------- session_id : str unique session id hex used for caching. interval : int update interval from counter used for updating data. Returns ------- df : pa...
c84253c0e6838b68454e228395f6a7bca578d282
52,008
def multi_dict_unpacking(lst): """ Receive a list of dictionaries, join them into one big dictionary """ result = {} for d in lst: for key, val in d.items(): result[key] = val return result
530947224d682cffb809e83f308a97a108002080
52,009
import math def dist(a: list, b: list) -> float: """Calculate the distancie between 2 points Args: a (list): point a b (list): point b Returns: float: Distance between a and b """ return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)
7ad6d2f36c0bccee106c7b54a4abebd246c4a3fa
52,010
def is_array_like(item): """Check if item is an array-like object.""" return isinstance(item, (list, set, tuple, np.ndarray))
7176330220ca903a38d28710053aee6c4edf9df5
52,011
async def verifyGroupPath(h5path): """ create any groups along the path that doesn't exist """ #print("current task: ", asyncio.Task.current_task()) client = globals["client"] domain = globals["domain"] h5path_cache = globals["h5path_cache"] params = {"host": domain} parent_group = h5pat...
5c5c5bc4984b1e58e7008142aa5a0d42ba280921
52,012
def coord(x, y, integer=False): """ Convert world coordinates to pixel coordinates. Setting 'integer' to True will return integer coordinates. """ xs = (DRAW_OFFSET[0] + DRAW_SCALE*x) ys = (DRAW_OFFSET[1] - DRAW_SCALE*y) if integer: return int(round(xs)), int(round(ys)) else: ...
7962dcf2dcbf16dfaaa7fd553ce99530f096106a
52,015
def handle_match(match, url): """Should there be a match, format a message and send a notification.""" if match: message = "Match found at {}:\n{}".format(url, match) return __send_notification(url, message) else: return 'Missing match at: {}'.format(url)
bd019baa184df41a209b19549074b38127ba29b6
52,016
import requests import io def call_model(model_type="mosaic", file_path="tests/flowers.jpg"): """helper function""" model_endpoint = 'http://localhost:5000/model/predict?model=' + model_type with open(file_path, 'rb') as file: file_form = {'image': (file_path, file, 'image/jpeg')} r = re...
47a5038de6f56c4ae6c099803b8cffc9482ed9f4
52,017
from bs4 import BeautifulSoup def get_soup(url): """Gets BS object from the given URL""" # - Get Data html = get_data(url) # - Get Soup soup = BeautifulSoup(html, 'html.parser') if soup is None: raise Exception("No data from URL") return soup
00b0ef5379e470b5603da54e93aa0d878132d41a
52,018
def node_wise_2_sample(latent, node_ind): """Get dcorr t stat for a single node""" node_latent_pop1 = np.squeeze(latent[:n_graphs, node_ind, :]) node_latent_pop2 = np.squeeze(latent[n_graphs:, node_ind, :]) t_stat = compute_t_stat(node_latent_pop1, node_latent_pop2) return t_stat
a1939f474d7407c92aea0eb4b0a6fdb30cf60045
52,019
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='', html_message='', scheduled_time=None, headers=None, template=None, priority=None, commit=True, backend=''): """ Creates an email from supplied keyword arguments. If template is specified, email su...
4bfe19949c0c07b34d9a5443c5aee8afb785dcca
52,021
from typing import Dict from typing import Union from typing import Set def get_fields_eligible_for_pagination( schema_info: QueryPlanningSchemaInfo, types: Dict[VertexPath, Union[GraphQLObjectType, GraphQLInterfaceType]], single_field_filters: Dict[PropertyPath, Set[FilterInfo]], fold_scope_roots: Di...
a9b606bb5f44fcb8ae3cfdbe2678f359e83e3a45
52,022
import re def _parse_commit_position(commit_message): """Parses a commit message for the commit position. Args: commit_message: The commit message as a string. Returns: An int if there is a commit position, or None otherwise.""" match = re.search( '^Cr-Commit-Position: [a-z/]...
7f4d93f8fc88a18276570f2d33ff2fbb75673025
52,023
from typing import Any def convert_simple_type(value: Any, json_definition: dict) -> Any: """ :param value: Can be of any JSON type except list or dict. :param json_definition: OpenAPI definition of the value (format used to parse it). """ if isinstance(value, str): field_format = json_def...
0d83275efa3cc2320d21ed8fb848ee3b2931aa91
52,024
import torch def block_diag(m): """ Make a block diagonal matrix along dim=-3 EXAMPLE: block_diag(torch.ones(4,3,2)) should give a 12 x 8 matrix with blocks of 3 x 2 ones. Prepend batch dimensions if needed. You can also give a list of matrices. :type m: torch.Tensor, list :rtype: ...
c814118d08b34a168e0e9a1ade047c3be26ae5e6
52,025
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False): """Convert a two-byte string to a numerical value, possibly scaling it. Args: * bytestring (str): A string of length 2. * numberOfDecimals (int): The number of decimals. Defaults to 0. * signed (bol): Whether large p...
246bff7ec138778718ac8aa47c6348e240a5051b
52,026
def smape(y_true, y_pred): """ Calculates the symmetric mean absolute percentage error of the predicted values to the true values. `y_true`, `y_pred` should be of the same type and shape. The SMAPE is calculated as: 2 * mean(|y_pred - y_true| / (|y_pred| + |y_true|)) Therefore, it is ...
ea109400eebf0768b485e434cef992f58e9e3b22
52,027
def _api_rss_now(name, output, kwargs): """ API: accepts output """ # Run RSS scan async, because it can take a long time scheduler.force_rss() return report(output)
72e74532fcd2cd4b5c41f9273ce6ebd00c5b566a
52,028
def get_middle_opt(string: str) -> str: """Get middle value of a string (efficient). Examples: >>> assert get_middle_opt('middle') == 'dd' """ return ( string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1] if not len(string) % 2 else string[int(len(string) // 2)]...
1636f39e22bacc4f571de876dd71add690e940e6
52,029
import csv def vmess_IO(class_): """ 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray """ def refresh_log(dataFlow): with open(SYS_AIRPORT_INFO_PATH, 'w', encoding='utf-8', newline='') as fp: writer = csv.writer(fp) writer.writerows(dataFlow) try: with open(SYS_AIRP...
6e99847f5b3b1ff09b74a1e669a9bb18ee0e5bfa
52,030
from typing import Optional def get_anonymous_current_user(locale: Optional[str]) -> CurrentUser: """Return an anonymous current user object.""" return CurrentUser( id=ANONYMOUS_USER_ID, screen_name=None, suspended=False, deleted=False, locale=locale, avatar_url...
3c503154f986cfd420751ce331943a8d5854b60a
52,031
def cut_sites_with_region(df_sites, df_region): """Find peak interval the crosslinks belong to.""" df_p = df_sites[df_sites['strand'] == '+'].copy() df_m = df_sites[df_sites['strand'] == '-'].copy() df_region_p = df_region[df_region['strand'] == '+'].copy() df_region_m = df_region[df_region['stran...
df40f8fc522e9be65d146b30a17c587899749957
52,032
def check_inplane_vector(vector, normal): """ Determines if a vector is in plane with the current element :param vector: Test vector :param normal: Normal of element :return: """ checkdot = np.dot(normal, vector) err = 1e-9 if -err < checkdot < err: return True else: ...
e535dd30d6f03b1ca9048958e769ec02b70e0ba2
52,033
def parse_temp_data(json_graph): """Parse the temp data""" temp_list = list(filter(lambda x: '100kHz' in x['label'], json_graph['graph_kind_1008'])) if len(temp_list) == 0: return None return clean_data(temp_list[0]['data'])
dff2ee90c7312a713815860668551619dceaba97
52,034
from typing import List def brl_out(offset: int, data: List[int]) -> bytes: """send data to braille display @param offset: Must be positive. """ d2 = len(data)+7 ret = bytearray([ STX, ord(b'S') ]) ret.extend(offset.to_bytes(2, "big", signed=False)) ret.extend(d2.to_bytes(2, "big", signed=False)) ret.ex...
c761dd0eadd4a59264c1dcca6d2dfed6323f0078
52,035
def degree_as_dm7(degree): """ Given a degree, return the equivalent dm7. Does not perform range validation. Performs integer conversion of the result. """ return int(round(_DM7_PER_DEGREE * degree))
1bdd862e32942175ba06f54987d89646e43dae4d
52,036
def duration(duration): """Filter that converts a duration in seconds to something like 01:54:01 """ if duration is None: return '' duration = int(duration) seconds = duration % 60 minutes = (duration // 60) % 60 hours = (duration // 60) // 60 s = '%02d' % (seconds) m = '%0...
7cd89654a84c2e3e41d96cb1b13688833ee54387
52,037
def test_log_dtypes(dtypes, capsys, test_df): """Test logging of dtypes can be switched on and off""" @log_step(dtypes=dtypes) def do_nothing(df, *args, **kwargs): return df test_df.pipe(do_nothing) captured = capsys.readouterr() assert ("dtypes=" in captured.out) == dtypes if d...
735b1479304dcc15bff10a95c37af9417da79ce7
52,038
def lookup_embedding_func( id_tensors, max_ids, embedding_dim, ): """ Args: id_layers: dict, the key is a string and the value is tf.keras.Input. standardized_tensor: input_tensors: dict, the key is a string and the value is a tensor outputed by the transform ...
2666832656bf9d98a933b068215c3076328f3a3d
52,039
import types def name(function): """ Retrieve a pretty name for the function :param function: function to get name from :return: pretty name """ if isinstance(function, types.FunctionType): return function.__name__ else: return str(function)
4002d7a945c3b3e3e4d957c0b10ff202f2cf0246
52,040
def loading_effects_decorator(func): """ Decorator for creating an loading cursor. >>> @loading_effects_decorator >>> def do_lengthy_process(): >>> # DO something >>> pass Parameters ---------- func: function Returns ------- new_function: object """ d...
28c495d0c5b31e124173184ccb2d00dd90986376
52,041
import requests def get_response_json(url: str): """ Function get response json dictionary from url. :param url: url address to get response json :type url: str :return: dictionary data :rtype: json :usage: function calling .. code:: python get_response_json...
dd209b1dba7f4320cd91addb1e49fa98bab0ae2b
52,042
def JobPostingDetails(request, pk): """ Retrieve, update or delete a job posting. """ try: job_posting = JobPosting.objects.get(pk=pk) except JobPosting.DoesNotExist: return HttpResponse(status=500) if request.method == "GET": serializer = JobPostingSerializer(job_postin...
1f1cc4be467fd64cf87bbab01fcae68a19905969
52,043
import ast import re def strip_typehints(source): """Strip the type hints from a function""" if black: source = black.format_str(source, line_length=82) # parse the source code into an AST parsed_source = ast.parse(source) # remove all type annotations, function return type definitions ...
46df36fcffd38b6657df041fb366f001c410ece6
52,045
def upconv(x, channels, kernel=3, stride=2, pad=1, use_bias=True, sn=False, scope='upconv_0'): """ upsampling + conv """ with tf.variable_scope(scope): x = up_sample(x, scale_factor=stride) x = conv(x, channels=channels, kernel=kernel, stride=1, pad=1, use_bias=use_bias, sn=sn, scope=sco...
6e3e13e6143757afb549a42632a877b9cb7089a9
52,046
import copy def create_temporary_copy(directory_path: str, target_directory_prefix: str = "") -> str: """Creates a copy of a directory in a temporary directory and returns its path""" copy_path = get_temporary_directory_path(target_directory_prefix) copy(directory_path, copy_path) return copy_path
b835724145ee64cc52d9193cc73b2b25eb33ec2a
52,047
import pickle def dumps_content(content): """ pickle 序列化响应对象 :param content: 响应对象 :return: 序列化内容 """ return pickle.dumps(content)
f88159b9d016a6e39744e7af09a76705c9f4e76f
52,048
def hide_solution(key, tpl_dict = latex_doc.tpl_dict): """Hide solutions by default""" return """ {%- if cell.metadata.solution_first or cell.metadata.solution2_first or cell.solution_first or cell.solution2_first -%} {# exercise #} {%- elif cell.metadata.solution == 'hidden' or cell.metadata...
836e6bb8009d5626b08ef339145758f7f3ce4214
52,050
def midpoint(f, a, b, N): """Zusammengesetzte Mittelpunktsregel in 1d. Input: f : Funktion f(x) welche integiert werden soll. a, b : untere/obere Grenze des Integrals. N : Anzahl Teilintervalle in der zusammengesetzten Regel. """ x, h = np.linspace(a, b, N+1, retstep=True)...
0c07c51a8f9c917c1b22ebfebb8c8904fa4dccba
52,051
def content_disposition_filename(filename): """ Sanitize a file name to be used in the Content-Disposition HTTP header. Even if the standard is quite permissive in terms of characters, there are a lot of edge cases that are not supported by different browsers. See http://greenbytes.de/tech...
dd60cddee1ccb08344e41a2ffbd4bb68b599d5da
52,053
from datetime import datetime def fmt_datetime(object_: datetime) -> str: """Parse datetime into pydantic's JSON encoded datetime string""" return object_.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
2e39b9d6a262aaa0297f50af8c1fbf9069ac5f4b
52,055
import json def get_table_list(transaction_executor): """ Connect to a given ledger using default settings. """ statement = "SELECT name FROM information_schema.user_tables" cursor = transaction_executor.execute_statement(statement) try: table_list = {} i = 0 for r...
c4d50798c0b6340ebe064e087664cfaca5f28a49
52,058
def _apply_conv_mode(ret, s1, s2, mode, axes): """Calculate the convolution result shape based on the `mode` argument. Returns the result sliced to the correct size for the given mode. Parameters ---------- ret : array The result array, with the appropriate shape for the 'full' mode. s...
873f5529da5e88a52278fb5c90537c7751b50845
52,059
def format_time(ogtime): """Increase readability of given catalog times.""" return pd.Timestamp(' '.join(ogtime.split('T'))[:-1])
93207ba2b09c3f25c15f5aa2fcf8030950f530f3
52,061
import time def train(loss_fn): """使用损失函数loss_fn训练回归""" print("Training;loss function:" + loss_fn.__name__) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) def loss_for_example(x, y): return loss_fn(y, prediction(x)) # `grad_fn(x_i, y_i)` returns (1) the value of `loss...
20de6a0bf6245efc4351e0339b942fbf80e0b9b2
52,062
def estimator(data): """ Takes input data and returns it in a specified format. """ # get days days = timeEstimateDays(data["periodType"], data["timeToElapse"]) # Challenge 1 # Currently infected estimates currentlyInfectedImpact = int(data["reportedCases"] * 10) curren...
1b7e6bd6772aae1b2b1d76fec083ec601515f7f8
52,063
def run(method): """Run method.""" switcher = { "construct": lambda: construct(), "execute": lambda: execute() } return switcher.get(method)()
602cf4765144bbb838fab3f8733cf953216a6d06
52,064