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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6000f4bba415dcab5f30af1c | train | class | class EllipticCurveCanonicalHeight:
r"""
Class for computing canonical heights of points on elliptic curves
defined over number fields, including rigorous lower bounds for
the canonical height of non-torsion points.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.height import EllipticC... | class EllipticCurveCanonicalHeight:
| r"""
Class for computing canonical heights of points on elliptic curves
defined over number fields, including rigorous lower bounds for
the canonical height of non-torsion points.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.height import EllipticCurveCanonicalHeight
sage: E ... | _part = r*(x*(1+r**2)-2*r)/denom
if imag_part is None:
imag_part = -(r**2-1)*y*r/denom
return CIF(real_part, imag_part)
def eps(err, is_real):
r"""
Return a Real or Complex interval centered on 0 with radius err.
INPUT:
- ``err`` (real) -- a positive real number, the radius of the i... | 256 | 256 | 13,088 | 8 | 248 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | EllipticCurveCanonicalHeight | EllipticCurveCanonicalHeight | 762 | 2,085 | 762 | 762 | b9860c384411289efcc18b013183601787400162 | bigcode/the-stack | train |
6d0cc9a7a82d1140f48a9e0e | train | class | class UnionOfIntervals:
r"""
A class representing a finite union of closed intervals in
`\RR` which can be scaled, shifted, intersected, etc.
The intervals are represented as an ordered list of their
endpoints, which may include `-\infty` and `+\infty`.
EXAMPLES::
sage: from sage.sche... | class UnionOfIntervals:
| r"""
A class representing a finite union of closed intervals in
`\RR` which can be scaled, shifted, intersected, etc.
The intervals are represented as an ordered list of their
endpoints, which may include `-\infty` and `+\infty`.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.heig... | (1) (2006), pages 42-68.
"""
##############################################################################
# Copyright (C) 2010 Robert Bradshaw <robertwb@math.washington.edu>
# 2014 John Cremona <john.cremona@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)... | 256 | 256 | 3,497 | 5 | 250 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | UnionOfIntervals | UnionOfIntervals | 61 | 485 | 61 | 61 | 718d92f97baa58fc687cc703d736f3d6847365d7 | bigcode/the-stack | train |
1647d22cd0df27ceb8a368bc | train | function | def rat_term_CIF(z, try_strict=True):
r"""
Compute the value of `u/(1-u)^2` in ``CIF``, where `u=\exp(2\pi i z)`.
INPUT:
- ``z`` (complex) -- a CIF element
- ``try_strict`` (bool) -- flag
EXAMPLES::
sage: from sage.schemes.elliptic_curves.height import rat_term_CIF
sage: z =... | def rat_term_CIF(z, try_strict=True):
| r"""
Compute the value of `u/(1-u)^2` in ``CIF``, where `u=\exp(2\pi i z)`.
INPUT:
- ``z`` (complex) -- a CIF element
- ``try_strict`` (bool) -- flag
EXAMPLES::
sage: from sage.schemes.elliptic_curves.height import rat_term_CIF
sage: z = CIF(0.5,0.2)
sage: rat_term_C... | 100: # discard the worse entries (if there are many)
L = L[unneeded:]
if fs.lower() < min_max: # we may beat the record, cannot yet tell: insert this region
# into the list at the appropriate palce to maintain sorting
bisect.insort(... | 193 | 193 | 645 | 12 | 181 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | rat_term_CIF | rat_term_CIF | 666 | 729 | 666 | 666 | 172642863461baba5c420867fe6935abbd3236d0 | bigcode/the-stack | train |
ffe407f6558449ba218e0719 | train | function | def inf_max_abs(f, g, D):
r"""
Returns `\inf_D(\max(|f|, |g|))`.
INPUT:
- ``f``, ``g`` (polynomials) -- real univariate polynomials
- ``D`` (UnionOfIntervals) -- a subset of `\RR`
OUTPUT:
A real number approximating the value of `\inf_D(\max(|f|, |g|))`.
ALGORITHM:
The extreme... | def inf_max_abs(f, g, D):
| r"""
Returns `\inf_D(\max(|f|, |g|))`.
INPUT:
- ``f``, ``g`` (polynomials) -- real univariate polynomials
- ``D`` (UnionOfIntervals) -- a subset of `\RR`
OUTPUT:
A real number approximating the value of `\inf_D(\max(|f|, |g|))`.
ALGORITHM:
The extreme values must occur at an e... | (x^4+1)
([-Infinity, +Infinity])
sage: nonneg_region(-x^4-1)
()
"""
roots = sorted(f.roots())
sign_changes = [r for r,e in roots if e%2 == 1]
if (f.leading_coefficient() * (-1)**f.degree()) > 0:
sign_changes = [-infinity] + sign_changes
if f.leading_coefficient() > 0:... | 126 | 126 | 422 | 10 | 116 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | inf_max_abs | inf_max_abs | 533 | 575 | 533 | 533 | df3dbd0cb5ebe9152ed66f8002096cbe9beee7b5 | bigcode/the-stack | train |
49f82ddc5569c638aeb3ddb2 | train | function | def eps(err, is_real):
r"""
Return a Real or Complex interval centered on 0 with radius err.
INPUT:
- ``err`` (real) -- a positive real number, the radius of the interval
- ``is_real`` (boolean) -- if True, returns a real interval in
RIF, else a complex interval in CIF
OUTPUT:
An ... | def eps(err, is_real):
| r"""
Return a Real or Complex interval centered on 0 with radius err.
INPUT:
- ``err`` (real) -- a positive real number, the radius of the interval
- ``is_real`` (boolean) -- if True, returns a real interval in
RIF, else a complex interval in CIF
OUTPUT:
An element of RIF or CIF (... | real_part is None:
real_part = r*(x*(1+r**2)-2*r)/denom
if imag_part is None:
imag_part = -(r**2-1)*y*r/denom
return CIF(real_part, imag_part)
def eps(err, is_real):
| 64 | 64 | 198 | 7 | 57 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | eps | eps | 732 | 759 | 732 | 732 | 39f02ddbe4ee79a9ab3fb1decdc53b0d162ef988 | bigcode/the-stack | train |
72cda18fb22c65f88d954a7c | train | function | def min_on_disk(f, tol, max_iter=10000):
r"""
Returns the minimum of a real-valued complex function on a square.
INPUT:
- ``f`` -- a function from CIF to RIF
- ``tol`` (real) -- a positive real number
- ``max_iter`` (integer, default 10000) -- a positive integer
bounding the number of ... | def min_on_disk(f, tol, max_iter=10000):
| r"""
Returns the minimum of a real-valued complex function on a square.
INPUT:
- ``f`` -- a function from CIF to RIF
- ``tol`` (real) -- a positive real number
- ``max_iter`` (integer, default 10000) -- a positive integer
bounding the number of iterations to be used
OUTPUT:
A... | x = polygen(RR)
sage: f = (x-10)^4+1
sage: g = 2*x^3+100
sage: inf_max_abs(f,g,UnionOfIntervals([1,2,3,4,5,6]))
425.638201706391
sage: r0 = (f-g).roots()[0][0]
sage: r0
5.46053402234697
sage: max(abs(f(r0)),abs(g(r0)))
425.638201706391
"""
... | 252 | 252 | 840 | 14 | 237 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | min_on_disk | min_on_disk | 577 | 656 | 577 | 577 | daf6d18ab7354a5e9e8a32a246c839ff1cdf9604 | bigcode/the-stack | train |
62fb8b9c2db93e8fbe735831 | train | function | def nonneg_region(f):
r"""
Returns the UnionOfIntervals representing the region where ``f`` is non-negative.
INPUT:
- ``f`` (polynomial) -- a univariate polynomial over `\RR`.
OUTPUT:
A UnionOfIntervals representing the set `\{x \in\RR mid f(x) \ge 0\}`.
EXAMPLES::
sage: from s... | def nonneg_region(f):
| r"""
Returns the UnionOfIntervals representing the region where ``f`` is non-negative.
INPUT:
- ``f`` (polynomial) -- a univariate polynomial over `\RR`.
OUTPUT:
A UnionOfIntervals representing the set `\{x \in\RR mid f(x) \ge 0\}`.
EXAMPLES::
sage: from sage.schemes.elliptic_c... | .height import UnionOfIntervals
sage: A = UnionOfIntervals([1,3,5,7])
sage: str(A)
'([1, 3] U [5, 7])'
"""
return repr(self)
def __repr__(self):
r"""
Return the string representation of this UnionOfIntervals.
EXAMPLES::
sage:... | 160 | 160 | 535 | 6 | 154 | bopopescu/sage | src/sage/schemes/elliptic_curves/height.py | Python | nonneg_region | nonneg_region | 488 | 531 | 488 | 488 | af0e7a0f70a2299ff7f1f4420cd95056a3af64bf | bigcode/the-stack | train |
38b188d0788149d144db0313 | train | class | class Normalize(object):
def __init__(self, mean, std, inplace=False):
self.mean = mean
self.std = std
self.inplace = inplace
def __call__(self, images):
normalized = np.stack([F.normalize(x, self.mean, self.std, self.inplace) for x in images])
return normalized
| class Normalize(object):
| def __init__(self, mean, std, inplace=False):
self.mean = mean
self.std = std
self.inplace = inplace
def __call__(self, images):
normalized = np.stack([F.normalize(x, self.mean, self.std, self.inplace) for x in images])
return normalized
| elif rand_num == 1:
return np.rot90(image, k=2, axes=(0, 1))
elif rand_num == 2:
return np.rot90(image, k=3, axes=(0, 1))
else:
return image
class Normalize(object):
| 64 | 64 | 76 | 4 | 59 | DonghyunAhn/sadvirus | dataloader.py | Python | Normalize | Normalize | 88 | 96 | 88 | 88 | 4d81ff22907a24f56145addcb3ab8658210c687e | bigcode/the-stack | train |
11d0bf4e3e50003b3e25469f | train | class | class UnlabeledDataset(Dataset):
def __init__(self, root_dir, transform=None):
self.file_list = glob.glob('./{}/*/*.png'.format(root_dir))
self.transform = transform
def __len__(self):
return len(self.file_list)
def __getitem__(self, idx):
images = Image.open(self.file_list... | class UnlabeledDataset(Dataset):
| def __init__(self, root_dir, transform=None):
self.file_list = glob.glob('./{}/*/*.png'.format(root_dir))
self.transform = transform
def __len__(self):
return len(self.file_list)
def __getitem__(self, idx):
images = Image.open(self.file_list[idx])
if self.transform:... | = [0, 0, 0]
#y[answer] = 1
sample = {'image': image, 'y': torch.Tensor(y)}
if self.transform:
sample['image'] = self.transform(image)
return sample
class UnlabeledDataset(Dataset):
| 63 | 64 | 93 | 8 | 54 | DonghyunAhn/sadvirus | dataloader.py | Python | UnlabeledDataset | UnlabeledDataset | 39 | 51 | 39 | 39 | 635d74fdd563e63a1942481795e5a114fad5cb9b | bigcode/the-stack | train |
33fa1c091b8dcf4646c07ce8 | train | class | class RandomRotate(object):
def __call__(self, images):
rotated = np.stack([self.random_rotate(x) for x in images])
return rotated
def random_rotate(self, image):
rand_num = np.random.randint(0, 4)
if rand_num == 0:
return np.rot90(image, k=1, axes=(0, 1))
... | class RandomRotate(object):
| def __call__(self, images):
rotated = np.stack([self.random_rotate(x) for x in images])
return rotated
def random_rotate(self, image):
rand_num = np.random.randint(0, 4)
if rand_num == 0:
return np.rot90(image, k=1, axes=(0, 1))
elif rand_num == 1:
... | str(year+2015)
img_name = os.path.join(root_dir, self.metadata[year*len(self.metadata)+ idx//5][0])
image = Image.open(img_name)
if self.transform:
img = self.transform(image)
return img, idx
class RandomRotate(object):
| 64 | 64 | 141 | 5 | 58 | DonghyunAhn/sadvirus | dataloader.py | Python | RandomRotate | RandomRotate | 72 | 86 | 72 | 72 | db6e2463d009c1ca9ec1ce3bd33d97695fb26557 | bigcode/the-stack | train |
ced3b6389e560101358b856b | train | class | class ToTensor(object):
def __call__(self, images):
images = images.transpose((0, 3, 1, 2))
return torch.from_numpy(images).float()
| class ToTensor(object):
| def __call__(self, images):
images = images.transpose((0, 3, 1, 2))
return torch.from_numpy(images).float()
| self.mean = mean
self.std = std
self.inplace = inplace
def __call__(self, images):
normalized = np.stack([F.normalize(x, self.mean, self.std, self.inplace) for x in images])
return normalized
class ToTensor(object):
| 63 | 64 | 40 | 5 | 57 | DonghyunAhn/sadvirus | dataloader.py | Python | ToTensor | ToTensor | 99 | 102 | 99 | 99 | f34bb3ac2f6dcccf0f079888232c7ce46c96d0b4 | bigcode/the-stack | train |
3827baa5ed00b88c0799fc03 | train | class | class UnlabeledDataset_year(Dataset):
def __init__(self, metadata, root_dir,transform=None):
self.metadata = pd.read_csv(metadata).values
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.metadata)*5
def __getitem__(self, idx):
y... | class UnlabeledDataset_year(Dataset):
| def __init__(self, metadata, root_dir,transform=None):
self.metadata = pd.read_csv(metadata).values
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.metadata)*5
def __getitem__(self, idx):
year = idx % 5
root_dir = self... | self.transform = transform
def __len__(self):
return len(self.file_list)
def __getitem__(self, idx):
images = Image.open(self.file_list[idx])
if self.transform:
images = self.transform(images)
return images
class UnlabeledDataset_year(Dataset):
| 64 | 64 | 148 | 9 | 54 | DonghyunAhn/sadvirus | dataloader.py | Python | UnlabeledDataset_year | UnlabeledDataset_year | 53 | 70 | 53 | 53 | 00a461ba1b4d0957780550e77f195a11121b4936 | bigcode/the-stack | train |
2d3336d36e7e334d8731d947 | train | class | class ProxyDataset(Dataset):
def __init__(self, metadata, root_dir, transform=None):
self.metadata = pd.read_csv(metadata)
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.metadata)
def __getitem__(self, idx):
assert(idx... | class ProxyDataset(Dataset):
| def __init__(self, metadata, root_dir, transform=None):
self.metadata = pd.read_csv(metadata)
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.metadata)
def __getitem__(self, idx):
assert(idx < len(self))
im... | import os
import glob
import torch
import numpy as np
import pandas as pd
from skimage import io, transform
from torchvision import transforms
import torchvision.transforms.functional as F
from torch.utils.data import Dataset
from PIL import Image
class ProxyDataset(Dataset):
| 57 | 64 | 199 | 6 | 50 | DonghyunAhn/sadvirus | dataloader.py | Python | ProxyDataset | ProxyDataset | 13 | 36 | 13 | 13 | 30fb27b6aa6069fc272871da3d88e1df53f056c9 | bigcode/the-stack | train |
2a5df7eebff5cdcf9ef7baf6 | train | function | @pytest.mark.light
def test_clutrr_v2():
embedding_size = 20
triples, hops = [], []
xxx = []
for i in range(16):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
xxx += [(f'a{i}', 'p', f'c{i}'), (f'a{i}', 'q', f'c{i}'), (f'a{i}', '... | @pytest.mark.light
def test_clutrr_v2():
| embedding_size = 20
triples, hops = [], []
xxx = []
for i in range(16):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
xxx += [(f'a{i}', 'p', f'c{i}'), (f'a{i}', 'q', f'c{i}'), (f'a{i}', 'r', f'c{i}')]
entity_lst = sorted({s... | 1_emb, arg2_emb = encode_arguments(facts=triples, entity_embeddings=entity_embeddings,
entity_to_idx=entity_to_index)
batch_size = xp.shape[0]
fact_size = rel_emb.shape[0]
rel_emb = re... | 249 | 249 | 832 | 12 | 236 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v2 | test_clutrr_v2 | 110 | 182 | 110 | 111 | a14e1b6efd555164942007701d12e396cbaab25a | bigcode/the-stack | train |
c1f8335f514520f695f6fd1b | train | function | @pytest.mark.light
def test_clutrr_v3():
embedding_size = 20
batch_size = 8
torch.manual_seed(0)
triples, hops = [], []
for i in range(32):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
entity_lst = sorted({s for (s, _, _) in ... | @pytest.mark.light
def test_clutrr_v3():
| embedding_size = 20
batch_size = 8
torch.manual_seed(0)
triples, hops = [], []
for i in range(32):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
entity_lst = sorted({s for (s, _, _) in triples + hops} | {o for (_, _, o) in tri... | 1, 1)
arg1_emb = arg1_emb.view(1, fact_size, -1).repeat(batch_size, 1, 1)
arg2_emb = arg2_emb.view(1, fact_size, -1).repeat(batch_size, 1, 1)
nb_facts = torch.tensor([fact_size for _ in range(batch_size)], dtype=torch.long)
... | 256 | 256 | 1,248 | 12 | 243 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v3 | test_clutrr_v3 | 185 | 306 | 185 | 186 | d871433622bc90d35e4fdb97d4a5b20c150e77e4 | bigcode/the-stack | train |
31c5cff240560ccb1aca7abd | train | function | def encode_relation(facts: List[Tuple[str, str, str]],
relation_embeddings: nn.Embedding,
relation_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tensor:
indices_np = np.array([relation_to_idx[r] for _, r, _ in facts], dtype=np.int64)
... | def encode_relation(facts: List[Tuple[str, str, str]],
relation_embeddings: nn.Embedding,
relation_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tensor:
| indices_np = np.array([relation_to_idx[r] for _, r, _ in facts], dtype=np.int64)
indices = torch.from_numpy(indices_np)
if device is not None:
indices = indices.to(device)
return relation_embeddings(indices)
| make_batches
from typing import List, Dict, Tuple, Optional
import pytest
def encode_relation(facts: List[Tuple[str, str, str]],
relation_embeddings: nn.Embedding,
relation_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tensor:
| 64 | 64 | 101 | 47 | 16 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | encode_relation | encode_relation | 23 | 31 | 23 | 26 | 81304f0a7b4e8f473109653d90bbfecabc23f6ec | bigcode/the-stack | train |
220251c2dfb0a98c8794ed49 | train | function | @pytest.mark.light
def test_clutrr_v7():
torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'... | @pytest.mark.light
def test_clutrr_v7():
| torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'),
('f', 'q', 'g'),
('g',... | _allclose(inf1_np, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.assert_allclose(inf2_np, [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.assert_allclose(inf3_np, [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.as... | 256 | 256 | 2,207 | 12 | 244 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v7 | test_clutrr_v7 | 757 | 932 | 757 | 758 | 4a45889b5228dfca6abaccb63667dff829632469 | bigcode/the-stack | train |
7851dd4011ddcb4a7ed5b464 | train | function | @pytest.mark.light
def test_clutrr_v5():
torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'... | @pytest.mark.light
def test_clutrr_v5():
| torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'),
('f', 'q', 'g'),
('g',... | 0
xo_np[0] = 1
xs_np[1] = 2
xp_np[1] = 1
xo_np[1] = 3
xs = torch.from_numpy(xs_np)
xp = torch.from_numpy(xp_np)
xo = torch.from_numpy(xo_np)
xs_emb = entity_embeddings(xs)
xp_emb = predicate_embeddings(xp)
... | 256 | 256 | 2,113 | 12 | 244 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v5 | test_clutrr_v5 | 402 | 573 | 402 | 403 | b06ca67f03a505dc0da7450fe65887ab120650ee | bigcode/the-stack | train |
0d03a9ebac3f5bbb78ce0128 | train | function | def encode_arguments(facts: List[Tuple[str, str, str]],
entity_embeddings: nn.Embedding,
entity_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tuple[Tensor, Tensor]:
indices_np = np.array([[entity_to_idx[s], entity_to_idx[o]] for s, _... | def encode_arguments(facts: List[Tuple[str, str, str]],
entity_embeddings: nn.Embedding,
entity_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tuple[Tensor, Tensor]:
| indices_np = np.array([[entity_to_idx[s], entity_to_idx[o]] for s, _, o in facts], dtype=np.int64)
indices = torch.from_numpy(indices_np)
if device is not None:
indices = indices.to(device)
emb = entity_embeddings(indices)
return emb[:, 0, :], emb[:, 1, :]
| indices = indices.to(device)
return relation_embeddings(indices)
def encode_arguments(facts: List[Tuple[str, str, str]],
entity_embeddings: nn.Embedding,
entity_to_idx: Dict[str, int],
device: Optional[torch.device] = None) -> Tuple[Tensor, Tens... | 64 | 64 | 126 | 51 | 13 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | encode_arguments | encode_arguments | 34 | 43 | 34 | 37 | a51458b21365ac49529a9e3ab18caad399abdd8c | bigcode/the-stack | train |
876632be8256e1e4faaa3269 | train | function | @pytest.mark.light
def test_clutrr_v1():
embedding_size = 50
triples, hops = [], []
for i in range(16):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
entity_lst = sorted({e for (e, _, _) in triples + hops} | {e for (e, _, e) in triples... | @pytest.mark.light
def test_clutrr_v1():
| embedding_size = 50
triples, hops = [], []
for i in range(16):
triples += [(f'a{i}', 'p', f'b{i}'), (f'b{i}', 'q', f'c{i}')]
hops += [(f'a{i}', 'r', f'c{i}')]
entity_lst = sorted({e for (e, _, _) in triples + hops} | {e for (e, _, e) in triples + hops})
predicate_lst = sorted({p f... | _np = np.array([relation_to_idx[r] for _, r, _ in facts], dtype=np.int64)
indices = torch.from_numpy(indices_np)
if device is not None:
indices = indices.to(device)
return relation_embeddings(indices)
def encode_arguments(facts: List[Tuple[str, str, str]],
entity_embeddings: n... | 190 | 191 | 639 | 12 | 178 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v1 | test_clutrr_v1 | 46 | 107 | 46 | 47 | 3185bc32215c5ef1bb8d44bda44acff280add11a | bigcode/the-stack | train |
7c18cb0b3929ff02e7c4efe7 | train | function | @pytest.mark.light
def test_clutrr_v6():
torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'... | @pytest.mark.light
def test_clutrr_v6():
| torch.set_num_threads(multiprocessing.cpu_count())
embedding_size = 20
torch.manual_seed(0)
rs = np.random.RandomState(0)
triples = [
('a', 'p', 'b'),
('b', 'q', 'c'),
('c', 'p', 'd'),
('d', 'q', 'e'),
('e', 'p', 'f'),
('f', 'q', 'g'),
('g',... | _allclose(inf1_np, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.assert_allclose(inf2_np, [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.assert_allclose(inf3_np, [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], rtol=1e-1, atol=1e-1)
np.testing.assert_allclos... | 256 | 256 | 2,145 | 12 | 244 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v6 | test_clutrr_v6 | 576 | 754 | 576 | 577 | dd93ef536d7351b4634d2548557dc176ca0a1214 | bigcode/the-stack | train |
37d490e2f611e123af101062 | train | function | @pytest.mark.light
def test_clutrr_v4():
embedding_size = 50
rs = np.random.RandomState(0)
for _ in range(4):
with torch.no_grad():
triples = [
('a', 'p', 'b'),
('c', 'q', 'd'),
('e', 'q', 'f'),
('g', 'q', 'h'),
... | @pytest.mark.light
def test_clutrr_v4():
| embedding_size = 50
rs = np.random.RandomState(0)
for _ in range(4):
with torch.no_grad():
triples = [
('a', 'p', 'b'),
('c', 'q', 'd'),
('e', 'q', 'f'),
('g', 'q', 'h'),
('i', 'q', 'l'),
('... | _emb, xs_emb, xo_emb, facts=facts, nb_facts=nb_facts,
entity_embeddings=emb, nb_entities=_nb_entities)
labels_np = np.zeros(xs_np.shape[0])
labels_np[:nb_positives] = 1
labels = torch.from_numpy(labels_np).float()
# for s, p, o, l in zip(xs_np, xp_np, xo_np... | 255 | 255 | 853 | 12 | 242 | mmorris44/ctp | tests/kbcr/clutrr/test_clutrr.py | Python | test_clutrr_v4 | test_clutrr_v4 | 309 | 399 | 309 | 310 | 8ab3e932c4a6d3aa9e38883a1ddb0072fcd30707 | bigcode/the-stack | train |
3ee68d76fd4722cf4ac483b9 | train | function | def get_data(request):
data = {
'male_data': [41, 26, 57, 47, 49, 40, 67, 68, 24, 26],
'female_data': [62, 39, 67, 33, 58, 67, 50, 48, 21, 30],
'label_data': ['13-17', '18-24', '25-34', '34-44', '45-54', '55-64'],
}
return JsonResponse(data)
| def get_data(request):
| data = {
'male_data': [41, 26, 57, 47, 49, 40, 67, 68, 24, 26],
'female_data': [62, 39, 67, 33, 58, 67, 50, 48, 21, 30],
'label_data': ['13-17', '18-24', '25-34', '34-44', '45-54', '55-64'],
}
return JsonResponse(data)
| from django.shortcuts import render
from django.http import JsonResponse
def home(request):
return render(request, 'index.html')
def get_data(request):
| 30 | 64 | 122 | 5 | 25 | madhu0309/djanogo-visualization | Visualization/Visualizations/views.py | Python | get_data | get_data | 7 | 15 | 7 | 8 | 17d42e7ee049d4992fa062e4d11559736d76894f | bigcode/the-stack | train |
39ce798bab644bc3ca9d054d | train | function | def home(request):
return render(request, 'index.html')
| def home(request):
| return render(request, 'index.html')
| from django.shortcuts import render
from django.http import JsonResponse
def home(request):
| 17 | 64 | 12 | 4 | 12 | madhu0309/djanogo-visualization | Visualization/Visualizations/views.py | Python | home | home | 4 | 5 | 4 | 4 | 2c1d615a60ff97a00bb758a1d6e6ef6b2a0f6616 | bigcode/the-stack | train |
0bfe51b432ddc8fd4b3e09db | train | function | def parse_meta_data(meta_file):
"""Parse the meta data json file generated by Trinh as of August 6th
Change this function if the meta data json file is modified later
Args:
meta_file: local meta data json file path
Returns:
meta_data: a dictionary with at least the following ke... | def parse_meta_data(meta_file):
| """Parse the meta data json file generated by Trinh as of August 6th
Change this function if the meta data json file is modified later
Args:
meta_file: local meta data json file path
Returns:
meta_data: a dictionary with at least the following keys:
'numFramesReques... | cor_map = get_cor_map(mat)
elif mat.ndim == 4:
cor_map = get_cor_map_4d(mat, select_frames=select_frames, top_cor_map_percentage=20, padding=2, topk=5, shift_times=[0, 1, 2],
return_all=False, plot=False)
label_image, regions = get_label_image(cor_map, min_thresh=min_t... | 155 | 155 | 518 | 7 | 147 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | parse_meta_data | parse_meta_data | 519 | 560 | 519 | 519 | f0866e760994a296343cfdd82f4ec48d0a5977b4 | bigcode/the-stack | train |
99e0ce1e8f47fd8ea7f00f76 | train | function | def detrend_high_magnification(mat, skip_segments=1, num_segments=6, period=500, train_size_left=0, train_size_right=350,
linear_order=3, plot=False, signal_start=0, signal_end=100, filepath=None, size=(-1, 180, 300),
device=torch.device('cuda'), start0=No... | def detrend_high_magnification(mat, skip_segments=1, num_segments=6, period=500, train_size_left=0, train_size_right=350,
linear_order=3, plot=False, signal_start=0, signal_end=100, filepath=None, size=(-1, 180, 300),
device=torch.device('cuda'), start0=No... | if mat is None:
mat = load_file(filepath=filepath, size=size, dtype=np.uint16, device=device)
L, nrow, ncol = mat.size()
if period == 'unknown':
period = L
if signal_end == 'period':
signal_end = period
train_idx = ([range(skip_segments*period)] +
[range(i*pe... | .show()
plot_tensor(y_adj.mean(1), marker='o-', markersize=1, alpha=0.8)
plt.axvline(test_left, color='g', linestyle='-.')
plt.axvline(test_right, color='g', linestyle='-.')
plt.title(f'Detrended segment {i+1}: min={y_adj.min().item():.0f} mean={y_adj.mean().item():.0f} m... | 207 | 207 | 691 | 91 | 115 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | detrend_high_magnification | detrend_high_magnification | 147 | 191 | 147 | 149 | 991736987e800046b7c30ff8e2efe80c780f66a6 | bigcode/the-stack | train |
64ac83f889985a29fe2a3c91 | train | function | def get_size_from_txt(filepath):
meta_data = pandas.read_csv(filepath, sep='\t', header=None, index_col=0)
size = int(meta_data.loc['frames']), int(meta_data.loc['ywidth']), int(meta_data.loc['xwidth'])
return size
| def get_size_from_txt(filepath):
| meta_data = pandas.read_csv(filepath, sep='\t', header=None, index_col=0)
size = int(meta_data.loc['frames']), int(meta_data.loc['ywidth']), int(meta_data.loc['xwidth'])
return size
| visualization import plot_tensor, plot_image_label_overlay, imshow, plot_hist, plot_curves, plot_singular_values, save_gif_file, get_good_colors
from train import step_decompose
from denoise import get_denoised_mat
from segmentation import split_clusters
def get_size_from_txt(filepath):
| 64 | 64 | 58 | 7 | 56 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | get_size_from_txt | get_size_from_txt | 23 | 26 | 23 | 23 | 07754bee563bc5b91db6712d209a3b0ea26bed0e | bigcode/the-stack | train |
fcabc40aabb34b9fbeb2a732 | train | function | def load_mat(exp_id, meta_data, folder, astype='float32', device=torch.device('cuda')):
file_meta = meta_data[exp_id]
ncol, nrow, L = file_meta['xwidth'], file_meta['ywidth'], file_meta['frames']
mat = load_file(filepath=os.path.join(folder, exp_id + '.bin'), size=[L, nrow, ncol], dtype=np.uint16, astype=as... | def load_mat(exp_id, meta_data, folder, astype='float32', device=torch.device('cuda')):
| file_meta = meta_data[exp_id]
ncol, nrow, L = file_meta['xwidth'], file_meta['ywidth'], file_meta['frames']
mat = load_file(filepath=os.path.join(folder, exp_id + '.bin'), size=[L, nrow, ncol], dtype=np.uint16, astype=astype, device=device)
return mat
| device=torch.device('cuda')):
array = np.fromfile(filepath, dtype=np.uint16).reshape(size).astype(astype)
mat = torch.from_numpy(array).to(device)
return mat
def load_mat(exp_id, meta_data, folder, astype='float32', device=torch.device('cuda')):
| 64 | 64 | 103 | 23 | 40 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | load_mat | load_mat | 33 | 37 | 33 | 33 | d4aec3ec864a9c3863825522883ea5b605286699 | bigcode/the-stack | train |
319a570e956cd595fe35f639 | train | function | def extract_single_trace(mat, label_mask, percentile=50):
binary_mask = label_mask > 0
if percentile > 0:
binary_mask = label_mask > get_percentile(label_mask[binary_mask], percentile)
trace = (mat*label_mask*binary_mask).sum(-1).sum(-1) / label_mask[binary_mask].sum()
return trace
| def extract_single_trace(mat, label_mask, percentile=50):
| binary_mask = label_mask > 0
if percentile > 0:
binary_mask = label_mask > get_percentile(label_mask[binary_mask], percentile)
trace = (mat*label_mask*binary_mask).sum(-1).sum(-1) / label_mask[binary_mask].sum()
return trace
| return cor_global, label_image, regions
def get_percentile(a, percentile):
if isinstance(a, torch.Tensor):
a = a.detach().cpu().numpy()
return np.percentile(a.reshape(-1), q=percentile)
def extract_single_trace(mat, label_mask, percentile=50):
| 63 | 64 | 81 | 13 | 50 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | extract_single_trace | extract_single_trace | 219 | 224 | 219 | 219 | 9cfb022029fcf88f6abf3aca6811bbae7c33fa7a | bigcode/the-stack | train |
ca5aa521f6e691ca186739c3 | train | function | def extract_super_pixels(mat_adj=None, test_left=None, test_right=None, mat_cat=None, num_neighbors=8, cor_choice='mean', connectivity=None,
min_pixels=50, image=None, plot=False, use_mean_image=False):
if image is None:
if mat_cat is None:
mat_cat = torch.cat([m[test_l... | def extract_super_pixels(mat_adj=None, test_left=None, test_right=None, mat_cat=None, num_neighbors=8, cor_choice='mean', connectivity=None,
min_pixels=50, image=None, plot=False, use_mean_image=False):
| if image is None:
if mat_cat is None:
mat_cat = torch.cat([m[test_left:test_right] for m in mat_adj], dim=0)
cor_global = neighbor_cor(mat_cat, neighbors=num_neighbors, choice=cor_choice, plot=plot,
title='correlation map')
if use_mean_image:
... | if return_mat:
return mat, mat_adj
else:
return mat_adj
def extract_super_pixels(mat_adj=None, test_left=None, test_right=None, mat_cat=None, num_neighbors=8, cor_choice='mean', connectivity=None,
min_pixels=50, image=None, plot=False, use_mean_image=False):
| 71 | 71 | 238 | 51 | 19 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | extract_super_pixels | extract_super_pixels | 194 | 212 | 194 | 195 | 6a7a4a710f04d6d65cdab6d95b8de855c9597887 | bigcode/the-stack | train |
1cbec56862a663e652c8ad31 | train | function | def extract_traces(mat, softmask, label_image, regions=None, percentile=50, median_detrend=False):
"""
Args:
label_image: background: 0, labels: 1, 2, 3, ... (no skipping)
"""
# assert len(np.unique(label_image)) == label_image.max()
if mat.dtype == torch.float16:
mat = mat.float()
... | def extract_traces(mat, softmask, label_image, regions=None, percentile=50, median_detrend=False):
| """
Args:
label_image: background: 0, labels: 1, 2, 3, ... (no skipping)
"""
# assert len(np.unique(label_image)) == label_image.max()
if mat.dtype == torch.float16:
mat = mat.float()
if regions is None:
if isinstance(label_image, torch.Tensor):
label_image_ =... | (-1), q=percentile)
def extract_single_trace(mat, label_mask, percentile=50):
binary_mask = label_mask > 0
if percentile > 0:
binary_mask = label_mask > get_percentile(label_mask[binary_mask], percentile)
trace = (mat*label_mask*binary_mask).sum(-1).sum(-1) / label_mask[binary_mask].sum()
r... | 115 | 115 | 385 | 25 | 89 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | extract_traces | extract_traces | 226 | 260 | 226 | 226 | 47db9b94a4b4a233c86c866caae741ca0c947451 | bigcode/the-stack | train |
3825e6a113f234c6fc51e7b8 | train | function | def refine_segmentation(submats, regions, label_image, min_pixels=50, min_pixels_super=900, connectivity=None):
for label_idx in range(1, len(submats)+1):
if (label_image==label_idx).sum() >= min_pixels_super:
submat = submats[label_idx-1]
minr, minc, maxr, maxc = regions[label_idx-1... | def refine_segmentation(submats, regions, label_image, min_pixels=50, min_pixels_super=900, connectivity=None):
| for label_idx in range(1, len(submats)+1):
if (label_image==label_idx).sum() >= min_pixels_super:
submat = submats[label_idx-1]
minr, minc, maxr, maxc = regions[label_idx-1].bbox
img = refine_one_label(submat, min_pixels=min_pixels)
label_image[minr:maxr, minc... | _image, regions=regions,
percentile=percentile)
return submats, traces, soft_attention, label_image, regions
else:
return label_image
def refine_segmentation(submats, regions, label_image, min_pixels=50, min_pixels_super=900, connectivity=None):
| 64 | 64 | 163 | 27 | 36 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | refine_segmentation | refine_segmentation | 467 | 477 | 467 | 467 | 6ca9b465002f241bba647cbc33ba00a6b4bef855 | bigcode/the-stack | train |
32962082733f0415c966fad4 | train | function | def get_submat_traces(regions, label_image, seg_idx=0, mat_adj=None, sig_list=None, mat_list=None, mat=None, cor=None,
weighted_denominator=True,
weight_percentile=50, return_name='all', linear_order=3, input_aug=None, beta_left=None, train_size_left=None,
... | def get_submat_traces(regions, label_image, seg_idx=0, mat_adj=None, sig_list=None, mat_list=None, mat=None, cor=None,
weighted_denominator=True,
weight_percentile=50, return_name='all', linear_order=3, input_aug=None, beta_left=None, train_size_left=None,
... | """Use four different methods to calculate traces
'mat_adj': use pre-calculated detrended matrices with linear regression
'mean_bg': use the mean background values to detrend
'y_adj': use the background to detrend with linear regression
'sig_list': use the original values without detrending
... | , minc:maxc].clone()
label_mask[sub_image!=i+1] = 0
trace = extract_single_trace(submat, label_mask, percentile=percentile)
submats.append(submat)
traces.append(trace)
for k in [k for k in locals().keys() if k not in ['submats', 'traces']]:
del locals()[k]
if len(traces) ... | 256 | 256 | 1,602 | 107 | 148 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | get_submat_traces | get_submat_traces | 262 | 383 | 262 | 266 | 1048d0c25f3493b584af9e99e3bb873dd21cae3f | bigcode/the-stack | train |
65b65b8408540d90da601c16 | train | function | def load_file(filepath, size=-1, dtype=np.uint16, astype='float32', device=torch.device('cuda')):
array = np.fromfile(filepath, dtype=np.uint16).reshape(size).astype(astype)
mat = torch.from_numpy(array).to(device)
return mat
| def load_file(filepath, size=-1, dtype=np.uint16, astype='float32', device=torch.device('cuda')):
| array = np.fromfile(filepath, dtype=np.uint16).reshape(size).astype(astype)
mat = torch.from_numpy(array).to(device)
return mat
| header=None, index_col=0)
size = int(meta_data.loc['frames']), int(meta_data.loc['ywidth']), int(meta_data.loc['xwidth'])
return size
def load_file(filepath, size=-1, dtype=np.uint16, astype='float32', device=torch.device('cuda')):
| 64 | 64 | 61 | 26 | 37 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | load_file | load_file | 28 | 31 | 28 | 28 | 9aaeaa7722690a735ad12248a6affbead758a0e8 | bigcode/the-stack | train |
a316f47bf813a3ce9c8bfe49 | train | function | def extract_one_label_data(submats, label_idx):
submat, label_mask, weight = submats[label_idx]
X = torch.log1p(submat - submat.min())
x = X.unsqueeze(0).unsqueeze(0)
y = x * label_mask
return x, y, label_mask, weight
| def extract_one_label_data(submats, label_idx):
| submat, label_mask, weight = submats[label_idx]
X = torch.log1p(submat - submat.min())
x = X.unsqueeze(0).unsqueeze(0)
y = x * label_mask
return x, y, label_mask, weight
| append(trace)
torch.cuda.empty_cache()
torch.set_grad_enabled(is_grad_enabled)
if return_name == 'all':
return traces, submats
else:
return traces[return_name], submats[return_name]
def extract_one_label_data(submats, label_idx):
| 63 | 64 | 73 | 12 | 51 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | extract_one_label_data | extract_one_label_data | 386 | 391 | 386 | 386 | 0f9a7c0a8dc8ea0ecacb48293ee4ba71e0d382f1 | bigcode/the-stack | train |
45716ff9f5aa54c4af3153fb | train | function | def prepare_data(bucket, bin_files=None, data_folder_prefix='.', result_folder='results', verbose=False):
"""Prepare meta data and create save folders
Args:
bucket: google bucket folder to be processed, e.g., gs://broad-opp-voltage/folder_name
bin_files: default None, process all the .bin f... | def prepare_data(bucket, bin_files=None, data_folder_prefix='.', result_folder='results', verbose=False):
| """Prepare meta data and create save folders
Args:
bucket: google bucket folder to be processed, e.g., gs://broad-opp-voltage/folder_name
bin_files: default None, process all the .bin files in the bucket; otherwise only process file(s) specified by bin_files
data_folder_prefix: defa... | meta_data = json.load(f)
except ValueError:
# Trinh's script to generate metadata json file has bugs; these lines are to required to handle it
with open(meta_file, 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
lines = [r... | 168 | 168 | 563 | 22 | 145 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | prepare_data | prepare_data | 562 | 614 | 562 | 562 | da0dce3ff996bcba68b89db6dcea4a269f3b566b | bigcode/the-stack | train |
510f01c03acf57d92ad05718 | train | function | def detrend(mat, start0, end0, train_size_left, train_size_right, linear_order=3, use_mean_bg=False, plot=False, test_left=None, test_right=None,
device=torch.device('cuda'), exp_id=None, meta_data=None, folder=None, show_singular_values=False, **kwargs):
if mat is None:
mat = load_mat(exp_id, ... | def detrend(mat, start0, end0, train_size_left, train_size_right, linear_order=3, use_mean_bg=False, plot=False, test_left=None, test_right=None,
device=torch.device('cuda'), exp_id=None, meta_data=None, folder=None, show_singular_values=False, **kwargs):
| if mat is None:
mat = load_mat(exp_id, meta_data, folder) # from **kwargs
_, nrow, ncol = mat.shape
mat_list = [mat[s:e] for s, e in zip(start0, end0)]
length0 = end0[0] - start0[0]
input_aug = torch.linspace(-2, 2, length0, device=device)
x_train = torch.cat([input_aug[:train_size_left]... | (input_aug)
if train_idx is None:
train_idx = range(mat.shape[0])
beta, trend = linear_regression(X=input_aug[train_idx], Y=mat.reshape(mat.shape[0], -1)[train_idx], order=linear_order,
X_test=input_aug)
trend = trend.reshape(mat.shape)
mat_adj = mat - trend
... | 237 | 237 | 792 | 68 | 168 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | detrend | detrend | 95 | 145 | 95 | 96 | 9fd2eeb58993abeed17bdc417331b34579cc0e14 | bigcode/the-stack | train |
4984c0b28dcb882a7a57db88 | train | function | def attention_map(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/segmentation_count_hardmask.pt',
batch_size=5000, return_detached=True, device=torch.device('cuda')):
if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[4, 8, 16], num_conv=2, n_dim=3,... | def attention_map(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/segmentation_count_hardmask.pt',
batch_size=5000, return_detached=True, device=torch.device('cuda')):
| if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[4, 8, 16], num_conv=2, n_dim=3,
kernel_size=[3, 3, 3], same_shape=True).to(device)
model.load_state_dict(torch.load(filepath))
nrow, ncol = mat.shape[1:]
if batch_size*nrow*ncol > 1e7:
ba... | for k in [k for k in locals().keys() if k!='mat']:
del locals()[k]
torch.cuda.empty_cache()
return mat
def attention_map(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/segmentation_count_hardmask.pt',
batch_size=5000, return_detached=True, device=torch.device('cuda... | 79 | 79 | 265 | 45 | 33 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | attention_map | attention_map | 438 | 455 | 438 | 439 | dad4ef06b3ebc4276f9fcbaa2b82bbc95e33f25e | bigcode/the-stack | train |
95e919fab265ede2524654eb | train | function | def detrend_linear(mat, train_idx=None, linear_order=3, input_min=-2, input_max=2, return_trend=False,
input_transformation=None, device=torch.device('cuda')):
input_aug = torch.linspace(input_min, input_max, mat.shape[0], device=device)
if input_transformation is not None:
input_aug ... | def detrend_linear(mat, train_idx=None, linear_order=3, input_min=-2, input_max=2, return_trend=False,
input_transformation=None, device=torch.device('cuda')):
| input_aug = torch.linspace(input_min, input_max, mat.shape[0], device=device)
if input_transformation is not None:
input_aug = input_transformation(input_aug)
if train_idx is None:
train_idx = range(mat.shape[0])
beta, trend = linear_regression(X=input_aug[train_idx], Y=mat.reshape(mat.s... | plt.axvline(x=signal_length, color='r', linestyle='-.')
plt.title(f'segment {i//period}')
plt.show()
def detrend_linear(mat, train_idx=None, linear_order=3, input_min=-2, input_max=2, return_trend=False,
input_transformation=None, device=torch.device('cuda')):
| 74 | 74 | 247 | 42 | 32 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | detrend_linear | detrend_linear | 73 | 93 | 73 | 74 | 64479a3e33c2977d7d5ec2615b7751455e7382a5 | bigcode/the-stack | train |
04c0ec3b205ca3fb7a50a838 | train | function | def prep_train_data(seg_idx, label_idx, label_image, regions, sig_list=None, mat_list=None, mat_adj=None, cor=None,
return_name='mat_adj'):
traces, submats = get_submat_traces(seg_idx=seg_idx, regions=regions, label_image=label_image, mat_adj=mat_adj, sig_list=sig_list,
... | def prep_train_data(seg_idx, label_idx, label_image, regions, sig_list=None, mat_list=None, mat_adj=None, cor=None,
return_name='mat_adj'):
| traces, submats = get_submat_traces(seg_idx=seg_idx, regions=regions, label_image=label_image, mat_adj=mat_adj, sig_list=sig_list,
mat_list=mat_list, cor=cor, weighted_denominator=True, return_name=return_name, compare=False)
x, y, label_mask, weight = extract_one_label_... | 0).unsqueeze(0)
y = x * label_mask
return x, y, label_mask, weight
def prep_train_data(seg_idx, label_idx, label_image, regions, sig_list=None, mat_list=None, mat_adj=None, cor=None,
return_name='mat_adj'):
| 64 | 64 | 148 | 38 | 25 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | prep_train_data | prep_train_data | 394 | 400 | 394 | 395 | 9d5eb19198b0a593fc9d3b1b8df4bc42a653b521 | bigcode/the-stack | train |
5762291e1bb735379a75aaff | train | function | def basic_segmentation(mat, min_thresh=0.05, min_pixels=50, select_frames=True, show=True, median_detrend=False,
fft=False, fft_max_freq=200):
"""Basic segmentation
Args:
mat: torch.Tensor with shape (nframe, nrow, ncol) or (n_experiments, nframe, nrow, ncol)
min_thresh:... | def basic_segmentation(mat, min_thresh=0.05, min_pixels=50, select_frames=True, show=True, median_detrend=False,
fft=False, fft_max_freq=200):
| """Basic segmentation
Args:
mat: torch.Tensor with shape (nframe, nrow, ncol) or (n_experiments, nframe, nrow, ncol)
min_thresh: float, used by get_label_image
min_pixels: int, used by get_label_image
select_frames: default True, only used when mat.ndim==4, selecting only frames... | if (label_image==label_idx).sum() >= min_pixels_super:
submat = submats[label_idx-1]
minr, minc, maxr, maxc = regions[label_idx-1].bbox
img = refine_one_label(submat, min_pixels=min_pixels)
label_image[minr:maxr, minc:maxc] = img
from skimage.measure import label, re... | 161 | 161 | 538 | 42 | 118 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | basic_segmentation | basic_segmentation | 480 | 517 | 480 | 481 | b12cb8e191aed1c5a2e2e50b7321f3fc367ee4b7 | bigcode/the-stack | train |
a8f3d63b5cc1eac153957fb5 | train | function | def denoise_3d(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/3d_denoise.pt', return_detached=True,
batch_size=5000, device=torch.device('cuda')):
if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[4, 8, 16], num_conv=2, n_dim=3,
... | def denoise_3d(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/3d_denoise.pt', return_detached=True,
batch_size=5000, device=torch.device('cuda')):
| if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[4, 8, 16], num_conv=2, n_dim=3,
kernel_size=[3, 3, 3], same_shape=True).to(device)
model.load_state_dict(torch.load(filepath))
with torch.no_grad():
num_batches = (mat.size(0) + batch_size - ... | !='pred']:
del locals()[k]
torch.cuda.empty_cache()
return pred
def denoise_3d(mat, model=None, filepath='/home/jupyter/notebooks/checkpoints/3d_denoise.pt', return_detached=True,
batch_size=5000, device=torch.device('cuda')):
| 66 | 66 | 221 | 47 | 18 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | denoise_3d | denoise_3d | 422 | 436 | 422 | 423 | 5686b8d076c1cb3cef1bb6b9e5e47a932e3cc608 | bigcode/the-stack | train |
5527e88e4b2b72e7a3310c6d | train | function | def get_percentile(a, percentile):
if isinstance(a, torch.Tensor):
a = a.detach().cpu().numpy()
return np.percentile(a.reshape(-1), q=percentile)
| def get_percentile(a, percentile):
| if isinstance(a, torch.Tensor):
a = a.detach().cpu().numpy()
return np.percentile(a.reshape(-1), q=percentile)
| = image.detach().cpu().numpy()
label_image, regions = get_label_image(image, min_pixels=min_pixels, connectivity=connectivity, plot=False)
if plot:
plot_image_label_overlay(image, label_image)
return cor_global, label_image, regions
def get_percentile(a, percentile):
| 64 | 64 | 41 | 8 | 55 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | get_percentile | get_percentile | 214 | 217 | 214 | 214 | 1f90d840818db1d5dcbf9b80006782b8ef46a186 | bigcode/the-stack | train |
09cca8c087b07f7949eadf7c | train | function | def plot_mean_intensity(mat, detrended=None, plot_detrended=False, plot_segments=False, num_frames=3000, period=500, signal_length=100,
figsize=(20, 10)):
array = mat.mean(-1).mean(-1).cpu()
if detrended is not None and plot_detrended:
array = array - array.min()
xs = [array... | def plot_mean_intensity(mat, detrended=None, plot_detrended=False, plot_segments=False, num_frames=3000, period=500, signal_length=100,
figsize=(20, 10)):
| array = mat.mean(-1).mean(-1).cpu()
if detrended is not None and plot_detrended:
array = array - array.min()
xs = [array]
colors = ['b']
labels = ['mean intensity']
if detrended is not None:
detrended = detrended.mean(-1).mean(-1).cpu()
if plot_detrended:
detr... | _meta = meta_data[exp_id]
ncol, nrow, L = file_meta['xwidth'], file_meta['ywidth'], file_meta['frames']
mat = load_file(filepath=os.path.join(folder, exp_id + '.bin'), size=[L, nrow, ncol], dtype=np.uint16, astype=astype, device=device)
return mat
def plot_mean_intensity(mat, detrended=None, plot_detrended=... | 123 | 123 | 413 | 45 | 77 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | plot_mean_intensity | plot_mean_intensity | 39 | 71 | 39 | 40 | 7dc6d721ea7b12a88d8ce05787c5928e083ab9e3 | bigcode/the-stack | train |
9350a23c3970739eb93ad9a5 | train | function | def denoise_trace(trace, model=None, filepath='/home/jupyter/notebooks/checkpoints/denoise_trace.pt', return_detached=True,
device=torch.device('cuda')):
if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[8, 16, 32], num_conv=2,
n_dim=1, kerne... | def denoise_trace(trace, model=None, filepath='/home/jupyter/notebooks/checkpoints/denoise_trace.pt', return_detached=True,
device=torch.device('cuda')):
| if model is None:
model = UNet(in_channels=1, num_classes=1, out_channels=[8, 16, 32], num_conv=2,
n_dim=1, kernel_size=3).to(device)
model.load_state_dict(torch.load(filepath))
with torch.no_grad():
mean = trace.mean()
std = trace.std()
pred = model... | , label_idx=label_idx)
trace = traces[label_idx]
return x, y, trace, label_mask, weight
def denoise_trace(trace, model=None, filepath='/home/jupyter/notebooks/checkpoints/denoise_trace.pt', return_detached=True,
device=torch.device('cuda')):
| 64 | 64 | 188 | 37 | 26 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | denoise_trace | denoise_trace | 403 | 420 | 403 | 404 | 93ac5c3b57e14e1e3d15cdbffebeb9abeb718d54 | bigcode/the-stack | train |
0d79fb3654b01c2664a4372f | train | function | def entire_pipeline(bucket, result_folder='results', bin_files=None, delete_local_data=True,
apply_spectral_clustering=False, spectral_soft_threshold=True, spectral_cor_threshold=None,
denoise=False, denoise_model_config=None, denoise_loss_threshold=0, denoise_num_epochs=12, den... | def entire_pipeline(bucket, result_folder='results', bin_files=None, delete_local_data=True,
apply_spectral_clustering=False, spectral_soft_threshold=True, spectral_cor_threshold=None,
denoise=False, denoise_model_config=None, denoise_loss_threshold=0, denoise_num_epochs=12, den... | """Entire pipeline to process OPP voltage imaging data
Args:
bucket: google bucket folder containing .bin files and metadata .json files
result_folder: default 'results'
bin_files: default None, process all the .bin files with metadata in the bucket;
otherwise only process t... | response = subprocess.run(command, capture_output=True)
assert response.returncode == 0
meta_data = {}
for file in bin_files:
meta_file = f'{data_folder}/json/{file}_metadata.json'
if not os.path.exists(meta_file):
command = ['gsutil', 'cp', f'{bucket}/{file}_metadata.json'... | 256 | 256 | 2,651 | 104 | 151 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | entire_pipeline | entire_pipeline | 617 | 801 | 617 | 621 | cfee8f807a05554e4dba45e7ce642548e8b0340f | bigcode/the-stack | train |
8e643e4566ac625234280ed0 | train | function | def refine_one_label(submat, min_pixels=50, return_traces=False, percentile=50):
soft_attention = attention_map(submat)
label_image, regions = get_label_image(soft_attention, min_pixels=min_pixels)
if return_traces:
submats, traces = extract_traces(submat, softmask=soft_attention, label_image=label_... | def refine_one_label(submat, min_pixels=50, return_traces=False, percentile=50):
| soft_attention = attention_map(submat)
label_image, regions = get_label_image(soft_attention, min_pixels=min_pixels)
if return_traces:
submats, traces = extract_traces(submat, softmask=soft_attention, label_image=label_image, regions=regions,
percentile=perc... | _detached:
mat = mat.detach()
for k in [k for k in locals().keys() if k!='mat']:
del locals()[k]
torch.cuda.empty_cache()
return mat
def refine_one_label(submat, min_pixels=50, return_traces=False, percentile=50):
| 64 | 64 | 114 | 21 | 42 | BeautyOfWeb/OPP_Analysis | code/optical_electrophysiology.py | Python | refine_one_label | refine_one_label | 457 | 465 | 457 | 457 | c91af57d9ce9b2c7f5c66685d3130b63c078220e | bigcode/the-stack | train |
4f7a8a00aeadf7111254c163 | train | class | class Iwlist(AdvancedConsole):
"""
Command /sbin/iwlist helper
"""
CACHE_DURATION = 2.0
FREQ_2_4GHZ = '2.4GHz'
FREQ_5GHZ = '5GHz'
def __init__(self):
"""
Constructor
"""
AdvancedConsole.__init__(self)
# members
self._command = '/sbin/iwlist... | class Iwlist(AdvancedConsole):
| """
Command /sbin/iwlist helper
"""
CACHE_DURATION = 2.0
FREQ_2_4GHZ = '2.4GHz'
FREQ_5GHZ = '5GHz'
def __init__(self):
"""
Constructor
"""
AdvancedConsole.__init__(self)
# members
self._command = '/sbin/iwlist %s scan'
self.timestam... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import time
from core.libs.console import AdvancedConsole
from core.libs.wpasupplicantconf import WpaSupplicantConf
import core.libs.tools as Tools
class Iwlist(AdvancedConsole):
| 58 | 256 | 1,296 | 8 | 49 | tangb/cleep-desktop | core/libs/iwlist.py | Python | Iwlist | Iwlist | 10 | 183 | 10 | 10 | faa836f1c52b74b124cdb6cf0d5ecd9dd6b215d8 | bigcode/the-stack | train |
8743fc9316513e001e2e814b | train | class | @dependency.requires('identity_api')
@dependency.provider('trust_api')
class Manager(manager.Manager):
"""Default pivot point for the Trust backend.
See :mod:`keystone.common.manager.Manager` for more details on how this
dynamically calls the backend.
"""
_TRUST = "OS-TRUST:trust"
def __init_... | @dependency.requires('identity_api')
@dependency.provider('trust_api')
class Manager(manager.Manager):
| """Default pivot point for the Trust backend.
See :mod:`keystone.common.manager.Manager` for more details on how this
dynamically calls the backend.
"""
_TRUST = "OS-TRUST:trust"
def __init__(self):
super(Manager, self).__init__(CONF.trust.driver)
@staticmethod
def _validate_... | # Copyright 2012 OpenStack Foundation
#
# 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... | 227 | 256 | 1,469 | 19 | 208 | rushiagr/keystone | keystone/trust/core.py | Python | Manager | Manager | 35 | 201 | 35 | 37 | e0e66638545e8307324e9db33ad9d26f283d0da6 | bigcode/the-stack | train |
9252d5db6e96303c57159cb6 | train | class | @six.add_metaclass(abc.ABCMeta)
class Driver(object):
@abc.abstractmethod
def create_trust(self, trust_id, trust, roles):
"""Create a new trust.
:returns: a new trust
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def get_trust(self, trust... | @six.add_metaclass(abc.ABCMeta)
class Driver(object):
@abc.abstractmethod
| def create_trust(self, trust_id, trust, roles):
"""Create a new trust.
:returns: a new trust
"""
raise exception.NotImplemented() # pragma: no cover
@abc.abstractmethod
def get_trust(self, trust_id, deleted=False):
"""Get a trust by the trust id.
:param tr... | == trust_id:
# recursive call to make sure all notifications are sent
try:
self.delete_trust(t['id'])
except exception.TrustNotFound:
# if trust was deleted by concurrent process
# consistency must not suffer
... | 108 | 108 | 360 | 21 | 87 | rushiagr/keystone | keystone/trust/core.py | Python | Driver | Driver | 204 | 251 | 204 | 207 | 5747c4ebc4f945cd8845d679146e130e3d47c125 | bigcode/the-stack | train |
3e9b74102013147e7b18d86b | train | class | class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('id', 'product_id', 'product_name',
'product_price', 'product_revenue', 'status')
| class ArticleSerializer(serializers.ModelSerializer):
| class Meta:
model = Products
fields = ('id', 'product_id', 'product_name',
'product_price', 'product_revenue', 'status')
| page_location')
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Events
fields = ('id', 'event_id', 'event_name', 'event_title',
'event_type', 'start_date', 'end_date', 'next_date', 'status')
class ArticleSerializer(serializers.ModelSerializer):
| 64 | 64 | 43 | 7 | 57 | cnam0203/trivi-backend | recommender/dimadb/serializers.py | Python | ArticleSerializer | ArticleSerializer | 15 | 19 | 15 | 15 | 47c349ec6b78d1c775835d4dd1c406c7bfca2bcb | bigcode/the-stack | train |
d4ca4e51d2e1bb7824166376 | train | class | class ImportInfoSerializer(serializers.ModelSerializer):
class Meta:
model = ImportInfo
fields = '__all__' | class ImportInfoSerializer(serializers.ModelSerializer):
| class Meta:
model = ImportInfo
fields = '__all__' | _date', 'end_date', 'next_date', 'status')
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('id', 'product_id', 'product_name',
'product_price', 'product_revenue', 'status')
class ImportInfoSerializer(serializers.ModelSerializer):
| 64 | 64 | 25 | 8 | 56 | cnam0203/trivi-backend | recommender/dimadb/serializers.py | Python | ImportInfoSerializer | ImportInfoSerializer | 20 | 23 | 20 | 20 | d1734b409b7e4e929391cbbbc4c3994df68892d7 | bigcode/the-stack | train |
c53828bf03244c4e5203ff14 | train | class | class InteractionSerializer(serializers.ModelSerializer):
class Meta:
model = Interaction
fields = ('id', 'interaction_id', 'session_id', 'visit_date', 'event_name', 'operating_system', 'device_category', 'device_brand', 'browser', 'page_title', 'page_location')
| class InteractionSerializer(serializers.ModelSerializer):
| class Meta:
model = Interaction
fields = ('id', 'interaction_id', 'session_id', 'visit_date', 'event_name', 'operating_system', 'device_category', 'device_brand', 'browser', 'page_title', 'page_location')
| from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import Events, Products, Interaction, ImportInfo
class InteractionSerializer(serializers.ModelSerializer):
| 36 | 64 | 62 | 7 | 28 | cnam0203/trivi-backend | recommender/dimadb/serializers.py | Python | InteractionSerializer | InteractionSerializer | 6 | 9 | 6 | 6 | 558c3acfc45dbab8241c4a9bb7aa35d7c35ebb82 | bigcode/the-stack | train |
c616cdf30df92fb8a794f152 | train | class | class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Events
fields = ('id', 'event_id', 'event_name', 'event_title',
'event_type', 'start_date', 'end_date', 'next_date', 'status')
| class EventSerializer(serializers.ModelSerializer):
| class Meta:
model = Events
fields = ('id', 'event_id', 'event_name', 'event_title',
'event_type', 'start_date', 'end_date', 'next_date', 'status')
| Serializer):
class Meta:
model = Interaction
fields = ('id', 'interaction_id', 'session_id', 'visit_date', 'event_name', 'operating_system', 'device_category', 'device_brand', 'browser', 'page_title', 'page_location')
class EventSerializer(serializers.ModelSerializer):
| 64 | 64 | 54 | 7 | 57 | cnam0203/trivi-backend | recommender/dimadb/serializers.py | Python | EventSerializer | EventSerializer | 10 | 14 | 10 | 10 | 63cea2e38fb7c195708e74f3d2c167f79d24fbf3 | bigcode/the-stack | train |
b24136f6897eab3e843b5ff3 | train | function | def test_convert_dataset(mock_data, tmpdir):
dataframe, genres_dict = mock_data
# Prepare a temporary file to load
datapath = tmpdir.mkdir("data")
dataframe.to_csv(os.path.join(datapath, 'data.csv'), index=None)
convert_dataset(path=os.path.join(datapath, 'data.csv'), out_data_path=datapath, genre... | def test_convert_dataset(mock_data, tmpdir):
| dataframe, genres_dict = mock_data
# Prepare a temporary file to load
datapath = tmpdir.mkdir("data")
dataframe.to_csv(os.path.join(datapath, 'data.csv'), index=None)
convert_dataset(path=os.path.join(datapath, 'data.csv'), out_data_path=datapath, genres_dict=genres_dict)
data = pd.read_csv(os.... | ': id_,
'title': title,
'overview': overview,
'genres': genres,
}])
genres_dict = {
53: 'Thriller',
27: 'Horror',
}
return data, genres_dict
def test_convert_dataset(mock_data, tmpdir):
| 64 | 64 | 123 | 10 | 53 | mgzeke0/movie_classifier | tests/test_preprocessing.py | Python | test_convert_dataset | test_convert_dataset | 29 | 38 | 29 | 30 | 810c60e70c46ff5f2bc9a9588b2242b56feff099 | bigcode/the-stack | train |
a50b84c1c87011966190aa12 | train | function | @pytest.fixture
def mock_data():
genres = [{'id': 53, 'name': 'Thriller'}, {'id': 27, 'name': 'Horror'}]
overview = 'Chris was a software developer, he found a strange door in his basement and something came out of it'
title = 'New movie'
id_ = 1
data = pd.DataFrame([{
'id': id_,
'ti... | @pytest.fixture
def mock_data():
| genres = [{'id': 53, 'name': 'Thriller'}, {'id': 27, 'name': 'Horror'}]
overview = 'Chris was a software developer, he found a strange door in his basement and something came out of it'
title = 'New movie'
id_ = 1
data = pd.DataFrame([{
'id': id_,
'title': title,
'overview': ... | import os
import pandas as pd
import pytest
from train.prepare_dataset import convert_dataset, compute_features
@pytest.fixture
def mock_data():
| 29 | 64 | 141 | 7 | 21 | mgzeke0/movie_classifier | tests/test_preprocessing.py | Python | mock_data | mock_data | 10 | 26 | 10 | 11 | 85ba4b00ca24167b9a5f93e5927568a2563ca04a | bigcode/the-stack | train |
51e6d2eadc10034bc8eeac50 | train | function | def test_create_features(mock_data, tmpdir):
dataframe, genres_dict = mock_data
# Prepare a temporary file to load
datapath = tmpdir.mkdir("data")
dataframe.to_csv(os.path.join(datapath, 'movies.csv'), index=None)
assert compute_features(str(datapath), datapath, save_to_disk=False)
| def test_create_features(mock_data, tmpdir):
| dataframe, genres_dict = mock_data
# Prepare a temporary file to load
datapath = tmpdir.mkdir("data")
dataframe.to_csv(os.path.join(datapath, 'movies.csv'), index=None)
assert compute_features(str(datapath), datapath, save_to_disk=False)
| .csv'), out_data_path=datapath, genres_dict=genres_dict)
data = pd.read_csv(os.path.join(datapath, 'movies.csv'))
assert data['genres_list'].apply(eval).tolist()[0] == [53, 27]
def test_create_features(mock_data, tmpdir):
| 64 | 64 | 73 | 10 | 54 | mgzeke0/movie_classifier | tests/test_preprocessing.py | Python | test_create_features | test_create_features | 41 | 47 | 41 | 41 | 90a34c4127090ba4abe285a0cd0210571deb145e | bigcode/the-stack | train |
972dae8c9afe7e0ed2781616 | train | class | class Rectangle(object):
def __init__(self, x, y, width=None, height=None, flag=None, data=None):
# Object information
self.width = width
self.height = height
# Scale data
self.scaleDeltaX = 0
self.scaleDeltaY = 0
self._scaleX = 1
self._scaleY = 1
... | class Rectangle(object):
| def __init__(self, x, y, width=None, height=None, flag=None, data=None):
# Object information
self.width = width
self.height = height
# Scale data
self.scaleDeltaX = 0
self.scaleDeltaY = 0
self._scaleX = 1
self._scaleY = 1
# Positon data
... | from gem import vector
from gem import matrix
from ed2d.physics import aabb
class Rectangle(object):
| 23 | 256 | 1,291 | 4 | 18 | explosiveduck/cubix | ed2d/physics/rectangle.py | Python | Rectangle | Rectangle | 5 | 142 | 5 | 5 | ae3b3fb1ffeb9f5cca59d5d6dd92b607c2bff81b | bigcode/the-stack | train |
62899c5b37978a24f763ab8d | train | function | def onEndSpeaking(text):
mouth.setmouth(90,120)
jaw.moveTo(95)
sleep(.5)
mouth.setmouth(110,120)
| def onEndSpeaking(text):
| mouth.setmouth(90,120)
jaw.moveTo(95)
sleep(.5)
mouth.setmouth(110,120)
| mouth(110,120)
mouth.autoAttach = False
speech = Runtime.createAndStart("Speech","MarySpeech")
print ("these are the voices I can have", speech.getVoices())
speech.setVoice('cmu-bdl-hsmm')
mouth.setMouth(speech)
def onEndSpeaking(text):
| 64 | 64 | 35 | 6 | 58 | rv8flyboy/pyrobotlab | home/Mats/MouthControl.py | Python | onEndSpeaking | onEndSpeaking | 14 | 18 | 14 | 14 | a9ba397ed4b41be9248ea5be3a98d98706283579 | bigcode/the-stack | train |
ecd9cfc3d15f308e49a36576 | train | class | class ServicesTest(utils.TestCase):
def test_list_services(self):
svs = cs.services.list()
cs.assert_called('GET', '/os-services')
self.assertEqual(len(svs), 3)
[self.assertTrue(isinstance(s, services.Service)) for s in svs]
def test_list_services_with_hostname(self):
s... | class ServicesTest(utils.TestCase):
| def test_list_services(self):
svs = cs.services.list()
cs.assert_called('GET', '/os-services')
self.assertEqual(len(svs), 3)
[self.assertTrue(isinstance(s, services.Service)) for s in svs]
def test_list_services_with_hostname(self):
svs = cs.services.list(host='host2')
... | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES ... | 149 | 149 | 497 | 7 | 142 | jamielennox/python-cinderclient | cinderclient/tests/v1/test_services.py | Python | ServicesTest | ServicesTest | 24 | 66 | 24 | 25 | 0ea5afc638039461572d264828df8888abb74cc8 | bigcode/the-stack | train |
f57da267c4f503dfa3478063 | train | class | class TestRiskTypeListView(APITestCase):
def setUp(self):
self.records = 5
for i in range(self.records):
obj = RiskType.objects.create(name='test')
risk_field_data = {
'risk_type': obj,
'field_type': RiskField.TYPE_CHAR,
'label'... | class TestRiskTypeListView(APITestCase):
| def setUp(self):
self.records = 5
for i in range(self.records):
obj = RiskType.objects.create(name='test')
risk_field_data = {
'risk_type': obj,
'field_type': RiskField.TYPE_CHAR,
'label': 'char'
}
RiskFi... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from ..models import RiskType, RiskField
from ..serializers import RiskTypeSerializer
class TestRiskTy... | 74 | 135 | 453 | 10 | 63 | intellisense/risks | backend/apps/risks/test/test_views.py | Python | TestRiskTypeListView | TestRiskTypeListView | 13 | 55 | 13 | 13 | 71cfa889b8bfcb1fbb55a2d0f1afa876a6dd64c8 | bigcode/the-stack | train |
e90b4bc0bef5cc6b165b16a7 | train | class | class TestFieldTypesView(APITestCase):
def setUp(self):
self.endpoint = reverse('api:field_types')
self.api_client = APIClient()
def test_get(self):
data = [{'field_type': k, 'name': v} for k, v in RiskField.FIELD_TYPES]
response = self.api_client.get(self.endpoint)
self... | class TestFieldTypesView(APITestCase):
| def setUp(self):
self.endpoint = reverse('api:field_types')
self.api_client = APIClient()
def test_get(self):
data = [{'field_type': k, 'name': v} for k, v in RiskField.FIELD_TYPES]
response = self.api_client.get(self.endpoint)
self.assertEqual(response.data, data)
... | _CONTENT)
self.assertEqual(RiskType.objects.count(), 0)
self.assertEqual(RiskField.objects.count(), 0)
def test_not_allowed_post(self):
response = self.api_client.post(self.endpoint, data={}, format='json')
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
c... | 77 | 77 | 257 | 9 | 68 | intellisense/risks | backend/apps/risks/test/test_views.py | Python | TestFieldTypesView | TestFieldTypesView | 113 | 138 | 113 | 113 | 7c52b2c09363760545799ea40c3df9e699893f05 | bigcode/the-stack | train |
2cf85921c571b477d5ddc2ba | train | class | class TestRiskTypeDetailView(APITestCase):
def setUp(self):
self.risk_type = RiskType.objects.create(name='test')
risk_field_data = {
'risk_type': self.risk_type,
'field_type': RiskField.TYPE_CHAR,
'label': 'char'
}
self.risk_field = RiskField.obje... | class TestRiskTypeDetailView(APITestCase):
| def setUp(self):
self.risk_type = RiskType.objects.create(name='test')
risk_field_data = {
'risk_type': self.risk_type,
'field_type': RiskField.TYPE_CHAR,
'label': 'char'
}
self.risk_field = RiskField.objects.create(**risk_field_data)
self.... | .api_client.post(self.endpoint, data=self.invalid_payload, format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_not_allowed_put(self):
response = self.api_client.put(self.endpoint, data=self.data, format='json')
self.assertEqual(response.status_code, s... | 166 | 166 | 556 | 10 | 156 | intellisense/risks | backend/apps/risks/test/test_views.py | Python | TestRiskTypeDetailView | TestRiskTypeDetailView | 58 | 110 | 58 | 58 | 3a425a3c4a35fbe44e255e7b055b265c74903f83 | bigcode/the-stack | train |
d9a72fe4eedb22578fdf4026 | train | function | def getTableDict(s_list, table, join):
# table_dict = {}
tables = [table]
for j in join:
tables.append(j.split('join ')[1].split(' ')[0])
for t in tables:
if len(join) == 0:
s_list.append("df = pd.read_csv('{0}.csv')".format(t))
else:
s_list.append("{0} = ... | def getTableDict(s_list, table, join):
# table_dict = {}
| tables = [table]
for j in join:
tables.append(j.split('join ')[1].split(' ')[0])
for t in tables:
if len(join) == 0:
s_list.append("df = pd.read_csv('{0}.csv')".format(t))
else:
s_list.append("{0} = pd.read_csv('{0}.csv')".format(t))
for t in tables:
... | import pandas as pd
import re
def getTableDict(s_list, table, join):
# table_dict = {}
| 25 | 64 | 192 | 17 | 7 | BuyiCheng/QueryTranslator | dataframetl.py | Python | getTableDict | getTableDict | 4 | 22 | 4 | 5 | 489ba773ed9d69db48461749d422dbac75b95966 | bigcode/the-stack | train |
4b5830bafed250a3148dab81 | train | function | def parse_group(s_list, group, projection, order, having):
if len(group) == 0:
return s_list
group = [g.replace('.', '_') for g in group]
s_list.append("df = df.groupby({}, sort=False)".format(str(group)))
# df = df.groupby(group, sort=False)
agg_dict = {}
attributes = projection[:]
... | def parse_group(s_list, group, projection, order, having):
| if len(group) == 0:
return s_list
group = [g.replace('.', '_') for g in group]
s_list.append("df = df.groupby({}, sort=False)".format(str(group)))
# df = df.groupby(group, sort=False)
agg_dict = {}
attributes = projection[:]
having_attrs, _ = parse_where([],having)
for h in havin... | ''
if len(where_list) >=1:
key, result = parse_condition(where_list[0],isHaving)
keys.append(key)
for i, l in enumerate(logic_list):
key, r = parse_condition(where_list[i+1],isHaving)
result = result + logic_map[l.strip()] + r
s_list.append('df = df['+result+']')
return ... | 104 | 104 | 349 | 14 | 89 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_group | parse_group | 127 | 160 | 127 | 127 | ae79a298bd61e7625866ff0126ff54a671613167 | bigcode/the-stack | train |
a2f274580c0b562e2cd270cc | train | function | def getResult(sql_dict):
if len(sql_dict['projection']) == 1 and sql_dict['projection'][0] == '*':
sql_dict['projection'] = []
s_list = []
s_list = getTableDict(s_list, sql_dict['table'], sql_dict['join'])
s_list = parse_join(s_list, sql_dict['table'], sql_dict['join'])
_, s_list = parse_wh... | def getResult(sql_dict):
| if len(sql_dict['projection']) == 1 and sql_dict['projection'][0] == '*':
sql_dict['projection'] = []
s_list = []
s_list = getTableDict(s_list, sql_dict['table'], sql_dict['join'])
s_list = parse_join(s_list, sql_dict['table'], sql_dict['join'])
_, s_list = parse_where(s_list, sql_dict['whe... | _list.append("df = df[{}]".format(group))
else:
attributes = [a.replace('.', '_') for a in attributes]
# df = df[attributes]
s_list.append("df = df[{}]".format(attributes))
return s_list
def getResult(sql_dict):
| 64 | 64 | 205 | 6 | 57 | BuyiCheng/QueryTranslator | dataframetl.py | Python | getResult | getResult | 220 | 238 | 220 | 220 | 7ac6e4be6ee9bbcf2f8e0276595e4f57ee6d7445 | bigcode/the-stack | train |
6eeef7ac097fd7b7f96521ba | train | function | def parse_between(item, isNot, isHaving):
key, value = item.split(' between ')
key = key.strip()
if isHaving:
key = key.replace('.','_')
v1,v2 = [handle_value_type(i.strip()) for i in value.split(' and ')]
n = '~' if isNot else ''
return key, "{3}(df['{0}'] >= {1})&{3}(df['{0}'] <= {2})"... | def parse_between(item, isNot, isHaving):
| key, value = item.split(' between ')
key = key.strip()
if isHaving:
key = key.replace('.','_')
v1,v2 = [handle_value_type(i.strip()) for i in value.split(' and ')]
n = '~' if isNot else ''
return key, "{3}(df['{0}'] >= {1})&{3}(df['{0}'] <= {2})".format(key, v1, v2, n)
| :
pass
try:
return float(value)
except ValueError:
pass
try:
import unicodedata
return unicodedata.numeric(value)
except (TypeError, ValueError):
pass
return value
def parse_between(item, isNot, isHaving):
| 64 | 64 | 116 | 11 | 52 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_between | parse_between | 61 | 68 | 61 | 61 | 540ec853ec9c392a1a23f04f55f4b132a963619a | bigcode/the-stack | train |
2922bfa9a08bf5d77e794788 | train | function | def parse_where(s_list, where, isHaving=False):
if where == '':
return [],s_list
# repalce between and with *between*
while where.find(' between ') != -1:
between_index = where.find(' between ') + 1
and_index = between_index + where[between_index:].find(' and ') + 1
where = w... | def parse_where(s_list, where, isHaving=False):
| if where == '':
return [],s_list
# repalce between and with *between*
while where.find(' between ') != -1:
between_index = where.find(' between ') + 1
and_index = between_index + where[between_index:].find(' and ') + 1
where = where[:between_index]+'*between*'+where[between_i... | key,value = [i.strip() for i in item.split(compare)]
if isHaving:
key = key.replace('.','_')
result = "{}(df['{}'] {} {})".format(n, key, compare, value)
print("result:",result)
return key, result
def parse_where(s_list, where, isHaving=False):
| 75 | 75 | 252 | 12 | 62 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_where | parse_where | 105 | 124 | 105 | 105 | 36c963edb3c536043b5c4268814b4df550ba2790 | bigcode/the-stack | train |
fc21c17f0c1963acf6e02f7f | train | function | def parse_condition(item, isHaving):
item = item.replace('*between*', 'between').replace('*and*','and')
if item.startswith('not '):
isNot = True
item = item[len('not '):]
else:
isNot = False
n = '~' if isNot else ''
if item.find(' between ') != -1:
key, result = parse... | def parse_condition(item, isHaving):
| item = item.replace('*between*', 'between').replace('*and*','and')
if item.startswith('not '):
isNot = True
item = item[len('not '):]
else:
isNot = False
n = '~' if isNot else ''
if item.find(' between ') != -1:
key, result = parse_between(item, isNot, isHaving)
e... | key.replace('.','_')
value = [handle_value_type(i.strip()) for i in value[1:-1].split(',')]
n = '~' if isNot else ''
return key, "{}(df['{}'].isin({}))".format(n, key, str(value))
def parse_condition(item, isHaving):
| 68 | 69 | 233 | 8 | 60 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_condition | parse_condition | 82 | 103 | 82 | 82 | 2a4d827dc58cee333f0908db18c8275e92e7e3d7 | bigcode/the-stack | train |
edd365cc4417848e48d0de67 | train | function | def parse_projection(s_list, attributes, group):
if len(attributes) == 0 and len(group) == 0:
pass
else:
# df = df.reset_index()
s_list.append("df = df.reset_index()")
if len(attributes) == 0:
group = [g.replace('.', '_') for g in group]
# df = df[group]
... | def parse_projection(s_list, attributes, group):
| if len(attributes) == 0 and len(group) == 0:
pass
else:
# df = df.reset_index()
s_list.append("df = df.reset_index()")
if len(attributes) == 0:
group = [g.replace('.', '_') for g in group]
# df = df[group]
s_list.append("df = df[{}]".format(gro... | if limit == 0:
return s_list
# df = df.iloc[offset:offset + limit]
s = "df = df.iloc[{}:{}]".format(offset, offset + limit)
s_list.append(s)
return s_list
def parse_projection(s_list, attributes, group):
| 64 | 64 | 142 | 10 | 53 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_projection | parse_projection | 203 | 217 | 203 | 203 | 1e1a4bb37014ca5ace182ebff5445c04add29ef6 | bigcode/the-stack | train |
f5ec167c305b4f337f41c4c7 | train | function | def parse_limit_offset(s_list, offset, limit):
if limit == '':
limit = 0
else:
limit = int(limit)
if offset == '':
offset = 0
else:
offset = int(offset)
# if df.size < offset: # review.drop(review.index)
# s = "df = df.drop(df.index)"
# df = df.drop(d... | def parse_limit_offset(s_list, offset, limit):
| if limit == '':
limit = 0
else:
limit = int(limit)
if offset == '':
offset = 0
else:
offset = int(offset)
# if df.size < offset: # review.drop(review.index)
# s = "df = df.drop(df.index)"
# df = df.drop(df.index)
# else:
if limit == 0:
... | else:
ascendings.append(False)
s_list.append("df = df.sort_values({},ascending={})".format(str(columns), str(ascendings)))
# df = df.sort_values(columns, ascending=ascendings)
return s_list
def parse_limit_offset(s_list, offset, limit):
| 64 | 64 | 148 | 11 | 52 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_limit_offset | parse_limit_offset | 181 | 200 | 181 | 181 | 6823e337c557439a98ad837c3cf9e2c23e0a6636 | bigcode/the-stack | train |
21394f2ad946419de9a910fc | train | function | def parse_order(s_list, order):
if len(order) == 0:
return s_list
columns, ascendings = [], []
for o in order:
columns.append(o.split(' ')[0].replace('.', '_'))
if len(o.split(' ')) == 1:
ascendings.append(True)
else:
if o.split(' ')[1].lower() == 'asc... | def parse_order(s_list, order):
| if len(order) == 0:
return s_list
columns, ascendings = [], []
for o in order:
columns.append(o.split(' ')[0].replace('.', '_'))
if len(o.split(' ')) == 1:
ascendings.append(True)
else:
if o.split(' ')[1].lower() == 'asc':
ascendings.ap... | ({})".format(str(agg_dict)))
s_list.append("df.columns = df.columns.droplevel(0)")
# df = df.agg(agg_dict)
# df.columns = df.columns.droplevel(0)
return s_list
def parse_order(s_list, order):
| 64 | 64 | 144 | 8 | 55 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_order | parse_order | 163 | 178 | 163 | 163 | 1c8a2c1b3f30a8c582d703a7ed021b1e342465bf | bigcode/the-stack | train |
c94bb63c3a19bf285b13d04e | train | function | def translate(sql_dict):
s_list = getResult(sql_dict)
return s_list
| def translate(sql_dict):
| s_list = getResult(sql_dict)
return s_list
| parse_order(s_list, sql_dict['order'])
s_list = parse_limit_offset(s_list, sql_dict['offset'], sql_dict['limit'])
print(s_list)
s_list = parse_projection(s_list, sql_dict['projection'], sql_dict['group'])
return s_list
def translate(sql_dict):
| 64 | 64 | 19 | 5 | 58 | BuyiCheng/QueryTranslator | dataframetl.py | Python | translate | translate | 240 | 242 | 240 | 240 | 4192e17b0920fd517b8d81b0ad2ec24b4d84d1c4 | bigcode/the-stack | train |
06db2b6b7aa6ca6b729ac57c | train | function | def handle_value_type(value):
if value[0] in ['"',"'"] and value[-1] in ['"',"'"]:
return value[1:-1]
else:
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
try:
... | def handle_value_type(value):
| if value[0] in ['"',"'"] and value[-1] in ['"',"'"]:
return value[1:-1]
else:
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
try:
import unicodedata
... | join_type = 'right'
s_list.append("df = {}.merge({},left_on='{}',right_on='{}',how='{}')".format(table,join_table,left.replace('.','_'),right.replace('.','_'), join_type))
return s_list
def handle_value_type(value):
| 64 | 64 | 103 | 6 | 57 | BuyiCheng/QueryTranslator | dataframetl.py | Python | handle_value_type | handle_value_type | 41 | 58 | 41 | 41 | 03a320f848cd000b7311be1e9c9ccdcb02ca767d | bigcode/the-stack | train |
c743521ba79f62b507466dd1 | train | function | def parse_in(item, isNot, isHaving):
if item.find(' not ') != -1:
key, value = item.split(' not in ')
isNot = not isNot
else:
key, value = item.split(' in ')
key = key.strip()
if isHaving:
key = key.replace('.','_')
value = [handle_value_type(i.strip()) for i in value... | def parse_in(item, isNot, isHaving):
| if item.find(' not ') != -1:
key, value = item.split(' not in ')
isNot = not isNot
else:
key, value = item.split(' in ')
key = key.strip()
if isHaving:
key = key.replace('.','_')
value = [handle_value_type(i.strip()) for i in value[1:-1].split(',')]
n = '~' if isN... | n = '~' if isNot else ''
return key, "{3}(df['{0}'] >= {1})&{3}(df['{0}'] <= {2})".format(key, v1, v2, n)
def parse_in(item, isNot, isHaving):
| 64 | 64 | 128 | 11 | 53 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_in | parse_in | 69 | 80 | 69 | 69 | 9bd992c2ba1f081de0a77a68fa9c58495812b1f5 | bigcode/the-stack | train |
f1d4e57c1a8b7f492ae7aa7a | train | function | def parse_join(s_list, table, joins):
for join in joins:
join_table = join.split('join ')[1].split(' ')[0]
right,left = join.split(' on ')[1].split(' = ')
if left.split('.')[0] == join_table:
left, right = right, left
join_type = 'inner'
if join.startswith('left'... | def parse_join(s_list, table, joins):
| for join in joins:
join_table = join.split('join ')[1].split(' ')[0]
right,left = join.split(' on ')[1].split(' = ')
if left.split('.')[0] == join_table:
left, right = right, left
join_type = 'inner'
if join.startswith('left'):
join_type = 'left'
... | in {}.columns:".format(t))
s_list.append("\tcolumns_map[c]='{}_'+c".format(t) )
s_list.append("{}.rename(columns=columns_map, inplace=True)".format(t, str(columns)))
return s_list
def parse_join(s_list, table, joins):
| 64 | 64 | 153 | 10 | 53 | BuyiCheng/QueryTranslator | dataframetl.py | Python | parse_join | parse_join | 25 | 38 | 25 | 26 | 05c8a553bebafd4d57278b2ac240542a212c6794 | bigcode/the-stack | train |
a6d0138c1612cf2d38e7a2e1 | train | class | class TestIntegrationEntity(unittest.TestCase):
"""IntegrationEntity unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test IntegrationEntity
include_option is a boolean, when False only required
... | class TestIntegrationEntity(unittest.TestCase):
| """IntegrationEntity unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test IntegrationEntity
include_option is a boolean, when False only required
params are included, when True both require... | document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import talon_one
from talon_one.models.integration_entity import IntegrationEntity # noqa: E501
from talon_one.rest import ApiException
class TestIntegrationEntity(unittest.T... | 74 | 74 | 249 | 8 | 65 | talon-one/talon_one.py | test/test_integration_entity.py | Python | TestIntegrationEntity | TestIntegrationEntity | 22 | 51 | 22 | 22 | 002fd710ecd59897116f475ed9b8827f4a653b8c | bigcode/the-stack | train |
4e684d5e2fadb7bfd9fc7a84 | train | class | @base.ReleaseTracks(base.ReleaseTrack.GA)
class StartUpdate(base.Command):
"""Replaces instances in a managed instance group.
Deletes the existing instance and creates a new instance from the target
template. The Updater creates a brand new instance with all new instance
properties, such as new internal and ex... | @base.ReleaseTracks(base.ReleaseTrack.GA)
class StartUpdate(base.Command):
| """Replaces instances in a managed instance group.
Deletes the existing instance and creates a new instance from the target
template. The Updater creates a brand new instance with all new instance
properties, such as new internal and external IP addresses.
"""
@staticmethod
def Args(parser):
_AddArg... | instance_groups_managed_flags.AddMaxUnavailableArg(parser)
if supports_min_ready:
instance_groups_managed_flags.AddMinReadyArg(parser)
if supports_replacement_method:
instance_groups_managed_flags.AddReplacementMethodFlag(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class StartUpdate(base.Command):
| 64 | 64 | 215 | 16 | 48 | bopopescu/Social-Lite | google-cloud-sdk/lib/surface/compute/instance_groups/managed/rolling_action/replace.py | Python | StartUpdate | StartUpdate | 40 | 67 | 40 | 41 | 64580f31553f35564f6e3fad3ad5b5260a690329 | bigcode/the-stack | train |
f22d298737446ecf25ddb7d6 | train | function | def _AddArgs(
parser, supports_min_ready=False, supports_replacement_method=False):
"""Adds args."""
instance_groups_managed_flags.AddMaxSurgeArg(parser)
instance_groups_managed_flags.AddMaxUnavailableArg(parser)
if supports_min_ready:
instance_groups_managed_flags.AddMinReadyArg(parser)
if supports_r... | def _AddArgs(
parser, supports_min_ready=False, supports_replacement_method=False):
| """Adds args."""
instance_groups_managed_flags.AddMaxSurgeArg(parser)
instance_groups_managed_flags.AddMaxUnavailableArg(parser)
if supports_min_ready:
instance_groups_managed_flags.AddMinReadyArg(parser)
if supports_replacement_method:
instance_groups_managed_flags.AddReplacementMethodFlag(parser)
| .compute.instance_groups.managed import flags as instance_groups_managed_flags
from googlecloudsdk.command_lib.compute.instance_groups.managed import rolling_action
from googlecloudsdk.command_lib.compute.managed_instance_groups import update_instances_utils
def _AddArgs(
parser, supports_min_ready=False, supports_... | 64 | 64 | 86 | 19 | 44 | bopopescu/Social-Lite | google-cloud-sdk/lib/surface/compute/instance_groups/managed/rolling_action/replace.py | Python | _AddArgs | _AddArgs | 29 | 37 | 29 | 30 | 701b3c8a4f69d444e4f70cf8e24d26d0a653b366 | bigcode/the-stack | train |
8a583c85c5154b8902ba72de | train | class | @base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class StartUpdateBeta(StartUpdate):
"""Replaces instances in a managed instance group.
Deletes the existing instance and creates a new instance from the target
template. The Updater creates a brand new instance with all new instance
propertie... | @base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class StartUpdateBeta(StartUpdate):
| """Replaces instances in a managed instance group.
Deletes the existing instance and creates a new instance from the target
template. The Updater creates a brand new instance with all new instance
properties, such as new internal and external IP addresses.
"""
@staticmethod
def Args(parser):
_AddArg... | max-surge', args.max_surge, client.messages)
return client.MakeRequests([
rolling_action.CreateRequest(args, client, resources,
minimal_action, max_surge)
])
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class StartUpdateBeta(StartUpdate):
| 63 | 64 | 122 | 24 | 39 | bopopescu/Social-Lite | google-cloud-sdk/lib/surface/compute/instance_groups/managed/rolling_action/replace.py | Python | StartUpdateBeta | StartUpdateBeta | 70 | 83 | 70 | 71 | 9e04d036da819803b4a3a5099439161c27e267db | bigcode/the-stack | train |
7ccb084043690101fe6619ed | train | function | def b(arg):
val = arg * 5
val = val * 2
c(val)
print('Leaving b()')
return 42
| def b(arg):
| val = arg * 5
val = val * 2
c(val)
print('Leaving b()')
return 42
| on line {} of {}'.format(
func_name, line_no, filename))
if func_name in to_be_traced:
# Trace into this function
return trace_lines
return
def c(input):
print('input =', input)
print('Leaving c()')
def b(arg):
| 64 | 64 | 36 | 4 | 60 | yswtrue/pycrunch-trace | pycrunch_trace/reference_code/sys_settrace_line.py | Python | b | b | 49 | 54 | 49 | 49 | 8979d836a735777488b05ab983745c50f7b2b03c | bigcode/the-stack | train |
250a8a16c800582ffcda4650 | train | function | def a():
b(2)
print('Leaving a()')
| def a():
| b(2)
print('Leaving a()')
| trace_lines
return
def c(input):
print('input =', input)
print('Leaving c()')
def b(arg):
val = arg * 5
val = val * 2
c(val)
print('Leaving b()')
return 42
def a():
| 64 | 64 | 15 | 3 | 60 | yswtrue/pycrunch-trace | pycrunch_trace/reference_code/sys_settrace_line.py | Python | a | a | 57 | 59 | 57 | 57 | 9adb9b736447d72dc7b650358f20abc8bff9b8f0 | bigcode/the-stack | train |
f9ebe36a7c904bc746817995 | train | function | def c(input):
print('input =', input)
print('Leaving c()')
| def c(input):
| print('input =', input)
print('Leaving c()')
| '):
# Ignore calls not in this module
return
print('* Call to {} on line {} of {}'.format(
func_name, line_no, filename))
if func_name in to_be_traced:
# Trace into this function
return trace_lines
return
def c(input):
| 64 | 64 | 19 | 4 | 59 | yswtrue/pycrunch-trace | pycrunch_trace/reference_code/sys_settrace_line.py | Python | c | c | 44 | 46 | 44 | 44 | 01958f0ea251e56f6cb7e7f75713247de02f2b8a | bigcode/the-stack | train |
b60a608a109038f4825f0935 | train | function | def trace_lines(frame, event, arg):
if event == 'return':
print(f' -> return')
print('f_locals ' + ppretty(frame))
return
if event != 'line':
return
co = frame.f_code
func_name = co.co_name
line_no = frame.f_lineno
print(f'* {func_name} line {line_no}')
pri... | def trace_lines(frame, event, arg):
| if event == 'return':
print(f' -> return')
print('f_locals ' + ppretty(frame))
return
if event != 'line':
return
co = frame.f_code
func_name = co.co_name
line_no = frame.f_lineno
print(f'* {func_name} line {line_no}')
print(f'* locals: {frame.f_locals}')... | import functools
import sys
from ppretty import ppretty
def trace_lines(frame, event, arg):
| 22 | 64 | 98 | 9 | 12 | yswtrue/pycrunch-trace | pycrunch_trace/reference_code/sys_settrace_line.py | Python | trace_lines | trace_lines | 7 | 20 | 7 | 7 | fefc7897d615c6800c252b773ed1f2ed5adac58d | bigcode/the-stack | train |
c11ba79546c5434cb2743e02 | train | function | def trace_calls(frame, event, arg, to_be_traced):
if event != 'call':
return
co = frame.f_code
func_name = co.co_name
if func_name == 'write':
# Ignore write() calls from printing
return
line_no = frame.f_lineno
filename = co.co_filename
if not filename.endswith('sys_... | def trace_calls(frame, event, arg, to_be_traced):
| if event != 'call':
return
co = frame.f_code
func_name = co.co_name
if func_name == 'write':
# Ignore write() calls from printing
return
line_no = frame.f_lineno
filename = co.co_filename
if not filename.endswith('sys_settrace_line.py'):
# Ignore calls not in ... | co = frame.f_code
func_name = co.co_name
line_no = frame.f_lineno
print(f'* {func_name} line {line_no}')
print(f'* locals: {frame.f_locals}')
def trace_calls(frame, event, arg, to_be_traced):
| 63 | 64 | 145 | 14 | 49 | yswtrue/pycrunch-trace | pycrunch_trace/reference_code/sys_settrace_line.py | Python | trace_calls | trace_calls | 23 | 41 | 23 | 23 | 3683b2b3ca975072ee21b8843bd91352e7d3eb66 | bigcode/the-stack | train |
b4b9e4ae8e7c21feafa85bef | train | function | def create_new_job() -> int:
URL = "https://playground.learnqa.ru/ajax/api/longtime_job"
first_response = requests.get(URL)
data = json.loads(first_response.text)
seconds = data.get("seconds")
token = data.get("token")
second_response = requests.get(URL, params = {"token": token})
data_2 ... | def create_new_job() -> int:
| URL = "https://playground.learnqa.ru/ajax/api/longtime_job"
first_response = requests.get(URL)
data = json.loads(first_response.text)
seconds = data.get("seconds")
token = data.get("token")
second_response = requests.get(URL, params = {"token": token})
data_2 = json.loads(second_response.... | import requests
import json
import time
def create_new_job() -> int:
| 17 | 64 | 192 | 8 | 8 | dmchu/Pytest_REST_API_with_Allure | exercises/ex8.py | Python | create_new_job | create_new_job | 5 | 29 | 5 | 5 | e26a009599f5c14677ae3fb31810248c32c499b5 | bigcode/the-stack | train |
4ccb2a194545fe6843aa9819 | train | class | class Camera( object ):
def __init__( self ):
self.center = arrayf( ( 0,0,0 ) )
self.eye = arrayf( ( 0,0,2 ) )
self.up = arrayf( ( 0,1,0 ) )
self.near_far = asarrayf( ( .1, 4.1 ) )
self.proj = self.Perspective( fovy = 50., aspect = 1. )
#self.proj = self.Orth... | class Camera( object ):
| def __init__( self ):
self.center = arrayf( ( 0,0,0 ) )
self.eye = arrayf( ( 0,0,2 ) )
self.up = arrayf( ( 0,1,0 ) )
self.near_far = asarrayf( ( .1, 4.1 ) )
self.proj = self.Perspective( fovy = 50., aspect = 1. )
#self.proj = self.Ortho( -1., 1., -1., 1. )
... | #!/usr/bin/env python
import logging
import threading
import time
import sys
from GLUTWindow import GLUTWindow
from trimesh import TriMesh
import numpy as np
## Most of myarray.py:s
from numpy import *
def asarrayf( *args, **kwargs ):
kwargs['dtype'] = float
return asarray( *args, **kwargs )
def arrayf( *args,... | 192 | 256 | 919 | 5 | 187 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | Camera | Camera | 29 | 127 | 29 | 29 | aac7cfb868dddf39d909ec4a28c96179ae3768ee | bigcode/the-stack | train |
25f683042062dee9d8c6a333 | train | function | def direction( vec ): return vec * 1./mag(vec)
| def direction( vec ): | return vec * 1./mag(vec)
| **kwargs )
def arrayf( *args, **kwargs ):
kwargs['dtype'] = float
return array( *args, **kwargs )
def mag2( vec ): return dot( vec, vec )
def mag( vec ): return sqrt( mag2( vec ) )
def direction( vec ): | 64 | 64 | 14 | 6 | 58 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | direction | direction | 20 | 20 | 20 | 20 | 7c14868c223a31d6b9af05f4163997073dd5a4c0 | bigcode/the-stack | train |
78217e46a13f6683070ee08c | train | function | def asarrayf( *args, **kwargs ):
kwargs['dtype'] = float
return asarray( *args, **kwargs )
| def asarrayf( *args, **kwargs ):
| kwargs['dtype'] = float
return asarray( *args, **kwargs )
| #!/usr/bin/env python
import logging
import threading
import time
import sys
from GLUTWindow import GLUTWindow
from trimesh import TriMesh
import numpy as np
## Most of myarray.py:s
from numpy import *
def asarrayf( *args, **kwargs ):
| 60 | 64 | 30 | 11 | 49 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | asarrayf | asarrayf | 12 | 14 | 12 | 12 | eb2608315afdb1204f283b71de33c7a15882dd48 | bigcode/the-stack | train |
0fe6f4c27463ea13b9c43645 | train | function | def mag( vec ): return sqrt( mag2( vec ) )
| def mag( vec ): | return sqrt( mag2( vec ) )
| ['dtype'] = float
return asarray( *args, **kwargs )
def arrayf( *args, **kwargs ):
kwargs['dtype'] = float
return array( *args, **kwargs )
def mag2( vec ): return dot( vec, vec )
def mag( vec ): | 64 | 64 | 14 | 6 | 58 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | mag | mag | 19 | 19 | 19 | 19 | fa030a73b191c9c662a72a9ea8ef24bdb9cdb7a9 | bigcode/the-stack | train |
4339c3ac981f5b3532649053 | train | function | def draw_mesh_faces_flat( mesh, will_draw_edges = True ):
'''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
Lighting and materials and colors be specified before this function is entered.
If the parameters indicates that edges will be drawn, then glPolygonOffse... | def draw_mesh_faces_flat( mesh, will_draw_edges = True ):
| '''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
Lighting and materials and colors be specified before this function is entered.
If the parameters indicates that edges will be drawn, then glPolygonOffset will be used.
'''
if will_draw_edges:
... | camera ):
light_position = [ camera.eye[0], camera.eye[1], camera.eye[2], 1.0 ]
glLightfv( GL_LIGHT0, GL_POSITION, light_position )
glEnable( GL_LIGHT0 )
def draw_mesh_faces_flat( mesh, will_draw_edges = True ):
| 64 | 64 | 202 | 14 | 50 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | draw_mesh_faces_flat | draw_mesh_faces_flat | 134 | 154 | 134 | 134 | 7cd9f7d50fa51b5bd9d7140e81f95ecdf8f875eb | bigcode/the-stack | train |
dec4da73ee3e9bc250bfe0fa | train | function | def arrayf( *args, **kwargs ):
kwargs['dtype'] = float
return array( *args, **kwargs )
| def arrayf( *args, **kwargs ):
| kwargs['dtype'] = float
return array( *args, **kwargs )
| from trimesh import TriMesh
import numpy as np
## Most of myarray.py:s
from numpy import *
def asarrayf( *args, **kwargs ):
kwargs['dtype'] = float
return asarray( *args, **kwargs )
def arrayf( *args, **kwargs ):
| 64 | 64 | 28 | 10 | 54 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | arrayf | arrayf | 15 | 17 | 15 | 15 | 44534b2cfcb8477a3893e578de60d2223254c57f | bigcode/the-stack | train |
ac68a7a8a93e63a22b728d79 | train | function | def mag2( vec ): return dot( vec, vec )
| def mag2( vec ): | return dot( vec, vec )
| asarrayf( *args, **kwargs ):
kwargs['dtype'] = float
return asarray( *args, **kwargs )
def arrayf( *args, **kwargs ):
kwargs['dtype'] = float
return array( *args, **kwargs )
def mag2( vec ): | 64 | 64 | 13 | 7 | 57 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | mag2 | mag2 | 18 | 18 | 18 | 18 | 0dd0491f4cbff94761e57165c5382c764c0c7611 | bigcode/the-stack | train |
3fadfe80df1a210784a32b9b | train | function | def draw_mesh_edges( mesh ):
'''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
'''
glShadeModel( GL_SMOOTH )
glBegin( GL_LINES )
for edge in mesh.edges:
edge = tuple( edge )
glColor(*(mesh.vs[ edge[0] ] + .5))
glVertex3f( *mesh.v... | def draw_mesh_edges( mesh ):
| '''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
'''
glShadeModel( GL_SMOOTH )
glBegin( GL_LINES )
for edge in mesh.edges:
edge = tuple( edge )
glColor(*(mesh.vs[ edge[0] ] + .5))
glVertex3f( *mesh.vs[ edge[0] ] )
glColo... | 3 * len( mesh.faces ), GL_UNSIGNED_INT, asarray( mesh.faces, dtype = uint32 ) )
#glDrawElementsui( GL_TRIANGLES, mesh.faces )
glDisableClientState( GL_NORMAL_ARRAY )
glDisableClientState( GL_VERTEX_ARRAY )
glDisable( GL_POLYGON_OFFSET_FILL )
## The default is flat shading.
draw_mesh_faces = d... | 92 | 92 | 309 | 7 | 84 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | draw_mesh_edges | draw_mesh_edges | 209 | 237 | 209 | 209 | 92d57bcc84b776f873a0dc519d6f3420f415d8b8 | bigcode/the-stack | train |
bf129f74e2993167710846b9 | train | class | class TriMeshWindow( GLUTWindow ):
def __init__( self, **kwargs ):
GLUTWindow.__init__( self )
kwargs.setdefault( 'background_color', ( .3, .3, .3 ) )
kwargs.setdefault( 'mesh', TriMesh() )
kwargs.setdefault( 'linestrips', [] )
kwargs.setdefault( 'points', [] )
... | class TriMeshWindow( GLUTWindow ):
| def __init__( self, **kwargs ):
GLUTWindow.__init__( self )
kwargs.setdefault( 'background_color', ( .3, .3, .3 ) )
kwargs.setdefault( 'mesh', TriMesh() )
kwargs.setdefault( 'linestrips', [] )
kwargs.setdefault( 'points', [] )
kwargs.setdefault( 'camera', Cam... | )
# print(v)
glEnd()
if video_points is not None:
glPointSize( 2 )
glBegin( GL_POINTS )
idx = np.random.randint(video_points.shape[0], size=10000)
for x, y, z in video_points[idx, :]:
glColor(x, y, z)
glVertex3f(x - .5, y - .5, z - .5)
... | 256 | 256 | 1,366 | 8 | 247 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | TriMeshWindow | TriMeshWindow | 298 | 461 | 298 | 298 | d223ec9605643575dedde2f6d82829534ac2b55c | bigcode/the-stack | train |
56a8539c1cf841643421e654 | train | function | def draw_mesh_faces_smooth( mesh, will_draw_edges = True ):
'''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
Lighting and materials and colors be specified before this function is entered.
If the parameters indicates that edges will be drawn, then glPolygonOff... | def draw_mesh_faces_smooth( mesh, will_draw_edges = True ):
| '''
Takes a TriMesh parameter mesh and draws it, setting as little OpenGL state as possible.
Lighting and materials and colors be specified before this function is entered.
If the parameters indicates that edges will be drawn, then glPolygonOffset will be used.
'''
## I assume that mesh.vs[... | .0, 1.0 )
glEnable( GL_POLYGON_OFFSET_FILL )
from itertools import izip
glBegin( GL_TRIANGLES )
for face, normal in izip( mesh.faces, mesh.face_normals ):
glNormal3f( *normal )
for vertex_index in face:
glVertex3f( *mesh.vs[ vertex_index ] )
glEnd()
glDi... | 163 | 163 | 545 | 15 | 148 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | draw_mesh_faces_smooth | draw_mesh_faces_smooth | 164 | 204 | 164 | 164 | 840013df4757517e1f2a6e577667211f9f3e60c4 | bigcode/the-stack | train |
f045d7fa6a9fa04415f034be | train | function | def draw_linestrips( linestrips ):
'''
Takes a sequence of line strips, where each line strip is a sequence of points,
and draws it, setting as little OpenGL state as possible.
'''
for linestrip in linestrips:
glBegin( GL_LINE_STRIP )
## For Songrun
glE... | def draw_linestrips( linestrips ):
| '''
Takes a sequence of line strips, where each line strip is a sequence of points,
and draws it, setting as little OpenGL state as possible.
'''
for linestrip in linestrips:
glBegin( GL_LINE_STRIP )
## For Songrun
glEnd()
| .5, s)
glColor(0., p, r)
glVertex3f(-.5, q, s)
glColor(1., p, r)
glVertex3f(.5, q, s)
glEnd()
def draw_linestrips( linestrips ):
| 64 | 64 | 76 | 10 | 54 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | draw_linestrips | draw_linestrips | 239 | 250 | 239 | 239 | 0dcbcf7f8aab1d9f4b22b367242acb4d61de97ed | bigcode/the-stack | train |
f5dada52c46a88047c46b24f | train | function | def set_headlight( camera ):
light_position = [ camera.eye[0], camera.eye[1], camera.eye[2], 1.0 ]
glLightfv( GL_LIGHT0, GL_POSITION, light_position )
glEnable( GL_LIGHT0 )
| def set_headlight( camera ):
| light_position = [ camera.eye[0], camera.eye[1], camera.eye[2], 1.0 ]
glLightfv( GL_LIGHT0, GL_POSITION, light_position )
glEnable( GL_LIGHT0 )
| ()
gluLookAt(
self.eye[0], self.eye[1], self.eye[2],
self.center[0], self.center[1], self.center[2],
self.up[0], self.up[1], self.up[2]
)
def set_headlight( camera ):
| 64 | 64 | 55 | 7 | 57 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | set_headlight | set_headlight | 129 | 132 | 129 | 129 | 986b095b82b7134cf3f064d4b2c2fbc08805158f | bigcode/the-stack | train |
55486eaf665e3f128155db49 | train | function | def main():
if len( sys.argv ) not in [2, 3]:
print('Usage:', sys.argv[0], 'mesh.obj')
sys.exit(-1)
mesh_path = sys.argv[1]
prefix = sys.argv[2]
print(mesh_path)
pid = view_mesh( mesh_path, prefix,mesh_path )
# print('Background process id:', pid)
x = threading.Thread(t... | def main():
| if len( sys.argv ) not in [2, 3]:
print('Usage:', sys.argv[0], 'mesh.obj')
sys.exit(-1)
mesh_path = sys.argv[1]
prefix = sys.argv[2]
print(mesh_path)
pid = view_mesh( mesh_path, prefix,mesh_path )
# print('Background process id:', pid)
x = threading.Thread(target=view_m... | ] )
w1.positionWindow( [500, 0] if 'sim' in mesh_path else [0, 0] )
glutMainLoop()
def view_lines( lines, title = None ):
raise NotImplementedError( 'Songrun, you can implement this.' )
def main():
| 64 | 64 | 108 | 3 | 61 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | main | main | 521 | 533 | 521 | 521 | 3ce63eb690890e982ff75f013a969063ea1d32d2 | bigcode/the-stack | train |
b9062c765a187f79ec36ef2c | train | function | def view_mesh( mesh_path,prefix, title = None):
'''
Given a TriMesh object 'mesh' and
optional window title 'title',
visualizes the mesh in a window by
spawning a separate process.
Returns immediately, with the visualization process ID
as the return value.
'''
# ## This function... | def view_mesh( mesh_path,prefix, title = None):
| '''
Given a TriMesh object 'mesh' and
optional window title 'title',
visualizes the mesh in a window by
spawning a separate process.
Returns immediately, with the visualization process ID
as the return value.
'''
# ## This function would never return if we didn't fork().
# #... | == 'D':
self.mesh_id += 1
self.refresh_time()
if key == 'a' or key == 'A':
self.mesh_id -= 1
self.refresh_time()
if 'r' == key: self.reset()
elif 'w' == key: self.draw_edges = not self.draw_edges
else: GLUTWindow.keyboardFunc( self, key... | 151 | 151 | 504 | 13 | 138 | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | ExtractVideoFrameConvexHull/dynamic_viewer.py | Python | view_mesh | view_mesh | 463 | 516 | 463 | 463 | 7885b103892d786cae279a7482259ca9698e2dfa | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.