content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def _is_winning_combination(board, combination, player):
"""
Checks if all 3 positions in given combination are occupied by given player.
:param board: Game board.
:param combination: Tuple containing three position elements.
Example: ((0,0), (0,1), (0,2))
Returns True of all three positions in the combination belongs to given
player, False otherwise.
"""
for position in combination:
# check if mark is not associated with player, if true return false
if board[int(position[0])][int(position[1])] != player:
return False
return True
|
19e2ff1e0c254dbde0f856e994e9b9fe63a20db0
| 230,348 |
def get_param_i(param, i):
"""Gets correct parameter for iteration i.
Parameters
----------
param : list
List of model hyperparameters to be iterated over.
i : integer
Hyperparameter iteration.
Returns
-------
Correct hyperparameter for iteration i.
"""
if len(param) > i:
return param[i]
else:
return param[0]
|
52b81a9f1f5a712586bf55dcdd10975fcd1bc8c2
| 482,629 |
def bilinear_interpolation_01(x, y, values):
"""Interpolate values given at the corners of
[0,1]x[0,1] square.
Parameters:
x : float
y : float
points : ((v00, v01), (v10, v11))
input grid with 4 values from which to interpolate.
Inner dimension = x, thus v01 = value at (x=1,y=0).
Returns:
float
interpolated value
"""
return (values[0][0] * (1 - x) * (1 - y) +
values[0][1] * x * (1 - y) +
values[1][0] * (1 - x) * y +
values[1][1] * x * y)
|
a5e0d8b974803073df159da4d16a01a47ec0f087
| 690,778 |
def get_alternated_ys(ys_count, low, high):
"""
A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the
x axis are too crowded.
:param ys_count: integer from 1 to 3.
:param low: lower bound of the area designated for annotations
:param high: higher bound for thr area designated for annotations.
:return:
"""
if ys_count not in [1, 2, 3]:
raise ValueError('Argument ys_count should be 1, 2 or 3.')
if ys_count == 1:
coefs = [0.5]
vas = ['center']
elif ys_count == 2:
coefs = [0.15, 0.85]
vas = ['bottom', 'top']
else:
coefs = [0.15, 0.5, 0.85]
vas = ['bottom', 'center', 'top']
ys = [low + coef * (high - low) for coef in coefs]
return ys, vas
|
e606ef555ff29285d4b7b77076939e66b8997856
| 631,116 |
def get_api_base(api_func):
"""Return the API base for Ghidra's flat API
:param api_func: Any function in Ghidra's flat API - eg. getInstructionAt
:type: function
:return: The api base
:rtype: ghidra.python.PythonScript
"""
return api_func.__self__
|
0a05e4667be620a62ea108f1c31484aa4bcb023c
| 359,044 |
def _validate_year(year):
""" Validate year is given as an int"""
if not isinstance(year, int):
raise TypeError("Year must give of type `int`.")
if year <= 1900:
raise ValueError("Please enter a year after 1990.")
return year
|
2818f988e32192436bcfd0c6c5d1c0aff9a7488f
| 369,612 |
def phrase(term: str) -> str:
"""
Format words to query results containing the desired phrase.
:param term: A phrase that appears in that exact form. (e.q. phrase "Chicago Bulls" vs. words "Chicago" "Bulls")
:return: String in the format google understands
"""
return '"{}"'.format(term)
|
8a327ca9dc9b223e4ba9adbba8d7f4ed85d7db68
| 689,958 |
from typing import Dict
from typing import Any
import logging
def web3_mint(userAddress: str, tokenURI: str, eth_json: Dict[str, Any]) -> str:
"""
Purpose:
mint a token for user on blockchain
Args:
userAddress - the user to mint for
tokenURI - uri for token
eth_json - blockchain info
Returns:
hash - txn of mint
tokenid - token minted
"""
PUBLIC_KEY = eth_json["public_key"]
CHAIN_ID = eth_json["chain_id"]
w3 = eth_json["w3"]
CODE_NFT = eth_json["contract"]
PRIVATE_KEY = eth_json["private_key"]
nonce = w3.eth.get_transaction_count(PUBLIC_KEY)
# logging.info(f"Nonce: {w3.eth.get_transaction_count(PUBLIC_KEY)}")
# Create the contracrt
mint_txn = CODE_NFT.functions.mint(userAddress, tokenURI).buildTransaction(
{
"chainId": CHAIN_ID,
"gas": 10000000,
"gasPrice": w3.toWei("1", "gwei"),
"nonce": nonce,
}
)
signed_txn = w3.eth.account.sign_transaction(mint_txn, private_key=PRIVATE_KEY)
w3.eth.send_raw_transaction(signed_txn.rawTransaction)
hash = w3.toHex(w3.keccak(signed_txn.rawTransaction))
logging.info(f"mint txn hash: {hash} ")
receipt = w3.eth.wait_for_transaction_receipt(hash) # hmmm have to wait...
hex_tokenid = receipt["logs"][0]["topics"][3].hex() # this is token id in hex
# convert from hex to decmial
tokenid = int(hex_tokenid, 16)
logging.info(f"Got tokenid: {tokenid}")
return hash
|
8848eba9be99e20c9b86215d6752d09dbcc3ee35
| 328,881 |
from typing import Tuple
import math
def factor(x: int) -> Tuple[int, int]:
"""
Factors :attr:`x` into 2 numbers, a and b, such that a + b is as small as possible.
Parameters
-----------
x: :class:`int`
The number to factor
Returns
--------
Tuple[:class:`int`, :class:`int`]
A Tuple of 2 integers that factor into :attr:`x`.
"""
rt = int(math.sqrt(x))
for i in range(0, rt):
if x % (rt + i) == 0:
return rt + i, x // (rt + i)
if x % (rt - i) == 0:
return rt - i, x // (rt - i)
return x, 1
|
bfee87f2812f54f9281bdc316366d037703cedac
| 443,114 |
def third_bashforth(state, tendencies_list, timestep):
"""Return the new state using third-order Adams-Bashforth. tendencies_list
should be a list of dictionaries whose values are tendencies in
units/second (from oldest to newest), and timestep should be a timedelta
object."""
return_state = {}
for key in tendencies_list[0].keys():
return_state[key] = state[key] + timestep.total_seconds() * (
23./12*tendencies_list[-1][key] - 4./3*tendencies_list[-2][key] +
5./12*tendencies_list[-3][key]
)
return return_state
|
6b1a62b94c662a1b14eafa3be6953e73486b6cfd
| 697,519 |
def _unescape_key(string):
"""
Unescape '__type' and '__meta' keys if they occur.
"""
if string.startswith("__") and string.lstrip("_") in ("type", "meta"):
return string[1:]
return string
|
593f5f178f9fe94465a85bfee4bd896c97c16dff
| 466,020 |
def atom2dict(atom, dictionary=None):
"""Get a dictionary of one of a structure's
:class:`diffpy.structure.Structure.atoms` content.
Only values necessary to initialize an atom object are returned.
Parameters
----------
atom : diffpy.structure.Structure.atom
Atom in a structure.
dictionary : dict, optional
Dictionary to update with structure atom information. If None
(default), a new dictionary is created.
Returns
-------
dictionary : dict
Dictionary with structure atoms information.
"""
if dictionary is None:
dictionary = {}
dictionary.update(
{
attribute: atom.__getattribute__(attribute)
for attribute in ["element", "label", "occupancy", "xyz", "U"]
}
)
return dictionary
|
6873c64bd39d211a43f302375d6a6c76e3bd0b7e
| 28,103 |
def row_includes_spans(table, row, spans):
"""
Determine if there are spans within a row
Parameters
----------
table : list of lists of str
row : int
spans : list of lists of lists of int
Returns
-------
bool
Whether or not a table's row includes spans
"""
for column in range(len(table[row])):
for span in spans:
if [row, column] in span:
return True
return False
|
217aa977b4029a62f379eb61ccef8a3d90ae90e2
| 524,346 |
from typing import Union
def read_file(path: str, mode: str) -> Union[str, bytes]:
""" Reads the content of the given file.
Args:
path (str): the path of the file
mode (str): the open mode, could be "r" or "rb"
Returns:
the content of the file, as string or bytes depending on the mode
"""
with open(path, mode) as f:
return f.read()
|
580244b671b4dbba2ee31973d98b3fa99a52a5c4
| 199,008 |
from typing import Union
def count_even(obj: Union[list, int]) -> int:
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
>>> count_even(3)
0
>>> count_even(16)
1
>>> count_even([1, 2, [3, 4], 5])
2
"""
# counter = 0
# # case case:
# if isinstance(obj, int):
# if obj % 2 == 0:
# counter += 1
# else:
# # obj is a list.
# for item in obj:
# # item is either an int or another list.
# counter += count_even(item)
# return counter
# with listcomp and ternary...
if isinstance(obj, int):
return 1 if obj % 2 == 0 else 0
return sum(count_even(item) for item in obj)
|
8d757d7004c11ac77eb85bbc37fd7b3c9e6c4798
| 638,597 |
def ping_time_to_distance(time, calibration=None, distance_units='cm'):
"""
Calculates the distance (in cm) given the time of a ping echo.
By default it uses the speed of sound (at sea level = 340.29 m/s)
to calculate the distance, but a list of calibrated points can
be used to calculate the distance using linear interpolation.
:arg calibration: A sorted list of (time, distance) tuples to calculate
the distance using linear interpolation between the
two closest points.
Example (for a HC-SR04 ultrasonic ranging sensor):
[(680.0, 10.0), (1460.0, 20.0), (2210.0, 30.0)]
"""
if not time:
return 0
if not calibration: # Standard calculation using speed of sound.
# 1 (second) / 340.29 (speed of sound in m/s) = 0.00293866995 metres
# distance = duration (microseconds) / 29.38 / 2 (go and back)
distance = time / 29.3866995 / 2
else: # Linear interpolation between two calibration points.
a = (0, 0)
b = calibration[-1]
for c in calibration:
if c[0] < time: a = c
if c[0] > time: b = c; break
if a == b:
a = calibration[-2]
distance = a[1] + (b[1] - a[1]) * ((time - a[0]) / (b[0] - a[0]))
return distance
|
db8cba30c8d50d301b6a0e15073c527e285d4aa6
| 51,225 |
def get_var(df, recorded_var, mean=True):
"""
Get variable from dataframe one level deep and optionally the mean.
:param df: Recorded data over time
:type df: pd.DataFrame
:param recorded_var: Variable to retrieve from df
:type recorded_var: str
:param mean: Include the mean in the return tuple
:type mean: bool
:return: Dataframe of variable and Series of the mean for the variable for each time step
:rtype: (pd.DataFrame, pd.Series or None)
"""
all_var_columns = df.xs(recorded_var, level=1, axis=1)
if mean:
# mean over the columns
mean_val = all_var_columns.mean(axis=1)
else:
mean_val = None
return all_var_columns, mean_val
|
79999aec48023c5dc5ac166613f2e9313f74ba07
| 252,191 |
from typing import Tuple
import re
def remove_markdown_formatting(preamble: str, remainder: str) -> Tuple[str, str]:
"""
Remove Markdown formatting from a preamble and remainder pair.
Parameters
----------
preamble : `str`
The textual preamble.
remainder : `str`
The textual remainder.
Returns
-------
`Tuple[str, str]`
A pair of the parsed preamble and remainder.
"""
# Remove bolds.
preamble = re.sub(r"\*\*(?P<unformatted>.*)\*\*", r"\g<unformatted>", preamble)
remainder = re.sub(
r"\*\*(?P<unformatted>.*)\*\*",
r"\g<unformatted>",
remainder,
)
# Remove italics.
preamble = re.sub(
r"(?<!\S)_(?P<unformatted>.*)_(?!\S)", r"\g<unformatted>", preamble
)
remainder = re.sub(
r"(?<!\S)_(?P<unformatted>.*)_(?!\S)", r"\g<unformatted>", remainder
)
preamble = re.sub(
r"(?<!\S)\*(?P<unformatted>.*)\*(?!\S)", r"\g<unformatted>", preamble
)
remainder = re.sub(
r"(?<!\S)\*(?P<unformatted>.*)\*(?!\S)", r"\g<unformatted>", remainder
)
# Remove underlines.
preamble = re.sub(r"__(?P<unformatted>.*)__", r"\g<unformatted>", preamble)
remainder = re.sub(r"__(?P<unformatted>.*)__", r"\g<unformatted>", remainder)
# Remove hyperlink escapes.
preamble = re.sub(r"<(?P<unformatted>http.*)>", r"\g<unformatted>", preamble)
remainder = re.sub(r"<(?P<unformatted>http.*)>", r"\g<unformatted>", remainder)
# Add escapes to parentheses surrounding hyperlinks.
preamble = re.sub(r"\((?P<unformatted>http.*)\)", r"\(\g<unformatted>\)", preamble)
remainder = re.sub(r"\((?P<unformatted>http.*)\)", r"\(\g<unformatted>\)", remainder)
return preamble, remainder
|
c6c8fff9890c33fc2b93ac4b2f2a05202e576a66
| 246,351 |
import re
def replace_empty_bracket(tokens):
"""
Remove empty bracket
:param tokens: List of tokens
:return: Fixed sequence
"""
merged = "".join(tokens)
find = re.search(r"\{\}", merged)
while find:
merged = re.sub(r"\{\}", "", merged)
find = re.search(r"\{\}", merged)
return list(merged)
|
fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb
| 707,808 |
import hashlib
def crackPwd(chunk, hashType, password):
"""This is the function that is sent to the nodes"""
#Insert haslib matching function (similar to youtube video)
testHash = None
for item in chunk:
item = item.strip()
if hashType == "MD5":
testHash = hashlib.md5(item.encode('utf-8')).hexdigest()
elif hashType == "SHA512":
testHash = hashlib.sha512(item.encode('utf-8')).hexdigest()
if testHash == password:
return item
return False
|
a0fae23920b4ead7c38e673c195d96e2f28ac085
| 205,229 |
import torch
def approx_equal(self, other, epsilon=1e-4):
"""
Determines if two tensors are approximately equal
Args:
- self: tensor
- other: tensor
Returns:
- bool
"""
if self.size() != other.size():
raise RuntimeError(
"Size mismatch between self ({self}) and other ({other})".format(self=self.size(), other=other.size())
)
return torch.max((self - other).abs()) <= epsilon
|
e5187e5724f4dd61c8b680241f74037ff13133fd
| 292,467 |
def http_request(transport, method, url, data=None, headers=None):
"""Make an HTTP request.
Args:
transport (object): An object which can make authenticated requests
via a ``request()`` method. This method mustaccept an HTTP method,
an upload URL, a ``data`` keyword argument and a
``headers`` keyword argument.
method (str): The HTTP method for the request.
url (str): The URL for the request.
data (Optional[bytes]): The body of the request.
headers (Mapping[str, str]): The headers for the request (``transport``
may also add additional headers).
Returns:
object: The return value of ``transport.request()``.
"""
return transport.request(method, url, data=data, headers=headers)
|
41c74c4ffb168dde7e489168e8a6a38e2c1babd5
| 181,345 |
def filter_df(freq_df, prediction=None, top=None):
"""Filter frequency df's columns
Parameters
----------
freq_df : pandas.DataFrame
Only a dataframe returned by `frequency_df()` should be used.
prediction : str, list
Allow only the class predictions that match this string or
list of strings.
top : int
Allow only the `top` most frequent classes.
Returns
-------
pandas.DataFrame
Same rows as input, but a filtered subset of columns.
"""
if prediction:
freq_df = freq_df.loc[:, prediction]
if top:
freq_df = freq_df[freq_df.sum().nlargest(top).index]
return freq_df
|
68fe77f6c5fc93a662388c98b10e69b29114d9d4
| 277,029 |
def decode_to_utf8(text) -> bytes: # pragma: no cover
"""
Paramiko returns bytes object and we need to ensure it is utf-8 before parsing.
:param text: non-decoded bytes
:return: decoded text
"""
try:
return text.decode("utf-8")
except (AttributeError, UnicodeEncodeError):
return text
|
f8d7ddf3960b167a7ddf56f90cfef0160d59b03d
| 170,281 |
def null_removal_drop(dataframe, colname):
"""Drops rows with nulls on dataframe[colname]"""
dataframe = dataframe.dropna(subset=[colname])
return dataframe
|
1cd11752f69d9ed6768e94fbe8ae6bef2637216c
| 452,381 |
def is_own_stt(user, requested_stt):
"""Verify user belongs to requested STT."""
user_stt = user.stt_id if hasattr(user, 'stt_id') else None
return bool(
user_stt is not None and
(requested_stt in [None, str(user_stt)])
)
|
b78b4a7fada170c09c740a7dec6027294b2b3c86
| 356,646 |
import re
def is_issue(text):
"""
Does this token look like an issue reference?
https://help.github.com/articles/autolinked-references-and-urls/#issues-and-pull-requests
>>> is_issue('26')
False
>>> is_issue('#26')
True
>>> is_issue('jlord#26')
True
>>> is_issue('jlord')
False
>>> is_issue('jlord/sheetsee.js')
False
>>> is_issue('jlord/sheetsee.js#26')
True
"""
return bool(re.match(r'''
(?: (?:[\w.-]+/)? # Owner
[\w.-]+)? # Repository
[#]\d+$ # Issue number
''', text, re.VERBOSE | re.UNICODE))
|
d0dac0a0b8743bd2f06abb865b593cf3bce1c174
| 387,760 |
def retreive_details(input_dict,keys_to_extract):
"""
Retreive specific keys from a dictionary object
This function searches through a dictionary, and
retreives keys that match keys from a list. This function
will find matching keys in every level of the dictionary heirarchy.
Inputs:
input_dict - A dictionary (expected to be from json.loads()
in the context of BetterReads, but the function
will work on any dictionary).
keys_to_extract - A list of keys that you want to extract from the
json_dict object.
Output:
new_dict - A new "flattened"dictionary with all the matching keys.
All the keys are in the top level.
"""
new_dict={}
for item in input_dict.keys():
if type(input_dict[item]) is dict:
temp_dict = retreive_details(input_dict[item],keys_to_extract)
new_dict.update(temp_dict)
if item in keys_to_extract:
new_dict[item] = input_dict[item]
return new_dict
|
f80c4bac321227a09a9cdf8bac3b1b4e0b16ff5d
| 637,039 |
def compute_var_bound(gammas):
""" computes the variance bound for the provided gamma values """
return 1./(1 + gammas**2)
|
7807f5be071af7ad4149ef1afa13ecbf8e2f7ef8
| 163,155 |
from pathlib import Path
from typing import List
def path_does_not_contain(path: Path, names: List[str]) -> bool:
"""Check if path does not contain a list of names."""
for name in names:
if name in str(path):
return False
return True
|
647aebe4debd5f97ebe686501a6075008f830de4
| 488,526 |
def camelize(string, uppercase_first_letter=True):
"""
Convert a string with underscores to a camelCase string.
Inspired by :func:`inflection.camelize` but even seems to run a little faster.
Args:
string (str): The string to be converted.
uppercase_first_letter (bool): Determines whether the first letter
of the string should be capitalized.
Returns:
str: The camelized string.
"""
if uppercase_first_letter:
return ''.join([word.capitalize() for word in string.split('_')])
elif not uppercase_first_letter:
words = [word.capitalize() for word in string.split('_')]
words[0] = words[0].lower()
return ''.join(words)
|
456056892220af135e26bed047a9bf51f178aa7f
| 561,495 |
def get_volume(low: list,
up: list) -> float:
"""Returns the volume defined of a box defined by lower and upper limits."""
vol = 1.0
for i in range(len(low)):
vol = vol * (up[i] - low[i])
return vol
|
6cf311e064822f4875137e98a51a8d8041aa2c7c
| 191,900 |
def sum_all(node):
"""
Sum all list elements together
:param node: value of head node, start of list
:return: int: sum of list elements
"""
if node is not None:
return node.value + sum_all(node.next_node) # tally those bad boys up
return 0
|
abecb662291705a615f03040affd861c74f998e4
| 275,811 |
from typing import Dict
def format_location_name(location: Dict):
"""Returns a string with a combination of venue name, city
and state, depending on what information is available"""
if not location:
return None
if "venue" not in location and "city" not in location and "state" not in location:
return None
if location["venue"] and location["city"] and location["state"]:
return "{} ({}, {})".format(location["venue"],
location["city"],
location["state"])
elif location["venue"] and (not location["city"] and not location["state"]):
return location["venue"]
elif location["city"] and location["state"] and not location["venue"]:
return "({}, {})".format(location["city"], location["state"])
elif location["city"] and not location["state"]:
return location["city"]
|
192542c15c17dde10feb9f8c0b6ec4a1fa65e991
| 660,889 |
def string_hash(text, mod):
""" Return a hash value for an ASCII string. The value will be
between 0 and mod-1. It is advisable to use a prime number
for mod to guarantee a fairly uniform distribution. """
base = 256 # size of the alphabet (ASCII)
numstr = [ord(char) for char in text]
length = len(numstr)
hashval = 0
assert all(0 <= num < base for num in numstr)
for ind, val in enumerate(numstr):
hashval += base ** (length-ind-1)*val
hashval %= mod
return hashval
|
ff6018fbf6404a6ac4dfc088c676581eb0b59b2b
| 182,328 |
def get_node_by_id(node_id, dialogue_node_list):
"""
Takes a node id and returns the node from the dialogue_node_list
"""
for dialogue_node in dialogue_node_list:
if dialogue_node["Id"] == node_id:
return dialogue_node
return None
|
f475e9c3d1d4eae5b1cc95325471bacb204a626d
| 500,603 |
import csv
def load_room_list(room_list_file):
"""Returns list rooms from file."""
with open(room_list_file, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
room_list = []
for row in spamreader:
room_list.append(row[1])
return room_list
|
0080becc3b2189bf441576901a8f0b14468b4932
| 272,180 |
def _only_one_selected(*args):
"""Test if only one item is True."""
return sum(args) == 1
|
9966cc7c2cde16c689f29ba2add80b2cddce56e7
| 704,592 |
import functools
def retry_with_fallback(triggering_error, **fallback_kwargs):
"""
Rerun a function in case a specific error occurs with new arguments.
:param triggering_error: Error class that triggers the decorator to re-run the function.
:type triggering_error: Exception
:param fallback_kwargs: Fallback named arguments that are applied when the function is re-run.
:type fallback_kwargs: dict
:return: Decorator.
:rtype: func
"""
def decorator(func):
"""
Actual decorator
"""
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
try:
function_result = func(*args, **kwargs)
except triggering_error:
kwargs.update(fallback_kwargs)
function_result = func(*args, **kwargs)
return function_result
return func_wrapper
return decorator
|
720320d33681dce682b3643538961cddf577ff29
| 290,392 |
def _calculate_verification_code(hash: bytes) -> int:
"""
Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed.
See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm
"""
return ((0xFC & hash[0]) << 5) | (hash[-1] & 0x7F)
|
173f9653f9914672160fb263a04fff7130ddf687
| 704,115 |
from typing import Sequence
def hagenbach_bishoff(vector_size: int, scores: Sequence[float]) -> Sequence[int]:
"""
Split a vector between participants based on continuous fractions.
https://en.wikipedia.org/wiki/Hagenbach-Bischoff_system
The code is based on https://github.com/crflynn/voting
:param vector_size: the total number of elements to be split
:param scores: real-valued vector fractions for each peer
:returns: integer-valued partitions assigned to every peer
"""
total_score = sum(scores)
allocated = [int(vector_size * score_i / total_score) for score_i in scores]
while sum(allocated) < vector_size:
quotients = [score / (allocated[idx] + 1) for idx, score in enumerate(scores)]
idx_max = quotients.index(max(quotients))
allocated[idx_max] += 1
return allocated
|
2e4582176600e37777387d4b0810ffab910d3921
| 215,740 |
def default_while_loop_termination_case(state):
"""
Checks if the state is falsey
Args:
state: An object that should capable of being passed to `bool`
Returns:
True if the state is falsey or False if the state is Truthy
"""
return not bool(state)
|
1af71d17ca80ed89cd5179fc375ecdd4a61af9c9
| 279,650 |
def get_input_masks(nx_node, nx_graph):
"""
Return input masks for all inputs of nx_node.
"""
input_edges = list(nx_graph.in_edges(nx_node['key']))
input_masks = [nx_graph.nodes[input_node]['output_mask'] for input_node, _ in input_edges]
return input_masks
|
f42a6aad02594deb9967c47a265c8cbec39f7b8c
| 167,427 |
def fix_top(fig):
"""Normalize memory usage reported by `top` to KB"""
if fig.endswith('m'):
return float(fig.strip('m')) * 1024
else:
return int(fig)
|
706642c45f03e7e54728e5d7bac819c91dbcea70
| 393,488 |
def one(nodes, or_none=False):
"""
Assert that there is exactly one node in the give list, and return it.
"""
if not nodes and or_none:
return None
assert len(
nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))
return nodes[0]
|
adb4d97553e00f53c38d32cf95ecdacb22f252d6
| 475,617 |
def to_hex(value):
"""
Convert decimal value to hex string.
"""
return " 0x%0.4X" % value
|
561617c8b4929b6dced807346c0fa9203f9221b8
| 448,663 |
def to_string(value):
""" Convert a boolean to on/off as a string.
"""
if value:
return "On"
else:
return "Off"
|
2069b48126a13c6b7a5c51b96dd90929a27a178c
| 349,945 |
def reverse(seq):
"""Reverses a string given to it."""
return seq[::-1]
|
ab4a45809dc81b850dde473dd21a893f9fcd92c6
| 471,540 |
def extract_bool(
params: dict,
key: str,
default: bool,
) -> bool:
"""Safely extract boolean value from user input."""
value = params.get(key)
if value is None:
result = default
else:
result = value == 'on'
return result
|
dd02e2544eb219c2d10f1d5570dd18b5e934d095
| 473,712 |
def get_steps_kwarg_parsers(cls, method_name):
"""
Analyze a method to extract the parameters with command line parsers.
The parser must be a :class:`Param` so it handles parsing of arguments
coming from the command line. It must be specified in the ``options``
class attribute.
:param method_name: name of the method to analyze
:param cls: class of the method to analyze
:returns: map of parameter names to their Param object
"""
method = getattr(cls, method_name)
meth_options = cls.options.get(method_name, dict())
return meth_options
|
5cc991c63c8008e92ff2bdc59c08ae1c96caa120
| 665,065 |
def test(agent, env, policy):
"""
Tests an agent given an environment and the agent's policy
:param agent: the agent to test
:param env: the environment to test in
:param policy: the policy to follow
:return: agent's total reward as float
"""
done = False
obs = env.reset()
total_reward = 0.0
while not done:
action = policy[agent.discretize(obs)]
next_obs, reward, done, info = env.step(action)
obs = next_obs
total_reward += reward
return total_reward
|
2a4c334ba00e7a3ec6fe92e48a300187b5476f80
| 226,570 |
def remote_property(name, get_command, set_command, field_name, doc=None):
"""Property decorator that facilitates writing properties for values from a remote device.
Arguments:
name: The field name to use on the local object to store the cached property.
get_command: A function that returns the remote value of the property.
set_command: A function that accepts a new value for the property and sets it remotely.
field_name: The name of the field to retrieve from the response message to get operations.
"""
def getter(self):
try:
return getattr(self, name)
except AttributeError:
value = getattr(self.sendCommand(get_command()), field_name)
setattr(self, name, value)
return value
def setter(self, value):
setattr(self, name, value)
self.sendCommand(set_command(value))
return property(getter, setter, doc=doc)
|
59c81882e69451409e6bb43219faf456cac93e4a
| 545,018 |
def count_increases(seq):
"""Count the number of elements in a sequece greater than the previous"""
increases = 0
for i in range(1, len(seq)):
if seq[i] > seq[i-1]:
increases += 1
return increases
|
10f2f6f8438b3747daf4e37a05fd21ed10ee745f
| 531,703 |
def bytes2str(data):
"""
Convert bytes to string
>>> bytes2str(b'Pwning')
'Pwning'
>>>
"""
data = "".join(map(chr, data))
return data
|
cd2e7fd59628c7b4eb8fdc918148f960f1226d6f
| 18,271 |
import torch
def random_points_1D(N=100):
"""Sample random points in 1d
Parameters
----------
N : int (default: 100)
Number of points
Return
------
x : tensor, shape (1, N)
points
"""
x = 2 * (torch.rand(1, N) - 0.5)
return x
|
8bdf44a66e47f28cd4d378d76ffacc0ddca3553e
| 189,237 |
def REDUCE(_input, initial_value, _in):
"""
Applies an expression to each element in an array and combines them into a single value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/
for more details
:param _input: Can be any valid expression that resolves to an array.
:param initial_value: The initial cumulative value set before in is applied to the first element of the input array.
:param _in: A valid expression that reduce applies to each element in the input array in left-to-right order.
:return: Aggregation operator
"""
return {'$reduce': {'input': _input, 'initialValue': initial_value, 'in': _in}}
|
730433e32b7d99de794589064bb0a31394ae7b34
| 675,726 |
def next_available_id(v):
"""
Return smallest nonnegative integer not in v.
"""
i = 0
while i in v:
i += 1
return i
|
f5b3d7215e435de92ebc6ae7d52f64329c82e847
| 259,805 |
def mean_over_dims(x, dims):
"""Take a mean over a list of dimensions keeping the as singletons"""
for dim in dims:
x = x.mean(dim=dim, keepdim=True)
return x
|
6e4dcba935b67c6c5e8e028c9e9a0930f1d84201
| 596,832 |
def readlines(path):
"""Read lines from a text file.
Args:
path (str): Full path to file
Returns:
list: File text
"""
with open(path, 'r') as handle:
return handle.readlines()
|
c899a9383e946e6047dd3945a1b0e02b511a3de4
| 465,683 |
import imghdr
def validateImageHeader(file_path):
"""
Check whether the file header is none
:param file_path: File to validate header of
:return: boolean indicating whether header is none or not
"""
header = imghdr.what(file_path)
if header is None:
return False
else:
return True
|
a9b92a71a4b35455ea401d8f82c448c170d33e63
| 261,642 |
from pathlib import Path
def is_installed_module(module_filename):
"""
Checks if a module is "installed" (e.g. using pip), as opposed to a "local" module, belonging
to user's env (e.g. local development tree).
"""
return any(
p.name in ['site-packages', 'dist-packages']
for p in Path(module_filename).parents
)
|
dfecff6c6c033e947271a1bbe04a98d6e8510ba6
| 232,729 |
from typing import Iterable
from typing import Tuple
import networkx
def build_graph(data: Iterable[Tuple[dict, str, dict]]):
"""
Builds a NetworkX DiGraph object from (Child, Edge, Parent) triples.
Each triple is represented as a directed edge from Child to Parent
in the DiGraph.
Child and Parent must be dictionaries containing all hashable values
and a 'name' key (this is the name of the node in the DiGraph).
Edge must be a string representing an edge label from Child to Parent.
:param data: Iterable of (Child, Edge, Parent) triples.
:rtype: networkx.DiGraph
"""
g = networkx.DiGraph()
for child_attrs, edge, parent_attrs in data:
if 'name' not in child_attrs or 'name' not in parent_attrs:
raise ValueError(
"Both child and parent dicts must contain a 'name' key.\n"
"Provided Child data: {}\n"
"Provided Parent data: {}\n".format(child_attrs, parent_attrs)
)
# Copy dicts so popping 'name' doesn't affect the underlying data
child_attrs, parent_attrs = child_attrs.copy(), parent_attrs.copy()
child_name, parent_name = child_attrs.pop('name'), parent_attrs.pop('name')
# Update node attributes only if the updated version has strictly more data
# than the previous version
if child_name not in g or set(child_attrs).issuperset(g.nodes[child_name]):
g.add_node(child_name, **child_attrs)
if parent_name not in g or set(parent_attrs).issuperset(g.nodes[parent_name]):
g.add_node(parent_name, **parent_attrs)
g.add_edge(child_name, parent_name, label=edge)
return g
|
6d43f3d2b9698eaac54cfcee38fd005e6762eaf6
| 20,813 |
def surround(text: str, tag: str):
"""Surround provided text with a tag.
:param text: text to surround
:param tag: tag to surround the text with
:return: original text surrounded with tag
"""
return "<{tag}>{text}</{tag}>".format(tag=tag, text=text)
|
b6316770a771a79c859c698406a13e8f8f239231
| 231,917 |
def _GetKubernetesObjectsExportConfigForClusterCreate(options, messages):
"""Gets the KubernetesObjectsExportConfig from create options."""
if options.kubernetes_objects_changes_target is not None or options.kubernetes_objects_snapshots_target is not None:
config = messages.KubernetesObjectsExportConfig()
if options.kubernetes_objects_changes_target is not None:
config.kubernetesObjectsChangesTarget = options.kubernetes_objects_changes_target
if options.kubernetes_objects_snapshots_target is not None:
config.kubernetesObjectsSnapshotsTarget = options.kubernetes_objects_snapshots_target
return config
|
34e30e59239e73caa7698f718f01b8192aa98e41
| 260,294 |
def reverse_hex(input_hex):
"""Reverse a HEX string, treating 2 chars as a byte.
Expected results look like this:
reverse_hex('abcdef') = 'efcdab'
Args:
input_hex (str): Input string in hex which needs to be converted.
Returns:
Hex string reversed.
"""
return "".join([input_hex[x: x + 2] for x in range(0, len(input_hex), 2)][::-1])
|
4ae94612184f1df6961a09a1f2dfea4167329a1a
| 296,250 |
def is_position_sup(pos1, pos2):
"""Return True is pos1 > pos2"""
return pos1 > pos2
|
4704f5053b2de631ab6758ff49c3a243dc479115
| 489,431 |
import re
def split_camel_case(input_string):
"""
This function is used to transform camel case words to more words
Args:
input_string: camel case string
Returns: Extracted words from camel case
"""
splitted = re.sub('([A-Z][a-z]+)', r' \1', re.sub('([A-Z]+)', r' \1', input_string)).split()
joined_string = " ".join(splitted)
return joined_string
|
3ab91f9e3a626fe990d475fb2952f4e2fb479861
| 314,093 |
def hsv_to_rgb(h, s, v):
""" Convert hsv color code to rgb color code.
Naive implementation of Wikipedia method.
See https://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93
Args:
h (int): Hue 0 ~ 360
s (int): Saturation 0 ~ 1
v (int): Value 0 ~ 1
"""
if s < 0 or 1 < s:
raise ValueError("Saturation must be between 0 and 1")
if v < 0 or 1 < v:
raise ValueError("Value must be between 0 and 1")
c = v * s
h_dash = h / 60
x = c * (1 - abs(h_dash % 2 - 1))
rgb_dict = {
0: (c, x, 0),
1: (x, c, 0),
2: (0, c, x),
3: (0, x, c),
4: (x, 0, c),
5: (c, 0, x),
}
default = (0, 0, 0)
rgb = [0, 0, 0]
for i in range(len(rgb)):
rgb[i] = (v - c + rgb_dict.get(int(h_dash), default)[i]) * 255
rgb = map(int, rgb)
return tuple(rgb)
|
6b210f50b0eaaec7e12b524811fda7bea45cd417
| 262,432 |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product
|
3d6d56f03817f9b4db0e7671f6c95c229a14a042
| 689,175 |
def sort_questions(data_df, grouped_questions, grouped_choices, sort_by_choices):
"""
Sort questions in the dataframe to plot them in their group and sort them in their group according to the responses.
Args:
data_df (df): Dataframe of data to plot
grouped_questions (list): each sub-list is a group of questions which will be plotted together
grouped_choices (dict): choices sorted by location where they will be plotted ("left", "center", "right")
sort_by_choices (str): choices by which to sort the questions ("left", "right", "no_sorting")
Returns:
df: Dataframe with reordered columns (columns represent the questions)
"""
if sort_by_choices == "no_sorting":
return data_df
# sort questions by the selected sorting (left / right)
# and add half of the "centered" responses as well since they shift the bars outside as well
sorted_questions = (
(
data_df.loc[grouped_choices[sort_by_choices]].sum(axis=0)
+ data_df.loc[grouped_choices["center"]].sum(axis=0) / 2
)
.sort_values(ascending=False)
.index
)
# resort data frame according to the groups so the questions are sorted within each group by the selected sorting
sorted_group_questions = [
question
for question_group in grouped_questions
for question in sorted_questions
if question in question_group
]
return data_df.reindex(columns=sorted_group_questions)
|
6239b8369a552c9f02116a980ca9c8b5b55c5daf
| 488,519 |
import random
def randhex(n):
"""generate a string of random hex digits"""
return "".join([random.choice("abcdef0123456789") for _ in range(n)])
|
76994a77d6e87b47a91c1e676a48159189112165
| 585,409 |
def IsPrefixLeDecoder(prefix, decoder, name_fcn):
"""Returns true if the prefix is less than or equal to the
corresponding prefix length of the decoder name."""
decoder_name = name_fcn(decoder)
prefix_len = len(prefix)
decoder_len = len(decoder_name)
decoder_prefix = (decoder_name[0:prefix_len]
if prefix_len < decoder_len
else decoder_name)
return prefix <= decoder_prefix
|
b7f5f01a5fe2a8e626ccbb8b6ec757db34769298
| 150,423 |
def get_passed_tests(log_file_path):
"""Gets passed tests with OK status"""
ok_test_line_pattern = "[ OK ] "
ok_tests = []
with open(log_file_path) as log_file_obj:
for line in log_file_obj.readlines():
if ok_test_line_pattern in line:
ok_tests.append(line.split(ok_test_line_pattern)[1])
return ok_tests
|
97fdeab4a2330864f57cd7ac70e8d5f81eaeaa78
| 39,146 |
import itertools
def fast_forward_to_length(sequences, length):
"""
Return an itertools.dropwhile that starts from
the first sequence that has the given length.
>>> list(fast_forward_to_length([list(range(n)) for n in range(6)], 4))
[[0, 1, 2, 3], [0, 1, 2, 3, 4]]
"""
return itertools.dropwhile(lambda seq: len(seq) != length, sequences)
|
41650d1bede05d96bfb1c1ceb4b94eee2a1c6f53
| 43,248 |
def get_longitude_tuple(imgMetadata):
"""
Returns the tuple containing the degrees, minutes and seconds of the
longitude coordinate as float values.
"""
return (imgMetadata['Exif.GPSInfo.GPSLongitude'].value[0], imgMetadata['Exif.GPSInfo.GPSLongitude'].value[1], imgMetadata['Exif.GPSInfo.GPSLongitude'].value[2])
|
46b1fa0c319e33c6e75c133446a679f955e6abda
| 201,697 |
def pixelsize(info_dict):
""" Computes the pixel size in m/pixel
Parameters
-----------
info_dict: dictionnary
Returns
-------
pixelsize: float
size of the pixel in meter/pixel
"""
# Pixel length (m/pix)
pixsize = info_dict['cameras'][info_dict['channel']]['Photocell_SizeX'] * info_dict['binning_X']
info_dict['pixelSize']=pixsize
return info_dict
|
c73f81152a48e8d9211d558b60453ef0bd37f639
| 611,946 |
def f_ema(close_prices, window):
"""Calculates exponential moving average (EMA).
This function takes historical data, and a moving window to calculate EMA.
EMA differs from standard moving average with EMA placing a higher weight on more recent prices.
As the moving average takes previous closing prices into account, its length will be len(candles) - window
Args:
close_prices (list of float): A list of close prices for each period.
window (int): The moving window to take averages over.
Returns:
list of float: A list of EMAs
"""
ema = []
# calculate EMA
# Smoothing factor
smooth = 2.0/(window + 1.0)
# Calculate first EMA from simple average
ema.append(sum(close_prices[:window])/window)
# Calculate remaining EMA values
i = 0
for close_price in close_prices[window:]:
new_ema = close_price*smooth + ema[-1]*(1.0-smooth)
ema.append(new_ema)
i += 1
return ema
|
3f7ece218cc234389da454b24c5a5325b2d932d4
| 505,667 |
def get_machines(graph):
"""
Return list of physical machines in the landscape
:param graph: Networkx graph
:return: List of physical machines
"""
machines = {}
for node, node_data in graph.nodes(data=True):
if node_data["type"] == "machine":
machines[node] = node
return machines
|
524e12412f5ebe3a717ccfba01eb15bd021eb877
| 594,632 |
import base64
import hashlib
def make_rule_hash(rule):
"""Make a good-enough hash for a rule."""
s = "\r".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)])
return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii')
|
4281608cecbac4a39c1574a874f469c618dc9f0d
| 200,050 |
def add_column(data, col_name, column):
"""Return data where a column has been added."""
return data.assign(**{col_name: column})
|
300b508679891f5b540c96a2b5f8317e13f0d5d7
| 315,657 |
def make_invalid_op(name: str):
"""
Return a binary method that always raises a TypeError.
Parameters
----------
name : str
Returns
-------
invalid_op : function
"""
def invalid_op(self, other=None):
typ = type(self).__name__
raise TypeError(f"cannot perform {name} with this index type: {typ}")
invalid_op.__name__ = name
return invalid_op
|
546416345b5040410a438fd1b3f07a4362fb1875
| 522,462 |
def trapezoidal(f, a, b, n=10000):
"""trapez method for numerical integration"""
s = 0.0
h = (b - a) / n
for i in range(0, n):
s += f(a + i * h)
return h * (s + 0.5 * (f(a) + f(b)))
|
113a6a047e3fe320f5e0d511dc3119d6564fffa5
| 634,005 |
def tensor_name(tensor):
"""Returns the Tensor's name.
Tensor names always have the structure <op_name>:<int>. This method
returns the portion before the ':'.
Args:
tensor: Tensor.
Returns:
String name of the Tensor.
"""
return tensor.name.split(":")[-2]
|
71e814731708d35394697cb3627cc8ad918b3cab
| 240,662 |
from typing import Dict
def create_branch(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
name: str,
revision: str,
) -> Dict[str, str]:
"""Execute the OpenAPI `POST /v2/datasets/{owner}/{dataset}/branches`.
Arguments:
access_key: User's access key.
url: The URL of the graviti website.
owner: The owner of the dataset.
dataset: Name of the dataset, unique for a user.
name: The name of the branch.
revision: The information to locate the specific commit, which can be the commit id,
the branch name, or the tag name.
Returns:
The response of OpenAPI.
Examples:
>>> create_branch(
... "ACCESSKEY-********",
... "https://api.graviti.com",
... "czhual",
... "MNIST",
... name="branch-1",
... revision="main"
... )
{
"name": "main",
"commit_id": "fde63f357daf46088639e9f57fd81cad",
"parent_commit_id": "f68b1375454f459b8a486b8d1f4d9ddb",
"title": "first commit",
"description": "desc",
"committer": "graviti",
"committed_at": "2021-03-03T18:58:10Z"
}
"""
url = f"{url}/v2/datasets/{owner}/{dataset}/branches"
post_data = {"name": name, "revision": revision}
return open_api_do( # type: ignore[no-any-return]
"POST", access_key, url, json=post_data
).json()
|
1f9c8c4414faffaa79ee96949662c17051589752
| 478,803 |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
for i in range(0, len(seq)):
iMin = i
for j in range(i+1, len(seq)):
if seq[iMin] > seq[j]:
iMin = j
if i != iMin:
seq[i], seq[iMin] = seq[iMin], seq[i]
return seq
|
764c73287b846479bbcde935345c4c0a26fa934e
| 619,489 |
import math
def _get_rupture_dimensions(src, mag, nodal_plane):
"""
Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param src:
a PointSource, AreaSource or MultiPointSource
:param mag:
a magnitude
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`.
:returns:
Tuple of two items: rupture length in width in km.
The rupture area is calculated using method
:meth:`~openquake.hazardlib.scalerel.base.BaseMSR.get_median_area`
of source's
magnitude-scaling relationship. In any case the returned
dimensions multiplication is equal to that value. Than
the area is decomposed to length and width with respect
to source's rupture aspect ratio.
If calculated rupture width being inclined by nodal plane's
dip angle would not fit in between upper and lower seismogenic
depth, the rupture width is shrunken to a maximum possible
and rupture length is extended to preserve the same area.
"""
area = src.magnitude_scaling_relationship.get_median_area(
mag, nodal_plane.rake)
rup_length = math.sqrt(area * src.rupture_aspect_ratio)
rup_width = area / rup_length
seismogenic_layer_width = (src.lower_seismogenic_depth
- src.upper_seismogenic_depth)
max_width = (seismogenic_layer_width
/ math.sin(math.radians(nodal_plane.dip)))
if rup_width > max_width:
rup_width = max_width
rup_length = area / rup_width
return rup_length, rup_width
|
067b71f4c4f52b82233443cf11c8e03d957f19ce
| 533,831 |
def iterpairs(seq):
"""
Parameters
----------
seq: sequence
Returns
-------
iterator returning overlapping pairs of elements
Examples
--------
>>> iterpairs([1, 2, 3, 4])
[(1, 2), (2, 3), (3, 4)
"""
# input may not be sliceable
seq_it = iter(seq)
seq_it_next = iter(seq)
next(seq_it_next)
return zip(seq_it, seq_it_next)
|
083f7381187c91259e438fe8aa98ab1f89e8677c
| 287,401 |
def check_schedule_cycle_bounds(current_cycle, max_cycle, check_cycle):
"""
Checks whether the provided schedule cycle slot falls within our accepting window
:param current_cycle: int
The current MHP cycle
:param max_cycle: int
The max MHP cycle
:param check_cycle: int
The mhp cycle number to check
"""
right_boundary = current_cycle
left_boundary = (right_boundary - max_cycle // 2) % max_cycle
# Check if the provided time falls within our modular window
if left_boundary < right_boundary:
return left_boundary <= check_cycle <= right_boundary
else:
return check_cycle <= right_boundary or check_cycle >= left_boundary
|
bd82b732ecbf9b07b77e4eae4a60fe57f5ad8807
| 553,690 |
def SplitMask(mask, mask_1_length):
"""
Parameters
----------
mask : tuple
tuple of n 1d array of size s, coordonate of s points.
mask_1_length : int
length of mask_1 after spliting
Returns
-------
mask_1 : tuple
tuple of n 1d array of size mask_1_length, coordonate of points
mask_2 : tuple
tuple of n 1d array of size s - mask_1_length, coordonate of points.
"""
mask_1 = []
mask_2 = []
for i in range(len(mask)):
mask_1.append(mask[i][0:mask_1_length])
mask_2.append(mask[i][mask_1_length:])
mask_1 = tuple(mask_1)
mask_2 = tuple(mask_2)
return mask_1, mask_2
|
7fcdf87a34bfaa564fdedffe03749e8e4eda1d3a
| 480,601 |
def get_size(ser, idx):
"""
Gets indexed value from pd.Series but returns 0 if index not found.
"""
try:
s = ser[idx]
except KeyError:
s = 0
return s
|
65f4dc1c936587b85832bbc164419f623f64987f
| 400,503 |
def quote(value):
"""Quote a value unambigously w.r.t. its data type.
The result can be used during import into a relational database.
:param value: The value to transform.
:return: ``'null'`` if ``value`` is ``None``, ``'true'`` if it is ``True``,
``'false' if it is ``False``. For numeric values, the result is the
corresponding string representation. Infinite values are represented by
``'inf'`` and ``'-inf'``, respectively; not-a-number is represented by
``'nan'``. For strings, the result is the string itself, surrounded by
``'"'``, and with the characters ``'"'``, ``'\\'``, ``'\\b'``,
``'\\t'``, ``'\\n'``, ``'\\v'``, ``'\\f'`` and ``'\\r'`` escaped using
``'\\'``.
:raises TypeError: If ``value`` is neither ``None`` nor of type ``bool``,
``int``, ``float`` or ``str``.
"""
if value is None:
return 'null'
if isinstance(value, bool):
return 'true' if value else 'false'
if isinstance(value, int) or isinstance(value, float):
return str(value)
if isinstance(value, str):
# Use double quotation marks around all strings (and only around
# strings), so that strings can be identified by them, and the special
# values ``null``, ``false``, ``true``, ``inf``, ``-inf`` and ``nan``
# can be identified by the absence of quotations marks.
return ('"' + value.replace('\\', '\\\\').replace('"', '\\"').replace('\b', '\\b').replace('\t', '\\t').replace('\n', '\\n').replace('\v', '\\v').replace('\f', '\\f').replace('\r', '\\r') + '"')
raise TypeError('Unable to quote value of type %r'
% (type(value).__name__,))
|
5da0d4faf06e0c1254f828a0d048f56859bbe5b6
| 187,639 |
from typing import Counter
def a_scramble(str_1,str_2):
"""Test if all the letters of word a are contained in word b"""
str_1 = str_1.upper()
str_2 = str_2.upper()
letters = Counter(str_1)
letters.subtract(Counter(str_2))
return all(v >= 0 for v in letters.values())
|
e9e088b4c2e18f7efb6ba5749c05eeede4531bef
| 402,081 |
def geq_indicate(var, indicator, var_max, thr):
"""Generates constraints that make indicator 1 iff var >= thr, else 0.
Parameters
----------
var : str
Variable on which thresholding is performed.
indicator : str
Identifier of the indicator variable.
var_max : int
An upper bound on var.
the : int
Comparison threshold.
Returns
-------
List[str]
A list holding the two constraints.
"""
lb = "- %s + %d %s <= 0" % (var, thr, indicator)
ub = "- %s + %d %s >= -%d" % (var, var_max - thr + 1, indicator, thr - 1)
return [lb, ub]
|
319f18f5343b806b7108dd9c02ca5d647e132dab
| 705,773 |
def utility_function(state, monte_carlo):
"""
This functions takes in a state and performs monte carlo
tree search. It returns the utility of the state and
the reward for each possible actions.
:param monte_carlo: a monte_carlo class
:param state: The state should be in the form that monte_carlo requires.
:return: U(state), Q(state,action) for all actions in A
"""
monte_carlo.update(state)
utility, q_values = monte_carlo.pick_move()
return utility, q_values
|
f0d7e2b341119dcbb1118220f1b4b0b04f79aca5
| 134,110 |
def split_path(path):
"""Split a *canonical* `path` into a parent path and a node name.
The result is returned as a tuple. The parent path does not
include a trailing slash.
>>> split_path('/')
('/', '')
>>> split_path('/foo/bar')
('/foo', 'bar')
"""
lastslash = path.rfind('/')
ppath = path[:lastslash]
name = path[lastslash + 1:]
if ppath == '':
ppath = '/'
return (ppath, name)
|
7c80188a9f84a2c51d684966867efa36e4d807de
| 371,887 |
def adjacent(g, x, y):
""" Returns whether nodes x and y are adjacent """
return g.has_edge(x, y) or g.has_edge(y, x)
|
c7149fe559c8fa6e533f1003b424147e22fba1c6
| 456,959 |
import json
def load_json_schema(filename=None):
""" Loads the given schema file """
if filename is None:
return
with open(filename) as schema_file:
schema = json.loads(schema_file.read())
return schema
|
f313bba5e3549d5ae161e5ec7a962e92e4e2d96f
| 639,903 |
def tally_letters(string):
"""Given a string of lowercase letters, returns a dictionary mapping each
letter to the number of times it occurs in the string."""
tally_dict = {}
for letter in string:
tally_dict[letter] = 0
for letter in string:
tally_dict[letter] += 1
return tally_dict
|
dba10fc0ac71d27cbbfe02c02d472360ec45a90b
| 552,205 |
def get_any(obj, keys, default=None):
"""
Return the first non-None value from any key in `keys`, in order
If all are None, then returns `default`
"""
for key in keys:
val = obj.get(key)
if val is not None:
return val
return default
|
8516d455bb5d19bf3a26f1f8f8471e6be3f06816
| 184,212 |
def flows_to_md(flows: dict, disp_num: int) -> str:
"""
Args:
flows: a raw dictionary of flows.
disp_num: The limit of flows to display.
Returns:
A mardkown of <=disp_num of flows, ordered in descending order.
"""
md = '|A|port|B|port|# of Packets|\n|---|---|---|---|---|\n'
ordered_flow_list = sorted(flows.items(), key=lambda x: x[1].get('counter'), reverse=True)
disp_num = min(disp_num, len(ordered_flow_list))
for flow in ordered_flow_list[:disp_num]:
(ipA, portA, ipB, portB), data = flow
md += f'|{ipA}|{portA}|{ipB}|{portB}|{data.get("counter", 0)}|\n'
return md
|
d57a3a51396c29930ecb243bf5c21cfef53d2ee2
| 216,745 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.