content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def build_goods_query(
good_ids: List[str], currency_id: str, is_searching_for_sellers: bool
) -> Query:
"""
Build buyer or seller search query.
Specifically, build the search query
- to look for sellers if the agent is a buyer, or
- to look for buyers if the agent is a seller.
In ... | 5,349,100 |
def make_piecewise_const(num_segments):
"""Makes a piecewise constant semi-sinusoid curve with num_segments segments."""
true_values = np.sin(np.arange(0, np.pi, step=0.001))
seg_idx = np.arange(true_values.shape[0]) // (true_values.shape[0] / num_segments)
return pd.Series(true_values).groupby(seg_idx)... | 5,349,101 |
def save_default_model(model, L):
"""Saving information associated with the exact diagonalization via
symmetry for the model model with the given model_params.
"""
H, model_params, symmetries = base.gen_model(model, L=L)
assert os.path.isfile(projfile(L, S=1/2, **symmetries)),\
"Could not f... | 5,349,102 |
def convert_rational_from_float(number):
"""
converts a float to rational as form of a tuple.
"""
f = Fraction(str(number)) # str act as a round
return f.numerator, f.denominator | 5,349,103 |
def classname(obj):
"""Returns the name of an objects class"""
return obj.__class__.__name__ | 5,349,104 |
def train(epoch, model, dataloader, optimizer, criterion, device, writer, cfg):
"""
training the model.
Args:
epoch (int): number of training steps.
model (class): model of training.
dataloader (dict): dict of dataset iterator. Keys are tasknames, values are correspon... | 5,349,105 |
async def test_trigger_with_pending_and_delay(opp, mqtt_mock):
"""Test trigger method and switch from pending to triggered."""
assert await async_setup_component(
opp,
alarm_control_panel.DOMAIN,
{
"alarm_control_panel": {
"platform": "manual_mqtt",
... | 5,349,106 |
def custom_timeseries_widget_for_behavior(node, **kwargs):
"""Use a custom TimeSeries widget for behavior data"""
if node.name == 'Velocity':
return SeparateTracesPlotlyWidget(node)
else:
return show_timeseries(node) | 5,349,107 |
def db_tween_factory(handler, registry):
"""A database tween, doing automatic session management."""
def db_tween(request):
response = None
try:
response = handler(request)
finally:
session = getattr(request, "_db_session", None)
if session is not Non... | 5,349,108 |
def calibrate_profiler(n, timer=time.time):
"""
Calibration routine to returns the fudge factor. The fudge factor
is the amount of time it takes to call and return from the
profiler handler. The profiler can't measure this time, so it
will be attributed to the user code unless it's subtracted off.... | 5,349,109 |
def getbias(x, bias):
"""Bias in Ken Perlin’s bias and gain functions."""
return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6) | 5,349,110 |
def modify_vm(hostname: str, vm_id: str, memory: int, cpu: int):
""" set memory and core count (cpu) of the given vm to the given values """
# TODO implement
pass | 5,349,111 |
def get_exif_flash_fired(exif_data: Dict) -> Optional[bool]:
"""
Parses the "flash" value from exif do determine if it was fired.
Possible values:
+-------------------------------------------------------+------+----------+-------+
| Status | Hex | Bi... | 5,349,112 |
def gyp_generator_flags():
"""Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary."""
return dict(arg.split('=', 1)
for arg in shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', ''))) | 5,349,113 |
def get_geoJson(addr):
"""
Queries the Google Maps API for specified address, returns
a dict of the formatted address, the state/territory name, and
a float-ified version of the latitude and longitude.
"""
res = requests.get(queryurl.format(addr=addr, gmapkey=gmapkey))
dictr = {}
if res.... | 5,349,114 |
def genomic_del6_abs_cnv(params, genomic_del6_seq_loc):
"""Create genomic del6 absolute cnv"""
_id = "ga4gh:VAC.6RkHgDOiRMZKMKgI6rmG9C3T6WuMhcex"
params["variation"] = {
"type": "AbsoluteCopyNumber",
"_id": _id,
"subject": genomic_del6_seq_loc,
"copies": {"type": "Number", "v... | 5,349,115 |
def check_bcc(msg: Match[bytes]):
"""Check that BCC from the response message is correct."""
calc_bcc = calculate_bcc(msg[0][1:-1])
if calc_bcc != msg["bcc"]:
raise WrongBCC(f"BCC must be {calc_bcc}, but received {msg['bcc']}") | 5,349,116 |
def display_data_in_new_tab(message, args, pipeline_data):
""" Displays the current message data in a new tab """
window = sublime.active_window()
tab = window.new_file()
tab.set_scratch(True)
edit_token = message['edit_token']
tab.insert(edit_token, 0, message['data'])
return tab | 5,349,117 |
def update_user_pool(UserPoolId=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, VerificationMessageTemplate=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfigura... | 5,349,118 |
def _cost( q,p, xt_measure, connec, params ) :
"""
Returns a total cost, sum of a small regularization term and the data attachment.
.. math ::
C(q_0, p_0) = .01 * H(q0,p0) + 1 * A(q_1, x_t)
Needless to say, the weights can be tuned according to the signal-to-noise ratio.
"""
s,r = params ... | 5,349,119 |
def get_full_lang_code(lang=None):
""" Get the full language code
Args:
lang (str, optional): A BCP-47 language code, or None for default
Returns:
str: A full language code, such as "en-us" or "de-de"
"""
if not lang:
lang = __active_lang
return lang or "en-us" | 5,349,120 |
def load_keras_model():
"""Load in the pre-trained model"""
global model
model = load_model('../models/train-embeddings-rnn-2-layers.h5')
# Required for model to work
#global graph
#graph = tf.compat.v1.get_default_graph()
#graph = tf.get_default_graph() | 5,349,121 |
async def handle_api_exception(request) -> User:
"""
API Description: Handle APIException. This will show in the swagger page (localhost:8000/api/v1/).
"""
raise APIException("Something bad happened", code=404) | 5,349,122 |
def acquire_images(cam, nodemap, nodemap_tldevice):
"""
This function acquires and saves 10 images from a device.
:param cam: Camera to acquire images from.
:param nodemap: Device nodemap.
:param nodemap_tldevice: Transport layer device nodemap.
:type cam: CameraPtr
:type nodemap: INodeMap
... | 5,349,123 |
def apply_operations(source: dict, graph: BaseGraph) -> BaseGraph:
"""
Apply operations as defined in the YAML.
Parameters
----------
source: dict
The source from the YAML
graph: kgx.graph.base_graph.BaseGraph
The graph corresponding to the source
Returns
-------
kg... | 5,349,124 |
def plotter(model, X, Y, ax, npts=5000):
"""
Simple way to get a visualization of the decision boundary
by applying the model to randomly-chosen points
could alternately use sklearn's "decision_function"
at some point it made sense to bring pandas into this
"""
xs = []
ys = []
cs = ... | 5,349,125 |
def skillLvl(ign, key):
"""Get the skill lvl of the player"""
data = requests.get(f'https://hypixel-api.senither.com/v1/profiles/{uuid(ign)}/weight/?key={key}').json()
skill_types = ['mining', 'foraging', 'enchanting', 'farming', 'combat', 'fishing', 'alchemy', 'taming']
skills_lvl = []
for i in ski... | 5,349,126 |
def tt_logdotexp(A, b):
"""Construct a Theano graph for a numerically stable log-scale dot product.
The result is more or less equivalent to `tt.log(tt.exp(A).dot(tt.exp(b)))`
"""
A_bcast = A.dimshuffle(list(range(A.ndim)) + ["x"])
sqz = False
shape_b = ["x"] + list(range(b.ndim))
if len(... | 5,349,127 |
def test_get_fallback_executable(mock_os_path_exists):
"""Find vmrun in PATH."""
mock_os_path_exists.return_value = True
with patch.dict('os.environ', {'PATH': '/tmp:/tmp2'}):
got = mech.utils.get_fallback_executable()
expected = '/tmp/vmrun'
assert got == expected
mock_os_path_exists.as... | 5,349,128 |
def _check_like(val, _np_types, _native_types, check_str=None): # pylint: disable=too-many-return-statements
"""
Checks the follwing:
- if val is instance of _np_types or _native_types
- if val is a list or ndarray of _np_types or _native_types
- if val is a string or list of strings that can... | 5,349,129 |
def rotation_matrix(x, y, theta):
""" Calculate the rotation matrix. Origin is assumed to be (0, 0)
theta must be in radians
"""
return [np.cos(theta) * x - np.sin(theta) * y, np.sin(theta) * x + np.cos(theta) * y] | 5,349,130 |
def create_players(num_human: int, num_random: int, smart_players: List[int]) \
-> List[Player]:
"""Return a new list of Player objects.
<num_human> is the number of human player, <num_random> is the number of
random players, and <smart_players> is a list of difficulty levels for each
Sma... | 5,349,131 |
def file_info(path):
"""
Return file information on `path`. Example output:
{
'filename': 'passwd',
'dir': '/etc/',
'path': '/etc/passwd',
'type': 'file',
'size': 2790,
'mode': 33188,
'uid': 0,
'gid': 0,
... | 5,349,132 |
def test_beam_focusing( show=False ):
"""
Runs the simulation of a focusing charged beam, in a boosted-frame,
with and without the injection through a plane.
The value of the RMS radius at focus is automatically checked.
"""
# Simulate beam focusing with injection through plane or not
simula... | 5,349,133 |
def extract_test_params(root):
"""VFT parameters, e.g. TEST_PATTERN, TEST_STRATEGY, ..."""
res = {}
'''
xpath = STATIC_TEST + '*'
elems = root.findall(xpath) + root.findall(xpath+'/FIXATION_CHECK*')
#return {e.tag:int(e.text) for e in elems if e.text.isdigit()}
print(xpath)
for e i... | 5,349,134 |
def csc_list(
city: str,
state: Optional[str] = None,
country: Optional[str] = None,
) -> List[db.Geoname]:
"""
>>> [g.country_code for g in csc_list('sydney')]
['AU', 'CA', 'US', 'US', 'ZA', 'VU', 'US', 'US', 'CA']
>>> [g.name for g in csc_list('sydney', country='australia')]
['Sydney']... | 5,349,135 |
def calculate_frame_score(current_frame_hsv: Iterable[cupy.ndarray],
last_frame_hsv: Iterable[cupy.ndarray]) -> Tuple[float]:
"""Calculates score between two adjacent frames in the HSV colourspace. Frames should be
split, e.g. cv2.split(cv2.cvtColor(frame_data, cv2.COLOR_BGR2HSV)).
... | 5,349,136 |
def test_md024_good_different_heading_content_setext():
"""
Test to make sure this rule does not trigger with a document that
contains SetExt headings with no duplicate content.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/rules/md... | 5,349,137 |
def huber_loss_function(sq_resi, k=1.345):
"""Robust loss function which penalises outliers, as detailed in Jankowski et al (2018).
Parameters
----------
sq_resi : `float` or `list`
A single or list of the squared residuals.
k : `float`, optional
A constant that defines at which dis... | 5,349,138 |
def clean_sentence(sentence: str) -> str:
"""
Bertに入れる前にtextに行う前処理
Args:
sentence (str): [description]
Returns:
str: [description]
"""
sentence = re.sub(r"<[^>]*?>", "", sentence) # タグ除外
sentence = mojimoji.zen_to_han(sentence, kana=False)
sentence = neologdn.normalize... | 5,349,139 |
def test_survive_after_linting():
"""Test that it handles vital.vim, without crashing."""
cmd = [sys.executable, "-m", "vint", vital_dir]
try:
output = subprocess.check_output(
cmd, stderr=subprocess.STDOUT, universal_newlines=True
)
except subprocess.CalledProcessError as er... | 5,349,140 |
def assert_user(user_id: int, permission: Union[str, Enum] = None) -> bool:
"""
Assert that a user_id belongs to the requesting user, or that
the requesting user has a given permission.
"""
permission = (
permission.value if isinstance(permission, Enum) else permission
)
return flask... | 5,349,141 |
def single_prob(n, n0, psi, c=2):
"""
Eq. 1.3 in Conlisk et al. (2007), note that this implmentation is
only correct when the variable c = 2
Note: if psi = .5 this is the special HEAP case in which the
function no longer depends on n.
c = number of cells
"""
a = (1 - psi) / psi
F = (... | 5,349,142 |
def getbyid(ctx,
# Mandatory main parameter
accountid):
"""GetAccountByID enables you to return details about a specific account, given its accountID."""
cli_utils.establish_connection(ctx)
ctx.logger.info(""": """"""accountid = """ + str(accountid)+""";"""+"")
... | 5,349,143 |
def array_pair_sum_iterative(arr, k):
"""
returns the array of pairs using an iterative method.
complexity: O(n^2)
"""
result = []
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == k:
result.append([arr[i], arr[j]])
return... | 5,349,144 |
def save_checkpoint(state, is_best, exp_name):
"""
save the checkpoint during training stage
:param state: content to be saved
:param is_best: if DPGN model's performance is the best at current step
:param exp_name: experiment name
:return: None
"""
torch.save(state, os.path.join('{}'.fo... | 5,349,145 |
def ComparativePlotting(t_df, p_df_dic):
"""
Plotting result comparisons.
"""
dims = {'s': 'start', 'd': 'duration',
'wt': 'waitTime', 'it': 'initTime', 'l': 'latency'}
t_df['execution'] = t_df['duration'] - t_df['initTime']
t_df['start'] = t_df['start']/1000.0
t_df['latency'] =... | 5,349,146 |
def cli(summary_sheet, output, village_id_map):
"""Reformat and combine collection spreadsheets into a single standardized file."""
village_id_map = get_village_id_map(village_id_map)
df_all = []
# load all xls files into a list of dataframes
for f in summary_sheet:
df_all.extend(load_xl... | 5,349,147 |
def merge_named_payload(name_to_merge_op):
"""Merging dictionary payload by key.
name_to_merge_op is a dict mapping from field names to merge_ops.
Example:
If name_to_merge_op is
{
'f1': mergeop1,
'f2': mergeop2,
'f3': mergeop3
},
Then t... | 5,349,148 |
def PrintResultsDuplicationsDistances(outfile,
categories,
histogram_data,
options):
"""write histograms of duplication distances."""
###################################
# construct and write h... | 5,349,149 |
def euclidean_distance(this_set, other_set, bsf_dist):
"""Calculate the Euclidean distance between 2 1-D arrays.
If the distance is larger than bsf_dist, then we end the calculation and return the bsf_dist.
Args:
this_set: ndarray
The array
other_set: ndarray
The com... | 5,349,150 |
def run_cmd_simple(cmd: str,
variables: dict,
env=None,
args: List[str] = None,
libraries=None) -> Union[dict, str]:
"""
Run cmd with variables written in environment.
:param args: cmd arguments
:param cmd: to run
:param var... | 5,349,151 |
def host(provider: Provider) -> Host:
"""Create host"""
return provider.host_create(utils.random_string()) | 5,349,152 |
def loop_invariant_branching_while():
"""Ensure node is walked up to find a loop-invariant branch"""
x = [1, 2, 3, 4]
i = 6
j = 0
while j < 10_000:
j += 1
# Marks entire branch
if len(x) > 2:
print(x * i)
# Marks comparator, but not print
j = 0
while ... | 5,349,153 |
def deal_with_direct(header: HeaderModel, body: BodyModel, name, packet_record: PacketRecord,
auth: WorkspaceAuth):
"""
手动录入认证信息
:param header:
:param body:
:param name:
:param packet_record:
:param auth:
:return:
"""
logger.info("{} deal with dire... | 5,349,154 |
def launch(reactor,
progress_updates=None,
control_port=None,
data_directory=None,
socks_port=None,
stdout=None,
stderr=None,
timeout=None,
tor_binary=None,
user=None, # XXX like the config['User'] special-casing from be... | 5,349,155 |
def bj_struktur_p89(x, n: int = 5, **s): # brute force
"""_summary_
:param x: _description_
:type x: _type_
:param n: _description_, defaults to 5
:type n: int, optional
:return: _description_
:rtype: _type_
"""
gamma, K = gamma_K_function(**s)
b_j = np.empty((x.size, n + 1))
... | 5,349,156 |
def test_get_left():
"""Test left method."""
from heap import Heap
high_low = Heap()
high_low.push(data[0])
high_low.push(data[1])
high_low.push(data[2])
assert high_low.high_low[high_low.get_left(0)] == data[1] | 5,349,157 |
def _get_pulse_width_and_area(tr, ipick, icross, max_pulse_duration=.08):
"""
Measure the width & area of the arrival pulse on the displacement trace
Start from the displacement peak index (=icross - location of first zero
crossing of velocity)
:param tr: displacement trace
:type tr: ob... | 5,349,158 |
def testQuestionMarkURI():
"""An URI with a question mark"""
assert ["http://www.bdog.fi/cgi-bin/netstore/tuotehaku.pl?tuoteryhma=16"] == grab('http://www.bdog.fi/cgi-bin/netstore/tuotehaku.pl?tuoteryhma=16', needScheme) | 5,349,159 |
def extract_video(video_path, out_dir, name_length, ext='.jpg'):
"""
retrieve all frames of an video
:param video_path: path of video
:param out_dir: directory of output images
:param name_length: name length of video
:param ext: extension of image
:return: None
"""
if not os.path.ex... | 5,349,160 |
def explain(variable, name=""):
"""
Show a brief overview of a variable, including type, size and a sample.
:param variable: any variable
:param name: optional name of the variable used in the title
"""
print()
print(f"Explanation of variable {name}")
print("===================... | 5,349,161 |
def load_backend(name, options=None):
"""Load the named backend.
Returns the backend class registered for the name.
If you pass None as the name, this will load the default backend.
See the documenation for get_default() for more information.
Raises:
UnknownBackend: The name is not recogn... | 5,349,162 |
def recursive_reload(module, paths=None, mdict=None):
"""Recursively reload modules."""
if paths is None:
paths = ['']
if mdict is None:
mdict = {}
if module not in mdict:
# modules reloaded from this module
mdict[module] = []
reload(module)
for attribute_name in ... | 5,349,163 |
def test() -> ScadObject:
"""
Create something.
"""
result = IDUObject()
result += box(10, 10, 5, center=True).translated((0, 0, -1)).named("Translated big box")
result -= box(4, 4, 4, center=True)
result += box(10, 10, 5)
result *= sphere(7).translated((0, 0, 1))
return (
r... | 5,349,164 |
def save_exp_log(file_name, d_log):
"""
Utility to save the experiment log as json file
details: Save the experiment log (a dict d_log) in file_name
args: file_name (str) the file in which to save the log
d_log (dict) python dict holding experiment log
"""
with open(file_name, 'w') ... | 5,349,165 |
def rollout(policy, env_class, step_fn=default_rollout_step, max_steps=None):
"""Perform rollout using provided policy and env.
:param policy: policy to use when simulating these episodes.
:param env_class: class to instantiate an env object from.
:param step_fn: a function to be called at each step of... | 5,349,166 |
def test_exact_cover_trivial_single_set_single_element_problem(solver_factory):
"""
Consider the following example:
There is a single time labelled 0. So T = {0}.
There is a single event type labelled 0. So U = {0}.
We observe 1 event count for t=0 and u=0, so rhs vector b is:
b = [b_{t=0, u_... | 5,349,167 |
def get_source(location, **kwargs):
"""Factory for StubSource Instance.
Args:
location (str): PathLike object or valid URL
Returns:
obj: Either Local or Remote StubSource Instance
"""
try:
utils.ensure_existing_dir(location)
except NotADirectoryError:
return Re... | 5,349,168 |
def about(request):
"""
Prepare and displays the about view of the web application.
Args:
request: django HttpRequest class
Returns:
A django HttpResponse class
"""
template = loader.get_template('about.html')
return HttpResponse(template.render()) | 5,349,169 |
def url(parser, token):
"""Overwrites built in url tag to use . It works identicaly, except that where possible
it will use subdomains to refer to a project instead of a full url path.
For example, if the subdomain is vessel12.domain.com it will refer to a page
'details' as /details/ instead of /site/v... | 5,349,170 |
def _update_environ(dest, src):
"""Overwrite ``environ`` with any additions from the prepared environ.
Does not remove any variables from ``environ``.
"""
# updating os.environ can be a memory leak, so we only update
# those values that actually changed.
for key, value in src.items():
i... | 5,349,171 |
def getAp(ground_truth, predict, fullEval=False):
"""
Calculate AP at IOU=.50:.05:.95, AP at IOU=.50, AP at IOU=.75
:param ground_truth: {img_id1:{{'position': 4x2 array, 'is_matched': 0 or 1}, {...}, ...}, img_id2:{...}, ...}
:param predict: [{'position':4x2 array, 'img_id': image Id, 'confident'... | 5,349,172 |
def aumenta_fome(ani):
""" aumenta_fome: animal --> animal
Recebe um animal e devolve o mesmo com o valor da fome incrementado por 1
"""
if obter_freq_alimentacao(ani) == 0:
return ani
else:
ani['a'][0] += 1
return ani | 5,349,173 |
def match_inputs(
bp_tree,
table,
sample_metadata,
feature_metadata=None,
ignore_missing_samples=False,
filter_missing_features=False
):
"""Matches various input sources.
Also "splits up" the feature metadata, first by calling
taxonomy_utils.split_taxonomy() on it and then by splitt... | 5,349,174 |
def test_writing_csv_files():
"""Tests writing a csv file.
:raises:
:rtype:
"""
x = datetime.datetime.now()
headers = ["Header1", "Header2", "Header3"]
content = [["Column1", "Column2", "Column3"],
["Row2C1", "Row2C2", "Row2C3"],
["Row3C1", "Row3C2", "Row3C3"]... | 5,349,175 |
def im_adjust(img, tol=1, bit=8):
"""
Adjust contrast of the image
"""
limit = np.percentile(img, [tol, 100 - tol])
im_adjusted = im_bit_convert(img, bit=bit, norm=True, limit=limit.tolist())
return im_adjusted | 5,349,176 |
def FibanocciSphere(samples=1):
""" Return a Fibanocci sphere with N number of points on the surface.
This will act as the template for the nanoparticle core.
Args:
Placeholder
Returns:
Placeholder
Raises:
Placeholder
"""
points = []
phi = math.pi * (3. - ... | 5,349,177 |
def get_code():
"""
returns the code for the activity_selection function
"""
return inspect.getsource(activity_selection) | 5,349,178 |
def calc_luminosity(flux, fluxerr, mu):
""" Normalise flux light curves with distance modulus.
Parameters
----------
flux : array
List of floating point flux values.
fluxerr : array
List of floating point flux errors.
mu : float
Distance modulus from luminosity distance.... | 5,349,179 |
def app(testdir):
"""Provide instance for basic Flask app."""
app = flask.Flask(__name__)
app.config['TESTING'] = True
# This config value is required and must be supplied.
app.config['HASHFS_ROOT_FOLDER'] = str(testdir)
with app.app_context():
yield app | 5,349,180 |
def download_file(url: str, destination: str, timeout: Optional[int] = None,
silent: Optional[bool] = False) -> str:
"""
Downloads file by given URL to destination dir.
"""
file_name = get_file_name_from_url(url)
file_path = join(destination, file_name)
parsed_url: ParseResult ... | 5,349,181 |
def inference(images):
"""Build the CIFAR-10 model.
Args:
images: Images returned from distorted_inputs() or inputs().
Returns:
Logits.
"""
###
# We instantiate all variables using tf.get_variable() instead of
# tf.Variable() in order to share variables across multiple GPU training runs.
# If... | 5,349,182 |
def euler237_():
"""Solution for problem 237."""
pass | 5,349,183 |
def cluster_molecules(mols, cutoff=0.6):
"""
Cluster molecules by fingerprint distance using the Butina algorithm.
Parameters
----------
mols : list of rdkit.Chem.rdchem.Mol
List of molecules.
cutoff : float
Distance cutoff Butina clustering.
Returns
-------
pandas.... | 5,349,184 |
def exec_benchmarks_empty_inspection(code_to_benchmark, repeats):
"""
Benchmark some code without mlinspect and with mlinspect with varying numbers of inspections
"""
benchmark_results = {
"no mlinspect": timeit.repeat(stmt=code_to_benchmark.benchmark_exec, setup=code_to_benchmark.benchmark_setu... | 5,349,185 |
def detect_version():
"""
Try to detect the main package/module version by looking at:
module.__version__
otherwise, return 'dev'
"""
try:
m = __import__(package_name, fromlist=['__version__'])
return getattr(m, '__version__', 'dev')
except ImportError:
pass
... | 5,349,186 |
def model(p, x):
""" Evaluate the model given an X array """
return p[0] + p[1]*x + p[2]*x**2. + p[3]*x**3. | 5,349,187 |
def normalize(x:"tensor|np.ndarray") -> "tensor|np.ndarray":
"""Min-max normalization (0-1):
:param x:"tensor|np.ndarray":
:returns: Union[Tensor,np.ndarray] - Return same type as input but scaled between 0 - 1
"""
return (x - x.min())/(x.max()-x.min()) | 5,349,188 |
def test_valid_amendment_adddebtors():
"""Assert that the schema is performing as expected for a amendment to add debtors."""
statement = copy.deepcopy(AMENDMENT_STATEMENT)
del statement['baseDebtor']
del statement['removeTrustIndenture']
del statement['addTrustIndenture']
del statement['addSecu... | 5,349,189 |
def apply_on_multi_fasta(file, function, *args):
"""Apply a function on each sequence in a multiple FASTA file (DEPRECATED).
file - filename of a FASTA format file
function - the function you wish to invoke on each record
*args - any extra arguments you want passed to the function
This function... | 5,349,190 |
def update_contracts_esi(force_sync=False, user_pk=None) -> None:
"""start syncing contracts"""
_get_contract_handler().update_contracts_esi(force_sync, user=_get_user(user_pk)) | 5,349,191 |
def resize_bbox(box, image_size, resize_size):
"""
Args:
box: iterable (ints) of length 4 (x0, y0, x1, y1)
image_size: iterable (ints) of length 2 (width, height)
resize_size: iterable (ints) of length 2 (width, height)
Returns:
new_box: iterable (ints) of length 4 (x0, y0,... | 5,349,192 |
def plot_emoji_heatmap(df, size=(20, 5), agg='from', axs=None):
"""
Plot an emoji heatmap according to the specified column passed as agg parameter
Eg. if agg='From' this plots a heatmap according to the smileys/emojis used by a person
if agg= df.time.dt.hour will give a heatmap of emojis used at some t... | 5,349,193 |
def spin_polarize(inp, mpol=1):
"""
Add a collinear spin polarization to the system.
Arguments:
mpol (int): spin polarization in Bohr magneton units.
"""
__set__(inp, 'dft', 'nspin', 2)
__set__(inp, 'dft', 'mpol', mpol) | 5,349,194 |
def perf_counter_ms():
"""Returns a millisecond performance counter"""
return time.perf_counter() * 1_000 | 5,349,195 |
def print_feed(items_objects):
"""Printing the results from all urls"""
print("---------------------------")
print("Number of RSS posts: ", len(items_objects))
print("---------------------------")
for item_object in items_objects:
# Used html.unescape for the conversion of named and numeric ... | 5,349,196 |
def make_shutdown_packet( ):
"""Create a shutdown packet."""
packet = struct.pack( "<B", OP_SHUTDOWN );
return packet; | 5,349,197 |
def unique():
"""Return unique identification number."""
global uniqueLock
global counter
with uniqueLock:
counter = counter + 1
return counter | 5,349,198 |
def shortcut_download(dataset, compression_type='tar.gz'):
"""Download and unpack pre-processed dataset"""
if compression_type not in ['tar.gz', 'zip']:
print('Warning! Wrong compression format. Changing to tar.gz')
compression_type = 'tar.gz'
if dataset == 'reddit_casual' and compression_... | 5,349,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.