content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def append_disputed_countries(grid_ctrys): """Add "disputed aliases" to the list of GRID countries, to "forgive" either GRID or the matching dataset for using the "wrong" country, in the case of disputed countries. Args: grid_ctrys (set): Set of countries to be extended with disputed aliases. ...
2535114e0d7873db012702fe9ee176d2e36fb13d
3,603,153
def _exp_greenwoods_ci(mf, nf, r, alpha=0.05): """ Gets the exponential Greenwood's confidence interval. """ if alpha <= 0 or alpha >= 1: raise ValueError("alpha must be between 0 and 1 exclusive.") # Don't calculate confidence interval for time 0 where R(t)=1. mf = mf[1:] nf = nf[1...
e7524853e388262703acf3657bea8381192aebce
3,603,154
import requests import time import json def api_call_networkcontainer_views(view, logger): """ DDI api call for network containers within the 'view' value. Returns the utf-8 decoded with a json load. Return Variables: -- rddijsonnetcont """ trynetworkview = 3 rnetcont = None ...
4356bb73fd679c8d9ad6210dadefc042466f099a
3,603,155
def turnoverrate(cftable, end=yesterdayobj()): """ calculate the annualized turnoverrate :param cftable: pd.DataFrame of cftable :param end: str or obj of datetime for the end date of the estimation """ if len(cftable) == 0: return 0 end = convert_date(end) start = cftable.iloc[...
2f8c63ce7d0e965e38d03900bc11e47268f99aa2
3,603,156
def build_production_problem(products, resources, consumptions, **kwargs): """ Takes as input: - a list of product tuples (name, demand, inside, outside) - a list of resource tuples (name, capacity) - a list of consumption tuples (product_name, resource_named, consumed) """ mdl = Mod...
9fd893e6c555ff654ddf9fdeb9f238b8bb3caf73
3,603,157
def C(classname): """get an ObjC Class by name""" return objc.objc_getClass(_utf8(classname))
a9ab411a637760be0cf9038728151017cf2d3e01
3,603,158
def GetMessages(): """Import and return the appropriate admin messages module.""" return apis.GetMessagesModule('datastore', _DATASTORE_API_VERSION)
4a83b56cd2c2831efa8baaa27e19695ccacf8636
3,603,159
def Jolanta_GTO_H(GTO_fn, alphas, Ns, param, l=1): """ Hamiltonian matrix in a GTO basis set Parameters ---------- GTO_fn : either Jolanta_1D_GTO() or Jolanta_3D_GTO() alphas : np.array of GTO exponents Ns : np.array of normalization constants param : (a, b, c): parameters of the Jo...
0105b7b035ff9b880b53683a3a5c91fa68fac1b7
3,603,160
import torch def list_of_dict_to_dict_of_array(old_lis, force_list=None, force_cat=None, stop_recursion=None, to_tensor=None): """ From a list of dict to a dict of array (or list) """ if isinstance(old_lis, list): if not old_lis: return {} elif not isinstance(old_lis[0], di...
0d306eb59af9b13477e02b2b5a27805b9797ab25
3,603,161
def testCuadro(linkCuadro): """ Dado el link de un cuadro, devuelve un diccionario con su info """ util.abrir_url_recarga(linkCuadro,"ficheros/cuadro.txt",True) f = open ("ficheros/cuadro.txt", "r") s = f.read() f.close() bs=BeautifulSoup(s,"html.parser") cuadro={} info=bs.find("...
531b80766b8d6001b7ffa44d89a989dbd9792f90
3,603,162
from typing import List def extract_transmon_coupled_Noscillator(capMatrix, Ic: float, CJ: float, N: int, fb: List[float], ...
481f1f1c4def657001d23faf50c4aed40e7c12d2
3,603,163
def bi_class(raw, boundary): """ divide raw input into two classes, based on selected boundary """ bi_class = pd.Series([0 if i < boundary else 1 for i in raw]) return bi_class
4e80f7cafeb1d66f660818b86b04331737991c75
3,603,164
def calculate_results(subject, eval_time, testfields, reffields): """ Function to print out the results of the colorimetric analysis Input: subject: ID of the subject eval_time: Evaluation time, after which the input image was taken: 30: Glucose, Bilirubin ...
1774ce16a2765f5b2b31fbbc1cd9ae8c28ee4702
3,603,167
def detect_delimiter_separated_values(filename): """Attempts to check for csv or tsv mimetypes""" df = pd.read_csv(filename) if len(df.columns) > 1: return 'text/csv' if len(df.columns) == 1: if df.columns[0].count('\t') >= 1: return 'text/tab-separated-values'
e653004be38db84c5ac2da7914591673e5cd8cf4
3,603,168
from shapely.geometry import Polygon # Find max in region def find_max_in_region(geodf,region): """ Find the largest cases value within a specified region and days list region_Lon = {'name': 'London', 'xlim':[-0.6,0.5], 'ylim':[51.2,51.8], 'date_loc':[0.2,51.75] } maxval = find_max_in_region(geodf,re...
dd49f86305380309c2b795a2e5932c42da88633b
3,603,170
def is_token_blacklisted(encoded_token, public_key=None): """ Decode an encoded token and check if it is blacklisted. Args: encoded_token (str): JWT to check public key (Optional[str]): key to decode JWT with Return: bool: whether JWT is blacklisted """ public_key = pub...
9bb4a42055b462fc2732f706006e044d90deff33
3,603,171
def config_multiple(): """Return multiple config fixture.""" return load_multiple_config_yaml()
f48c03f9c713700cec8b172454533bc87a554c40
3,603,172
def perimeterCircle(r=1.): """Calculate the length of the perimeter of a circle. Parameters ---------- r: float, optional (default=1.) Radius of the circle, r>0. Returns ------- float Perimeter of the circle. """ return 2. * np.pi * r
c1af01851816109fae5506aa022b55f3a31c588a
3,603,173
def _gh_stepsize(vP): """ Purpose: Calculate stepsize close (but not too close) to machine precision Inputs: vP 1D array of parameters Return value: vh 1D array of step sizes """ vh = 1e-8*(np.fabs(vP)+1e-8) # Find stepsize vh= np.maximum(vh, 5e-6) ...
f53089dd00b3b853fb330b04c124f8cdd1eb602b
3,603,174
from typing import Optional import json def read_template_description(filename: str) -> Optional[TemplateEntity]: """ Reads the template description file, and returns None if it isn't valid, or a template entity (with the purpose left blank) if it is. """ with open(filename, 'r') as f: dat...
7173cd93202527122cfab57cd87238f5a1bc9685
3,603,175
from datetime import datetime def fetch_from_github(shapes_graph, client, oauth_token, topics, github_direct_search): """Fetch shapes files from GitHub using the GraphQL API. We filter repositories by topics provided as argument """ time_start = datetime.now() stopping_job = False for github_t...
a81385f8ca804eeddfd238a8d976efe68ef27431
3,603,178
from typing import List def roles_required(roles: List[str], require_all: bool = False): """ Wrapper used to check for multiple roles for a current user. User can be required to have all roles or only 1 of the provided list. :param roles: List of String names for the roles :param require_all: If ...
f24604f64041e9d5957b8577e7cb99f9a2240482
3,603,179
import requests import html import re def get_stat (ipaddr): """ Get statistics from a host. May be 4 miners type. 0 - unsupported device 1 - antminer hwv 1.0.0.6 or 1.0.1.3 or 16.8.1.3 2 - antminer hwv 1.0.0.9 3 - innosilicon Return string with parameters """ miners_device = {} ...
13a255b287476f2be2cd57376fc7193531bd4122
3,603,180
def forensic(): """ brute force / comprendre le problème ... """ def is_strange(i): l = len(str(i)) if l == 1: return True if i % l != 0: return False return is_strange(i // l) def construction(i): s = str(i) l = len(s) if l...
02acb3a92aa2fc110ab356dc5786dac247c3c63f
3,603,181
def analyze_msg(raws, a): """ Analyze message. Determine if sender and command are valid. Return values: None: Sender is invalid or no text part False: Invalid command Otherwise: Array: message split by lines :type raws: dict """ print("Analyzing message with uid " + str(a)) ...
a7583ca657e49b472f77300fadddb73b1aa6d131
3,603,182
def adjust_RED_by_structure_name(dicom_dataset): """Adjust the structure electron density based on structure name. """ structure_names = [ structure_set.ROIName for structure_set in dicom_dataset.StructureSetROISequence ] adjustment_map = RED_adjustment_map_from_structure_names(structure_na...
0ef06038806795d7e42e4e88fa18e1ab832e0fd5
3,603,183
def mass_comp_function(values, bins, scale=1, aktomassd=183): """ M(>Ak), mass weighted complimentary cdf """ if hasattr(bins, "__getitem__"): range = (np.nanmin(bins), np.nanmax(bins)) else: range = None # if scale != 1: # aktomassd = scale h, bins = np.histogram( ...
a94f56c94c037543202d90e472c0ca2e57945091
3,603,184
import itertools import math def split_dl(data_it: dataset.DataIterable, fpath_template: str, num_artcles_per_file: int) -> dataset.DataIterable: """Split the dataloader data into `num_articles_per_file` articles splits and generate new paths with the template `fpath_template` for each split. Parameters ...
6bf9802b70a10fcd58256106fb58efcd4ff86a74
3,603,185
def generate_all_bns_parameters(sample, likelihood=None, priors=None): """ From either a single sample or a set of samples fill in all missing BNS parameters, in place. Since we assume BNS waveforms are aligned, component spins won't be calculated. Parameters ---------- sample: dict or...
8e9b6b256f436a6c415e715e79c897be2874ac64
3,603,186
def load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file. 'fp' should be (readable) file object. Return the unpacked root object (which usually is a dictionary). """ if fmt is None: header = fp.read(32) fp.seek(0) for info in _FORMATS.values(): ...
daa0f41e0814654e49dbdb6d86f277b8c84d37d9
3,603,187
def _conv_arg_to_workload(data, kernel, strides, padding, layout, out_dtype): """convert argument to workload""" if len(kernel.shape) == 4: raw_kernel = kernel else: # the input kernel is transformed by alter_op_layout shape = get_const_tuple(kernel.shape) raw_kernel = tvm.placehold...
c38369d25e0336f7c2a72bda63bac09566a439d5
3,603,188
def avgDicts(list_of_dicts): """given a non empty list of dicts with the same keys, it returns a dict which contains the avg of each dict in the list Arguments: list_of_dicts {list} -- """ result_dict = {x:0 for x in list_of_dicts[0].keys()} for key in result_dict.keys(): re...
2cd24e3260f933df2082b426cfb5f9058f05d319
3,603,189
def binarize_weights(x, name=None): """Creates the binarize_weights Op with f as forward pass and df as the gradient for the backward pass Args: x: The input Tensor name: the name for the Op Returns: The output tensor """ def f(x): alpha = np.abs(x).sum(0).s...
67be10ec023c7923d7fb52a698b85a38f1e04ce4
3,603,190
def similarity(data_lst, user1, user2): """ gets list of sets of hashtags for both users for each item in user lists find intersection of hashtags add intersection to intersection list at that month :param data_lst - list of twitter data: :param user1 - first twitter user entered by ...
f908337cf27bf368f651c7d5c2fd3a5cd17fa645
3,603,191
import re def trim_http(url :str) -> str: """ Discard the "http://" or "https://" prefix from an url. Args: url: A str containing an URL. Returns: The str corresponding to the trimmed URL. """ return re.sub("https?://", "", url, flags = re.IGNORECASE)
472e71a646de94a1ad9b84f46fc576ed5eb5a889
3,603,192
def _create_overpass_query(polygon_coord_str, tags): """ Create an overpass query string based on passed tags. Parameters ---------- polygon_coord_str : list list of lat lng coordinates tags : dict dict of tags used for finding elements in the selected area Returns ----...
aa766c983d4fa7aa46c9dfd5259f82b94f153798
3,603,193
import time def cache_function(length): """ Cache the result of function :param length: time in seconds to stay in cache """ def _decorated(func): def _cache(*args, **kwargs): key = sha1(str(func.__module__) + str(func.__name__)).hexdigest() # Search in cache if...
18585ee83dfcae3608e7d99fbbe51dc2d9378c96
3,603,194
from aquaregia.unction import MaskedBatchNorm import random def test_MaskedBatchNorm(): """test the `MaskedBatchNorm`; ensure it appropriately masks the right dimension and scales outputs to unit normal""" _inputs = random.normal(random.PRNGKey(2623), shape = (5,3)) _mask = Array([1,1,1,1,0], dtype=jnp.bo...
2c3218f604aa08db9f52615390b8087186f49682
3,603,195
def notify_sample_status(profile_id=str(), action="message", msg=str(), data={}, html_id=""): """ function notifies client changes in Sample creation status :param profile_id: :param action: :param msg: :return: """ # type points to the object type which will be passe...
07f13a2c19c7f9fb280504a484e1fb6e2e0c8bf4
3,603,196
def tf_augment_image(image, random_augmentation=False, intensity=0, rotation=0, width_shift=0., height_shift=0., brightness=None, horizontal_flip=False, vertical_flip=False,...
cd360c6c38c83c657fb6c51474b205a7ea26cd62
3,603,197
def test_validate(monkeypatch): """ . """ # pylint: disable=unused-argument @counter_wrapper def fake_validate_false(self) -> bool: """ . """ return False @counter_wrapper def fake_validate_true(self) -> bool: """ . """ re...
eec55c3a46886d2af7aee5e5c9c9110515230442
3,603,198
def interpolate_image_at_mask( *, image, bad_msk, maxfrac=0.90, buff=4, fill_isolated_with_noise=False, weight=None, rng=None, iso_buff=1, ): """ interpolate the bad pixels in an image Parameters ---------- image : array the pixel data bad_msk : array boolean array, True...
2b0d1f8fde2a5b8bb09c56e0521fe8982e5efc68
3,603,200
from typing import List def weave_helper(first: List[int], second: List[int]) -> List[List[int]]: """ Does the recursion to find the weaving of the ramaining of the list excluding the first char of the first list """ sufix_weaving: List[List[int]] = weave(first[1:], second) result: List[List[int]] = [] for wea...
d0ef6390b836d80be195ff455e96190d27509f9a
3,603,201
from typing import Sequence def compute_offset_slots(start_slot: Slot, end_slot: Slot) -> Sequence[Slot]: """ Return the offset slots that are greater than ``start_slot`` and less than ``end_slot``. """ return [Slot(start_slot + x) for x in SHARD_BLOCK_OFFSETS if start_slot + x < end_slot]
8750385aae199c5bf5371604615cca9ebecd5a06
3,603,202
import re import json def resolve_type(session: Session, link: str) -> ProductType: """ Given a link, it will return the ProductType """ if not re.search('bookrags.com', link): return ProductType.UNKNOWN try: page = session.get(link).text json_raw = re.search( '...
814733595e9eacd824681ad981265ded80370523
3,603,203
def material(): """Factory associated with Elasticity. """ return Elasticity()
eeb0c30a2644348244801f88aca1aa5a4f5280ea
3,603,204
import time def get_spam_score( message: Message, email_log: EmailLog, can_retry=True ) -> (float, dict): """ Return the spam score and spam report """ LOG.d("get spam score for %s", email_log) sa_input = to_bytes(message) # Spamassassin requires to have an ending linebreak if not sa_...
81e7d5535a375231bc53dea85b418b326eb0375c
3,603,205
def changeArc(G, i ,j): """ change statistic for Arc """ return 1
90b33be8ac87a67362b43185e688e8fdff218e64
3,603,206
def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None): """ Given a sentence, perform preprocessing and normalize number words to digits. :param sent: sentence (str) :return: a list of normalized words from the sentence """ out_words = [] words, sigfigs = preprocess(sent, re...
7c306598dd0b35a3b1f341582ebaa9bfab49c0ba
3,603,207
def compute_expires_at(ipn): """ Compute the expiration date of the payment. :param ipn: the ipn object """ for key, value in PREMIUM_IDS.iteritems(): if ipn.item_number == value: number_of_months = int(key.replace("p", "").replace("f", "")) break else: ...
8a49f0549bb4591d6f496580a4d44ca94d322e85
3,603,208
def test_override_secrets_using_fn(): """ Just another way for overriding KEYS method """ with mock.patch('awsvault.core.boto3') as boto3: boto3.client().get_secret_value.return_value = AWS_SECRETS_MOCK.get("DATABASE") def override(name): if name == 'DB_PASS': ...
6e4c76bd9db834b917fb010f7f87b9309d47159b
3,603,209
def eval_input_fn(data, batch_size): """An input function for evaluation or prediction""" inputs = None try: # If there are labels, then we evaluate features, labels = data inputs = (dict(features), labels) except: # If there are no labels --> prediction inputs ...
4186bd22b6d3064198df58954e6773c46661c03b
3,603,211
def browser_key_press_h(key_1="", key_2=""): """Type text using Browser Helium Functions and press hot keys. Args: key_1 (str): Keys you want to simulate or string you want to press Eg: "tab" or "Murali". Defaults: "" key_2 (str, optional): Key you want to simulate with combination to k...
248973d646a49bf3b8ac059ac9e9cd4baf57ad4d
3,603,212
def _jq_format(code): """ DEPRECATED - Use re.escape() instead, which performs the intended action. Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. If you just want to escape quotes, there's escape_quotes_if...
3c46caa1a02798a7b8539a92a6b68f29e3dcd63c
3,603,213
def initial_policy(observation): """A policy that sticks if the player score is >= 20 and his otherwise Parameters: ----------- observation: Returns: -------- action: 0 or 1 0: STICK 1: HIT """ return 0 if observation[0] >= 20 else 1
03e6cf5deb5dded598cb625fb68ad98cf3f356cc
3,603,216
def _make_path_tree(basepath, path): """ Return a list of paths leading to the destination path. :param basepath: Base path to search under. MUST begin with a '/'. :param path: Path to search for. :returns: Tuple of (full path, list of paths from root level to the given path) Tests:: ...
660fbb21378d8596b6ddf1f427cd180121a1395c
3,603,218
from typing import List import aiohttp async def fetcher( urls: List[str], output=False, task_per_second: int = 1000, forbidden_max: int = 10, output_number: int = 100, ): """ Main function to run the programs here with default parameters, etc... I don't think that this is even a nesse...
27e33dad9db08e4b554ad35c7bf72a170391a7d0
3,603,220
def levinson_durbin(r, order): """ from http://aidiary.hatenablog.com/entry/20120415/1334458954 """ a = np.zeros(order + 1) e = np.zeros(order + 1) # k = 1 a[0] = 1.0 a[1] = - r[1] / r[0] e[1] = r[0] + r[1] * a[1] lam = - r[1] / r[0] for k in xrange(1, order): # upd...
f58918eff73d8055ab430c373bbc368876653434
3,603,221
def transform_action_space(env_name_or_creator): """Wrapper for gym.Envs to have their action space transformed. Args: env_name_or_creator (Union[str, Callable[]]: String specifier or env_maker function. Returns: Type[TransformedActionSpaceEnv]: New TransformedActionSpaceEnv cl...
cd644b6f04b0a1335a66b21b58d17b6aab02042b
3,603,222
from typing import Type def test_option_plan_to_policy(): """Tests for option_plan_to_policy().""" cup_type = Type("cup_type", ["feat1"]) plate_type = Type("plate_type", ["feat1", "feat2"]) cup = cup_type("cup") plate = plate_type("plate") state = State({cup: [0.5], plate: [1.0, 1.2]}) de...
5d3082e8a7e6bd3bffb2397be2a312689c62f27c
3,603,224
import turtle def getturtle() -> turtle.Turtle: """Return the Turtleobject itself. No argument. Only reasonable use: as a function to return the 'anonymous turtle': Example: >>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x0187D810> >>> turtles() [<tur...
da45c4ae8d1b8291c5bfd6a556d45ffc0f2bff0d
3,603,225
def get_behavior(name): """Returns an instance of the given behavior.""" return Behavior.get_behaviors(name)()
9e62f8c4d514b4c54b39b7884259f9f7ff49b628
3,603,226
def schwartzberg(poly): """ Alterantive name for the Isoareal Quotient """ return iaq(poly)
fb48b20e115b6fa8f4e4b8a559afeb24cbe9792a
3,603,227
def _kde_support(data, bw, gridsize, cut, clip): """Establish support for a kernel density estimate.""" support_min = max(data.min() - bw * cut, clip[0]) support_max = min(data.max() + bw * cut, clip[1]) return np.linspace(support_min, support_max, gridsize)
52711f45f0b8f2e430b708babd56210f2686dbb8
3,603,228
def get_exact_ijs_(f, parallel=True, verbose=False, backend="loky"): """ Takes the metric f and returns the function get_exact_ijs(f,X,IJ), which calculates the distances between pairs given in array IJ. Parameters ---------- f: function The metric. Takes two points from the data set an...
97e748d5c4bcdc3b3d5cc32e3dba1e1417077989
3,603,229
from typing import Optional from typing import Sequence def get_function_scaling_policy(function_id: Optional[str] = None, policies: Optional[Sequence[pulumi.InputType['GetFunctionScalingPolicyPolicyArgs']]] = None, opts: Optional[pulumi.InvokeOptions] =...
2ef0d899080a858cd7a507dcc90a1447d50db305
3,603,230
def identity_block(inputs, filters, name, strides=1, training=True): """ resnet卷积块 :param inputs: 卷积块的输入 :param filters: 卷积核的数量 :param name: 卷积块名字相关 :param strides: 为1时候不改变特征层宽高,为2就减半 :param training: 是否是训练模式 :return : x """ filter1, filter2, filter3 = filters x = layers.Con...
2092cf79c7c43fe7fc999fa673b224df4599d336
3,603,231
from openeo_udf.api.datacube import DataCube def datacube_from_file(filename, fmt='netcdf') -> 'openeo_udf.api.datacube.DataCube': """ Converts source files of different formats into openeo_udf.api.datacube.DataCube in memory :param filename: the file on disk :param fmt: format to load from :...
8fbe04b399cd718c00f67bbde187cdacbbc24537
3,603,232
import functools def read_tf_records(batch_size, tf_records, interleave=True): """ Args: batch_size: batch size to return tf_records: a list of tf_record filenames interleave: iwhether to interleave examples from multiple tf_records Returns: a tf dataset of batched tensors ...
3ed3dde9db3ff0e6527eb93da875c3cc868088b2
3,603,233
def score_distribution(num_players, difficulty = Difficulty.MEDIUM): """Return a list of score distributions given the number of players and the difficulty.""" #initialize scores list scores = [] for i in range(num_players,0,-1): scores.append(i) #adjust scores so its average is the same as other...
fa21a1bfe4684f16e9c680ada677b9a764b08063
3,603,234
import torch def glu(x: torch.Tensor, dim: int = -1): """Generalized linear unit nonlinear activation. Expects 2*n_units-dimensional input. Half of it is used to determine the gating of the GLU activation and the other half is used as an input to GLU, """ return nn.functional.glu(x, dim)
45042030ffbf03908e8431c016ad9d0b7fa4ce67
3,603,235
def serial_christie_lamp_status(connection): """Build the lamp status list for a Christie projector This list has format [(lamp1_hours, lamp1_on), (lamp2_hours, lamp2_on)]""" connection.reset_input_buffer() # Get lamp hours l1_hours_response = serial_send_command(connection, "(LPH?)", char_to_rea...
353f1286cdd74bce8aa1078c93a17f7b4b8508d9
3,603,236
def entropy_shannon(signal): """ Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo. Parameters ---------- signal : list or array List or array of values. Returns ---------- shannon_entropy : float The Shannon...
b469e4d9b0706324baa624528d7b279fc5a19cc4
3,603,237
def basic_xml_tree(): """Basic XML tree used for testing.""" xml_tree = ET.Element("root") xml_tree.text = "100" xml_level_1 = [ET.SubElement(xml_tree, "leaf1"), ET.SubElement(xml_tree, "leaf2")] return xml_tree
553a98cc58c49627d56c1d24e5b47f5ec7417d64
3,603,239
import typing def upgrade_database( config: Config, engine: Engine, metadata: MetaData, *, revision: str = 'head', module_name: typing.Optional[str] = None, ) -> None: """Upgrades the database schema to the chosen ``revision`` (default is head). """ script = ScriptDirectory.fr...
f9313d0ce1899791f2056306751be801b0b18e77
3,603,240
def encrypt_decrypt(plaintext, key, decrypt): """ Use a Vigenere cihper to encrypt or decrypt the message.""" # Convert the key into an array of offsets. offset = [] if decrypt: for i in range(len(key)): offset.append(26 - (ord(key[i]) - ord_a)) else: for i in range(len(k...
7af986cdbc12a9e344a5f570265dfa89c0ff901b
3,603,241
import ast def parse(code, para, module): """Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str) """ global para_cfg global prefix_name para_cfg = para prefix_name = module try: ast_tree = ast.parse(code...
154a59d2b59cbc0ec603d022dc3d74060d090ca1
3,603,242
def compiler(program: list): """ Compiles a whole multiline program and returns the final result (current Register). :param program: The whole multiline commands separated with \n as a string list. :return: Returns the final program output. """ REGISTER.clear() i = 0 while i < len(progra...
6ce7ee11d6b834afa98b66bf9995021ba74dcae6
3,603,243
import time import traceback def withdraw(body): """ 自动提现 :param headers: :return: """ time.sleep(0.3) url = 'https://ios.baertt.com/v5/wechat/withdraw2.json' headers = { 'User-Agent': 'KDApp/1.8.0 (iPhone; iOS 14.2; Scale/3.00)', 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-...
209469d986b24d488f09d0426517d02524fbc459
3,603,244
def parse_http_response(response): """Extract all triples from HTTP response object.""" logger.info("Extracting new information from HTTP request/response...") # Prepare for parsing request = response.request triples = [] # Create new individual which becomes the subject of all triples re...
842d69422899f2a0e9dffb2e92ef9564e6ecde6e
3,603,245
def kneeJointCenter(frame,hip_JC,delta,vsk=None): """Calculate the knee joint center and axis function. Takes in a dictionary of xyz positions and marker names, as well as an index. and takes the hip axis and pelvis axis. Calculates the knee joint axis and returns the knee origin and axis Markers ...
f1c9608455468843bb802914d5134ec994921475
3,603,246
def getOpenFileName(*args, **kwargs): """ Wrapper for the :func:`~PyQt5.QtWidgets.QFileDialog.getOpenFileName` function, which automatically applies several standard options and makes using filters easier. %(optional)s Returns ------- filename : str The filename that was chosen...
20f0d074fb010e4b1548c591739ee595f91bff9f
3,603,247
def get_log_km_brenda_blk( posterior: Dataset, ec4: str, organism: str, substrate: str ) -> DataArray: """Get a DataArray of log kms for the brenda-blk model.""" # if substrate not in posterior.coords["substrate"]: # substrate = "unknown substrate" ec4_sub = f"{ec4}|{substrate}" if ec4_sub not i...
de1ed23b2544aa8e3852ae9a63a00c5185e44632
3,603,248
def addDefaultArgs(parser, defaultLog="none"): """!Add default arguments common to all commands.""" parser.add_argument("--version", action="version", version=f"Isle {isle.__version__}") parser.add_argument("-v", "--verbose", action="count", default=0, help="M...
b06877fa8b5aaa23b98458105bb38fa4f4c78214
3,603,249
import scipy def preprocess_data(mat): """ This function is a Matlab rewritten function from https://gitlab.stimulate.ovgu.de/christoph.reichert/visual-spatial-attention-bci :param mat: matrix loaded with read_mat library :return: features extracted from the specific file """ bci_exp = mat...
52292a7c4e4815487093b11db49e618e4bc213b9
3,603,250
def wfg(P): """ Speed of sound; [m / s] saturation rise of""" return region4.wfg(P)
05fcb202138ad1b3e25c019c49b751c9f2e25171
3,603,251
import torch def reduce_int_float(input_value, average, all_reduce, device): """Reduce an integer or float by converting it to tensor, performing reduction and, finally, casting it back to the initial type. """ data_type = type(input_value) # save the original data type tensor = torch.Tensor([i...
cc10f2d830821f24d71cb728e9bc20ea2bd2aa51
3,603,252
def create_OHE(df): """ Codifica los Cromosomas y los Alelos en OHE. :param df: Pandas DataFrame con los datos de la petición. :type df: Pandas DataFrame. :return: Pandas DataFrame con los datos transformados. :rtype: Pandas DataFrame. """ def isValue(x,i): if x == str(i): ...
92064dbb9937cdd2b4e4e24bb9f2d5e181d41e31
3,603,253
import math def compute_decimal_val_for_fractional_num(digits, base): """Return the representation of a number in the base 10 system. Parameters: digits: str -- string representation of number (in given base) base: int -- base of given number Return: int -- integer representation of ...
f5f22e77bc028348b9a51687093b8f5bef936cb3
3,603,254
def send_limit_message(context: CallbackContext, chat_id: int, messages: dict) -> tuple: """ Send error message about unsupported platform :param context: telegram context :param chat_id: chat id with user :param messages: dict with templates of messages :param platform: platform name :retur...
af6380cf6982ac2b24935f81afc957552f78e566
3,603,256
def compute_index(capacity, from_data_table=True): """Compute the index from the given capacity. Strongly recommended: use the data table. Can be done either from the computed capacities table or computed directly the from equations. Parameters ---------- capacity: float Capacity value...
2f45f18cfa22cd0ac8e28efc2659c7fb018ca954
3,603,257
def load_ref_system(): """ Returns 5-trigonal-bipyramidal as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" P 0.0000 -0.0011 0.0000 Cl 0.0000 2.0091 0.0000 Cl 1.7511 -0.9...
127f19c17905ad84cf4ff20c80432e4c488b56b7
3,603,258
from textwrap import dedent import yaml def load_yaml_from_docstring(docstring: str) -> dict: """Loads YAML from docstring.""" split_lines = trim_docstring(docstring).split("\n") # Cut YAML from rest of docstring for index, line in enumerate(split_lines): line = line.strip() if line.s...
e0178f98fc6a7fd607387bc4f4df90d127652b57
3,603,259
import random def make_batch_pay_data(busi_type, client_tp): """ 批量代付标识,预付卡业务不填 :param busi_type: :return: """ if busi_type == "03": batch_pay = "" elif client_tp == "1": batch_pay = "2" else: batch_pay = random.choice(["1", "2"]) return batch_pay
28992bfe369f0befd3fc78022a2f1035174243c8
3,603,260
from typing import List def make_prog(prog_path: str, c_files: List[File]) -> File: """ Compile one program from its source C files. """ o_files = [ compile(c_file) for c_file in c_files ] prog_file = link(prog_path, o_files) return prog_file
065791d168ec893c41020a50ce9d98d75864f87a
3,603,261
from operator import concat def factory(architecture): """get a model class Args: conf: the model conf Returns: a model class""" if architecture == 'dblstm': return dblstm.DBLSTM elif architecture == 'leaky_dblstm': return leaky_dblstm.LeakyDBLSTM elif archit...
e7fbb09a1284942aac7b80b8c8f61a61727382da
3,603,262
def min_os_level(release): """ Usage:: class Tests (unittest.TestCase): @min_os_level('10.6') def testSnowLeopardCode(self): pass """ return _unittest.skipUnless( os_level_key(os_release()) >= os_level_key(release), f"Requires OSX {releas...
9985ac07eabe0f76e860cbbb5f2518f784cd861d
3,603,264
def user_info(username): """User info""" user = get_user(login=username) if user: con, conn = connection() con.execute("SELECT idnote, title, note_type FROM note_view WHERE creator_id = %s", escape_string( str(user['iduser']))) notes = con.fetchall() con.execute("...
8ba2a7d917c7d7aecd3a71d4343dca61e38a02e9
3,603,266
def chi_squared_homogeneity(*args, statistic: str = "likelihood_ratio"): """Chi-squared test for homogeneity. Checks whether all data groups follows the same data distribution. Assumptions: None. Test statistic: The same statistics from the Chi-squared test for goodness of fit...
1b3506752a965e09f6611200f9b36be69f80c2f7
3,603,267
def read_data_from_mongodb(rack_name="all", unit='C'): """ Read data from mongo db """ rack_data = RackData() rack_temperature = RackTemperature() raw_data_dict = rack_data.get_rack_temperature_data(rack_name) if raw_data_dict is None: return None dict_data = {} for rack_name in...
e1a564c59051ca103b2af0b089a0d0a8f120734b
3,603,268