uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ec45605c77996f7680e62f0f | train | function | def test_get_example(mock_client: TestClient):
"""Asserts ping endpoint returns pong"""
response = mock_client.get(f"{EXAMPLE_API_PREFIX}/")
assert response.status_code == HTTPStatus.OK.value
assert "Hello" in response.json()["msg"]
| def test_get_example(mock_client: TestClient):
| """Asserts ping endpoint returns pong"""
response = mock_client.get(f"{EXAMPLE_API_PREFIX}/")
assert response.status_code == HTTPStatus.OK.value
assert "Hello" in response.json()["msg"]
| import TestClient
from lambda_restapi.core.config import TEST_SERVER
if TEST_SERVER == "http://testserver":
EXAMPLE_API_PREFIX = "api/v1/example/"
else:
EXAMPLE_API_PREFIX = f"{TEST_SERVER}/api/v1/example"
def test_get_example(mock_client: TestClient):
| 64 | 64 | 55 | 10 | 54 | gbourniq/lambda-restapi | sam-application/lambda_restapi/api/endpoints/v1/tests/test_example.py | Python | test_get_example | test_get_example | 14 | 20 | 14 | 14 | 2c08ae3fae5894f8f923d33ee0323020e4aa944f | bigcode/the-stack | train |
dcc8c663009ddd7c175a698f | train | class | class WeightedCrossEntropyLoss(nn.Module):
"""
Transform input to fit the fomation of PyTorch offical cross entropy loss
with anchor-wise weighting.
"""
def __init__(self):
super(WeightedCrossEntropyLoss, self).__init__()
def forward(self, input: torch.Tensor, target: torch.Tensor, wei... | class WeightedCrossEntropyLoss(nn.Module):
| """
Transform input to fit the fomation of PyTorch offical cross entropy loss
with anchor-wise weighting.
"""
def __init__(self):
super(WeightedCrossEntropyLoss, self).__init__()
def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor):
"""
Ar... | , self.beta)
# anchor-wise weighting
if weights is not None:
assert weights.shape[0] == loss.shape[0] and weights.shape[1] == loss.shape[1]
loss = loss * weights.unsqueeze(-1)
return loss
class WeightedCrossEntropyLoss(nn.Module):
| 64 | 64 | 210 | 8 | 55 | halostorm/OpenPCDet | pcdet/utils/loss_utils.py | Python | WeightedCrossEntropyLoss | WeightedCrossEntropyLoss | 137 | 163 | 137 | 137 | d3451515544712c5d81f8438959e70b3fcb31f4c | bigcode/the-stack | train |
2d794e1f89fcb93c07cc8453 | train | class | class WeightedSmoothL1Loss(nn.Module):
"""
Code-wise Weighted Smooth L1 Loss modified based on fvcore.nn.smooth_l1_loss
https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/smooth_l1_loss.py
| 0.5 * x ** 2 / beta if abs(x) < beta
smoothl1(x) = |
| abs(x)... | class WeightedSmoothL1Loss(nn.Module):
| """
Code-wise Weighted Smooth L1 Loss modified based on fvcore.nn.smooth_l1_loss
https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/smooth_l1_loss.py
| 0.5 * x ** 2 / beta if abs(x) < beta
smoothl1(x) = |
| abs(x) - 0.5 * beta otherwise,
where x ... | (input)
alpha_weight = target * self.alpha + (1 - target) * (1 - self.alpha)
pt = target * (1.0 - pred_sigmoid) + (1.0 - target) * pred_sigmoid
focal_weight = alpha_weight * torch.pow(pt, self.gamma)
bce_loss = self.sigmoid_cross_entropy_with_logits(input, target)
loss = focal_... | 162 | 162 | 541 | 9 | 152 | halostorm/OpenPCDet | pcdet/utils/loss_utils.py | Python | WeightedSmoothL1Loss | WeightedSmoothL1Loss | 74 | 134 | 74 | 74 | f4c293dc9b4488085666a55219c8953c45b96394 | bigcode/the-stack | train |
5d0f5de5651dab5ffff3be0c | train | class | class SigmoidFocalClassificationLoss(nn.Module):
"""
Sigmoid focal cross entropy loss.
"""
def __init__(self, gamma: float = 2.0, alpha: float = 0.25):
"""
Args:
gamma: Weighting parameter to balance loss for hard and easy examples.
alpha: Weighting parameter to ... | class SigmoidFocalClassificationLoss(nn.Module):
| """
Sigmoid focal cross entropy loss.
"""
def __init__(self, gamma: float = 2.0, alpha: float = 0.25):
"""
Args:
gamma: Weighting parameter to balance loss for hard and easy examples.
alpha: Weighting parameter to balance loss for positive and negative examples.
... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import box_utils
class SigmoidFocalClassificationLoss(nn.Module):
| 37 | 171 | 573 | 10 | 26 | halostorm/OpenPCDet | pcdet/utils/loss_utils.py | Python | SigmoidFocalClassificationLoss | SigmoidFocalClassificationLoss | 8 | 71 | 8 | 8 | 09ba6923063148bf6d61470706cea9738fc63af0 | bigcode/the-stack | train |
83b55832220ab9d676022450 | train | function | def get_corner_loss_lidar(pred_bbox3d: torch.Tensor, gt_bbox3d: torch.Tensor):
"""
Args:
pred_bbox3d: (N, 7) float Tensor.
gt_bbox3d: (N, 7) float Tensor.
Returns:
corner_loss: (N) float Tensor.
"""
assert pred_bbox3d.shape[0] == gt_bbox3d.shape[0]
pred_box_corners = bo... | def get_corner_loss_lidar(pred_bbox3d: torch.Tensor, gt_bbox3d: torch.Tensor):
| """
Args:
pred_bbox3d: (N, 7) float Tensor.
gt_bbox3d: (N, 7) float Tensor.
Returns:
corner_loss: (N) float Tensor.
"""
assert pred_bbox3d.shape[0] == gt_bbox3d.shape[0]
pred_box_corners = box_utils.boxes_to_corners_3d(pred_bbox3d)
gt_box_corners = box_utils.boxes_t... | ) float tensor.
Weighted cross entropy loss without reduction
"""
input = input.permute(0, 2, 1)
target = target.argmax(dim=-1)
loss = F.cross_entropy(input, target, reduction='none') * weights
return loss
def get_corner_loss_lidar(pred_bbox3d: torch.Tensor, gt_bb... | 81 | 81 | 272 | 22 | 58 | halostorm/OpenPCDet | pcdet/utils/loss_utils.py | Python | get_corner_loss_lidar | get_corner_loss_lidar | 166 | 189 | 166 | 166 | 1f01ed56dddf081a2bb56b79913d7123cc19a37e | bigcode/the-stack | train |
37ac8d559b9055b16fea628b | train | function | @inject(config=Config)
def schedule_gearman_task(path, data, config):
gm_client = gearman.GearmanClient(["{0}:{1}".format(config['GEARMAN']['host'], config['GEARMAN']['port'])])
gm_client.submit_job(config['GEARMAN_TASK_NAME'], json.dumps(
{'path': path, 'data': json.dumps(data)}), wait_until_complete=F... | @inject(config=Config)
def schedule_gearman_task(path, data, config):
| gm_client = gearman.GearmanClient(["{0}:{1}".format(config['GEARMAN']['host'], config['GEARMAN']['port'])])
gm_client.submit_job(config['GEARMAN_TASK_NAME'], json.dumps(
{'path': path, 'data': json.dumps(data)}), wait_until_complete=False, background=True)
| mod:`zsl.utils.import_helper`
------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import json
from zsl import Config, inject
from zsl.gearman import gearman
@inject(config=Config)
def schedule_gearman_task(path, data, config):
| 64 | 64 | 89 | 17 | 46 | AtteqCom/zsl | src/zsl/utils/gearman_helper.py | Python | schedule_gearman_task | schedule_gearman_task | 15 | 19 | 15 | 16 | 366a55b920b75e258aa77e6dcf7a5f9f2ad39c7a | bigcode/the-stack | train |
b5871f23c6e76ee205a1d135 | train | class | class DatabaseWrapper(postgis_base.DatabaseWrapper, QueryProfilerDatabaseWrapperMixin):
pass
| class DatabaseWrapper(postgis_base.DatabaseWrapper, QueryProfilerDatabaseWrapperMixin):
| pass
| import django.contrib.gis.db.backends.postgis.base as postgis_base
from django_query_profiler.django.db.backends.database_wrapper_mixin import QueryProfilerDatabaseWrapperMixin
class DatabaseWrapper(postgis_base.DatabaseWrapper, QueryProfilerDatabaseWrapperMixin):
| 50 | 64 | 18 | 15 | 34 | sonej/django-query-profiler | django_query_profiler/django/contrib/gis/db/backends/postgis/base.py | Python | DatabaseWrapper | DatabaseWrapper | 6 | 7 | 6 | 6 | 3bd815612700e21e68d1b9477d2c66284227d5e0 | bigcode/the-stack | train |
d8e760dfe8ea56b885fe2baf | train | function | def load_byfilename(filename):
ext = os.path.splitext(filename)[1].lower()
if ext==".brep" or ext==".brp":
return load_brep(filename)
elif ext==".step" or ext==".stp":
return load_step_singleshape(filename)
elif ext==".iges" or ext==".igs":
return load_iges(filename)
raise V... | def load_byfilename(filename):
| ext = os.path.splitext(filename)[1].lower()
if ext==".brep" or ext==".brp":
return load_brep(filename)
elif ext==".step" or ext==".stp":
return load_step_singleshape(filename)
elif ext==".iges" or ext==".igs":
return load_iges(filename)
raise ValueError("Unknown filename ext... | status != IFSelect_RetDone:
raise IOError("IGES reader status = %s" % (str(status)))
iges_reader.TransferRoots() # Not sure what this does
BRepShape=iges_reader.Shape(1)
return BRepShape
def load_byfilename(filename):
| 64 | 64 | 98 | 6 | 57 | isuthermography/spatialnde | spatialnde/opencascade/loaders.py | Python | load_byfilename | load_byfilename | 56 | 65 | 56 | 56 | 0b2f33dac49db43e84dd0115d6d9a1ecc0b2e7ca | bigcode/the-stack | train |
43d9dcb2ab9635b79db575ab | train | function | def GetFacesSurfaces(BRepShape):
FaceExplorer=TopExp_Explorer(BRepShape,TopAbs_FACE)
Faces = []
while FaceExplorer.More():
ShapeFace=FaceExplorer.Current() # a TopoDS_Shape
# Convert TopoDS_Shape to a TopoDS_Face
Face=topods.Face(ShapeFace)
Faces.append(Face)
... | def GetFacesSurfaces(BRepShape):
| FaceExplorer=TopExp_Explorer(BRepShape,TopAbs_FACE)
Faces = []
while FaceExplorer.More():
ShapeFace=FaceExplorer.Current() # a TopoDS_Shape
# Convert TopoDS_Shape to a TopoDS_Face
Face=topods.Face(ShapeFace)
Faces.append(Face)
FaceExplorer.Next()
pas... | ".step" or ext==".stp":
return load_step_singleshape(filename)
elif ext==".iges" or ext==".igs":
return load_iges(filename)
raise ValueError("Unknown filename extension %s" % (ext))
def GetFacesSurfaces(BRepShape):
| 63 | 64 | 139 | 9 | 54 | isuthermography/spatialnde | spatialnde/opencascade/loaders.py | Python | GetFacesSurfaces | GetFacesSurfaces | 69 | 85 | 69 | 69 | fff8df9f533cb4c62e4766976d52e4d0fb33a0ee | bigcode/the-stack | train |
b72528836dea61237cbe9a4c | train | function | def load_step_singleshape(filename):
step_reader = STEPControl_Reader()
status = step_reader.ReadFile(filename)
if status != IFSelect_RetDone:
raise IOError("STEP reader status = %s" % (str(status)))
step_reader.TransferRoot(1) # Not sure what this does
if step_reader.NbShapes() > 1:
... | def load_step_singleshape(filename):
| step_reader = STEPControl_Reader()
status = step_reader.ReadFile(filename)
if status != IFSelect_RetDone:
raise IOError("STEP reader status = %s" % (str(status)))
step_reader.TransferRoot(1) # Not sure what this does
if step_reader.NbShapes() > 1:
raise ValueError("STEP file c... | Entity
#from OCC.Display.SimpleGui import init_display
def load_brep(BRepFile):
BRepShape=TopoDS_Shape()
builder=BRep_Builder()
breptools_Read(BRepShape,BRepFile,builder)
return BRepShape
def load_step_singleshape(filename):
| 64 | 64 | 99 | 8 | 55 | isuthermography/spatialnde | spatialnde/opencascade/loaders.py | Python | load_step_singleshape | load_step_singleshape | 28 | 39 | 28 | 28 | 5fd204beab4f3707eb484f488769af3b1566d48f | bigcode/the-stack | train |
86228ba05206c0303e917f17 | train | function | def load_iges(filename):
iges_reader = IGESControl_Reader()
status = iges_reader.ReadFile(filename)
if status != IFSelect_RetDone:
raise IOError("IGES reader status = %s" % (str(status)))
iges_reader.TransferRoots() # Not sure what this does
BRepShape=iges_reader.Shape(1)
return... | def load_iges(filename):
| iges_reader = IGESControl_Reader()
status = iges_reader.ReadFile(filename)
if status != IFSelect_RetDone:
raise IOError("IGES reader status = %s" % (str(status)))
iges_reader.TransferRoots() # Not sure what this does
BRepShape=iges_reader.Shape(1)
return BRepShape
| = %s" % (str(status)))
step_reader.TransferRoot(1) # Not sure what this does
if step_reader.NbShapes() > 1:
raise ValueError("STEP file contains multiple shapes")
return step_reader.Shape(1)
def load_iges(filename):
| 62 | 64 | 87 | 6 | 56 | isuthermography/spatialnde | spatialnde/opencascade/loaders.py | Python | load_iges | load_iges | 43 | 54 | 43 | 44 | 11879cdd1fbea801d78ac16cbfcf8cc06b5dfcf5 | bigcode/the-stack | train |
67ddb9043210d26a63dbdf3f | train | function | def load_brep(BRepFile):
BRepShape=TopoDS_Shape()
builder=BRep_Builder()
breptools_Read(BRepShape,BRepFile,builder)
return BRepShape
| def load_brep(BRepFile):
| BRepShape=TopoDS_Shape()
builder=BRep_Builder()
breptools_Read(BRepShape,BRepFile,builder)
return BRepShape
| Abs import TopAbs_FACE
from OCC.STEPControl import STEPControl_Reader
from OCC.IGESControl import IGESControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
#from OCC.Display.SimpleGui import init_display
def load_brep(BRepFile):
| 64 | 64 | 45 | 8 | 55 | isuthermography/spatialnde | spatialnde/opencascade/loaders.py | Python | load_brep | load_brep | 21 | 26 | 21 | 21 | 7fc34e724af3dbbfed537ddd23327a0e0b98d438 | bigcode/the-stack | train |
e0b5eced35e3783b9535abcb | train | function | def str_column_to_int(dataset, column):
for row in dataset:
row[column] = int(row[column])
| def str_column_to_int(dataset, column):
| for row in dataset:
row[column] = int(row[column])
| import sqrt
from matplotlib import pyplot as plt
import numpy as np
import cv2 as cv
import os
import sys
import time
import threading
import itertools
from group_three import *
from lvq import LVQ
# Convert string column to integer
def str_column_to_int(dataset, column):
| 64 | 64 | 23 | 9 | 54 | erikwii/sscode | train_pitch/experimental_split/train_three.py | Python | str_column_to_int | str_column_to_int | 24 | 26 | 24 | 24 | 28765053b657f6d9095f24a15f6477167fcee4bf | bigcode/the-stack | train |
4db8dc17739f0b1d26eabbef | train | function | def find_middle(input_list):
middle = float(len(input_list))/2
if middle % 2 != 0:
return (input_list[int(middle + .5)], input_list[int(middle - .5)])
else:
return (input_list[int(middle)], input_list[int(middle-1)])
| def find_middle(input_list):
| middle = float(len(input_list))/2
if middle % 2 != 0:
return (input_list[int(middle + .5)], input_list[int(middle - .5)])
else:
return (input_list[int(middle)], input_list[int(middle-1)])
|
import os
import sys
import time
import threading
import itertools
from group_three import *
from lvq import LVQ
# Convert string column to integer
def str_column_to_int(dataset, column):
for row in dataset:
row[column] = int(row[column])
def find_middle(input_list):
| 64 | 64 | 67 | 6 | 58 | erikwii/sscode | train_pitch/experimental_split/train_three.py | Python | find_middle | find_middle | 28 | 33 | 28 | 28 | 9eb62d15e51a0434c638872509b665d62ac91740 | bigcode/the-stack | train |
ea63d875745b7b12e93fa74f | train | function | def find_middle_factor(num):
count = 0
number = int(num)
factors = list()
for i in range(2, number-1):
if number % i == 0:
factors.append(i)
i += 1
count += 1
if count == 0:
return (num, 1)
if count == 1:
return (factors[0], facto... | def find_middle_factor(num):
| count = 0
number = int(num)
factors = list()
for i in range(2, number-1):
if number % i == 0:
factors.append(i)
i += 1
count += 1
if count == 0:
return (num, 1)
if count == 1:
return (factors[0], factors[0])
return find_m... | float(len(input_list))/2
if middle % 2 != 0:
return (input_list[int(middle + .5)], input_list[int(middle - .5)])
else:
return (input_list[int(middle)], input_list[int(middle-1)])
def find_middle_factor(num):
| 64 | 64 | 103 | 6 | 58 | erikwii/sscode | train_pitch/experimental_split/train_three.py | Python | find_middle_factor | find_middle_factor | 35 | 51 | 35 | 35 | 9120eb1b18587cb4ab81476ef27704678f3a7849 | bigcode/the-stack | train |
3226ed92edb9b7d41ecaf896 | train | function | def test_iterating_over_raw_velocity():
velocity = units.Velocity(au_per_d=1.234)
with assert_raises(units.UnpackingError):
x, y, z = velocity
| def test_iterating_over_raw_velocity():
| velocity = units.Velocity(au_per_d=1.234)
with assert_raises(units.UnpackingError):
x, y, z = velocity
| s == '[ 1.23 4.56] au'
def test_iterating_over_raw_measurement():
distance = units.Distance(au=1.234)
with assert_raises(units.UnpackingError):
x, y, z = distance
def test_iterating_over_raw_velocity():
| 64 | 64 | 44 | 8 | 55 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_iterating_over_raw_velocity | test_iterating_over_raw_velocity | 36 | 39 | 36 | 36 | 307edd3a6a10a0dd7f8b74d20be51d447f5e7929 | bigcode/the-stack | train |
9d442dba94947b6f5a53b6dd | train | function | @needs_astropy
def test_converting_velocity_with_astropy():
velocity = units.Velocity(au_per_d=1.234)
value1 = velocity.km_per_s
value2 = velocity.to(u.km / u.s)
epsilon = 1e-6
assert abs(value1 - value2.value) < epsilon
| @needs_astropy
def test_converting_velocity_with_astropy():
| velocity = units.Velocity(au_per_d=1.234)
value1 = velocity.km_per_s
value2 = velocity.to(u.km / u.s)
epsilon = 1e-6
assert abs(value1 - value2.value) < epsilon
| 234)
value1 = distance.km
value2 = distance.to(u.km)
epsilon = 0.02 # definitions of AU seem to disagree slightly
assert abs(value1 - value2.value) < epsilon
@needs_astropy
def test_converting_velocity_with_astropy():
| 64 | 64 | 75 | 14 | 49 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_converting_velocity_with_astropy | test_converting_velocity_with_astropy | 57 | 63 | 57 | 58 | b6c7154bfbdd6f0c71cd4d4354fc2556f355b35f | bigcode/the-stack | train |
1fa148580fe43df18589a7ab | train | function | def test_stringifying_vector_distance():
a = array([1.23, 4.56])
s = str(units.Distance(au=a))
if '[1' in s:
# Python 3.5, says Travis CI. No idea.
assert s == '[1.23 4.56] au'
else:
# Every other version of Python.
assert s == '[ 1.23 4.56] au'
| def test_stringifying_vector_distance():
| a = array([1.23, 4.56])
s = str(units.Distance(au=a))
if '[1' in s:
# Python 3.5, says Travis CI. No idea.
assert s == '[1.23 4.56] au'
else:
# Every other version of Python.
assert s == '[ 1.23 4.56] au'
| v1 = units.Velocity(au_per_d=2.0)
v2 = units.Velocity(km_per_s=3462.9137)
assert abs(v1.au_per_d - v2.au_per_d) < 1e-7
def test_stringifying_vector_distance():
| 64 | 64 | 99 | 7 | 56 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_stringifying_vector_distance | test_stringifying_vector_distance | 21 | 29 | 21 | 21 | 98520377a951b8a35d32e8997950883ddb3b0f21 | bigcode/the-stack | train |
4110d73ad5c97d11ccf46544 | train | function | @needs_astropy
def test_converting_distance_with_astropy():
distance = units.Distance(au=1.234)
value1 = distance.km
value2 = distance.to(u.km)
epsilon = 0.02 # definitions of AU seem to disagree slightly
assert abs(value1 - value2.value) < epsilon
| @needs_astropy
def test_converting_distance_with_astropy():
| distance = units.Distance(au=1.234)
value1 = distance.km
value2 = distance.to(u.km)
epsilon = 0.02 # definitions of AU seem to disagree slightly
assert abs(value1 - value2.value) < epsilon
| 0) < 1e-15
def test_converting_from_m_to_km():
distance = units.Distance(m=1234.0)
assert abs(distance.km - 1.234) < 1e-15
@needs_astropy
def test_converting_distance_with_astropy():
| 64 | 64 | 74 | 14 | 49 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_converting_distance_with_astropy | test_converting_distance_with_astropy | 49 | 55 | 49 | 50 | 5e70842348c3da05a3ec16e9f652e5d9ac7d17b3 | bigcode/the-stack | train |
d0d45d6b00ed8d48d9618d5e | train | function | def test_converting_from_km_to_m():
distance = units.Distance(km=1.234)
assert abs(distance.m - 1234.0) < 1e-15
| def test_converting_from_km_to_m():
| distance = units.Distance(km=1.234)
assert abs(distance.m - 1234.0) < 1e-15
| ):
x, y, z = distance
def test_iterating_over_raw_velocity():
velocity = units.Velocity(au_per_d=1.234)
with assert_raises(units.UnpackingError):
x, y, z = velocity
def test_converting_from_km_to_m():
| 64 | 64 | 41 | 10 | 53 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_converting_from_km_to_m | test_converting_from_km_to_m | 41 | 43 | 41 | 41 | cf42b0e15c9136ba3fff1afb0bd43187558b50c2 | bigcode/the-stack | train |
1dc906b394664c55d2696b79 | train | function | def test_velocity_input_units():
v1 = units.Velocity(au_per_d=2.0)
v2 = units.Velocity(km_per_s=3462.9137)
assert abs(v1.au_per_d - v2.au_per_d) < 1e-7
| def test_velocity_input_units():
| v1 = units.Velocity(au_per_d=2.0)
v2 = units.Velocity(km_per_s=3462.9137)
assert abs(v1.au_per_d - v2.au_per_d) < 1e-7
|
from skyfield import units
try:
from astropy import units as u
except ImportError:
u = None
def needs_astropy(test):
"""Skip `test` if AstroPy is not available."""
return None if (u is None) else test
def test_velocity_input_units():
| 64 | 64 | 64 | 6 | 57 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_velocity_input_units | test_velocity_input_units | 16 | 19 | 16 | 16 | 969f639688249807037a21dbc2e89d74c7938afe | bigcode/the-stack | train |
40a58d88c4e40e2e17ccb6ef | train | function | def test_converting_from_m_to_km():
distance = units.Distance(m=1234.0)
assert abs(distance.km - 1.234) < 1e-15
| def test_converting_from_m_to_km():
| distance = units.Distance(m=1234.0)
assert abs(distance.km - 1.234) < 1e-15
| .UnpackingError):
x, y, z = velocity
def test_converting_from_km_to_m():
distance = units.Distance(km=1.234)
assert abs(distance.m - 1234.0) < 1e-15
def test_converting_from_m_to_km():
| 64 | 64 | 41 | 10 | 53 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_converting_from_m_to_km | test_converting_from_m_to_km | 45 | 47 | 45 | 45 | aaa4176004bff04f020296be1af032c33d04c8f1 | bigcode/the-stack | train |
18aace9e75b1bbb4df0ca432 | train | function | def test_iterating_over_raw_measurement():
distance = units.Distance(au=1.234)
with assert_raises(units.UnpackingError):
x, y, z = distance
| def test_iterating_over_raw_measurement():
| distance = units.Distance(au=1.234)
with assert_raises(units.UnpackingError):
x, y, z = distance
| 3.5, says Travis CI. No idea.
assert s == '[1.23 4.56] au'
else:
# Every other version of Python.
assert s == '[ 1.23 4.56] au'
def test_iterating_over_raw_measurement():
| 64 | 64 | 41 | 9 | 55 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | test_iterating_over_raw_measurement | test_iterating_over_raw_measurement | 31 | 34 | 31 | 31 | 094b8e8d33efc15d695a0bf6fcf1503cd321b96f | bigcode/the-stack | train |
c77bdc4da1897fbea9832dbb | train | function | def needs_astropy(test):
"""Skip `test` if AstroPy is not available."""
return None if (u is None) else test
| def needs_astropy(test):
| """Skip `test` if AstroPy is not available."""
return None if (u is None) else test
| """Tests of whether units behave."""
from assay import assert_raises
from numpy import array
from skyfield import units
try:
from astropy import units as u
except ImportError:
u = None
def needs_astropy(test):
| 51 | 64 | 31 | 6 | 44 | pdav-sfi/python-skyfield | skyfield/tests/test_units.py | Python | needs_astropy | needs_astropy | 12 | 14 | 12 | 12 | a06cf0f7c9089e48965ff4f33935c53889d35154 | bigcode/the-stack | train |
c3a153574589f26c86bee7e4 | train | function | def get_config():
"""Returns a standard normal experiment config as ConfigDict."""
config = ConfigDict()
num_dim = 10
config.seed = 1
config.batch_size = 2000
config.estimation_batch_size = 6000
config.sample_shape = (num_dim,)
config.report_step = 1
config.vi_report_step = 10
config.num_temps = 5... | def get_config():
| """Returns a standard normal experiment config as ConfigDict."""
config = ConfigDict()
num_dim = 10
config.seed = 1
config.batch_size = 2000
config.estimation_batch_size = 6000
config.sample_shape = (num_dim,)
config.report_step = 1
config.vi_report_step = 10
config.num_temps = 5
config.resample... | # Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 156 | 237 | 791 | 4 | 151 | LaudateCorpus1/annealed_flow_transport | configs/funnel.py | Python | get_config | get_config | 21 | 100 | 21 | 21 | b7fb02b162695a1ef63c749851768ea16b8d90cb | bigcode/the-stack | train |
45d015e7d8f78c983402099c | train | function | def read_db_properties_format(raw_db_properties):
"""Helper to read non-standard db properties format.
Note:
Spark/Hive doesn't provide a way to read separate key/values for database properties.
They provide a custom format like: ((key_a,value_a), (key_b,value_b))
Neither keys nor value... | def read_db_properties_format(raw_db_properties):
| """Helper to read non-standard db properties format.
Note:
Spark/Hive doesn't provide a way to read separate key/values for database properties.
They provide a custom format like: ((key_a,value_a), (key_b,value_b))
Neither keys nor values are escaped.
Here we try our best to par... | get_db_name(table_name):
"""Get database name from full table name."""
parts = table_name.split('.', 1)
if len(parts) == 1:
return None
else:
return parts[0]
def get_table_name(table_name):
"""Get table name from full table name."""
parts = table_name.split('.', 1)
return ... | 90 | 90 | 300 | 9 | 81 | Tubular/sparkly | sparkly/catalog.py | Python | read_db_properties_format | read_db_properties_format | 289 | 335 | 289 | 289 | 5aa56a508b023a2dd98b18c74d29056e697bed15 | bigcode/the-stack | train |
182a6645c1b0105c6545e737 | train | function | def get_table_name(table_name):
"""Get table name from full table name."""
parts = table_name.split('.', 1)
return parts[-1]
| def get_table_name(table_name):
| """Get table name from full table name."""
parts = table_name.split('.', 1)
return parts[-1]
| property_name, value,
))
def get_db_name(table_name):
"""Get database name from full table name."""
parts = table_name.split('.', 1)
if len(parts) == 1:
return None
else:
return parts[0]
def get_table_name(table_name):
| 64 | 64 | 33 | 7 | 57 | Tubular/sparkly | sparkly/catalog.py | Python | get_table_name | get_table_name | 283 | 286 | 283 | 283 | 244ba29f89b25a78d183ba5b70318f5fb685ea47 | bigcode/the-stack | train |
1d6e7de4be9caf6d6de0e91d | train | function | def get_db_name(table_name):
"""Get database name from full table name."""
parts = table_name.split('.', 1)
if len(parts) == 1:
return None
else:
return parts[0]
| def get_db_name(table_name):
| """Get database name from full table name."""
parts = table_name.split('.', 1)
if len(parts) == 1:
return None
else:
return parts[0]
| list:
raise ValueError(
'Property value must not contain symbols: {}'.format(property_value_blacklist))
self._spark.sql("ALTER DATABASE {} SET DBPROPERTIES ('{}'='{}')".format(
db_name, property_name, value,
))
def get_db_name(table_name):
| 63 | 64 | 49 | 7 | 56 | Tubular/sparkly | sparkly/catalog.py | Python | get_db_name | get_db_name | 274 | 280 | 274 | 274 | a65e6142ec8af466f4f6bd14de23da3553690ac3 | bigcode/the-stack | train |
2f093bcffb8ee7ee2a00c2a7 | train | class | class SparklyCatalog(object):
"""A set of tools to interact with HiveMetastore."""
def __init__(self, spark):
"""Constructor.
Args:
spark (sparkly.SparklySession)
"""
self._spark = spark
def create_table(self, table_name, path=None, source=None, schema=None, **... | class SparklyCatalog(object):
| """A set of tools to interact with HiveMetastore."""
def __init__(self, spark):
"""Constructor.
Args:
spark (sparkly.SparklySession)
"""
self._spark = spark
def create_table(self, table_name, path=None, source=None, schema=None, **options):
"""Create ta... | #
# Copyright 2017 Tubular Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 160 | 256 | 1,729 | 6 | 153 | Tubular/sparkly | sparkly/catalog.py | Python | SparklyCatalog | SparklyCatalog | 22 | 271 | 22 | 22 | d8a58cf2c2899f05cdca8277b1938d5f9bdee631 | bigcode/the-stack | train |
5a08c21b70290131544e19c4 | train | function | def bench():
# Inputs
clk = Signal(bool(0))
rst = Signal(bool(0))
current_test = Signal(intbv(0)[8:])
input_axis_tdata = Signal(intbv(0)[64:])
input_axis_tkeep = Signal(intbv(0)[8:])
input_axis_tvalid = Signal(bool(0))
input_axis_tlast = Signal(bool(0))
input_axis_tuser = Signal(bo... | def bench():
# Inputs
| clk = Signal(bool(0))
rst = Signal(bool(0))
current_test = Signal(intbv(0)[8:])
input_axis_tdata = Signal(intbv(0)[64:])
input_axis_tkeep = Signal(intbv(0)[8:])
input_axis_tvalid = Signal(bool(0))
input_axis_tlast = Signal(bool(0))
input_axis_tuser = Signal(bool(0))
output_eth_paylo... | publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PR... | 256 | 256 | 2,302 | 7 | 249 | renaissanxe/verilog-ethernet | tb/test_eth_axis_rx_64.py | Python | bench | bench | 44 | 355 | 44 | 46 | f53ed6502b7dbb87edf410b58f609eceee583c1d | bigcode/the-stack | train |
c8327508f7399d226d4756af | train | function | def test_bench():
sim = Simulation(bench())
sim.run()
| def test_bench():
| sim = Simulation(bench())
sim.run()
| assert error_header_early_termination_asserted
rx_frame = sink.recv()
assert rx_frame == test_frame2
assert sink.empty()
yield delay(100)
raise StopSimulation
return dut, source_logic, sink_logic, clkgen, monitor, check
def test_bench():... | 64 | 64 | 16 | 5 | 58 | renaissanxe/verilog-ethernet | tb/test_eth_axis_rx_64.py | Python | test_bench | test_bench | 357 | 359 | 357 | 357 | aa4bb05f92b6f9725e7e41f1b38aae13a4446abc | bigcode/the-stack | train |
ab8e5a0c8cd194bc7e643864 | train | function | def register_url():
my_access_token = generate_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl"
headers = {"Authorization": "Bearer %s" % my_access_token}
request = {
"ShortCode": keys.shortcode,
"ResponseType": " ",
"ConfirmationURL": "https://... | def register_url():
| my_access_token = generate_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl"
headers = {"Authorization": "Bearer %s" % my_access_token}
request = {
"ShortCode": keys.shortcode,
"ResponseType": " ",
"ConfirmationURL": "https://fullstackdjango.com/... | import requests
import keys
from requests.auth import HTTPBasicAuth
from access_token import generate_access_token
def register_url():
| 26 | 64 | 124 | 4 | 21 | Meakelvis/daraja_api | c2b.py | Python | register_url | register_url | 7 | 20 | 7 | 7 | d6fab21bc01ed04f28bed12de6dd9d234211f167 | bigcode/the-stack | train |
d5d8c48180ba13db497e8d47 | train | function | def simulate_c2b_transaction():
my_access_token = generate_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate"
headers = {"Authorization": "Bearer %s" % my_access_token}
request = {
"ShortCode": keys.shortcode,
"CommandID": "CustomerPayBillOnline",
"A... | def simulate_c2b_transaction():
| my_access_token = generate_access_token()
api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate"
headers = {"Authorization": "Bearer %s" % my_access_token}
request = {
"ShortCode": keys.shortcode,
"CommandID": "CustomerPayBillOnline",
"Amount": "2",
"Msisdn": k... | ",
"ConfirmationURL": "https://fullstackdjango.com/confirmation",
"ValidationURL": "https://fullstackdjango.com/validation_url"
}
response = requests.post(api_url, json=request, headers=headers)
print(response.text)
# register_url()
def simulate_c2b_transaction():
| 64 | 64 | 131 | 7 | 57 | Meakelvis/daraja_api | c2b.py | Python | simulate_c2b_transaction | simulate_c2b_transaction | 25 | 39 | 25 | 25 | ea5ed6b71226bd6ea85510e936bab9dfe4993b2f | bigcode/the-stack | train |
0a6366cb40762fd73771aef6 | train | function | def get_map(seq,input_instruction):
computer = Intcode()
computer.initialize_memory(seq)
computer.set_pointer(0)
mapping = defaultdict(int)
# initial position
color, direc = computer.calculate(input_instruction)
curr_pos = [0,0]
curr_ang = 0
# running Intcode
while comp... | def get_map(seq,input_instruction):
| computer = Intcode()
computer.initialize_memory(seq)
computer.set_pointer(0)
mapping = defaultdict(int)
# initial position
color, direc = computer.calculate(input_instruction)
curr_pos = [0,0]
curr_ang = 0
# running Intcode
while computer.pointer != -1:
mapping[... | from intcode import Intcode
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
def get_map(seq,input_instruction):
| 30 | 98 | 327 | 7 | 22 | paaraujo/Advent-of-Code | 2019/day11.py | Python | get_map | get_map | 6 | 40 | 6 | 6 | 7d11f16fda9164577367c12ce12a057d9a109c3f | bigcode/the-stack | train |
5178acea25ca4f6080c8aa8b | train | function | def part1(input_instruction):
with open('inputs/day11.txt') as f:
seq = f.read().rstrip('\n').split(',')
mapping = get_map(seq,input_instruction)
return len(mapping)
| def part1(input_instruction):
| with open('inputs/day11.txt') as f:
seq = f.read().rstrip('\n').split(',')
mapping = get_map(seq,input_instruction)
return len(mapping)
| elif curr_ang == 270:
curr_pos = [curr_pos[0],curr_pos[1]-1]
# getting next coordinates
color, direc = computer.calculate(mapping[str(curr_pos[0])+','+str(curr_pos[1])])
return mapping
def part1(input_instruction):
| 64 | 64 | 46 | 6 | 57 | paaraujo/Advent-of-Code | 2019/day11.py | Python | part1 | part1 | 42 | 46 | 42 | 42 | c41c124540dbdd434d4c230ddefb4becb32145d5 | bigcode/the-stack | train |
84ee1da007b26a7d343a7fa3 | train | function | def part2(input_instruction):
with open('inputs/day11.txt') as f:
seq = f.read().rstrip('\n').split(',')
mapping = get_map(seq,input_instruction)
# getting limits
x_min = int(min(mapping.keys(),key=lambda k: int(k.split(',')[0])).split(',')[0])
x_max = int(max(mapping.keys()... | def part2(input_instruction):
| with open('inputs/day11.txt') as f:
seq = f.read().rstrip('\n').split(',')
mapping = get_map(seq,input_instruction)
# getting limits
x_min = int(min(mapping.keys(),key=lambda k: int(k.split(',')[0])).split(',')[0])
x_max = int(max(mapping.keys(),key=lambda k: int(k.split(',')... | [0],curr_pos[1]-1]
# getting next coordinates
color, direc = computer.calculate(mapping[str(curr_pos[0])+','+str(curr_pos[1])])
return mapping
def part1(input_instruction):
with open('inputs/day11.txt') as f:
seq = f.read().rstrip('\n').split(',')
mapping = get_map(seq,i... | 96 | 96 | 323 | 6 | 90 | paaraujo/Advent-of-Code | 2019/day11.py | Python | part2 | part2 | 48 | 76 | 48 | 48 | f846d825fb771c069f184c2806db957c4ae038f8 | bigcode/the-stack | train |
76aaab32f0e774ad21a54e2b | train | function | def get_parsed_context(args):
"""Parse args as path to a json file and returns context as dictionary."""
assert args, ("pipeline must be invoked with context arg set. For "
"this json parser you're looking for something "
"like: "
"pypyr pipelinename './myjs... | def get_parsed_context(args):
| """Parse args as path to a json file and returns context as dictionary."""
assert args, ("pipeline must be invoked with context arg set. For "
"this json parser you're looking for something "
"like: "
"pypyr pipelinename './myjsonfile.json'")
logger.debu... | """Context parser that returns a dictionary from a local json file."""
import logging
import json
# use pypyr logger to ensure loglevel is set correctly
logger = logging.getLogger(__name__)
def get_parsed_context(args):
| 48 | 64 | 158 | 7 | 41 | FooBarQuaxx/pypyr | pypyr/parser/jsonfile.py | Python | get_parsed_context | get_parsed_context | 10 | 25 | 10 | 10 | 8ed5199a6383dab84d23eacd0252c4776aa8b797 | bigcode/the-stack | train |
5abdf786ac9c1f4e3b94e1cd | train | function | def magickSquare(n):
return int(n*((n**2+1)/2))
| def magickSquare(n):
| return int(n*((n**2+1)/2))
| FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from itertools import permutations
import stackless
import argparse
def magickSquare(n):
| 64 | 64 | 19 | 6 | 57 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | magickSquare | magickSquare | 25 | 26 | 25 | 25 | 6c7d3f57ab276a6fb50e66b46758207f7dae2e7f | bigcode/the-stack | train |
b2ceb6b43735351b5f14f3dd | train | function | def theNumbers(n):
return [x for x in range(1,n*n+1)]
| def theNumbers(n):
| return [x for x in range(1,n*n+1)]
| TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from itertools import permutations
import stackless
import argparse
def magickSquare(n):
return int(n*((n**2+1)/2))
def theNumbers(n):
| 64 | 64 | 20 | 5 | 59 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | theNumbers | theNumbers | 28 | 29 | 28 | 28 | 5bc1a2b506e42c7c622bd4778cfeba77de00af97 | bigcode/the-stack | train |
120a76824779dc5dc2e0ef03 | train | function | def main(size, tasklets):
p = do_permutations(size, tasklets)
for x in p:
print("FOUND ->", x)
| def main(size, tasklets):
| p = do_permutations(size, tasklets)
for x in p:
print("FOUND ->", x)
| x += 1
for z in threads: z.disbatch.send(None)
for z in threads:
recv = z.results.receive()
for y in recv:
ret.append(y)
z.disbatch.close()
z.results.close()
return ret
def main(size, tasklets):
| 64 | 64 | 33 | 7 | 56 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | main | main | 104 | 107 | 104 | 104 | 350ef53ee74ebc786313e58c9ffaed3df2f9d036 | bigcode/the-stack | train |
00b84c227019fd7828972215 | train | function | def do_permutations(n, th):
ret = []
s = magickSquare(n)
r = get_permutations(n)
threads = []
for i in range(th): threads.append(Worker())
stackless.run()
x = 0
for p in permutations(r, n):
if x > (th-1): x = 0
threads[x].disbatch.send({'p':p, 's':s, 'n':n})
x += ... | def do_permutations(n, th):
| ret = []
s = magickSquare(n)
r = get_permutations(n)
threads = []
for i in range(th): threads.append(Worker())
stackless.run()
x = 0
for p in permutations(r, n):
if x > (th-1): x = 0
threads[x].disbatch.send({'p':p, 's':s, 'n':n})
x += 1
for z in threads: z.di... | break
t = checksquare(recv['p'], recv['s'], recv['n'])
if t != False:
ret.append(t)
self.results.send(ret)
return
def finish():
self.disbatch.close()
self.results.close()
def do_permutations(n, th):
| 64 | 64 | 159 | 9 | 55 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | do_permutations | do_permutations | 83 | 102 | 83 | 83 | aeef8acb1a2730552966170468efa2e52993c5d7 | bigcode/the-stack | train |
6f34733b284bb8d66d746957 | train | function | def get_permutations(n):
ret = []
s = magickSquare(n)
for p in permutations(theNumbers(n), n):
if sum(p) == s:
ret.append(p)
return ret
| def get_permutations(n):
| ret = []
s = magickSquare(n)
for p in permutations(theNumbers(n), n):
if sum(p) == s:
ret.append(p)
return ret
| IN
# THE SOFTWARE.
from itertools import permutations
import stackless
import argparse
def magickSquare(n):
return int(n*((n**2+1)/2))
def theNumbers(n):
return [x for x in range(1,n*n+1)]
def get_permutations(n):
| 64 | 64 | 47 | 7 | 57 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | get_permutations | get_permutations | 31 | 37 | 31 | 31 | 2fa512a00bc407ee73406234d75b0f50ef053210 | bigcode/the-stack | train |
4e3d82d6c99ff5efffcd2f0f | train | class | class Worker:
def __init__(self):
self.disbatch = stackless.channel()
self.results = stackless.channel()
stackless.tasklet(self.work)()
def work(self):
ret = []
while True:
recv = self.disbatch.receive()
if recv == None: break
t = che... | class Worker:
| def __init__(self):
self.disbatch = stackless.channel()
self.results = stackless.channel()
stackless.tasklet(self.work)()
def work(self):
ret = []
while True:
recv = self.disbatch.receive()
if recv == None: break
t = checksquare(recv['... | return False
d2 = sum(p[x][x] for x in range(n))
d1 = sum(p[x][n-x-1] for x in range(n))
if d1 == s and d2 == s:
return p
else: return False
class Worker:
| 64 | 64 | 118 | 3 | 60 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | Worker | Worker | 61 | 81 | 61 | 62 | 756927ca0909b91398566e49626bbdb3b581e527 | bigcode/the-stack | train |
846ad9ef8e285c8e41ed0bd9 | train | function | def checksquare(p, s, n):
d = []
for x in range(n):
t = []
for y in range(n):
t.append(p[y][x])
d.append(t)
t = theNumbers(n)
for r in d:
for y in r:
if y in t:
t.remove(y)
else: return False
for r in d:
if s... | def checksquare(p, s, n):
| d = []
for x in range(n):
t = []
for y in range(n):
t.append(p[y][x])
d.append(t)
t = theNumbers(n)
for r in d:
for y in r:
if y in t:
t.remove(y)
else: return False
for r in d:
if sum(r) != s:
re... | range(1,n*n+1)]
def get_permutations(n):
ret = []
s = magickSquare(n)
for p in permutations(theNumbers(n), n):
if sum(p) == s:
ret.append(p)
return ret
def checksquare(p, s, n):
| 64 | 64 | 155 | 9 | 54 | WWelna/MagicSquare-Stackless | magicsquare.py | Python | checksquare | checksquare | 39 | 59 | 39 | 39 | 251909d6c14e7557ed0c62509add595d47d81d5a | bigcode/the-stack | train |
90973dcf777ca2d9ad591719 | train | class | class HookManager(object):
def __init__(self, hooks_folder, hook_names, output):
self._hooks_folder = hooks_folder
self._hook_names = hook_names
self.hooks = defaultdict(list)
self.output = output
self._attribute_checker_path = os.path.join(self._hooks_folder, "attribute_che... | class HookManager(object):
| def __init__(self, hooks_folder, hook_names, output):
self._hooks_folder = hooks_folder
self._hook_names = hook_names
self.hooks = defaultdict(list)
self.output = output
self._attribute_checker_path = os.path.join(self._hooks_folder, "attribute_checker.py")
self._mute... | from collections import defaultdict
from threading import Lock
from conans.client.output import ScopedOutput
from conans.client.tools.files import chdir
from conans.errors import ConanException, NotFoundException
from conans.util.files import save
attribute_checker_hook = """
def pre_export(output, conanfile, conanfi... | 255 | 256 | 857 | 5 | 250 | matthiasng/conan | conans/client/hook_manager.py | Python | HookManager | HookManager | 36 | 130 | 36 | 37 | a7370ddbbbb06c09a3d66011bf91c61e79b676e3 | bigcode/the-stack | train |
b59b964e8a5c1a917f29b019 | train | class | @dataclass
class UserFragment(DataClassJsonMixin):
id: str
authID: str
email: str
status: UserStatus = enum_field(UserStatus)
role: UserRole = enum_field(UserRole)
| @dataclass
class UserFragment(DataClassJsonMixin):
| id: str
authID: str
email: str
status: UserStatus = enum_field(UserStatus)
role: UserRole = enum_field(UserRole)
| _field
from ..enum.user_role import UserRole
from ..enum.user_status import UserStatus
QUERY: List[str] = ["""
fragment UserFragment on User {
id
authID
email
status
role
}
"""]
@dataclass
class UserFragment(DataClassJsonMixin):
| 64 | 64 | 49 | 11 | 53 | kyaaqba/magma | symphony/cli/pyinventory/graphql/fragment/user.py | Python | UserFragment | UserFragment | 31 | 37 | 31 | 32 | 08eb70c2f04fc5d92135930305fb98012d0973c9 | bigcode/the-stack | train |
4c11db8b32ef446a9258e2e1 | train | class | class NewRelicSpanExporter(SpanExporter):
def __init__(self, *args, **kwargs):
self.client = SpanClient(*args, **kwargs)
self.client.add_version_info("NewRelic-OpenTelemetry-Exporter", __version__)
@staticmethod
def _transform(span):
attributes = dict(span.resource.attributes)
... | class NewRelicSpanExporter(SpanExporter):
| def __init__(self, *args, **kwargs):
self.client = SpanClient(*args, **kwargs)
self.client.add_version_info("NewRelic-OpenTelemetry-Exporter", __version__)
@staticmethod
def _transform(span):
attributes = dict(span.resource.attributes)
attributes.update(span.attributes)
... | typing
from newrelic_telemetry_sdk import Span as NewRelicSpan
from newrelic_telemetry_sdk import SpanClient
from opentelemetry.sdk.trace.export import Span, SpanExporter, SpanExportResult
from opentelemetry.trace.status import StatusCode
try:
from opentelemetry_exporter_python.version import version as __versio... | 121 | 121 | 404 | 10 | 111 | newrelic/opentelemetry-exporter-python | src/opentelemetry_ext_newrelic/span.py | Python | NewRelicSpanExporter | NewRelicSpanExporter | 32 | 83 | 32 | 32 | 92a1bf09a74aafadfdc3e57333294d9fe3bdb703 | bigcode/the-stack | train |
f511fce879d67399fb82cf04 | train | class | class Lox(object):
hadError = False
hadRuntimeError = False
exit_status = {64: "EX_USAGE ", 65: "EX_DATAERR",
66: "EX_NOINPUT", 70: "EX_SOFTWARE"}
interpreter = Interpreter.Interpreter()
@classmethod
def main(cls, argv):
if len(argv) > 2:
print(... | class Lox(object):
| hadError = False
hadRuntimeError = False
exit_status = {64: "EX_USAGE ", 65: "EX_DATAERR",
66: "EX_NOINPUT", 70: "EX_SOFTWARE"}
interpreter = Interpreter.Interpreter()
@classmethod
def main(cls, argv):
if len(argv) > 2:
print("Usage: python Pylox... | #coding=utf-8
import sys
import Scanner
import TokenType
import Parser
import AstPrinter
import Interpreter
import Resolver
class Lox(object):
| 34 | 157 | 525 | 5 | 28 | nicheng0019/crafting-interpreters | pylox/Pylox.py | Python | Lox | Lox | 12 | 99 | 12 | 12 | da5c42e8d0a149e13fd1e0fea8a0566255193617 | bigcode/the-stack | train |
f8e92c33da8bef235c54326a | train | class | class Extractor(object):
def __init__(self) -> None:
# find packages
llvm = Package_LLVM()
self.clang = os.path.join(llvm.path_store, 'bin', 'clang')
self.clang_libs = os.path.join(llvm.path_store, 'lib')
musl = Package_MUSL()
self.musl_inc = os.path.join(musl.path_... | class Extractor(object):
| def __init__(self) -> None:
# find packages
llvm = Package_LLVM()
self.clang = os.path.join(llvm.path_store, 'bin', 'clang')
self.clang_libs = os.path.join(llvm.path_store, 'lib')
musl = Package_MUSL()
self.musl_inc = os.path.join(musl.path_store, 'include')
... | from typing import cast, Any, Set, Dict, List, Tuple, Union, Optional
import re
import os
import json
from sortedcontainers import SortedDict # type: ignore
from pkg_llvm import Package_LLVM
from pkg_musl import Package_MUSL
from pkg_linux import Package_LINUX
from util import cd, prepdn, execute0, envldpaths
clas... | 89 | 256 | 3,399 | 5 | 83 | oslab-swrc/Krace | script/spec_extract.py | Python | Extractor | Extractor | 16 | 488 | 16 | 17 | aec97aafb31e3ace6697ccac7c2835b3216418a3 | bigcode/the-stack | train |
d074c4a4902ea6430cea5edf | train | class | class Lexer:
"""
The Lexer class reads all the Tokens of the program and fulfills all the
Token instances with the required params (token_type, literal)
param: _source -> The plain text of the program.
param: _character -> The actual character we are processing.
param: _read_position -> The nex... | class Lexer:
| """
The Lexer class reads all the Tokens of the program and fulfills all the
Token instances with the required params (token_type, literal)
param: _source -> The plain text of the program.
param: _character -> The actual character we are processing.
param: _read_position -> The next position of... | from re import match
from .token import Token, TokenType, lookup_token_type
class Lexer:
| 21 | 256 | 1,358 | 3 | 17 | jeronimobarea/Programming-Language-Interpreter | src/lexer/lexer.py | Python | Lexer | Lexer | 6 | 156 | 6 | 6 | 35a53b8d974a3293abea7939028328b205de3c41 | bigcode/the-stack | train |
40bd71e626ed37b570e3e08d | train | class | class UnexpectedDeletedXForm(Exception):
pass
| class UnexpectedDeletedXForm(Exception):
| pass
| (Exception):
"""
A custom exception for the XForms application.
"""
pass
class XMLSyntaxError(CouchFormException):
pass
class DuplicateError(CouchFormException):
def __init__(self, xform):
self.xform = xform
class UnexpectedDeletedXForm(Exception):
| 64 | 64 | 10 | 7 | 56 | johan--/commcare-hq | corehq/ex-submodules/couchforms/exceptions.py | Python | UnexpectedDeletedXForm | UnexpectedDeletedXForm | 17 | 18 | 17 | 17 | 301c1e2fd3e5a16589d165ce7ee2a399dfd4b311 | bigcode/the-stack | train |
0300da5d4ef0616ac352bf74 | train | class | class CouchFormException(Exception):
"""
A custom exception for the XForms application.
"""
pass
| class CouchFormException(Exception):
| """
A custom exception for the XForms application.
"""
pass
| class CouchFormException(Exception):
| 6 | 64 | 23 | 6 | 0 | johan--/commcare-hq | corehq/ex-submodules/couchforms/exceptions.py | Python | CouchFormException | CouchFormException | 1 | 5 | 1 | 1 | 44fc0df9a6b25b89ccde289a76799b8df78efdae | bigcode/the-stack | train |
669680c3442a51e6d4fe184a | train | class | class XMLSyntaxError(CouchFormException):
pass
| class XMLSyntaxError(CouchFormException):
| pass
| class CouchFormException(Exception):
"""
A custom exception for the XForms application.
"""
pass
class XMLSyntaxError(CouchFormException):
| 32 | 64 | 12 | 9 | 22 | johan--/commcare-hq | corehq/ex-submodules/couchforms/exceptions.py | Python | XMLSyntaxError | XMLSyntaxError | 8 | 9 | 8 | 8 | 85acdc55c86d0861840af9d9be326d14fa6acdca | bigcode/the-stack | train |
f9281d74998ec4cdc4ac79c9 | train | class | class DuplicateError(CouchFormException):
def __init__(self, xform):
self.xform = xform
| class DuplicateError(CouchFormException):
| def __init__(self, xform):
self.xform = xform
| class CouchFormException(Exception):
"""
A custom exception for the XForms application.
"""
pass
class XMLSyntaxError(CouchFormException):
pass
class DuplicateError(CouchFormException):
| 43 | 64 | 26 | 8 | 34 | johan--/commcare-hq | corehq/ex-submodules/couchforms/exceptions.py | Python | DuplicateError | DuplicateError | 12 | 14 | 12 | 12 | 1367343eb18a94aaedd7398c516483f50e3cc804 | bigcode/the-stack | train |
34579afaf253c8296f7465d8 | train | class | class PhoneDateValueError(CouchFormException):
pass
| class PhoneDateValueError(CouchFormException):
| pass
| .
"""
pass
class XMLSyntaxError(CouchFormException):
pass
class DuplicateError(CouchFormException):
def __init__(self, xform):
self.xform = xform
class UnexpectedDeletedXForm(Exception):
pass
class PhoneDateValueError(CouchFormException):
| 64 | 64 | 13 | 10 | 53 | johan--/commcare-hq | corehq/ex-submodules/couchforms/exceptions.py | Python | PhoneDateValueError | PhoneDateValueError | 21 | 22 | 21 | 21 | ec9a5c300f3de47ca440924aef9874539faa5b67 | bigcode/the-stack | train |
e165fa8b9b9718c1e6c5df3f | train | class | class GanPowLrScheduler (GanBaseLrScheduler):
def __init__ (self, decay = 1, step = 1):
super().__init__()
self._decay = decay
self._step = step
def _scheduled_lr (self, lr0, epoch):
return lr0 / (1.0 + self._decay * epoch / self._step)
| class GanPowLrScheduler (GanBaseLrScheduler):
| def __init__ (self, decay = 1, step = 1):
super().__init__()
self._decay = decay
self._step = step
def _scheduled_lr (self, lr0, epoch):
return lr0 / (1.0 + self._decay * epoch / self._step)
| from tf_gen_models.callbacks.schedulers import GanBaseLrScheduler
class GanPowLrScheduler (GanBaseLrScheduler):
| 26 | 64 | 85 | 13 | 12 | mbarbetti/tf-gen-models | tf_gen_models/callbacks/schedulers/GanPowLrScheduler.py | Python | GanPowLrScheduler | GanPowLrScheduler | 3 | 10 | 3 | 3 | f6b77983d4eb565297e40e05213e15f96d8531b3 | bigcode/the-stack | train |
a1a3c027d498e9bb22c2dcee | train | class | class JSONField(sqlalchemy.types.TypeDecorator): # pylint: disable=abstract-method
"""Represent an immutable structure as a json-encoded string or json.
Usage::
JSONField(enforce_string=True|False, enforce_unicode=True|False)
"""
def process_literal_param(self, value: typing.Any, dialect: "... | class JSONField(sqlalchemy.types.TypeDecorator): # pylint: disable=abstract-method
| """Represent an immutable structure as a json-encoded string or json.
Usage::
JSONField(enforce_string=True|False, enforce_unicode=True|False)
"""
def process_literal_param(self, value: typing.Any, dialect: "DefaultDialect") -> typing.Any:
"""Re-use of process_bind_param."""
... | www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing per... | 188 | 188 | 627 | 18 | 169 | qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3 | venv/lib/python3.9/site-packages/sqlalchemy_jsonfield/jsonfield.py | Python | JSONField | JSONField | 34 | 100 | 34 | 34 | 386c0f61718f20834ca5e70919f45467fd85ff37 | bigcode/the-stack | train |
a1d0f2767ee10fb613e634ef | train | function | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg, redefined-outer-name
enforce_string: bool = False,
enforce_unicode: bool = False,
json: typing.Union[types.ModuleType, typing.Any] = json,
*args: typing.Any,
**kwargs: typing.Any
) -> JSONField:
"""Mutable JSONField creator.
... | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg, redefined-outer-name
enforce_string: bool = False,
enforce_unicode: bool = False,
json: typing.Union[types.ModuleType, typing.Any] = json,
*args: typing.Any,
**kwargs: typing.Any
) -> JSONField:
| """Mutable JSONField creator.
:param enforce_string: enforce String(UnicodeText) type usage
:type enforce_string: bool
:param enforce_unicode: do not encode non-ascii data
:type enforce_unicode: bool
:param json: JSON encoding/decoding library.
By default: standard json package... | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg, redefined-outer-name
enforce_string: bool = False,
enforce_unicode: bool = False,
json: typing.Union[types.ModuleType, typing.Any] = json,
*args: typing.Any,
**kwargs: typing.Any
) -> JSONField:
| 76 | 74 | 247 | 76 | 0 | qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3 | venv/lib/python3.9/site-packages/sqlalchemy_jsonfield/jsonfield.py | Python | mutable_json_field | mutable_json_field | 103 | 127 | 103 | 109 | 27606eca575ddf2ba011f14aa8835dc106e5af7e | bigcode/the-stack | train |
951ab216a275f7c9e0d9973e | train | class | class utility(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_msg = None
# Prints on the console when the extension is loaded
@commands.Cog.listener()
async def on_ready(self):
print(
"{} Cog has been loaded\n-----".format(
se... | class utility(commands.Cog):
| def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_msg = None
# Prints on the console when the extension is loaded
@commands.Cog.listener()
async def on_ready(self):
print(
"{} Cog has been loaded\n-----".format(
self.__class__.__name__
... | # Imports
import discord
from discord.ext import commands
from datetime import datetime, timedelta
import asyncio
import humanize
# Intializing the extension
class utility(commands.Cog):
| 39 | 256 | 1,737 | 6 | 32 | sourcery-ai-bot/Jaaag-one | Jaaagbot/cogs/utility.py | Python | utility | utility | 10 | 262 | 10 | 10 | d76830c979d956a48e6aebc0dd10bb5c72a38a31 | bigcode/the-stack | train |
bf38818e789d16bff1240918 | train | function | def setup(bot: commands.Bot):
bot.add_cog(utility(bot)) | def setup(bot: commands.Bot):
| bot.add_cog(utility(bot)) | name="Vote for us!",
value=
"Bot list links:\n[Top.gg](https://top.gg/bot/816034868899086386/vote)",
inline=False
)
await ctx.send(embed=embed)
# Adds the extention
def setup(bot: commands.Bot):
| 64 | 64 | 16 | 7 | 56 | sourcery-ai-bot/Jaaag-one | Jaaagbot/cogs/utility.py | Python | setup | setup | 266 | 267 | 266 | 266 | fcd3d7b851735e13c66ee5305d42c8dfc598cafa | bigcode/the-stack | train |
002c8e352abbd9f85c2bd3c5 | train | function | def test_zip_longest(iterables):
"""Zip longest several test cases."""
for it1 in iterables:
for it2 in iterables:
izi = list(izip(it1, it2, longest=True))
zli = list(zip_longest(it1, it2))
assert izi == zli # instances
| def test_zip_longest(iterables):
| """Zip longest several test cases."""
for it1 in iterables:
for it2 in iterables:
izi = list(izip(it1, it2, longest=True))
zli = list(zip_longest(it1, it2))
assert izi == zli # instances
| None], {None})]
def test_zip(iterables):
"""Zip several test cases."""
for it1 in iterables:
for it2 in iterables:
assert list(izip(it1, it2)) == list(zip(it1, it2))
def test_zip_longest(iterables):
| 64 | 64 | 72 | 8 | 56 | stanislav-kudriavtsev/Algorithms | Python/iterative/izip/test_izip.py | Python | test_zip_longest | test_zip_longest | 32 | 38 | 32 | 32 | 61e896ea1b473e7951da72aad452871012c59d37 | bigcode/the-stack | train |
35b134ddd12cb46d49a872ae | train | function | @fixture()
def iterables():
"""Iterables for izip."""
return [[], [0], [1, 0], [-1, 0, 1], "hello", (None, [None], {None})]
| @fixture()
def iterables():
| """Iterables for izip."""
return [[], [0], [1, 0], [-1, 0, 1], "hello", (None, [None], {None})]
| : utf-8 -*-
"""The izip test module."""
__author__ = "Stanislav D. Kudriavtsev"
from itertools import zip_longest
from pytest import fixture
from izip import izip
# pylint: disable=redefined-outer-name
@fixture()
def iterables():
| 64 | 64 | 50 | 7 | 56 | stanislav-kudriavtsev/Algorithms | Python/iterative/izip/test_izip.py | Python | iterables | iterables | 19 | 22 | 19 | 20 | 55c1d845067a5bd129d500011265ed80e3d8ac53 | bigcode/the-stack | train |
6fba3e44a7b3edefd5663fe2 | train | function | def test_zip(iterables):
"""Zip several test cases."""
for it1 in iterables:
for it2 in iterables:
assert list(izip(it1, it2)) == list(zip(it1, it2))
| def test_zip(iterables):
| """Zip several test cases."""
for it1 in iterables:
for it2 in iterables:
assert list(izip(it1, it2)) == list(zip(it1, it2))
| : disable=redefined-outer-name
@fixture()
def iterables():
"""Iterables for izip."""
return [[], [0], [1, 0], [-1, 0, 1], "hello", (None, [None], {None})]
def test_zip(iterables):
| 64 | 64 | 50 | 6 | 58 | stanislav-kudriavtsev/Algorithms | Python/iterative/izip/test_izip.py | Python | test_zip | test_zip | 25 | 29 | 25 | 25 | 3c15bf388db1105e964a5e141557ade27a9dbdc1 | bigcode/the-stack | train |
66385d5f483d483605bb81dd | train | function | def flag(s0, p0, s1, p1, p2):
sock.sendlineafter("flag\x0d\n", "4")
sock.recvline()
sock.recvline()
sock.sendline(base64.b64encode(s0.export()))
sock.recvline()
sock.sendline(base64.b64encode(p0.export()))
sock.recvline()
sock.sendline(base64.b64encode(s1.export()))
sock.recvline()
... | def flag(s0, p0, s1, p1, p2):
| sock.sendlineafter("flag\x0d\n", "4")
sock.recvline()
sock.recvline()
sock.sendline(base64.b64encode(s0.export()))
sock.recvline()
sock.sendline(base64.b64encode(p0.export()))
sock.recvline()
sock.sendline(base64.b64encode(s1.export()))
sock.recvline()
sock.sendline(base64.b64enc... | *
def sign(data):
sock.sendlineafter("flag\x0d\n", "3")
sock.recvline()
sock.sendline(data)
sock.recvline()
return base64.b64decode(sock.recvline())
def flag(s0, p0, s1, p1, p2):
| 64 | 64 | 130 | 17 | 47 | mihaid-b/CyberSakura | Gathered CTF writeups/ptr-yudai-writeups/2019/CSAW_CTF_Qualification_Round_2019/brillouin/solve.py | Python | flag | flag | 15 | 28 | 15 | 15 | 748b779b830337bfb8c0f55b8ed3404a3173a9ab | bigcode/the-stack | train |
d9a503cdbe15e9e9089f2fde | train | function | def sign(data):
sock.sendlineafter("flag\x0d\n", "3")
sock.recvline()
sock.sendline(data)
sock.recvline()
return base64.b64decode(sock.recvline())
| def sign(data):
| sock.sendlineafter("flag\x0d\n", "3")
sock.recvline()
sock.sendline(data)
sock.recvline()
return base64.b64decode(sock.recvline())
| from ptrlib import *
import base64
from bls.scheme import *
from bplib.bp import G1Elem, G2Elem
from petlib.bn import Bn
from bls.utils import *
def sign(data):
| 46 | 64 | 46 | 4 | 42 | mihaid-b/CyberSakura | Gathered CTF writeups/ptr-yudai-writeups/2019/CSAW_CTF_Qualification_Round_2019/brillouin/solve.py | Python | sign | sign | 8 | 13 | 8 | 8 | f4551afb9c837786179c6bb74ac78b453aea0d8e | bigcode/the-stack | train |
78171edb99748bc4f9cf1c7e | train | class | class CmdMarket(ArxCommand):
"""
market
Usage:
market
market/buy <material>=<amount>
market/sell <material>=<amount>
market/info <material>
market/import <material>=<amount>
Purchase with silver:
market/economic <amount>
market/social <amount>
... | class CmdMarket(ArxCommand):
| """
market
Usage:
market
market/buy <material>=<amount>
market/sell <material>=<amount>
market/info <material>
market/import <material>=<amount>
Purchase with silver:
market/economic <amount>
market/social <amount>
market/military <amount>
... | class_path == self.path and ob.db.can_stack]
if stacking:
obj = stacking[0]
obj.set_num(obj.db.num_instances + 1)
else:
obj = create_object(typeclass=self.path, key=self.name,
location=caller, home=caller)
return obj
class Mar... | 256 | 256 | 1,786 | 8 | 247 | Zironic/arxcode | commands/cmdsets/market.py | Python | CmdMarket | CmdMarket | 84 | 277 | 84 | 84 | 0ba9a1e6625ff2d13cdd3b897b001a0e3cc2b150 | bigcode/the-stack | train |
76f133b2a2c09899452c2910 | train | class | class CmdHaggle(ArxCommand):
"""
Haggle to get a discount on goods
Usage:
haggle
haggle/roll
haggle/findbuyer <material>[,target]=<amount>[,minimum bonus]
haggle/findseller <material>[,target]=<amount>[,minimum bonus]
haggle/accept
haggle/decline
This can... | class CmdHaggle(ArxCommand):
| """
Haggle to get a discount on goods
Usage:
haggle
haggle/roll
haggle/findbuyer <material>[,target]=<amount>[,minimum bonus]
haggle/findseller <material>[,target]=<amount>[,minimum bonus]
haggle/accept
haggle/decline
This can buy/sell materials and resou... | log_info("Haggle Log: %s" % log_msg)
def buy_materials(self):
"""Attempt to buy the materials we made the deal for"""
err = "You cannot afford the silver cost of %s."
if self.resource_type:
cost = self.silver_value
if cost > self.caller.currency:
... | 256 | 256 | 1,842 | 10 | 246 | Zironic/arxcode | commands/cmdsets/market.py | Python | CmdHaggle | CmdHaggle | 466 | 640 | 466 | 466 | 54503370cd973a13206d42154e5234444a0a2253 | bigcode/the-stack | train |
571ffa901123dd6543b7efc1 | train | class | class OtherMaterial(object):
"""Class for handling transactions of buying generic items in shop"""
def __init__(self, otype):
self.name = "book"
self.value = other_items[otype][0]
self.category = other_items[otype][1]
self.path = other_items[otype][2]
self.desc = other_it... | class OtherMaterial(object):
| """Class for handling transactions of buying generic items in shop"""
def __init__(self, otype):
self.name = "book"
self.value = other_items[otype][0]
self.category = other_items[otype][1]
self.path = other_items[otype][2]
self.desc = other_items[otype][3]
def __str_... | _dice_check
RESOURCE_VAL = 250
BOOK_PRICE = 1
other_items = {"book": [BOOK_PRICE, "parchment",
"typeclasses.readable.readable.Readable",
"A book that you can write in and others can read."],
}
class OtherMaterial(object):
| 64 | 64 | 184 | 5 | 59 | Zironic/arxcode | commands/cmdsets/market.py | Python | OtherMaterial | OtherMaterial | 35 | 56 | 35 | 35 | 0821840ca472036074858d70e7f329ef118c25de | bigcode/the-stack | train |
8b209d08b19f6a9037de7e6b | train | class | class MarketCmdSet(CmdSet):
"""CmdSet for a market."""
key = "MarketCmdSet"
priority = 101
duplicates = False
no_exits = False
no_objs = False
def at_cmdset_creation(self):
"""
This is the only method defined in a cmdset, called during
its creation. It should populat... | class MarketCmdSet(CmdSet):
| """CmdSet for a market."""
key = "MarketCmdSet"
priority = 101
duplicates = False
no_exits = False
no_objs = False
def at_cmdset_creation(self):
"""
This is the only method defined in a cmdset, called during
its creation. It should populate the set with command insta... | .can_stack]
if stacking:
obj = stacking[0]
obj.set_num(obj.db.num_instances + 1)
else:
obj = create_object(typeclass=self.path, key=self.name,
location=caller, home=caller)
return obj
class MarketCmdSet(CmdSet):
| 64 | 64 | 176 | 8 | 55 | Zironic/arxcode | commands/cmdsets/market.py | Python | MarketCmdSet | MarketCmdSet | 59 | 80 | 59 | 59 | 0c0701ecb8d33ab57c71f318468dca8eac785f88 | bigcode/the-stack | train |
cf5e2eaedf59574e8d017074 | train | class | class HaggledDeal(object):
"""Helper class for trying to haggle a deal"""
VALID_RESOURCES = ('economic', 'military', 'social')
def __init__(self, caller):
self.caller = caller
# build from SaverDict stored in haggling_deal attribute
deal = self.caller.db.haggling_deal
self.t... | class HaggledDeal(object):
| """Helper class for trying to haggle a deal"""
VALID_RESOURCES = ('economic', 'military', 'social')
def __init__(self, caller):
self.caller = caller
# build from SaverDict stored in haggling_deal attribute
deal = self.caller.db.haggling_deal
self.transaction_type = deal[0]
... | n" % cost
caller.msg(msg)
return
if "economic" in self.switches or "military" in self.switches or "social" in self.switches:
try:
assets = caller.player_ob.Dominion.assets
amt = int(self.args)
if amt <= 0:
ra... | 256 | 256 | 1,838 | 7 | 248 | Zironic/arxcode | commands/cmdsets/market.py | Python | HaggledDeal | HaggledDeal | 285 | 463 | 285 | 285 | 79998218d2afc4bbee941ea28792a7bad4d31811 | bigcode/the-stack | train |
f22662417052d5ae8fea79a1 | train | class | class HaggleError(Exception):
"""Errors raised when haggling"""
pass
| class HaggleError(Exception):
| """Errors raised when haggling"""
pass
| += amt
elif "military" in self.switches:
assets.military += amt
assets.save()
caller.msg("You have bought %s resources for %s." % (amt, cost))
return
caller.msg("Invalid switch.")
return
class HaggleError(Exception):
| 64 | 64 | 18 | 6 | 57 | Zironic/arxcode | commands/cmdsets/market.py | Python | HaggleError | HaggleError | 280 | 282 | 280 | 280 | 14bd4c3ea66c2bec008056d4727357e0d8bd43a4 | bigcode/the-stack | train |
9a5060c635458e9a387e955c | train | function | def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset",
type=str,
help="Dataset name. Now ptb|yahoo is supported.")
parser.add_argument("--learning_rate",
type=float,
... | def parse_args():
| parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset",
type=str,
help="Dataset name. Now ptb|yahoo is supported.")
parser.add_argument("--learning_rate",
type=float,
default=0.00... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | 145 | 180 | 600 | 4 | 140 | mukaiu/PaddleNLP | examples/text_generation/vae-seq2seq/args.py | Python | parse_args | parse_args | 18 | 123 | 18 | 18 | 0110058e7c3d25f7522e642600c2c466c5a83f07 | bigcode/the-stack | train |
a4a7b64abf6d970de2613aaf | train | function | @frappe.whitelist()
def get_payment_account(mode_of_payment, company):
account = frappe.db.get_value("Mode of Payment Account",
{"parent": mode_of_payment, "company": company}, "default_account")
if not account:
frappe.throw(_("Please set default account in Mode of Payment {0}")
.format(mode_of_payment))
ret... | @frappe.whitelist()
def get_payment_account(mode_of_payment, company):
| account = frappe.db.get_value("Mode of Payment Account",
{"parent": mode_of_payment, "company": company}, "default_account")
if not account:
frappe.throw(_("Please set default account in Mode of Payment {0}")
.format(mode_of_payment))
return {
"account": account,
"account_currency": frappe.db.get_value("... | (item_code, company).get("expense_account") or
get_company_default(company, "default_expense_account") or frappe.get_cached_value('Company', company,
"default_expense_account"))
return item_dict
@frappe.whitelist()
def get_payment_account(mode_of_payment, company):
| 64 | 64 | 106 | 16 | 47 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_payment_account | get_payment_account | 417 | 428 | 417 | 418 | 3554bcfaea7fb5f0f87cee76f1ee29315a4dc1f2 | bigcode/the-stack | train |
29c5c565234cbc3d6a3793d7 | train | function | @frappe.whitelist()
def get_beneficiary_details(beneficiary,aid_decision_date,type1,beneficiary_aid_type,to_date,additional):
filters=[beneficiary_aid_type,aid_decision_date]
cond=''
if beneficiary:
cond += 'and ben.beneficiary=%s '
filters.append(beneficiary)
if to_date :
cond += 'and dis.aid_decision_date... | @frappe.whitelist()
def get_beneficiary_details(beneficiary,aid_decision_date,type1,beneficiary_aid_type,to_date,additional):
| filters=[beneficiary_aid_type,aid_decision_date]
cond=''
if beneficiary:
cond += 'and ben.beneficiary=%s '
filters.append(beneficiary)
if to_date :
cond += 'and dis.aid_decision_date <= %s '
filters.append(to_date)
if additional :
cond += 'and dis.additional = %s '
filters.append(additional)
if ty... | come_account, id.default_warehouse, id.cost_center, id.project, id.project_activities
from `tabItem` i LEFT JOIN `tabItem Default` id ON i.name=id.parent and id.company=%s
where i.name=%s
and i.disabled=0
and (i.end_of_life is null or i.end_of_life='0000-00-00' or i.end_of_life > %s)""",
(args.get('co... | 187 | 187 | 625 | 33 | 154 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_beneficiary_details | get_beneficiary_details | 319 | 366 | 319 | 320 | 7d204c6d35f7aea88bedb47264142e3303888a28 | bigcode/the-stack | train |
b3442bb4d5ae6c1f994c52be | train | function | @frappe.whitelist()
def get_item_detail(company, type,item_code):
item_dict = {}
if type=="Material" or type=="Additional":
item_details = get_item_details({'item_code': item_code, 'company': company})
item_dict['warehouse'] = item_details.get('default_warehouse')
item_dict['income_account'] = (item_details.get... | @frappe.whitelist()
def get_item_detail(company, type,item_code):
| item_dict = {}
if type=="Material" or type=="Additional":
item_details = get_item_details({'item_code': item_code, 'company': company})
item_dict['warehouse'] = item_details.get('default_warehouse')
item_dict['income_account'] = (item_details.get("income_account") or get_item_group_defaults(item_code, company).... | @frappe.whitelist()
def get_conversion_factor(item_code, uom):
return frappe.db.get_value('UOM Conversion Detail', {'parent': item_code,'uom': uom}, 'conversion_factor')
from erpnext.stock.get_item_details import get_valuation_rate
from erpnext.accounts.utils import get_company_default
@frappe.whitelist()
def get_it... | 84 | 84 | 283 | 16 | 67 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_item_detail | get_item_detail | 395 | 413 | 395 | 396 | 1565367ffb65e632d7b87c0af32d8dc80b81bedc | bigcode/the-stack | train |
63daa2b22e46f546ef32020c | train | function | @frappe.whitelist()
def get_conversion_factor(item_code, uom):
return frappe.db.get_value('UOM Conversion Detail', {'parent': item_code,'uom': uom}, 'conversion_factor')
| @frappe.whitelist()
def get_conversion_factor(item_code, uom):
| return frappe.db.get_value('UOM Conversion Detail', {'parent': item_code,'uom': uom}, 'conversion_factor')
| , det.aid_decision_date,det.amount,det.item_code,det.rent_no
""".format(cond), filters, as_dict=True)
# frappe.msgprint(frappe.as_json(x))
return x
@frappe.whitelist()
def get_conversion_factor(item_code, uom):
| 64 | 64 | 43 | 16 | 47 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_conversion_factor | get_conversion_factor | 387 | 389 | 387 | 388 | 59738c064ff68166b32f9721de99a051937fce09 | bigcode/the-stack | train |
31ca6d9746ae30859eee793c | train | function | @frappe.whitelist()
def get_paid_beneficiaries(beneficiary,aid_decision_date,type1):
filters=[type1,aid_decision_date]
cond=''
if beneficiary:
cond = 'and det.beneficiary=%s '
filters.append(beneficiary)
x= frappe.db.sql("""select det.beneficiary, det.beneficiary_name ,det.item_code ,det.aid_decision_date,d... | @frappe.whitelist()
def get_paid_beneficiaries(beneficiary,aid_decision_date,type1):
| filters=[type1,aid_decision_date]
cond=''
if beneficiary:
cond = 'and det.beneficiary=%s '
filters.append(beneficiary)
x= frappe.db.sql("""select det.beneficiary, det.beneficiary_name ,det.item_code ,det.aid_decision_date,det.amount,det.warehouse ,det.qty,det.valuation_rate
,det.item_name,det.type,det.ra... | _date,dis.amount,dis.rent_no,dis.type
""".format(cond), filters, as_dict=True)
# frappe.msgprint(frappe.as_json(x))
return x
@frappe.whitelist()
def get_paid_beneficiaries(beneficiary,aid_decision_date,type1):
| 66 | 66 | 220 | 24 | 41 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_paid_beneficiaries | get_paid_beneficiaries | 367 | 386 | 367 | 368 | 8ddbc11208d87f599f69c1c0027a6d297e912b65 | bigcode/the-stack | train |
a80d02cd2418075e24e682de | train | function | def get_item_details(args=None):
item = frappe.db.sql("""select i.name, id.income_account, id.default_warehouse, id.cost_center, id.project, id.project_activities
from `tabItem` i LEFT JOIN `tabItem Default` id ON i.name=id.parent and id.company=%s
where i.name=%s
and i.disabled=0
and (i.end_of_life is ... | def get_item_details(args=None):
| item = frappe.db.sql("""select i.name, id.income_account, id.default_warehouse, id.cost_center, id.project, id.project_activities
from `tabItem` i LEFT JOIN `tabItem Default` id ON i.name=id.parent and id.company=%s
where i.name=%s
and i.disabled=0
and (i.end_of_life is null or i.end_of_life='0000-00-00... | _from,
"debit": self.total,
"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
"cost_center": item.cost_center,
"project": item.project,
}, item=item)
)
def get_item_details(args=None):
| 62 | 64 | 173 | 7 | 55 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | get_item_details | get_item_details | 307 | 317 | 307 | 307 | 94dd54ebe521c81f6266ba86d406c703ea85e1f8 | bigcode/the-stack | train |
b1289fd60622f36157de064e | train | class | class BeneficiaryAidPayment(BuyingController):
def validate(self):
self.number_of_beneficiaries = len(self.get("items"))
def on_submit(self):
self.make_gl_entries()
if (self.type == 'Material' or self.type=='Additional') and self.update_stock == 1:
self.update_stock_ledger()
self.update_deserve_check(canc... | class BeneficiaryAidPayment(BuyingController):
| def validate(self):
self.number_of_beneficiaries = len(self.get("items"))
def on_submit(self):
self.make_gl_entries()
if (self.type == 'Material' or self.type=='Additional') and self.update_stock == 1:
self.update_stock_ledger()
self.update_deserve_check(cancel=False)
# self.update_logs()
def before_c... | # -*- coding: utf-8 -*-
# Copyright (c) 2021, Baida and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from erpnext.accounts.general_ledger import make_gl_entries, merge_similar_entries, delete_gl_entries
f... | 201 | 256 | 2,804 | 10 | 190 | baidalala/beneficiaries | beneficiaries/beneficiaries/doctype/beneficiary_aid_payment/beneficiary_aid_payment.py | Python | BeneficiaryAidPayment | BeneficiaryAidPayment | 18 | 303 | 18 | 18 | d583c526bb2e90b0bec563a2742097ba0bff6e27 | bigcode/the-stack | train |
3a038d2e476c2f6b04b4136d | train | class | class CExecutor(base.BaseExecutor):
model_name = "score"
def __init__(self, model):
self.model = model
self.interpreter = interpreters.CInterpreter()
assembler_cls = assemblers.get_assembler_cls(model)
self.model_ast = assembler_cls(model).assemble()
self._gcc = "gcc"... | class CExecutor(base.BaseExecutor):
| model_name = "score"
def __init__(self, model):
self.model = model
self.interpreter = interpreters.CInterpreter()
assembler_cls = assemblers.get_assembler_cls(model)
self.model_ast = assembler_cls(model).assemble()
self._gcc = "gcc"
def predict(self, X):
... | {print_code}
return 0;
}}
"""
EXECUTE_AND_PRINT_SCALAR = """
printf("%f\\n", score(input));
"""
EXECUTE_AND_PRINT_VECTOR_TPL = """
double result[{size}];
score(input, result);
for (int i = 0; i < {size}; ++i) {{
printf("%f ", *(result+i));
}}
"""
class CExecutor(base.BaseExecutor... | 90 | 90 | 300 | 7 | 83 | Aulust/m2cgen | tests/e2e/executors/c.py | Python | CExecutor | CExecutor | 41 | 81 | 41 | 42 | 4dfbfc2ebbeb879ccc35b367e9f7f582398903b8 | bigcode/the-stack | train |
cf0dce2acb33657846a813fb | train | class | class Umap(CMakePackage):
"""Umap is a library that provides an mmap()-like interface to a
simple, user-space page fault handler based on the userfaultfd Linux
feature (starting with 4.3 linux kernel)."""
homepage = "https://github.com/LLNL/umap"
url = "https://github.com/LLNL/umap/archive/v2.... | class Umap(CMakePackage):
| """Umap is a library that provides an mmap()-like interface to a
simple, user-space page fault handler based on the userfaultfd Linux
feature (starting with 4.3 linux kernel)."""
homepage = "https://github.com/LLNL/umap"
url = "https://github.com/LLNL/umap/archive/v2.1.0.tar.gz"
git =... | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Umap(CMakePackage):
| 62 | 161 | 538 | 7 | 55 | jeanbez/spack | var/spack/repos/builtin/packages/umap/package.py | Python | Umap | Umap | 9 | 37 | 9 | 9 | a412e6d16e8466a7ef8db9ab3e17d9f563ce38f7 | bigcode/the-stack | train |
1fb7697c8f71e99a2af05362 | train | function | def generate_data():
if not Path(data_path).is_file():
X,y = make_classification(
n_samples = 1000,
n_features = 5,
n_informative = 5,
n_redundant = 0,
n_classes = 2,
)
df = pd.DataFr... | def generate_data():
| if not Path(data_path).is_file():
X,y = make_classification(
n_samples = 1000,
n_features = 5,
n_informative = 5,
n_redundant = 0,
n_classes = 2,
)
df = pd.DataFrame(data=X)
d... | -NN) Classification', 'Support Vector Machine (SVM) Classification', 'Kernel SVM Classification', 'Gaussian Naive Bayes', 'Multinomial Naive Bayes', 'Decision Tree Classification', 'Random Forest Classification', 'Text Classification']
data_path = 'tests/sample_data.csv'
def generate_data():
| 64 | 64 | 93 | 4 | 60 | samhiggs/DSSnippets | tests/test_snippets.py | Python | generate_data | generate_data | 11 | 22 | 11 | 11 | 1c59217132f627f61eafc51311aa179939547e1d | bigcode/the-stack | train |
8d5c858f80040e6c654235c9 | train | function | def parse_json_code(json_str, key):
code_list = json_str[key]['body']
code_str = '\n'.join(code_list)
code_str = code_str.replace("'$1'", f"'{data_path}'")
return code_str
| def parse_json_code(json_str, key):
| code_list = json_str[key]['body']
code_str = '\n'.join(code_list)
code_str = code_str.replace("'$1'", f"'{data_path}'")
return code_str
| n_informative = 5,
n_redundant = 0,
n_classes = 2,
)
df = pd.DataFrame(data=X)
df['label'] = y
df.to_csv(data_path, index=False)
def parse_json_code(json_str, key):
| 64 | 64 | 54 | 9 | 55 | samhiggs/DSSnippets | tests/test_snippets.py | Python | parse_json_code | parse_json_code | 24 | 28 | 24 | 24 | 92805e21f39872f2e887595d773d013625eecca8 | bigcode/the-stack | train |
ffad9227e9ba33d721b29b5a | train | function | def test_valid_json():
"""Checks that the json was loaded correctly and dict contains correct keys"""
with open('snippets/snippets.code-snippets') as json_file:
data = json.load(json_file)
assert set(snippet_names) == set(data.keys())
| def test_valid_json():
| """Checks that the json was loaded correctly and dict contains correct keys"""
with open('snippets/snippets.code-snippets') as json_file:
data = json.load(json_file)
assert set(snippet_names) == set(data.keys())
| _path, index=False)
def parse_json_code(json_str, key):
code_list = json_str[key]['body']
code_str = '\n'.join(code_list)
code_str = code_str.replace("'$1'", f"'{data_path}'")
return code_str
def test_valid_json():
| 64 | 64 | 56 | 5 | 58 | samhiggs/DSSnippets | tests/test_snippets.py | Python | test_valid_json | test_valid_json | 30 | 34 | 30 | 30 | c42f80a3f3adcb514457554b4b31d071047afddc | bigcode/the-stack | train |
deee02444708f511a1f3f954 | train | function | def test_rfc_snippet():
generate_data()
with open('snippets/snippets.code-snippets') as json_file:
data = json.load(json_file)
code_str = parse_json_code(data, 'Random Forest Classification')
exec(code_str)
assert Path('model/classifier.joblib').is_file()
shutil.rmtree('model')
| def test_rfc_snippet():
| generate_data()
with open('snippets/snippets.code-snippets') as json_file:
data = json.load(json_file)
code_str = parse_json_code(data, 'Random Forest Classification')
exec(code_str)
assert Path('model/classifier.joblib').is_file()
shutil.rmtree('model')
|
def test_valid_json():
"""Checks that the json was loaded correctly and dict contains correct keys"""
with open('snippets/snippets.code-snippets') as json_file:
data = json.load(json_file)
assert set(snippet_names) == set(data.keys())
def test_rfc_snippet():
| 64 | 64 | 74 | 7 | 57 | samhiggs/DSSnippets | tests/test_snippets.py | Python | test_rfc_snippet | test_rfc_snippet | 36 | 43 | 36 | 36 | 88d7a4278df50c292ba45ce363aab554f2cdb999 | bigcode/the-stack | train |
b86fe586e2fd6d3506e0c4b6 | train | function | def get_dependencies():
dep_file = path.join(HERE, 'requirements.in')
if not path.isfile(dep_file):
return []
with open(dep_file, encoding='utf-8') as f:
return f.readlines()
| def get_dependencies():
| dep_file = path.join(HERE, 'requirements.in')
if not path.isfile(dep_file):
return []
with open(dep_file, encoding='utf-8') as f:
return f.readlines()
| adog_checks', 'rabbitmq', '__about__.py')) as f:
exec(f.read(), ABOUT)
# Get the long description from the README file
with open(path.join(HERE, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
def get_dependencies():
| 64 | 64 | 48 | 4 | 60 | TheBooper/integrations-core | rabbitmq/setup.py | Python | get_dependencies | get_dependencies | 21 | 27 | 21 | 21 | fd55762dcd7054d08da86cea56ce80a8611cf4ec | bigcode/the-stack | train |
53f9857fafdc75572e57d982 | train | class | @HEADS.register_module()
class YOLOXHead(BaseDenseHead, BBoxTestMixin):
"""YOLOXHead head used in `YOLOX <https://arxiv.org/abs/2107.08430>`_.
Args:
num_classes (int): Number of categories excluding the background
category.
in_channels (int): Number of channels in the input feature ... | @HEADS.register_module()
class YOLOXHead(BaseDenseHead, BBoxTestMixin):
| """YOLOXHead head used in `YOLOX <https://arxiv.org/abs/2107.08430>`_.
Args:
num_classes (int): Number of categories excluding the background
category.
in_channels (int): Number of channels in the input feature map.
feat_channels (int): Number of hidden channels in stacking ... | # Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule,
bias_init_with_prob)
from mmcv.ops.nms import batched_nms
from mmcv.runner import force_fp32
from mmdet.c... | 165 | 256 | 4,752 | 20 | 144 | chenxinfeng4/mmdetection | mmdet/models/dense_heads/yolox_head.py | Python | YOLOXHead | YOLOXHead | 20 | 491 | 20 | 21 | b625dc7b1625a479a5908b6da79aa24fe2ea0eba | bigcode/the-stack | train |
c32168f40398b2a37ef52c8a | train | class | class FindReplace(Action):
"""Rewrite a value in one of Atom's cson configuration files."""
def binary_dependencies(self):
return ['atom']
def arguments(self):
return [
('path', 'The configuration file to rewrite a value in.'),
('find', 'The string to be replaced.')... | class FindReplace(Action):
| """Rewrite a value in one of Atom's cson configuration files."""
def binary_dependencies(self):
return ['atom']
def arguments(self):
return [
('path', 'The configuration file to rewrite a value in.'),
('find', 'The string to be replaced.'),
('replace', '... | from core.action import Action
class FindReplace(Action):
| 11 | 64 | 148 | 5 | 5 | nielsvm/toggle-desktop | plugins/atomio/find_replace.py | Python | FindReplace | FindReplace | 3 | 24 | 3 | 3 | ece08bf2cee1b970d9c2c36aadea98c19dac6c2c | bigcode/the-stack | train |
f6ca380097af2972f789f94e | train | class | @register('room_client_event_handler')
class EditGetMapHandler(object):
event_type = 'edit_get_map'
@staticmethod
def handle(room, client):
pass
| @register('room_client_event_handler')
class EditGetMapHandler(object):
| event_type = 'edit_get_map'
@staticmethod
def handle(room, client):
pass
| from spyd.registry_manager import register
@register('room_client_event_handler')
class EditGetMapHandler(object):
| 23 | 64 | 38 | 15 | 7 | DanSeraf/spyd | src/spyd/game/room/client_event_handlers/edit_get_map_handler.py | Python | EditGetMapHandler | EditGetMapHandler | 3 | 9 | 3 | 4 | c8f3254a3e132adc893a33f5905a134d87dde5d0 | bigcode/the-stack | train |
15c052b42030faf8f3d8ecf4 | train | function | def test_average_distance_of_n_nearest_other_labels_map():
cle.select_device("gfx")
labels = cle.push(np.asarray([
[1, 0, 0, 0, 0, 3],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, ... | def test_average_distance_of_n_nearest_other_labels_map():
| cle.select_device("gfx")
labels = cle.push(np.asarray([
[1, 0, 0, 0, 0, 3],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 2]
]))
oth... | import pyclesperanto_prototype as cle
import numpy as np
def test_average_distance_of_n_nearest_other_labels_map():
| 27 | 141 | 471 | 12 | 14 | elsandal/pyclesperanto_prototype | tests/test_average_distance_to_n_nearest_other_labels_map.py | Python | test_average_distance_of_n_nearest_other_labels_map | test_average_distance_of_n_nearest_other_labels_map | 4 | 44 | 4 | 4 | 41e4036ee603e1735c34e625be21e41a063a8bf4 | bigcode/the-stack | train |
16bda9680e547cab7b0f7741 | train | function | def generate_remote_matches(
pipeline: PipelineContext,
repository_name: str = None,
contributor_name: str = None,
progress=ProgressMonitor.NULL,
):
"""Find matches between local and remote files."""
chunk_size = 1000
config = pipeline.config
logger.info("Starting remote match detectio... | def generate_remote_matches(
pipeline: PipelineContext,
repository_name: str = None,
contributor_name: str = None,
progress=ProgressMonitor.NULL,
):
| """Find matches between local and remote files."""
chunk_size = 1000
config = pipeline.config
logger.info("Starting remote match detection.")
# Prepare index of local signatures to detect matches
local_signatures = bulk_read(pipeline.repr_storage.signature)
neighbor_matcher = NeighborMatc... |
from winnow.pipeline.progress_monitor import ProgressMonitor, ProgressBar
from winnow.storage.repr_utils import bulk_read
# Default module logger
logger = logging.getLogger(__name__)
def generate_remote_matches(
pipeline: PipelineContext,
repository_name: str = None,
contributor_name: str = None,
prog... | 75 | 75 | 251 | 35 | 40 | benetech/Winnow2.0 | winnow/pipeline/generate_remote_matches.py | Python | generate_remote_matches | generate_remote_matches | 13 | 45 | 13 | 18 | 3fc1be2e2aef3b385931332ea3ecc10ac3453bcc | bigcode/the-stack | train |
59539f5167decf9e2421e33e | train | function | def _progress(remote_signatures_storage, repository_name, contributor_name, chunk_size):
"""Get total work and step work to account all available remote fingerprints."""
total_count = remote_signatures_storage.count(
repository_name=repository_name,
contributor_name=contributor_name,
)
i... | def _progress(remote_signatures_storage, repository_name, contributor_name, chunk_size):
| """Get total work and step work to account all available remote fingerprints."""
total_count = remote_signatures_storage.count(
repository_name=repository_name,
contributor_name=contributor_name,
)
if total_count is None:
return 1.0, 0
iterations = ceil(max(total_count, 1) / ... | _matcher.find_matches(needles=remote_signatures, max_distance=config.proc.match_distance)
storage.save_matches(matches)
progress.increase(amount=step_work)
logger.info("Done remote match detection.")
progress.complete()
def _progress(remote_signatures_storage, repository_name, contributor_name,... | 64 | 64 | 99 | 17 | 47 | benetech/Winnow2.0 | winnow/pipeline/generate_remote_matches.py | Python | _progress | _progress | 48 | 57 | 48 | 48 | d78633c8fe75ed8a34c2fd72b4027fbcb2184239 | bigcode/the-stack | train |
a4a6f6a1dcfd093f9c145d76 | train | function | @app.route("/exampleQuery")
def exampleQuery():
example_query = """PREFIX mu: <http://mu.semte.ch/vocabularies/core/>
PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>
PREFIX dbpedia: <http://dbpedia.org/ontology/>
PREFIX nie: <http://www.semanticdesktop.org/ontologies/... | @app.route("/exampleQuery")
def exampleQuery():
| example_query = """PREFIX mu: <http://mu.semte.ch/vocabularies/core/>
PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>
PREFIX dbpedia: <http://dbpedia.org/ontology/>
PREFIX nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#>
SELECT DISTINCT (?virt... |
@app.route("/exampleMethod")
def exampleMethod():
return "tests"
@app.route("/exampleQuery")
def exampleQuery():
| 26 | 64 | 203 | 10 | 16 | redpencilio/shmdoc-analyzer-service | examples.py | Python | exampleQuery | exampleQuery | 7 | 24 | 7 | 8 | f99a963c13d1d30d3f2ff018cc502cc13ffb7215 | bigcode/the-stack | train |
8b82703d276b498fe4960cdd | train | function | @app.route("/exampleMethod")
def exampleMethod():
return "tests"
| @app.route("/exampleMethod")
def exampleMethod():
| return "tests"
| @app.route("/exampleMethod")
def exampleMethod():
| 10 | 64 | 15 | 10 | 0 | redpencilio/shmdoc-analyzer-service | examples.py | Python | exampleMethod | exampleMethod | 2 | 4 | 2 | 3 | cef96350c4a5ba832bbdc06e799cc4cd53283294 | bigcode/the-stack | train |
b03bbd9fdb82eb7ed56800da | train | function | @app.route("/test2")
def test2():
f = open("/share/5f0c25efd7814c000c000001.xml")
s = ""
for line in f:
s += line + "\n"
f.close()
return s
| @app.route("/test2")
def test2():
| f = open("/share/5f0c25efd7814c000c000001.xml")
s = ""
for line in f:
s += line + "\n"
f.close()
return s
| physicalFile a nfo:FileDataObject ;
nie:dataSource ?virtualFile .
?virtualFile nfo:fileName ?name .
?virtualFile dbpedia:fileExtension ?extension .
}"""
return flask.jsonify(helpers.query(example_query))
@app.route("/test2")
def test2():
| 64 | 64 | 58 | 10 | 54 | redpencilio/shmdoc-analyzer-service | examples.py | Python | test2 | test2 | 27 | 34 | 27 | 28 | d69dafa8e107704e9251f2d8e3307f4ede82076e | bigcode/the-stack | train |
ca73037bca64bb5cb0543eb8 | train | function | def check_localization(outdir):
lprojdir = outdir / 'Contents' / 'Resources' / 'en.lproj'
assert (lprojdir / 'localized.txt').isfile()
| def check_localization(outdir):
| lprojdir = outdir / 'Contents' / 'Resources' / 'en.lproj'
assert (lprojdir / 'localized.txt').isfile()
| assert len(plist)
assert plist.get('CFBundleIdentifier', None) == 'org.sphinx-doc.Sphinx.help'
assert (contentsdir / 'Resources').isdir()
assert (contentsdir / 'Resources' / 'en.lproj').isdir()
def check_localization(outdir):
| 64 | 64 | 42 | 7 | 57 | muravjov/sphinx-doc | tests/test_build_applehelp.py | Python | check_localization | check_localization | 41 | 43 | 41 | 41 | 011a2928c5cf90a967d9688713a3c10734854d35 | bigcode/the-stack | train |
7cf5d9d39086aa6e7cd0ddca | train | function | def check_structure(outdir):
contentsdir = outdir / 'Contents'
assert contentsdir.isdir()
assert (contentsdir / 'Info.plist').isfile()
with open(contentsdir / 'Info.plist', 'rb') as f:
plist = read_plist(f)
assert plist
assert len(plist)
assert plist.get('CFBundleIdentifier', None) ... | def check_structure(outdir):
| contentsdir = outdir / 'Contents'
assert contentsdir.isdir()
assert (contentsdir / 'Info.plist').isfile()
with open(contentsdir / 'Info.plist', 'rb') as f:
plist = read_plist(f)
assert plist
assert len(plist)
assert plist.get('CFBundleIdentifier', None) == 'org.sphinx-doc.Sphinx.hel... | for details.
"""
import plistlib
from util import with_app
from path import path
# Use plistlib.load in 3.4 and above
try:
read_plist = plistlib.load
except AttributeError:
read_plist = plistlib.readPlist
def check_structure(outdir):
| 64 | 64 | 122 | 6 | 57 | muravjov/sphinx-doc | tests/test_build_applehelp.py | Python | check_structure | check_structure | 26 | 38 | 26 | 26 | 5878ff7bb6cec136659cb4f51dec92bc343e7fb5 | bigcode/the-stack | train |
7032308cd1008eab4bb837e7 | train | function | @with_app(buildername='applehelp')
def test_applehelp_output(app, status, warning):
app.builder.build_all()
# Have to use bundle_path, not outdir, because we alter the latter
# to point to the lproj directory so that the HTML arrives in the
# correct location.
bundle_path = path(app.builder.bundle_... | @with_app(buildername='applehelp')
def test_applehelp_output(app, status, warning):
| app.builder.build_all()
# Have to use bundle_path, not outdir, because we alter the latter
# to point to the lproj directory so that the HTML arrives in the
# correct location.
bundle_path = path(app.builder.bundle_path)
check_structure(bundle_path)
check_localization(bundle_path)
| ()
def check_localization(outdir):
lprojdir = outdir / 'Contents' / 'Resources' / 'en.lproj'
assert (lprojdir / 'localized.txt').isfile()
@with_app(buildername='applehelp')
def test_applehelp_output(app, status, warning):
| 64 | 64 | 90 | 21 | 43 | muravjov/sphinx-doc | tests/test_build_applehelp.py | Python | test_applehelp_output | test_applehelp_output | 46 | 55 | 46 | 47 | ade78bae20c2d20742ef57799f59672fd1353772 | bigcode/the-stack | train |
1ecad1dec2fa6d1299028da0 | train | class | class Issues:
def __init__(self, reqp, response, args):
self.__reqp = reqp
self.__response = response
self.__args = args
def create(self, title, body=None, labels=None, milestone=None, assignees=None):
method_params = {}
if None is title: title = '{0:%Y-%m-%d %H:... | class Issues:
| def __init__(self, reqp, response, args):
self.__reqp = reqp
self.__response = response
self.__args = args
def create(self, title, body=None, labels=None, milestone=None, assignees=None):
method_params = {}
if None is title: title = '{0:%Y-%m-%d %H:%M:%S}'.format(... | #!python3
#encoding:utf-8
import requests
import urllib.parse
import json
import os.path
import datetime
import web.http.Paginator
import web.service.github.api.v3.Response
import web.log.Log
class Issues:
| 50 | 256 | 919 | 3 | 46 | trysrv/GitHub.Uploader.CuiCmd.201706231541 | web/service/github/api/v3/issues/Issues.py | Python | Issues | Issues | 11 | 92 | 11 | 11 | d34049027d47f3d6b1d40972038199b789abdbd6 | bigcode/the-stack | train |
7b28a6bb14cd827adf558d22 | train | class | class InstanceSegmentation(object):
def __init__( self,
use_algorithm,
path,
pretrained_weights = None,
batchsize = 2,
iterations_over_dataset = 100,
data_gen_args = None,
lo... | class InstanceSegmentation(object):
| def __init__( self,
use_algorithm,
path,
pretrained_weights = None,
batchsize = 2,
iterations_over_dataset = 100,
data_gen_args = None,
loss_function = "mse",
... | '''
InstantDL
Written by Dominik Waibel and Ali Boushehri
In this file the functions are started to train and test the networks
'''
from instantdl.utils import *
class InstanceSegmentation(object):
| 45 | 256 | 1,040 | 6 | 39 | ruolinsss/InstantDL | instantdl/segmentation/InstanceSegmentation.py | Python | InstanceSegmentation | InstanceSegmentation | 10 | 133 | 10 | 10 | efd6565fc5d737dd36f22ca25fc0dfa96fdf9ed1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.