seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def indent_lines(block,
num_tabs=1, expand_tabs=True, tab_size=4,
skip_first_line=False):
"""Return `block` indented with additional tabs on each line.
Parameters
==========
block : string
Block to indent after newlines
num_tabs : integer
Number of ... | bigcode/self-oss-instruct-sc2-concepts |
def applier(f):
"""Returns a function that applies `f` to a collection of inputs (or just one).
Useful to use in conjuction with :func:`dlt.util.compose`
Args:
f (function): Function to be applied.
Returns:
callable: A function that applies 'f' to collections
... | bigcode/self-oss-instruct-sc2-concepts |
import math
import random
def split_data(ids, train_ratio=0.8, validation_ratio=0.1, test_ratio=0.1):
"""Split list of sample IDs randomly with a given ratio for the training, validation and test set."""
# Check validity of ratio arguments
if train_ratio + validation_ratio + test_ratio != 1.0:
ra... | bigcode/self-oss-instruct-sc2-concepts |
def getSpan(W):
"""Return the span of W
sp(W) = max W(s) - min W(s)
"""
return W.max() - W.min() | bigcode/self-oss-instruct-sc2-concepts |
from io import StringIO
def run_command(control, cmd, ok_codes=None):
"""
Run a spack or git command and get output and error
"""
ok_codes = ok_codes or [0, 1]
res = StringIO()
err = StringIO()
control(*cmd, _out=res, _err=err, _ok_code=ok_codes)
return res.getvalue(), err.getvalue() | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_meta(meta, meta_file):
"""Extract __*meta*__ from `meta_file`."""
meta_match = re.search(r"^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]".format(meta=meta), meta_file, re.M)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=... | bigcode/self-oss-instruct-sc2-concepts |
def get_excluded_varaibles(all_features, excluded_features):
"""
Returns a list of feature names to be excluded from feature scaling
Parameters:
all_features: List of features returned from choose_featuers for clustering
excluded_features: List of features in all_features to be excluded from featur... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_coordinate(s):
"""Check if input is a coordinate."""
matches = re.search(
r'([+-]?([0-9]{1,2}):([0-9]{2})(:[0-9]{2})?\.?([0-9]+)?)', s)
return False if matches is None else True | bigcode/self-oss-instruct-sc2-concepts |
import re
def binary_conversion(txt):
"""Convert binary txt to ascii string."""
if len(txt) % 8 > 0:
raise ValueError(f"txt length is not base 8. The value of txt: {txt}")
ascii_message = "".join([chr(int(byte, 2))
for byte in re.findall(r"\d{8}", txt)]
... | bigcode/self-oss-instruct-sc2-concepts |
def HermiteP(n, x):
"""
Hermite polynomial of rank n Hn(x)
Parameters
----------
n: order of the LG beam
x: matrix of x
Returns
-------
Hermite polynomial
"""
if n == 0:
return 1
elif n == 1:
return 2 * x
else:
return 2 * x * HermiteP(n - 1, ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix + 1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + ... | bigcode/self-oss-instruct-sc2-concepts |
def format_go_time(dt):
"""Format datetime in Go's time.RFC3339Nano format which looks like
2018-10-04T15:08:53.229364634+03:00
If dt tzinfo is None, UTC will be used
"""
prefix = dt.strftime('%Y-%m-%dT%H:%M:%S')
nsec = dt.microsecond * 1000
tz = dt.strftime('%z') or '+0000'
return '{}.... | bigcode/self-oss-instruct-sc2-concepts |
def GeBuildConfigAllBoards(ge_build_config):
"""Extract a list of board names from the GE Build Config.
Args:
ge_build_config: Dictionary containing the decoded GE configuration file.
Returns:
A list of board names as strings.
"""
return [b['name'] for b in ge_build_config['boards']] | bigcode/self-oss-instruct-sc2-concepts |
def round_to_nearest(x):
"""Python 3 style round: round a float x to the nearest int, but
unlike the builtin Python 2.x round function:
- return an int, not a float
- do round-half-to-even, not round-half-away-from-zero.
We assume that x is finite and nonnegative; except wrong results
if ... | bigcode/self-oss-instruct-sc2-concepts |
import crypt
def check_hash(p,s,sha):
"""
Checking the password with given sha with crypt
"""
c_pass = crypt.crypt(p,s)
if c_pass == sha:
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def count_increases_in_window(numbers, window_length=3):
"""Count number of times sum of the window with window_length increases."""
increases = 0
for index, _ in enumerate(numbers[:-window_length]):
prev_window = sum(numbers[index:index + window_length])
cur_window = sum(numbers[index + 1:i... | bigcode/self-oss-instruct-sc2-concepts |
def _compare_ch_names(names1, names2, bads):
"""Return channel names of common and good channels."""
ch_names = [ch for ch in names1 if ch not in bads and ch in names2]
return ch_names | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha256(hashable) -> str:
"""Use instead of the builtin hash() for repeatable values."""
if isinstance(hashable, str):
hashable = hashable.encode("utf-8")
return hashlib.sha256(hashable).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def put_whitespace(in_str):
"""
Replace periods (.), underscores (_) and hyphens (-) in `in_str` with spaces
"""
return in_str.replace(".", " ").replace("-", " ").replace("_", " ") | bigcode/self-oss-instruct-sc2-concepts |
def split_instr(instr):
"""
Given an instruction of the form "name arg1, arg2, ...",
returns the pair ("name", "arg1, arg2, ...").
If the instruction has no arguments, the second element of
the pair is the empty string.
"""
result = instr.split(None, 1)
if len(result) == 1:
return result[0], ""
e... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def update_var(old_mean, old_var, old_count, new_mean, new_var, new_count):
"""Update mean and variance statistics based on a new batch of data.
Parameters
----------
old_mean : array_like
old_var : array_like
old_count : int
new_mean : array_like
new_var : array_like
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_checkpoint(resume_path):
"""
Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed
"""
checkpoint = torch.load(resume_path)
epoch = checkpoint['epoch']
mnt_best = checkpoint['monitor_best']
# load architecture params from checkpoint.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_fields_from_fieldsets(fieldsets):
"""Get a list of all fields included in a fieldsets definition."""
fields = []
try:
for name, options in fieldsets:
fields.extend(options['fields'])
except (TypeError, KeyError):
raise ValueError('"fieldsets" must be an iterable of tw... | bigcode/self-oss-instruct-sc2-concepts |
from typing import IO
from typing import Any
from typing import Optional
import struct
def read_bytes_as_value(f: IO[Any], fmt: str, nodata: Optional[Any] = None) -> Any:
"""Read bytes using a `struct` format string and return the unpacked data value.
Parameters
----------
f : IO[Any]
The IO ... | bigcode/self-oss-instruct-sc2-concepts |
def readable_timedelta(days):
""" Display days in a human readable way
original function by Syed Marwan Jamal
Arguments:
- days : (int) amount of day to translate
Returns:
- : (str) human readable string with date
"""
number_of_weeks = days // 7
number_of_days = days % ... | bigcode/self-oss-instruct-sc2-concepts |
def read_metadata(metadata_file):
"""
Function that returns a dictionary object from a KEY=VALUE lines file.
:param metadata_file: Filename with the KEY=VALUE pairs
:return: Dictionary object with key and value pairs
"""
if not metadata_file:
return {}
with open(metadata_file) as f:... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def openDb(database_filepath):
"""Return opened database connection."""
database_connection = sqlite3.connect(database_filepath)
database_connection.row_factory = sqlite3.Row
return database_connection | bigcode/self-oss-instruct-sc2-concepts |
def select_nodeids(xmrs, iv=None, label=None, pred=None):
"""
Return the list of all nodeids whose respective [EP] has the
matching *iv* (intrinsic variable), *label*, or *pred* values. If
none match, return an empty list.
"""
def datamatch(nid):
ep = xmrs.ep(nid)
return ((iv is ... | bigcode/self-oss-instruct-sc2-concepts |
def get_console_logging_level(verbose, quiet):
"""
Returns the logging level for the console based on the verbose and quiet
flags.
Logging levels can be found here:
https://docs.python.org/2/library/logging.html#logging-levels
logging.WARNING is 30 and the default console logging level. Each v... | bigcode/self-oss-instruct-sc2-concepts |
def validate_scale_count(value, _):
"""Validate the `scale_count` input."""
if value is not None and value < 3:
return 'need at least 3 scaling factors.' | bigcode/self-oss-instruct-sc2-concepts |
import math
def _geometric_mean(nums) -> float:
"""Return geometric mean of nums : n-root(a1 * a2 * ... * an)"""
exponent = 1 / len(nums)
product = math.prod(nums)
return product ** exponent | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def life(before):
"""
Takes as input a state of Conway's Game of Life, represented as an iterable
of ``(int, int)`` pairs giving the coordinates of living cells, and returns
a `set` of ``(int, int)`` pairs representing the next state
"""
before = set(before)
neig... | bigcode/self-oss-instruct-sc2-concepts |
import re
import click
def click_validate_reposlug(ctx, param, value):
"""Validate reposlugs (Click callback)
:param ctx: Click context
:type ctx: class:`click.Context`
:param param: Click params
:type param: dict
:param value: reposlugs to validate
:type value: tuple
:return: val... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def linspace(start, end, num) -> List[int]:
"""Linear spaced points within a division. Like numpy.linspace"""
delta = (end - start) / (num - 1)
return [int(start + i*delta) for i in range(num)] | bigcode/self-oss-instruct-sc2-concepts |
def convert_data(datain):
"""converts the output of the ADC into a voltage
Arguments
----------
datain : list
A list of bytes (the raw output of the adc)
Returns
-------
float
a float indicating a voltage between 2.5v and -2.5v - This will
not be adjusted for PGA ga... | bigcode/self-oss-instruct-sc2-concepts |
def calc_acc(ta, precip, tacc=274.16, **config):
"""
calculate accumulation when precip is below threshold
:param ta: grid of current temperature (K)
:param precip: grid of current precipitation (mm)
:param tacc: temperature threshold for accumlation (K)
:return: acc: grid of accumulation in cu... | bigcode/self-oss-instruct-sc2-concepts |
def scroll_with_mousewheel(widget, target=None, modifier='Shift', apply_to_children=False):
"""scroll a widget with mouse wheel
Args:
widget: tkinter widget
target: scrollable tkinter widget, in case you need "widget" to catch mousewheel event and make another widget
to scroll, ... | bigcode/self-oss-instruct-sc2-concepts |
def compute_etan(sch1, sch2, cos2phi, sin2phi):
"""Compute tangential ellipticity."""
return - (sch1 * cos2phi + sch2 * sin2phi) | bigcode/self-oss-instruct-sc2-concepts |
def prepare_project(project_manager, project_name="working_project"):
"""
* load working project if the project is exist.
* create working project if the project is not exist.
Parameters
----------
project_manager : ProjectManager
a ProjectManager instance
project_name : str
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_dollars(x):
"""
Used to clean up dollar fields of $ and commas
"""
if type(x) != float:
return x.replace('$','').replace(',','').replace('city','') | bigcode/self-oss-instruct-sc2-concepts |
def decode_parent(parent):
"""
Function used to decode encoded parent vector into a value for function eval.
Parameters
----------
parent : encoded parent vector
Returns
-------
evaluation of parent on f(x)
"""
sign = 1
if parent[0][0] < 0:
sign = -1
number... | bigcode/self-oss-instruct-sc2-concepts |
import math
def michalewicz(ind, m=10.):
"""Michalewicz function defined as:
$$ f(x) = - \sum_{i=1}^{n} \sin(x_i) \sin( \frac{i x_i^2}{\pi} )^(2*m)$$
with a search domain of $0 < x_i < \pi, 1 \leq i \leq n$.
"""
return - sum(( math.sin(ind[i]) * (math.sin(((i+1.)*(ind[i] **2.))/math.pi))**(2.*m) f... | bigcode/self-oss-instruct-sc2-concepts |
def set_brackets(pathway):
"""
Function defines levels of all brackets in expression. The output will be used by function <check_brackets>
Example 1:
expression: A B (C,D)
levels: -1,-1,-1,-1,0,-1,-1,-1,0
Example 2:
expression: (A B (C,D))
levels: 0,-1,-1,-1,-1,1,-1,-1,... | bigcode/self-oss-instruct-sc2-concepts |
def shared_branch_length_to_root(t, envs):
"""Returns the shared branch length for a single env from tips to root
t: phylogenetic tree relating sequences
envs: dict of {sequence:{env:count}} showing environmental abundance
Returns {env:shared_branch_length}
"""
working_t = t.copy()
res... | bigcode/self-oss-instruct-sc2-concepts |
def read_dist(file):
"""Read in a distribution
# Distribution of StackScore values at Harvard, 2015-06-24
#
#record_count stackscore fraction_of_records
13560805 1 0.98078307
76281 2 0.00551701
48500 3 0.00350775
24538 4 0.00177471
...... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_path(obj):
"""Convert a str into a fully resolved & expanded Path object.
Args:
obj (:obj:`str` or :obj:`pathlib.Path`): obj to convert into
expanded and resolved absolute Path obj
Returns:
:obj:`pathlib.Path`: resolved path
"""
return pathlib.P... | bigcode/self-oss-instruct-sc2-concepts |
def is_unique(var_values):
"""
Checks whether a variable has one unique value.
"""
return len(var_values.unique()) == 1 | bigcode/self-oss-instruct-sc2-concepts |
def tailcuts_clean(geom, image, pedvars, picture_thresh=4.25,
boundary_thresh=2.25):
"""Clean an image by selection pixels that pass a two-threshold
tail-cuts procedure. The picture and boundary thresholds are
defined with respect to the pedestal dispersion. All pixels that
have a si... | bigcode/self-oss-instruct-sc2-concepts |
def get_opatch_version(module, msg, oracle_home):
"""
Returns the Opatch version
"""
command = '%s/OPatch/opatch version' % oracle_home
(rc, stdout, stderr) = module.run_command(command)
if rc != 0:
msg = 'Error - STDOUT: %s, STDERR: %s, COMMAND: %s' % (stdout, stderr, command)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
from typing import List
def split_on_dot(line: Union[str, Path], only_last_dot: bool = False) -> List[str]:
"""
Split a string on the dot character (.).
Args:
line: The line ot split on.
only_last_dot: Only split on the last occurrence of ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def readJSON(filepath):
"""
Imports the content of the json file at the given filepath.
Parameters
----------
filepath : str
Path to the json file which will be read.
Returns
----------
The content of the json file as a dictionary.
"""
with open(filep... | bigcode/self-oss-instruct-sc2-concepts |
def strip_keys(key_list):
""" Given a list of keys, remove the prefix and remove just
the data we care about.
for example:
['defender:blocked:ip:ken', 'defender:blocked:ip:joffrey']
would result in:
['ken', 'joffrey']
"""
return [key.split(":")[-1] for key in key_list] | bigcode/self-oss-instruct-sc2-concepts |
import functools
def partial(f, *args, **kwargs):
"""
Create partial while preserving __name__ and __doc__.
:param f: function
:type f: callable
:param args: arguments
:type args: dict
:param kwargs: keyword arguments
:type kwargs: dict
:return: partial
:rtype: callable
""... | bigcode/self-oss-instruct-sc2-concepts |
import json
def encode_recommendation(rec, dims):
"""This function encodes a representation and associated list of dimensions
into a JSON dictionary. This dictionary contains keys giving the name of
the associated hyperparameter and the suggested value of that dimension of
the hyperparameter set.
... | bigcode/self-oss-instruct-sc2-concepts |
def _translate_int(exp, length):
""" Given an integer index, return a 3-tuple
(start, count, step)
for hyperslab selection
"""
if exp < 0:
exp = length+exp
if not 0<=exp<length:
raise ValueError("Index (%s) out of range (0-%s)" % (exp, length-1))
return exp, 1, 1 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Dict
def _format_peak_comment(mz: Union[int, float], peak_comments: Dict):
"""Format peak comment for given mz to return the quoted comment or empty string if no peak comment is present."""
if peak_comments is None:
return ""
peak_comment = peak_comments... | bigcode/self-oss-instruct-sc2-concepts |
def get_force_datakeeper(self, symbol_list, is_multi=False):
"""
Generate DataKeepers to store by default results from force module
Parameters
----------
self: VarLoad
A VarLoad object
symbol_list : list
List of the existing datakeeper (to avoid duplicate)
is_multi : bool
... | bigcode/self-oss-instruct-sc2-concepts |
def isNorm(s):
"""
Check whether a given value is a normalized Jacques-ID string.
The given value must be a string of exactly eight characters, and each
of those characters must be a non-padding base-64 digit with the only
non-alphanumeric symbols being + and /
Parameters:
s : str | mixed - the va... | bigcode/self-oss-instruct-sc2-concepts |
def decorate_init(init_decorator):
"""
Given a class definition and a decorator that acts on methods,
applies that decorator to the class' __init__ method.
Useful for decorating __init__ while still allowing __init__ to be
inherited.
"""
def class_decorator(cls):
cls.__init__ = init... | bigcode/self-oss-instruct-sc2-concepts |
def pad_data(data, pad_amount, pad_value=b"\x00", start_at=0):
""" Pad a piece of data according to the padding value and returns the
result. Use start_at to specify an offset at the starting point. """
end_position = len(data) + start_at
if end_position % pad_amount != 0:
pad_size = pad_amount ... | bigcode/self-oss-instruct-sc2-concepts |
def remove_2_digit_sector_ranges(fba_df):
"""
BLS publishes activity ranges of '31-33', 44-45', '48-49... drop these ranges.
The individual 2 digit naics are summed later.
:param fba_df: df, BLS QCEW in FBA format
:return: df, no sector ranges
"""
df = fba_df[~fba_df['ActivityProducedBy'].s... | bigcode/self-oss-instruct-sc2-concepts |
def extend_box(bbox, image_size, extend_ratio):
"""Zoom the input bbox
Args:
bbox: Input bbox
image_size: Input image original size
extend_ratio: Zoom ratio
Returns:
a box extand from input bbox
"""
x_x = (bbox[2] - bbox[0]) * extend_ratio
y_y = (bbox[3] - bbox[1]) * extend_ratio
... | bigcode/self-oss-instruct-sc2-concepts |
def rt_to_r(rt):
"""Convert RT matrix to R, removing T."""
result = []
for i in range(3):
for j in range(3):
result.append(rt[4 * i + j])
return result | bigcode/self-oss-instruct-sc2-concepts |
def _preprocess_transcript(phrase, use_phonemes, word_phoneme_dict):
"""
transform the input phrase. if use_phonemes is true, the words in phrase
are transformed into phoneme labels specified in word_phoneme_dict
Arguments:
phrase (list): list of words
use_phonemes (b... | bigcode/self-oss-instruct-sc2-concepts |
def upd_flag_g_smaller_g_min(flag, g, g_min):
"""
Update the flag to 'o' for small RDF.
Take a flag list, copy it, and set the flag to 'o'utside if g is smaller
g_min.
"""
flag_new = flag.copy()
for i, gg in enumerate(g):
if gg < g_min:
flag_new[i] = 'o'
return flag... | bigcode/self-oss-instruct-sc2-concepts |
def format_hex(num):
"""Format an integer as a hex number"""
return "0x%x" % num | bigcode/self-oss-instruct-sc2-concepts |
def threshold_pixel(image, center, x, y):
"""Calculate if Pixel(x, y) intensity is greater than center intensity of neighborhood.
:param image: Input image to pull from
:type: numpy.ndarray
:param center: Value of center pixel in 3x3 neighborhood
:type: int
... | bigcode/self-oss-instruct-sc2-concepts |
def readSeq(inputfile):
"""Reads the DNA sequence and returns as string. Removes all the special characters."""
# opne data
with open(inputfile, "r") as seqfile:
# read data
seq = seqfile.read()
# remove special characters \n and \t
seq = seq.replace("\n", "")
s... | bigcode/self-oss-instruct-sc2-concepts |
def textToBool(text):
"""
Converts a text to a boolean.
"""
true_values = ['True', 'true', 't', 'T', '1']
if text in true_values:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def mandatory_keys_check(list_mandatory, list_dict_keys):
"""
Check if the payload json file have the mandatory keys
:param list_mandatory: list
:param list_dict_keys: list
:return True or False
"""
check = all(item in list_dict_keys for item in list_mandatory)
return check | bigcode/self-oss-instruct-sc2-concepts |
def calculate_test_code_to_production_code_ratio(production_code_metrics, test_code_metrics):
"""Calculate the ratio between the test code and the production code."""
lines_of_code = production_code_metrics["SUM"]["code"]
lines_of_test_code = test_code_metrics["SUM"]["code"]
return float(lines_of_test... | bigcode/self-oss-instruct-sc2-concepts |
def otherPicks(df, ct):
""" Returns a list of the top ranked non-QB's currently available.
df : DataFrame - dataframe to parse for player data. Should only contain 1
position classification
ct : int - number of QB entries to return.
"""
df = df.iloc[1:]
if int(ct) > len(df):
entrie... | bigcode/self-oss-instruct-sc2-concepts |
import time
def retry(function, timeout=10, delay=.001, max_delay=1):
"""Call function until it returns a true value or timeout expires.
Double the delay for each retry up to max_delay.
Returns what function returns if true, None if timeout expires."""
deadline = time.time() + timeout
ret = None
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def verify_json(filename):
""" Checks that a JSON file is valid JSON """
try:
with open(filename) as jsonfile:
json.loads(jsonfile.read())
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def flatten(m, im_shape):
"""Flatten matrix in shape of (batches, channels, rows, cols)
to (batches, -1).
This function has no side effect, that is, it doesn't modify
argument "m" directly.
Arguments
---------
m : np.array
4D matrix in shape of (batches, channels, rows, cols).
... | bigcode/self-oss-instruct-sc2-concepts |
def _map_step_size(map_size: int, lod: int) -> int:
"""Return the step size in the tile grid for the given map.
Args:
map_size (int): The base map size in map units
lod (int): The LOD level for which to calculate step size
Returns:
int: The coordinate distance between two tiles in ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def fetch(filepath):
"""Fetch content of the given file into memory."""
with open(filepath, 'r') as infile:
return json.load(infile) | bigcode/self-oss-instruct-sc2-concepts |
def find_duplicate_schedule_items(all_items):
"""Find talks / pages assigned to mulitple schedule items"""
duplicates = []
seen_talks = {}
for item in all_items:
if item.talk and item.talk in seen_talks:
duplicates.append(item)
if seen_talks[item.talk] not in duplicates:
... | bigcode/self-oss-instruct-sc2-concepts |
import pkgutil
def avail_approaches(pkg):
"""Create list of available modules.
Parameters
----------
pkg : module
module to inspect
Returns
---------
method : list
A list of available submodules
"""
methods = [modname for importer, modname, ispkg in
... | bigcode/self-oss-instruct-sc2-concepts |
def user_info_query(user_id: str) -> dict:
"""
Build User information query.
:param user_id: User id
:return: Query
"""
return {
"id": 3,
"operationName": "ProfileGet",
"query": "query ProfileGet($user_id: ID!) {userprofile {get(user_id: $user_id) {... on UserProfile {id user {"
"id... | bigcode/self-oss-instruct-sc2-concepts |
def to_float(val):
"""Convert string to float, but also handles None and 'null'."""
if val is None:
return None
if str(val) == "null":
return None
return float(val) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def flatten(list_of_lists):
"""Flatten a list-of-lists into a single list."""
return list(itertools.chain.from_iterable(list_of_lists)) | bigcode/self-oss-instruct-sc2-concepts |
def train_batch(sess, model, batch_data):
"""
Given a Tensorflow session, train the provided model on a single batch.
Args:
sess: a Tensorflow session
model: an Attalos model
batch_data: a batch generated by model.to_batches
Returns:
Training loss for this batch.
""... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def iou(occ1, occ2, weights=None, average=True):
"""Compute the intersection over union (IoU) for two sets of occupancy
values.
Arguments:
----------
occ1: Tensor of size BxN containing the first set of occupancy values
occ2: Tensor of size BxN containing the first set of... | bigcode/self-oss-instruct-sc2-concepts |
def hasIntersectionCost(criterion, frRow, exRow):
"""Returns 1 if the two do not share an answer on the specified question, else 0"""
frQ = criterion['frQ']
exQ = criterion['exQ']
if 'singleFr' in criterion and criterion['singleFr']:
frSet = set([frRow[frQ]])
else:
frSet = set(frRow[... | bigcode/self-oss-instruct-sc2-concepts |
def unscale_coordinates(point, M):
"""
Unscale coordinates by M
:param point: Point
:param M: Scaling factor
:return: Unscaled points
"""
return point * M | bigcode/self-oss-instruct-sc2-concepts |
def update(pos, dims, orig_dims):
""" Finds neg number in dims and restores it to the value in
original-dims and subtracts one from the number after it
e.g (0 -1 0) (0 1 0)-> (0 1 -1) """
ret_dim = []
for i, dim in enumerate(dims):
if pos == i:
ret_dim.insert(i, orig_dims[i])
... | bigcode/self-oss-instruct-sc2-concepts |
def generate_booty_pts(criteria_left, criteria_top, item_width, item_height,
margin_width, margin_height):
"""
ScreenShot#booty_pts() が返すべき座標リストを生成する。
全戦利品画像が等間隔に並んでいることを仮定している。
criteria_left ... 左上にある戦利品の left 座標
criteria_top ... 左上にある戦利品の top 座標
item... | bigcode/self-oss-instruct-sc2-concepts |
def select_keys(records, keys):
"""Filter the records extracting only the selected fields.
Args:
records (list(dict)): the list of dicts to be filtered.
keys (list(str)): the keys to select from the records.
Returns:
list(dict): the list of records containing only the specified key... | bigcode/self-oss-instruct-sc2-concepts |
def has_merge_task(job):
""" Check if user has specified a mergeTask on the task factory
:param job_obj: The JSON job entity loaded from a template.:
:return: true if merge task present
"""
if job.task_factory.type in ['parametricSweep', 'taskPerFile'] and job.task_factory.merge_task:
return... | bigcode/self-oss-instruct-sc2-concepts |
def split_args_for_flags(args):
"""Returns `split_args, other_args` for `args`.
Split occurs using the last occurrence of `--` in `args`.
If `arg` does not contain `--` returns `args, []`.
"""
for i in range(len(args) - 1, -1, -1):
if args[i] == "--":
return args[i + 1 :], args... | bigcode/self-oss-instruct-sc2-concepts |
def packed_to_index(ix):
"""Convert 0-63 index to 0x88 index"""
return ix + (ix & ~7) | bigcode/self-oss-instruct-sc2-concepts |
import csv
def load_aitlas_format_dataset(file_path):
"""Reads the images from a CSV. Format: (image_path, class_name)"""
data = []
with open(file_path, "r") as f:
csv_reader = csv.reader(f)
for index, row in enumerate(csv_reader):
path = row[0]
item = (path, row[1... | bigcode/self-oss-instruct-sc2-concepts |
import math
def euclidian_distance(point1, point2):
"""
Returns the euclidian distance of the 2 given points.
:param point1: tuple (x, y)
:param point2: tuple (x, y)
:return: float
"""
return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) | bigcode/self-oss-instruct-sc2-concepts |
import base64
import hashlib
def stable_filename(value: str):
"""Generate a stable filename by Base32 encoding the sha256 of a string"""
return str(
base64.b32encode(hashlib.sha256(value.encode("utf-8")).digest()), "utf-8"
).replace("====", "") | bigcode/self-oss-instruct-sc2-concepts |
import csv # import a library
def parse_csv_file(filename):
"""
Read the contents of a .csv file and put them into a useful data structure:
ddict = {
"category1": { "location1": [entry1, entry2], "location2": [entry3] },
"category2": { "location1": []}
}
Parameters
---------... | bigcode/self-oss-instruct-sc2-concepts |
def MOSQ_MSB(A):
"""get most significant byte."""
return (( A & 0xFF00) >> 8) | bigcode/self-oss-instruct-sc2-concepts |
def is_payload_in_json(content_type):
"""
Verify the content_type.
If "Content-Type" is NOT specified pass the payload to the "json" argument - return True.
If "Content-Type" is specified:
- if the value is "application/json" pass the payload to the "json" argument - return True.
- if t... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def get_random_string(length):
""" Generates a random string of upper & lower case letters. """
letters = string.ascii_letters
rand_string = ''.join(random.choice(letters) for i in range(length))
return rand_string | bigcode/self-oss-instruct-sc2-concepts |
import requests
def fetch_json_package(url, host, referer, encoding):
"""
JSON抓包函数
:param url: AJAX API地址
:param host: 目标服务器
:param referer: header的引用页
:param encoding: 编码
:return: 字典格式的JSON数据包
"""
kv = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ... | 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.