content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def pos_neg(a: int, b: int, negative: bool) -> bool: """Differences in signed digits. Return True if: - negative is True and both a,b < 0. - negative is False and ((a > 0 and b < 0) or (a < 0 and b > 0). Return False otherwise. """ if negative: return (a < 0 and b < ...
a29aa95c270f8bc3747bbbe88f8ab6f3676bead8
687,980
def is_file(obj): """Retrun True is object has 'next', '__enter__' and '__exit__' methods. Suitable to check both builtin ``file`` and ``django.core.file.File`` instances. """ return all( [callable(getattr(obj, method_name, None)) for method_name in ('__enter__', '__exit__')] + ...
3bfb0e228515fb028a51d65830d1ffc8023dd7df
687,982
import requests def fetch_page(url, cookies): """ fetch the source of a page """ r = requests.post(url, cookies=cookies) return r.text
410c65138a65eae1922848ab723b40e04373df86
687,983
def args_cleanup( args, s ): """ Clean-up the substring s for keys in args Arguments --------- args: The dictionary to be parsed s : Substring to be discarded. e.g. s = '--', then "--record" --> "record" """ if not isinstance( args, dict ) or not isinstan...
fbfb5a3a63663b6a32080cfcfec4c856ed77fc2e
687,984
import importlib def import_module(dotted_path): """ Import a dotted module path. Raise ImportError if the import failed. """ return importlib.import_module(dotted_path)
e805d2e7a0c81d389ef58ea9ee43469bdaed4c5f
687,985
import re def preprocess(sentences): """ 1. 특수문자 제거, 소문자 2. 숫자 제거 :return new_sent : 전처리 후 문장 """ re_special = re.compile('[^A-Za-z0-9]+') # 문자,숫자 제외한 나머지(=특수문자) re_num = re.compile('[0-9]+') # 숫자 new_sent = [] for sent in sentences: text = [(tup[0].lower(), tup[1]) f...
cc161270f7c420ef14dadceadff3cbd8874219c1
687,986
def check_7(oe_repos, srcoe_repos): """ All repositories' name must follow the gitee requirements """ print("All repositories' name must follow the gitee requirements") errors_found = 0 error_msg = "Repo name allows only letters, numbers, or an underscore (_), dash (-),"\ " and ...
be537ac653fcf2e60b88aba79f3c30d0f82c47c6
687,987
def merge_small_partition(partitions: list): """ Merge small partitions of length 1 into previous partition, reduce number of recursive runs. :param partitions: :return: """ to_merge = [] for partition in partitions: if len(partition) == 1: to_merge.append(partition[0]) ...
79001266589e5d37371c4121b777272698767739
687,988
def get_fib_header_len(hdr): """ Get length. """ return hdr[1]
af91352776a0cf32d4f1d7a71d433a9c6802f996
687,989
def my_input(): """Mock input, return 5.""" return 5
eeeb873c3aac205cfa053a9f7ceb1e68712d623a
687,990
def make_kms_map(map_string): """Convert a string into a map.""" # The one line version: # dict({tuple(k.split(':')) for k in [i.strip() for i in m.split(',')]}) result = dict() # split string by comma and strip lines = [i.strip() for i in map_string.split(",")] for line in lines: # ...
10405d9e11f3ae7e262c0ceb4bedfa2f407a0ec0
687,991
def remove_help_message(schema): """ Remove the help_messages in the validation dict. """ for field, rules in schema.items(): if "help_message" in rules: del rules["help_message"] if rules.get("type") == "dict": rules["schema"] = remove_help_message(rules.get("sch...
fb1db1ec17722862380f411f2dea3a2d520716d9
687,992
def allowed_transitions(states): """ this function takes a set of states and uses it to compute the allowed transitions it assumes the model is acyclic ie. individuals can only transition towards states to the right of it in the list Parameters ---------- states : list a list with t...
baa09435de2fabad66f18e0c828f634af23190b6
687,993
import requests def get_series_name(cfg, series_id): """ Request series information from Opencast. :param series_id: Unique identifier for series :param cfg: Opencast configuration :return: Title of the series """ url = cfg['uri'] + "/api/series/" + series_id r = requests.get(url=url,...
8580b2df7f7ed8ada382889a3e656aa5877d555d
687,995
import requests def get_osm_location(query): """ Query OpenStreetMaps for the location information of a postal code and place name """ url = f"https://nominatim.openstreetmap.org/search/{query}?format=json" try: response = requests.get(url, params={'polygon':'1'}) except Exception as...
d3b7f7cf2855831c9fd4e492c0fd6980fa79d402
687,996
import contextlib import wave import audioop def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sam...
d87f538d8e5f055a1b5783911d3cd2584b887ee5
687,997
import itertools import time def retry(delays=(0, 100, 500), exception=Exception, report=lambda *args: None): """ This is a Python decorator which helps implementing an aspect oriented implementation of a retrying of certain steps which might fail sometimes. https://code.activestate.com/recipes/580745...
aebf566b6a52571a5fea1f9229801f4351b20a4f
687,998
def calc_simple_profit(orders, kl_pd): """ 计算交易收益,simple的意思是不考虑手续费 :param orders: AbuOrder对象序列 :param kl_pd: 金融时间序列,pd.DataFrame对象 :return: """ all_profit = 0 now_price = kl_pd[-1:].close for order in orders: if order.sell_type == 'keep': # 单子如果还没有卖出,使用now_price计算...
956f820c65c0c9939682438003e54a8ddea4a836
687,999
def decimal_to_octal(decimal: int)->str: """Convert a Decimal Number to an Octal Number.""" if not isinstance(decimal , int): raise TypeError("You must enter integer value") rem , oct , c = 0 , 0 ,0 is_negative = '-' if decimal < 0 else '' decimal = abs(decimal) while decimal > 0: ...
503ae83edd4715af6f81cfac90b9ee57a5f9ab33
688,000
def rfam_problems(status): """ Create a list of the names of all Rfam problems. """ ignore = {"has_issues", "messages", "has_issue", "id"} problems = sorted(n for n, v in status.items() if v and n not in ignore) return problems or ["none"]
aafcf100cb82ded5c09d6c0da0f885ac3d5164b8
688,001
import os def list_all_files(root: str, keys=[], outliers=[], full_path=False): """ 列出某个文件下所有文件的全路径 Author: wangye Datetime: 2019/4/16 18:03 :param root: 根目录 :param keys: 所有关键字 :param outliers: 所有排除关键字 :param full_path: 是否返回全路径,True为全路径 :return: 所有根目录下包含关键字的文件全路径 ...
7e59ab0d98bc7dea288a3f5e8d95b529da1fc864
688,002
import random import copy def sample_relationships(relationships, pred_counts, n_per_pred): """Randomly samples up to `n_per_pred` relationships per predicate. Args: relationships: list of relationships from VG (e.g. relationships.json) pred_counts: dict of predicate names to correspondin...
0c1e2db10a187842eb6a40a99df3decf1fb144b7
688,003
def getTopic(): """ - retrieves the name of a topic on which the client is subscried """ return f'Bishu1'
bb851063b2e437e07cb893f0b3fffebfbebe3f9f
688,004
def get_subscribers(cursor, imei_norm): """ Method to get IMSI-MSISDN pairs seen on the network with imei_norm. :param cursor: db cursor :param imei_norm: normalized imei :return: subscribers list """ cursor.execute("""SELECT DISTINCT imsi, msisdn, last_seen FROM mon...
291791f21c8f8677d112b6945339c2444c54df28
688,005
import logging def create_dict(timespan, extremes, numbeats, mean_hr, beat_times): """Creates metrics dictionary with key ECG information The metrics dictionary contains the the following info: duration: float, voltage_extremes: float tuple, num_beats: int, mean_hr_bpm: int, beats: list of floats ...
9de6c74067b7d91c619cbfc3d17d640c938b9ea4
688,006
def _get_tile_paths(catalog, item_ids, asset_key): """ Extract the asset paths from the catalog """ items = (catalog.get_item(item_id, recursive=True) for item_id in item_ids) assets = (item.assets[asset_key] for item in items) return [asset.get_absolute_href() for asset in assets]
a14010a4ee5dc5547f9c963ba6cf9223eb54bc37
688,007
def preserve_sesam_special_fields(target, original): """ Preserves special and reserved fields. ref https://docs.sesam.io/entitymodel.html#reserved-fields """ sys_attribs = ["_deleted","_hash","_id","_previous","_ts","_updated","_filtered", "$ids", "$children", "$replaced"] for attr in sys_at...
8934ca1a047ca39d48927bbfce59eeb8098594ae
688,008
def unique_edge_list(network): """ Generates an edge list with only unique edges. This removes duplicates resulting from the bidirectional nature of the edges. :param network_simulator.Network network: source network :return: list edge_list: unique set of edges """ edge_list = [] nodes ...
4d01288ec719b7260cc31edc1bd4c7c5b02907b9
688,009
def reverse_DNA(DNA_string): """ This function takes a DNA string and returns the reverse-complement sequence. It uses the Nucleotides dictionary to change the nucleotides with and iterative for loop. PARAMETERS ---------- DNA_string : string DNA sequence of the FASTA/Q file R...
718e036a56fd5fa508e6d739d6a589908a701a77
688,010
import torch def calculate_segmentation_from_image(model, image): """Note image must be in the correct tensor form. """ output = model(image.unsqueeze(0))["out"].detach().squeeze() probabilities = torch.nn.Softmax(dim=0)(output) return output, probabilities
2237dcc1d0b6e7e8c1f58dca53138a34d3e9bd4d
688,011
import getpass def get_user(): """ Get current user. :return: current user :rtype: str or unicode """ return getpass.getuser()
a01da6239acf1d46d9bb041551b162279e75e36e
688,012
import math def calc_rb_max(n_pe, beam_tot_z, beam_num_ptcl): """ Calculate the maximum radius of the plasma bubble Valid in "strong bubble regime", where rb_max*k_pe >> 1. Args: n_pe: number density of the electron plasma beam_tot_z: total length of the drive beam ...
b2e80992ab5b3c0fc93248d681bcb2c2cb476646
688,014
def get_window_start_times(profileDict): """ Gets the times of the start of the sampling windows used in the profiled run Args: profileDict (dict): Dictionary of values representing an Arm MAP profiled run Returns: List of start times of sampling window """ asse...
6f955551958f48d0c21d2c673f95dd140ff7f8e9
688,015
from typing import List def table_string(table: List[List[str]]) -> str: """Table as list-of=lists to string.""" # print while padding each column to the max column length if len(table) == 0: return "" col_lens = [0] * len(table[0]) for row in table: for i, cell in enumerate(row): col_lens[i] ...
77428da7abd28c6ebbbf32f747e13dc932feb5ee
688,016
def extreme_points_2(contour): """Returns extreme points of the contour""" extreme_left = tuple(contour[contour[:, :, 0].argmin()][0]) extreme_right = tuple(contour[contour[:, :, 0].argmax()][0]) extreme_top = tuple(contour[contour[:, :, 1].argmin()][0]) extreme_bottom = tuple(contour[contour[:, :,...
637e6e9383dd496c7a2a604076ecddf4377b0b18
688,017
def connect(endpoint=None): """Generate connect packet. `endpoint` Optional endpoint name """ return u'1::%s' % ( endpoint or '' )
bce21b5f7796ec26e5e238e68427decf2e34d46d
688,018
def parse_volume_string(volume_string): """Parses a volume specification string SOURCE:TARGET:MODE into its components, or raises click.BadOptionUsage if not according to format.""" try: source, target, mode = volume_string.split(":") except ValueError: raise ValueError("Volume strin...
f47cb756b575d364585cbed06719e27b6481f324
688,019
def use_filter(filter, url, input): """Apply a filter function to input from an URL""" output = filter(url, input) if output is None: # If the filter does not return a value, it is # assumed that the input does not need filtering. # In this case, we simply return the input. ...
a1a0005b7e792eb9a36523709ed93a1bbd826f19
688,020
import sqlite3 def db_retrieve_all(cursor: sqlite3.Cursor, table: str) -> list: """Get all values of a table.""" ret = cursor.execute(f"SELECT * FROM {table}") return ret.fetchall()
c92f0b8a0c25d4f7bb351a28d4f5121f434e872e
688,021
import os import json def get_messages(basepath, mtype): """load list of messages from _message files""" # get message list path = os.path.join(basepath, '_messages_' + mtype + '.json') messages = [] if os.path.exists(path): with open(path, 'r') as msgfile: messages = json.loads(msgfile.read()) return ...
0aca46d4cfc3f556239a4af73f626c792d3bed5b
688,022
import struct def _compute_dc42_checksum(data): """Compute checksum DC42 uses to verify sector and tag data integrity. Args: data: data to compute a checksum for. Returns: a 32-bit (big endian) checksum as a 2-byte string. """ def addl_rorl(uint, csum): """Add `uint` to `csum`; 32-bit truncate; 3...
13d048ed2878e09d638b50208a33957fc2af04b5
688,023
import re def regex_overlap(text, regex): """ for a list of tokens in text and a regex, match it in the tokens and return a list of booleans denoting which tokens are a part of the match """ overlap = [False for t in text] for m in re.finditer(regex, ' '.join(text)): begin, end = m.span() ...
77fbb138cb98f2e4f7a6d14c932c17666cac6c1e
688,024
def get_product_img_href(product_page_object) -> str: """ Get product image href link from product page-object. :param product_page_object: BeautifulSoup4 page object :return: string representation of product image href """ anchor_element = product_page_object.find("figure", {"class": "offer-th...
30fd9781380c5a87eaf19a54977a10f13114d2a0
688,026
def __number_measurements(a, func_axis=None): """ Calculates the number of measurements of an array from the array and the function axis. """ if func_axis == None: return a.size else: return a.size / a.shape[func_axis]
cea5e89077b0f0cf493ee54d2649ef70aa92210c
688,027
def func_6(mol,bits): """ *Internal Use Only* unsaturated non-aromatic nitrogen-containing """ ringSize=[] AllRingsBond = mol.GetRingInfo().BondRings() temp={3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0} for ring in AllRingsBond: unsaturated = False nonaromatic = True Co...
323ee31dfa116a0f13674c7b9d494231f918cccf
688,028
def crop_image_to_bbox(img_arr, X_meta): """Given an image array, crops the image to just the bounding box provided.""" shape = img_arr.shape x_min = int(X_meta['x']) x_max = int(X_meta['x'] + X_meta['width']) y_min = int(X_meta['y']) y_max = int(X_meta['y'] + X_meta['height']) retu...
87e76c0712b6ffa99d7a6bafc74732eea179fffb
688,030
def grid_case_group(self, group_id): """Get a particular grid case group belonging to a project Arguments: groupId(int): group id Returns: :class:`rips.generated.generated_classes.GridCaseGroup` """ case_groups = self.grid_case_groups() for case_group in case_groups: if...
6abde2d46408f98e3281d24b77916055431a5df9
688,031
import numpy def max_type(num): """Returns array converted to supported type with maximum precision. """ return num.astype(numpy.float64)
7176bd93a824f5b06911c6cf63575fda3ba49981
688,032
import re def lineStartsWithDate(line): """ checks to see if the line starts with a date """ match = re.search("\d\d\d\d\-\d\d\-\d\d", line ) if (re.search("\d\d\d\d\-\d\d\-\d\d", line ) ): return True else: return False
f04642987b56056fb191911b5f0c74d6f5e2e656
688,033
import pandas def na_cmp(): """ Binary operator for comparing NA values. Should return a function of two arguments that returns True if both arguments are (scalar) NA for your type. By default, uses ``operator.is_`` """ def isna(x, y): return ((x is pandas.NA or all(x.isna())) ...
6f181e6d4be4c815be030bc652e95acca797877b
688,034
import argparse def parse_args(): """ Parse the input arguments using `argparse` module. Parameters: nothing Returns: args : an instance of the class returned by `parser.parse_args` with the arguments as instance attributes. Output...
20473a5fadc6e7cd8ee054b37e7d9a64a3532425
688,035
def version_tuple(version): """ Convert a version string or tuple to a tuple. Will return (major, minor, release) kind of format. """ if isinstance(version, str): return tuple(int(x) for x in version.split('.')) elif isinstance(version, tuple): return version
01dbb657ced6a9f96ebda18c761d014bf53fd168
688,036
def _dso2info(dso): """Return mangled name of DSO info module. eg. 'my.pkg.libs.adso' -> 'my.pkg.libs.adso_dsoinfo' """ parts = dso.split('.') parts[-1] = '{}_dsoinfo'.format(parts[-1]) return '.'.join(parts)
164d1758d662d5112a1d787323ed33acdba63a81
688,037
def is_torch_not_a_number(v): """checks whether a tortured variable is nan""" v = v.data if not ((v == v).item()): return True return False
03ec2f1c1b151ad6b55f4a8cb15c73f53db11edf
688,038
def accuflux(idxs_ds, seq, data, nodata): """Returns maps of accumulate upstream <data> Parameters ---------- idxs_ds : 1D-array of intp index of next downstream cell seq : 1D array of int ordered cell indices from down- to upstream data : 1D array local values to be acc...
3a581dee6be3ef076876965a25a7ae081f90ecbf
688,039
def topic_exists(client, topic_name): """ Reports if the topic is created Args: client (Kafka Client): The Kafka admin client topic_name (str): the topic name to be checked """ topic_data = client.list_topics(timeout=2) return topic_name in set(t.topic for t in iter(topic_data.to...
824b858d1b7b376e78c5a6b1bae875e874868bdb
688,040
import argparse def check_valid_frac(num) -> float: """Argparse type checker for valid float between 0 and 1""" if (num < 0) or (num > 1): raise argparse.ArgumentTypeError(f"{num} is an invalid percentage") return num
dc24c4ed72024be130805e7da235a713ee5c6f26
688,041
import numpy def log1mexp(x, threshold=numpy.log(.5)): """Computes log(1 - exp(x)) Note to self: Add citation""" #Some type handling if type(x) is not numpy.array: x=numpy.array(x) if hasattr(x, 'shape'): filter_val=x<threshold val=numpy.zeros(x.shape) #x<threshold ...
49780f09720d20d0079031622ffe3b2a34770b4d
688,043
def _from_json(doc): """Invert _to_json()""" if "$numberLong" in doc: return int(doc["$numberLong"]) elif "__nonstring_keys" in doc: nonstring_keys = doc.pop("__nonstring_keys") return {nonstring_keys[k]: v for k, v in doc.items()} else: return doc
f6ebd40a4f375f6d320692328f9a7c362c73f17c
688,044
def _change_memo(amount, coins, T, n): """Helper function for num_coin_changes_memo().""" # Base cases. if amount < 0: return 0 if amount == 0: return 1 if n <= 0 and amount > 0: return 0 # Apply memoization. if T[n][amount]: return T[n][amount] # Sum n...
dacc57c364d803de9fea799a7a43656d387671aa
688,046
import os def get_versioned_dir(repodir, version): """ Return the path to a specific version of a repository. """ return os.path.join(repodir, version)
5a9f959d3443327b6d1e2ccc5e3d0641e918175a
688,048
def filter_allocated_item_from_view(xml_item_list, xml_view_list): """For a type of item from xml, check if a View is activated and if the item is in its allocated item's list""" if not any(j.activated for j in xml_view_list): return xml_item_list filtered_items_list = [] activated_view = '...
bb310a4f67a7c2e4cbc242f38d37cabdcff8ce29
688,049
import re def clean_str(text): """ Apply some standard text cleaning with regular expressions. 1. Remove unicode characters. 2. Combine multiline hyphenated words. 3. Remove newlines and extra spaces. Parameters ---------- text : str Text to clean. Returns ...
9cad22ab843823416ead46ae34dbff0ed991d597
688,050
import re def make_decode_dict(dict, decode_dict, words): """ Make a decoding dictionary that also includes <s> and </s> """ fh2 = open(decode_dict, 'w') fh2.write('<s> sil\n') fh2.write('</s> sil\n') count = 0 for line in open(dict): line = line.strip() if len(lin...
368593f2dce850be18b9c1e0bb1a890b9d740345
688,051
def close_short_position(df): """Function calculates signal to close short position Returns: string: return "Close short position" if condition is met else False """ close_price = df["<CLOSE>"] ma = df["MA"] csp = "" if close_price[-1] > ma[-1] and close_price[-2] < ma[-2]: ...
f4171bd85962c4aa6b1aeeb7ff5d1c2c4d8837df
688,052
def insertion_sort(arr = []): """ 挿入ソートは初めに配列の左端をソート済にする. 未探索領域の左端を取り出して,ソート済の数と右端から順に、 自分より小さい数が現れるまで比較して交換する. 最悪計算量:1 + 2 + ... + N-1 = (N^2 - N) / 2 の比較回数 最良計算量:1 + 1 + ... + 1 = N - 1 の比較回数 計算量はO(n^2) """ N = len(arr) for sorted_idx in range(0, N-1): ref_idx = s...
ee62067084272982e12ccfb75423151c5283d095
688,053
def get_modifiers(target, markup): """ target: a tagItem node in markup markup: a networkx DiGraph representing a ConText markup """ return markup.predecessors(target)
b840eb9064d81ae46024fb733cc136ecf2cee9f8
688,054
def get_protocol(path): """Parse the given protocol. Parse the given protocol and return a dictonary with all test ids and there 'PASS' 'FAIL' values. """ f = open(path, 'r') lines = f.readlines() f.close return dict((line.strip().split(': ') for line in lines if line.strip()))
8c07df021a968da60f570cc2843f16edf4c1ef08
688,055
import pkg_resources def starlist_fd(_starlist_fn): """Starlist file descriptor""" return pkg_resources.resource_stream(__name__, _starlist_fn)
c45d322046e9d19a7fa52d0d766cf54d8f6621b4
688,056
def additionner_deux_nombres(premier_nombre, second_nombre): """ Additionne deux nombres inputs: Deux nombres outputs: Un nombre """ total = premier_nombre + second_nombre return total
652435df9772eaebfe8669a910977a8089be3c09
688,057
import os def create_index(directory, filename='', root=False): """Creates index.html files for the package index""" index = os.path.join(directory, 'index.html') if root: with open(index, 'w') as index_file: index_file.writelines(( '<!DOCTYPE html>\n', ...
0a41cd6caf67dadb103dab98b3e46354685ce968
688,058
def removeOutlier(df_in, col_name): """ This funtion drops all outliers in a pandas dataframe according to the specified column with the IQR method. Input: - df_in: pandas dataframe that the outliers will be removed from. - col_name: name of the column that the IQR will be calculated...
8b489b149740a3bb3b7b2453328b54052cba8b26
688,059
def static_params_to_dygraph(model, static_tensor_dict): """Simple tool for convert static paramters to dygraph paramters dict. **NOTE** The model must both support static graph and dygraph mode. Args: model (nn.Layer): the model of a neural network. static_tensor_dict (string): path of wh...
66d322447f972d9cd8e64bb95023a4b803fba63c
688,060
def accept_peaks_size_width(time, data, peak_inx, index, min_inx, threshold, pfac=0.75): """ Accept each detected peak and compute its size and width. Args: time (array): time, must not be None data (array): the data with teh peaks peak_inx: index of the current peak index: ...
63728b265619566c7b4e23c9149b2b67253e5ab1
688,061
from typing import Counter def to_vocabulary(corpus): """ スペースで分かち書きされた文字列のリストを受け取り、 単語の出現回数を数え上げる。 [(単語,回数),(単語,回数)...]というリストを返す """ words = [] text = [] for line in corpus: l = line.split() words.extend(l) text.append(l) v = Counter(words) return (v,t...
d7e5e5e67cf639b2edeb6208d9c3360579a6f0f0
688,062
def _content_matches(element_def, element): """ Checks for match of content (if provided), must partially match one of the text items in the element. """ if not element_def.content: return True for string in element.strings: if string and str(element_def.content) in string: retu...
e7aa48786e04e37ee3bbe6ddf6665a0e11073d16
688,063
import torch def get_candidate_span(bio_logits, label_mapping): """ Use python for now. Will consider a C++ binding later. :param bio_logits: (batch_size, sentence_length, 3) :param label_mappings: :return: """ preds_tags = bio_logits.argmax(-1).data.cpu().numpy() inv_label_mapping = {v: k for k, v in...
a685d9925fc4d945f83a908b0c93e8018fca04d3
688,064
import base64 def extract_salt(salted_ciphertext: bytes): """ Extract salt and ciphertext from salted ciphertext and returns as a tuple """ encoded_salt, ciphertext = salted_ciphertext.split(b':') salt = base64.urlsafe_b64decode(encoded_salt) return salt, ciphertext
023de8e7288c65564946c020f981c7395d961a48
688,065
def _Backward1_T_Ph(P, h): """Backward equation for region 1, T=f(P,h) >>> "%.6f" % _Backward1_T_Ph(3,500) '391.798509' >>> "%.6f" % _Backward1_T_Ph(80,1500) '611.041229' """ I=[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6] J=[0, 1, 2, 6, 22, 32, 0, 1, 2, 3, 4, 10, 32,...
ae79043acf07b0e144607f415feacf99e1a2495c
688,066
def get_optimizer_variables(optimizer): """Returns a list of variables for the given `tf.compat.v1.train.Optimizer`. Equivalent to `optimizer.variables()`. Args: optimizer: An instance of `tf.compat.v1.train.Optimizer` which has created variables (typically after a call to `Optimizer.minimize`). Re...
dd0fd0933969bba78ed0609ebd14612c39ae5452
688,067
import datetime def datetime_formatter(key, time_format='%Y/%m/%d %H:%M:%S'): """Create a datetime formatting function This factory creates a function that formats a specified key and with a timestamp value from a dictionary into a string. Parameters ---------- key The dictionary ke...
c0a0188e22c6b9dd36b69953543daf6a1f2c3348
688,069
def scale_array(arr, s): """Scale an array by s Parameters: 1. array: a numeric array or list 2. s: scaling factor, real number """ return [a*s for a in arr]
3b7cbec86a73c8e5f99f08ce8eb091ce6aecf4ac
688,072
import os def ftype(path): """returns file extension of [path]""" try: file = os.path.basename(path) i = file.rindex('.') return file[i+1:] except ValueError: return ''
e55c07b64206e4c54d2855441314bc1671d88a3f
688,073
def unwrap_model(model): """ Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. """ # since there could be multiple levels of wrapping, unwrap recursively if hasattr(model, "module"): ret...
4c36d3fa14fd41764c4f3b3352418b8d6981e713
688,074
def get_header(results): """Extracts the headers, using the first value in the dict as the template.""" ret = ['name', ] values = next(iter(results.values())) for k, v in values.items(): for metric in v.keys(): ret.append('%s:%s' % (k, metric)) return ret
e4efb44ea450d08f884a6c38ef24d49ce7e0af5c
688,075
import dataclasses from typing import Union from enum import Enum from typing import Optional def _int_to_enum(field_value: int, field_description: dataclasses.Field) -> Union[int, Enum]: """If the int actually belongs to an Enum field, return an instance of that Enum. """ enum_cls = None if field_de...
6880080ff65a3e88ec8693764a139d6b3f3a55b0
688,076
def unpack_dataset_joint_variables(dataset, n_dof): """ Unpacks a dataset in the format with examples in rows with joint positions, velocities and accelerations in columns (in that order) Returns matrices q, qv, qa; containing rows of examples for joint positions, velocities and acceleratio...
d3152365f777c830888f30dec6aa00b16d246146
688,077
def spell_stats(user): """ Get's the player/boss' def, name and str. Useful as it's stored differently between bosses and players in a battle Returns ------- Any float - The defence of the user. str - The name of the account. float - The defence of the account """ ...
f4fa6425dbf18cf8a7e7a50c44cb3a8092f085ac
688,079
def wordlists(*wl): """ Input is arbitrary number of lists of strings. Output is one dictionary where each string is a key and the count of those strings is the value """ word_dict = {} for i in wl: for x in i: if x in word_dict: word_dict[x] += 1 els...
4af789da735886447c02f089065e30b46f348b22
688,080
def gen_aes_key(size): """Generates a random AES key. This function generate a random AES key from /dev/urandom. :parameter: size : int The key length in bytes, must be 16 (128 bits), 24 (192 bits) or 32 ( 256 bits). :return: A string, the random generated AES key. """ v...
537601f353d28c8f779a65e5057c3a9b7df614fe
688,081
def tokenize_french(sentence): """French language tokenizer """ return sentence.split(" ")
836637fd330062141f8da1a76b54a3a45b7287c1
688,082
def max_divider(divs): """ Наибольший делитель :param divs: list :return: int """ return max(divs)
f3544bf0e8eee6b608d57005999beb285747c846
688,083
def get_no_choke_scorerank(mods: list, acc: float): """ Get the scorerank of an unchoked play. """ if ("HD" in mods or "FL" in mods) and acc == 1: scorerank = "XH" elif "HD" in mods or "FL" in mods: scorerank = "SH" elif acc == 1: scorerank = "X" else: scorerank = "S"...
032e5a1fd5336b1bc4211538646758f3d6568ed3
688,084
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: :param subproblem: :param stage: :param conn: :return: """ # Get project availability if project_availability_scenario_id is not NUL c = conn.cursor() availability_params =...
0394b4ecd8d35659f14704f85a700004bd8557cb
688,085
import torch def softmax(X): """ Entropy-smoothed max, a.k.a. logsumexp. Solves $max_{p \in \Delta^d} <x, p> - \sum_{i=1}^d p_i \log(p_i)$ along dim=2. :param x: torch.Tensor, shape = (b, n, m) Vector to project :return: torch.Tensor, shape = (b, n) Projected vector """ ...
815422860956e60fd9993325cf5d9bee83ffe759
688,086
import torch def matperm2listperm(matperm): """Converts permutation matrix to its enumeration (list) form. Args: matperm: (..., n, n) Returns: listperm: (..., n) - listperm[t,i] is the index of the only non-zero entry in matperm[t, i, :] """ batch_size = matperm.size(0) n = matperm.s...
a825383e3e3c0e48c65fc7100265e2abafe8a4b7
688,087
def is_pure_binary(table): """ Check to see if the table has the propoerties of a pure binary association. That is it only has two foreign keys: 1. It only has two foreign keys, 2. There is a uniqueness constraint on the two keys. 3. NULL values are not allowed in the foreign keys. :param...
0f4da72d3cab3e49b85f1c305fd7deae18cb8f40
688,090
def _get_notice(html): """Pulls title information for the regulation. Parameters ---------- html : bs4.BeautifulSoupt The bs4 representation of the site Returns ------- notice : str The string of the notice """ para = html.find("p", class_="notice0") return para...
f1721c6dd526e88ad90b0780d9fc26f855b39791
688,091
import cProfile def profile_start(): """ Start profile """ prof = cProfile.Profile() prof.enable() return prof
b5696fe54538ca2bf826b2273f2d3c0ab6f2e78b
688,092
def get_default_dict(): """ Return a dict with default value """ default = { 'name': '', 'keyword': '', 'translation_team': [], 'start_date': '', 'total_ep': '', 'dled_ep': '0', 'offset': '0', 'folder': '', } return default
1bd86415d080b0ae7886d19866ed5dac8c89dbda
688,093