content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import hashlib
def sharip(data):
""" Calculate a address hash """
h1 = hashlib.new('sha256')
h1.update(data)
h2 = hashlib.new('ripemd160')
h2.update( h1.digest() )
return h2.digest() | 5bbf228b6a9b7ed8f9540ab8d1c93562497e8ad4 | 653,376 |
def defaultparamsfunc(curlag, sensdict, simparams):
"""
Just a pass through function.
"""
return(curlag, sensdict, simparams) | a184c73c317d9b3c589781ca2d3a1a89c9147800 | 653,377 |
def get_draft_list(service):
"""
prints the list of drafts present in user's draft box
:param service: authenticated and built gmail API service client
:return: list containing iD and subject of drafts
"""
draft_list = service.users().drafts().list(userId='me').execute()
beautiful_draft_lis... | 03a945a211db471f5fd08df764623ca0a38c01cc | 653,378 |
import ast
def _from_list(s: str):
"""Convert a value into a list/tuple/dict."""
# note that the function will fail if the list has other spaces
return ast.literal_eval(s.replace(' ', ",")) | 8925a9e7ac6d91e3a56f64bc377851c62866d4d8 | 653,379 |
from datetime import datetime
def check_validity_of_date_string(date_str: str):
""" Checks if the string is a valid DD.MM string. """
try:
datetime.strptime(date_str, "%d.%m")
return True
except ValueError:
return False | 8eafbcfa20a09c44f3750d5ea520e2447d357dff | 653,380 |
def extract_fields(data, exclude=()):
"""Return a tuple of all fields in the DataFrames within *data*."""
features = set()
for station in data:
features = features | set(station['Data'].columns.tolist())
return sorted(list(features - set(exclude))) | d7e32cc9873b70d8ef43c4fc7ff69fb8a7bf8b61 | 653,381 |
import binascii
import hashlib
def create_credential(macaddress, nonce, upload_key, from_eyefi=False):
"""Returns an EyeFi credential.
Generates the credential used by the EyeFi for authentication purposes. The
credential is generated slightly differently based on if it is EyeFlask
authenticating the... | da10448c9c4b705edf7a1939625bd223a1e2c58e | 653,382 |
import typing
def get_dxq_score_pairs(odds: float) -> typing.Dict[str, list]:
"""
according odd value to get the number of goals scored by the home and away
team in the following situation, such as big, draw, small
:param odds: 2.5
:return: dict
result = {'home_win': [(1, 0), (2, 0), ... | 59b48bbe6d63fa9ca79166088882c7210d73e0a8 | 653,383 |
def response_formatter_api_doquery(res):
"""Convert API_DoQuery response to usable format."""
if not res['table']['records']:
res['table']['records'] = {'record': None}
else:
if not isinstance(res['table']['records']['record'], list):
res['table']['records']['record'] = [res['tab... | 5e0de9e3e22e378876657a4547fc03606ecce342 | 653,385 |
def spot_is_free(spot, candles, light):
"""
A spot is NOT free if the horizontal and vertical distance between
that and the light is less than the light strength
"""
for candle in candles:
x_dist = abs(candle[0] - spot[0])
y_dist = abs(candle[1] - spot[1])
if x_dist < light a... | 97d5ca3e3a40d914f4291ff6f7e047aa8bfb7d87 | 653,386 |
def _format_strings(the_string='', prefix='', suffix=''):
"""Small convenience function, allows easier logic in .format() calls"""
if the_string:
return '{0}{1}{2}'.format(prefix, the_string, suffix)
else:
return '' | ef3ac0f8d0972d8d562a763f6255b197951acc26 | 653,387 |
def is_license_plate(string):
"""
Retruns true when the string is in Ontario license plate
with example format such as ABCD-012, with 4 letters, followed
by a hyphen, and 3 numbers.
"""
if string[0].isalpha():
if string[1].isalpha():
if string[2].isalpha():
if... | 0e93b0cd54bc2133cd6da88e8dddc5d2e21b17a8 | 653,388 |
import torch
def extract_logits(out, task_ids, n_classes, device):
"""
Extract logits corresponding to task_ids from out.
Args:
out: Predictions
task_ids: Task ids
n_classes: Number of classes per task
"""
indices = (
(torch.arange(n_classes * out.size(0)) % n_clas... | 551ee2eb2e6319a02c0e905b38c310379cf88a29 | 653,389 |
def task_flake8(output_file):
"""Run flake8 over the code base and benchmarks."""
opts = ''
if output_file:
opts += f'--output-file={output_file}'
return {
'actions': [f"flake8 {opts} scipy benchmarks/benchmarks"],
'doc': 'Lint scipy and benchmarks directory',
} | 7e6dd2a9b49216e3ade2852e86c783f388d97f62 | 653,390 |
def get_labeled_atoms_alkoxy_decomposition(molecule):
"""
input is a reaction of molecule objects from RMG-mol with proper labeling
output is a dictionary with keys 'radical', 'carbonyl oxygen' and 'carbonyl carbon'
"""
output = {}
for atom in molecule.atoms:
if atom.label == '*3':
... | 9712db3c30112eb34efd9c3fcb4a5920cb96d128 | 653,391 |
def GetMachMsgOOLDescriptorSummary(desc):
""" Returns description for mach_msg_ool_descriptor_t * object
"""
format_string = "{: <#020x} {: <#020x} {: <#010x}"
out_string = format_string.format(desc, desc.address, desc.size)
return out_string | 2c853befaedf0f7f53b0ce258824a61a9d73031c | 653,393 |
def has_duplicates(t):
"""Returns True if any element appears more than once in a sequence.
t: list returns: bool
"""
s = t[:] # make a copy of t to avoid modifying the parameter
s.sort()
for i in range(len(s)-1):
if s[i] == s[i+1]: # check for adjacent eleme... | 2200d4c5c5b22937f60e560937794d7419082f40 | 653,394 |
def _tx_resource_for_name(name):
""" Return the Transifex resource name """
return "taiga-back.{}".format(name) | 9f54f40776c5cbbbb08169114623ef521414a625 | 653,395 |
import os
def extant_file(path, name=None, allow_errors=False):
""" Verify file exists or report error """
if os.path.isfile(path):
return path
label = '`{}` with path '.format(name) if name is not None else ''
skipping = ' Skipping...' if allow_errors else ''
msg = 'File {label}{path} is ... | 20136cb2f8d73ad8b86af3a78fc655fb2e7798e3 | 653,396 |
import re
def remove_svg_dimensions(svg_data):
"""Remove explicit height and width attributes from an svg, if present."""
desired_index = 0
svg_lines = svg_data.split("\n")
for index, line in enumerate(svg_lines):
if "<svg" in line:
desired_index = index
break
line = svg_lines[desired_index]
line = re.... | 7a9c011d8907632825101baa84b7093242d42b1b | 653,397 |
def hex_to_rgb(hex_str):
"""Convert html hex codes to RGB tuple."""
hex_str = hex_str.strip("#")
return tuple(int(hex_str[i : i + 2], 16) for i in (0, 2, 4)) | 45d13aa5290b2a17205dc63899f6d7a9701434bb | 653,398 |
def _concatenate_statements(statement_list):
"""
concatenate statements
is_put_or_get is set to True if the statement is PUT or GET otherwise
False for valid statement. None is set if the statement is empty or
comment only.
:return: a statement, is_put_or_get
"""
valid_statement_list = ... | 068e3e3d1932d308dd9903fa20041d928db75aec | 653,399 |
import re
import numpy
def dict2matrix(in_dict):
"""
This function returns a matrix from a dictionary.
Each key from in_dict must have 2 numbers representing [row][colum].
They can be separated by any characters.
{'m|1_1': 1, 'm|1_2': 2, 'm|2_1': 3, 'm|2_2': 4, ..., 'm|i_j':n}
_ _
| |
| 1 ... | bd3ea27c66687e8665b6598c59fa4bb36d739ba4 | 653,400 |
def insert_bold(means, stds, table, use_latex):
"""Draw predictions and ground truth annotations
on the image.
Parameters
----------
means : ndarray
Means from experiments.
stds : ndarray
Standard deviations from experiments.
table : str
Tabul... | eb3236da7949979be5bde2cf2dac3ce4f59f6312 | 653,401 |
def make_collections_query(value, tag=None):
"""Creates sql and values to query database for collections."""
# init buffers
sqls = []
values = []
# init value
value_like = "%%%s%%" % value.lower()
# search by DBID
if tag == '[ID]':
sqls.append("(id = ?)""")
... | dc3a8697e5cafc9a757d9a35cc28aa0a96f3d7b2 | 653,402 |
def count_from_0(index, collection):
"""Numbering function: consecutive integers starting at 0."""
return index | bc01bc8e46e913c325e4972b3bd71cd4d2543237 | 653,403 |
def sanitize_id(int_id):
"""
Return int_id as either an integer or None, if it is not convertible.
For use with model find function where either integer or None is acceptable, but
input from the controller is either a string representation of the integer or None.
This handles the conversion and swa... | 1d7e53def5619c580c798b7adf0d3101f498f95d | 653,404 |
from pathlib import Path
import configparser
def lit_config(filenames: list[Path]) -> dict:
"""Lecture du fichier de configuration.
Args:
filenames: liste de répertoires où trouver le fichier de configuration.
Returns: dict créé à partir de la section 'paths',
contenant des répertoires e... | 2a76888d262610aca22659b960b13824df5fc16f | 653,405 |
def get_json_carts(response):
"""Get rendered cart's templates from JsonResponse."""
return response.json()['header'], response.json()['table'] | 5d80db9330390dbef74f27cc82d2a84de211b0e5 | 653,407 |
def generate_mts_string(groups_of_fgs, R_before=True, n_R=1):
"""groups_of_fgs is a list of tuples, containing an iterable and an integer.
E.g.
[([3], 1),
([1,2], 10),
([0], 4)
]
We execute the first group [3] once per timestep.
We execute the second group [1,2] 10 times per timestep.
... | c605dc3db1a050ec7f5c6238ef265ee8f74b0505 | 653,408 |
def organize_data(ds, limit=''):
"""
Organize data for easy use in the evaluation
'original','original+ctf_by_predicted_causal','original+ctf_by_annotated_causal','original+ctf_by_all_causal','original+ctf_by_human'
"""
train_data = {}
if(limit == 'ct'): # only those have counterfactuals as... | c98c274bd096f2d5bf408729bfabd254351d58b1 | 653,409 |
def list_average(score_list):
"""
Utility function to get the average of a list.
Args:
score_list: List containing real numbers that must be averaged
Returns:
Float representing the average of the values in the provided list
"""
if len(score_list) == 0:
return -100
... | cc50f53277850e9837e36b54f3f065e7278f6b25 | 653,410 |
def get_azs(region=''):
"""The intrinsic function Fn::GetAZs returns an array that lists all \
Availability Zones for the specified region.
Because customers have access to different Availability Zones, the
intrinsic function Fn::GetAZs enables template authors to write
templates that adapt to the ... | 44472ea5336a1d389b97b7c24db7c8c70302cd54 | 653,412 |
def parse_req_file(fname, initial=None):
"""Reads requires.txt file generated by setuptools and outputs a
new/updated dict of extras as keys and corresponding lists of dependencies
as values.
The input file's contents are similar to a `ConfigParser` file, e.g.
pkg_1
pkg_2
pkg_3
[extras... | a677d85dfb72c80404ca527bbd059350d5c37ba5 | 653,413 |
from typing import Iterator
def ascii_table(dictset: Iterator[dict], limit: int = 5):
"""
Render the dictset as a ASCII table.
NOTE:
This exhausts generators so is only recommended to be used on lists.
Parameters:
dictset: iterable of dictionaries
The dictset to render
... | 7dcfb922f01b5642265ad59a03f5b3e580199e43 | 653,414 |
def clean_text(element):
"""
Removes whitespace from an element's text. Linebreaks and other
whitespaces inside a single tag are meaningless. IE:
>>> e = BeautifulSoup('''
... <p>This whole thing
... is just one line. No need
... for breaks!!!
... </p>
... ''')
>>> Piece.c... | 85789ddd5313ce79ca2e9bc77e2cab277661f55f | 653,415 |
def item_version(item):
"""
Split the item and version based on sep ':'
"""
sep = ':'
count = item.count(sep)
if count == 0:
return item, None
elif count == 1:
return item.split(sep)
else:
msg = "Found multiple instances of '%s'" % sep
raise ValueError(msg... | 77e595b32aee2ffb28971f5f1f1b0e1cafaf28e8 | 653,416 |
def version_check():
"""Check Version number to see if exploitable before sending reset request"""
return True | 9386c6f6e944d887701ab4e628aafbea1f9103ef | 653,417 |
def bits_table_h() -> dict[int, int]:
"""The table of the maximum amount of information (bits) for the version H.
Returns:
dict[int, int]: Dictionary of the form {version: number of bits}
"""
table = {
1: 72, 2: 128, 3: 208, 4: 288, 5: 368, 6: 480, 7: 528, 8: 688, 9: 800,
10: 97... | 30e9f42605d650f1d541e73a815b9b60632442a1 | 653,418 |
def compute_errors(df, var, n):
"""Return an array containing the standard error of variable 'var' at each match for all account_ids in dataframe 'df' over 'n' matches"""
games = df.groupby(['SID', 'game_number'], sort=False).head(n)
errors = games.groupby('episode_number', sort=False)[var].sem().tolist()
... | a51d5b1a3dcc3711aa5b848491e535429c605e54 | 653,419 |
def fibonacci(n):
"""
斐波那契数列:1,1,2,3,5,8,...
:param n: 要求第 n 个斐波那契数
:return: 第 n 个斐波那契数
"""
if n <= 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2) | be271ff003bdf0a405cae75f88ca040aad5ed33e | 653,421 |
import re
import json
def parse_label_map(label_map):
"""Provides a short implementation of label map parsing.
Args:
label_map: The label map data, as a UTF-8 string.
Returns:
The label map dictionary.
Example output:
dict {
1: 'label',
2: 'label2'
}
"""
# Converts... | 250108596f55efc0c09816f55df082cc813fc8a3 | 653,423 |
def llvm_frontend(input_file, args):
"""Return LLVM IR file. Exists for symmetry with other frontends."""
return input_file | 2f01384430438b139de422530105065d55a8aff6 | 653,424 |
import os
import pkg_resources
def get_include():
"""Returns a path to the directory containing the C header files"""
def is_ok(path):
return os.path.exists(path) and os.path.isdir(path)
package_path = os.path.dirname(os.path.realpath(__file__))
install_path = os.path.join(package_path, "in... | c0e081f95132e1eb7f0020ec591532c4a147a337 | 653,425 |
import subprocess
def pdf_to_text(pdf_path):
"""
Return text content from given PDF on disk.
Requires pdftotext from poppler-utils to be installed
"""
return subprocess.check_output(['pdftotext', pdf_path, '-']).decode() | 6f333a036707600c7526579c598dcf1e4808e238 | 653,426 |
import numpy as np
def select_image_qc(id_list, mri_qc_subj):
"""Select image from several scans according to QC.
Args:
id_list: List of images identifiers to choose among
mri_qc_subj: Dataframe containing list of QC of scans for the subject
Returns: int - Chosen image identifier
"""... | c592acb73c52561713eee601abd45d8c70ad884e | 653,427 |
import json
def safe_json_load(in_str):
"""
safely load json strings as dictionaries
:param in_str: string with encoded json
:return: dict
>>> safe_json_load('{"bob": 5}')
{'bob': 5}
>>> safe_json_load('{"bob": [1,2,3]}')
{'bob': [1, 2, 3]}
>>> safe_json_load('{"bob": [1,2,3}')
... | 860ec8758a752cafde1b017d24392f922fc36844 | 653,429 |
def colPurpleGrey():
"""List of 6 purple-grey colors as RGB."""
col = [(220, 95, 189), (208, 152, 238), (153, 86, 136),
(148, 145, 123), (123, 102, 210), (215, 213, 197)]
# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for j in range(len(col)):
r, ... | 9f625314f17ad0bc276400c45aa24948fd73fabf | 653,430 |
def is_reprinting(title: str) -> bool:
"""
Check if a string contains some substrings.
"""
is_2nd_printing = ("2nd Printing" in title) | ("Second Printing" in title)
is_3rd_printing = ("3rd Printing" in title) | ("Third Printing" in title)
is_4th_printing = ("4th Printing" in title) | ("Fourth P... | 9e9db9bcbce64fd907417eac3643f52be42568c7 | 653,431 |
from typing import List
import tokenize
def first_token(file_tokens: List[tokenize.TokenInfo]) -> tokenize.TokenInfo:
"""
Returns:
First token of provided list.
"""
return file_tokens[0] | 31651480f38dd7f7915af302457af36f8abcbc59 | 653,432 |
def entity_dict_to_list(entity_dict, entity_type='all'):
""" returns a list of entities from the entity dict """
if entity_type == 'all':
output_list = []
for classification in entity_dict:
for item in entity_dict[classification]:
output_list.append(item)
... | 7e3b7234e0514b5e5dde302387133c96ea07b776 | 653,433 |
def dfs(nxobject, initial, goal, compute_exploration_cost=False, reverse=False):
"""the no-oop way!"""
frontier = [{'label': initial, 'parent': None}]
explored = {initial}
number_of_explored_nodes = 1
while frontier:
node = frontier.pop() # pop from the right of the list
number_of... | 1dd7b032f530b81978cd59bd27261b0742c3fa4a | 653,434 |
def pretty_dict(d, indent=0):
"""Pretty the output format of a dictionary.
Parameters
----------
d
dict, the input dictionary instance.
indent
int, indent level, non-negative.
Returns
-------
res
str, the output string
"""
res = ""
for k, v in d.item... | 868c102e70bd477960bf29dc8040eda50b13fffa | 653,436 |
import re
def javadoc(comment):
"""Basic javadoc conversion to reStructuredText"""
# @param
comment = re.sub(r"(?m)^([ \t]*)@param([ \t]+)([a-zA-Z0-9_]+|\.\.\.)([ \t]+)",
"\n\\1:param\\2\\3:\\4", comment)
# @param[direction]
comment = re.sub(r"(?m)^([ \t]*)@param\[([^]]*)\]([... | 73f8fb420821a99f88d7514e3a405c220b5b22fd | 653,437 |
import os
def awhere_api_key():
"""Fixture that returns the key used to
connect to the aWhere API.
"""
return os.environ.get("AWHERE_API_KEY") | 6f4b71d13ad56e6321b90c06f56351fb9a65cd9c | 653,438 |
def get_keyword(token):
"""If ``token`` is a keyword, return its lowercase name.
Otherwise return ``None``.
"""
if token.type == 'ident':
return token.lower_value | 2f518754456d98453cfb379a9bae08100b7e7648 | 653,439 |
def clean_full_uri(request):
"""Return the full URI without querystrings"""
return '%s://%s%s' % ('https' if request.is_secure() else 'http',
request.get_host(), request.path) | 6d9b067fd1ce40a4d27619e4b60941cf71afa93a | 653,440 |
def str_to_bool(string_in: str):
"""convert a string to boolean
Args:
string_in (string): Text from config file value
Raises:
ValueError: Cannot convert the string to a bool as it isn't True or False
Returns:
Boolean: True/False value
"""
if string_in.lower() == "true"... | 1074878b8da7a0d10fd128309ec6215746eb8bfb | 653,441 |
def find_twin(device_id, device_list):
"""
Locate the emulated twin of source device with identifier device_id.
Parameters
----------
device_id : str
Identifier of original device for which the twin is located.
device_list : list
List of device dictionaries in project fetched by... | 9bad722712069b86cd1912a7daadd81253f0f578 | 653,442 |
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int , the length of the returned array
"""
if not nums:
return 0
pointer = 0
for n in range(1,len(nums)) :
if nums[n] != nums[pointer]:
p... | 7e98646efb81fcb66af1dae84f058fc8b1c530a8 | 653,443 |
def f(x):
"""does some math"""
return x + x * x | 095491436abeb67d907855da95baf1cbc7f3bb13 | 653,444 |
def is_dict(obj):
"""
Checks if a given sequence is a dictionary.
Parameters
----------
obj : object
The input argument.
Returns
-------
test result : bool
The test result of whether seq is a dictionary or not.
>>> is_dict([1, 2, 3])
False
>>> is_dict((1, ... | 17ae4d761699e6b7a52a780aacdeb9f23da26716 | 653,445 |
def judge_same_decomp(profile1, profile2):
"""
Judge whether two profiles have identical decomposition products
"""
if len(profile1) != len(profile2):
return False
for step in range(len(profile1)):
ratio1, (decomp1, e1) = profile1[step]
ratio2, (decomp2, e1) = profile2[step]
... | 5c81fe5c2de4c234ec03f33991f0310191d06446 | 653,446 |
import requests
def get_raw(url):
"""
A memoizing wrapper for requests.get, to avoid sending duplicate requests
"""
return requests.get(url) | dbd6190828c7a061223e6337eb2457b5066427b7 | 653,448 |
import os
import sys
def get_abs_path(path: str) -> str:
"""
:param path: a path
:returns: an absolute path, corrected to CygWin path for Windows
"""
abs_path = os.path.abspath(path)
if sys.platform == "win32":
abs_path = abs_path.replace("C:\\", "/cygdrive/c/").replace("\\", "/")
... | ef8c2cb14f891af19e08ac9e48ddad65d5300165 | 653,449 |
def countTokens(vendorRDD):
""" Count and return the number of tokens
Args:
vendorRDD (RDD of (recordId, tokenizedValue)): Pair tuple of record ID to tokenized output
Returns:
count: count of all tokens
"""
return vendorRDD.map(lambda x: len(x[1])).reduce(lambda a, b: a + b) | 6c8070c799495edbe12123420c4f6703ce13127f | 653,450 |
def common_op_info(json_file):
"""
Create more detail info
:param json_file: origin json file
:return: origin json file
"""
json_file["L1_addr_offset"] = 0
json_file["L1_fusion_type"] = -1
json_file["L1_workspace_size"] = -1
json_file["addr_type"] = 0
json_file["slice_offset"] = ... | 25f7037c92970832522e431dd4a1ee6ff265e2ec | 653,451 |
def process_annotation(annot):
""" This function process the annotation to extract methods having given annotation
@parameters
annot: Annotation condition (Ex: @Test)
@return
This function returns starting and ending character of the annotation"""
annot_start = an... | 3173ca57ba23009316d5dbeaf91f0b8110bc67c8 | 653,452 |
def id2word(ids, vocab):
"""Summary
Parameters
----------
ids : TYPE
Description
vocab : TYPE
Description
Returns
-------
TYPE
Description
"""
words = []
id2words = {v: k for k, v in vocab.items()}
for s in ids:
this_sentence = [id2words.... | 35003e78f82b3f7dce019de1b03df1aa6299d4c2 | 653,453 |
def invoke_assertionError():
"""
Raised when an assert statement fails.
"""
a = 0
assert a != 0
return a | 26c52645e39e1c1fe4cf142782b57664e7e369df | 653,454 |
import ctypes
def create_string_buffer(value, size=None):
"""Create a ctypes string buffer.
Converts any string to a bytes object before calling
ctypes.create_string_buffer().
Args:
value (object): value to pass to ctypes.create_string_buffer()
size (int, optional): sze to pass to ctypes.cre... | edf2534a1fe7f8fc0f6fbf962e48c388268d8ca8 | 653,455 |
from typing import Any
from typing import MutableSequence
def aslist(thing: Any) -> MutableSequence[Any]:
"""Wrap any non-MutableSequence/list in a list."""
if isinstance(thing, MutableSequence):
return thing
return [thing] | 311a7e30567f6cf9632201315ab447b1aa085ff2 | 653,456 |
def display_dup(dup_result):
"""Display the duplication check results."""
lines = [k + ": " + ", ".join(v) for k, v in dup_result]
return lines | bcaab47751a532cd6fed2e6f1bad9ce9dbb7f0a9 | 653,457 |
import multiprocessing
def _run_in_process(target, *args, **kwargs):
"""Runs target in process and returns its exitcode after 10s (None if still alive)."""
process = multiprocessing.Process(target=target, args=args, kwargs=kwargs)
process.daemon = True
try:
process.start()
# Do not nee... | 4ac57947c821a02b8e0ffe55f2f577a7847f248b | 653,458 |
def elev_to_pres(elev):
"""Given an elevation in feet, determine the pressure level it normally
occurs at."""
return elev / 100 | ff1ff81f4fe8cfcfc7886a685d5098d8bcd36cc7 | 653,459 |
import json
def generate_plot(run_dir, y_fct):
""" Generates commands for PGF group plot.
Args:
run_dir: source data for plot
y_fct: how to calculate
Returns:
list of plot groups
"""
plots = []
for model_id in ['code-cushman-001', 'code-davinci-002']:
... | 2afe1fd32c11cdc5af296ecf22ed87f0da05cd5b | 653,461 |
def total_after(integer_number):
"""Returns the total number of grains on the chess board for given number of squares.
See README file for how it is calculated.
The calculation is essentially a Geometric series where a=1, r=2 and the sum of such a series is given by
a(1-r**n)
... | db5a7a15be3c637f4aa8bc2446387750755b85a7 | 653,462 |
from typing import Dict
import math
def logarithmic_utility(
utility_params_by_good_id: Dict[str, float],
quantities_by_good_id: Dict[str, int],
quantity_shift: int = 1,
) -> float:
"""
Compute agent's utility given her utility function params and a good bundle.
:param utility_params_by_good_... | 477e7f098e0721894a2ab0e3647e341a34677141 | 653,463 |
def parse_as_numeric(value, return_type=int):
"""
Try isolating converting to return type, if a ValueError Arises then return zero.
"""
try:
return return_type(value)
except ValueError:
return 0 | 083824818b2a7dbe4d183f55ac2cf43e6cdfdcf4 | 653,465 |
def root_finder(node):
"""Utility for getting the root node
"""
if getattr(node, 'root_node', None):
return node.root_node
parent = node.parent
if parent and getattr(parent, 'root_node', None):
return parent.root_node
else:
for n in node.walk_reverse(loopback=True):
... | 7278da0a1d94bd21d2dd9d5be5fd5a8beb95ee00 | 653,466 |
def receive_all(sock, n):
"""
Helper function to fully receive an arbitrary amount of data from a socket.
:param sock: Socket connection
:param n: Number of bytes to receive
:return: Received data
"""
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if n... | a510a4878238500c101e9660dba47188bc7d0ba6 | 653,467 |
def convert_tokens_to_ids(tokenized_sentences, words_dict, embedding_word_dict, sentences_length,
unknown_word_id, end_word_id):
"""
Convert tokenized sentences based on word_list dictionary to embedding_word_dict dictionary.
:param tokenized_sentences: list of sentences [0, 9, 5].... | 63230583b27f443dba8979cf3c65224771c0473e | 653,468 |
from typing import Counter
def get_validated_inputs(sysargs):
"""Quick and dirty config parsing/validation."""
# clean & coerce sys.argsv input
args = []
for arg in sysargs[1:]: # omit first entry (it's just the filename)
try:
args.append(int(arg))
except:
... | e6de3f5a6cecc60642610a18ca1f04f8a9177ea3 | 653,469 |
def get_dict_modes(dict):
"""Finds the keys of the modes of a dictionary
@param dict: A dictionary of the form {"key":#}
"""
highest_count = dict[max(dict)]
modes = []
for key in dict:
if dict[key] == highest_count:
modes.append(key)
return modes | 2952395f9989aa77e008cb351fd99c5de5544788 | 653,470 |
import requests
def fetch_ontologies(enhanced_keywords):
"""
Fetch the connected ontology for each enhanced keyword.
Parameters
----------
enhanced_keywords: list
List of enhanced keywords in string format
Returns
-------
A list of dictionaries. Each one containing the ontolo... | f38580641683b9128febdc8ea180c0f51ceb50b1 | 653,471 |
def entity_key(entity):
"""
Generate a key for the given entity that is unique within the
project.
"""
key = entity.key or entity.string
return ":".join([entity.resource.path, key]) | 7872d209c6eef1054e49d2978d83c988a354b61a | 653,472 |
import re
def split_entries(text, split_expr):
"""Splits text into entries according to split expression"""
return re.split(split_expr, text)[1:] | 224c682f5b9e90fd86fd3d0ba07e33835a92b472 | 653,473 |
def custom_attention_masks(input_ids):
"""Creates attention mask for the given inputs"""
attention_masks = []
# For each sentence...
for sent in input_ids:
# Create the attention mask.
# - If a token ID is 0, then it's padding, set the mask to 0.
# - If a token ID is > 0, t... | ab38c8a0cbd23da4937bdd44785b1d5a3ab08748 | 653,474 |
def check_nodes_count(baremetal_client, stack, parameters, defaults):
"""Check if there are enough available nodes for creating/scaling stack"""
count = 0
for param, default in defaults.items():
if stack:
try:
current = int(stack.parameters[param])
except Key... | 378526962a8417221947bc0346df66d651eb69cb | 653,475 |
import binascii
def unhexlify(blob):
"""
Takes a hexlified script and turns it back into a string of Python code.
"""
lines = blob.split('\n')[1:]
output = []
for line in lines:
# Discard the address, length etc. and reverse the hexlification
output.append(binascii.unhexlify(li... | 074edf1359f404e9de14da1cccf3952812ca7cb7 | 653,476 |
def ExampleParam(request):
"""Placeholder to force multiple executions of the test"""
return request.param | 62f0adc74bb6fa666a0ea57562ca8670052fad05 | 653,477 |
def make_geotransform(x_len, y_len, origin):
"""
Build an array of affine transformation coefficients.
Parameters:
x_len (int or float): The length of a pixel along the x axis.
Generally, this will be a positive value.
y_len (int of float): The length of a pixel along the y axi... | 2eb38a36e59130713457ce03dd51281edec0d1c5 | 653,478 |
def choices(dateformat=0, timeformat=0,
parse_vdirsyncer_conf=True,
create_vdir=False,
default_calendar='',
write_config=True):
"""helper function to generate input for testing `configure`"""
confirm = {True: 'y', False: 'n'}
out = [
str(dateformat), ... | 957906520ddb6a9a130ba4756d8c607e0bf0e9d6 | 653,479 |
def pretty_print(parsed_file):
"""
We just print so it looks decent in a terminal
"""
indented_uc = ' ' + parsed_file['uncommented_content'].replace('\n', '\n ')
return '{origpath} ({artifact}):\n{indented_uc}'.format(
origpath=parsed_file['origpath'],
artifact=parsed_file['art... | e2ab07a6b1ff36f678f96777fbcb2aca3847a07e | 653,480 |
import glob
import os
def discoverRiplDecayFiles(directory):
"""
Discover the RIPL decay/level files in the specified directory.
RIPL decay/level files are like z001.dat where the number represents
the atomic number of the nuclides within.
Parameters
----------
directory : str
fi... | 5e2d3ad49863f08e8b03716703f89263b8891228 | 653,481 |
import os
import json
def get_google_adj_cls_from_s3(s3_resource, bucket_name, prefix='') -> dict:
"""
Load Alphabet Inc. stock json serialized data from S3 resource
:param prefix: prefix of the path where the file is located
:param s3_resource: s3 resource to get data from
:param bucket_name: s3 ... | 9743d90cea4c5e6d9181859cc899371612f8ff8a | 653,482 |
def _nb_subst_metric(seq1, seq2, subst_dict, as_similarity=False):
"""Computes sequence similarity based on the substitution matrix.
Requires that sequences are pre-aligned and equal length.
Operates on strings and a dict substitution matrix"""
assert len(seq1) == len(seq2)
def _sim_func(s1, s2, su... | 0f6a612d0b93e5c792b614e1363ee511e58134ec | 653,483 |
def mul(a,b):
""" component-wise 3 vector multiplication"""
return [a[0]*b[0],a[1]*b[1],a[2]*b[2],1.0] | 4298c1d178fc6f02cb3aa3c7e7012fe732560aa1 | 653,484 |
def _Backward3b_T_Ph(P, h):
"""Backward equation for region 3b, T=f(P,h)
>>> "%.7f" % _Backward3b_T_Ph(20,2500)
'641.8418053'
>>> "%.7f" % _Backward3b_T_Ph(100,2700)
'842.0460876'
"""
I=[-12, -12, -10, -10, -10, -10, -10, -8, -8, -8, -8, -8, -6, -6, -6, -4, -4, -3, -2, -2, -1, -1, -1, -... | 9d9e81345f82bf87f4cae70bb85d7b9e6101692d | 653,485 |
def corrigir_palavra(cad_car): # 1.2.1
""" corrigir_palavra : str --> str
Esta função recebe uma cadeia de carateres que representam uma palavra (potencialmente
modificada por um ssurto de letras) e devolve a cadeia de carateres que corresponde à
aplicação da sequência de reduções, da seguinte forma, s... | 402f696913ac712768f61a4c10a26536d154006d | 653,486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.