seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import json
def add_metadata_to_table(table, metadata, key='my_metadata'):
"""
Add json metadata to a pyarrow.Table under a given key
Notes
-----
Based on: https://stackoverflow.com/a/58978449/709975
"""
# convert dictionary to json representation (str object),
# then convert it to a ... | bigcode/self-oss-instruct-sc2-concepts |
def correl(dataset):
"""
Function that computes the correlation matrix for a given dataset.
:param dataset: Pandas dataframe
:return: Correlation matrix (Pandas Dataframe)
"""
corr_matrix = dataset.corr().abs()
return corr_matrix | bigcode/self-oss-instruct-sc2-concepts |
def get_aggregate_stats_overlay_bandwidth_ne_pk_tunnels(
self,
ne_pk_tunnel_list: list[str],
start_time: int,
end_time: int,
granularity: str,
) -> dict:
"""Get aggregate overlay bandwidth stats data filter by query
parameters
.. list-table::
:header-rows: 1
* - Swagger... | bigcode/self-oss-instruct-sc2-concepts |
def transpose(matrix):
"""Returns the transpose for the given matrix"""
if not matrix:
return []
elif matrix[0] and not isinstance(matrix[0], list):
return [[elem] for elem in matrix]
return list(map(list, zip(*matrix))) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def box2corners_th(box:torch.Tensor)-> torch.Tensor:
"""convert box coordinate to corners
Args:
box (torch.Tensor): (B, N, 5) with x, y, w, h, alpha
Returns:
torch.Tensor: (B, N, 4, 2) corners
"""
B = box.size()[0]
x = box[..., 0:1]
y = box[..., 1:2]
w = bo... | bigcode/self-oss-instruct-sc2-concepts |
def strip(input_str):
"""Strip newlines and whitespace from a string."""
return str(input_str.replace('\n', '').replace(' ', '')) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def rmlink_safe(linkpath: Path):
"""Remove the linkpath only if it is a symbolic link."""
if linkpath.is_symlink():
linkpath.unlink()
if linkpath.exists():
print(f"'{linkpath}' is not a symbolic link; it will not be replaced.")
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import collections
def _get_infrequent_phrases(features_set, threshold_rate=0.03):
"""Get infrequent phrases on given dataset
Args:
features_set (iter): list of feature's dict
threshold_rate (float, optional): Defaults to 0.03.
Returns:
set: set of infrequent phrase features
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_csv_links(text):
"""Get a list of csv links from the download link response text"""
links = text.replace("\r", "").split("\n")
links.remove("")
return links | bigcode/self-oss-instruct-sc2-concepts |
def str_is_empty_or_none(str_field: str) -> bool:
"""
Verifies whether a string is empty or None.
Args:
str_field (str): String to validate.
Returns:
bool: Evaluation result.
"""
return str_field is None or not str_field or str_field.isspace() | bigcode/self-oss-instruct-sc2-concepts |
def filter_clone(function, xs):
"""
Elements from xs are filtered out only for which the output of function holds True.
"""
filtered_lst = [] # We'll store our results here.
for elem in xs:
if function(elem):
filtered_lst += [elem]
return filtered_lst | bigcode/self-oss-instruct-sc2-concepts |
def _get_unit_of_variable(df, variable, multiple_units="raise"):
"""
Get the unit of a variable in ``df``
Parameters
----------
variable : str
String to use to filter variables
multiple_units : str
If ``"raise"``, check that the variable only has one unit and raise an
`... | bigcode/self-oss-instruct-sc2-concepts |
def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args... | bigcode/self-oss-instruct-sc2-concepts |
def YumGetPathToConfig(vm):
"""Returns the path to the mongodb config file."""
return '/etc/mongod.conf' | bigcode/self-oss-instruct-sc2-concepts |
def define_stim_state(rel_time, on_time, off_time):
"""
Define stimulus state (1 = ON; 0 = OFF) based on relative stimulus time
"""
stim_state = ((rel_time > on_time) * (rel_time < off_time)).astype(int)
return stim_state | bigcode/self-oss-instruct-sc2-concepts |
def check_axes(x, axes):
"""
Checks if a list of axes is valid for a tensor or ndarray.
If the input axis indices are not valid, a ValueError
will be raised. Otherwise, the axes will be processed into
a tuple of nonnegative integers
Parameters
----------
x : torch.Tensor or np.ndarray
... | bigcode/self-oss-instruct-sc2-concepts |
def send_request(client, post_data, **kwargs):
"""uses a dict to create a request on dataforSeo api
parameters:
client : Restclient object created with create_request
post_data: dict created with create_request
Optional parameters:
server: server to use for request
returns json style list"... | bigcode/self-oss-instruct-sc2-concepts |
def psy_const_of_psychrometer(psychrometer, atmos_pres):
"""
Calculate the psychrometric constant for different types of
psychrometer at a given atmospheric pressure.
Based on FAO equation 16 in Allen et al (1998).
:param psychrometer: Integer between 1 and 3 which denotes type of
psychrom... | bigcode/self-oss-instruct-sc2-concepts |
def to_lowercase_all(df):
"""
This function transforms all strings in the dataframe to lowercase
Args:
df (pd.DataFrame): Raw dataframe with some text columns.
Returns:
pd.DataFrame: Dataframe with lowercase standardization.
"""
return df.applymap(lambda s: s.lower() if type(s)... | bigcode/self-oss-instruct-sc2-concepts |
def hard_most_common_letter(a):
"""Takes in a string of lowercase letters and returns the most common letter (if multiple, just pick one)."""
# too tricky?
d = {}
for c in a:
d[c] = d.get(c, 0) + 1
l = list(d.items())
l.sort(key=lambda x: -x[1])
return l[0][0] | bigcode/self-oss-instruct-sc2-concepts |
def decompose_tokenized_text(token_list):
"""
Split the output of BERT tokenizer into word_list and tag_list
"""
# The initial tag is 'O'
tag = 'O'
word_list = []
tag_list = []
# A flag to indicate if it is in the entity now
# 0 means out, 1 means start, 2 means in the middle
i... | bigcode/self-oss-instruct-sc2-concepts |
import math
def temperature_range(n, cut):
"""
Define the range of allowed temperature
for given image size and cut.
"""
if isinstance(cut, (float, int)):
log = math.log(cut)
else:
log = cut.log()
T1 = 1 / (math.pi * n ** 2 * log)
T2 = 4 / (math.pi ** 3 * cut ** 2 * log... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def getLetters(string: str) -> Dict[str, int]:
"""Gets the letters of string and puts their occurences in a dictionary"""
letters: Dict[str, int] = {}
for letter in string:
letters[letter] = letters.get(letter, 0) + 1
return letters | bigcode/self-oss-instruct-sc2-concepts |
import html
def html2unicode(code):
""" Converts HTML entities to unicode ('&' => '&') """
return html.unescape(code) | bigcode/self-oss-instruct-sc2-concepts |
def should_send_event(socket, annotation, event_data):
"""
Inspects the passed annotation and action and decides whether or not
the underlying session should receive the event. If it should, the
action is wrapped up in a websocket packet and sent to the client.
"""
if socket.terminated:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse(text: str) -> List[str]:
"""
Parse a textual arguments into a list of strings in Unix style.
This function currently supports:
* Splitting arguments by spaces, cleaning up redundant spaces
* String literals using single and double quotes
:param text:... | bigcode/self-oss-instruct-sc2-concepts |
def rotate(password, rotate_type, *params):
"""Rotate password
- rotate left/right X steps - means that the whole string
should be rotated; for example, one right rotation would turn
abcd into dabc.
- rotate based on position of letter X - means that the whole string should
be rotat... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def point_asdict(search_space, point_as_list):
"""Convert the list representation of a point from a search space
to the dictionary representation, where keys are dimension names
and values are corresponding to the values of dimensions in the list.
.. seealso:: :class:`s... | bigcode/self-oss-instruct-sc2-concepts |
def split(arr, n_devices):
"""Splits the first axis of `arr` evenly across the number of devices."""
return arr.reshape(n_devices, arr.shape[0] // n_devices, *arr.shape[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (elemen... | bigcode/self-oss-instruct-sc2-concepts |
def find_root(node):
"""
Find the root of the current node.
:param node:
:return:
"""
current = node
while current.parent:
current = current.parent
return current | bigcode/self-oss-instruct-sc2-concepts |
def _strip_empty(d):
"""Strips entries of dict with no value, but allow zero."""
return {
k: v
for k, v in d.items()
if v or (type(v) == int and v == 0) or (type(v) == str and v == "")
} | bigcode/self-oss-instruct-sc2-concepts |
def adapt_param(p: float,
p_min: float,
p_max: float,
d: float,
d_target: float,
xi: float
) -> float:
""" Self adapts a param p given a measure m and control xi
Args:
p (float):... | bigcode/self-oss-instruct-sc2-concepts |
def repeated_argument(e: SyntaxError) -> str:
"""Generates a feedback for a repeated keyword argument error.
Parameters
----------
e : SyntaxError
the error object
Returns
-------
str
feedback message
"""
msg = "I couldn't parse your function call because I got a re... | bigcode/self-oss-instruct-sc2-concepts |
def _Cond(test, if_true, if_false):
"""Substitute for 'if_true if test else if_false' in Python 2.4."""
if test:
return if_true
else:
return if_false | bigcode/self-oss-instruct-sc2-concepts |
def dictfetchall(connection, sql, *params, **kwargs):
"""
Return all rows from a cursor as a dict,
if kwargs.get("format") == 'list', return as list
"""
with connection.cursor() as cursor:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description]
if kwargs.get("... | bigcode/self-oss-instruct-sc2-concepts |
def get_video_shape(params, is_space_to_depth=False):
"""Returns exact video shape as model's input."""
if is_space_to_depth:
video_shape = [params.num_frames // 2,
params.frame_size // 2,
params.frame_size // 2,
24]
else:
video_shape = [params.num_... | bigcode/self-oss-instruct-sc2-concepts |
import json
def make_request_callback(timeout_count, body_on_success,
http_error_status=504):
"""Make a request callback that timeout a couple of time before returning
body_on_success.
Returns:
A tuple (request_callback, attempts), attempts is an array of size one
... | bigcode/self-oss-instruct-sc2-concepts |
def factorial_recursive(num):
"""returns the factorial of num using a recursive method."""
if num == 1:
return 1
return num * factorial_recursive(num -1) | bigcode/self-oss-instruct-sc2-concepts |
import time
def timed(func):
"""
This decorator adds a timer to the decorated function. The original function results and the timer results
are returned as a tuple of size 2
:param func: the function to decorate
:return: decorated function
"""
def timed_method(*args, **kwargs):
sta... | bigcode/self-oss-instruct-sc2-concepts |
def fit_predict_for_chain(chain, train_input, predict_input):
""" Function apply fit and predict operations
:param chain: chain to process
:param train_input: InputData for fit
:param predict_input: InputData for predict
:return preds: prediction of the chain
"""
# Fit it
chain.fit_fro... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def ListIntToSequence(l: List[int], separator: str = '.') -> str:
"""Merge [192,168,42,1] to '192.168.42.1'
Returns:
str: int join with sep
"""
return separator.join(str(x) for x in l) | bigcode/self-oss-instruct-sc2-concepts |
def get_exec_command_python(language_cmd: str, in_file_path: str) -> str:
"""
Function which provides the execution command for an upcoming python execution
@param language_cmd: base language command, in this case "python"
@param in_file_path: file where the input code will exist
@return the execu... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_config(config, key=None):
"""Read a config file and return the right configuration."""
print("INFO: Loading configuration from", config)
config = yaml.load(open(config, 'r'), Loader=yaml.SafeLoader)
if key is not None:
if key in config:
print("INFO: Using the '... | bigcode/self-oss-instruct-sc2-concepts |
def get_user_display_name(u):
"""Get `display_name` for a user
Args:
u: user
Returns:
A string
example:
'Donald J. Trump'
"""
name = []
if u.first_name:
name.append(u.first_name)
if u.last_name:
name.append(u.last_name)
return '|'.joi... | bigcode/self-oss-instruct-sc2-concepts |
def launch_label(cfg):
"""Returns a label based on how far the piepline has progressed"""
order = ["Initial", "Classify", "Post", "Upload", "Debase", "RM", "RVM_initial", "RVM_final", "Finish"]
counter = sum(cfg["completed"].values()) # Number of True statements
return order[counter] | bigcode/self-oss-instruct-sc2-concepts |
import base64
import hashlib
def make_hash_string(string, output_length=10):
"""Create a hash for given string
Truncates an md5 hash to the desired length.
Will always be safe for file names.
Args:
string (str): input string
output_length (int): length for output
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def dot_prod(a,b):
"""
This function takes two vectors, a and b, and finds the dot
product,c.
"""
c = a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
return(c) | bigcode/self-oss-instruct-sc2-concepts |
def drop_msg(module_name, module_package):
""" Create info message for dropped modules.
"""
if module_package is not None:
ignore_msg = "drop %s (in %s)" % (module_name, module_package)
else:
ignore_msg = "drop %s" % module_name
return ignore_msg | bigcode/self-oss-instruct-sc2-concepts |
def format_coverage_line(text, statements, missed, coverage, missed_lines=False):
"""Format one line with code coverage report of one class or for a summary."""
format_string = "{:80} {:3d} {:3d} {:3d}%"
if missed_lines:
format_string += " N/A"
return format_string.format(text, statements... | bigcode/self-oss-instruct-sc2-concepts |
def extract_7z(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a 7z archive."""
cmdlist = [cmd, 'x']
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-o%s' % outdir, '--', archive])
return cmdlist | bigcode/self-oss-instruct-sc2-concepts |
def find_failed_results(run_artifacts: dict) -> list:
"""find the index and ID for which elements failed in run
Args:
run_artifacts (dict): dbt api run artifact json response
Returns:
list: list of tuples with unique id, index
"""
failed_steps = []
for index, result in enumera... | bigcode/self-oss-instruct-sc2-concepts |
def _check(value,x,y):
"""
Check if a value is between x and y
Parameters
----------
value : float
Value of interest.
x : float
Limit x.
y : float
Limit y.
Returns
-------
int
Numerical bool if value is between limits x and y.
"""
if x <... | bigcode/self-oss-instruct-sc2-concepts |
def d2l(dx, fc, i):
""" second-order left-sided derivative at index i """
D = -fc[i+2] + 4.0*fc[i+1] -3.0*fc[i]
D = D/(2.0*dx)
return D | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def custom_ravel(tup: Tuple[int, int], shape: Tuple[int, int]) -> int:
"""Ravel indexes for 2D array.
This is a jitted function, equivalent to the `numpy` implementation of
`ravel_multi_index`, but configured to accept only a single tuple as
the index to ravel, and only works... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cat_arange(counts, dtype=torch.int32):
"""
Concatenate results of multiple arange calls
E.g.: cat_arange([2,1,3]) = [0, 1, 0, 0, 1, 2]
Credits: https://stackoverflow.com/a/20033438
:param torch.tensor counts: a 1D tensor
:return: equivalent to torch.cat([torch.arange(c) for c... | bigcode/self-oss-instruct-sc2-concepts |
def is_ends_with_underscore(value: str):
"""Does value end with underscore."""
if value == "":
return False
else:
return value[-1] == '_' | bigcode/self-oss-instruct-sc2-concepts |
def verify_operator(operator):
"""
Check that ``operator`` is one of the allowed strings.
Legal operators include the following strings:
- '='
- '<='
- '>='
- '<'
- '>'
- '<>'
- 'like'
- 'regexp'
- 'is null'
- 'is not null'
EXAMPLES::
sage: from sage.da... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_float(source: str) -> float:
"""Converts a str to a float."""
return float(source) | bigcode/self-oss-instruct-sc2-concepts |
def get_parameter_list_from_request(req,parameter):
"""Extracts a parameter from the request.
Parameters
----------
req : HttpRequest
The HTTP request.
parameter : str
The parameter being extracted.
Returns
-------
List
List of comma separated parameters.
"... | bigcode/self-oss-instruct-sc2-concepts |
def notify_upgrade(app, flash):
"""If a new version is available, notifies the user via flash
that there is an upgrade to specter.desktop
:return the current version
"""
if app.specter.version.upgrade:
flash(
f"Upgrade notification: new version {app.specter.version.latest} is ava... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def import_config(conf_name):
"""
Load YAML configuration file
"""
with open("../etc/config.yaml", 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile)
cfg_sect = cfg[conf_name]
return cfg_sect | bigcode/self-oss-instruct-sc2-concepts |
import re
def sub_name(s):
"""replaces brackets with '-' and removes ',* """
#replace brackets with '_' and remove ',*
#s = re.sub('\W', '',s_n) # dont do that, will replace '-' as well
s_n = re.sub('[()]',"-",s)
s_n = re.sub("'","",s_n)
s_n = re.sub('\*',"",s_n)
return s_n | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_inline_name(op):
"""Tell if given name is viable for inlining."""
if re.match(r'^i_.*$', op.getName(), re.I):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import yaml
def load_yaml(file):
"""
Loads the yaml file and returns a dictionary of the file contents.
Parameters
----------
file : string
Name of the yaml file with extension i.e. 'filename.yaml'.
Returns
-------
dict
Structured contents of the yaml f... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def string_width(string):
"""Measure rendering width of string.
Count ZENKAKU-character as 2-point and non ZENKAKU-character as 1-point
"""
widthmap = {'Na': 1, 'N': 1, 'H': 1, 'W': 2, 'F': 2, 'A': 2}
return sum(widthmap[unicodedata.east_asian_width(c)] for c in string) | bigcode/self-oss-instruct-sc2-concepts |
def fixIncorrectDateEncoding(Date):
"""
Fix date string to make it conform to ISO standard.
"""
if 'T00:00:00Z' in Date:
return Date
return Date + "T00:00:00Z" | bigcode/self-oss-instruct-sc2-concepts |
import re
def replace_forceinline(input_string):
"""__forceinline__'d methods can cause 'symbol multiply defined' errors in HIP.
Adding 'static' to all such methods leads to compilation errors, so
replacing '__forceinline__' with 'inline' as a workaround
https://github.com/ROCm-Developer-Tools/HIP/blo... | bigcode/self-oss-instruct-sc2-concepts |
def split_macros(macros):
"""Split user-provided macro strings into a dictionary."""
split = [macro.split('=', 1) for macro in macros]
return {var: value for var, value in split} | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_cr(realmrep):
""" Removes probably sensitive details from a realm representation.
:param realmrep: the realmrep dict to be sanitized
:return: sanitized realmrep dict
"""
result = realmrep.copy()
if 'secret' in result:
result['secret'] = '********'
if 'attributes' in res... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def format_modified_time(entry):
"""Formats the modified time (seconds since epoch) for display on screen"""
return datetime.fromtimestamp(entry['mtime']).strftime('%b %-d %H:%M') | bigcode/self-oss-instruct-sc2-concepts |
def record_item_style(context):
"""
Return the style to be usd for the metric's current record specific item.
Like the :func:`record_style` template tag, this expects a template context
variable ``'metric'`` referring to the metric instance in question, as well
as a context variable ``'record'`` co... | bigcode/self-oss-instruct-sc2-concepts |
def find_first(item, vector):
"""return the index of the first occurence of item in vector"""
for i in range(len(vector)):
if item == vector[i]:
return i
return len(vector) | bigcode/self-oss-instruct-sc2-concepts |
def to_str(Q):
"""An informal, nicely printable string representation of the Quaternion object.
"""
return "{:.3f} {:+.3f}i {:+.3f}j {:+.3f}k".format(Q.q[0], Q.q[1], Q.q[2], Q.q[3]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def decontracted(phrase):
"""
Change words abbreviations into their actual word meaning
:param phrase: sentence we want to change
:return: modified sentence
"""
# specific
phrase = re.sub(r"won't", "will not", phrase)
phrase = re.sub(r"can\'t", "can not", phrase)
# gener... | bigcode/self-oss-instruct-sc2-concepts |
async def get_alternate_id(db, name: str) -> str:
"""
Get an alternate id for an API key whose provided `name` is not unique. Appends an integer
suffix to the end of the `name`.
:param db: the application database object
:param name: the API key name
:return: an alternate unique id for the key
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def _hash_file_obj(obj):
"""Hash a file-like object."""
return hashlib.sha256(obj).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def expand_path(path: Union[str, Path]) -> Path:
"""Convert relative paths to absolute with resolving user directory."""
return Path(path).expanduser().resolve() | bigcode/self-oss-instruct-sc2-concepts |
def _VerifyDirectoryIterables(existing, expected):
"""Compare two iterables representing contents of a directory.
Paths in |existing| and |expected| will be compared for exact match.
Arguments:
existing: An iterable containing paths that exist.
expected: An iterable of paths that are expected.
Raises... | bigcode/self-oss-instruct-sc2-concepts |
def prime_factor_decomposition(num):
"""
Prime factor decomposition of a number.
:param num: input number.
:return: all prime factors of input number.
"""
primes = [2]
for i in range(3, num):
if i * i > num:
break
flag = True
for j in primes:
i... | bigcode/self-oss-instruct-sc2-concepts |
def avoid_duplicate_names(new_column_name, columns, suffix):
"""Adds a suffix in case of a column name collision in a recursive way
:param new_column_name: a possible new column name
:type: str
:param columns: existing column names
:type: list
:param suffix: suffix to add to prevent collisions
... | bigcode/self-oss-instruct-sc2-concepts |
def validate_list(value):
"""
Validate a list input.
Parameters:
value (any): Input value
Returns:
boolean: True if value is a list
"""
return isinstance(value, list) | bigcode/self-oss-instruct-sc2-concepts |
def p(key):
"""Returns PDT namespace prefix"""
return '{http://ufal.mff.cuni.cz/pdt/pml/}%s' % (key) | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_llh(llh: float, gt_llh: float, tol: float = 1e-3):
"""Evaluate whether log likelihoods match."""
if llh is None:
return False
return abs(llh - gt_llh) < tol | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def servo_yaml(tmp_path: pathlib.Path) -> pathlib.Path:
"""Return the path to an empty servo config file."""
config_path: pathlib.Path = tmp_path / "servo.yaml"
config_path.touch()
return config_path | bigcode/self-oss-instruct-sc2-concepts |
def get_coords(x, y, params):
"""
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple c... | bigcode/self-oss-instruct-sc2-concepts |
def xor_decrypt(ciphertext: str, key: int) -> str:
""" Decrypt a hex-encoded ciphertext into plaintext.
Args:
ciphertext (str): The hex-encoded ciphertext
key (int): The single-byte key
Returns:
str: The plaintext
"""
return ''.join(chr(b ^ key) for b in bytes.fromhex(ciphe... | bigcode/self-oss-instruct-sc2-concepts |
def CreateFile(fileName):
"""
Create an empty file as per passed path and name
"""
try:
f = open(fileName, "w+")
f.close()
return 0, None
except Exception as e:
return -1, e | bigcode/self-oss-instruct-sc2-concepts |
def DictionaryLower(dictionaryForward: dict):
"""
Function to convert dictionaries with string entries to upper case.
Args:
dictionaryForward: Simple 1-dimensional dictionaries.
Returns: dictionary forward in lower case key/values.
"""
return dict((str(k).lower(), v.lower()) for k, v i... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def flatten(x):
"""
Flatten list of lists
"""
flatted_list = list(itertools.chain(*x))
return flatted_list | bigcode/self-oss-instruct-sc2-concepts |
def divideList(x, k):
"""
Divide list @x into roughly @k parts.
"""
if k > len(x): return [[elem] for elem in x]
part_len = int(len(x) / k)
parts = []
start = 0
while start < len(x):
parts.append(x[start: start + part_len])
start += part_len
return parts | bigcode/self-oss-instruct-sc2-concepts |
import time
def epoch(value):
"""
Convert datetime to unix epoch time.
Alternatively you can you this {{ my_date|date:"U" }}
:param value: datetime instance
:return: int
"""
try:
return int(time.mktime(value.timetuple()) * 1000)
except AttributeError:
return '' | bigcode/self-oss-instruct-sc2-concepts |
def to_byte(byte):
"""Make sure an object really represents an integer from 0 to 255,
and return the integer.
"""
byte = float(byte)
assert byte.is_integer(), f"Got a non-integer byte: {byte}!"
byte = int(byte)
assert byte >= 0, f"Got a negative value for a byte: {byte}!"
assert byte <=... | bigcode/self-oss-instruct-sc2-concepts |
def ifelse (pred:bool, cons, alt):
"""
If predicate consequent else alternative
"""
if pred:
return cons
else:
return alt | bigcode/self-oss-instruct-sc2-concepts |
def parse_config(path):
"""
This method parses a config file and constructs a list of blocks.
Each block is a singular unit in the architecture as explained in
the paper. Blocks are represented as a dictionary in the list.
Input:
- path: path to the config file.
Returns:
- a list co... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_arches_from_config_in(fname):
"""Given a path to an arch/Config.in.* file, parse it to get the list
of BR2_ARCH values for this architecture."""
arches = set()
with open(fname, "r") as f:
parsing_arches = False
for line in f:
line = line.strip()
... | bigcode/self-oss-instruct-sc2-concepts |
def test_module(client):
"""
Test connection to Azure by calling the list incidents API with limit=1
"""
client.http_request('GET', 'incidents', params={'$top': 1})
return 'ok' | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
from typing import Sequence
from typing import Union
from typing import List
import itertools
def hyper_grid(
grid_dict: Mapping[str, Sequence[Union[str, int, float]]]
) -> List[Mapping[str, Union[str, int, float]]]:
"""Converts a param-keyed dict of lists to a list of mapping.
Arg... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_qs(dct):
"""
Takes a dictionary and uses it to create a query string.
"""
itms = ["%s=%s" % (key, val) for key, val in list(dct.items())
if val is not None]
return "&".join(itms) | bigcode/self-oss-instruct-sc2-concepts |
def factorial(n):
"""Factorial function. This will be used in the power series"""
if n==1:
return 1
return n * factorial(n-1) | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.