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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
97e5db8767093edeac5238fa | train | function | @pytest.mark.parametrize(
"shape, out_chans, chans",
[
([1, 1, 32, 16], 5, 1),
([5, 1, 15, 12], 10, 32),
([3, 2, 13, 18], 1, 16),
([1, 2, 17, 19], 3, 8),
],
)
def test_unet(shape, out_chans, chans):
x = create_input(shape)
num_chans = x.shape[1]
unet = Unet(in_c... | @pytest.mark.parametrize(
"shape, out_chans, chans",
[
([1, 1, 32, 16], 5, 1),
([5, 1, 15, 12], 10, 32),
([3, 2, 13, 18], 1, 16),
([1, 2, 17, 19], 3, 8),
],
)
def test_unet(shape, out_chans, chans):
| x = create_input(shape)
num_chans = x.shape[1]
unet = Unet(in_chans=num_chans, out_chans=out_chans, chans=chans, num_pool_layers=2)
y = unet(x)
assert y.shape[1] == out_chans
| @pytest.mark.parametrize(
"shape, out_chans, chans",
[
([1, 1, 32, 16], 5, 1),
([5, 1, 15, 12], 10, 32),
([3, 2, 13, 18], 1, 16),
([1, 2, 17, 19], 3, 8),
],
)
def test_unet(shape, out_chans, chans):
| 107 | 64 | 175 | 107 | 0 | josmfred/fastMRI | tests/test_models.py | Python | test_unet | test_unet | 18 | 36 | 18 | 27 | 41eeb28c74495ca83d6867e7eca822ff8a514a4e | bigcode/the-stack | train |
5a5db99f31e46c6876122b2a | train | function | def setup(bot):
bot.add_cog(Settings(bot))
| def setup(bot):
| bot.add_cog(Settings(bot))
| 2) ON CONFLICT (id) DO UPDATE SET
theme=EXCLUDED.theme;
"""
await self.bot.db.execute(query, ctx.author.id, theme_id)
self.fetch_config.invalidate(self, ctx.author.id)
await ctx.send(f"Set theme to `{theme}`")
def setup(bot):
| 64 | 64 | 12 | 4 | 60 | ilovetocode2019/Logger | cogs/settings.py | Python | setup | setup | 77 | 78 | 77 | 77 | 062c8337f1a20c7dc55858dae0991fa07c30917b | bigcode/the-stack | train |
1044ac02b35541cc0077a7f7 | train | class | class UserConfig:
@classmethod
def from_record(cls, record):
self = cls()
self.id = record["id"]
self.theme = theme_module.get_theme(record["theme"])
return self
| class UserConfig:
@classmethod
| def from_record(cls, record):
self = cls()
self.id = record["id"]
self.theme = theme_module.get_theme(record["theme"])
return self
| from discord.ext import commands
import discord
from .utils import cache
from .utils import theme as theme_module
class UserConfig:
@classmethod
| 32 | 64 | 45 | 8 | 23 | ilovetocode2019/Logger | cogs/settings.py | Python | UserConfig | UserConfig | 7 | 15 | 7 | 8 | e345f6ff5285cc7c46ada38f8005f5fc3f0a4cc0 | bigcode/the-stack | train |
8763cccd3a407d9bf237b55d | train | class | class Settings(commands.Cog):
"""Commands to configure the bot"""
def __init__(self, bot):
self.bot = bot
@cache.cache()
async def fetch_config(self, user_id):
query = """SELECT *
FROM user_config
WHERE id=$1;
"""
record = ... | class Settings(commands.Cog):
| """Commands to configure the bot"""
def __init__(self, bot):
self.bot = bot
@cache.cache()
async def fetch_config(self, user_id):
query = """SELECT *
FROM user_config
WHERE id=$1;
"""
record = await self.bot.db.fetchrow(que... | ["id"]
self.theme = theme_module.get_theme(record["theme"])
return self
class ThemeConverter(commands.Converter):
async def convert(self, ctx, arg):
arg = arg.lower()
for k, v in theme_module.THEME_MAPPING.items():
if str(v) == arg:
return v, k
... | 85 | 85 | 286 | 6 | 79 | ilovetocode2019/Logger | cogs/settings.py | Python | Settings | Settings | 29 | 74 | 29 | 29 | 4a29864ae5ed20dd1aee250db4ea915b1aa40bfb | bigcode/the-stack | train |
62653f629bd6d13d8558f052 | train | class | class ThemeConverter(commands.Converter):
async def convert(self, ctx, arg):
arg = arg.lower()
for k, v in theme_module.THEME_MAPPING.items():
if str(v) == arg:
return v, k
raise commands.BadArgument("Invalid theme provided")
| class ThemeConverter(commands.Converter):
| async def convert(self, ctx, arg):
arg = arg.lower()
for k, v in theme_module.THEME_MAPPING.items():
if str(v) == arg:
return v, k
raise commands.BadArgument("Invalid theme provided")
| import cache
from .utils import theme as theme_module
class UserConfig:
@classmethod
def from_record(cls, record):
self = cls()
self.id = record["id"]
self.theme = theme_module.get_theme(record["theme"])
return self
class ThemeConverter(commands.Converter):
| 64 | 64 | 60 | 7 | 56 | ilovetocode2019/Logger | cogs/settings.py | Python | ThemeConverter | ThemeConverter | 18 | 26 | 18 | 18 | 507d9f11e50f4a665e31e1580233c543ff4e713d | bigcode/the-stack | train |
a04ab229c22cad4ff35758d1 | train | function | def main():
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
handler = loop.run_until_complete(app.setup(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(handler.finish_connections())
loop.close()
| def main():
| logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
handler = loop.run_until_complete(app.setup(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(handler.finish_connections())
loop.close()
| #!/usr/bin/env python3
import logging
import asyncio
from pyportify import app
def main():
| 23 | 64 | 57 | 3 | 19 | JoeSchr/pyportify | pyportify/server.py | Python | main | main | 8 | 17 | 8 | 8 | 322217950a6cd1e3d4e89f746640395ca71db98c | bigcode/the-stack | train |
8e06b85fe1bd410ddf21449a | train | function | def main():
aj=AltJob()
aj.run()
| def main():
| aj=AltJob()
aj.run()
| import sys
if sys.version_info[0] < 3:
print("Sorry, you must use Python 3")
sys.exit(1)
from .core import AltJob
def main():
| 43 | 64 | 13 | 3 | 39 | tristanlatr/alt_job | alt_job/__main__.py | Python | main | main | 9 | 11 | 9 | 9 | 8d3b7cc8bffbd7072f8210c854c1936a91bd1757 | bigcode/the-stack | train |
8a18d95a944c6ff63928970f | train | class | class CorrectNotFittedError(ValueError):
"""Exception class to raise if estimator is used before fitting.
Like NotFittedError, it inherits from ValueError, but not from
AttributeError. Used for testing only.
"""
| class CorrectNotFittedError(ValueError):
| """Exception class to raise if estimator is used before fitting.
Like NotFittedError, it inherits from ValueError, but not from
AttributeError. Used for testing only.
"""
| sklearn.utils.estimator_checks import check_estimator
from sklearn.utils.estimator_checks import check_estimators_unfitted
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_model import MultiTaskElasticNet
from sklearn.utils.validation import check_X_y, check_array
class CorrectNotFittedError(ValueEr... | 64 | 64 | 50 | 9 | 54 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | CorrectNotFittedError | CorrectNotFittedError | 15 | 20 | 15 | 15 | 73017f45e7b37e053b581f3958d5b65fb8cafdcf | bigcode/the-stack | train |
6a01d4d56fc3ca7f2e454198 | train | class | class NoCheckinPredict(BaseBadClassifier):
def fit(self, X, y):
X, y = check_X_y(X, y)
return self
| class NoCheckinPredict(BaseBadClassifier):
| def fit(self, X, y):
X, y = check_X_y(X, y)
return self
| fit(self, X, y=None):
X, y = check_X_y(X, y)
return self
def predict(self, X):
X = check_array(X)
self.key = 1000
return np.ones(X.shape[0])
class NoCheckinPredict(BaseBadClassifier):
| 64 | 64 | 34 | 9 | 55 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | NoCheckinPredict | NoCheckinPredict | 45 | 48 | 45 | 45 | e32a027afbc2204e5f74743affb9928a433f5cc1 | bigcode/the-stack | train |
a8dbc35e3a6869a9691766f8 | train | class | class BaseBadClassifier(BaseEstimator, ClassifierMixin):
def fit(self, X, y):
return self
def predict(self, X):
return np.ones(X.shape[0])
| class BaseBadClassifier(BaseEstimator, ClassifierMixin):
| def fit(self, X, y):
return self
def predict(self, X):
return np.ones(X.shape[0])
| _array
class CorrectNotFittedError(ValueError):
"""Exception class to raise if estimator is used before fitting.
Like NotFittedError, it inherits from ValueError, but not from
AttributeError. Used for testing only.
"""
class BaseBadClassifier(BaseEstimator, ClassifierMixin):
| 63 | 64 | 40 | 11 | 52 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | BaseBadClassifier | BaseBadClassifier | 23 | 28 | 23 | 23 | 480578f49e0b107e7ecf3d3cdd200c9b02c4f1c7 | bigcode/the-stack | train |
40ba950179e91ecbcd933cb9 | train | class | class NoSparseClassifier(BaseBadClassifier):
def fit(self, X, y):
X, y = check_X_y(X, y, accept_sparse=['csr', 'csc'])
if sp.issparse(X):
raise ValueError("Nonsensical Error")
return self
def predict(self, X):
X = check_array(X)
return np.ones(X.shape[0])
| class NoSparseClassifier(BaseBadClassifier):
| def fit(self, X, y):
X, y = check_X_y(X, y, accept_sparse=['csr', 'csc'])
if sp.issparse(X):
raise ValueError("Nonsensical Error")
return self
def predict(self, X):
X = check_array(X)
return np.ones(X.shape[0])
| = check_array(X)
self.key = 1000
return np.ones(X.shape[0])
class NoCheckinPredict(BaseBadClassifier):
def fit(self, X, y):
X, y = check_X_y(X, y)
return self
class NoSparseClassifier(BaseBadClassifier):
| 64 | 64 | 84 | 8 | 55 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | NoSparseClassifier | NoSparseClassifier | 51 | 60 | 51 | 51 | 16bace1d9008e53fdac13a78892cfa08d3e1db36 | bigcode/the-stack | train |
8419285237106fabbf0fd471 | train | function | def test_check_estimators_unfitted():
# check that a ValueError/AttributeError is raised when calling predict
# on an unfitted estimator
msg = "AttributeError or ValueError not raised by predict"
assert_raises_regex(AssertionError, msg, check_estimators_unfitted,
"estimator", NoS... | def test_check_estimators_unfitted():
# check that a ValueError/AttributeError is raised when calling predict
# on an unfitted estimator
| msg = "AttributeError or ValueError not raised by predict"
assert_raises_regex(AssertionError, msg, check_estimators_unfitted,
"estimator", NoSparseClassifier)
# check that CorrectNotFittedError inherit from either ValueError
# or AttributeError
check_estimators_unfitted("es... | _buffer.getvalue())
# doesn't error on actual estimator
check_estimator(AdaBoostClassifier)
check_estimator(MultiTaskElasticNet)
def test_check_estimators_unfitted():
# check that a ValueError/AttributeError is raised when calling predict
# on an unfitted estimator
| 64 | 64 | 113 | 33 | 31 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | test_check_estimators_unfitted | test_check_estimators_unfitted | 119 | 128 | 119 | 121 | 2f12c73274691922b93af12ca7a5efbb3fe131da | bigcode/the-stack | train |
5931afdcf329ef375d1ee1cf | train | class | class CorrectNotFittedErrorClassifier(BaseBadClassifier):
def fit(self, X, y):
X, y = check_X_y(X, y)
self.coef_ = np.ones(X.shape[1])
return self
def predict(self, X):
if not hasattr(self, 'coef_'):
raise CorrectNotFittedError("estimator is not fitted yet")
... | class CorrectNotFittedErrorClassifier(BaseBadClassifier):
| def fit(self, X, y):
X, y = check_X_y(X, y)
self.coef_ = np.ones(X.shape[1])
return self
def predict(self, X):
if not hasattr(self, 'coef_'):
raise CorrectNotFittedError("estimator is not fitted yet")
X = check_array(X)
return np.ones(X.shape[0])
| =['csr', 'csc'])
if sp.issparse(X):
raise ValueError("Nonsensical Error")
return self
def predict(self, X):
X = check_array(X)
return np.ones(X.shape[0])
class CorrectNotFittedErrorClassifier(BaseBadClassifier):
| 64 | 64 | 97 | 11 | 53 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | CorrectNotFittedErrorClassifier | CorrectNotFittedErrorClassifier | 63 | 73 | 63 | 63 | 35b02f15b57fc5b4fe20b199acc22defe5a0f889 | bigcode/the-stack | train |
0513a338ec8bfb5ccc0984b4 | train | class | class ChangesDict(BaseEstimator):
def __init__(self):
self.key = 0
def fit(self, X, y=None):
X, y = check_X_y(X, y)
return self
def predict(self, X):
X = check_array(X)
self.key = 1000
return np.ones(X.shape[0])
| class ChangesDict(BaseEstimator):
| def __init__(self):
self.key = 0
def fit(self, X, y=None):
X, y = check_X_y(X, y)
return self
def predict(self, X):
X = check_array(X)
self.key = 1000
return np.ones(X.shape[0])
| Error, but not from
AttributeError. Used for testing only.
"""
class BaseBadClassifier(BaseEstimator, ClassifierMixin):
def fit(self, X, y):
return self
def predict(self, X):
return np.ones(X.shape[0])
class ChangesDict(BaseEstimator):
| 64 | 64 | 77 | 6 | 58 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | ChangesDict | ChangesDict | 31 | 42 | 31 | 31 | 75e744fff948ef3777804047e3549356a1ba5c41 | bigcode/the-stack | train |
a2204bfb0d0511bc9897d05f | train | function | def test_check_estimator():
# tests that the estimator actually fails on "bad" estimators.
# not a complete test of all checks, which are very extensive.
# check that we have a set_params and can clone
msg = "it does not implement a 'get_params' methods"
assert_raises_regex(TypeError, msg, check_es... | def test_check_estimator():
# tests that the estimator actually fails on "bad" estimators.
# not a complete test of all checks, which are very extensive.
# check that we have a set_params and can clone
| msg = "it does not implement a 'get_params' methods"
assert_raises_regex(TypeError, msg, check_estimator, object)
# check that we have a fit method
msg = "object has no attribute 'fit'"
assert_raises_regex(AttributeError, msg, check_estimator, BaseEstimator)
# check that fit does input validatio... | y):
X, y = check_X_y(X, y)
self.coef_ = np.ones(X.shape[1])
return self
def predict(self, X):
if not hasattr(self, 'coef_'):
raise CorrectNotFittedError("estimator is not fitted yet")
X = check_array(X)
return np.ones(X.shape[0])
def test_check_estimator... | 128 | 128 | 428 | 49 | 79 | wfehrnstrom/harmonize | lib/python2.7/site-packages/sklearn/utils/tests/test_estimator_checks.py | Python | test_check_estimator | test_check_estimator | 76 | 116 | 76 | 80 | 75952fb4fcf6c24e60e090d6c77684a77b3bc4dc | bigcode/the-stack | train |
15374dc5231c784caa6eaca5 | train | class | class KiwiExporter:
"""
Exports system description as Kiwi configuration.
"""
def __init__(self, grains, format):
self.__grains__ = grains
self.format = format
self._data = type("data", (), {})
self.name = None
def load(self, **descr):
"""
Load data ... | class KiwiExporter:
| """
Exports system description as Kiwi configuration.
"""
def __init__(self, grains, format):
self.__grains__ = grains
self.format = format
self._data = type("data", (), {})
self.name = None
def load(self, **descr):
"""
Load data by keys.
:p... | #
# Copyright 2016 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | 209 | 256 | 1,709 | 4 | 204 | vveliev-tc/salt | salt/modules/inspectlib/kiwiproc.py | Python | KiwiExporter | KiwiExporter | 37 | 270 | 37 | 37 | d8d90e5124e6634c7b2778f4ca72e16e2aa0a7fb | bigcode/the-stack | train |
89f9b1d7cf9bb56802bf676f | train | function | def create_image_grid(images, grid_size=None):
assert images.ndim == 3 or images.ndim == 4
num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2]
if grid_size is not None:
grid_w, grid_h = tuple(grid_size)
else:
grid_w = max(int(np.ceil(np.sqrt(num))), 1)
grid_h... | def create_image_grid(images, grid_size=None):
| assert images.ndim == 3 or images.ndim == 4
num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2]
if grid_size is not None:
grid_w, grid_h = tuple(grid_size)
else:
grid_w = max(int(np.ceil(np.sqrt(num))), 1)
grid_h = max((num - 1) // grid_w + 1, 1)
grid = ... | range_in[1]) - np.float32(drange_in[0]))
bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale)
data = data * scale + bias
return data
def create_image_grid(images, grid_size=None):
| 64 | 64 | 198 | 10 | 53 | siavashdarkvision/stylegan2 | training/misc.py | Python | create_image_grid | create_image_grid | 48 | 63 | 48 | 48 | 2ac82a9c42bb16ece9e8009c9002b40c56d872c0 | bigcode/the-stack | train |
6297560db99e5fa38d529966 | train | function | def open_file_or_url(file_or_url):
if dnnlib.util.is_url(file_or_url):
return dnnlib.util.open_url(file_or_url, cache_dir='.stylegan2-cache')
return open(file_or_url, 'rb')
| def open_file_or_url(file_or_url):
| if dnnlib.util.is_url(file_or_url):
return dnnlib.util.open_url(file_or_url, cache_dir='.stylegan2-cache')
return open(file_or_url, 'rb')
| 64 + 14, 64 - 14: 64 + 14, ...] = 255
return square
#----------------------------------------------------------------------------
# Convenience wrappers for pickle that are able to load data produced by
# older versions of the code, and from external URLs.
def open_file_or_url(file_or_url):
| 64 | 64 | 51 | 9 | 55 | siavashdarkvision/stylegan2 | training/misc.py | Python | open_file_or_url | open_file_or_url | 25 | 28 | 25 | 25 | 45bf162f60eebfa70b3c47870bd3104f66c72c88 | bigcode/the-stack | train |
7abfcdd0b39dbb1e9cf81a94 | train | function | def parse_config_for_previous_run(run_dir):
with open(os.path.join(run_dir, 'submit_config.pkl'), 'rb') as f:
data = pickle.load(f)
data = data.get('run_func_kwargs', {})
return dict(train=data, dataset=data.get('dataset_args', {}))
| def parse_config_for_previous_run(run_dir):
| with open(os.path.join(run_dir, 'submit_config.pkl'), 'rb') as f:
data = pickle.load(f)
data = data.get('run_func_kwargs', {})
return dict(train=data, dataset=data.get('dataset_args', {}))
| ibatch.shape[0]) < 0.5
minibatch = np.array(minibatch)
minibatch[mask] = minibatch[mask, :, :, ::-1]
return minibatch
#----------------------------------------------------------------------------
# Loading data from previous training runs.
def parse_config_for_previous_run(run_dir):
| 64 | 64 | 62 | 9 | 55 | siavashdarkvision/stylegan2 | training/misc.py | Python | parse_config_for_previous_run | parse_config_for_previous_run | 122 | 126 | 122 | 122 | 63a6ace58b575e8f865ecc139082dd021580ef52 | bigcode/the-stack | train |
2d8c741ab046202e504e55b1 | train | function | def save_texture_grid(images, prefix):
textures = create_texture_grid(images)
for texture_idx, texture in enumerate(textures):
filename = prefix + '_{:d}.png'.format(texture_idx)
fmt = 'RGB' if texture.ndim == 3 else 'L'
PIL.Image.fromarray(texture, fmt).save(filename)
| def save_texture_grid(images, prefix):
| textures = create_texture_grid(images)
for texture_idx, texture in enumerate(textures):
filename = prefix + '_{:d}.png'.format(texture_idx)
fmt = 'RGB' if texture.ndim == 3 else 'L'
PIL.Image.fromarray(texture, fmt).save(filename)
| col = image_in_texture_idx % (texture_size // image_width)
texture[row * image_width: (row + 1)* image_width,
col * image_height: (col + 1) * image_height, ...] = image
return textures
def save_texture_grid(images, prefix):
| 64 | 64 | 71 | 8 | 55 | siavashdarkvision/stylegan2 | training/misc.py | Python | save_texture_grid | save_texture_grid | 90 | 95 | 90 | 90 | e74a444fdb377d17b25f8902e958bb2f9964c1d5 | bigcode/the-stack | train |
6bfb9c0f5ef4d6172f1e8e05 | train | function | def convert_to_pil_image(image, drange=[0,1]):
assert image.ndim == 2 or image.ndim == 3
if image.ndim == 3:
if image.shape[0] == 1:
image = image[0] # grayscale CHW => HW
else:
image = image.transpose(1, 2, 0) # CHW -> HWC
image = adjust_dynamic_range(image, drange,... | def convert_to_pil_image(image, drange=[0,1]):
| assert image.ndim == 2 or image.ndim == 3
if image.ndim == 3:
if image.shape[0] == 1:
image = image[0] # grayscale CHW => HW
else:
image = image.transpose(1, 2, 0) # CHW -> HWC
image = adjust_dynamic_range(image, drange, [0,255])
image = np.rint(image).clip(0, 25... | in enumerate(textures):
filename = prefix + '_{:d}.png'.format(texture_idx)
fmt = 'RGB' if texture.ndim == 3 else 'L'
PIL.Image.fromarray(texture, fmt).save(filename)
def convert_to_pil_image(image, drange=[0,1]):
| 64 | 64 | 152 | 15 | 49 | siavashdarkvision/stylegan2 | training/misc.py | Python | convert_to_pil_image | convert_to_pil_image | 97 | 108 | 97 | 97 | cc894ecdc10e17f5ac8dcaf768d95a88d78c52f1 | bigcode/the-stack | train |
8da80dd91ed6ef962abae4b1 | train | function | def apply_mirror_augment(minibatch):
mask = np.random.rand(minibatch.shape[0]) < 0.5
minibatch = np.array(minibatch)
minibatch[mask] = minibatch[mask, :, :, ::-1]
return minibatch
| def apply_mirror_augment(minibatch):
| mask = np.random.rand(minibatch.shape[0]) < 0.5
minibatch = np.array(minibatch)
minibatch[mask] = minibatch[mask, :, :, ::-1]
return minibatch
| 3 else 'L'
return PIL.Image.fromarray(image, fmt)
def save_image_grid(images, filename, drange=[0,1], grid_size=None):
convert_to_pil_image(create_image_grid(images, grid_size), drange).save(filename)
def apply_mirror_augment(minibatch):
| 64 | 64 | 62 | 10 | 54 | siavashdarkvision/stylegan2 | training/misc.py | Python | apply_mirror_augment | apply_mirror_augment | 113 | 117 | 113 | 113 | 55ccf2d8f541e05544ff8ef660b8837d8f79b2a7 | bigcode/the-stack | train |
8d1ee6f8fde5ea175c1c4262 | train | function | def setup_snapshot_image_grid(training_set,
size = '1080p', # '1080p' = to be viewed on 1080p display, '4k' = to be viewed on 4k display.
layout = 'random'): # 'random' = grid contents are selected randomly, 'row_per_class' = each row corresponds to one class label.
# Select size.
gw = 1; g... | def setup_snapshot_image_grid(training_set,
size = '1080p', # '1080p' = to be viewed on 1080p display, '4k' = to be viewed on 4k display.
layout = 'random'): # 'random' = grid contents are selected randomly, 'row_per_class' = each row corresponds to one class label.
# Select size.
| gw = 1; gh = 1
if size == '1080p':
gw = np.clip(1920 // training_set.shape[2], 3, 32)
gh = np.clip(1080 // training_set.shape[1], 2, 32)
if size == '4k':
gw = np.clip(3840 // training_set.shape[2], 7, 32)
gh = np.clip(2160 // training_set.shape[1], 4, 32)
if size == '8k':... | :, :, ::-1]
return minibatch
#----------------------------------------------------------------------------
# Loading data from previous training runs.
def parse_config_for_previous_run(run_dir):
with open(os.path.join(run_dir, 'submit_config.pkl'), 'rb') as f:
data = pickle.load(f)
data = data.ge... | 190 | 190 | 634 | 87 | 103 | siavashdarkvision/stylegan2 | training/misc.py | Python | setup_snapshot_image_grid | setup_snapshot_image_grid | 132 | 180 | 132 | 136 | 44a8ea14a3eb0664bc4a92d5cf6599e545820647 | bigcode/the-stack | train |
adcf8dfae80fa67f37e3b2b3 | train | function | def save_pkl(obj, filename):
with open(filename, 'wb') as file:
pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
| def save_pkl(obj, filename):
| with open(filename, 'wb') as file:
pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
| .open_url(file_or_url, cache_dir='.stylegan2-cache')
return open(file_or_url, 'rb')
def load_pkl(file_or_url):
with open_file_or_url(file_or_url) as file:
return pickle.load(file, encoding='latin1')
def save_pkl(obj, filename):
| 64 | 64 | 34 | 8 | 56 | siavashdarkvision/stylegan2 | training/misc.py | Python | save_pkl | save_pkl | 34 | 36 | 34 | 34 | ce0a9c4acd807336c19352bf63e8921d909e9c23 | bigcode/the-stack | train |
aa161f7e7c367f082c06047a | train | function | def make_white_square():
square = np.zeros((128, 128, 3), dtype=np.uint8)
square[64 - 14: 64 + 14, 64 - 14: 64 + 14, ...] = 255
return square
| def make_white_square():
| square = np.zeros((128, 128, 3), dtype=np.uint8)
square[64 - 14: 64 + 14, 64 - 14: 64 + 14, ...] = 255
return square
| -NC.
# To view a copy of this license, visit
# https://nvlabs.github.io/stylegan2/license.html
"""Miscellaneous utility functions."""
import os
import pickle
import numpy as np
import PIL.Image
import PIL.ImageFont
import dnnlib
def make_white_square():
| 64 | 64 | 60 | 5 | 58 | siavashdarkvision/stylegan2 | training/misc.py | Python | make_white_square | make_white_square | 16 | 19 | 16 | 16 | 68abb2e072cfd6716457e1a1b48e55c1b2a62bca | bigcode/the-stack | train |
037ecc00dd15123c79510306 | train | function | def adjust_dynamic_range(data, drange_in, drange_out):
if drange_in != drange_out:
scale = (np.float32(drange_out[1]) - np.float32(drange_out[0])) / (np.float32(drange_in[1]) - np.float32(drange_in[0]))
bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale)
data = data * scale... | def adjust_dynamic_range(data, drange_in, drange_out):
| if drange_in != drange_out:
scale = (np.float32(drange_out[1]) - np.float32(drange_out[0])) / (np.float32(drange_in[1]) - np.float32(drange_in[0]))
bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale)
data = data * scale + bias
return data
| return pickle.load(file, encoding='latin1')
def save_pkl(obj, filename):
with open(filename, 'wb') as file:
pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
#----------------------------------------------------------------------------
# Image utils.
def adjust_dynamic_range(data, drange_in, drang... | 64 | 64 | 107 | 14 | 50 | siavashdarkvision/stylegan2 | training/misc.py | Python | adjust_dynamic_range | adjust_dynamic_range | 41 | 46 | 41 | 41 | 2a18f1f6bb508c49feeda3e60b89a0100d202fed | bigcode/the-stack | train |
8c638051ed790c442cf1170e | train | function | def load_pkl(file_or_url):
with open_file_or_url(file_or_url) as file:
return pickle.load(file, encoding='latin1')
| def load_pkl(file_or_url):
| with open_file_or_url(file_or_url) as file:
return pickle.load(file, encoding='latin1')
| and from external URLs.
def open_file_or_url(file_or_url):
if dnnlib.util.is_url(file_or_url):
return dnnlib.util.open_url(file_or_url, cache_dir='.stylegan2-cache')
return open(file_or_url, 'rb')
def load_pkl(file_or_url):
| 64 | 64 | 32 | 8 | 56 | siavashdarkvision/stylegan2 | training/misc.py | Python | load_pkl | load_pkl | 30 | 32 | 30 | 30 | 698dc11948a7037653d46a6b4385d5058d0d4667 | bigcode/the-stack | train |
c5f966ed194485bf59eec816 | train | function | def create_texture_grid(images):
assert len(images)
image_width, image_height, n_channels = images[0].shape
assert image_width == image_height == 128
assert n_channels in (1, 3)
texture_size = 2048
n_images_per_texture = (texture_size * texture_size) // (image_width * image_height)
n_textu... | def create_texture_grid(images):
| assert len(images)
image_width, image_height, n_channels = images[0].shape
assert image_width == image_height == 128
assert n_channels in (1, 3)
texture_size = 2048
n_images_per_texture = (texture_size * texture_size) // (image_width * image_height)
n_textures = len(images) // n_images_per... | _w], dtype=images.dtype)
for idx in range(num):
x = (idx % grid_w) * img_w
y = (idx // grid_w) * img_h
grid[..., y : y + img_h, x : x + img_w] = images[idx]
return grid
def create_texture_grid(images):
| 71 | 71 | 239 | 6 | 64 | siavashdarkvision/stylegan2 | training/misc.py | Python | create_texture_grid | create_texture_grid | 65 | 88 | 65 | 65 | 3ad9628afdd445a181077b50414ae409e58b5954 | bigcode/the-stack | train |
9bbb88d6064ea05e9a9b3291 | train | function | def save_image_grid(images, filename, drange=[0,1], grid_size=None):
convert_to_pil_image(create_image_grid(images, grid_size), drange).save(filename)
| def save_image_grid(images, filename, drange=[0,1], grid_size=None):
| convert_to_pil_image(create_image_grid(images, grid_size), drange).save(filename)
| = np.rint(image).clip(0, 255).astype(np.uint8)
fmt = 'RGB' if image.ndim == 3 else 'L'
return PIL.Image.fromarray(image, fmt)
def save_image_grid(images, filename, drange=[0,1], grid_size=None):
| 64 | 64 | 39 | 19 | 45 | siavashdarkvision/stylegan2 | training/misc.py | Python | save_image_grid | save_image_grid | 110 | 111 | 110 | 110 | e6956f9154c03025490375ccd01f54c6e3dce4ea | bigcode/the-stack | train |
73b1e3eeac62492907ea1838 | train | function | def custom_tile_plot_with_inference_hists(
layout,
images,
labels,
predictions,
classes=np.linspace(start=0,stop=10,num=10,endpoint=False,dtype=np.uint8),
only_misclassified=False,
filename="",
cmap="gray",
label_size=32,
figure_size=(8., 8.)
):
"""
Show multiple images... | def custom_tile_plot_with_inference_hists(
layout,
images,
labels,
predictions,
classes=np.linspace(start=0,stop=10,num=10,endpoint=False,dtype=np.uint8),
only_misclassified=False,
filename="",
cmap="gray",
label_size=32,
figure_size=(8., 8.)
):
| """
Show multiple images AND their class probabilities as subplots.
Args:
layout (tuple): Tuple of integers (m,n).
images (np.array): NumPy array containing the images.
labels (np.array): A list or NumPy array of labels.
predictions (np.array): Contains the inference cla... | #
image = images[(r*layout[1]+c),:]
if(len(image.shape) == 2):
axes_dict[(r, c)].imshow(image, origin="upper", cmap=cmap)
elif(len(image.shape) == 3 and image.shape[-1] == 1):
axes_dict[(r, c)].imshow(image[:, :, 0], origin="upper", cmap=cmap)
... | 255 | 256 | 1,986 | 78 | 177 | sedihub/deep_learning_research | old_projects/cnn_classifiers/utilities/tile_image_plot_utilities.py | Python | custom_tile_plot_with_inference_hists | custom_tile_plot_with_inference_hists | 116 | 304 | 116 | 127 | 2bcd9390802a48f3a3779ccbf3cff5cd570fa828 | bigcode/the-stack | train |
b7e02f1831d142cd367fc0b2 | train | function | def custom_tile_image_plot(
layout,
images,
labels=None,
filename="",
cmap="gray",
label_size=16,
label_color=None,
figure_size=(8., 8.),
):
"""
Plots multiple images as subplots.
Args:
layout (tuple): Tuple of integers (m,n).
images (np.array): NumPy arr... | def custom_tile_image_plot(
layout,
images,
labels=None,
filename="",
cmap="gray",
label_size=16,
label_color=None,
figure_size=(8., 8.),
):
| """
Plots multiple images as subplots.
Args:
layout (tuple): Tuple of integers (m,n).
images (np.array): NumPy array containing the images.
labels (np.array): A list or NumPy array of labels (optional)
filename (str): Filename to save the plot to as png (optional).
... | """This script contains utility functions for
generating tile plots of image/matrices.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
def custom_tile_image_plot(
layout,
images,
labels=None,
filename="",
cmap="gray",
label_size=16,
label_color=None,
figure_size=(8., ... | 79 | 256 | 949 | 47 | 31 | sedihub/deep_learning_research | old_projects/cnn_classifiers/utilities/tile_image_plot_utilities.py | Python | custom_tile_image_plot | custom_tile_image_plot | 11 | 113 | 11 | 20 | ffcac459a3a51b5e94265a3256239b15d400fc6e | bigcode/the-stack | train |
2483a810c772c4a601c47ba0 | train | class | class View(np.ndarray): # type: ignore[type-arg]
__slots__ = ()
_FIELDS: ClassVar[Tuple[str, ...]]
def __getitem__(self, ind: StrIndex) -> "np.typing.NDArray[Any]":
sliced = super().__getitem__(ind)
# If the shape is empty, return the parent type
if not sliced.shape:
r... | class View(np.ndarray): # type: ignore[type-arg]
| __slots__ = ()
_FIELDS: ClassVar[Tuple[str, ...]]
def __getitem__(self, ind: StrIndex) -> "np.typing.NDArray[Any]":
sliced = super().__getitem__(ind)
# If the shape is empty, return the parent type
if not sliced.shape:
return self._PARENT._make(*sliced) # type: ignore[... | from typing import Any, Callable, ClassVar, Mapping, MutableMapping, Tuple, Type, Union
import numpy as np
from ..accumulators import Mean, WeightedMean, WeightedSum
from .typing import ArrayLike, StrIndex, Ufunc
class View(np.ndarray): # type: ignore[type-arg]
| 67 | 142 | 474 | 14 | 52 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | View | View | 9 | 52 | 9 | 9 | b79ee5376765fb46997355c9f553818973da5c09 | bigcode/the-stack | train |
cc0a737a8f1ae89f4f891fd1 | train | class | @fields(
"sum_of_weights",
"sum_of_weights_squared",
"value",
"_sum_of_weighted_deltas_squared",
)
class WeightedMeanView(View):
__slots__ = ()
_PARENT = WeightedMean
sum_of_weights: "np.typing.NDArray[Any]"
sum_of_weights_squared: "np.typing.NDArray[Any]"
value: "np.typing.NDArray[... | @fields(
"sum_of_weights",
"sum_of_weights_squared",
"value",
"_sum_of_weighted_deltas_squared",
)
class WeightedMeanView(View):
| __slots__ = ()
_PARENT = WeightedMean
sum_of_weights: "np.typing.NDArray[Any]"
sum_of_weights_squared: "np.typing.NDArray[Any]"
value: "np.typing.NDArray[Any]"
_sum_of_weighted_deltas_squared: "np.typing.NDArray[Any]"
@property
def variance(self) -> "np.typing.NDArray[Any]":
wi... | _ufunc__(ufunc, method, *inputs, **kwargs) # type: ignore[misc, no-any-return]
@fields(
"sum_of_weights",
"sum_of_weights_squared",
"value",
"_sum_of_weighted_deltas_squared",
)
class WeightedMeanView(View):
| 64 | 64 | 195 | 37 | 27 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | WeightedMeanView | WeightedMeanView | 198 | 219 | 198 | 204 | 865feb69e1a7685e7790c8399d66eeb7c55ecb94 | bigcode/the-stack | train |
759fe557bbada3653dbfddaf | train | function | def _to_view(
item: "np.typing.NDArray[Any]", value: bool = False
) -> Union["np.typing.NDArray[Any]", WeightedSumView, WeightedMeanView, MeanView]:
for cls in View.__subclasses__():
if cls._FIELDS == item.dtype.names:
ret = item.view(cls)
if value and ret.shape:
... | def _to_view(
item: "np.typing.NDArray[Any]", value: bool = False
) -> Union["np.typing.NDArray[Any]", WeightedSumView, WeightedMeanView, MeanView]:
| for cls in View.__subclasses__():
if cls._FIELDS == item.dtype.names:
ret = item.view(cls)
if value and ret.shape:
return ret.value # type: ignore[no-any-return]
else:
return ret # type: ignore[no-any-return]
return item
| self["_sum_of_deltas_squared"] / (self["count"] - 1)
def _to_view(
item: "np.typing.NDArray[Any]", value: bool = False
) -> Union["np.typing.NDArray[Any]", WeightedSumView, WeightedMeanView, MeanView]:
| 64 | 64 | 114 | 46 | 18 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | _to_view | _to_view | 238 | 248 | 238 | 240 | 784589425cfd388aeda8c9837ce3c47eca08f5ae | bigcode/the-stack | train |
107fa6c5f9090bf52a174fb5 | train | function | def make_getitem_property(name: str) -> property:
def fget(self: Mapping[str, Any]) -> Any:
return self[name]
def fset(self: MutableMapping[str, Any], value: Any) -> None:
self[name] = value
return property(fget, fset)
| def make_getitem_property(name: str) -> property:
| def fget(self: Mapping[str, Any]) -> Any:
return self[name]
def fset(self: MutableMapping[str, Any], value: Any) -> None:
self[name] = value
return property(fget, fset)
| : ignore[attr-defined]
elif self.dtype == array.dtype:
super().__setitem__(ind, array) # type: ignore[no-untyped-call]
else:
raise ValueError("Needs matching ndarray or n+1 dim array")
def make_getitem_property(name: str) -> property:
| 64 | 64 | 66 | 12 | 52 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | make_getitem_property | make_getitem_property | 55 | 62 | 55 | 55 | 1b1211abce59abf230bc1d49d40a1a2bb0a3cff4 | bigcode/the-stack | train |
d9e7372e4c1897cde350c8c5 | train | function | def fields(*names: str) -> Callable[[Type[object]], Type[object]]:
"""
This decorator adds the name to the _FIELDS
class property (for printing in reprs), and
adds a property that looks like this:
@property
def name(self):
return self["name"]
@name.setter
def name(self, value):
... | def fields(*names: str) -> Callable[[Type[object]], Type[object]]:
| """
This decorator adds the name to the _FIELDS
class property (for printing in reprs), and
adds a property that looks like this:
@property
def name(self):
return self["name"]
@name.setter
def name(self, value):
self["name"] = value
"""
def injector(cls: Type[ob... | , Any]) -> Any:
return self[name]
def fset(self: MutableMapping[str, Any], value: Any) -> None:
self[name] = value
return property(fget, fset)
def fields(*names: str) -> Callable[[Type[object]], Type[object]]:
| 64 | 64 | 185 | 18 | 46 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | fields | fields | 65 | 92 | 65 | 65 | 0cc80da379bb954ecf0d4481cda6a56450d094c5 | bigcode/the-stack | train |
597ee58d5915351705bf8750 | train | class | @fields("count", "value", "_sum_of_deltas_squared")
class MeanView(View):
__slots__ = ()
_PARENT = Mean
count: "np.typing.NDArray[Any]"
value: "np.typing.NDArray[Any]"
_sum_of_deltas_squared: "np.typing.NDArray[Any]"
# Variance is a computation
@property
def variance(self) -> "np.typin... | @fields("count", "value", "_sum_of_deltas_squared")
class MeanView(View):
| __slots__ = ()
_PARENT = Mean
count: "np.typing.NDArray[Any]"
value: "np.typing.NDArray[Any]"
_sum_of_deltas_squared: "np.typing.NDArray[Any]"
# Variance is a computation
@property
def variance(self) -> "np.typing.NDArray[Any]":
with np.errstate(divide="ignore", invalid="ignore... | _of_weighted_deltas_squared"] / ( # type: ignore[no-any-return]
self["sum_of_weights"]
- self["sum_of_weights_squared"] / self["sum_of_weights"]
)
@fields("count", "value", "_sum_of_deltas_squared")
class MeanView(View):
| 64 | 64 | 137 | 20 | 44 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | MeanView | MeanView | 222 | 235 | 222 | 223 | 1084bd5bfb5c83a15c47079464f7ce85b361b3ad | bigcode/the-stack | train |
c1e414cbcdbb08e2bad7eb24 | train | class | @fields("value", "variance")
class WeightedSumView(View):
__slots__ = ()
_PARENT = WeightedSum
value: "np.typing.NDArray[Any]"
variance: "np.typing.NDArray[Any]"
# Could be implemented on master View
def __array_ufunc__(
self, ufunc: Ufunc, method: str, *inputs: Any, **kwargs: Any
... | @fields("value", "variance")
class WeightedSumView(View):
| __slots__ = ()
_PARENT = WeightedSum
value: "np.typing.NDArray[Any]"
variance: "np.typing.NDArray[Any]"
# Could be implemented on master View
def __array_ufunc__(
self, ufunc: Ufunc, method: str, *inputs: Any, **kwargs: Any
) -> "np.typing.NDArray[Any]":
# This one is defi... | -> property:
def fget(self: Mapping[str, Any]) -> Any:
return self[name]
def fset(self: MutableMapping[str, Any], value: Any) -> None:
self[name] = value
return property(fget, fset)
def fields(*names: str) -> Callable[[Type[object]], Type[object]]:
"""
This decorator adds the na... | 256 | 256 | 898 | 14 | 241 | scikit-hep/boost-histogram | src/boost_histogram/_internal/view.py | Python | WeightedSumView | WeightedSumView | 95 | 195 | 95 | 96 | 58ddd2d628b2dac3d4a4307d3e6a5875449fd9e4 | bigcode/the-stack | train |
2e39908dca44a8639732de99 | train | class | class SquareWave:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
def trigonometric(a, f, x, c=0, m=0):
return a * np.sign(np.sin(2*np.pi * f * x + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x):
result = 0
... | class SquareWave:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| def trigonometric(a, f, x, c=0, m=0):
return a * np.sign(np.sin(2*np.pi * f * x + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x):
result = 0
for n in range(1, a):
result += (np.sin(2 * np.pi * f * (2*n - 1) * x) / (2 * n... | ():
return r'$\dfrac{-2a}{\pi} + \dfrac{1}{\pi} \arctan(\dfrac{1}{\tan(2\pi \dfrac{f}{2} x)}) + C $'
class SquareWave:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| 82 | 82 | 276 | 26 | 56 | denczo/FM_Synthesis | code/waveform.py | Python | SquareWave | SquareWave | 30 | 51 | 30 | 33 | 7500ff5b4c82ee1cba6f3a5d6f5c92920f7fea7d | bigcode/the-stack | train |
70d59d4f5a56531538c293e3 | train | class | class Sawtooth:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
def trigonometric(a, f, x, c=0, m=0):
return -2 * a / np.pi * np.arctan(1 / np.tan(2 * np.pi * f/2 * x + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x)... | class Sawtooth:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| def trigonometric(a, f, x, c=0, m=0):
return -2 * a / np.pi * np.arctan(1 / np.tan(2 * np.pi * f/2 * x + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x):
result = 0
for n in range(1, a):
result += (np.sin(2 * np.pi * f * ... | import numpy as np
# for mathematical symbols
# https://matplotlib.org/3.1.1/tutorials/text/mathtext.html
class Sawtooth:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| 56 | 87 | 292 | 27 | 28 | denczo/FM_Synthesis | code/waveform.py | Python | Sawtooth | Sawtooth | 6 | 27 | 6 | 9 | 81345b354297e8b21d30e26df4be51ee2d4618a5 | bigcode/the-stack | train |
955abb2bd5a5653a806e6014 | train | class | class Sine:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
def trigonometric(a, f, x, c, m):
return a * np.sin(2 * np.pi * f * x - np.pi/2 + m) + c
@staticmethod
def equation_trigon():
return r'$a\/\sin(2\pi\/f\/x - \dfrac{\pi}{2})) + C $'
| class Sine:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| def trigonometric(a, f, x, c, m):
return a * np.sin(2 * np.pi * f * x - np.pi/2 + m) + c
@staticmethod
def equation_trigon():
return r'$a\/\sin(2\pi\/f\/x - \dfrac{\pi}{2})) + C $'
| $\dfrac{2a}{\pi}\/\arcsin(\sin(2\pi\/f\/x - \dfrac{\pi}{2})) + C $'
class Sine:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| 64 | 64 | 106 | 26 | 38 | denczo/FM_Synthesis | code/waveform.py | Python | Sine | Sine | 78 | 87 | 78 | 81 | a02b1fefbae37f7c662438e6bd1c4ce67569a344 | bigcode/the-stack | train |
898579f9b5a96151f58dab1c | train | class | class Triangle:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
def trigonometric(a, f, x, c, m):
return 2 * a / np.pi * np.arcsin(np.sin(2 * np.pi * f * x - np.pi/2 + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x):... | class Triangle:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| def trigonometric(a, f, x, c, m):
return 2 * a / np.pi * np.arcsin(np.sin(2 * np.pi * f * x - np.pi/2 + m)) + c
# a = amplitude, f = frequency, x = samples
@staticmethod
def fourier_series(a, f, x):
result = 0
for n in range(1, a):
result += (np.cos(2 * np.pi * f * (... | frac{2}{\pi}\/f\/(2n - 1)\/x)}{2n - 1}$'
@staticmethod
def equation_trigon():
return r'$a\/\/ \mathrm{\mathsf{sign}}(\sin(2\pi\/f\/x)) + C $'
class Triangle:
# a = amplitude, f = frequency, x = samples, c = constant
@staticmethod
| 92 | 92 | 307 | 25 | 67 | denczo/FM_Synthesis | code/waveform.py | Python | Triangle | Triangle | 54 | 75 | 54 | 57 | d881a612d19bef089adf34d41064a1529eae0891 | bigcode/the-stack | train |
23b0e0ef64a06365174ab368 | train | class | class Dataset(list):
""" Seismic data container
A list of ObsPy streams in which each stream corresponds to a single
seismic station
.. note::
Each supported file format has a corresponding reader that creates
Datasets (see ``mtuq.io.readers``).
"""
def __init__(self, stream... | class Dataset(list):
| """ Seismic data container
A list of ObsPy streams in which each stream corresponds to a single
seismic station
.. note::
Each supported file format has a corresponding reader that creates
Datasets (see ``mtuq.io.readers``).
"""
def __init__(self, streams=[], id=None, tags=[... |
import obspy
import numpy as np
import pickle
from copy import copy, deepcopy
from mtuq.event import Origin
from mtuq.station import Station
from mtuq.util import warn
from obspy import Stream
from obspy.geodetics import gps2dist_azimuth
class Dataset(list):
| 65 | 256 | 1,533 | 4 | 60 | ammcpherson/mtuq | mtuq/dataset.py | Python | Dataset | Dataset | 15 | 275 | 15 | 15 | 25f531348f43f91c699b37fe16926df07f8e7baf | bigcode/the-stack | train |
a3f557aecc612f85a4b00831 | train | class | class AppServicePythonVersion(BaseResourceValueCheck):
def __init__(self):
name = "Ensure that 'Python version' is the latest, if used to run the web app"
id = "CKV_AZURE_82"
supported_resources = ['azurerm_app_service']
categories = [CheckCategories.GENERAL_SECURITY]
super()... | class AppServicePythonVersion(BaseResourceValueCheck):
| def __init__(self):
name = "Ensure that 'Python version' is the latest, if used to run the web app"
id = "CKV_AZURE_82"
supported_resources = ['azurerm_app_service']
categories = [CheckCategories.GENERAL_SECURITY]
super().__init__(name=name, id=id, categories=categories, supp... | from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
class AppServicePythonVersion(BaseResourceValueCheck):
| 41 | 64 | 141 | 10 | 30 | pmalkki/checkov | checkov/terraform/checks/resource/azure/AppServicePythonVersion.py | Python | AppServicePythonVersion | AppServicePythonVersion | 5 | 18 | 5 | 5 | 6f2346b985631e403a9b39d27dfdacaf13749d94 | bigcode/the-stack | train |
f1bd867294294332fe555f7a | train | function | def load_mnist():
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype("float32") / 255
x_train = x_train.reshape(x_train.shape + (1,))
x_test = x_test.astype("float32") / 255
x_test = x_test.reshape(x_test.shape + (1,))
return x_train, y_train, x_test, y_test
| def load_mnist():
| (x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype("float32") / 255
x_train = x_train.reshape(x_train.shape + (1,))
x_test = x_test.astype("float32") / 255
x_test = x_test.reshape(x_test.shape + (1,))
return x_train, y_train, x_test, y_test
| from tensorflow.keras.datasets import mnist
from autoencoder import Autoencoder
LEARNING_RATE = 0.0005
BATCH_SIZE = 32
EPOCHS = 20
def load_mnist():
| 44 | 64 | 99 | 5 | 38 | aishifugi/generating-sound-with-neural-networks | 06 Training an autoencoder/train.py | Python | load_mnist | load_mnist | 11 | 19 | 11 | 11 | ad8563b3e6a6c3416d88f4882e167f72eb4adc7e | bigcode/the-stack | train |
883cfe19d83586ac5a24c50b | train | function | def train(x_train, learning_rate, batch_size, epochs):
autoencoder = Autoencoder(
input_shape=(28, 28, 1),
conv_filters=(32, 64, 64, 64),
conv_kernels=(3, 3, 3, 3),
conv_strides=(1, 2, 2, 1),
latent_space_dim=2
)
autoencoder.summary()
autoencoder.compile(learning_... | def train(x_train, learning_rate, batch_size, epochs):
| autoencoder = Autoencoder(
input_shape=(28, 28, 1),
conv_filters=(32, 64, 64, 64),
conv_kernels=(3, 3, 3, 3),
conv_strides=(1, 2, 2, 1),
latent_space_dim=2
)
autoencoder.summary()
autoencoder.compile(learning_rate)
autoencoder.train(x_train, batch_size, epochs... | (x_train.shape + (1,))
x_test = x_test.astype("float32") / 255
x_test = x_test.reshape(x_test.shape + (1,))
return x_train, y_train, x_test, y_test
def train(x_train, learning_rate, batch_size, epochs):
| 64 | 64 | 118 | 13 | 50 | aishifugi/generating-sound-with-neural-networks | 06 Training an autoencoder/train.py | Python | train | train | 22 | 33 | 22 | 22 | 0bf4ee003d27cb2444e2a056fa0befda4e586f73 | bigcode/the-stack | train |
f9fa71d1cf56c6dd4ec129eb | train | class | class TestMetricsAdvisorAdministrationClientAsync(TestMetricsAdvisorAdministrationClientBaseAsync):
@AzureTestCase.await_prepared_test
async def test_create_ad_config_whole_series_detection(self):
data_feed = await self._create_data_feed("adconfigasync")
async with self.admin_client:
... | class TestMetricsAdvisorAdministrationClientAsync(TestMetricsAdvisorAdministrationClientBaseAsync):
@AzureTestCase.await_prepared_test
| async def test_create_ad_config_whole_series_detection(self):
data_feed = await self._create_data_feed("adconfigasync")
async with self.admin_client:
try:
detection_config_name = self.create_random_name("testdetectionconfigasync")
config = await self.admi... | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import py... | 150 | 256 | 8,866 | 25 | 124 | bishnu-shb/azure-sdk-for-python | sdk/metricsadvisor/azure-ai-metricsadvisor/tests/async_tests/test_detection_config_aad_async.py | Python | TestMetricsAdvisorAdministrationClientAsync | TestMetricsAdvisorAdministrationClientAsync | 24 | 827 | 24 | 26 | 378d776f01ba83eaf6e932ef3eb6758b6c0d12c0 | bigcode/the-stack | train |
5425260679a7a9e9e0e5098b | train | class | @pulumi.output_type
class HelmOperatorPropertiesResponse(dict):
"""
Properties for Helm operator.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "chartValues":
suggest = "chart_values"
elif key == "chartVersion":
suggest = "cha... | @pulumi.output_type
class HelmOperatorPropertiesResponse(dict):
| """
Properties for Helm operator.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "chartValues":
suggest = "chart_values"
elif key == "chartVersion":
suggest = "chart_version"
if suggest:
pulumi.log.warn(f"K... | umi.get(self, "level")
@property
@pulumi.getter
def message(self) -> Optional[str]:
"""
Detailed message of the status from the Extension.
"""
return pulumi.get(self, "message")
@property
@pulumi.getter
def time(self) -> Optional[str]:
"""
DateLi... | 114 | 114 | 382 | 13 | 101 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | HelmOperatorPropertiesResponse | HelmOperatorPropertiesResponse | 311 | 362 | 311 | 312 | 590978dd23df6e8a0cdb85f0971066578e5a8b62 | bigcode/the-stack | train |
6a4fe8aaba5172f87af5359f | train | class | @pulumi.output_type
class ErrorAdditionalInfoResponse(dict):
"""
The resource management error additional info.
"""
def __init__(__self__, *,
info: Any,
type: str):
"""
The resource management error additional info.
:param Any info: The additiona... | @pulumi.output_type
class ErrorAdditionalInfoResponse(dict):
| """
The resource management error additional info.
"""
def __init__(__self__, *,
info: Any,
type: str):
"""
The resource management error additional info.
:param Any info: The additional info.
:param str type: The additional info type.
... | (self, "message")
@property
@pulumi.getter(name="messageLevel")
def message_level(self) -> Optional[str]:
"""
Level of the message.
"""
return pulumi.get(self, "message_level")
@pulumi.output_type
class ErrorAdditionalInfoResponse(dict):
| 64 | 64 | 178 | 13 | 51 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ErrorAdditionalInfoResponse | ErrorAdditionalInfoResponse | 105 | 135 | 105 | 106 | 6ae2cc076b044927a59d0df29800d5b3bdedae32 | bigcode/the-stack | train |
44d29209943a387a981f2c44 | train | class | @pulumi.output_type
class ComplianceStatusResponse(dict):
"""
Compliance Status details
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "complianceState":
suggest = "compliance_state"
elif key == "lastConfigApplied":
suggest = "... | @pulumi.output_type
class ComplianceStatusResponse(dict):
| """
Compliance Status details
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "complianceState":
suggest = "compliance_state"
elif key == "lastConfigApplied":
suggest = "last_config_applied"
elif key == "messageLevel":
... | # 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
fro... | 165 | 172 | 576 | 12 | 153 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ComplianceStatusResponse | ComplianceStatusResponse | 26 | 102 | 26 | 27 | 5056af2caae246588c996f9c82e5bfa68cfad247 | bigcode/the-stack | train |
e20735c8b489628d8a30cc3c | train | class | @pulumi.output_type
class ScopeResponse(dict):
"""
Scope of the extension. It can be either Cluster or Namespace; but not both.
"""
def __init__(__self__, *,
cluster: Optional['outputs.ScopeClusterResponse'] = None,
namespace: Optional['outputs.ScopeNamespaceResponse'] ... | @pulumi.output_type
class ScopeResponse(dict):
| """
Scope of the extension. It can be either Cluster or Namespace; but not both.
"""
def __init__(__self__, *,
cluster: Optional['outputs.ScopeClusterResponse'] = None,
namespace: Optional['outputs.ScopeNamespaceResponse'] = None):
"""
Scope of the exten... | )
@property
@pulumi.getter(name="targetNamespace")
def target_namespace(self) -> Optional[str]:
"""
Namespace where the extension will be created for an Namespace scoped extension. If this namespace does not exist, it will be created
"""
return pulumi.get(self, "target_name... | 79 | 79 | 266 | 11 | 68 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ScopeResponse | ScopeResponse | 509 | 541 | 509 | 510 | bd058d490ef9c5ef532047a0829ec7505bc3fa8c | bigcode/the-stack | train |
b4a43bee4858da45bef27aee | train | class | @pulumi.output_type
class ScopeNamespaceResponse(dict):
"""
Specifies that the scope of the extension is Namespace
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "targetNamespace":
suggest = "target_namespace"
if suggest:
pulu... | @pulumi.output_type
class ScopeNamespaceResponse(dict):
| """
Specifies that the scope of the extension is Namespace
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "targetNamespace":
suggest = "target_namespace"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in ScopeNamespaceRes... | pulumi.set(__self__, "release_namespace", release_namespace)
@property
@pulumi.getter(name="releaseNamespace")
def release_namespace(self) -> Optional[str]:
"""
Namespace where the extension Release must be placed, for a Cluster scoped extension. If this namespace does not exist, it will ... | 94 | 94 | 315 | 12 | 82 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ScopeNamespaceResponse | ScopeNamespaceResponse | 469 | 506 | 469 | 470 | 7586fce9325e24bf406666dc3d182999d0febf6b | bigcode/the-stack | train |
26879dd61c22942e9bb50b3c | train | class | @pulumi.output_type
class ErrorDetailResponse(dict):
"""
The error detail.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "additionalInfo":
suggest = "additional_info"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in Err... | @pulumi.output_type
class ErrorDetailResponse(dict):
| """
The error detail.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "additionalInfo":
suggest = "additional_info"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in ErrorDetailResponse. Access the value via the '{suggest}... | init__(__self__, *,
info: Any,
type: str):
"""
The resource management error additional info.
:param Any info: The additional info.
:param str type: The additional info type.
"""
pulumi.set(__self__, "info", info)
pulumi.set(__sel... | 162 | 162 | 541 | 12 | 150 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ErrorDetailResponse | ErrorDetailResponse | 138 | 218 | 138 | 139 | bddaba18dc40b514332ca6a8502edc152a320795 | bigcode/the-stack | train |
cbe9eb0df1bdd0f9f43df845 | train | class | @pulumi.output_type
class SystemDataResponse(dict):
"""
Metadata pertaining to creation and last modification of the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "createdAt":
suggest = "created_at"
elif key == "createdBy":
... | @pulumi.output_type
class SystemDataResponse(dict):
| """
Metadata pertaining to creation and last modification of the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "createdAt":
suggest = "created_at"
elif key == "createdBy":
suggest = "created_by"
elif key == "... | either Cluster or Namespace; but not both.
"""
def __init__(__self__, *,
cluster: Optional['outputs.ScopeClusterResponse'] = None,
namespace: Optional['outputs.ScopeNamespaceResponse'] = None):
"""
Scope of the extension. It can be either Cluster or Namespace; ... | 256 | 256 | 892 | 12 | 244 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | SystemDataResponse | SystemDataResponse | 544 | 651 | 544 | 545 | 56522dc172ddf528bd2123ced2197ab7b502478d | bigcode/the-stack | train |
cabf979ce09cb5ec85a4ca69 | train | class | @pulumi.output_type
class ExtensionStatusResponse(dict):
"""
Status from the extension.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "displayStatus":
suggest = "display_status"
if suggest:
pulumi.log.warn(f"Key '{key}' not f... | @pulumi.output_type
class ExtensionStatusResponse(dict):
| """
Status from the extension.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "displayStatus":
suggest = "display_status"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in ExtensionStatusResponse. Access the value via the... | The error additional info.
"""
return pulumi.get(self, "additional_info")
@property
@pulumi.getter
def code(self) -> str:
"""
The error code.
"""
return pulumi.get(self, "code")
@property
@pulumi.getter
def details(self) -> Sequence['outp... | 188 | 188 | 629 | 12 | 176 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ExtensionStatusResponse | ExtensionStatusResponse | 221 | 308 | 221 | 222 | b52c7137506fa17ba1f37dadde6dd376164c1ae8 | bigcode/the-stack | train |
39fa133fd28c6fdbae6659ce | train | class | @pulumi.output_type
class ScopeClusterResponse(dict):
"""
Specifies that the scope of the extension is Cluster
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "releaseNamespace":
suggest = "release_namespace"
if suggest:
pulumi... | @pulumi.output_type
class ScopeClusterResponse(dict):
| """
Specifies that the scope of the extension is Cluster
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "releaseNamespace":
suggest = "release_namespace"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in ScopeClusterRespo... | property
@pulumi.getter(name="tenantId")
def tenant_id(self) -> str:
"""
The tenant ID of resource.
"""
return pulumi.get(self, "tenant_id")
@property
@pulumi.getter
def type(self) -> Optional[str]:
"""
The identity type.
"""
return pu... | 95 | 95 | 319 | 12 | 83 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | ScopeClusterResponse | ScopeClusterResponse | 429 | 466 | 429 | 430 | 0c52880244967cdfc4a8ad11ace5c5accc3c492d | bigcode/the-stack | train |
22ccb76cd276dc95040d5019 | train | class | @pulumi.output_type
class IdentityResponse(dict):
"""
Identity for the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "principalId":
suggest = "principal_id"
elif key == "tenantId":
suggest = "tenant_id"
if s... | @pulumi.output_type
class IdentityResponse(dict):
| """
Identity for the resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "principalId":
suggest = "principal_id"
elif key == "tenantId":
suggest = "tenant_id"
if suggest:
pulumi.log.warn(f"Key '{key}' ... | is not None:
pulumi.set(__self__, "chart_version", chart_version)
@property
@pulumi.getter(name="chartValues")
def chart_values(self) -> Optional[str]:
"""
Values override for the operator Helm chart.
"""
return pulumi.get(self, "chart_values")
@property
... | 126 | 126 | 421 | 11 | 115 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210501preview/outputs.py | Python | IdentityResponse | IdentityResponse | 365 | 426 | 365 | 366 | d22d4b2a789513b263df10377d6986d9ce358892 | bigcode/the-stack | train |
6247488a448aa9a6c9181726 | train | function | def _plant_visitors(username):
visits_file = VISITORS_FILE.format(username)
# check if the file is empty before trying to deserialize
# the JSON in it.
if os.stat(visits_file).st_size > 0:
with open(visits_file) as fvisit:
return json.load(fvisit)
else:
return []
| def _plant_visitors(username):
| visits_file = VISITORS_FILE.format(username)
# check if the file is empty before trying to deserialize
# the JSON in it.
if os.stat(visits_file).st_size > 0:
with open(visits_file) as fvisit:
return json.load(fvisit)
else:
return []
| plant_data.json"
AGE_RE = re.compile(
r"(?P<days>\d+)d:(?P<hours>\d+)h:(?P<minutes>\d+)m:(?P<seconds>\d+)s"
)
modname = "botany"
def _plant_visitors(username):
| 64 | 64 | 76 | 7 | 57 | kiedtl/ircbot | mod/botany.py | Python | _plant_visitors | _plant_visitors | 26 | 34 | 26 | 26 | d7a447503c40d9d2e271b4c03be5fe8a7f769ec4 | bigcode/the-stack | train |
a49c6104f00ada644009e90c | train | function | def _plant_info(username):
with open(PLANT_FILE.format(username, username)) as finfo:
return json.load(finfo)
| def _plant_info(username):
| with open(PLANT_FILE.format(username, username)) as finfo:
return json.load(finfo)
| # check if the file is empty before trying to deserialize
# the JSON in it.
if os.stat(visits_file).st_size > 0:
with open(visits_file) as fvisit:
return json.load(fvisit)
else:
return []
def _plant_info(username):
| 63 | 64 | 29 | 6 | 57 | kiedtl/ircbot | mod/botany.py | Python | _plant_info | _plant_info | 37 | 39 | 37 | 37 | 73e378ad5847cf9c83749f281577234289fe54a6 | bigcode/the-stack | train |
8ceb634b3d4be7d92b4c312c | train | function | async def visit(self, ch, src, msg):
"""
:name: visit
:hook: cmd
:help: water your (or someone else's) botany plant
:args: @username:str
:aliases: water
"""
username = src
if len(msg) > 1:
username = msg.split()[0]
user_noping = fmt.zwnj(username)
visits_file = VISI... | async def visit(self, ch, src, msg):
| """
:name: visit
:hook: cmd
:help: water your (or someone else's) botany plant
:args: @username:str
:aliases: water
"""
username = src
if len(msg) > 1:
username = msg.split()[0]
user_noping = fmt.zwnj(username)
visits_file = VISITORS_FILE.format(username)
info =... | is_dead"] or last_watered.days >= 5:
is_dead = True
if is_dead:
await self.msg(modname, ch, [f"{user_noping}'s {description} is dead!"])
else:
await self.msg(
modname,
ch,
[
f"{user_noping}'s {description} was last watered {str_last_wa... | 129 | 129 | 433 | 11 | 118 | kiedtl/ircbot | mod/botany.py | Python | visit | visit | 119 | 176 | 119 | 119 | bd0751bbbf36263c41653ac40547b0139f90eda0 | bigcode/the-stack | train |
d3397dd46dadc7a93962920d | train | function | async def init(self):
handlers.register(self, modname, visit)
handlers.register(self, modname, botany)
| async def init(self):
| handlers.register(self, modname, visit)
handlers.register(self, modname, botany)
| cp(ch, "ACTION", f"waters {user_noping}'s {description}!")
except PermissionError:
await self.ctcp(
ch,
"ACTION",
f"peeks at {user_noping}'s {description} over their garden wall",
)
async def init(self):
| 64 | 64 | 26 | 5 | 59 | kiedtl/ircbot | mod/botany.py | Python | init | init | 179 | 181 | 179 | 179 | 7f62488b93061b5927a61dbadd8f01ace50b6eff | bigcode/the-stack | train |
37817434443aa7f7289eb46a | train | function | async def botany(self, ch, src, msg):
"""
:name: botany
:hook: cmd
:help: check on your (or someone else's) botany plant
:args: @username:str
"""
username = src
if len(msg) > 1:
username = msg.split()[0]
user_noping = fmt.zwnj(username)
info = {}
visitors = []
t... | async def botany(self, ch, src, msg):
| """
:name: botany
:hook: cmd
:help: check on your (or someone else's) botany plant
:args: @username:str
"""
username = src
if len(msg) > 1:
username = msg.split()[0]
user_noping = fmt.zwnj(username)
info = {}
visitors = []
try:
info = _plant_info(usernam... | itors.json"
PLANT_FILE = "/home/{}/.botany/{}_plant_data.json"
AGE_RE = re.compile(
r"(?P<days>\d+)d:(?P<hours>\d+)h:(?P<minutes>\d+)m:(?P<seconds>\d+)s"
)
modname = "botany"
def _plant_visitors(username):
visits_file = VISITORS_FILE.format(username)
# check if the file is empty before trying to deserial... | 191 | 191 | 638 | 12 | 179 | kiedtl/ircbot | mod/botany.py | Python | botany | botany | 42 | 116 | 42 | 42 | e63d8cdc9417c275eba9117881e4789185af81dc | bigcode/the-stack | train |
0523cf394f5c3a3409cfa2b4 | train | class | class Float32TC(TextualConvention, OctetString):
reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 32-bit (4-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueS... | class Float32TC(TextualConvention, OctetString):
| reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 32-bit (4-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4)
fixedLength = 4
| 4.c of the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info). This version of this MIB module is part of RFC 6340; see the RFC itself for full legal notices.")
class Float32TC(TextualConvention, OctetString):
| 64 | 64 | 90 | 12 | 52 | agustinhenze/mibs.snmplabs.com | pysnmp-with-texts/FLOAT-TC-MIB.py | Python | Float32TC | Float32TC | 23 | 28 | 23 | 23 | c31c04dd915b02f6c978ef62d3b72aae5924de67 | bigcode/the-stack | train |
9ea5a4f75d9a27a996d91695 | train | class | class Float64TC(TextualConvention, OctetString):
reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 64-bit (8-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueS... | class Float64TC(TextualConvention, OctetString):
| reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 64-bit (8-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)
fixedLength = 8
| a 32-bit (4-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4)
fixedLength = 4
class Float64TC(TextualConvention, OctetString):
| 64 | 64 | 90 | 12 | 51 | agustinhenze/mibs.snmplabs.com | pysnmp-with-texts/FLOAT-TC-MIB.py | Python | Float64TC | Float64TC | 30 | 35 | 30 | 30 | e340db89c542bbd3c6f2b18863df8d09c3c34a04 | bigcode/the-stack | train |
08d468d16bf0d8e9e1619dd1 | train | class | class Float128TC(TextualConvention, OctetString):
reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 128-bit (16-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + Val... | class Float128TC(TextualConvention, OctetString):
| reference = 'IEEE Standard for Floating-Point Arithmetic, Standard 754-2008'
description = 'This type represents a 128-bit (16-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(16, 16)
fixedLength = 16
| a 64-bit (8-octet) IEEE floating-point number in binary interchange format.'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)
fixedLength = 8
class Float128TC(TextualConvention, OctetString):
| 64 | 64 | 90 | 12 | 51 | agustinhenze/mibs.snmplabs.com | pysnmp-with-texts/FLOAT-TC-MIB.py | Python | Float128TC | Float128TC | 37 | 42 | 37 | 37 | db226d62ac86a6d7876f055cf7bfaee26e80a3d2 | bigcode/the-stack | train |
e1924106616d6d7bc4df8faa | train | function | def rules():
return [*additional_fields.rules(), *python_rules(), *target_rules()]
| def rules():
| return [*additional_fields.rules(), *python_rules(), *target_rules()]
| See https://www.pantsbuild.org/docs/protobuf.
"""
from pants.backend.codegen.protobuf.python import additional_fields
from pants.backend.codegen.protobuf.python.rules import rules as python_rules
from pants.backend.codegen.protobuf.target_types import ProtobufLibrary
from pants.backend.codegen.protobuf.target_types im... | 64 | 64 | 19 | 3 | 60 | jperkelens/pants | src/python/pants/backend/codegen/protobuf/python/register.py | Python | rules | rules | 15 | 16 | 15 | 15 | 48504fa37f855ba09f4af0dd571769de2cf926d6 | bigcode/the-stack | train |
114535d213c377339c69b66e | train | function | def target_types():
return [ProtobufLibrary]
| def target_types():
| return [ProtobufLibrary]
| _fields
from pants.backend.codegen.protobuf.python.rules import rules as python_rules
from pants.backend.codegen.protobuf.target_types import ProtobufLibrary
from pants.backend.codegen.protobuf.target_types import rules as target_rules
def rules():
return [*additional_fields.rules(), *python_rules(), *target_rule... | 63 | 64 | 11 | 4 | 59 | jperkelens/pants | src/python/pants/backend/codegen/protobuf/python/register.py | Python | target_types | target_types | 19 | 20 | 19 | 19 | 7b95af95672f2c9695205eaec2ab6b586e88a0cc | bigcode/the-stack | train |
2a9ec8fe50721a89ec100da1 | train | function | def download_file(url, filename):
r = requests.get(url, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
| def download_file(url, filename):
| r = requests.get(url, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
| ):
mod = requests.get(config["modsurl"] + i["name"])
modinfo[i["name"]] = mod.json()
def generate_filename(i):
st = "{name}-{version}.zip".format(name=i["name"], version=i["version"])
return st
def download_file(url, filename):
| 64 | 64 | 64 | 7 | 56 | LizzyTrickster/ssdeploy | ssdeploy.py | Python | download_file | download_file | 74 | 80 | 74 | 74 | eabddb2e0225a505faca14c764bfd4d8dad7e2d1 | bigcode/the-stack | train |
8e96bdc8e2a5e1a52cba6006 | train | function | def md5(filename, blocksize=2**20):
m = hashlib.md5()
with open(filename, "rb") as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
| def md5(filename, blocksize=2**20):
| m = hashlib.md5()
with open(filename, "rb") as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
| (url, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
def md5(filename, blocksize=2**20):
| 64 | 64 | 62 | 12 | 52 | LizzyTrickster/ssdeploy | ssdeploy.py | Python | md5 | md5 | 82 | 90 | 82 | 82 | a11cc0358aed62b41050431476f6aa05c3199bca | bigcode/the-stack | train |
e5c1ef8e51dd221748707ad9 | train | function | def generate_filename(i):
st = "{name}-{version}.zip".format(name=i["name"], version=i["version"])
return st
| def generate_filename(i):
| st = "{name}-{version}.zip".format(name=i["name"], version=i["version"])
return st
| "])
modindex = modindex.json()
modinfo = {}
for i in tqdm.tqdm(modindex["mods"], desc="Downloading Mod Info", leave=True):
mod = requests.get(config["modsurl"] + i["name"])
modinfo[i["name"]] = mod.json()
def generate_filename(i):
| 64 | 64 | 30 | 5 | 59 | LizzyTrickster/ssdeploy | ssdeploy.py | Python | generate_filename | generate_filename | 70 | 72 | 70 | 70 | 28b903a940d98c5b970fe1b1390645ef70338b81 | bigcode/the-stack | train |
cfbff8563a22b3d1cbe46175 | train | class | @admin.register(OpeningHoursPeriod)
class OpeningHoursPeriodAdmin(TranslatableAdmin):
list_display = (
"feature_name",
"valid_from",
"valid_to",
"language_column",
)
search_fields = ("feature__translations__name",)
autocomplete_fields = ("feature",)
inlines = (Opening... | @admin.register(OpeningHoursPeriod)
class OpeningHoursPeriodAdmin(TranslatableAdmin):
| list_display = (
"feature_name",
"valid_from",
"valid_to",
"language_column",
)
search_fields = ("feature__translations__name",)
autocomplete_fields = ("feature",)
inlines = (OpeningHourInline,)
def feature_name(self, obj):
return obj.feature.name
de... | )
search_fields = ("translations__name",)
list_filter = ("translations__language_code",)
@admin.register(SourceType)
class SourceTypeAdmin(admin.ModelAdmin):
search_fields = ("system", "type")
@admin.register(OpeningHoursPeriod)
class OpeningHoursPeriodAdmin(TranslatableAdmin):
| 64 | 64 | 128 | 18 | 46 | City-of-Helsinki/ah | features/admin.py | Python | OpeningHoursPeriodAdmin | OpeningHoursPeriodAdmin | 146 | 167 | 146 | 147 | 3d04fb2cfdc3db4e572c8eee72434731499600e9 | bigcode/the-stack | train |
7540bb02c305713c96042e26 | train | class | class LinkInline(admin.TabularInline):
model = Link
extra = 0
| class LinkInline(admin.TabularInline):
| model = Link
extra = 0
| FeatureTag
autocomplete_fields = ("tag",)
extra = 0
class FeatureTeaserInLine(TranslatableTabularInline):
model = FeatureTeaser
class ImageInline(admin.TabularInline):
model = Image
extra = 0
class LinkInline(admin.TabularInline):
| 64 | 64 | 19 | 8 | 55 | City-of-Helsinki/ah | features/admin.py | Python | LinkInline | LinkInline | 42 | 44 | 42 | 42 | affa68a002c2e042ee937056c272275a7fb33f81 | bigcode/the-stack | train |
04cf6187e2f7fab1b39ef225 | train | class | class PriceTagInLine(TranslatableTabularInline):
model = PriceTag
extra = 0
| class PriceTagInLine(TranslatableTabularInline):
| model = PriceTag
extra = 0
| OpeningHoursPeriodInline(TranslatableTabularInline):
model = OpeningHoursPeriod
show_change_link = True
extra = 0
class OverrideInline(TranslatableTabularInline):
model = Override
extra = 1
class PriceTagInLine(TranslatableTabularInline):
| 64 | 64 | 24 | 12 | 51 | City-of-Helsinki/ah | features/admin.py | Python | PriceTagInLine | PriceTagInLine | 66 | 68 | 66 | 66 | 7d840bc917b335136505b9a3914d94a1fbd0d3c9 | bigcode/the-stack | train |
ee10fe1a69d34f3a0db561b2 | train | class | @admin.register(Feature)
class FeatureAdmin(TranslatableAdmin, admin.OSMGeoAdmin):
# Helsinki
default_lon = 2777215
default_lat = 8434296
default_zoom = 11
actions = ["hide_features"]
list_display = (
"ahti_id",
"name",
"category",
"modified_at",
"visibil... | @admin.register(Feature)
class FeatureAdmin(TranslatableAdmin, admin.OSMGeoAdmin):
# Helsinki
| default_lon = 2777215
default_lat = 8434296
default_zoom = 11
actions = ["hide_features"]
list_display = (
"ahti_id",
"name",
"category",
"modified_at",
"visibility",
"language_column",
)
list_filter = (
"source_type",
"categor... | () if obj else self.extra
class OpeningHoursPeriodInline(TranslatableTabularInline):
model = OpeningHoursPeriod
show_change_link = True
extra = 0
class OverrideInline(TranslatableTabularInline):
model = Override
extra = 1
class PriceTagInLine(TranslatableTabularInline):
model = PriceTag
... | 108 | 108 | 362 | 24 | 83 | City-of-Helsinki/ah | features/admin.py | Python | FeatureAdmin | FeatureAdmin | 71 | 128 | 71 | 73 | 3ed4e03968aec36e74789c867ea13c3b77279987 | bigcode/the-stack | train |
60273cacbfe26d1aef1230ab | train | class | class FeatureTagInline(admin.TabularInline):
model = FeatureTag
autocomplete_fields = ("tag",)
extra = 0
| class FeatureTagInline(admin.TabularInline):
| model = FeatureTag
autocomplete_fields = ("tag",)
extra = 0
| Tag,
FeatureTeaser,
Image,
License,
Link,
OpeningHours,
OpeningHoursPeriod,
Override,
PriceTag,
SourceType,
Tag,
)
class ContactInfoInline(admin.StackedInline):
model = ContactInfo
class FeatureTagInline(admin.TabularInline):
| 64 | 64 | 29 | 9 | 54 | City-of-Helsinki/ah | features/admin.py | Python | FeatureTagInline | FeatureTagInline | 27 | 30 | 27 | 27 | 8ead9682a745e1c8f6b2490515756752edb28f17 | bigcode/the-stack | train |
2afa2dc7349e8f9ed028f817 | train | class | @admin.register(SourceType)
class SourceTypeAdmin(admin.ModelAdmin):
search_fields = ("system", "type")
| @admin.register(SourceType)
class SourceTypeAdmin(admin.ModelAdmin):
| search_fields = ("system", "type")
| admin.register(License)
class LicenseAdmin(TranslatableAdmin):
list_display = (
"name",
"language_column",
)
search_fields = ("translations__name",)
list_filter = ("translations__language_code",)
@admin.register(SourceType)
class SourceTypeAdmin(admin.ModelAdmin):
| 64 | 64 | 24 | 14 | 50 | City-of-Helsinki/ah | features/admin.py | Python | SourceTypeAdmin | SourceTypeAdmin | 141 | 143 | 141 | 142 | 263ffabcc9d5075a511d828493d94d553fd82486 | bigcode/the-stack | train |
fae06801e023d58afa906dd2 | train | class | class OpeningHoursPeriodInline(TranslatableTabularInline):
model = OpeningHoursPeriod
show_change_link = True
extra = 0
| class OpeningHoursPeriodInline(TranslatableTabularInline):
| model = OpeningHoursPeriod
show_change_link = True
extra = 0
| class OpeningHourInline(admin.TabularInline):
model = OpeningHours
extra = 7
def get_extra(self, request, obj=None, **kwargs):
return self.extra - obj.opening_hours.count() if obj else self.extra
class OpeningHoursPeriodInline(TranslatableTabularInline):
| 64 | 64 | 32 | 12 | 51 | City-of-Helsinki/ah | features/admin.py | Python | OpeningHoursPeriodInline | OpeningHoursPeriodInline | 55 | 58 | 55 | 55 | e734f4beb9fe7abba452a5d9d19278375b3aba2d | bigcode/the-stack | train |
31140d1e08244a1a26761382 | train | class | class FeatureTeaserInLine(TranslatableTabularInline):
model = FeatureTeaser
| class FeatureTeaserInLine(TranslatableTabularInline):
| model = FeatureTeaser
| SourceType,
Tag,
)
class ContactInfoInline(admin.StackedInline):
model = ContactInfo
class FeatureTagInline(admin.TabularInline):
model = FeatureTag
autocomplete_fields = ("tag",)
extra = 0
class FeatureTeaserInLine(TranslatableTabularInline):
| 64 | 64 | 20 | 13 | 50 | City-of-Helsinki/ah | features/admin.py | Python | FeatureTeaserInLine | FeatureTeaserInLine | 33 | 34 | 33 | 33 | 8e804e1e49ab09d9ae8c32c65446fc0c435e7c8f | bigcode/the-stack | train |
c42f7df4c9835d746f44155c | train | class | class OverrideInline(TranslatableTabularInline):
model = Override
extra = 1
| class OverrideInline(TranslatableTabularInline):
| model = Override
extra = 1
| =None, **kwargs):
return self.extra - obj.opening_hours.count() if obj else self.extra
class OpeningHoursPeriodInline(TranslatableTabularInline):
model = OpeningHoursPeriod
show_change_link = True
extra = 0
class OverrideInline(TranslatableTabularInline):
| 64 | 64 | 21 | 10 | 53 | City-of-Helsinki/ah | features/admin.py | Python | OverrideInline | OverrideInline | 61 | 63 | 61 | 61 | 6ffcc6b7fc40105a3c9003ddc44c0f36c80a0e54 | bigcode/the-stack | train |
44103b434385f0f03b6ed5b1 | train | class | @admin.register(Tag)
class TagAdmin(TranslatableAdmin):
list_display = (
"id",
"name",
"language_column",
)
search_fields = ("id", "translations__name")
list_filter = ("translations__language_code",)
| @admin.register(Tag)
class TagAdmin(TranslatableAdmin):
| list_display = (
"id",
"name",
"language_column",
)
search_fields = ("id", "translations__name")
list_filter = ("translations__language_code",)
| feature_name(self, obj):
return obj.feature.name
def get_queryset(self, request):
return (
super()
.get_queryset(request)
.select_related("feature")
.prefetch_related("feature__translations")
)
@admin.register(Tag)
class TagAdmin(Translatable... | 64 | 64 | 56 | 13 | 51 | City-of-Helsinki/ah | features/admin.py | Python | TagAdmin | TagAdmin | 170 | 178 | 170 | 171 | ca64468475b84a40d5a8f89992d8d8e8676348d3 | bigcode/the-stack | train |
fd0a6715b2007e2fbd48c4b1 | train | class | @admin.register(License)
class LicenseAdmin(TranslatableAdmin):
list_display = (
"name",
"language_column",
)
search_fields = ("translations__name",)
list_filter = ("translations__language_code",)
| @admin.register(License)
class LicenseAdmin(TranslatableAdmin):
| list_display = (
"name",
"language_column",
)
search_fields = ("translations__name",)
list_filter = ("translations__language_code",)
| was hidden"
else:
message = f"{features_hidden} features were hidden"
self.message_user(request, message)
def get_queryset(self, request):
return super().get_queryset(request).prefetch_related("category__translations")
@admin.register(License)
class LicenseAdmin(TranslatableAdm... | 64 | 64 | 51 | 14 | 50 | City-of-Helsinki/ah | features/admin.py | Python | LicenseAdmin | LicenseAdmin | 131 | 138 | 131 | 132 | 4430830cb71cd802e67376ebbab723a4649755f6 | bigcode/the-stack | train |
c0ce23f8a8558fb1015c1f42 | train | class | class ContactInfoInline(admin.StackedInline):
model = ContactInfo
| class ContactInfoInline(admin.StackedInline):
| model = ContactInfo
|
from features.models import (
ContactInfo,
Feature,
FeatureTag,
FeatureTeaser,
Image,
License,
Link,
OpeningHours,
OpeningHoursPeriod,
Override,
PriceTag,
SourceType,
Tag,
)
class ContactInfoInline(admin.StackedInline):
| 64 | 64 | 15 | 9 | 55 | City-of-Helsinki/ah | features/admin.py | Python | ContactInfoInline | ContactInfoInline | 23 | 24 | 23 | 23 | 8da0b77fbb543042a26f91e4478dea716d864c89 | bigcode/the-stack | train |
9fed59d7be017a4b24339ed9 | train | class | class OpeningHourInline(admin.TabularInline):
model = OpeningHours
extra = 7
def get_extra(self, request, obj=None, **kwargs):
return self.extra - obj.opening_hours.count() if obj else self.extra
| class OpeningHourInline(admin.TabularInline):
| model = OpeningHours
extra = 7
def get_extra(self, request, obj=None, **kwargs):
return self.extra - obj.opening_hours.count() if obj else self.extra
| aserInLine(TranslatableTabularInline):
model = FeatureTeaser
class ImageInline(admin.TabularInline):
model = Image
extra = 0
class LinkInline(admin.TabularInline):
model = Link
extra = 0
class OpeningHourInline(admin.TabularInline):
| 64 | 64 | 52 | 9 | 54 | City-of-Helsinki/ah | features/admin.py | Python | OpeningHourInline | OpeningHourInline | 47 | 52 | 47 | 47 | 68e9bfbb7c5233d3985046689ead01bb90fbc409 | bigcode/the-stack | train |
f16179735805bab32133a737 | train | class | class ImageInline(admin.TabularInline):
model = Image
extra = 0
| class ImageInline(admin.TabularInline):
| model = Image
extra = 0
| ):
model = ContactInfo
class FeatureTagInline(admin.TabularInline):
model = FeatureTag
autocomplete_fields = ("tag",)
extra = 0
class FeatureTeaserInLine(TranslatableTabularInline):
model = FeatureTeaser
class ImageInline(admin.TabularInline):
| 64 | 64 | 19 | 8 | 55 | City-of-Helsinki/ah | features/admin.py | Python | ImageInline | ImageInline | 37 | 39 | 37 | 37 | 61b5ab8b3e1014342bf69464623998692a746a7f | bigcode/the-stack | train |
3a63f97899127541d5fa3a52 | train | class | class Solid(Tile):
def __init__(self, rect: pygame.Rect):
"""Initialize the solid object
Args:
x (int): the x position of the solid
y (int): the y position of the solid
width (int): the width of the solid
height (int): the height of the solid
... | class Solid(Tile):
| def __init__(self, rect: pygame.Rect):
"""Initialize the solid object
Args:
x (int): the x position of the solid
y (int): the y position of the solid
width (int): the width of the solid
height (int): the height of the solid
"""
image =... | import pygame
from src.terrain.mode import ScaleMode
from src.terrain.tiles.tile import Tile
class Solid(Tile):
| 25 | 64 | 102 | 4 | 20 | ProfessorQu/Risky-Robots | src/terrain/tiles/solid.py | Python | Solid | Solid | 7 | 18 | 7 | 7 | 61a470bc9b8f30579ae2d6a15052924baa021a22 | bigcode/the-stack | train |
f2d73dba312098ad573010c2 | train | function | def load_json(file):
with open(file, "r") as f:
output = json.load(f)
return output
| def load_json(file):
| with open(file, "r") as f:
output = json.load(f)
return output
| import json
from os import path
def load_json(file):
| 13 | 64 | 27 | 5 | 7 | wufanyou/TLab-Last-Mile | src/model_apply_check.py | Python | load_json | load_json | 5 | 8 | 5 | 5 | d15354936d054d8b40ae770c2e390046fd41211a | bigcode/the-stack | train |
16b5db9a7b7a09a6d0436454 | train | class | class Data:
def __init__(self, data_path="."):
self.travel_times = load_json(
f"{data_path}/model_apply_inputs/new_travel_times.json"
)
self.route_id = list(self.travel_times.keys())
def __len__(self) -> int:
return len(self.route_id)
| class Data:
| def __init__(self, data_path="."):
self.travel_times = load_json(
f"{data_path}/model_apply_inputs/new_travel_times.json"
)
self.route_id = list(self.travel_times.keys())
def __len__(self) -> int:
return len(self.route_id)
| import json
from os import path
def load_json(file):
with open(file, "r") as f:
output = json.load(f)
return output
class Data:
| 38 | 64 | 67 | 3 | 34 | wufanyou/TLab-Last-Mile | src/model_apply_check.py | Python | Data | Data | 11 | 19 | 11 | 11 | 522bacf32d1241c0d4bedd3c959f5636ef191387 | bigcode/the-stack | train |
b64d4918734e40a588e26d18 | train | class | class _ProductLinearOperator(LinearOperator):
def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape[1] != B.shape[0]:
raise ValueError('ca... | class _ProductLinearOperator(LinearOperator):
| def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape[1] != B.shape[0]:
raise ValueError('cannot multiply %r and %r: shape mismatch'
... | [1].rmatvec(x)
def _matmat(self, x):
return self.args[0].matmat(x) + self.args[1].matmat(x)
def _adjoint(self):
A, B = self.args
return A.H + B.H
class _ProductLinearOperator(LinearOperator):
| 70 | 70 | 236 | 9 | 60 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _ProductLinearOperator | _ProductLinearOperator | 520 | 543 | 520 | 520 | 9f47c0d789590a704bc2276fb5b64a35b48ae3f7 | bigcode/the-stack | train |
156f5196d1b062b85cc93b85 | train | class | class _SumLinearOperator(LinearOperator):
def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape != B.shape:
raise ValueError('cannot add %... | class _SumLinearOperator(LinearOperator):
| def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape != B.shape:
raise ValueError('cannot add %r and %r: shape mismatch'
... | def _get_dtype(operators, dtypes=None):
if dtypes is None:
dtypes = []
for obj in operators:
if obj is not None and hasattr(obj, 'dtype'):
dtypes.append(obj.dtype)
return np.find_common_type(dtypes, [])
class _SumLinearOperator(LinearOperator):
| 68 | 69 | 231 | 9 | 59 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _SumLinearOperator | _SumLinearOperator | 495 | 517 | 495 | 495 | 5eeac5fa73bdf72c115b8c175e659481d86adc47 | bigcode/the-stack | train |
b75a82a13ff159d44a49a954 | train | class | class _CustomLinearOperator(LinearOperator):
"""Linear operator defined in terms of user-specified operations."""
def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None):
super(_CustomLinearOperator, self).__init__(dtype, shape)
self.args = ()
self.__matvec_impl = mat... | class _CustomLinearOperator(LinearOperator):
| """Linear operator defined in terms of user-specified operations."""
def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None):
super(_CustomLinearOperator, self).__init__(dtype, shape)
self.args = ()
self.__matvec_impl = matvec
self.__rmatvec_impl = rmatvec
... | T = property(transpose)
def _adjoint(self):
"""Default implementation of _adjoint; defers to rmatvec."""
shape = (self.shape[1], self.shape[0])
return _CustomLinearOperator(shape, matvec=self.rmatvec,
rmatvec=self.matvec,
... | 80 | 80 | 267 | 9 | 71 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _CustomLinearOperator | _CustomLinearOperator | 450 | 483 | 450 | 450 | e070bd0a3e09362e527fd335f26b104a066592fb | bigcode/the-stack | train |
ee843d40d5252b023612f51d | train | class | class MatrixLinearOperator(LinearOperator):
def __init__(self, A):
super(MatrixLinearOperator, self).__init__(A.dtype, A.shape)
self.A = A
self.__adj = None
self.args = (A,)
def _matmat(self, X):
return self.A.dot(X)
def _adjoint(self):
if self.__adj is None... | class MatrixLinearOperator(LinearOperator):
| def __init__(self, A):
super(MatrixLinearOperator, self).__init__(A.dtype, A.shape)
self.A = A
self.__adj = None
self.args = (A,)
def _matmat(self, X):
return self.A.dot(X)
def _adjoint(self):
if self.__adj is None:
self.__adj = _AdjointMatrixOpe... | .args[0].rmatvec, x)
def _matmat(self, x):
return self._power(self.args[0].matmat, x)
def _adjoint(self):
A, p = self.args
return A.H ** p
class MatrixLinearOperator(LinearOperator):
| 64 | 64 | 103 | 8 | 55 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | MatrixLinearOperator | MatrixLinearOperator | 602 | 615 | 602 | 602 | cade6de522948ed8726aff74fc47b0e30941a2e0 | bigcode/the-stack | train |
59c0aeb4854c56f4fbcc7db8 | train | class | class LinearOperator(object):
"""Common interface for performing matrix vector products
Many iterative methods (e.g. cg, gmres) do not need to know the
individual entries of a matrix to solve a linear system A*x=b.
Such solvers only require the computation of matrix vector
products, A*v where v is ... | class LinearOperator(object):
| """Common interface for performing matrix vector products
Many iterative methods (e.g. cg, gmres) do not need to know the
individual entries of a matrix to solve a linear system A*x=b.
Such solvers only require the computation of matrix vector
products, A*v where v is a dense vector. This class se... | linear operator multiplies with (operates on) a vector. We can now
add this operator to a sparse matrix that stores only offsets from one::
>>> from scipy.sparse import csr_matrix
>>> offsets = csr_matrix([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
>>> A = aslinearoperator(offsets) + Ones(offsets.shape)
>>> A... | 256 | 256 | 2,828 | 5 | 251 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | LinearOperator | LinearOperator | 53 | 447 | 53 | 53 | ad1f534f6da7a5c058dad2e30feb8feea2d123cd | bigcode/the-stack | train |
1e7edd1a34da335b7621fd25 | train | class | class _ScaledLinearOperator(LinearOperator):
def __init__(self, A, alpha):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if not np.isscalar(alpha):
raise ValueError('scalar expected as alpha')
dtype = _get_dtype([A], [type(alph... | class _ScaledLinearOperator(LinearOperator):
| def __init__(self, A, alpha):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if not np.isscalar(alpha):
raise ValueError('scalar expected as alpha')
dtype = _get_dtype([A], [type(alpha)])
super(_ScaledLinearOperator, sel... | rmatvec(x))
def _matmat(self, x):
return self.args[0].matmat(self.args[1].matmat(x))
def _adjoint(self):
A, B = self.args
return B.H * A.H
class _ScaledLinearOperator(LinearOperator):
| 64 | 64 | 202 | 9 | 54 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _ScaledLinearOperator | _ScaledLinearOperator | 546 | 567 | 546 | 546 | 82b6baf9dfb8ae4c544d7e2f5e7583164b28b2a0 | bigcode/the-stack | train |
ff75562f69a01ff6f59b8aa3 | train | function | def _get_dtype(operators, dtypes=None):
if dtypes is None:
dtypes = []
for obj in operators:
if obj is not None and hasattr(obj, 'dtype'):
dtypes.append(obj.dtype)
return np.find_common_type(dtypes, [])
| def _get_dtype(operators, dtypes=None):
| if dtypes is None:
dtypes = []
for obj in operators:
if obj is not None and hasattr(obj, 'dtype'):
dtypes.append(obj.dtype)
return np.find_common_type(dtypes, [])
| _impl(x)
def _adjoint(self):
return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
matvec=self.__rmatvec_impl,
rmatvec=self.__matvec_impl,
dtype=self.dtype)
def _get_dtype(operators, ... | 64 | 64 | 59 | 11 | 53 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _get_dtype | _get_dtype | 486 | 492 | 486 | 486 | d311056e51f960c059d9f2685f336a3c7e36fa08 | bigcode/the-stack | train |
1c5487979aaf60f73feeb861 | train | class | class _AdjointMatrixOperator(MatrixLinearOperator):
def __init__(self, adjoint):
self.A = adjoint.A.T.conj()
self.__adjoint = adjoint
self.args = (adjoint,)
self.shape = adjoint.shape[1], adjoint.shape[0]
@property
def dtype(self):
return self.__adjoint.dtype
de... | class _AdjointMatrixOperator(MatrixLinearOperator):
| def __init__(self, adjoint):
self.A = adjoint.A.T.conj()
self.__adjoint = adjoint
self.args = (adjoint,)
self.shape = adjoint.shape[1], adjoint.shape[0]
@property
def dtype(self):
return self.__adjoint.dtype
def _adjoint(self):
return self.__adjoint
| = (A,)
def _matmat(self, X):
return self.A.dot(X)
def _adjoint(self):
if self.__adj is None:
self.__adj = _AdjointMatrixOperator(self)
return self.__adj
class _AdjointMatrixOperator(MatrixLinearOperator):
| 64 | 64 | 95 | 10 | 53 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _AdjointMatrixOperator | _AdjointMatrixOperator | 618 | 630 | 618 | 618 | f556c0da9f0a21b38a737443d5ae717ce053236b | bigcode/the-stack | train |
482ae9e19fb793df6c710cea | train | class | class _PowerLinearOperator(LinearOperator):
def __init__(self, A, p):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if A.shape[0] != A.shape[1]:
raise ValueError('square LinearOperator expected, got %r' % A)
if not isintlike(p)... | class _PowerLinearOperator(LinearOperator):
| def __init__(self, A, p):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if A.shape[0] != A.shape[1]:
raise ValueError('square LinearOperator expected, got %r' % A)
if not isintlike(p) or p < 0:
raise ValueError('non... | return np.conj(self.args[1]) * self.args[0].rmatvec(x)
def _matmat(self, x):
return self.args[1] * self.args[0].matmat(x)
def _adjoint(self):
A, alpha = self.args
return A.H * alpha
class _PowerLinearOperator(LinearOperator):
| 78 | 78 | 261 | 9 | 68 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | _PowerLinearOperator | _PowerLinearOperator | 570 | 599 | 570 | 570 | 37776ce6cf3b48b8b19411f7a831123ecd19087c | bigcode/the-stack | train |
01b3484867abb1d27c9b18ea | train | function | def aslinearoperator(A):
"""Return A as a LinearOperator.
'A' may be any of the following types:
- ndarray
- matrix
- sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
- LinearOperator
- An object with .shape and .matvec attributes
See the LinearOperator documentation for addition... | def aslinearoperator(A):
| """Return A as a LinearOperator.
'A' may be any of the following types:
- ndarray
- matrix
- sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
- LinearOperator
- An object with .shape and .matvec attributes
See the LinearOperator documentation for additional information.
Note... | ):
return self.__adjoint.dtype
def _adjoint(self):
return self.__adjoint
class IdentityOperator(LinearOperator):
def __init__(self, shape, dtype=None):
super(IdentityOperator, self).__init__(dtype, shape)
def _matvec(self, x):
return x
def _rmatvec(self, x):
... | 113 | 113 | 378 | 6 | 106 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | aslinearoperator | aslinearoperator | 650 | 700 | 650 | 650 | 152dc94e5522ac68f35d00eb3e05abf02f0424b6 | bigcode/the-stack | train |
6b95ffe82f7db2072e636b98 | train | class | class IdentityOperator(LinearOperator):
def __init__(self, shape, dtype=None):
super(IdentityOperator, self).__init__(dtype, shape)
def _matvec(self, x):
return x
def _rmatvec(self, x):
return x
def _matmat(self, x):
return x
def _adjoint(self):
return sel... | class IdentityOperator(LinearOperator):
| def __init__(self, shape, dtype=None):
super(IdentityOperator, self).__init__(dtype, shape)
def _matvec(self, x):
return x
def _rmatvec(self, x):
return x
def _matmat(self, x):
return x
def _adjoint(self):
return self
| oint
self.args = (adjoint,)
self.shape = adjoint.shape[1], adjoint.shape[0]
@property
def dtype(self):
return self.__adjoint.dtype
def _adjoint(self):
return self.__adjoint
class IdentityOperator(LinearOperator):
| 64 | 64 | 84 | 7 | 56 | anthowen/duplify | env/lib/python3.6/site-packages/scipy/sparse/linalg/interface.py | Python | IdentityOperator | IdentityOperator | 633 | 647 | 633 | 633 | 11a919981913dd5168e25d257d824996aeed240d | bigcode/the-stack | train |
24cc360d651b6d6c61a9893d | train | function | def query(): # pylint: disable=too-many-locals
"""Query script entry point."""
hl.init(default_reference='GRCh38')
snp_chip = hl.read_matrix_table(SNP_CHIP)
tob_wgs = hl.read_matrix_table(TOB_WGS)
tob_wgs = hl.experimental.densify(tob_wgs)
tob_wgs = tob_wgs.annotate_entries(GT=lgt_to_gt(tob_w... | def query(): # pylint: disable=too-many-locals
| """Query script entry point."""
hl.init(default_reference='GRCh38')
snp_chip = hl.read_matrix_table(SNP_CHIP)
tob_wgs = hl.read_matrix_table(TOB_WGS)
tob_wgs = hl.experimental.densify(tob_wgs)
tob_wgs = tob_wgs.annotate_entries(GT=lgt_to_gt(tob_wgs.LGT, tob_wgs.LA))
snp_chip = snp_chip.sem... | """
Project WGS data onto SNP-chip data
"""
import re
import hail as hl
import pandas as pd
from analysis_runner import bucket_path, output_path
from hail.experimental import pc_project
from hail.experimental import lgt_to_gt
from bokeh.plotting import ColumnDataSource, figure
from bokeh.palettes import Dark2 # pylin... | 183 | 256 | 1,018 | 15 | 168 | populationgenomics/ancestry | scripts/hail_batch/project_wgs_onto_snp_chip_pca/project_wgs_samples_onto_snp_chip.py | Python | query | query | 24 | 125 | 24 | 24 | d2ec6574f132556c5b6bdcbdced22b2718d6765e | bigcode/the-stack | train |
84bc6ffb24e2231b416e550e | train | function | def build_hash160_lookup(secret_exponents, generators):
d = {}
for secret_exponent in secret_exponents:
for generator in generators:
public_pair = secret_exponent * generator
for compressed in (True, False):
hash160 = public_pair_to_hash160_sec(public_pair, compre... | def build_hash160_lookup(secret_exponents, generators):
| d = {}
for secret_exponent in secret_exponents:
for generator in generators:
public_pair = secret_exponent * generator
for compressed in (True, False):
hash160 = public_pair_to_hash160_sec(public_pair, compressed=compressed)
d[hash160] = (secret_ex... | import hashlib
from pycoin.encoding.hash import hash160
from pycoin.encoding.sec import public_pair_to_hash160_sec
def build_hash160_lookup(secret_exponents, generators):
| 36 | 64 | 90 | 11 | 24 | jaschadub/pycoin | pycoin/solve/utils.py | Python | build_hash160_lookup | build_hash160_lookup | 7 | 15 | 7 | 7 | 3f3def8a59b1191bcf97c606ad88c2cac6888d17 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.