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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
59f39c27d46e899d71398859 | train | class | class TestLags(ut.TestCase):
def test_map_equivalence(self):
m = MAP([[-10., 1], [2., -3.]], [[9, 0], [0.1, 0.9]])
samples = list(m.generate(20000))
self.assertIsInstance(stats.lag(m, 1), np.ndarray)
self.assertIsInstance(stats.lag(m, 2), np.ndarray)
self.assertIsInstance(st... | class TestLags(ut.TestCase):
| def test_map_equivalence(self):
m = MAP([[-10., 1], [2., -3.]], [[9, 0], [0.1, 0.9]])
samples = list(m.generate(20000))
self.assertIsInstance(stats.lag(m, 1), np.ndarray)
self.assertIsInstance(stats.lag(m, 2), np.ndarray)
self.assertIsInstance(stats.lag(samples, 1), np.ndarra... | 2), np.ndarray)
assert_almost_equal(stats.moment(source, 1), [1 / 3], 10)
assert_almost_equal(stats.moment(source, 2), [1 / 3, 2 / 9], 10)
class TestLags(ut.TestCase):
| 64 | 64 | 149 | 9 | 55 | larioandr/pyqumo | tests/statistical_tests/test_stats.py | Python | TestLags | TestLags | 66 | 75 | 66 | 67 | 2c18aa7079b46d412745fd02eecc51c9e7fcfcae | bigcode/the-stack | train |
f5e439d18cbaac3f432b639d | train | class | class TestMoments(ut.TestCase):
def test_moments_const_samples(self):
samples_1 = [1.0] * 10
samples_2 = [2.0] * 10
self.assertIsInstance(stats.moment(samples_1, 1), np.ndarray)
self.assertIsInstance(stats.moment(samples_1, 2), np.ndarray)
self.assertIsInstance(stats.moment... | class TestMoments(ut.TestCase):
| def test_moments_const_samples(self):
samples_1 = [1.0] * 10
samples_2 = [2.0] * 10
self.assertIsInstance(stats.moment(samples_1, 1), np.ndarray)
self.assertIsInstance(stats.moment(samples_1, 2), np.ndarray)
self.assertIsInstance(stats.moment(samples_2, 1), np.ndarray)
... | import unittest as ut
import numpy as np
from numpy.testing import assert_almost_equal
import pyqumo.stats as stats
from pyqumo.distributions import Exp, PhaseType
from pyqumo.arrivals import PoissonProcess, MAP
class TestMoments(ut.TestCase):
| 61 | 216 | 720 | 9 | 51 | larioandr/pyqumo | tests/statistical_tests/test_stats.py | Python | TestMoments | TestMoments | 10 | 63 | 10 | 11 | 6136524bfe71a01d770a68225091967c68cd919a | bigcode/the-stack | train |
0093e2d487bf9f858145aa95 | train | function | def visual(model, out_dir):
global visualizer
render = SMPLRenderer(image_size=IMG_SIZE).cuda()
texs = render.debug_textures().cuda()[None]
with h5py.File(osp.join(out_dir, 'smpl_infos.h5'), 'r') as reader:
cams_crop = reader['cam_crop']
poses = reader['pose']
shapes = reader[... | def visual(model, out_dir):
| global visualizer
render = SMPLRenderer(image_size=IMG_SIZE).cuda()
texs = render.debug_textures().cuda()[None]
with h5py.File(osp.join(out_dir, 'smpl_infos.h5'), 'r') as reader:
cams_crop = reader['cam_crop']
poses = reader['pose']
shapes = reader['shape']
frame_ids =... | 2
import torch
import numpy as np
import os
import os.path as osp
import glob
from tqdm import tqdm
import time
from utils.visdom_visualizer import VisdomVisualizer
from utils.nmr import SMPLRenderer
from networks.hmr import HumanModelRecovery
os.environ['CUDA_DEVICES_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DE... | 125 | 125 | 419 | 7 | 118 | eyaler/impersonator | tools/visual_iPER.py | Python | visual | visual | 21 | 62 | 21 | 21 | 574141d54c99fd8d12bc01dbdd6a927660a3429d | bigcode/the-stack | train |
d97d581966da84500d6d2d84 | train | function | def upgrade():
pass
| def upgrade():
| pass
| 489543
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8cc311e0f18a'
down_revision = '157210e1f7c7'
branch_labels = None
depends_on = None
def upgrade():
| 64 | 64 | 6 | 3 | 60 | sankalploomba/StockManagementBackend | app/alembic/versions/8cc311e0f18a_store_table_changes.py | Python | upgrade | upgrade | 19 | 20 | 19 | 19 | 1d5a403ea9b06ac507d5747dcc49b264b8587cb1 | bigcode/the-stack | train |
3f9c7df614e141ed89f9082e | train | function | def downgrade():
pass
| def downgrade():
| pass
| mbic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8cc311e0f18a'
down_revision = '157210e1f7c7'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
| 64 | 64 | 6 | 3 | 60 | sankalploomba/StockManagementBackend | app/alembic/versions/8cc311e0f18a_store_table_changes.py | Python | downgrade | downgrade | 23 | 24 | 23 | 23 | 159c894bca0d9c55968917c4b9f7c18e26716f4c | bigcode/the-stack | train |
d799cdbdc0d3a786a255feae | train | class | class AddGroupNode(Node, ArmLogicTreeNode):
'''Add Group node'''
bl_idname = 'LNAddGroupNode'
bl_label = 'Add Collection'
bl_icon = 'NONE'
def init(self, context):
self.inputs.new('ArmNodeSocketAction', 'In')
self.inputs.new('NodeSocketString', 'Collection')
self.outputs.new... | class AddGroupNode(Node, ArmLogicTreeNode):
| '''Add Group node'''
bl_idname = 'LNAddGroupNode'
bl_label = 'Add Collection'
bl_icon = 'NONE'
def init(self, context):
self.inputs.new('ArmNodeSocketAction', 'In')
self.inputs.new('NodeSocketString', 'Collection')
self.outputs.new('ArmNodeSocketAction', 'Out')
| import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class AddGroupNode(Node, ArmLogicTreeNode):
| 36 | 64 | 88 | 11 | 25 | Sanva/armory | blender/arm/logicnode/action_add_group.py | Python | AddGroupNode | AddGroupNode | 6 | 15 | 6 | 6 | 03d63c7acb2dc4fb86dafb29d1e2998efdea5c29 | bigcode/the-stack | train |
6df3e3de97b14c2e0dab2fe5 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def preferential_attachment(G, ebunch=None):
r"""Compute the preferential attachment score of all node pairs in ebunch.
Preferential attachment score of `u` and `v` is defined as
.. math::
|\Gamma(u)| |\Gamma(v)|
where $\Gam... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def preferential_attachment(G, ebunch=None):
| r"""Compute the preferential attachment score of all node pairs in ebunch.
Preferential attachment score of `u` and `v` is defined as
.. math::
|\Gamma(u)| |\Gamma(v)|
where $\Gamma(u)$ denotes the set of neighbors of $u$.
Parameters
----------
G : graph
NetworkX undirec... | inf = float("inf")
def predict(u, v):
if u == v:
raise nx.NetworkXAlgorithmError("Self links are not supported")
path_len = spl[u].get(v, inf)
return alpha * sum(1 for _ in nx.common_neighbors(G, u, v)) + (
1 - alpha
) * (... | 125 | 125 | 418 | 27 | 98 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | preferential_attachment | preferential_attachment | 305 | 355 | 305 | 307 | 7df9ed87319057cc04f14bb4a543daed4b76eb9a | bigcode/the-stack | train |
b2ce4c8618ece6eeb5a0454d | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"):
r"""Compute the resource allocation index of all node pairs in
ebunch using community information.
For two nodes $u$ and $v$, this function computes the resource
... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"):
| r"""Compute the resource allocation index of all node pairs in
ebunch using community information.
For two nodes $u$ and $v$, this function computes the resource
allocation index considering only common neighbors belonging to the
same community as $u$ and $v$. Mathematically,
.. math::
... | ta Soundarajan and John Hopcroft.
Using community information to improve the precision of link
prediction methods.
In Proceedings of the 21st international conference companion on
World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
http://doi.acm.org/10.1145/2187980.2... | 220 | 220 | 734 | 37 | 183 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | ra_index_soundarajan_hopcroft | ra_index_soundarajan_hopcroft | 432 | 504 | 432 | 434 | 419f92bd559c05116247b043355eb7082dcd387e | bigcode/the-stack | train |
2446be765ce9a901b7260088 | train | function | def _community(G, u, community):
"""Get the community of the given node."""
node_u = G.nodes[u]
try:
return node_u[community]
except KeyError as err:
raise nx.NetworkXAlgorithmError("No community information") from err
| def _community(G, u, community):
| """Get the community of the given node."""
node_u = G.nodes[u]
try:
return node_u[community]
except KeyError as err:
raise nx.NetworkXAlgorithmError("No community information") from err
| {w for w in cnbors if _community(G, w, community) == Cu}
inter = cnbors - within
return len(within) / (len(inter) + delta)
return _apply_prediction(G, predict, ebunch)
def _community(G, u, community):
| 64 | 64 | 59 | 9 | 55 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | _community | _community | 590 | 596 | 590 | 590 | ff4a76de24c8a70d2cd62972f0a15def438b9f18 | bigcode/the-stack | train |
5980e7a25d71cf6461fda869 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def jaccard_coefficient(G, ebunch=None):
r"""Compute the Jaccard coefficient of all node pairs in ebunch.
Jaccard coefficient of nodes `u` and `v` is defined as
.. math::
\frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def jaccard_coefficient(G, ebunch=None):
| r"""Compute the Jaccard coefficient of all node pairs in ebunch.
Jaccard coefficient of nodes `u` and `v` is defined as
.. math::
\frac{|\Gamma(u) \cap \Gamma(v)|}{|\Gamma(u) \cup \Gamma(v)|}
where $\Gamma(u)$ denotes the set of neighbors of $u$.
Parameters
----------
G : graph
... | 0.75000000
References
----------
.. [1] T. Zhou, L. Lu, Y.-C. Zhang.
Predicting missing links via local information.
Eur. Phys. J. B 71 (2009) 623.
https://arxiv.org/pdf/0901.0553.pdf
"""
def predict(u, v):
return sum(1 / G.degree(w) for w in nx.common_neighbors(G, u,... | 145 | 145 | 486 | 30 | 115 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | jaccard_coefficient | jaccard_coefficient | 97 | 150 | 97 | 99 | 2b0bb9d977f3854c5393afde621d15fbc0f6f3e5 | bigcode/the-stack | train |
d0530f5145864dc6c8ad338a | train | function | def _apply_prediction(G, func, ebunch=None):
"""Applies the given function to each edge in the specified iterable
of edges.
`G` is an instance of :class:`networkx.Graph`.
`func` is a function on two inputs, each of which is a node in the
graph. The function can return anything, but it should retur... | def _apply_prediction(G, func, ebunch=None):
| """Applies the given function to each edge in the specified iterable
of edges.
`G` is an instance of :class:`networkx.Graph`.
`func` is a function on two inputs, each of which is a node in the
graph. The function can return anything, but it should return a
value representing a prediction of th... | efficient",
"adamic_adar_index",
"preferential_attachment",
"cn_soundarajan_hopcroft",
"ra_index_soundarajan_hopcroft",
"within_inter_cluster",
"common_neighbor_centrality",
]
def _apply_prediction(G, func, ebunch=None):
| 64 | 64 | 171 | 12 | 52 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | _apply_prediction | _apply_prediction | 23 | 40 | 23 | 23 | 0b5f0e3798c75760de0dba6e0d6657e556841e90 | bigcode/the-stack | train |
2b8f38d81013062cfc0cd641 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def resource_allocation_index(G, ebunch=None):
r"""Compute the resource allocation index of all node pairs in ebunch.
Resource allocation index of `u` and `v` is defined as
.. math::
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def resource_allocation_index(G, ebunch=None):
| r"""Compute the resource allocation index of all node pairs in ebunch.
Resource allocation index of `u` and `v` is defined as
.. math::
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|}
where $\Gamma(u)$ denotes the set of neighbors of $u$.
Parameters
----------
G : gr... | is a node in the
graph. The function can return anything, but it should return a
value representing a prediction of the likelihood of a "link"
joining the two nodes.
`ebunch` is an iterable of pairs of nodes. If not specified, all
non-edges in the graph `G` will be used.
"""
if ebunch is ... | 140 | 140 | 469 | 29 | 111 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | resource_allocation_index | resource_allocation_index | 43 | 94 | 43 | 45 | 8eb84434f28516cf48d59c3a8283f200188d610b | bigcode/the-stack | train |
1d2919d875ff1ac5097f5360 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def adamic_adar_index(G, ebunch=None):
r"""Compute the Adamic-Adar index of all node pairs in ebunch.
Adamic-Adar index of `u` and `v` is defined as
.. math::
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}
... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def adamic_adar_index(G, ebunch=None):
| r"""Compute the Adamic-Adar index of all node pairs in ebunch.
Adamic-Adar index of `u` and `v` is defined as
.. math::
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{\log |\Gamma(w)|}
where $\Gamma(u)$ denotes the set of neighbors of $u$.
This index leads to zero-division for nodes only... |
References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
The Link Prediction Problem for Social Networks (2004).
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
"""
def predict(u, v):
union_size = len(set(G[u]) | set(G[v]))
if union_size == 0:
... | 150 | 150 | 501 | 30 | 120 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | adamic_adar_index | adamic_adar_index | 153 | 205 | 153 | 155 | f9c952fc244da53b9bedada2de8cad16d4c3fe9d | bigcode/the-stack | train |
57427195bdc4dafbf3cdbc23 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def cn_soundarajan_hopcroft(G, ebunch=None, community="community"):
r"""Count the number of common neighbors of all node pairs in ebunch
using community information.
For two nodes $u$ and $v$, this function computes the number of
c... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def cn_soundarajan_hopcroft(G, ebunch=None, community="community"):
| r"""Count the number of common neighbors of all node pairs in ebunch
using community information.
For two nodes $u$ and $v$, this function computes the number of
common neighbors and bonus one for each common neighbor belonging to
the same community as $u$ and $v$. Mathematically,
.. math:... | Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.preferential_attachment(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
... print(f"({u}, {v}) -> {p}")
(0, 1) -> 16
(2, 3) -> 16
References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
The Link Pre... | 209 | 209 | 697 | 36 | 173 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | cn_soundarajan_hopcroft | cn_soundarajan_hopcroft | 358 | 429 | 358 | 360 | c1329e9ca73ae4ed68f5c9563cf4b9bcf3b85f32 | bigcode/the-stack | train |
07f2e6049dcc362681b37f17 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def common_neighbor_centrality(G, ebunch=None, alpha=0.8):
r"""Return the CCPA score for each pair of nodes.
Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
score of all node pairs in ebunch.
CCPA score ... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def common_neighbor_centrality(G, ebunch=None, alpha=0.8):
| r"""Return the CCPA score for each pair of nodes.
Compute the Common Neighbor and Centrality based Parameterized Algorithm(CCPA)
score of all node pairs in ebunch.
CCPA score of `u` and `v` is defined as
.. math::
\alpha \cdot (|\Gamma (u){\cap }^{}\Gamma (v)|)+(1-\alpha )\cdot \frac{N}{... | (u, v) is a
pair of nodes and p is their Adamic-Adar index.
Examples
--------
>>> G = nx.complete_graph(5)
>>> preds = nx.adamic_adar_index(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
... print(f"({u}, {v}) -> {p:.8f}")
(0, 1) -> 2.16404256
(2, 3) -> 2.16404256
Refe... | 256 | 256 | 873 | 36 | 220 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | common_neighbor_centrality | common_neighbor_centrality | 208 | 302 | 208 | 210 | bcd864c5956656afe1aef692da1298839892fb19 | bigcode/the-stack | train |
da04ccd8b0d14672e4ba1a33 | train | function | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"):
"""Compute the ratio of within- and inter-cluster common neighbors
of all node pairs in ebunch.
For two nodes `u` and `v`, if a common neighbor `w` belongs to th... | @not_implemented_for("directed")
@not_implemented_for("multigraph")
def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"):
| """Compute the ratio of within- and inter-cluster common neighbors
of all node pairs in ebunch.
For two nodes `u` and `v`, if a common neighbor `w` belongs to the
same community as them, `w` is considered as within-cluster common
neighbor of `u` and `v`. Otherwise, it is considered as
inter-clu... | "({u}, {v}) -> {p:.8f}")
(0, 3) -> 0.50000000
References
----------
.. [1] Sucheta Soundarajan and John Hopcroft.
Using community information to improve the precision of link
prediction methods.
In Proceedings of the 21st international conference companion on
World Wide Web ... | 256 | 256 | 894 | 38 | 218 | SultanOrazbayev/networkx | networkx/algorithms/link_prediction.py | Python | within_inter_cluster | within_inter_cluster | 507 | 587 | 507 | 509 | 0c3892d9ab9f804834b248c9aba91bcede1f4603 | bigcode/the-stack | train |
63ccc30e2014fddbf5a74083 | train | class | class TileCacheTestBase(object):
always_loads_metadata = False
def setup(self):
self.cache_dir = tempfile.mkdtemp()
def teardown(self):
if hasattr(self, 'cache_dir') and os.path.exists(self.cache_dir):
shutil.rmtree(self.cache_dir)
def create_tile(self, coord=(0, 0, 4)):
... | class TileCacheTestBase(object):
| always_loads_metadata = False
def setup(self):
self.cache_dir = tempfile.mkdtemp()
def teardown(self):
if hasattr(self, 'cache_dir') and os.path.exists(self.cache_dir):
shutil.rmtree(self.cache_dir)
def create_tile(self, coord=(0, 0, 4)):
return Tile(coord,
... | .apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# ... | 256 | 256 | 1,212 | 7 | 248 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | TileCacheTestBase | TileCacheTestBase | 45 | 193 | 45 | 45 | b7044edd1f47ca502bc2d7dff072a78817e92686 | bigcode/the-stack | train |
45826f1773b1eeb449903bbf | train | class | class TestQuadkeyFileTileCache(TileCacheTestBase):
def setup(self):
TileCacheTestBase.setup(self)
self.cache = FileCache(self.cache_dir, 'png', directory_layout='quadkey')
def test_store_tile(self):
tile = self.create_tile((3, 4, 2))
self.cache.store_tile(tile)
tile_loca... | class TestQuadkeyFileTileCache(TileCacheTestBase):
| def setup(self):
TileCacheTestBase.setup(self)
self.cache = FileCache(self.cache_dir, 'png', directory_layout='quadkey')
def test_store_tile(self):
tile = self.create_tile((3, 4, 2))
self.cache.store_tile(tile)
tile_location = os.path.join(self.cache_dir, '11.png' )
... | .05)
assert self.cache.store_tile(self.create_tile((0, 0, 1))) == False
finally:
t.join()
assert self.cache.store_tile(self.create_tile((0, 0, 1))) == True
class TestQuadkeyFileTileCache(TileCacheTestBase):
| 64 | 64 | 100 | 12 | 51 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | TestQuadkeyFileTileCache | TestQuadkeyFileTileCache | 289 | 298 | 289 | 289 | c41eaffb190c6cd3c4fcc767d188458bc389de99 | bigcode/the-stack | train |
1a19c337705aee37b8e7be34 | train | class | class TestMBTileLevelCache(TileCacheTestBase):
always_loads_metadata = True
def setup(self):
TileCacheTestBase.setup(self)
self.cache = MBTilesLevelCache(self.cache_dir)
def test_level_files(self):
eq_(os.listdir(self.cache_dir), [])
self.cache.store_tile(self.create_tile(... | class TestMBTileLevelCache(TileCacheTestBase):
| always_loads_metadata = True
def setup(self):
TileCacheTestBase.setup(self)
self.cache = MBTilesLevelCache(self.cache_dir)
def test_level_files(self):
eq_(os.listdir(self.cache_dir), [])
self.cache.store_tile(self.create_tile((0, 0, 1)))
eq_(os.listdir(self.cache_d... | ((0, 0, 1))) == True
class TestQuadkeyFileTileCache(TileCacheTestBase):
def setup(self):
TileCacheTestBase.setup(self)
self.cache = FileCache(self.cache_dir, 'png', directory_layout='quadkey')
def test_store_tile(self):
tile = self.create_tile((3, 4, 2))
self.cache.store_tile(... | 123 | 123 | 413 | 11 | 111 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | TestMBTileLevelCache | TestMBTileLevelCache | 301 | 339 | 301 | 301 | b055eaaf640967335382a530faeb4e0cafb12059 | bigcode/the-stack | train |
cc764f74daf039700310d111 | train | class | class TestFileTileCache(TileCacheTestBase):
def setup(self):
TileCacheTestBase.setup(self)
self.cache = FileCache(self.cache_dir, 'png')
def test_store_tile(self):
tile = self.create_tile((5, 12, 4))
self.cache.store_tile(tile)
tile_location = os.path.join(self.cache_dir... | class TestFileTileCache(TileCacheTestBase):
| def setup(self):
TileCacheTestBase.setup(self)
self.cache = FileCache(self.cache_dir, 'png')
def test_store_tile(self):
tile = self.create_tile((5, 12, 4))
self.cache.store_tile(tile)
tile_location = os.path.join(self.cache_dir,
'04', '000', '000', '005', '00... | Tile((0, 0, 4), ImageSource(BytesIO(b'foo')))
tile.stored = True
self.cache.store_tile(tile)
assert self.cache.is_cached(tile)
tile = Tile((0, 0, 4))
assert not self.cache.is_cached(tile)
def test_remove(self):
tile = self.create_tile((1, 0, 4))
self.creat... | 164 | 164 | 549 | 10 | 154 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | TestFileTileCache | TestFileTileCache | 195 | 249 | 195 | 195 | eede0cd229c7933e16875201ce23812703bed287 | bigcode/the-stack | train |
f9b5852c4e613076f99cce92 | train | class | class TestMBTileCache(TileCacheTestBase):
def setup(self):
TileCacheTestBase.setup(self)
self.cache = MBTilesCache(os.path.join(self.cache_dir, 'tmp.mbtiles'))
def test_load_empty_tileset(self):
assert self.cache.load_tiles([Tile(None)]) == True
assert self.cache.load_tiles([Til... | class TestMBTileCache(TileCacheTestBase):
| def setup(self):
TileCacheTestBase.setup(self)
self.cache = MBTilesCache(os.path.join(self.cache_dir, 'tmp.mbtiles'))
def test_load_empty_tileset(self):
assert self.cache.load_tiles([Tile(None)]) == True
assert self.cache.load_tiles([Tile(None), Tile(None), Tile(None)]) == True
... | (open(loc, 'rb'))
def test_load_metadata_missing_tile(self):
tile = Tile((0, 0, 0))
self.cache.load_tile_metadata(tile)
assert tile.timestamp == 0
assert tile.size == 0
def create_cached_tile(self, tile):
loc = self.cache.tile_location(tile, create_dir=True)
wit... | 102 | 102 | 340 | 10 | 92 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | TestMBTileCache | TestMBTileCache | 252 | 286 | 252 | 252 | d84fb89ab3bc75c0aea2c182f474a28e6557c85f | bigcode/the-stack | train |
b0b762898a6025597a5cf500 | train | function | def timestamp_is_now(timestamp, delta=5):
return abs(timestamp - time.time()) <= delta
| def timestamp_is_now(timestamp, delta=5):
| return abs(timestamp - time.time()) <= delta
| import create_tmp_image_buf, is_png
from nose.tools import eq_, assert_raises
tile_image = create_tmp_image_buf((256, 256), color='blue')
tile_image2 = create_tmp_image_buf((256, 256), color='red')
def timestamp_is_now(timestamp, delta=5):
| 64 | 64 | 21 | 10 | 54 | kaiCu/mapproxy | mapproxy/test/unit/test_cache_tile.py | Python | timestamp_is_now | timestamp_is_now | 42 | 43 | 42 | 42 | aefce0ad35bead2676cee0f3af5733ad0fabd492 | bigcode/the-stack | train |
758fa7afd5fd044f21213e3c | train | class | class NoMoreMessages(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
| class NoMoreMessages(Exception):
| def __init__(self, m=''):
super().__init__('Not part of flight' + m)
| WrongLength(NotAMessage):
actual: int
expected: int
def __init__(self, actual: int, expected: int, m=''):
self.actual = actual
self.expected = expected
super().__init__('Wrong buffer length' + m)
class NoMoreMessages(Exception):
| 64 | 64 | 29 | 6 | 58 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | NoMoreMessages | NoMoreMessages | 29 | 31 | 29 | 29 | 12a986c804c15f42c8ade1a0d1d20cf1a764c1a2 | bigcode/the-stack | train |
d79553d0a5f116f8f1d7255e | train | class | class EndOfFile(Exception):
pass
| class EndOfFile(Exception):
| pass
| int, m=''):
self.actual = actual
self.expected = expected
super().__init__('Wrong buffer length' + m)
class NoMoreMessages(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
class EndOfFile(Exception):
| 64 | 64 | 9 | 6 | 58 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | EndOfFile | EndOfFile | 34 | 35 | 34 | 34 | ae75cb858982dc70f937f20921d726e2db860744 | bigcode/the-stack | train |
c63a891f88fdf5f4e76ad969 | train | class | class CrcMismatch(NotAMessage):
totalBytes: int
def __init__(self, totalBytes: int, m=''):
self.totalBytes = totalBytes
super().__init__('CRC Mismatch' + m)
| class CrcMismatch(NotAMessage):
| totalBytes: int
def __init__(self, totalBytes: int, m=''):
self.totalBytes = totalBytes
super().__init__('CRC Mismatch' + m)
| OfFlightException(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
class NotAMessage(Exception):
def __init__(self, m=''):
super().__init__('Not a message' + m)
class CrcMismatch(NotAMessage):
| 64 | 64 | 49 | 8 | 56 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | CrcMismatch | CrcMismatch | 11 | 16 | 11 | 11 | 79dc34fe66713761c484bd90939e99900024ea88 | bigcode/the-stack | train |
4405edd368c68a152fb54c85 | train | class | class NotAMessage(Exception):
def __init__(self, m=''):
super().__init__('Not a message' + m)
| class NotAMessage(Exception):
| def __init__(self, m=''):
super().__init__('Not a message' + m)
| class NotPartOfFlightException(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
class NotAMessage(Exception):
| 37 | 64 | 28 | 6 | 31 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | NotAMessage | NotAMessage | 6 | 8 | 6 | 6 | 80ddf40d78c77883b629c79c9ca1ca730ef6f943 | bigcode/the-stack | train |
1aa90673c81e0f9ba626da49 | train | class | class EndOfRecord(Exception):
pass
| class EndOfRecord(Exception):
| pass
| actual
self.expected = expected
super().__init__('Wrong buffer length' + m)
class NoMoreMessages(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
class EndOfFile(Exception):
pass
class EndOfRecord(Exception):
| 64 | 64 | 9 | 6 | 57 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | EndOfRecord | EndOfRecord | 38 | 39 | 38 | 38 | 360008487425bb2eca89517de020b21e69cf25ab | bigcode/the-stack | train |
294c5455dc2e6b08e67847a0 | train | class | class NotPartOfFlightException(Exception):
def __init__(self, m=''):
super().__init__('Not part of flight' + m)
| class NotPartOfFlightException(Exception):
| def __init__(self, m=''):
super().__init__('Not part of flight' + m)
| class NotPartOfFlightException(Exception):
| 8 | 64 | 31 | 8 | 0 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | NotPartOfFlightException | NotPartOfFlightException | 1 | 3 | 1 | 1 | 14c2dbaaa78e11d1253bf42c61fff7dca46d0fdc | bigcode/the-stack | train |
c7a8dfb73eb0346636e0e287 | train | class | class WrongLength(NotAMessage):
actual: int
expected: int
def __init__(self, actual: int, expected: int, m=''):
self.actual = actual
self.expected = expected
super().__init__('Wrong buffer length' + m)
| class WrongLength(NotAMessage):
| actual: int
expected: int
def __init__(self, actual: int, expected: int, m=''):
self.actual = actual
self.expected = expected
super().__init__('Wrong buffer length' + m)
| __('Not a message' + m)
class CrcMismatch(NotAMessage):
totalBytes: int
def __init__(self, totalBytes: int, m=''):
self.totalBytes = totalBytes
super().__init__('CRC Mismatch' + m)
class WrongLength(NotAMessage):
| 64 | 64 | 59 | 7 | 57 | azemon/mgl_efis_plotter | mgl_efis_plotter/Exceptions.py | Python | WrongLength | WrongLength | 19 | 26 | 19 | 19 | 91a30cdc038ef37d3986efbfccbe14b7b1223d3d | bigcode/the-stack | train |
be0465079e57801f66caf0f3 | train | function | def sample_user(email='test@example.com', password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
| def sample_user(email='test@example.com', password='testpass'):
| """Create a sample user"""
return get_user_model().objects.create_user(email, password)
| from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@example.com', password='testpass'):
| 41 | 64 | 34 | 14 | 26 | demirtaserdem/django-rest-adv | app/core/tests/test_models.py | Python | sample_user | sample_user | 7 | 9 | 7 | 7 | 9e5aa5731c94d49d82aedb52975c175ad1a16301 | bigcode/the-stack | train |
867759144624015cc7137f75 | train | class | class ModalTests(TestCase):
def test_case_user_with_email_successful(self):
"""Test creating a new user with an email is successful"""
email = 'test@example.com'
password = 'Testpass123'
user = get_user_model().objects.create_user(
email=email,
password=passw... | class ModalTests(TestCase):
| def test_case_user_with_email_successful(self):
"""Test creating a new user with an email is successful"""
email = 'test@example.com'
password = 'Testpass123'
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.as... | from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@example.com', password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
class ModalTests(TestC... | 67 | 149 | 499 | 6 | 61 | demirtaserdem/django-rest-adv | app/core/tests/test_models.py | Python | ModalTests | ModalTests | 12 | 81 | 12 | 13 | f43cca002e9caeb79d9fb8d70b2ea2f20267c426 | bigcode/the-stack | train |
7fceea69d7406600a9d0a1b1 | train | function | def build_continent_map(map_date,val='Active', continent = 'World', pop = 1):
df_continent = get_df_projections()
if continent !='World':
df_continent = df_continent.loc[df_continent.Continent == continent] #Filter by continent
if map_date is None:
return None
if isinstance(map_date, s... | def build_continent_map(map_date,val='Active', continent = 'World', pop = 1):
| df_continent = get_df_projections()
if continent !='World':
df_continent = df_continent.loc[df_continent.Continent == continent] #Filter by continent
if map_date is None:
return None
if isinstance(map_date, str):
map_date = datetime.datetime.strptime(map_date, '%Y-%m-%d').date(... | import datetime
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from textwrap import wrap
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from assets.mappings import get_states, get_colors
from projections.utils import get_cols, g... | 101 | 256 | 1,116 | 21 | 79 | solomon3m/solomon4m.github.io | projections/visuals_funcs.py | Python | build_continent_map | build_continent_map | 14 | 111 | 14 | 14 | 8e5f9d344a5f72e42078c9a493034a63887a219c | bigcode/the-stack | train |
f0ffde84b7531bf6579e2c18 | train | function | def find_smallest_scope(state, country, continent):
location = state
if state in 'None':
if country is 'None':
location = continent
else:
location = country
return location
| def find_smallest_scope(state, country, continent):
| location = state
if state in 'None':
if country is 'None':
location = continent
else:
location = country
return location
| 0,0)',
'color': 'lightgray',
'activecolor': 'gray'
}
)
graph = dcc.Graph(
id='us-projection-map',
figure=fig
)
return graph
return
def find_smallest_scope(state, country, continent):
| 64 | 64 | 47 | 11 | 52 | solomon3m/solomon4m.github.io | projections/visuals_funcs.py | Python | find_smallest_scope | find_smallest_scope | 202 | 209 | 202 | 202 | 988cf9522ca081644b8d0b2d9cb0ff9cb8aad640 | bigcode/the-stack | train |
ab2228eaa7885cd882871310 | train | function | def build_state_projection(state, country, continent, vals):
location = find_smallest_scope(state, country, continent)
df_projections = get_df_projections()
df_projections_sub = df_projections.loc[ (df_projections.Province == state) & (df_projections.Country == country)]
if continent not in ['US', 'Worl... | def build_state_projection(state, country, continent, vals):
| location = find_smallest_scope(state, country, continent)
df_projections = get_df_projections()
df_projections_sub = df_projections.loc[ (df_projections.Province == state) & (df_projections.Country == country)]
if continent not in ['US', 'World']:
df_projections_sub = df_projections_sub.loc[(df_... | ',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True, # lakes
lakecolor='rgb(255, 255, 255)'
),
modebar={
'orientation': 'v',
'bgcolor': 'rgba(0,0,0,0)',
... | 176 | 176 | 587 | 12 | 163 | solomon3m/solomon4m.github.io | projections/visuals_funcs.py | Python | build_state_projection | build_state_projection | 211 | 274 | 211 | 211 | d1aa988537957f8026da28083ed9919fa64eb62f | bigcode/the-stack | train |
c7c71278e3575fc9fb069843 | train | function | def build_us_map(map_date,val='Active', pop = 1):
if map_date is None:
return None
if isinstance(map_date, str):
map_date = datetime.datetime.strptime(map_date, '%Y-%m-%d').date()
df_us = get_df_us()
df_map = df_us.loc[df_us['Day']==map_date]
df_map = df_map.loc[df_us['Province']!=... | def build_us_map(map_date,val='Active', pop = 1):
| if map_date is None:
return None
if isinstance(map_date, str):
map_date = datetime.datetime.strptime(map_date, '%Y-%m-%d').date()
df_us = get_df_us()
df_map = df_us.loc[df_us['Day']==map_date]
df_map = df_map.loc[df_us['Province']!='US']
states = get_states()
df_map.loc[:,... | format(add_cases(val))]), width=10))
))
fig.update_layout(
margin=dict(l=10, r=10, t=50, b=50),
title_text=add_cases('{} Predicted {} {}'.format(map_date.strftime('%b %d,%Y'), continent, val)),
geo = dict(
scope= continent.lower() if c... | 256 | 256 | 1,001 | 15 | 240 | solomon3m/solomon4m.github.io | projections/visuals_funcs.py | Python | build_us_map | build_us_map | 114 | 200 | 114 | 114 | d6f92d17803bbe1dd64932a35950ce6ed2a982ad | bigcode/the-stack | train |
c650b2b24117a3322a661356 | train | function | def get_stat(d, val, scope):
if d is None:
return None
if isinstance(d, str):
d = datetime.datetime.strptime(d, '%Y-%m-%d').date()
df_projections = get_df_projections()
if scope == 'US':
df_projections_sub = df_projections.loc[(df_projections.Country == scope) & (df_projections.P... | def get_stat(d, val, scope):
| if d is None:
return None
if isinstance(d, str):
d = datetime.datetime.strptime(d, '%Y-%m-%d').date()
df_projections = get_df_projections()
if scope == 'US':
df_projections_sub = df_projections.loc[(df_projections.Country == scope) & (df_projections.Province == 'None')]
elif ... | modebar={
'orientation': 'v',
'bgcolor': 'rgba(0,0,0,0)',
'color': 'lightgray',
'activecolor': 'gray'
}
)
graph = dcc.Graph(
id='projection-graph',
figure=fig
)
return... | 81 | 81 | 273 | 9 | 71 | solomon3m/solomon4m.github.io | projections/visuals_funcs.py | Python | get_stat | get_stat | 276 | 305 | 276 | 276 | 939ff1737f26b141db50a8933987b8504b0f39a2 | bigcode/the-stack | train |
5ef858232161fbb0f182959b | train | function | def lazy_import():
from cryptoapis.model.limit_greater_than_allowed_error import LimitGreaterThanAllowedError
globals()['LimitGreaterThanAllowedError'] = LimitGreaterThanAllowedError
| def lazy_import():
| from cryptoapis.model.limit_greater_than_allowed_error import LimitGreaterThanAllowedError
globals()['LimitGreaterThanAllowedError'] = LimitGreaterThanAllowedError
|
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
| 64 | 64 | 38 | 4 | 60 | xan187/Crypto_APIs_2.0_SDK_Python | cryptoapis/model/limit_greater_than_allowed.py | Python | lazy_import | lazy_import | 30 | 32 | 30 | 30 | 903aae378f2607137c08845e2f32ddcf7146e2bc | bigcode/the-stack | train |
025efdb515511d7499af7c94 | train | class | class LimitGreaterThanAllowed(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_na... | class LimitGreaterThanAllowed(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides ... | 256 | 256 | 1,336 | 8 | 247 | xan187/Crypto_APIs_2.0_SDK_Python | cryptoapis/model/limit_greater_than_allowed.py | Python | LimitGreaterThanAllowed | LimitGreaterThanAllowed | 35 | 186 | 35 | 35 | 3dab713750db4f75e34fb65565bcef07e47653e5 | bigcode/the-stack | train |
11727af2ca16f038fad5feaa | train | class | class UI:
def __init__(self, board):
# Store board
self.board = board
# Board scale
self.boardScale = (6, 3)
# Offset when drawing board
self.boardOffset = [3, 2]
# Set labels
self.instructionLabels = [
"Ru... | class UI:
| def __init__(self, board):
# Store board
self.board = board
# Board scale
self.boardScale = (6, 3)
# Offset when drawing board
self.boardOffset = [3, 2]
# Set labels
self.instructionLabels = [
"Run/Pause Al... | import curses, time
from annealing import *
from plotter import *
class UI:
| 18 | 256 | 1,890 | 3 | 15 | Brobz/8queen_annealing | ui.py | Python | UI | UI | 6 | 199 | 6 | 6 | c4c7bb2cac1d5cc81ce9a3c0f722ee5d6114a2fe | bigcode/the-stack | train |
cbdef1b2bc98709da042ecb8 | train | class | class Reconstruction2d(data.Dataset):
"""Simple dataset for 2d reconstruction for auto-encoders etc..
"""
def __init__(
self,
inp_paths,
transform=transforms.Identity(),
in_memory=True,
inp_dtype=np.float32,
epoch_multiplier=1, # Prete... | class Reconstruction2d(data.Dataset):
| """Simple dataset for 2d reconstruction for auto-encoders etc..
"""
def __init__(
self,
inp_paths,
transform=transforms.Identity(),
in_memory=True,
inp_dtype=np.float32,
epoch_multiplier=1, # Pretend to have more data in one epoch
... | .offset
target = target[:, off[0]:-off[0], off[1]:-off[1]]
sample = {
'inp': torch.as_tensor(inp.astype(self.inp_dtype)),
'target': torch.as_tensor(target.astype(self.target_dtype)),
'cube_meta': np.inf,
'fname': str(index)
}
return sam... | 109 | 109 | 366 | 7 | 101 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | Reconstruction2d | Reconstruction2d | 627 | 675 | 627 | 627 | 4ba7b500785ac66039c82a87d618a0407b1ffbc1 | bigcode/the-stack | train |
2bddfa13d83fd1c53be6c0f4 | train | class | class PatchCreator(data.Dataset):
"""Dataset iterator class that creates 3D image patches from HDF5 files.
It implements the PyTorch ``Dataset`` interface and is meant to be used
with a PyTorch ``DataLoader`` (or the modified
:py:class:`elektronn3.training.trainer.train_utils.DelayedDataLoader`, if it ... | class PatchCreator(data.Dataset):
| """Dataset iterator class that creates 3D image patches from HDF5 files.
It implements the PyTorch ``Dataset`` interface and is meant to be used
with a PyTorch ``DataLoader`` (or the modified
:py:class:`elektronn3.training.trainer.train_utils.DelayedDataLoader`, if it is
used with :py:class:`elektr... | # ELEKTRONN3 - Neural Network Toolkit
#
# Copyright (c) 2017 - now
# Max Planck Institute of Neurobiology, Munich, Germany
# Authors: Martin Drawitsch, Philipp Schubert
__all__ = ['PatchCreator', 'SimpleNeuroData2d', 'Segmentation2d', 'Reconstruction2d']
import logging
import os
import sys
import traceback
from os.pa... | 220 | 256 | 4,327 | 6 | 213 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | PatchCreator | PatchCreator | 33 | 443 | 33 | 33 | ecf41429eabe27d2815f01f82ee308c4a02c994e | bigcode/the-stack | train |
c89f531e0c1c3bdba1f83a34 | train | class | class Segmentation2d(data.Dataset):
"""Simple dataset for 2d segmentation.
Expects a list of ``input_paths`` and ``target_paths`` where
``target_paths[i]`` is the target of ``input_paths[i]`` for all i.
"""
def __init__(
self,
inp_paths,
target_paths,
... | class Segmentation2d(data.Dataset):
| """Simple dataset for 2d segmentation.
Expects a list of ``input_paths`` and ``target_paths`` where
``target_paths[i]`` is the target of ``input_paths[i]`` for all i.
"""
def __init__(
self,
inp_paths,
target_paths,
transform=transforms.Identity(),
... | memory -> no need to keep the file open.
def __getitem__(self, index):
# Get z slices
inp = self.inp[:, index]
target = self.target[index]
inp, target = self.transform(inp, target)
inp = torch.as_tensor(inp)
target = torch.as_tensor(target)
fname = str(index... | 159 | 159 | 531 | 8 | 150 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | Segmentation2d | Segmentation2d | 558 | 623 | 558 | 558 | a681946499ea12ce70731dcd4e33615975fece8e | bigcode/the-stack | train |
2304045104674e766ba16775 | train | class | class TripletData2d(data.Dataset):
"""Simple dataset for 2D triplet loss training.
"""
def __init__(
self,
inp_paths,
transform=transforms.Identity(),
invariant_transform=None,
in_memory=True,
inp_dtype=np.float32,
epoch_mul... | class TripletData2d(data.Dataset):
| """Simple dataset for 2D triplet loss training.
"""
def __init__(
self,
inp_paths,
transform=transforms.Identity(),
invariant_transform=None,
in_memory=True,
inp_dtype=np.float32,
epoch_multiplier=1, # Pretend to have more ... | .inp_paths) # Wrap around to support epoch_multiplier
if self.in_memory:
inp = self.inps[index]
else:
inp = np.array(imageio.imread(self.inp_paths[index]), dtype=self.inp_dtype)
if inp.ndim == 2: # (H, W)
inp = inp[None] # (C=1, H, W)
while ... | 201 | 201 | 670 | 9 | 191 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | TripletData2d | TripletData2d | 678 | 754 | 678 | 678 | 9013654a60ab3e8bbcdfdc3401c1d85dbd22d0a0 | bigcode/the-stack | train |
f8087e21c1c803f496d84304 | train | class | class _DefaultCubeMeta:
def __getitem__(self, *args, **kwargs): return np.inf
| class _DefaultCubeMeta:
| def __getitem__(self, *args, **kwargs): return np.inf
| numpy as np
import torch
from torch.utils import data
from elektronn3.data import coord_transforms, transforms
from elektronn3.data.sources import DataSource, HDF5DataSource, slice_3d
logger = logging.getLogger('elektronn3log')
class _DefaultCubeMeta:
| 64 | 64 | 23 | 6 | 58 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | _DefaultCubeMeta | _DefaultCubeMeta | 28 | 29 | 28 | 28 | dc43e5ea19176a36a7991cc4586fcc8a930d8ce7 | bigcode/the-stack | train |
1ea0a1d8f8609588df6f7bc8 | train | class | class SimpleNeuroData2d(data.Dataset):
""" 2D Dataset class for neuro_data_cdhw, reading from a single HDF5 file.
Delivers 2D image slices from the (H, W) plane at given D indices.
Not scalable, keeps everything in memory.
This is just a minimalistic proof of concept.
"""
def __init__(
... | class SimpleNeuroData2d(data.Dataset):
| """ 2D Dataset class for neuro_data_cdhw, reading from a single HDF5 file.
Delivers 2D image slices from the (H, W) plane at given D indices.
Not scalable, keeps everything in memory.
This is just a minimalistic proof of concept.
"""
def __init__(
self,
inp_path=None,
... | of input source.'
f'Requested {preview_shape}, but can only deliver {tuple(inp_shape)}.'
)
memstr = ' (in memory)' if in_memory else ''
logger.info(f'\nPreview data{memstr}:')
logger.info(f' input: {fname}[{key}]: {inp_h5.shape} ({inp_h5.dtype})\n')
inp_np = slice_3d(... | 192 | 192 | 641 | 10 | 181 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | SimpleNeuroData2d | SimpleNeuroData2d | 483 | 554 | 483 | 483 | d816f43aead7a0f3b8028fc9aa7dda3d40d187da | bigcode/the-stack | train |
af123ab746a07853a57e52a9 | train | function | def get_preview_batch(
h5data: Tuple[str, str],
preview_shape: Optional[Tuple[int, ...]] = None,
transform: Optional[Callable] = None,
in_memory: bool = False
) -> torch.Tensor:
fname, key = h5data
inp_h5 = h5py.File(fname, 'r')[key]
if in_memory:
inp_h5 = inp_h5.valu... | def get_preview_batch(
h5data: Tuple[str, str],
preview_shape: Optional[Tuple[int, ...]] = None,
transform: Optional[Callable] = None,
in_memory: bool = False
) -> torch.Tensor:
| fname, key = h5data
inp_h5 = h5py.File(fname, 'r')[key]
if in_memory:
inp_h5 = inp_h5.value
dim = len(preview_shape) # 2D or 3D
inp_shape = np.array(inp_h5.shape[-dim:])
if preview_shape is None: # Slice everything
inp_lo = np.zeros_like(inp_shape)
inp_hi = inp_shape
... | : {target_fname}[{target_key}]: {target_source.shape} ({target_source.dtype})')
if not np.all(cube_meta == np.inf):
logger.info(f' cube_meta: {cube_meta}')
inp_sources.append(inp_source)
target_sources.append(target_source)
logger.info('')
... | 126 | 126 | 421 | 52 | 73 | riegerfr/elektronn3 | elektronn3/data/cnndata.py | Python | get_preview_batch | get_preview_batch | 446 | 480 | 446 | 451 | 624564e6328213b89b2b9f0598a1eb25b37fb0b3 | bigcode/the-stack | train |
cdf7317a789b3dc19af35dee | train | class | class PatchGroup(pulumi.CustomResource):
baseline_id: pulumi.Output[str]
"""
The ID of the patch baseline to register the patch group with.
"""
patch_group: pulumi.Output[str]
"""
The name of the patch group that should be registered with the patch baseline.
"""
def __init__(__self__... | class PatchGroup(pulumi.CustomResource):
| baseline_id: pulumi.Output[str]
"""
The ID of the patch baseline to register the patch group with.
"""
patch_group: pulumi.Output[str]
"""
The name of the patch group that should be registered with the patch baseline.
"""
def __init__(__self__, resource_name, opts=None, baseline_id=N... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class PatchGroup(pulumi.CustomResource... | 77 | 146 | 489 | 9 | 67 | lemonade-hq/pulumi-aws | sdk/python/pulumi_aws/ssm/patch_group.py | Python | PatchGroup | PatchGroup | 11 | 63 | 11 | 11 | a9606894032326ede35e596dba574e9e8bb0e7fe | bigcode/the-stack | train |
ee22c47b06294e66dbe3e8a9 | train | class | @SkipIf.not_krpc
class TestKrpcMetrics(CustomClusterTestSuite):
"""Test for KRPC metrics that require special arguments during cluster startup."""
RPCZ_URL = 'http://localhost:25000/rpcz?json'
METRICS_URL = 'http://localhost:25000/metrics?json'
TEST_QUERY = 'select count(*) from tpch_parquet.lineitem l1 \
... | @SkipIf.not_krpc
class TestKrpcMetrics(CustomClusterTestSuite):
| """Test for KRPC metrics that require special arguments during cluster startup."""
RPCZ_URL = 'http://localhost:25000/rpcz?json'
METRICS_URL = 'http://localhost:25000/metrics?json'
TEST_QUERY = 'select count(*) from tpch_parquet.lineitem l1 \
join tpch_parquet.lineitem l2 where l1.l_orderkey = l2.l_orderk... |
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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/... | 229 | 229 | 765 | 18 | 210 | mjacobs/impala | tests/custom_cluster/test_krpc_metrics.py | Python | TestKrpcMetrics | TestKrpcMetrics | 27 | 108 | 27 | 28 | 114403e85a7ba311d60bf50a15e2ccd3614e4e2a | bigcode/the-stack | train |
b6615d75610f20cb609745de | train | function | def require_params(oauth_request, parameters=None):
""" Ensures that the request contains all required parameters. """
if parameters is None:
parameters = []
params = [
'oauth_consumer_key',
'oauth_nonce',
'oauth_signature',
'oauth_signature_method',
'oauth_ti... | def require_params(oauth_request, parameters=None):
| """ Ensures that the request contains all required parameters. """
if parameters is None:
parameters = []
params = [
'oauth_consumer_key',
'oauth_nonce',
'oauth_signature',
'oauth_signature_method',
'oauth_timestamp'
]
params.extend(parameters)
mi... | not None:
token = oauth.Token(
token.key.encode('ascii', 'ignore'), token.secret.encode('ascii', 'ignore'))
oauth_server.verify_request(oauth_request, consumer, token)
except oauth.Error:
return False
return True
def require_params(oauth_request, parameters=None):
| 64 | 64 | 137 | 10 | 53 | Andrea-MariaDB-2/treeio | treeio/core/api/auth/utils.py | Python | require_params | require_params | 47 | 68 | 47 | 47 | 5e448f324e06dc607a385f46f5751c7778fbc095 | bigcode/the-stack | train |
f8559b9c8a437f78807a5314 | train | function | def verify_oauth_request(request, oauth_request, consumer, token=None):
""" Helper function to verify requests. """
from treeio.core.api.auth.store import store
# Check nonce
if not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']):
return False
# Verify request
t... | def verify_oauth_request(request, oauth_request, consumer, token=None):
| """ Helper function to verify requests. """
from treeio.core.api.auth.store import store
# Check nonce
if not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']):
return False
# Verify request
try:
oauth_server = oauth.Server()
oauth_server.add_signa... | if 'HTTP_AUTHORIZATION' in request.META:
headers['Authorization'] = request.META['HTTP_AUTHORIZATION']
return oauth.Request.from_request(request.method, request.build_absolute_uri(request.path), headers,
dict(request.REQUEST))
def verify_oauth_request(request, oauth... | 64 | 64 | 209 | 15 | 49 | Andrea-MariaDB-2/treeio | treeio/core/api/auth/utils.py | Python | verify_oauth_request | verify_oauth_request | 19 | 44 | 19 | 19 | 28b3327f34948b24d72c1e484dabae31b0035697 | bigcode/the-stack | train |
55889d3d3335d8e0f85650ce | train | function | def get_oauth_request(request):
""" Converts a Django request object into an `oauth2.Request` object. """
headers = {}
if 'HTTP_AUTHORIZATION' in request.META:
headers['Authorization'] = request.META['HTTP_AUTHORIZATION']
return oauth.Request.from_request(request.method, request.build_absolute_u... | def get_oauth_request(request):
| """ Converts a Django request object into an `oauth2.Request` object. """
headers = {}
if 'HTTP_AUTHORIZATION' in request.META:
headers['Authorization'] = request.META['HTTP_AUTHORIZATION']
return oauth.Request.from_request(request.method, request.build_absolute_uri(request.path), headers,
... | # encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
import oauth2 as oauth
from django.http import HttpResponse
def get_oauth_request(request):
| 52 | 64 | 77 | 7 | 44 | Andrea-MariaDB-2/treeio | treeio/core/api/auth/utils.py | Python | get_oauth_request | get_oauth_request | 10 | 16 | 10 | 10 | 4d3e89e24ba2c7531bd5d028e0daad0de52c14b5 | bigcode/the-stack | train |
16370d7a78e112910a9cab3c | train | function | def convert_to_vap( tas_arr, hur_arr ):
esa_arr = 6.112 * np.exp( 17.62 * tas_arr / (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46*tas_arr / (272.62 + tas_arr) )
return (hur_arr * esa_arr) / 100
| def convert_to_vap( tas_arr, hur_arr ):
| esa_arr = 6.112 * np.exp( 17.62 * tas_arr / (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46*tas_arr / (272.62 + tas_arr) )
return (hur_arr * esa_arr) / 100
| tas_arr/ (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46 * tas_arr / (272.62 + tas_arr) )
return vap_arr/esa_arr * 100
def convert_to_vap( tas_arr, hur_arr ):
| 64 | 64 | 83 | 12 | 51 | ua-snap/downscale | old/old_bin/convert_ts31_to_vap.py | Python | convert_to_vap | convert_to_vap | 6 | 9 | 6 | 6 | 9da425ac88a67bf62604118c7cfae9c5d3f811db | bigcode/the-stack | train |
f8fddb5887049645c4c4e22c | train | function | def convert_to_hur( tas_arr, vap_arr ):
esa_arr = 6.112 * np.exp( 17.62 * tas_arr/ (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46 * tas_arr / (272.62 + tas_arr) )
return vap_arr/esa_arr * 100
| def convert_to_hur( tas_arr, vap_arr ):
| esa_arr = 6.112 * np.exp( 17.62 * tas_arr/ (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46 * tas_arr / (272.62 + tas_arr) )
return vap_arr/esa_arr * 100
| # script to convert the newly generated Relative Humidity
def convert_to_hur( tas_arr, vap_arr ):
| 23 | 64 | 81 | 12 | 10 | ua-snap/downscale | old/old_bin/convert_ts31_to_vap.py | Python | convert_to_hur | convert_to_hur | 2 | 5 | 2 | 2 | 92835bb8d24b01fa39be096c63862c14683ec5c4 | bigcode/the-stack | train |
70666320359298ed58f8623c | train | function | def run( x ):
tas = rasterio.open( x[0] )
hur = rasterio.open( x[1] )
meta = tas.meta
meta[ 'dtype' ] = 'float32' # set it to float32
meta.update( compress='lzw' )
meta.pop( 'transform' )
tas_arr = tas.read( 1 )
hur_arr = hur.read( 1 )
vap_arr = convert_to_vap( tas_arr, hur_arr )
# mask it:
mask = tas.re... | def run( x ):
| tas = rasterio.open( x[0] )
hur = rasterio.open( x[1] )
meta = tas.meta
meta[ 'dtype' ] = 'float32' # set it to float32
meta.update( compress='lzw' )
meta.pop( 'transform' )
tas_arr = tas.read( 1 )
hur_arr = hur.read( 1 )
vap_arr = convert_to_vap( tas_arr, hur_arr )
# mask it:
mask = tas.read_masks( 1 )
... | 6.112 * np.exp( 17.62 * tas_arr / (243.12 + tas_arr) )
# esa_arr = 6.112 * np.exp( 22.46*tas_arr / (272.62 + tas_arr) )
return (hur_arr * esa_arr) / 100
def run( x ):
| 71 | 71 | 237 | 5 | 65 | ua-snap/downscale | old/old_bin/convert_ts31_to_vap.py | Python | run | run | 10 | 37 | 10 | 10 | 1c3c53a39c4bab8d953c8a873e8702ef445514bc | bigcode/the-stack | train |
d5a1adcaae9f655c1f1e3322 | train | function | @pytest.fixture(scope="module")
def subscription_sync(subscriber_client, topic):
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_SYNC
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)... | @pytest.fixture(scope="module")
def subscription_sync(subscriber_client, topic):
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_SYNC
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)
except NotFound:
subscription = subscriber_client.create_subscriptio... | = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)
except NotFound:
subscription = subscriber_client.create_subscription(
request={"name": subscription_path, "topic": topic}
)
yield subscription.name
@pytest.fixture(scope="module... | 64 | 64 | 168 | 15 | 48 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | subscription_sync | subscription_sync | 102 | 127 | 102 | 103 | 154671119c704b3c03153cd5592e6f3a57c00074 | bigcode/the-stack | train |
06d423da6243b315aac86609 | train | function | def test_receive_synchronously(publisher_client, topic, subscription_sync, capsys):
_publish_messages(publisher_client, topic)
subscriber.synchronous_pull(PROJECT_ID, SUBSCRIPTION_SYNC)
out, _ = capsys.readouterr()
assert "Received" in out
assert f"{subscription_sync}" in out
| def test_receive_synchronously(publisher_client, topic, subscription_sync, capsys):
| _publish_messages(publisher_client, topic)
subscriber.synchronous_pull(PROJECT_ID, SUBSCRIPTION_SYNC)
out, _ = capsys.readouterr()
assert "Received" in out
assert f"{subscription_sync}" in out
| subscriber.listen_for_errors(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert subscription_async in out
assert "threw an exception" in out
def test_receive_synchronously(publisher_client, topic, subscription_sync, capsys):
| 64 | 64 | 70 | 17 | 46 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive_synchronously | test_receive_synchronously | 409 | 417 | 409 | 409 | 6d000b0bacc36f835e09aa9235364c5c015a623a | bigcode/the-stack | train |
b6077d50ca11b619042da42d | train | function | def test_create(subscriber_client, subscription_admin, capsys):
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_path}
)
except NotFound:
... | def test_create(subscriber_client, subscription_admin, capsys):
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_path}
)
except NotFound:
pass
subscriber.create_subscription(PROJECT_ID, TOPIC, SU... | , AssertionError, max_time=60)
def eventually_consistent_test():
subscriber.list_subscriptions_in_project(PROJECT_ID)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_consistent_test()
def test_create(subscriber_client, subscription_admin, capsys):
| 64 | 64 | 97 | 13 | 51 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_create | test_create | 204 | 219 | 204 | 204 | 81f2902747473a00e9c7c92788a1f41fa78f492b | bigcode/the-stack | train |
9b89e10a412192886d0d63ff | train | function | def test_create_push(subscriber_client, subscription_admin, capsys):
# The scope of `subscription_path` is limited to this function.
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={... | def test_create_push(subscriber_client, subscription_admin, capsys):
# The scope of `subscription_path` is limited to this function.
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_path}
)
except NotFound:
pass
subscriber.create_push_subscription(PROJECT_ID, TOPIC... | ()
assert "Created subscription with ordering" in out
assert f"{subscription_admin}" in out
assert "enable_message_ordering: true" in out
def test_create_push(subscriber_client, subscription_admin, capsys):
# The scope of `subscription_path` is limited to this function.
| 64 | 64 | 117 | 29 | 34 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_create_push | test_create_push | 317 | 332 | 317 | 318 | 0d171a84897350e0174c76427b3fe196fd4f8ac7 | bigcode/the-stack | train |
d8308de7baf66bfe31acbc1e | train | function | def test_receive_synchronously_with_lease(
publisher_client, topic, subscription_sync, capsys
):
@backoff.on_exception(backoff.expo, Unknown, max_time=300)
def run_sample():
_publish_messages(publisher_client, topic, message_num=3)
subscriber.synchronous_pull_with_lease_management(PROJECT_ID... | def test_receive_synchronously_with_lease(
publisher_client, topic, subscription_sync, capsys
):
@backoff.on_exception(backoff.expo, Unknown, max_time=300)
| def run_sample():
_publish_messages(publisher_client, topic, message_num=3)
subscriber.synchronous_pull_with_lease_management(PROJECT_ID, SUBSCRIPTION_SYNC)
run_sample()
out, _ = capsys.readouterr()
# Sometimes the subscriber only gets 1 or 2 messages and test fails.
# I think it'... | capsys.readouterr()
assert "Received" in out
assert f"{subscription_sync}" in out
def test_receive_synchronously_with_lease(
publisher_client, topic, subscription_sync, capsys
):
@backoff.on_exception(backoff.expo, Unknown, max_time=300)
| 64 | 64 | 147 | 40 | 23 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive_synchronously_with_lease | test_receive_synchronously_with_lease | 420 | 435 | 420 | 423 | 5bc456bc00ee15890385e5cafa443749ec03c068 | bigcode/the-stack | train |
effe2beb9c5cdcb4765302ac | train | function | @pytest.fixture(scope="module")
def topic(publisher_client):
topic_path = publisher_client.topic_path(PROJECT_ID, TOPIC)
try:
topic = publisher_client.get_topic(request={"topic": topic_path})
except: # noqa
topic = publisher_client.create_topic(request={"name": topic_path})
yield topi... | @pytest.fixture(scope="module")
def topic(publisher_client):
| topic_path = publisher_client.topic_path(PROJECT_ID, TOPIC)
try:
topic = publisher_client.get_topic(request={"topic": topic_path})
except: # noqa
topic = publisher_client.create_topic(request={"name": topic_path})
yield topic.name
publisher_client.delete_topic(request={"topic": t... | PROJECT_ID}.appspot.com/push2"
DEFAULT_MAX_DELIVERY_ATTEMPTS = 5
UPDATED_MAX_DELIVERY_ATTEMPTS = 20
@pytest.fixture(scope="module")
def publisher_client():
yield pubsub_v1.PublisherClient()
@pytest.fixture(scope="module")
def topic(publisher_client):
| 64 | 64 | 82 | 12 | 52 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | topic | topic | 49 | 60 | 49 | 50 | 508e1167bff9ce94068259669046a7197b50e8ce | bigcode/the-stack | train |
02c74fefaa07c2689c17a180 | train | function | def test_receive(publisher_client, topic, subscription_async, capsys):
_publish_messages(publisher_client, topic)
subscriber.receive_messages(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in out
assert "message" in out
| def test_receive(publisher_client, topic, subscription_async, capsys):
| _publish_messages(publisher_client, topic)
subscriber.receive_messages(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in out
assert "message" in out
| _exception(backoff.expo, AssertionError, max_time=60)
def eventually_consistent_test():
with pytest.raises(Exception):
subscriber_client.get_subscription(
request={"subscription": subscription_admin}
)
eventually_consistent_test()
def test_receive(publisher_clien... | 64 | 64 | 76 | 15 | 49 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive | test_receive | 358 | 366 | 358 | 358 | 84d334a66aa522f28bc12a1cd47545294a8799f9 | bigcode/the-stack | train |
69417c395f30ba9131ad283d | train | function | def test_listen_for_errors(publisher_client, topic, subscription_async, capsys):
_publish_messages(publisher_client, topic)
subscriber.listen_for_errors(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert subscription_async in out
assert "threw an exception" in out
| def test_listen_for_errors(publisher_client, topic, subscription_async, capsys):
| _publish_messages(publisher_client, topic)
subscriber.listen_for_errors(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert subscription_async in out
assert "threw an exception" in out
| JECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in out
assert "message" in out
def test_listen_for_errors(publisher_client, topic, subscription_async, capsys):
| 64 | 64 | 75 | 18 | 45 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_listen_for_errors | test_listen_for_errors | 398 | 406 | 398 | 399 | d659ffc183f19f2d5b4589883de42d112c46320b | bigcode/the-stack | train |
4844b2a3d99d813248f85081 | train | function | def test_receive_with_custom_attributes(
publisher_client, topic, subscription_async, capsys
):
_publish_messages(publisher_client, topic, origin="python-sample")
subscriber.receive_messages_with_custom_attributes(
PROJECT_ID, SUBSCRIPTION_ASYNC, 5
)
out, _ = capsys.readouterr()
asser... | def test_receive_with_custom_attributes(
publisher_client, topic, subscription_async, capsys
):
| _publish_messages(publisher_client, topic, origin="python-sample")
subscriber.receive_messages_with_custom_attributes(
PROJECT_ID, SUBSCRIPTION_ASYNC, 5
)
out, _ = capsys.readouterr()
assert subscription_async in out
assert "message" in out
assert "origin" in out
assert "python... | , SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in out
assert "message" in out
def test_receive_with_custom_attributes(
publisher_client, topic, subscription_async, capsys
):
| 64 | 64 | 103 | 20 | 43 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive_with_custom_attributes | test_receive_with_custom_attributes | 369 | 383 | 369 | 372 | f2e4b18cb1d8438f2a397963239e9fa944b94f75 | bigcode/the-stack | train |
e6c3d1b84d2e43cacf19c08c | train | function | def test_create_subscription_with_dead_letter_policy(
subscriber_client, subscription_dlq, dead_letter_topic, capsys
):
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_dlq}
)
except NotFound:
pass
subscriber.create_subscription_with_... | def test_create_subscription_with_dead_letter_policy(
subscriber_client, subscription_dlq, dead_letter_topic, capsys
):
| try:
subscriber_client.delete_subscription(
request={"subscription": subscription_dlq}
)
except NotFound:
pass
subscriber.create_subscription_with_dead_letter_topic(
PROJECT_ID, TOPIC, SUBSCRIPTION_DLQ, DEAD_LETTER_TOPIC
)
out, _ = capsys.readouterr()
... | pass
subscriber.create_subscription(PROJECT_ID, TOPIC, SUBSCRIPTION_ADMIN)
out, _ = capsys.readouterr()
assert f"{subscription_admin}" in out
def test_create_subscription_with_dead_letter_policy(
subscriber_client, subscription_dlq, dead_letter_topic, capsys
):
| 64 | 64 | 148 | 25 | 38 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_create_subscription_with_dead_letter_policy | test_create_subscription_with_dead_letter_policy | 222 | 239 | 222 | 224 | df5f512953089649fe533a452adfcf25edc74da4 | bigcode/the-stack | train |
20f52010c53f71c82739131b | train | function | @pytest.fixture(scope="module")
def dead_letter_topic(publisher_client):
topic_path = publisher_client.topic_path(PROJECT_ID, DEAD_LETTER_TOPIC)
try:
dead_letter_topic = publisher_client.get_topic(request={"topic": topic_path})
except NotFound:
dead_letter_topic = publisher_client.create_to... | @pytest.fixture(scope="module")
def dead_letter_topic(publisher_client):
| topic_path = publisher_client.topic_path(PROJECT_ID, DEAD_LETTER_TOPIC)
try:
dead_letter_topic = publisher_client.get_topic(request={"topic": topic_path})
except NotFound:
dead_letter_topic = publisher_client.create_topic(request={"name": topic_path})
yield dead_letter_topic.name
... | = publisher_client.get_topic(request={"topic": topic_path})
except: # noqa
topic = publisher_client.create_topic(request={"name": topic_path})
yield topic.name
publisher_client.delete_topic(request={"topic": topic.name})
@pytest.fixture(scope="module")
def dead_letter_topic(publisher_client):
| 64 | 64 | 93 | 14 | 50 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | dead_letter_topic | dead_letter_topic | 63 | 74 | 63 | 64 | da5830a4cc6de28427f8372e07d4aa3565ff6f9f | bigcode/the-stack | train |
476a5e1890f7b6efd2a1572e | train | function | @flaky(max_runs=3, min_passes=1)
def test_remove_dead_letter_policy(subscription_dlq, capsys):
subscription_after_update = subscriber.remove_dead_letter_policy(
PROJECT_ID, TOPIC, SUBSCRIPTION_DLQ
)
out, _ = capsys.readouterr()
assert subscription_dlq in out
assert subscription_after_update... | @flaky(max_runs=3, min_passes=1)
def test_remove_dead_letter_policy(subscription_dlq, capsys):
| subscription_after_update = subscriber.remove_dead_letter_policy(
PROJECT_ID, TOPIC, SUBSCRIPTION_DLQ
)
out, _ = capsys.readouterr()
assert subscription_dlq in out
assert subscription_after_update.dead_letter_policy.dead_letter_topic == ""
| assert dead_letter_topic in out
assert subscription_dlq in out
assert f"max_delivery_attempts: {UPDATED_MAX_DELIVERY_ATTEMPTS}" in out
@flaky(max_runs=3, min_passes=1)
def test_remove_dead_letter_policy(subscription_dlq, capsys):
| 64 | 64 | 85 | 27 | 36 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_remove_dead_letter_policy | test_remove_dead_letter_policy | 285 | 293 | 285 | 286 | 4c73ce2ab65f0841236da7fc964c123afb795e1d | bigcode/the-stack | train |
39f5613dd218216cfb1812c9 | train | function | @pytest.fixture(scope="module")
def subscription_admin(subscriber_client, topic):
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
... | @pytest.fixture(scope="module")
def subscription_admin(subscriber_client, topic):
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)
except NotFound:
subscription = subscriber_client.create_subscripti... | _topic.name
publisher_client.delete_topic(request={"topic": dead_letter_topic.name})
@pytest.fixture(scope="module")
def subscriber_client():
subscriber_client = pubsub_v1.SubscriberClient()
yield subscriber_client
subscriber_client.close()
@pytest.fixture(scope="module")
def subscription_admin(subsc... | 64 | 64 | 89 | 15 | 49 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | subscription_admin | subscription_admin | 84 | 99 | 84 | 85 | a9714095ead882ad236709827c5189d5abe74f28 | bigcode/the-stack | train |
7e4826997a010f478104d7c6 | train | function | def test_create_subscription_with_ordering(
subscriber_client, subscription_admin, capsys
):
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_path}
... | def test_create_subscription_with_ordering(
subscriber_client, subscription_admin, capsys
):
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ADMIN
)
try:
subscriber_client.delete_subscription(
request={"subscription": subscription_path}
)
except NotFound:
pass
subscriber.create_subscription_with_ordering(PROJECT_... | , TOPIC, SUBSCRIPTION_DLQ
)
out, _ = capsys.readouterr()
assert subscription_dlq in out
assert subscription_after_update.dead_letter_policy.dead_letter_topic == ""
def test_create_subscription_with_ordering(
subscriber_client, subscription_admin, capsys
):
| 63 | 64 | 130 | 19 | 44 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_create_subscription_with_ordering | test_create_subscription_with_ordering | 296 | 314 | 296 | 298 | 7f689a7ed6217f7e828871aad526a121ca0986e5 | bigcode/the-stack | train |
4e2cfddf86be5649e292afe3 | train | function | @flaky(max_runs=3, min_passes=1)
def test_receive_with_delivery_attempts(
publisher_client, topic, dead_letter_topic, subscription_dlq, capsys
):
# The dlq subscription raises 404 before it's ready.
# We keep retrying up to 10 minutes for mitigating the flakiness.
@backoff.on_exception(backoff.expo, (U... | @flaky(max_runs=3, min_passes=1)
def test_receive_with_delivery_attempts(
publisher_client, topic, dead_letter_topic, subscription_dlq, capsys
):
# The dlq subscription raises 404 before it's ready.
# We keep retrying up to 10 minutes for mitigating the flakiness.
@backoff.on_exception(backoff.expo, (U... | def run_sample():
_publish_messages(publisher_client, topic)
subscriber.receive_messages_with_delivery_attempts(PROJECT_ID, SUBSCRIPTION_DLQ, 90)
run_sample()
out, _ = capsys.readouterr()
assert f"Listening for messages on {subscription_dlq}.." in out
assert "With delivery attempt... | @flaky(max_runs=3, min_passes=1)
def test_receive_with_delivery_attempts(
publisher_client, topic, dead_letter_topic, subscription_dlq, capsys
):
# The dlq subscription raises 404 before it's ready.
# We keep retrying up to 10 minutes for mitigating the flakiness.
@backoff.on_exception(backoff.expo, (U... | 93 | 64 | 172 | 93 | 0 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive_with_delivery_attempts | test_receive_with_delivery_attempts | 242 | 259 | 242 | 249 | 547364e7840c52fc2a247eb915f0c13ece463206 | bigcode/the-stack | train |
a5798fd3ce10abecbeb95032 | train | function | def test_delete(subscriber_client, subscription_admin):
subscriber.delete_subscription(PROJECT_ID, SUBSCRIPTION_ADMIN)
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def eventually_consistent_test():
with pytest.raises(Exception):
subscriber_client.get_subscription(
... | def test_delete(subscriber_client, subscription_admin):
| subscriber.delete_subscription(PROJECT_ID, SUBSCRIPTION_ADMIN)
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def eventually_consistent_test():
with pytest.raises(Exception):
subscriber_client.get_subscription(
request={"subscription": subscription_admi... | ):
subscriber.update_push_subscription(
PROJECT_ID, TOPIC, SUBSCRIPTION_ADMIN, NEW_ENDPOINT
)
out, _ = capsys.readouterr()
assert "Subscription updated" in out
assert f"{subscription_admin}" in out
def test_delete(subscriber_client, subscription_admin):
| 64 | 64 | 77 | 10 | 53 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_delete | test_delete | 345 | 355 | 345 | 345 | e3b41c46db54b5df1d3372ba83dd9b501df4896e | bigcode/the-stack | train |
7ad485c1fd41be57e74f15ff | train | function | @flaky(max_runs=3, min_passes=1)
def test_update_dead_letter_policy(subscription_dlq, dead_letter_topic, capsys):
# We saw internal server error that suggests to retry.
@backoff.on_exception(backoff.expo, (Unknown, InternalServerError), max_time=60)
def run_sample():
subscriber.update_subscription... | @flaky(max_runs=3, min_passes=1)
def test_update_dead_letter_policy(subscription_dlq, dead_letter_topic, capsys):
# We saw internal server error that suggests to retry.
@backoff.on_exception(backoff.expo, (Unknown, InternalServerError), max_time=60)
| def run_sample():
subscriber.update_subscription_with_dead_letter_policy(
PROJECT_ID,
TOPIC,
SUBSCRIPTION_DLQ,
DEAD_LETTER_TOPIC,
UPDATED_MAX_DELIVERY_ATTEMPTS,
)
run_sample()
out, _ = capsys.readouterr()
assert dead_letter_to... | @flaky(max_runs=3, min_passes=1)
def test_update_dead_letter_policy(subscription_dlq, dead_letter_topic, capsys):
# We saw internal server error that suggests to retry.
@backoff.on_exception(backoff.expo, (Unknown, InternalServerError), max_time=60)
| 66 | 64 | 165 | 66 | 0 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_update_dead_letter_policy | test_update_dead_letter_policy | 262 | 282 | 262 | 267 | 49e742c5924f7a299a288e92563f08794f791a2a | bigcode/the-stack | train |
611f996835931ed4c0f56bcd | train | function | def test_receive_with_flow_control(publisher_client, topic, subscription_async, capsys):
_publish_messages(publisher_client, topic)
subscriber.receive_messages_with_flow_control(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in ... | def test_receive_with_flow_control(publisher_client, topic, subscription_async, capsys):
| _publish_messages(publisher_client, topic)
subscriber.receive_messages_with_flow_control(PROJECT_ID, SUBSCRIPTION_ASYNC, 5)
out, _ = capsys.readouterr()
assert "Listening" in out
assert subscription_async in out
assert "message" in out
| )
out, _ = capsys.readouterr()
assert subscription_async in out
assert "message" in out
assert "origin" in out
assert "python-sample" in out
def test_receive_with_flow_control(publisher_client, topic, subscription_async, capsys):
| 64 | 64 | 82 | 18 | 45 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_receive_with_flow_control | test_receive_with_flow_control | 386 | 395 | 386 | 387 | 52426b75752e91d04fc0583ac317803af61cbdb2 | bigcode/the-stack | train |
f8244d46201c9399183399d2 | train | function | def test_list_in_project(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def eventually_consistent_test():
subscriber.list_subscriptions_in_project(PROJECT_ID)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_cons... | def test_list_in_project(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
| def eventually_consistent_test():
subscriber.list_subscriptions_in_project(PROJECT_ID)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_consistent_test()
| scriptions_in_topic(PROJECT_ID, TOPIC)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_consistent_test()
def test_list_in_project(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
| 64 | 64 | 72 | 30 | 34 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_list_in_project | test_list_in_project | 194 | 201 | 194 | 195 | 7c3dae3cea638c9e39e1e804e33a161e9993f689 | bigcode/the-stack | train |
aa768c596715822a5a34f388 | train | function | def _publish_messages(publisher_client, topic, message_num=5, **attrs):
for n in range(message_num):
data = f"message {n}".encode("utf-8")
publish_future = publisher_client.publish(topic, data, **attrs)
publish_future.result()
| def _publish_messages(publisher_client, topic, message_num=5, **attrs):
| for n in range(message_num):
data = f"message {n}".encode("utf-8")
publish_future = publisher_client.publish(topic, data, **attrs)
publish_future.result()
| dead_letter_topic=dead_letter_topic, max_delivery_attempts=10
),
}
subscription = subscriber_client.create_subscription(request)
yield subscription.name
subscriber_client.delete_subscription(request={"subscription": subscription.name})
def _publish_messages(publishe... | 64 | 64 | 60 | 18 | 46 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | _publish_messages | _publish_messages | 177 | 181 | 177 | 177 | 1123c0d9b5509c85594182dada46c49991c0c961 | bigcode/the-stack | train |
c307ad407ad7c73c23289bd0 | train | function | @pytest.fixture(scope="module")
def subscriber_client():
subscriber_client = pubsub_v1.SubscriberClient()
yield subscriber_client
subscriber_client.close()
| @pytest.fixture(scope="module")
def subscriber_client():
| subscriber_client = pubsub_v1.SubscriberClient()
yield subscriber_client
subscriber_client.close()
| = publisher_client.get_topic(request={"topic": topic_path})
except NotFound:
dead_letter_topic = publisher_client.create_topic(request={"name": topic_path})
yield dead_letter_topic.name
publisher_client.delete_topic(request={"topic": dead_letter_topic.name})
@pytest.fixture(scope="module")
def su... | 64 | 64 | 32 | 10 | 54 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | subscriber_client | subscriber_client | 77 | 81 | 77 | 78 | ac6ee9df8883af0546d79602097ffbedd1283296 | bigcode/the-stack | train |
86f3b26773ca98fa636de135 | train | function | @pytest.fixture(scope="module")
def subscription_async(subscriber_client, topic):
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ASYNC
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
... | @pytest.fixture(scope="module")
def subscription_async(subscriber_client, topic):
| subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_ASYNC
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)
except NotFound:
subscription = subscriber_client.create_subscripti... | _subscription(request={"subscription": subscription.name})
except NotFound:
print("When Unknown error happens, the server might have"
" successfully deleted the subscription under the cover, so"
" we ignore NotFound")
delete_subscription()
@pytest.fixture(scop... | 64 | 64 | 102 | 15 | 49 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | subscription_async | subscription_async | 130 | 147 | 130 | 131 | 3fb7cd947f86f9fe85e147ef95919e8fbfa2908c | bigcode/the-stack | train |
c5a29394cc192cd59cb8724a | train | function | @pytest.fixture(scope="module")
def subscription_dlq(subscriber_client, topic, dead_letter_topic):
from google.cloud.pubsub_v1.types import DeadLetterPolicy
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_DLQ
)
try:
subscription = subscriber_client.get... | @pytest.fixture(scope="module")
def subscription_dlq(subscriber_client, topic, dead_letter_topic):
| from google.cloud.pubsub_v1.types import DeadLetterPolicy
subscription_path = subscriber_client.subscription_path(
PROJECT_ID, SUBSCRIPTION_DLQ
)
try:
subscription = subscriber_client.get_subscription(
request={"subscription": subscription_path}
)
except NotFoun... | except NotFound:
subscription = subscriber_client.create_subscription(
request={"name": subscription_path, "topic": topic}
)
yield subscription.name
subscriber_client.delete_subscription(request={"subscription": subscription.name})
@pytest.fixture(scope="module")
def subscription_... | 64 | 64 | 154 | 20 | 44 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | subscription_dlq | subscription_dlq | 150 | 174 | 150 | 151 | 2afc4d5e0e6acf2d131c3a5f8558931530b69a73 | bigcode/the-stack | train |
42f39e61445868ac0177801c | train | function | @pytest.fixture(scope="module")
def publisher_client():
yield pubsub_v1.PublisherClient()
| @pytest.fixture(scope="module")
def publisher_client():
| yield pubsub_v1.PublisherClient()
| POINT = f"https://{PROJECT_ID}.appspot.com/push"
NEW_ENDPOINT = f"https://{PROJECT_ID}.appspot.com/push2"
DEFAULT_MAX_DELIVERY_ATTEMPTS = 5
UPDATED_MAX_DELIVERY_ATTEMPTS = 20
@pytest.fixture(scope="module")
def publisher_client():
| 64 | 64 | 20 | 10 | 53 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | publisher_client | publisher_client | 44 | 46 | 44 | 45 | 941e4845d6f4c437db5f59f0b43a706a41398cdf | bigcode/the-stack | train |
c49572131af7b6c48ed931b2 | train | function | def test_list_in_topic(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def eventually_consistent_test():
subscriber.list_subscriptions_in_topic(PROJECT_ID, TOPIC)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_c... | def test_list_in_topic(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
| def eventually_consistent_test():
subscriber.list_subscriptions_in_topic(PROJECT_ID, TOPIC)
out, _ = capsys.readouterr()
assert subscription_admin in out
eventually_consistent_test()
| data = f"message {n}".encode("utf-8")
publish_future = publisher_client.publish(topic, data, **attrs)
publish_future.result()
def test_list_in_topic(subscription_admin, capsys):
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
| 64 | 64 | 75 | 30 | 34 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_list_in_topic | test_list_in_topic | 184 | 191 | 184 | 185 | 7ba8382a304a643070874c3502d2211343dda878 | bigcode/the-stack | train |
e6539f97ea24b431cd756233 | train | function | def test_update(subscription_admin, capsys):
subscriber.update_push_subscription(
PROJECT_ID, TOPIC, SUBSCRIPTION_ADMIN, NEW_ENDPOINT
)
out, _ = capsys.readouterr()
assert "Subscription updated" in out
assert f"{subscription_admin}" in out
| def test_update(subscription_admin, capsys):
| subscriber.update_push_subscription(
PROJECT_ID, TOPIC, SUBSCRIPTION_ADMIN, NEW_ENDPOINT
)
out, _ = capsys.readouterr()
assert "Subscription updated" in out
assert f"{subscription_admin}" in out
| ": subscription_path}
)
except NotFound:
pass
subscriber.create_push_subscription(PROJECT_ID, TOPIC, SUBSCRIPTION_ADMIN, ENDPOINT)
out, _ = capsys.readouterr()
assert f"{subscription_admin}" in out
def test_update(subscription_admin, capsys):
| 64 | 64 | 62 | 9 | 54 | manojpandey/python-pubsub | samples/snippets/subscriber_test.py | Python | test_update | test_update | 335 | 342 | 335 | 335 | 185729d0e63e55c43e584902578826a0805e5cd8 | bigcode/the-stack | train |
eafc43d4f14f2d187121fe5a | train | function | def maxProfitWithKTransaction(prices, k):
if not len(prices):
return 0
evenProfits = [0 for d in prices]
oddProfits = [0 for d in prices]
for transaction in range(1, k + 1):
maxThusFar = float('-inf')
if transaction % 2 == 1:
currentProfits = oddProfits
pr... | def maxProfitWithKTransaction(prices, k):
| if not len(prices):
return 0
evenProfits = [0 for d in prices]
oddProfits = [0 for d in prices]
for transaction in range(1, k + 1):
maxThusFar = float('-inf')
if transaction % 2 == 1:
currentProfits = oddProfits
previousProfits = evenProfits
else:
... | profits[transaction][day] = max(profits[transaction][day - 1], maxThusFar + prices[day])
return profits[-1][-1]
# Solution 2
# O(nk) time | O(n) space
def maxProfitWithKTransaction(prices, k):
| 64 | 64 | 207 | 11 | 52 | mamane19/coding-interview-gym | algoexpert.io/python/Max_Profit_With_K_Transactions.py | Python | maxProfitWithKTransaction | maxProfitWithKTransaction | 17 | 33 | 17 | 17 | 22033a8be7a037fd53230f55bb301c739365b553 | bigcode/the-stack | train |
9c75e925fc18c6967a5e1a68 | train | function | def maxProfitWithKTransaction(prices, k):
if not len(prices):
return 0
profits = [[0 for day in prices] for transaction in range(len(k + 1))]
for transaction in range(1, k + 1):
maxThusFar = float('-inf')
for day in range(1, prices + 1):
maxThusFar = max(maxThusFar, profi... | def maxProfitWithKTransaction(prices, k):
| if not len(prices):
return 0
profits = [[0 for day in prices] for transaction in range(len(k + 1))]
for transaction in range(1, k + 1):
maxThusFar = float('-inf')
for day in range(1, prices + 1):
maxThusFar = max(maxThusFar, profits[transaction - 1][day - 1] - prices[day ... | # Solution 1
# O(nk) time | O(nk) space
def maxProfitWithKTransaction(prices, k):
| 31 | 64 | 143 | 11 | 19 | mamane19/coding-interview-gym | algoexpert.io/python/Max_Profit_With_K_Transactions.py | Python | maxProfitWithKTransaction | maxProfitWithKTransaction | 3 | 12 | 3 | 3 | 48b149ab4314a49178a8e477dc7d76a0b1740fdf | bigcode/the-stack | train |
ba4fd41163ed90ff389af50d | train | function | @pytest.mark.parametrize("file_name,num_bags",test_data3)
def test_contains(file_name,num_bags):
bags = Bags(file_name)
assert(bags.bags_inside() == num_bags) | @pytest.mark.parametrize("file_name,num_bags",test_data3)
def test_contains(file_name,num_bags):
| bags = Bags(file_name)
assert(bags.bags_inside() == num_bags) | @pytest.mark.parametrize("file_name,num_bags",test_data2)
def test_contains(file_name,num_bags):
bags = Bags(file_name)
assert(bags.contains() == num_bags)
@pytest.mark.parametrize("file_name,num_bags",test_data3)
def test_contains(file_name,num_bags):
| 64 | 64 | 43 | 23 | 41 | dh256/adventofcode | 2020/Day7/tests.py | Python | test_contains | test_contains | 21 | 24 | 21 | 22 | e9cdbf2e931a76cdc9c7bdaa53a8f2079a47863e | bigcode/the-stack | train |
82f414237a1b5941a7854988 | train | function | @pytest.mark.parametrize("bag_desc,colour,contents",test_data1)
def test_bags(bag_desc,colour,contents):
assert(Bags._get_colour(bag_desc) == colour)
assert(Bags._get_contents(bag_desc) == contents)
| @pytest.mark.parametrize("bag_desc,colour,contents",test_data1)
def test_bags(bag_desc,colour,contents):
| assert(Bags._get_colour(bag_desc) == colour)
assert(Bags._get_contents(bag_desc) == contents)
| 3),("dotted black",4)])]
test_data2=[("test.txt",4)]
test_data3=[("test.txt",32),("test2.txt",126)]
@pytest.mark.parametrize("bag_desc,colour,contents",test_data1)
def test_bags(bag_desc,colour,contents):
| 64 | 64 | 55 | 27 | 37 | dh256/adventofcode | 2020/Day7/tests.py | Python | test_bags | test_bags | 11 | 14 | 11 | 12 | 7754b5aa3b2fcca7cde017525112e03fc83a4afa | bigcode/the-stack | train |
04a0e7d4252801fc30d0d82c | train | function | @pytest.mark.parametrize("file_name,num_bags",test_data2)
def test_contains(file_name,num_bags):
bags = Bags(file_name)
assert(bags.contains() == num_bags)
| @pytest.mark.parametrize("file_name,num_bags",test_data2)
def test_contains(file_name,num_bags):
| bags = Bags(file_name)
assert(bags.contains() == num_bags)
| def test_bags(bag_desc,colour,contents):
assert(Bags._get_colour(bag_desc) == colour)
assert(Bags._get_contents(bag_desc) == contents)
@pytest.mark.parametrize("file_name,num_bags",test_data2)
def test_contains(file_name,num_bags):
| 63 | 64 | 41 | 23 | 40 | dh256/adventofcode | 2020/Day7/tests.py | Python | test_contains | test_contains | 16 | 19 | 16 | 17 | 707aa94ed1c1536cd426f125069a972a450a92df | bigcode/the-stack | train |
6dffde788655a81d325f617e | train | class | class TestGameplay:
"""
The class contains tests running through entire games.
The purpose of this test class is to check that macro functionality, such as
moving, promotion, taking, stalemates etc. works in practice.
"""
def _run_gameplay_test(self, moves, result):
game = Game()
... | class TestGameplay:
| """
The class contains tests running through entire games.
The purpose of this test class is to check that macro functionality, such as
moving, promotion, taking, stalemates etc. works in practice.
"""
def _run_gameplay_test(self, moves, result):
game = Game()
game.reset()
... | from alphadraughts import Game
class TestGameplay:
| 12 | 165 | 553 | 4 | 7 | TTitcombe/AlphaDraughts | tests/systemtests/draughts/test_gameplay.py | Python | TestGameplay | TestGameplay | 4 | 92 | 4 | 4 | 2242ab1b809692968ea7c20cb2e50aca1d1e1126 | bigcode/the-stack | train |
4046de2700acc392058ed96e | train | class | class CreateEventsRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list =... | class CreateEventsRequest:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import pprint
import re
import six
class CreateEventsRequest:
| 21 | 171 | 572 | 5 | 15 | wuchen-huawei/huaweicloud-sdk-python-v3 | huaweicloud-sdk-ces/huaweicloudsdkces/v1/model/create_events_request.py | Python | CreateEventsRequest | CreateEventsRequest | 12 | 110 | 12 | 14 | b3fd2ea3b89ad60b746b175cdfea1948d3281011 | bigcode/the-stack | train |
a3977fde4bba888bc94cfd52 | train | class | class ToolWalletTest(PicacoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.rpc_timeout = 120
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_wallet_tool()
def picacoin_wallet_process(... | class ToolWalletTest(PicacoinTestFramework):
| def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.rpc_timeout = 120
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
self.skip_if_no_wallet_tool()
def picacoin_wallet_process(self, *args):
binary = self.config["e... | #!/usr/bin/env python3
# Copyright (c) 2018-2020 The Picacoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test picacoin-wallet."""
import hashlib
import os
import stat
import subprocess
import textwrap
from... | 122 | 256 | 4,901 | 11 | 110 | picacoin/picacoin | test/functional/tool_wallet.py | Python | ToolWalletTest | ToolWalletTest | 21 | 407 | 21 | 21 | 13458e0a2ede9d1b07a58033ad214111424c86c1 | bigcode/the-stack | train |
73778472dc10b893045ec97f | train | class | class Python38ParserSingle(Python38Parser, PythonParserSingle):
pass
| class Python38ParserSingle(Python38Parser, PythonParserSingle):
| pass
| _FROM"):
jb_index -= 1
t = tokens[jb_index]
if t.kind != "JUMP_BACK":
return True
return t.attr != tokens[first].off2int()
pass
return False
class Python38ParserSingle(Python38Parser, PythonParserSingle):
| 64 | 64 | 17 | 14 | 49 | NeonOcean/Environment | S4/S4 Decompiler/decompyle3/parsers/p38/base.py | Python | Python38ParserSingle | Python38ParserSingle | 130 | 131 | 130 | 130 | 321d0efd1976ed03cd19b457b158f35c0559676b | bigcode/the-stack | train |
eb1baaf2c6a54ec788682b5f | train | class | class Python38Parser(Python38FullParser):
def __init__(self, debug_parser=PARSER_DEFAULT_DEBUG, compile_mode="exec"):
super(Python38Parser, self).__init__(debug_parser, compile_mode=compile_mode)
self.customized = {}
def remove_rules_38(self):
self.remove_rules(
"""
... | class Python38Parser(Python38FullParser):
| def __init__(self, debug_parser=PARSER_DEFAULT_DEBUG, compile_mode="exec"):
super(Python38Parser, self).__init__(debug_parser, compile_mode=compile_mode)
self.customized = {}
def remove_rules_38(self):
self.remove_rules(
"""
stmt ::= async_for_stmt37... | # Copyright (c) 2020 Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distrib... | 237 | 256 | 936 | 10 | 227 | NeonOcean/Environment | S4/S4 Decompiler/decompyle3/parsers/p38/base.py | Python | Python38Parser | Python38Parser | 25 | 128 | 25 | 25 | 3e1bf57a327a586c50cf15507ecddcf5d7cd97d9 | bigcode/the-stack | train |
b741c1d8a09eee4f44bb25e0 | train | class | @pulumi.output_type
class GetConnectionResult:
def __init__(__self__, connection_arn=None, connection_status=None, owner_account_id=None, tags=None):
if connection_arn and not isinstance(connection_arn, str):
raise TypeError("Expected argument 'connection_arn' to be a str")
pulumi.set(__... | @pulumi.output_type
class GetConnectionResult:
| def __init__(__self__, connection_arn=None, connection_status=None, owner_account_id=None, tags=None):
if connection_arn and not isinstance(connection_arn, str):
raise TypeError("Expected argument 'connection_arn' to be a str")
pulumi.set(__self__, "connection_arn", connection_arn)
... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | 121 | 136 | 455 | 11 | 110 | pulumi/pulumi-aws-native | sdk/python/pulumi_aws_native/codestarconnections/get_connection.py | Python | GetConnectionResult | GetConnectionResult | 19 | 65 | 19 | 20 | a7b1294c05014d5ccfd966e705ac1b2623aba15a | bigcode/the-stack | train |
c5d352cea0eee959520267cf | train | class | class AwaitableGetConnectionResult(GetConnectionResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetConnectionResult(
connection_arn=self.connection_arn,
connection_status=self.connection_status,
owner... | class AwaitableGetConnectionResult(GetConnectionResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetConnectionResult(
connection_arn=self.connection_arn,
connection_status=self.connection_status,
owner_account_id=self.owner_account_id,
tags=self.tags)
| pulumi.getter
def tags(self) -> Optional[Sequence['outputs.ConnectionTag']]:
"""
Specifies the tags applied to a connection.
"""
return pulumi.get(self, "tags")
class AwaitableGetConnectionResult(GetConnectionResult):
# pylint: disable=using-constant-test
| 64 | 64 | 72 | 21 | 43 | pulumi/pulumi-aws-native | sdk/python/pulumi_aws_native/codestarconnections/get_connection.py | Python | AwaitableGetConnectionResult | AwaitableGetConnectionResult | 68 | 77 | 68 | 69 | e831c2976f5119aa185c8dd36ccde444dba33d16 | bigcode/the-stack | train |
78213d113c68792533ffc5d8 | train | function | @_utilities.lift_output_func(get_connection)
def get_connection_output(connection_arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetConnectionResult]:
"""
Schema for AWS::CodeStarConnections::Connection resource which can be used ... | @_utilities.lift_output_func(get_connection)
def get_connection_output(connection_arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetConnectionResult]:
| """
Schema for AWS::CodeStarConnections::Connection resource which can be used to connect external source providers with AWS CodePipeline
:param str connection_arn: The Amazon Resource Name (ARN) of the connection. The ARN is used as the connection reference when the connection is shared between AWS serv... | ret__.owner_account_id,
tags=__ret__.tags)
@_utilities.lift_output_func(get_connection)
def get_connection_output(connection_arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetConnectionResult]:
| 64 | 64 | 118 | 50 | 14 | pulumi/pulumi-aws-native | sdk/python/pulumi_aws_native/codestarconnections/get_connection.py | Python | get_connection_output | get_connection_output | 103 | 112 | 103 | 105 | c6f93739a89ee5437cecc21180550b11036fc337 | bigcode/the-stack | train |
317c4d4e43cc6d13c0371883 | train | function | def get_connection(connection_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult:
"""
Schema for AWS::CodeStarConnections::Connection resource which can be used to connect external source providers with AWS CodePipeline
:param str con... | def get_connection(connection_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetConnectionResult:
| """
Schema for AWS::CodeStarConnections::Connection resource which can be used to connect external source providers with AWS CodePipeline
:param str connection_arn: The Amazon Resource Name (ARN) of the connection. The ARN is used as the connection reference when the connection is shared between AWS serv... | return GetConnectionResult(
connection_arn=self.connection_arn,
connection_status=self.connection_status,
owner_account_id=self.owner_account_id,
tags=self.tags)
def get_connection(connection_arn: Optional[str] = None,
opts: Optional[pulumi.Invo... | 69 | 69 | 233 | 33 | 36 | pulumi/pulumi-aws-native | sdk/python/pulumi_aws_native/codestarconnections/get_connection.py | Python | get_connection | get_connection | 80 | 100 | 80 | 81 | 847a73929eb38eec4187924ef8aabcd6d7b9df78 | bigcode/the-stack | train |
3109bbda4f0f6615c2c27faa | train | class | class Migration(migrations.Migration):
dependencies = [
('inventory', '0002_tags'),
]
operations = [
migrations.DeleteModel(
name='MachineTagManager',
),
migrations.DeleteModel(
name='TagManager',
),
migrations.AlterField(
... | class Migration(migrations.Migration):
| dependencies = [
('inventory', '0002_tags'),
]
operations = [
migrations.DeleteModel(
name='MachineTagManager',
),
migrations.DeleteModel(
name='TagManager',
),
migrations.AlterField(
model_name='machinetag',
na... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-04 19:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 111 | 7 | 46 | gwhitehawk/zentral | zentral/contrib/inventory/migrations/0003_auto_20160504_1939.py | Python | Migration | Migration | 8 | 30 | 8 | 9 | 0ffbe124beb18abd2a337ed6a1de019ae5b4890b | bigcode/the-stack | train |
25c80b8b62c1eb8be1503914 | train | class | class TestStyler:
def setup_method(self, method):
np.random.seed(24)
self.s = DataFrame({"A": np.random.permutation(range(6))})
self.df = DataFrame({"A": [0, 1], "B": np.random.randn(2)})
self.f = lambda x: x
self.g = lambda x: x
def h(x, foo="bar"):
retu... | class TestStyler:
| def setup_method(self, method):
np.random.seed(24)
self.s = DataFrame({"A": np.random.permutation(range(6))})
self.df = DataFrame({"A": [0, 1], "B": np.random.randn(2)})
self.f = lambda x: x
self.g = lambda x: x
def h(x, foo="bar"):
return pd.Series(f"col... | import copy
import re
import textwrap
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
jinja2 = pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler, _get_level_lengths # noqa # isort:skip
c... | 89 | 256 | 16,153 | 5 | 83 | Ethanator/pandas | pandas/tests/io/formats/test_style.py | Python | TestStyler | TestStyler | 18 | 1,698 | 18 | 18 | 9fff5a937ed8c276ec1370eabe2761c29391657e | bigcode/the-stack | train |
e07d321038bf46855e792392 | train | class | @td.skip_if_no_mpl
class TestStylerMatplotlibDep:
def test_background_gradient(self):
df = pd.DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
for c_map in [None, "YlOrRd"]:
result = df.style.background_gradient(cmap=c_map)._compute().ctx
assert all("#" in x[0] for x in resul... | @td.skip_if_no_mpl
class TestStylerMatplotlibDep:
| def test_background_gradient(self):
df = pd.DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
for c_map in [None, "YlOrRd"]:
result = df.style.background_gradient(cmap=c_map)._compute().ctx
assert all("#" in x[0] for x in result.values())
assert result[(0, 0)] == r... | (a, b, styler):
return (a, b, styler)
styler = self.df.style
result = styler.pipe((f, "styler"), a=1, b=2)
assert result == (1, 2, styler)
def test_no_cell_ids(self):
# GH 35588
# GH 35663
df = pd.DataFrame(data=[[0]])
styler = Styler(df, uuid="_... | 256 | 256 | 1,015 | 16 | 240 | Ethanator/pandas | pandas/tests/io/formats/test_style.py | Python | TestStylerMatplotlibDep | TestStylerMatplotlibDep | 1,701 | 1,791 | 1,701 | 1,702 | 12362a6fed45e8cf94c038e1e5bf725dcb8252f2 | bigcode/the-stack | train |
1f71e0d7c3de3fd8ca1f1876 | train | function | def test_from_custom_template(tmpdir):
p = tmpdir.mkdir("templates").join("myhtml.tpl")
p.write(
textwrap.dedent(
"""\
{% extends "html.tpl" %}
{% block table %}
<h1>{{ table_title|default("My Table") }}</h1>
{{ super() }}
{% endblock table %}"""
... | def test_from_custom_template(tmpdir):
| p = tmpdir.mkdir("templates").join("myhtml.tpl")
p.write(
textwrap.dedent(
"""\
{% extends "html.tpl" %}
{% block table %}
<h1>{{ table_title|default("My Table") }}</h1>
{{ super() }}
{% endblock table %}"""
)
)
result = Styler.from_cus... | tbody",
"after_table",
"before_head_rows",
"head_tr",
"after_head_rows",
"before_rows",
"tr",
"after_rows",
}
result = set(Styler.template.blocks)
assert result == expected
def test_from_custom_template(tmpdir):
| 64 | 64 | 157 | 8 | 55 | Ethanator/pandas | pandas/tests/io/formats/test_style.py | Python | test_from_custom_template | test_from_custom_template | 1,819 | 1,836 | 1,819 | 1,819 | f063e9695602f1daacb7ecf9c126e058ac425704 | bigcode/the-stack | train |
23e84904db0d7168caf07e15 | train | function | def test_block_names():
# catch accidental removal of a block
expected = {
"before_style",
"style",
"table_styles",
"before_cellstyle",
"cellstyle",
"before_table",
"table",
"caption",
"thead",
"tbody",
"after_table",
... | def test_block_names():
# catch accidental removal of a block
| expected = {
"before_style",
"style",
"table_styles",
"before_cellstyle",
"cellstyle",
"before_table",
"table",
"caption",
"thead",
"tbody",
"after_table",
"before_head_rows",
"head_tr",
"after_head_rows"... | 0)] == ctx1[(0, 0)]
assert ctx2[(1, 0)] == ctx1[(1, 0)]
assert ctx2[(2, 0)] == ctx1[(2, 0)]
def test_block_names():
# catch accidental removal of a block
| 63 | 64 | 118 | 14 | 49 | Ethanator/pandas | pandas/tests/io/formats/test_style.py | Python | test_block_names | test_block_names | 1,794 | 1,816 | 1,794 | 1,795 | 3ee2a9d4a8e140b819a0ee18af14ec36707f1e39 | bigcode/the-stack | train |
d061f265bd93a4a2eca7bf4f | train | class | class BaconInstall:
"""
Object responsible with installing bacon
"""
def __init__(self, bacon_jar_location, shell_location, maven_url, version=None):
self.bacon_jar_location = bacon_jar_location
self.shell_location = shell_location
self.maven_url = maven_url
self.latest_... | class BaconInstall:
| """
Object responsible with installing bacon
"""
def __init__(self, bacon_jar_location, shell_location, maven_url, version=None):
self.bacon_jar_location = bacon_jar_location
self.shell_location = shell_location
self.maven_url = maven_url
self.latest_version = None
... | 'filename'
Add retries in case the download fails due to stale server content issue on
repositories.jboss.org
"""
print("Downloading: " + link)
if sys.version_info[0] >= 3:
import urllib.request as request
else:
import urllib2 as request
try:
r = request.urlopen(l... | 247 | 247 | 825 | 4 | 243 | akoufoudakis/bacon | bacon_install.py | Python | BaconInstall | BaconInstall | 160 | 268 | 160 | 160 | 5f6e127cf3caf7d3e27c64173b40c2ee66878d6f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.