content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import csv
def read_test_data(filepath, patch=False):
"""
Args: - path of the folder containing the tests data
Return: - list containing the unpatch test data's names
"""
if patch:
"""
Args: - path of the folder containing the tests data
Return: - list containing all the... | ae2792e3440a9a2f5f404d02f69eafbb4dd3cf9e | 678,343 |
from typing import Tuple
import math
def measure_to_ma2_time(measure: float, resolution: int) -> Tuple[int, int]:
"""Convert measure in decimal form to ma2's format.
Ma2 uses integer timing for its measures. It does so by taking
the fractional part and multiplying it to the chart's
resolution, then r... | d10e47c0e2c91288676a14890663509468bbe95d | 678,345 |
import uuid
from datetime import datetime
def make_event(name, payload, safe=True, idempotent=True):
"""
Build an event structure made of the given payload
"""
return {
"id": str(uuid.uuid4()),
"name": name,
"created": datetime.utcnow().isoformat(),
"safe": safe,
... | 9b6d8677354416f27a78448ff16ba54565c12bdb | 678,346 |
import collections
def numIslands(grid):
"""
Islands counting algorithm
This function are publicly available from: https://leetcode.com/problems/number-of-islands/discuss/121164/Python-BFS-and-DFS-solution
"""
if not len(grid):
return 0
nofisland = 0
visited = {}
nrow = len(gr... | 8eecd929e55204fbf999bcb21951941a896fbb15 | 678,347 |
def firewall_rule_group_update_payload(passed_keywords: dict) -> dict:
"""Create a properly formatted firewall rule group payload.
{
"diff_operations": [
{
"from": "string",
"op": "string",
"path": "string"
}
],
"di... | 1dc54172b8f0d7d15b7333b7ea1e69a4d7ab49b5 | 678,348 |
def getUserNick(user: int) -> str:
"""获取用户昵称"""
return "[GETUSERNICK(%d)]" % user | 8fd9aa3ec51f303c46acbe84c176bfd3c5fad496 | 678,349 |
import time
def now_time():
"""20370307133007"""
return time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) | b3ef6c0eea1534245fdcec568a59f2354a613e2c | 678,350 |
def as_dict(val, key):
"""Construct a dict with a {`key`: `val`} structure if given `val` is not a `dict`, or copy `val` otherwise."""
return val.copy() if isinstance(val, dict) else {key: val} | 15057a88fc69aab0e12ba73065e6dccf040077b5 | 678,351 |
def secondMap(baskets, candidates):
"""
baskets - [[a,b,c], ...]
candidates - a list of candidates generated by the first mapreduce. a candidate is either an integer or a tuple of integers
"""
candi_dict = {}
for candidate in candidates:
candi_dict[candidate] = 0
for basket in bask... | 9f83d11f2a5cd1c3b038e4d4d37344d00c25f69a | 678,352 |
def multiply(number_1: int, number_2: int) -> int:
"""Multiply two numbers_together"""
return number_1 * number_2 | b87ffd7c48d64b7b0dbd0d9e9acb65e90e7ed9fa | 678,353 |
import base64
def get_chat_download_link():
"""Generates a link allowing the data in a given PDF to be downloaded
in: PDF file
out: href string
"""
with open("chart.pdf", "rb") as pdf_file:
base64_pdf = base64.b64encode(pdf_file.read()).decode()
href = f'<a href="data:file/pdf;base64,... | a5b95c2301eb83be0d8373282c1c5832fa37cc03 | 678,354 |
import hashlib
def get_str_md5(str):
""" 计算字符串md5值 """
md5 = hashlib.md5(str.encode('utf-8'))
md5_digest = md5.hexdigest()
return md5_digest | 68e2c17196afdc565692a995e94b45139b15d81e | 678,355 |
def resolve_obj_path(obj_path: str) -> tuple:
"""Resolve object module and attribute names from dot notated path.
Example:
>>> _resolve_obj_path("uuid.uuid4")
("uuid", "uuid4")
>>> _resolve_obj_path("foo.bar.baz.uuid4")
("foo,bar.baz", "uuid4")
"""
module_name, attribute... | 7107b831cabdeeab4c1fcf826371794a69da5523 | 678,356 |
def incrochet(strg):
""" get content inside crochet
Parameters
----------
strg : string
Returns
-------
lbra : left part of the string
inbr : string inside the bracket
Examples
--------
>>> strg ='abcd[un texte]'
>>> lbra,inbr = incrochet(strg)
>>> assert(lbra=='ab... | 2c589fd1b6f1a840cf1bda6513a521ab3cafcb0d | 678,358 |
def clipper(arr, frac=.01):
"""
Clips first dimension of array by some fraction of the length of the dimension
"""
tot = arr.shape[0]
num = int(tot*frac)
return arr[:-num,...] | 69eac2aecd559642fff536b8571f7dbe64207b89 | 678,359 |
def reachHead(path, graph):
"""
Whether the path can be extended at head, and the extended path is still
a simple path.
"""
former_nodes = filter(lambda n: path[0] in graph[
'edges'][n], graph['nodes'])
for n in former_nodes:
if n not in path or n == path[-1]:
... | a7773edb584b3e068d38a90f406e3ce8c0646474 | 678,360 |
def fuselage_form_factor(
fineness_ratio: float,
ratio_of_corner_radius_to_body_width: float = 0.5
):
"""
Computes the form factor of a fuselage as a function of various geometrical parameters.
Assumes the body cross section is a rounded square with constant-radius-of-curvature fillets.
... | e82891f60c0eef03f5787d38186a7c050b78c4b5 | 678,361 |
def _miller_rabin(a, n, u, t):
"""
Miller-Rabin that a number is *definitely* composite (if not then it is
*probably* prime, though you should try several to be sure
a - test prime
n - number for testing
u,t - decomposition of n,s.t. n=u 2^t +1
is a^t mod n != 1 *and* (2^(ajt)... | d9b46ffced50c6765c0af82a9384c4d7c3f73b36 | 678,362 |
def make_envelope_JSON(args):
"""
Create envelope JSON
<br>Document 1: An HTML document.
<br>Document 2: A Word .docx document.
<br>Document 3: A PDF document.
<br>DocuSign will convert all of the documents to the PDF format.
<br>The recipients" field tags are placed using <b>anchor</b> str... | 286de9b86045781c528f97ac0e8360dc3f5f02fe | 678,363 |
def _read_string_array(array):
"""
Helper function taking a string data and preparing it so it can be
read to other object.
As string array are stored as ASCII-int in HDF5, decode is required.
data (numpy.array): data array that encodes a string
Args:
array (numpy.array):
Returns... | 2a3560619e16d8fa6c8848cdac01c915a1018444 | 678,364 |
import simplejson as json
def pack(result):
"""This one unpacks the result."""
result_dict={}
result_dict['data']=result
return "flyingpigscantfly(%s)" % json.dumps(result_dict) | 9f0288f2fddb20ccdb02e7e7844f7a35f94f23f6 | 678,366 |
from typing import Dict
from typing import Any
import re
def get_entrypoint(doc: Dict[str, Any]) -> Dict[str, Any]:
"""Find and return the entrypoint object in the doc."""
# Search supportedClass
for class_ in doc["supportedClass"]:
# Check the @id for each class
try:
class_id ... | 45c085568867c2ce800f92d46e685cf7872f6e89 | 678,367 |
def bin2int(bits):
"""Converts a binary string into its integer value.
Parameters
----------
bits : list or tuple of bool
The binary string as a list of True/False values.
"""
i = 0
for bit in bits:
i = i * 2 + bit
return i | f2512ff28a587405dd44c46338767e376354a50d | 678,368 |
def get_species_mappings(num_specs, last_species):
"""
Maps species indices around species moved to last position.
Parameters
----------
num_specs : int
Number of species.
last_species : int
Index of species being moved to end of system.
Returns
-------
fwd_species_... | 3d0c83b4eae2d22ad13c14ce6d307e3bda7dcbb1 | 678,369 |
def get_data_view_status(data_view_id):
"""
URL for retrieving the statuses of all services
associated with a data view.
:param data_view_id: The ID of the desired data views
:type data_view_id: str
"""
return "data_views/{}/status".format(data_view_id) | 7185dd6266d08aebe7791cc82338ee8336522951 | 678,370 |
def fapiao_query(self, fapiao_apply_id, fapiao_id=None):
"""查询电子发票
:param fapiao_apply_id: 发票申请单号,示例值:'4200000444201910177461284488'
:param fapiao_id: 商户发票单号,示例值:'20200701123456'
"""
path = '/v3/new-tax-control-fapiao/fapiao-applications/%s' % fapiao_apply_id
if fapiao_id:
path += '?fapi... | 53f0677e6722e25cbe8dd9c10f08288ffb4797bb | 678,373 |
def merge_args_and_kwargs(param_names, args, kwargs):
"""Merges args and kwargs for a given list of parameter names into a single
dictionary."""
merged = dict(zip(param_names, args))
merged.update(kwargs)
return merged | 46f4e0249979579d592aea504796fbc556e40f1b | 678,374 |
import base64
def encode_from_file(filename):
"""
This function encode the content of the credential file for datasnapshot authentication
:param filename: the path of the file containing the credentials
:rtype: str
:Example:
>>> encode_from_file("./mycredentials")
"""
with open(filenam... | b262c7677268e80885600a97875a5370551d3e0e | 678,375 |
import re
def filename_clean(filename: str) -> str:
"""Try to clean a filename for safe consumption as much as we can. These
filenames are sent to other users."""
# If there's a dot we remove the suffix
if "." in filename:
filename = filename.rsplit(".", 1)[0]
# Replace anything that cou... | 941448ec5321cf0e39fe9c56525805ecc541c644 | 678,376 |
import os
def _find_base_dir(base_path, config):
"""
Finds the base dir for the configuration, and returns it as a complete path.
A FileNotFoundError is raised if no configuration file could be found.
:param base_path: The base directory
:param config: Name of the configuration file
:return: ... | 7472680d83d0fb6c152b68fca63b9b48c6ed6410 | 678,377 |
def apply_address_mask(address, bitmask):
"""Each bit in the bitmask modifies the corresponding bit of the destination memory address
in the following way:
If the bitmask bit is 0, the corresponding memory address bit is unchanged.
If the bitmask bit is 1, the corresponding memory address bit i... | d4f86f6c9dd849baeb46e28bbe76220dfa67c32b | 678,378 |
from pathlib import Path
def baddir(path: Path) -> bool:
"""
tells if a directory is not a Git repo or excluded.
A directory with top-level file ".nogit" is excluded.
Parameters
----------
path : pathlib.Path
path to check if it's a Git repo
Results
-------
bad : bool
... | 027366d5c1ddf1f55e2011709d826561d86950de | 678,379 |
import re
def findWords(line):
"""Parse string to extract all non-numeric strings"""
return re.findall(r'[a-z]*[A-Z]+', line, re.I) | 3c5e7c3ea455b569cd8ee9cc5ec0f4b07311b34c | 678,380 |
import torch
def hz_to_mel(freqs: torch.Tensor):
"""
Converts a Tensor of frequencies in hertz to the mel scale.
Uses the simple formula by O'Shaughnessy (1987).
Args:
freqs (torch.Tensor): frequencies to convert.
"""
return 2595 * torch.log10(1 + freqs / 700) | 02ac7b5af09a12ae0040ea612c6e1a1d478baf35 | 678,381 |
import csv
def get_run_parameter_value(param_name, contents):
"""
Parses outfile contents and extracts the value for the field named as `param_name` from the last row
"""
# read the header + the last line, and strip whitespace from field names
header = ','.join([c.lstrip() for c in contents[0].sp... | 7dec2ff99b2fa2caf4c4c77599cb9efbce6be1a4 | 678,383 |
def escapeToXML(text, isattrib = False):
"""Borrowed from twisted.xish.domish
Escape text to proper XML form, per section 2.3 in the XML specification.
@type text: L{str}
@param text: Text to escape
@type isattrib: L{bool}
@param isattrib: Triggers escaping of characters necessary for use... | 5642d5cc1df1f1a8966f2ad2043e4e5b034b6a92 | 678,384 |
def normalize(a):
"""Normalize array values to 0.0...255.0 range"""
a = a.astype(float)
lo, hi = a.min(), a.max()
a -= lo
a *= 255.0 / (hi - lo)
return a.round() | 6b35428ab9eb254bbd18319b63f1dd604722e9b0 | 678,385 |
def check_zero_poly(coefficients):
"""
This function checks whether all elements of coefficients equal
zero or not. If all elements of coefficients equal zero, this
function returns True. Else this function returns False.
"""
for i in coefficients:
if i != 0:
return False
... | 9d413a196f6b1dc4e1c9781bdcb314db165fcc9e | 678,386 |
def _nested_lambda_operator_base(string, lambda_operator1, lambda_operator2):
"""
Funcao base que constroi uma consulta usando dois operadores lambda do Odata.
Args:
string (str): String "cru" que serve de base para construir o operador.
Ex.: customFieldValues/items/customFieldItem eq '... | 10832da19bd8f2a622129368395b10a5df901baa | 678,387 |
def compare_plain_holes(hole_position1, hole_position2):
"""
Returns -1 if first hole_position is close to (0,0), 1 otherwise
"""
if hole_position1.x < hole_position2.x:
return -1
if hole_position1.x == hole_position2.x and hole_position1.y < hole_position2.y:
return -1
return 1 | 0b5b8f1e1e7e32143c7ded8345cc5617a650449e | 678,388 |
import json
def dethemify(topicmsg):
""" Inverse of themify() """
json0 = topicmsg.find('{')
topic = topicmsg[0:json0].strip()
msg = json.loads(topicmsg[json0:])
return topic, msg | 527cd8c3bb5a9ae75600b19050ca388b9321c630 | 678,389 |
from warnings import warn
def reusesf(sfs,dm1,dm2):
"""Help function to copy SFs for other DM in dictionary, if it does not exist already."""
if dm1 in sfs and dm2 not in sfs: # reuse dm1 for dm2
print(warn(f"Reusing DM{dm1} SF {sfs[dm1]} for DM{dm2} SF..."))
if isinstance(sfs[dm1],(list,tuple)):
sf... | 4fa869886fc380ca6f542e47013c2b8ccfd0afdc | 678,390 |
def normalize_search_terms(search_terms: str)->str:
"""
Normalize the search terms so that searching for "A b c" is the same as searching for
"a b C", "B C A", etc.
Args:
search_terms (str): Space-delimited list of search terms.
Returns:
(str): Space-delimited search terms, lowerca... | be9afce684c3139d0ee132b37bf5dcec7269a3b2 | 678,391 |
import torch
def masking_noise(data, frac):
"""
data: Tensor
frac: fraction of unit to be masked out
"""
data_noise = data.clone()
rand = torch.rand(data.size())
data_noise[rand<frac] = 0
return data_noise | 216b6d728abf95627fb758199368e1f82d645e11 | 678,392 |
from typing import Set
def candidates_to_bits(candidates: Set[int]) -> int:
"""
Convert a candidates set into its bits representation
The bits are in big endian order
>>> bin(candidates_to_bits({1, 2, 3, 6, 7}))
'0b1100111'
>>> bin(candidates_to_bits({6, 9}))
'0b100100000'
"""
bi... | 0f69cb3515975687d1c83fabf690936667a6cf06 | 678,393 |
import hashlib
import json
def generate_key_from_string():
"""
Generate a key from an image and store it in the .keys/AES.key file
:return: key
:rtype: bytearray
"""
s = input("type something random:")
k = hashlib.sha256(s.encode()).hexdigest()
d = {"key": str(k)}
with open('.keys... | 06e5ed68a1eb13fbe823ee45fe6d3579b0d5d186 | 678,394 |
def get_compute_op_list(job_content):
"""
Get compute op info list from job content info
:param job_content: tbe compilation content info
:return: compute op info list
"""
op_list = job_content["op_list"]
op_compute_list = []
for op in op_list:
if op["type"] != "Data":
... | dc4cf0a9fbc8ff104aeaba812db533bf574bbc84 | 678,395 |
def get_correct_answer(*answers):
"""Checking the correctness of the answer.
Checking if the user's response is
included in the set of available responses.
"""
while 1:
answer = input()
if answer in answers:
return answer
print('Попробуй еще раз, в ответе нужно у... | 28934ce0a6d0df157ccedd8532356db232615958 | 678,396 |
def remove_namespace(tag, name, ns_dict):
"""Used to remove namespaces from tags to create keys in dictionary for quick key lookup.
Attr:
tag(str): Full tag value. Should include namespace by default.
name(str): The namespace key. Usually the ticker of the company.
ns_di... | 0c85db8481007df4b1e0744a315ab7ec4d110a0d | 678,397 |
def find_youngest_cluster(data_err, min_cluster_size):
"""
Finds the youngest cluster of analyses that overlap
Parameters
----------
data_err : array of tuples [(age1, error1), (age2, error2), etc.]
"""
i_min = 0
i_max = 0
for i in range(1, len(data_err)):
top = data_err[i... | f2e497e12ccc3f19167af5109ae5ddbdc07a5082 | 678,399 |
import base64
def from_base16(data):
"""
解base16编码
:param data: base16字符串
:return: 字符串
"""
return base64.b16decode(data) | 5d8369113cc0bbe3a4a25822b00ec97c54e481e2 | 678,400 |
def get_default_dti_task_names():
"""Get that default dti task names"""
return ['chemical', 'protein'] | d3192a80f93cada1a39569646e09afd025a1172f | 678,401 |
def energy_distance_one_based(graph):
"""
We calculate energy distance from a given graphs to the solutions. The smaller the closer to solutions
:param graph:
:return:
"""
# We calculate the distance by calculating the variance of vertex weight
# to its mean weight, since we want
# all v... | 258b59c23e6fa0debe5a9228d0b264022049e674 | 678,402 |
def are_expected_fieldnames(fieldnames, expected_fieldnames):
"""
Check whether field names correspond to expected field names by stripping their contents and replacing non-python
friendly characters with underscores
"""
norm_fieldnames = map(lambda f: f.strip().replace(' ', '_') if f else '', field... | 2387216b7aac328af6a9b250b5b7a711f68bcb24 | 678,403 |
from typing import List
def flip_v(matrix: List[List]) -> List[List]:
"""Flip a matrix (list of list) vertically
"""
return matrix[::-1] | e52561c8d8aeec737d585c28d5a6f34324da8d78 | 678,404 |
import os
import json
def load_multiple_pdf_main_articles():
"""
When a publication/revision has more than one pdf, use this result to get the main article.
This dict has been manually populated.
Note: When the main article is an empty string, it means all the pdfs are supplemental.
For exam... | 1c5fe23edd5dd193550ce6f7eb2629f6a2b27b73 | 678,405 |
from typing import Union
def int_conversion(string: str) -> Union[int, str]:
"""
Check and convert string that can be represented as an integer
:param string: Input string
:return: Result of conversion
"""
try:
value = int(string)
except ValueError:
value = string
ret... | a223fcb6194907876156ee4e028cb37b048051c2 | 678,406 |
def get_wire_distance_map(directions):
"""Return a dict of tuple to distance"""
return_dict = {}
x = 0
y = 0
distance = 0
for direction in directions:
dir_str = str.upper(direction[0])
size = int(direction[1:])
for _ in range(size):
if ("U" == dir_str):
... | 9cc2e393b7b493830547eb48f63abe727a988555 | 678,407 |
def get_question_marker(doc):
"""Returns list of question values of sentences."""
return [s._.is_question for s in doc.sents] | 5799eba59119e7d2d8e751f06754271f267d11ba | 678,408 |
def str_to_bool(string, truelist=None):
"""Returns a boolean according to a string. True if the string
belongs to 'truelist', false otherwise.
By default, truelist has "True" only.
"""
if truelist is None:
truelist = ["True"]
return string in truelist | bd43763fc211e555b977953ef574d64a2d82eee1 | 678,409 |
def level_to_criticality(level: int) -> str:
"""Translate level integer to Criticality string."""
if level >= 4:
return "Very Malicious"
elif level >= 3:
return "Malicious"
elif level >= 2:
return "Suspicious"
elif level >= 1:
return "Informational"
return "Unknow... | c1933f4a1f38e87b5a54643d49b402c0185fe010 | 678,410 |
import re
import os
def replace_env_vars(config_json: str) -> str:
"""
Replaces env variables matching form ${VAR_NAME} with its string value
:param config_json: input configuratio json as string
:return: str, with replaced values
:raise: AssertionError if variables matching ${VAR_NAME} form are n... | 0ab88d851302012d3154f0fc51d977f79ccaaed9 | 678,411 |
def get_title_to_id_dict(titles):
"""Creates a dict mapping each title with an id.
:param titles: list of titles
:type titles: list
:return: dict mapping a title to an id.
:rtype: dict
"""
title_to_id = {title: i for i, title in enumerate(titles)}
return title_to_id | fac39a472da59a24a7db80a73ce33e4b1022d409 | 678,412 |
def timestep(dtime, time, end_time):
"""
calculates the timestep for a given time
Returns the timestep if the calculation isnt overstepping the endtime
if it would overstep it returns the resttime to calculte to the endtime.
:param dtime: timestep
:param time: current time in simulation
:p... | 516ba4df05fa8f472c3f45471b63c01806aa76b2 | 678,413 |
def compose_tbl_filename(
key_names, key_indices=None,
prefix='tbl', suffix='txt',
var_separator='.', idx_separator='-'):
"""compose a file name based on key names
Parameters
----------
key_names : list of str
A list of key names
key_indices : list of str
A l... | e4774d4ebc14f8014e12b2973de178ea364b6f9b | 678,415 |
import random
def _random_value(x = None, min=0, max=10):
"""
(not very eye pleasing ;)
returns a random int between min and max
"""
return random.randint(min,max) | 315300dd21d56885d47448e5b6660a72cffb0bc4 | 678,416 |
import re
def _is_bed_row(bed_row):
"""Checks the format of a row of a bedfile.
The logic is to check the first three fields that should be
chromosome start end."""
if len(bed_row) < 3:
return False
return (
(re.match(r"^chr.+$", bed_row[0]) is not None)
and (re.match(r"^[0... | 187a52230d1b71542c4adc3cd5355a3063cb4844 | 678,417 |
import os
import filecmp
def locate(tgt_fpath, survey):
"""Given a fpath on the "camera", determine if present in the survey of the library.
I could just return True/False, but returning the library fpath/None might be more interesting.
filecmp.cmp has a fast sanity check mode, and a full test.
... | 6649bb39842e21825b90656e3212c5339be165c8 | 678,418 |
def Return(node):
"""Return statement
Examples:
>>> print(matlab2cpp.qscript("function f(); return"))
void f()
{
return ;
}
>>> print(matlab2cpp.qscript("function y=f(); return; y=1"))
int f()
{
int y ;
return y ;
y = 1 ;
return y ;
}
>>> print(matl... | 8e4dedc4d3c7064aa323551788b2e486adacff70 | 678,419 |
import hashlib
def generate_key(password, salt):
"""
PyCrypto block-level encryption API is low level & expects key to be 16, 24 or 32 bytes (AES-128, AES-196 and AES-256).
Generating 32 byte key from password provided to eaze up the process.
256 bit key: 1.1x10e77 combinations and 3.31x10e56 years to... | 7aa82f482643c53cb41e206bd03333b787b5e3db | 678,420 |
import collections
def group_train_data(training_data):
"""
Group training pairs by first phrase
:param training_data: list of (seq1, seq2) pairs
:return: list of (seq1, [seq*]) pairs
"""
groups = collections.defaultdict(list)
for p1, p2 in training_data:
l = groups[tuple(p1)]
... | f916d4f4eaee8ec8a30a9fc9290fbcac68d4c9c5 | 678,421 |
def gcd(a, b):
"""Calculate Greatest Common Divisor (GCD)."""
return b if a == 0 else gcd(b % a, a) | 366a547c680aa5a36ac42b945acd906607b5efc0 | 678,422 |
def _samples_calls(variant_collection, dataset_id, samples):
"""Count all allele calls for a dataset in variants collection
Accepts:
variant_collection(pymongo.database.Database.Collection)
dataset_id(str): id of dataset to be updated
samples(list): list of dataset samples
Returns:
... | edda3c29aa1b844bf2ddcd2df0fb459f22f739d7 | 678,423 |
import zlib
def decode_gzip(content):
"""Return gzip-decoded string.
Arguments:
- `content`: bytestring to gzip-decode.
"""
return zlib.decompress(content, 16 + zlib.MAX_WBITS) | ddded4185b85774d75af7dba93def4efba669f41 | 678,424 |
from functools import reduce
import operator
def prod(iterable):
"""Take product of iterable like."""
return reduce(operator.mul, iterable, 1) | b0534333e870723e88eec01dd7e765185381b6a7 | 678,425 |
import random
def computer_move(board, move):
"""This function creates the AI of the game.
It takes the board of the game and a move for the computer.
It creates a move using random and returning booleans. """
while True:
x = random.randint(0, 7)
y = random.randint(0, 7)
if mov... | 1b8a0582bce92aa2a084753cc20e866d6830b85d | 678,426 |
def external(cls):
"""
Decorator.
This class or package is meant to be used *only* by code outside this project.
"""
return cls | d56422d291a3468368fdbdd35cf57d65aa695621 | 678,429 |
import math
def sqrt_sin(x):
"""Returns square root from sinus
Examples
--------
Zero input produces zero output:
>>> print(sqrt_sin(0))
0.0
Some mystical values produces errors:
>>> print(sqrt_sin(-1)) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
V... | 441bf62c5c8974eff27baa57953a3142a8eafb85 | 678,430 |
def change_polarity(mutation):
"""
Return + if the protein mutation introduce
a change in the polarity of the residue.
"""
groups = {
"Ala": "Non polar",
"Asn": "Polar",
"Asp": "Acidic",
"Arg": "Basic",
"His": "Basic",
"Cys": "... | e836fd43d01c11527e24556f893eaf9156745f15 | 678,431 |
def extract_models(tsk):
""" pull modesl from tasks
"""
key_dct = tsk[-1]
pes_mod = key_dct['kin_model']
spc_mods = tuple(key_dct[key] for key in key_dct.keys()
if 'spc_mod' in key)
return spc_mods, pes_mod | 81b6bc661f99c2acb25cf1d3465fb1e387a62fa4 | 678,432 |
def arrays_to_strings(measure_json):
"""To facilitate readability via newlines, we express some JSON
strings as arrays, but store them as strings.
Returns the json with such fields converted to strings.
"""
fields_to_convert = [
'title', 'description', 'why_it_matters', 'numerator_columns'... | 35c66fc170cd9c3a3acedb2873c1bb7f4ead2841 | 678,433 |
def get_tag(body):
"""Get the annotation tag from the body."""
if not isinstance(body, list):
body = [body]
try:
return [b['value'] for b in body if b['purpose'] == 'tagging'][0]
except IndexError:
return None | ce71747e108fe806b68be10732b56aaffadffeac | 678,435 |
def get_querylist(querydict, key):
"""
Работает с объектом QueryDict, выполняет метод getlist
"""
return querydict.getlist(key) | bf7b040f0927ccf7bb15db105d9951c690fa7489 | 678,437 |
import os
def which(filename, path=None):
"""
Return first occurence of file on the path.
"""
if not path:
path = os.environ['PATH'].split(os.pathsep)
for dirname in path:
candidate = os.path.join(dirname, filename)
if os.path.isfile(candidate):
return candidate... | 475cd73f8b8c4d36ff22602feeda8f85182e0138 | 678,438 |
def descending_order(num):
"""
num: any integer
return: num sorted in a descending order (highest to lowest)
"""
list = ([int(i) for i in str(num)])
list.sort()
new_list = []
while len(list) > 0:
new_list.append(list.pop())
string_ints = [str(int) for int in new_list]
string_ints = int("".join(s... | 794d52e585d8b2e62c1a5c612e1105f107c49aed | 678,439 |
def filter_clusters(graph, consensual_clusters):
"""
Remove propositions that are not consensual
:param graph: the original graph
:param consensual_clusters:
:return: the graph, containing only the consensual clusters
"""
consensual_graph = graph.clone()
removed = []
for prop_id, p... | 3ca39540490576abe5bcd832825c8d07941b938d | 678,440 |
import ast
def query_to_dict(query: dict, parse: bool = False, ignore=None) -> dict:
"""Parse url query and makes dict from it"""
if ignore is None:
ignore = []
save_query = {field: value for field, value in query.items() if field not in ignore}
if parse:
return {field: ast.literal_e... | 5fe684ddcaead6a3e9731ccee1f2365f07088df2 | 678,441 |
def fix_indentation_depth(query):
"""Make indentation use 4 spaces, rather than the 2 spaces GraphQL normally uses."""
lines = query.split('\n')
final_lines = []
for line in lines:
consecutive_spaces = 0
for char in line:
if char == ' ':
consecutive_spaces +=... | 38e94840701abb04192f94a6280ea9f62560384d | 678,442 |
def dot1q_post_build(self, packet, payload):
""" Implement post build to calculate length for 802.3 frame.
"""
if self.type == None or self.type <= 1500 :
l = len(payload)
packet = packet[:2] + chr((l >> 8) & 0xff) + chr(l & 0xff)
self.type = l
return packet + payload | 07c9a1d8036ee170d6d6b1ffcba327c3885c264c | 678,443 |
def check_is_faang(item):
"""
Function checks that record belongs to FAANG project
:param item: item to check
:return: True if item has FAANG project label and False otherwise
"""
if 'characteristics' in item and 'project' in item['characteristics']:
for project in item['characteristics'... | 24b6a3a827974aa57e69b2afee26ebb91644e748 | 678,444 |
def preprocess_prediction_data(data, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
data (obj:`List[str]`): The prediction data whose each element is a tokenized text.
tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese strin... | b9fa5fcd65e0e17d0fbeccc68773f1a0678a7cfe | 678,445 |
def ListFeatures(font):
"""List features for specified font. Table assumed structured like GPS/GSUB.
Args:
font: a TTFont.
Returns:
List of 3-tuples of ('GPOS', tag, name) of the features in the font.
"""
results = []
for tbl in ["GPOS", "GSUB"]:
if tbl in font.keys():
results += [
... | 0fb2a1ac5b367d7d711cab7b303d2ba1fd487514 | 678,446 |
import networkx as nx
from numpy import log10
def flatten_graph(G, weight="score", log=True):
"""
Collapse graph and calculate edge weight between clusters as:
weight = sum(weighted_score)
log: log the sum of scores
Returns: a nx.DiGraph
.. note::
Use flatten graph to export to a si... | 07b9827c2d453f20881eacf6ccd66fe82958751a | 678,447 |
import random
def random_flip(img, y_random=False, x_random=False,
return_param=False, copy=False):
"""Randomly flip an image in vertical or horizontal direction.
Args:
img (~numpy.ndarray): CHW format.
y_random (bool):
x_random (bool):
return_param (bool): R... | 1b1d10471b2f7315d3ce17ff1020a3ebeb90f742 | 678,448 |
def svm_grid():
""" Return grid for RandomSearchCV for the SVM classifier
:return: dictionary
"""
C = [0.1, 1, 10, 100]
kernel = ['linear', 'poly', 'rbf', 'sigmoid']
degree = [2, 3, 4, 5, 6, 7, 8]
coef0 = [0.1, 1, 10, 100]
gamma = ['scale', 'auto']
shrinking = [True, False]
prob... | 08a5bc50e3a34a067874d91abe3f36b4acd2ea0b | 678,449 |
def get_user_templates(context, user_id):
""" Retrieves the top n_templates product templates of all given products.
:param context: A session context.
:param user_id: A list with the ids of the intended users.
:returns: A map {user_id: list of [strength, template_id] pairs}.
"""
r... | 84b73819332f772f4e837e0ae291bdf984f9ac6c | 678,450 |
import numpy
def _computeEdges(x, histogramType):
"""Compute the edges from a set of xs and a rule to generate the edges
:param x: the x value of the curve to transform into an histogram
:param histogramType: the type of histogram we wan't to generate.
This define the way to center the histogram... | 9c18fc21a20dc68f8bbacb9ddaa14cc061b544b9 | 678,451 |
from numpy import argsort
def sorted_lists(lists):
"""Sort lists by order of first list"""
order = argsort(lists[0])
def reorder(list,order): return [list[i] for i in order]
sorted_lists = [reorder(list,order) for list in lists]
return sorted_lists | aace0ae4913310328647a7d60e62950d4d0bb405 | 678,452 |
from typing import Tuple
def manual_map() -> Tuple[str, Tuple[Tuple[str, str]]]:
"""Defines documentation for addon.
Returns:
tuple: A hyperlink to the relevant documentation.
"""
url_manual_prefix = "https://docs.blender.org/manual/en/latest/"
url_manual_mapping = (
("bpy.ops.ex... | 935f15e8b3b9ba79a5f887f2127f9eacc4509a33 | 678,453 |
def constant_sd(data, k = 1):
"""method to get anomalies as dates (DatetimeIndex) (dtype=datetime64[ns])
- constant mean mu
- constand std sigma
- data points xn
- anomalies definition: xn - mu > k*std
- maximum ten anomalies (10 'biggest' anomalies)
:argument data: dataframe with one colu... | b5dcba66814174d195e73be8a0e76d7b87283028 | 678,454 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.