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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1aed8802ddd625fccb355eac | train | function | def showmarker(fm, marker, index=None):
"""utility function to display obsolescence marker in a readable way
To be used by debug function."""
if index is not None:
fm.write('index', '%i ', index)
fm.write('prednode', '%s ', hex(marker.prednode()))
succs = marker.succnodes()
fm.condwrite... | def showmarker(fm, marker, index=None):
| """utility function to display obsolescence marker in a readable way
To be used by debug function."""
if index is not None:
fm.write('index', '%i ', index)
fm.write('prednode', '%s ', hex(marker.prednode()))
succs = marker.succnodes()
fm.condwrite(succs, 'succnodes', '%s ',
... | .get('style'))
if not spec.ref and not spec.tmpl and not spec.mapfile:
return changeset_printer(ui, repo, matchfn, opts, buffered)
return changeset_templater(ui, repo, spec, matchfn, opts, buffered)
def showmarker(fm, marker, index=None):
| 68 | 68 | 227 | 11 | 57 | EnjoyLifeFund/py36pkgs | mercurial/cmdutil.py | Python | showmarker | showmarker | 2,017 | 2,036 | 2,017 | 2,017 | 03f82cbecb715948da933d1f4d03ea04e897b355 | bigcode/the-stack | train |
91eda177f4a22b1635265357 | train | function | def ctft(x, f, domega=0.01, omega_max=None):
"""
Approximate Fourier transform of a compactly-supported continuous signal.
We assume that the samples x[n] are equally spaced.
"""
dx = x[1] - x[0]
if omega_max is None:
# use Nyquist frequency as cut-off
omega_max = 1 / (2 * dx)
... | def ctft(x, f, domega=0.01, omega_max=None):
| """
Approximate Fourier transform of a compactly-supported continuous signal.
We assume that the samples x[n] are equally spaced.
"""
dx = x[1] - x[0]
if omega_max is None:
# use Nyquist frequency as cut-off
omega_max = 1 / (2 * dx)
else:
# downsample (this is an opt... | import numpy as np
import scipy.fftpack
__all__ = ["convmtx", "ctft", "dtft", "dtft2d"]
def convmtx(h, N):
"""Return convolution matrix for kernel h and input signals of length N."""
return scipy.linalg.toeplitz(np.r_[h, [0] * (N - 1)], np.zeros(N))
def ctft(x, f, domega=0.01, omega_max=None):
| 103 | 131 | 437 | 18 | 85 | illc-uva/pyfermions | pyfermions/utils.py | Python | ctft | ctft | 12 | 51 | 12 | 12 | 87a1611188813e13fb8e9bdf8e74a99eb5b3665e | bigcode/the-stack | train |
f4f82609b0920b78bcd963a3 | train | function | def dtft(n, s, omega):
"""Periodic Fourier transform of a discrete signal s[n]."""
return np.sum(
s[:, np.newaxis] * np.exp(-1j * n[:, np.newaxis] * omega[np.newaxis, :]), axis=0
)
| def dtft(n, s, omega):
| """Periodic Fourier transform of a discrete signal s[n]."""
return np.sum(
s[:, np.newaxis] * np.exp(-1j * n[:, np.newaxis] * omega[np.newaxis, :]), axis=0
)
| omega = np.r_[omega[half:], omega[:half]]
g = np.r_[g[half:], g[:half]]
mask = (-omega_max <= omega) & (omega <= omega_max)
return (omega[mask], g[mask])
def dtft(n, s, omega):
| 64 | 64 | 61 | 9 | 55 | illc-uva/pyfermions | pyfermions/utils.py | Python | dtft | dtft | 54 | 58 | 54 | 54 | 030818b97070ca5b1c530f9e31ddf8044bf6a921 | bigcode/the-stack | train |
94580322ae52cbed0b70aaff | train | function | def dtft2d(n, m, s, omega):
"""Periodic 2D Fourier transform of a discrete signal s[n,m]."""
# sample discrete-time Fourier transform
f_half = np.sum(
s[:, :, np.newaxis]
* np.exp(-1j * m[np.newaxis, :, np.newaxis] * omega[np.newaxis, np.newaxis, :]),
axis=1,
)
f = np.sum(
... | def dtft2d(n, m, s, omega):
| """Periodic 2D Fourier transform of a discrete signal s[n,m]."""
# sample discrete-time Fourier transform
f_half = np.sum(
s[:, :, np.newaxis]
* np.exp(-1j * m[np.newaxis, :, np.newaxis] * omega[np.newaxis, np.newaxis, :]),
axis=1,
)
f = np.sum(
f_half[:, np.newaxis, ... | """Periodic Fourier transform of a discrete signal s[n]."""
return np.sum(
s[:, np.newaxis] * np.exp(-1j * n[:, np.newaxis] * omega[np.newaxis, :]), axis=0
)
def dtft2d(n, m, s, omega):
| 64 | 64 | 145 | 13 | 51 | illc-uva/pyfermions | pyfermions/utils.py | Python | dtft2d | dtft2d | 61 | 74 | 61 | 61 | ce1078d3c5fdb4c89fef27957b79ad19d367b584 | bigcode/the-stack | train |
97169e255cb0ba3157899373 | train | function | def convmtx(h, N):
"""Return convolution matrix for kernel h and input signals of length N."""
return scipy.linalg.toeplitz(np.r_[h, [0] * (N - 1)], np.zeros(N))
| def convmtx(h, N):
| """Return convolution matrix for kernel h and input signals of length N."""
return scipy.linalg.toeplitz(np.r_[h, [0] * (N - 1)], np.zeros(N))
| import numpy as np
import scipy.fftpack
__all__ = ["convmtx", "ctft", "dtft", "dtft2d"]
def convmtx(h, N):
| 42 | 64 | 50 | 8 | 34 | illc-uva/pyfermions | pyfermions/utils.py | Python | convmtx | convmtx | 7 | 9 | 7 | 7 | ae6ef2e4d0dbeadfc12ef11a2bf2658ed49b03de | bigcode/the-stack | train |
9e13564de677dea8481548f5 | train | function | @pytest.fixture
def catalog():
return {
"users": {
"table_name": "users",
"instance_id": "my_instance",
"column_families": {
"profile": {
"only_read_latest": True,
"columns": {"age": int, "gender": str},
... | @pytest.fixture
def catalog():
| return {
"users": {
"table_name": "users",
"instance_id": "my_instance",
"column_families": {
"profile": {
"only_read_latest": True,
"columns": {"age": int, "gender": str},
},
},
... | import pytest
from google.auth.credentials import AnonymousCredentials
from bigql.client import Client
from bigql.select import SelectQuery
@pytest.fixture
def catalog():
| 32 | 64 | 184 | 6 | 25 | jychen7/BigQL | tests/conftest.py | Python | catalog | catalog | 7 | 34 | 7 | 8 | bef48955bb552549816b8e352479762c08b5e919 | bigcode/the-stack | train |
3cc6fd7d256cc97b3c01709b | train | function | @pytest.fixture
def anonymous_client():
return Client(project="my_project", credentials=AnonymousCredentials())
| @pytest.fixture
def anonymous_client():
| return Client(project="my_project", credentials=AnonymousCredentials())
| ments": {
"only_read_latest": True,
"columns": {"pressure": int, "temperature": str},
},
},
"row_key_identifiers": ["device_id", "event_minute"],
"row_key_separator": "#",
},
}
@pytest.fixture
def anonymous_client():... | 64 | 64 | 20 | 7 | 57 | jychen7/BigQL | tests/conftest.py | Python | anonymous_client | anonymous_client | 37 | 39 | 37 | 38 | cba20bee517007008d3b923d83a8fbf80c778018 | bigcode/the-stack | train |
cbecc8ba588db4bf67c524c2 | train | function | @bot.event
async def on_connect():
print("Startup latency: {}ms\n".format(int(bot.latency * 1000)))
print(f"hlaskyList: {len(bot.hlaskyList)}")
print(f"rejoinList: {len(bot.rejoinList)}")
print(f"audioList: {len(bot.audioList)}")
print("\nAUDIO:")
print(" " + format_aud... | @bot.event
async def on_connect():
| print("Startup latency: {}ms\n".format(int(bot.latency * 1000)))
print(f"hlaskyList: {len(bot.hlaskyList)}")
print(f"rejoinList: {len(bot.rejoinList)}")
print(f"audioList: {len(bot.audioList)}")
print("\nAUDIO:")
print(" " + format_audio(bot.audioList).replace("\n", "\n... | from time import gmtime
from time import strftime
import discord
from discord.ext import commands
from bot import BotWrapper
from utils import format_audio
from settings import *
bot = BotWrapper(command_prefix=PREFIX, description=DESC, activity=ACTIVITY)
@bot.event
async def on_connect():
| 64 | 64 | 107 | 9 | 55 | relativehysteria/enigma | src/main.py | Python | on_connect | on_connect | 18 | 25 | 18 | 19 | 669e492facd72361243b576dc09f2bd08a4bc540 | bigcode/the-stack | train |
b8d76b010a44a6b9910b1a2a | train | function | @bot.event
async def on_ready():
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("\033[92mREADY\033[0m")
| @bot.event
async def on_ready():
| print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("\033[92mREADY\033[0m")
| joinList: {len(bot.rejoinList)}")
print(f"audioList: {len(bot.audioList)}")
print("\nAUDIO:")
print(" " + format_audio(bot.audioList).replace("\n", "\n "))
@bot.event
async def on_ready():
| 63 | 64 | 43 | 9 | 54 | relativehysteria/enigma | src/main.py | Python | on_ready | on_ready | 27 | 30 | 27 | 28 | b0b1803fdc15a0a33e98e7dea593feb690a4ec17 | bigcode/the-stack | train |
12975fec200895da3cbd9574 | train | function | @bot.command()
async def count(context):
"""
Spočítá humor
"""
await context.send(str(len(bot.hlaskyList)))
| @bot.command()
async def count(context):
| """
Spočítá humor
"""
await context.send(str(len(bot.hlaskyList)))
| msg.split(FILEEXT)
msg = FILEEXT.join(msplit[:-1])
fileName = discord.File(f"{PICDIR}/" + msplit[-1].strip())
else:
fileName = None
await context.send(msg, file=fileName)
@bot.command()
async def count(context):
| 64 | 64 | 32 | 9 | 55 | relativehysteria/enigma | src/main.py | Python | count | count | 53 | 58 | 53 | 54 | 448c737f205e63bf274f96995c16cc56833709bb | bigcode/the-stack | train |
59eee488451391eb57c07e77 | train | function | @bot.command()
async def gank(context, *args):
"""
Gankne ti voice chat
"""
# Pokud nekdo posle ID nejakeho voice chatu, gankne dany voice chat
if len(args) == 1:
try:
voiceChannel = discord.utils.get(
context.guild.voice_channels,
id=int(args[0])
... | @bot.command()
async def gank(context, *args):
| """
Gankne ti voice chat
"""
# Pokud nekdo posle ID nejakeho voice chatu, gankne dany voice chat
if len(args) == 1:
try:
voiceChannel = discord.utils.get(
context.guild.voice_channels,
id=int(args[0])
)
except:
retur... | else:
fileName = None
await context.send(msg, file=fileName)
@bot.command()
async def count(context):
"""
Spočítá humor
"""
await context.send(str(len(bot.hlaskyList)))
@bot.command()
async def gank(context, *args):
| 64 | 64 | 185 | 13 | 51 | relativehysteria/enigma | src/main.py | Python | gank | gank | 60 | 83 | 60 | 61 | 831032a6d18c0a2e8638edd547d87ce46bfe6ffc | bigcode/the-stack | train |
489d1eba4c70ce9ee677f60a | train | function | @bot.command()
async def naga(context, *args):
"""
Něco ti zahraje ve voice chatu
"""
if len(args) == 0:
message = "Příklad: `bota naga 3`\n"
message += '```\n'
message += format_audio(bot.audioList)
message += '```'
await context.send(message)
return
... | @bot.command()
async def naga(context, *args):
| """
Něco ti zahraje ve voice chatu
"""
if len(args) == 0:
message = "Příklad: `bota naga 3`\n"
message += '```\n'
message += format_audio(bot.audioList)
message += '```'
await context.send(message)
return
if args[0] == "random":
randomNumbe... | Bot se nesmi jiz nachazet v nejakem voice chatu
if bot.currentVoiceClient is not None:
await context.send(choice(bot.rejoinList))
return
bot.currentVoiceClient = await voiceChannel.connect()
@bot.command()
async def naga(context, *args):
| 64 | 64 | 129 | 12 | 52 | relativehysteria/enigma | src/main.py | Python | naga | naga | 86 | 105 | 86 | 87 | 744a03732d5b53b38849b7e0efa3162488ca3e31 | bigcode/the-stack | train |
f50312977aa8a56feadb2454 | train | function | @bot.command()
async def wtf(context):
"""
Ukáže humor
"""
msg = choice(bot.hlaskyList)
msg = msg.replace(NEWLINE, "\n")
# Pokud se ve zprave nachazi `FILEEXT`, tak posleme nejaky soubor
if msg.count(FILEEXT) >= 1:
msplit = msg.split(FILEEXT)
msg = FILEEXT.join(msplit[:-1])
... | @bot.command()
async def wtf(context):
| """
Ukáže humor
"""
msg = choice(bot.hlaskyList)
msg = msg.replace(NEWLINE, "\n")
# Pokud se ve zprave nachazi `FILEEXT`, tak posleme nejaky soubor
if msg.count(FILEEXT) >= 1:
msplit = msg.split(FILEEXT)
msg = FILEEXT.join(msplit[:-1])
fileName = discord.File(f"{PICD... | "\n "))
@bot.event
async def on_ready():
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("\033[92mREADY\033[0m")
## COMMANDS ####################################################################
@bot.command()
async def wtf(context):
| 63 | 64 | 132 | 10 | 53 | relativehysteria/enigma | src/main.py | Python | wtf | wtf | 34 | 50 | 34 | 35 | 418954f6f8fcdbf377773274af754b0a50ffb11f | bigcode/the-stack | train |
6c4d211f4462dd520e841508 | train | function | @bot.command()
async def feed(context):
"""
Feedne ti voice chat
"""
if bot.currentVoiceClient is not None:
await bot.currentVoiceClient.disconnect()
bot.currentVoiceClient = None
| @bot.command()
async def feed(context):
| """
Feedne ti voice chat
"""
if bot.currentVoiceClient is not None:
await bot.currentVoiceClient.disconnect()
bot.currentVoiceClient = None
| '```'
await context.send(message)
return
if args[0] == "random":
randomNumber = randint(1, len(bot.audioList) + 1)
bot.play(randomNumber)
return
bot.play(args[0])
@bot.command()
async def feed(context):
| 64 | 64 | 47 | 9 | 55 | relativehysteria/enigma | src/main.py | Python | feed | feed | 108 | 116 | 108 | 109 | 8099cd6395f2f6d448eb61306aac0f6713923eb7 | bigcode/the-stack | train |
c3cbe01ab2e0162bbe8747d7 | train | class | class SerializerCallable:
"""A callable object that calls the given serializer function with the given object returns a serialized
dictionary of the form {<key>: <serialized value>}.
"""
def __init__(self, obj, key=None, serializer_function=None):
"""Setup the object to be serialized, its name i... | class SerializerCallable:
| """A callable object that calls the given serializer function with the given object returns a serialized
dictionary of the form {<key>: <serialized value>}.
"""
def __init__(self, obj, key=None, serializer_function=None):
"""Setup the object to be serialized, its name in the dictionary and the s... | contains the serialized dictionary.
"""
self._serializer_callables = serializer_callables
self.serialized = Manager().dict()
def __call__(self):
"""Call each of the defined callables in-order and update the multiprocessing.Manager dictionary with their
returned dictionaries... | 89 | 89 | 299 | 4 | 85 | mohammadsadiq/autotrail | src/autotrail/core/api/serializers.py | Python | SerializerCallable | SerializerCallable | 44 | 72 | 44 | 44 | 00fd66edd67e7e73360964280394be93934a05b0 | bigcode/the-stack | train |
2561ef9e80b91c645e8fa84c | train | class | class Serializer:
"""A callable object that invokes all the given serializer callables and collates them into a single serialized
dictionary presented as a multiprocessing.Manager dictionary.
"""
def __init__(self, serializer_callables):
"""Define the list of callables that will be invoked in-or... | class Serializer:
| """A callable object that invokes all the given serializer callables and collates them into a single serialized
dictionary presented as a multiprocessing.Manager dictionary.
"""
def __init__(self, serializer_callables):
"""Define the list of callables that will be invoked in-order.
:par... | or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from multiprocessing import Manage... | 64 | 64 | 190 | 3 | 60 | mohammadsadiq/autotrail | src/autotrail/core/api/serializers.py | Python | Serializer | Serializer | 19 | 41 | 19 | 19 | e363b0a0d60e32542d77a19fe34fdf98e69588c1 | bigcode/the-stack | train |
3db4337a0b0c2de783657861 | train | function | def clear_prev_tokens(trainer):
# This function clears the cache before/after validation.
for name, module in trainer.get_model().named_modules():
if isinstance(module, TransformerDecoderLayer):
module.prev_out = None
| def clear_prev_tokens(trainer):
# This function clears the cache before/after validation.
| for name, module in trainer.get_model().named_modules():
if isinstance(module, TransformerDecoderLayer):
module.prev_out = None
| valid_losses[0])
return valid_losses, should_stop
def get_training_stats(stats):
stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
return stats
def clear_prev_tokens(trainer):
# This function clears the cache before/after validation.
| 64 | 64 | 48 | 19 | 44 | ofirpress/shortformer | fairseq_cli/train.py | Python | clear_prev_tokens | clear_prev_tokens | 290 | 294 | 290 | 291 | 3edad035b2d19eb5349661feaf004e13180e47e9 | bigcode/the-stack | train |
281d62ac2b5b8a0e7aa721cd | train | function | def cli_main(modify_parser=None):
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
if args.profile:
with torch.cuda.profiler.profile():
with torch.autograd.profiler.emit_nvtx():
distributed_utils.call_main(args... | def cli_main(modify_parser=None):
| parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
if args.profile:
with torch.cuda.profiler.profile():
with torch.autograd.profiler.emit_nvtx():
distributed_utils.call_main(args, main)
else:
distribu... | key = "best_{0}".format(args.best_checkpoint_metric)
best_function = max if args.maximize_best_checkpoint_metric else min
stats[key] = best_function(
checkpoint_utils.save_checkpoint.best, stats[args.best_checkpoint_metric]
)
return stats
def cli_main(modify_parser=None):
| 64 | 64 | 77 | 8 | 55 | ofirpress/shortformer | fairseq_cli/train.py | Python | cli_main | cli_main | 349 | 357 | 349 | 349 | 7aedfa973b06e85c9bf3491c232ddc836917d97f | bigcode/the-stack | train |
7e54964e57f292c841c7b951 | train | function | def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch):
num_updates = trainer.get_num_updates()
max_update = args.max_update or math.inf
do_save = (
(end_of_epoch and epoch_itr.epoch % args.save_interval == 0)
or num_updates >= max_update
or (
... | def validate_and_save(args, trainer, task, epoch_itr, valid_subsets, end_of_epoch):
| num_updates = trainer.get_num_updates()
max_update = args.max_update or math.inf
do_save = (
(end_of_epoch and epoch_itr.epoch % args.save_interval == 0)
or num_updates >= max_update
or (
args.save_interval_updates > 0
and num_updates > 0
and num_u... | if should_stop:
break
# log end-of-epoch stats
logger.info("end of epoch {} (average epoch stats below)".format(epoch_itr.epoch))
stats = get_training_stats(metrics.get_smoothed_values("train"))
progress.print(stats, tag="train", step=num_updates)
# reset epoch-level meters
metric... | 108 | 108 | 361 | 21 | 86 | ofirpress/shortformer | fairseq_cli/train.py | Python | validate_and_save | validate_and_save | 239 | 283 | 239 | 239 | dd9c1b9ea95078442b461b0fa503bd700512c00c | bigcode/the-stack | train |
b4f50fac3b6ac63f0d8390ff | train | function | @metrics.aggregate("train")
def train(args, trainer, task, epoch_itr):
"""Train the model for one epoch and return validation losses."""
clear_prev_tokens(trainer)
# Initialize data iterator
itr = epoch_itr.next_epoch_itr(
fix_batches_to_gpus=args.fix_batches_to_gpus,
shuffle=(epoch_itr.... | @metrics.aggregate("train")
def train(args, trainer, task, epoch_itr):
| """Train the model for one epoch and return validation losses."""
clear_prev_tokens(trainer)
# Initialize data iterator
itr = epoch_itr.next_epoch_itr(
fix_batches_to_gpus=args.fix_batches_to_gpus,
shuffle=(epoch_itr.next_epoch_idx > args.curriculum),
)
update_freq = (
ar... | _better(a, b):
return a > b if args.maximize_best_checkpoint_metric else a < b
prev_best = getattr(should_stop_early, "best", None)
if prev_best is None or is_better(valid_loss, prev_best):
should_stop_early.best = valid_loss
should_stop_early.num_runs = 0
return False
else:... | 166 | 166 | 554 | 17 | 148 | ofirpress/shortformer | fairseq_cli/train.py | Python | train | train | 171 | 236 | 171 | 172 | fea95d4127b14db8b3a43260547a029ea848f36d | bigcode/the-stack | train |
9a32d045b7269efd83394e32 | train | function | def get_training_stats(stats):
stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
return stats
| def get_training_stats(stats):
| stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
return stats
| 60) > args.stop_time_hours
)
)
# Save checkpoint
if do_save or should_stop:
logger.info("begin save checkpoint")
checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
return valid_losses, should_stop
def get_training_stats(stats):
| 64 | 64 | 32 | 6 | 57 | ofirpress/shortformer | fairseq_cli/train.py | Python | get_training_stats | get_training_stats | 286 | 288 | 286 | 286 | 1ba009264738efe0742768988710698a07753793 | bigcode/the-stack | train |
2ee09e48f3355d1b89852e05 | train | function | def validate(args, trainer, task, epoch_itr, subsets):
"""Evaluate the model on the validation set(s) and return the losses."""
clear_prev_tokens(trainer)
if args.fixed_validation_seed is not None:
# set fixed seed for every validation
utils.set_torch_seed(args.fixed_validation_seed)
v... | def validate(args, trainer, task, epoch_itr, subsets):
| """Evaluate the model on the validation set(s) and return the losses."""
clear_prev_tokens(trainer)
if args.fixed_validation_seed is not None:
# set fixed seed for every validation
utils.set_torch_seed(args.fixed_validation_seed)
valid_losses = []
for subset in subsets:
log... | valid_losses, should_stop
def get_training_stats(stats):
stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
return stats
def clear_prev_tokens(trainer):
# This function clears the cache before/after validation.
for name, module in trainer.get_model().named_modules():
... | 99 | 99 | 331 | 13 | 85 | ofirpress/shortformer | fairseq_cli/train.py | Python | validate | validate | 296 | 335 | 296 | 296 | dfb4e9f48a7a4ee4b09e3e617e6237e6ffee87e4 | bigcode/the-stack | train |
0a5014b739bd8d04e0f745da | train | function | def should_stop_early(args, valid_loss):
# skip check if no validation was done in the current epoch
if valid_loss is None:
return False
if args.patience <= 0:
return False
def is_better(a, b):
return a > b if args.maximize_best_checkpoint_metric else a < b
prev_best = geta... | def should_stop_early(args, valid_loss):
# skip check if no validation was done in the current epoch
| if valid_loss is None:
return False
if args.patience <= 0:
return False
def is_better(a, b):
return a > b if args.maximize_best_checkpoint_metric else a < b
prev_best = getattr(should_stop_early, "best", None)
if prev_best is None or is_better(valid_loss, prev_best):
... | datasets
disable_iterator_cache=task.has_sharded_data("train"),
)
train_meter.stop()
logger.info("done training in {:.1f} seconds".format(train_meter.sum))
def should_stop_early(args, valid_loss):
# skip check if no validation was done in the current epoch
| 64 | 64 | 201 | 24 | 40 | ofirpress/shortformer | fairseq_cli/train.py | Python | should_stop_early | should_stop_early | 143 | 168 | 143 | 144 | 86e7869b522748d464995b29786500039aebb3aa | bigcode/the-stack | train |
9db2d99a48a892c8d5ea7cf6 | train | function | def main(args):
utils.import_user_module(args)
assert (
args.max_tokens is not None or args.max_sentences is not None
), "Must specify batch size either with --max-tokens or --max-sentences"
metrics.reset()
np.random.seed(args.seed)
utils.set_torch_seed(args.seed)
if distributed_... | def main(args):
| utils.import_user_module(args)
assert (
args.max_tokens is not None or args.max_sentences is not None
), "Must specify batch size either with --max-tokens or --max-sentences"
metrics.reset()
np.random.seed(args.seed)
utils.set_torch_seed(args.seed)
if distributed_utils.is_master(... | Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import argparse
import logging
import math
import os
import random
import sys
import numpy as np
i... | 229 | 229 | 766 | 4 | 225 | ofirpress/shortformer | fairseq_cli/train.py | Python | main | main | 42 | 140 | 42 | 42 | 1a093b4ac1b88e677ac34ee1680c9ed04c766e96 | bigcode/the-stack | train |
b4018eba4d6aa1877b61c01c | train | function | def get_valid_stats(args, trainer, stats):
stats["num_updates"] = trainer.get_num_updates()
if hasattr(checkpoint_utils.save_checkpoint, "best"):
key = "best_{0}".format(args.best_checkpoint_metric)
best_function = max if args.maximize_best_checkpoint_metric else min
stats[key] = best_fu... | def get_valid_stats(args, trainer, stats):
| stats["num_updates"] = trainer.get_num_updates()
if hasattr(checkpoint_utils.save_checkpoint, "best"):
key = "best_{0}".format(args.best_checkpoint_metric)
best_function = max if args.maximize_best_checkpoint_metric else min
stats[key] = best_function(
checkpoint_utils.save_c... | # log validation stats
stats = get_valid_stats(args, trainer, agg.get_smoothed_values())
progress.print(stats, tag=subset, step=trainer.get_num_updates())
valid_losses.append(stats[args.best_checkpoint_metric])
return valid_losses
def get_valid_stats(args, trainer, stats):
| 64 | 64 | 91 | 10 | 53 | ofirpress/shortformer | fairseq_cli/train.py | Python | get_valid_stats | get_valid_stats | 338 | 346 | 338 | 338 | f138017fe637d352a911accfa254f60cda015dde | bigcode/the-stack | train |
c4fbbcc5079e9697a634c80d | train | class | class VaeRnn(GranularEncoderDecoderModel):
"""VaeRnn - variational encoder using RNN with Gaussian prior and approximate posterior."""
def __init__(
self,
name: str,
position: int,
data: Dict[str, str],
vocab_size: int,
embedding_size: int,
tokenizer: Tok... | class VaeRnn(GranularEncoderDecoderModel):
| """VaeRnn - variational encoder using RNN with Gaussian prior and approximate posterior."""
def __init__(
self,
name: str,
position: int,
data: Dict[str, str],
vocab_size: int,
embedding_size: int,
tokenizer: Tokenizer,
hidden_size_enc: int = 265,... | and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHO... | 256 | 256 | 2,569 | 12 | 243 | christofid/gt4sd-core | src/gt4sd/frameworks/granular/ml/models/vae_rnn/core.py | Python | VaeRnn | VaeRnn | 40 | 362 | 40 | 40 | 62b5128dc085631e2f55a1f5c0ebe2669e202b12 | bigcode/the-stack | train |
d71a9ba299c3b643772e4c4a | train | class | class PhragmentSnapshotChild(Base):
__tablename__ = 'phragment_snapshotchild'
__table_args__ = (
Index('key_child', 'snapshotPHID', 'fragmentPHID', 'fragmentVersionPHID', unique=True),
)
id = Column(Integer, primary_key=True)
snapshotPHID = Column(String, nullable=False)
fragmentPHID = ... | class PhragmentSnapshotChild(Base):
| __tablename__ = 'phragment_snapshotchild'
__table_args__ = (
Index('key_child', 'snapshotPHID', 'fragmentPHID', 'fragmentVersionPHID', unique=True),
)
id = Column(Integer, primary_key=True)
snapshotPHID = Column(String, nullable=False)
fragmentPHID = Column(String, nullable=False)
f... | = Column(String, nullable=False, unique=True)
primaryFragmentPHID = Column(String, nullable=False)
name = Column(Unicode(128), nullable=False)
dateCreated = Column(dbdatetime, nullable=False)
dateModified = Column(dbdatetime, nullable=False)
class PhragmentSnapshotChild(Base):
| 64 | 64 | 116 | 8 | 56 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | PhragmentSnapshotChild | PhragmentSnapshotChild | 78 | 89 | 78 | 78 | d479210628da33f936eb32cfab76f47560f2f45e | bigcode/the-stack | train |
6e10b7774b5346f3446079f4 | train | class | class Edge(Base):
__tablename__ = 'edge'
__table_args__ = (
Index('key_dst', 'dst', 'type', 'src', unique=True),
Index('src', 'src', 'type', 'dateCreated', 'seq')
)
src = Column(String, primary_key=True, nullable=False)
type = Column(Integer, primary_key=True, nullable=False)
ds... | class Edge(Base):
| __tablename__ = 'edge'
__table_args__ = (
Index('key_dst', 'dst', 'type', 'src', unique=True),
Index('src', 'src', 'type', 'dateCreated', 'seq')
)
src = Column(String, primary_key=True, nullable=False)
type = Column(Integer, primary_key=True, nullable=False)
dst = Column(String,... | Column, Index, Integer, String, VARBINARY
from sqlalchemy import String, Unicode, ForeignKey
from sqlalchemy.orm import relationship, backref
from dbdatetime import dbdatetime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Edge(Base):
| 64 | 64 | 123 | 4 | 59 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | Edge | Edge | 13 | 25 | 13 | 13 | f14927de550be436dfce108ca6417af55ae35622 | bigcode/the-stack | train |
1935d2a66f63010a5e8c878a | train | class | class PhragmentFragment(Base):
__tablename__ = 'phragment_fragment'
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
path = Column(Unicode(128), nullable=False, unique=True)
depth = Column(Integer, nullable=False)
latestVersionPHID = Column(String)
v... | class PhragmentFragment(Base):
| __tablename__ = 'phragment_fragment'
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
path = Column(Unicode(128), nullable=False, unique=True)
depth = Column(Integer, nullable=False)
latestVersionPHID = Column(String)
viewPolicy = Column(String, null... | (dbdatetime, nullable=False)
seq = Column(Integer, nullable=False)
dataID = Column(Integer)
class EdgeData(Base):
__tablename__ = 'edgedata'
id = Column(Integer, primary_key=True)
data = Column(Unicode, nullable=False)
class PhragmentFragment(Base):
| 64 | 64 | 115 | 7 | 57 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | PhragmentFragment | PhragmentFragment | 35 | 46 | 35 | 35 | abcc28fa913161bc151f8ec06be477a57538cd13 | bigcode/the-stack | train |
66d0508c1067dace7b5609fc | train | class | class PhragmentFragmentVersion(Base):
__tablename__ = 'phragment_fragmentversion'
__table_args__ = (
Index('key_version', 'fragmentPHID', 'sequence', unique=True),
)
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
sequence = Column(Integer, null... | class PhragmentFragmentVersion(Base):
| __tablename__ = 'phragment_fragmentversion'
__table_args__ = (
Index('key_version', 'fragmentPHID', 'sequence', unique=True),
)
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
sequence = Column(Integer, nullable=False)
fragmentPHID = Column(... | (Integer, nullable=False)
latestVersionPHID = Column(String)
viewPolicy = Column(String, nullable=False)
editPolicy = Column(String, nullable=False)
dateCreated = Column(dbdatetime, nullable=False)
dateModified = Column(dbdatetime, nullable=False)
class PhragmentFragmentVersion(Base):
| 64 | 64 | 118 | 8 | 56 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | PhragmentFragmentVersion | PhragmentFragmentVersion | 49 | 61 | 49 | 49 | b96a17d61e893c04f3e974564e4cbfc7ae90c8cf | bigcode/the-stack | train |
a4fd4b9b3a8b74e6180f0518 | train | class | class PhragmentSnapshot(Base):
__tablename__ = 'phragment_snapshot'
__table_args__ = (
Index('key_name', 'primaryFragmentPHID', 'name', unique=True),
)
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
primaryFragmentPHID = Column(String, nullable... | class PhragmentSnapshot(Base):
| __tablename__ = 'phragment_snapshot'
__table_args__ = (
Index('key_name', 'primaryFragmentPHID', 'name', unique=True),
)
id = Column(Integer, primary_key=True)
phid = Column(String, nullable=False, unique=True)
primaryFragmentPHID = Column(String, nullable=False)
name = Column(Unico... | , nullable=False, unique=True)
sequence = Column(Integer, nullable=False)
fragmentPHID = Column(String, nullable=False)
filePHID = Column(String)
dateCreated = Column(dbdatetime, nullable=False)
dateModified = Column(dbdatetime, nullable=False)
class PhragmentSnapshot(Base):
| 64 | 64 | 113 | 7 | 57 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | PhragmentSnapshot | PhragmentSnapshot | 64 | 75 | 64 | 64 | 774c7b0c0e08f1f5cd6405d8f4c4d00a242e05f8 | bigcode/the-stack | train |
d99be46aa95b9e6a0882424c | train | class | class EdgeData(Base):
__tablename__ = 'edgedata'
id = Column(Integer, primary_key=True)
data = Column(Unicode, nullable=False)
| class EdgeData(Base):
| __tablename__ = 'edgedata'
id = Column(Integer, primary_key=True)
data = Column(Unicode, nullable=False)
| _key=True, nullable=False)
type = Column(Integer, primary_key=True, nullable=False)
dst = Column(String, primary_key=True, nullable=False)
dateCreated = Column(dbdatetime, nullable=False)
seq = Column(Integer, nullable=False)
dataID = Column(Integer)
class EdgeData(Base):
| 64 | 64 | 35 | 5 | 59 | veblush/PyPhabricatorDb | pyphabricatordb/phragment.py | Python | EdgeData | EdgeData | 28 | 32 | 28 | 28 | f985570538dca9ccece3b75b5dae928bc2c87a09 | bigcode/the-stack | train |
1be00649d5f0aba7b75e3a0c | train | class | class Send(BaseService):
"""Service to send the command/string with "\\r" to spawned channel.
If target is passed as standby, command will be sent to standby spawn.
Arguments:
command: Command to be sent.
target: Target connection, Defaults to active.
Returns:
True: on Success... | class Send(BaseService):
| """Service to send the command/string with "\\r" to spawned channel.
If target is passed as standby, command will be sent to standby spawn.
Arguments:
command: Command to be sent.
target: Target connection, Defaults to active.
Returns:
True: on Success
Raises:
Sub... | invalid_state_change_action(spawn, err_state, sm):
msg = "Expected device to reach '{}' state, but landed on '{}' state."\
.format(sm.current_state, err_state.name)
# Update device current state with unexpected state.
sm.update_cur_state(err_state)
raise StateMachineError(msg)
class Send(Base... | 71 | 71 | 238 | 5 | 66 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Send | Send | 55 | 97 | 55 | 55 | 727649ceede562397c361aa01ef4b694479e1435 | bigcode/the-stack | train |
c5fb903c8b1a6b622195653a | train | class | class ExpectLogging(BaseService):
r""" Service to enable expect internal logging.
Arguments:
enable: True/False for enabling and disabling the expect_log
Example:
.. code::
rtr.expect_log(enable=True)
"""
def log_service_call(self):
pass
def pre_service(... | class ExpectLogging(BaseService):
| r""" Service to enable expect internal logging.
Arguments:
enable: True/False for enabling and disabling the expect_log
Example:
.. code::
rtr.expect_log(enable=True)
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pa... | (logging.Formatter(fmt='[%(asctime)s] %(message)s'))
conn.log.addHandler(fh)
self.result = True
else:
if file_handler:
self.result = file_handler.baseFilename
def get_service_result(self):
return self.result
class ExpectLogging(BaseService):
| 64 | 64 | 177 | 6 | 57 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | ExpectLogging | ExpectLogging | 406 | 442 | 406 | 406 | c77db3315edbe4c368fafac7c12e65f4e5861950 | bigcode/the-stack | train |
4bd80d02ab25aabd06a62c93 | train | class | class HaConfigure(HaConfigureService):
def call_service(self, *args, **kwargs):
self.connection.log.warning('**** This service is deprecated. ' +
'Please use "configure" service ****')
super().call_service(*args, **kwargs)
| class HaConfigure(HaConfigureService):
| def call_service(self, *args, **kwargs):
self.connection.log.warning('**** This service is deprecated. ' +
'Please use "configure" service ****')
super().call_service(*args, **kwargs)
| = rtr.configure('no logging console')
cmd =['hostname si-tvt-7200-28-41', 'no logging console']
output = rtr.configure(cmd)
output = rtr.configure(cmd, target='standby')
"""
pass
class HaConfigure(HaConfigureService):
| 64 | 64 | 55 | 8 | 55 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | HaConfigure | HaConfigure | 1,776 | 1,781 | 1,776 | 1,777 | 4b28e6f36c5bdf8de5224f01f3849e93baf75128 | bigcode/the-stack | train |
49a728b4ba8875d15d3e086a | train | class | class ReceiveService(BaseService):
"""match a pattern from spawn buffer
Arguments:
pattern: regular expression pattern to match. If r'nopattern^' is used then
no pattern is match and all data till timeout period will be matched.
timeout: time to wait for the pattern to match.
... | class ReceiveService(BaseService):
| """match a pattern from spawn buffer
Arguments:
pattern: regular expression pattern to match. If r'nopattern^' is used then
no pattern is match and all data till timeout period will be matched.
timeout: time to wait for the pattern to match.
size: read size in bytes for... | def log_service_call(self):
pass
def pre_service(self, *args, **kwargs):
pass
def post_service(self, *args, **kwargs):
pass
def call_service(self, patterns, timeout=None,
size=None, trim_buffer=True,
target=None, *args, **kwargs):
... | 142 | 142 | 475 | 6 | 135 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | ReceiveService | ReceiveService | 199 | 256 | 199 | 199 | 659b3e985f0d1727577e03376fb712969e857279 | bigcode/the-stack | train |
0a440db522a4e799d4cdd5f4 | train | class | class Disable(BaseService):
"""Service to change the device to disable mode from any state.
Brings the standby handle to disable state, if standby is passed as
input.
Arguments:
target: Target connection, Defaults to active
Returns:
True on Success, raise SubCommandFailure on fail... | class Disable(BaseService):
| """Service to change the device to disable mode from any state.
Brings the standby handle to disable state, if standby is passed as
input.
Arguments:
target: Target connection, Defaults to active
Returns:
True on Success, raise SubCommandFailure on failure
Example:
..... | sm.paths[sm.paths.index(pt)].command = command
try:
sm.go_to(self.start_state,
spawn,
context=handle.context)
except Exception as err:
raise SubCommandFailure("Failed to Bring device to Enable State",
... | 69 | 69 | 233 | 5 | 63 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Disable | Disable | 491 | 527 | 491 | 491 | 5ed834d13700d2e8c057d1e08d1541e1ae82a0a0 | bigcode/the-stack | train |
8ceeb53b4f3a357d5adc306a | train | class | class Traceroute(BaseService):
""" Service to issue traceroute response request to another network from device.
Returns:
traceroute command response on Success
Raises:
SubCommandFailure on failure
Example:
.. code-block:: python
traceroute(addr="9.33.11.41")
"... | class Traceroute(BaseService):
| """ Service to issue traceroute response request to another network from device.
Returns:
traceroute command response on Success
Raises:
SubCommandFailure on failure
Example:
.. code-block:: python
traceroute(addr="9.33.11.41")
"""
def __init__(self, conn... | con.spawn.sendline(reload_command)
try:
reload_output = dialog.process(con.spawn,
timeout=timeout,
prompt_recovery=self.prompt_recovery,
context=context)
... | 187 | 187 | 626 | 7 | 180 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Traceroute | Traceroute | 1,077 | 1,158 | 1,077 | 1,077 | f35d8587a15240a70ec2e8dbb13a416cab5bf314 | bigcode/the-stack | train |
b0bec1fa02fdc6a19743837f | train | class | class Config(Configure):
def call_service(self, *args, **kwargs):
self.connection.log.warning('**** This service is deprecated. Please use "configure" service ****')
super().call_service(*args, **kwargs)
| class Config(Configure):
| def call_service(self, *args, **kwargs):
self.connection.log.warning('**** This service is deprecated. Please use "configure" service ****')
super().call_service(*args, **kwargs)
| context=self.context)
raise
def update_hostname_if_needed(self, cmd_list):
for cmd in cmd_list:
m = re.match(r'^\s*hostname (\S+)', cmd)
if m:
self.connection.hostname = m.group(1)
return
class Config(Configure):
| 64 | 64 | 48 | 5 | 58 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Config | Config | 966 | 970 | 966 | 967 | 0f7fceecc2be18f486aa0d5444da7760312554b2 | bigcode/the-stack | train |
1f5f262548ec4d95ea144d16 | train | class | class Execute(BaseService):
""" Execute Service implementation
Service to executes exec_commands on the device and return the
console output. reply option can be passed for the interactive exec
command.
By default, device start state should be same as end state. If device
ends in some other st... | class Execute(BaseService):
| """ Execute Service implementation
Service to executes exec_commands on the device and return the
console output. reply option can be passed for the interactive exec
command.
By default, device start state should be same as end state. If device
ends in some other state, StateMachineError excep... | Bring device to Enable State",
err) from err
self.result = True
class Disable(BaseService):
"""Service to change the device to disable mode from any state.
Brings the standby handle to disable state, if standby is passed as
input.
Arguments:
targe... | 256 | 256 | 1,691 | 5 | 250 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Execute | Execute | 530 | 750 | 530 | 530 | d8a629ed665af20c43bdfda47c19aab6480ccb65 | bigcode/the-stack | train |
4cd31dfa6eddeb3717226455 | train | class | class AttachModuleService(BaseService):
""" Service to connect to a device module and execute commands.
Arguments:
None
Returns:
AttributeError: No attributes
Examples:
.. code-block:: python
rtr.attach(1, timeout=60).execute('show interface')
with rt... | class AttachModuleService(BaseService):
| """ Service to connect to a device module and execute commands.
Arguments:
None
Returns:
AttributeError: No attributes
Examples:
.. code-block:: python
rtr.attach(1, timeout=60).execute('show interface')
with rtr.attach(1) as m:
m.exec... | enable_bash=False, timeout=None):
self.conn = connection
# Specific platforms has its own prompt
self.enable_bash = enable_bash
self.timeout = timeout or connection.settings.CONSOLE_TIMEOUT
def __enter__(self):
raise NotImplementedError('No enter she... | 194 | 194 | 647 | 7 | 187 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | AttachModuleService | AttachModuleService | 2,373 | 2,472 | 2,373 | 2,373 | fd82978c672acd6d1cb3234ea4ac0d25d1f3cb57 | bigcode/the-stack | train |
8781ce07df2e5cdc802ad6a8 | train | class | class Copy(BaseService):
""" Implements Copy service
Service to support variants of the IOS copy command, which basically
copies images and configs into and out of router Flash memory.
Arguments:
timeout: Timeout value in sec, Default Value is 60 sec
Returns:
True on Success, rais... | class Copy(BaseService):
| """ Implements Copy service
Service to support variants of the IOS copy command, which basically
copies images and configs into and out of router Flash memory.
Arguments:
timeout: Timeout value in sec, Default Value is 60 sec
Returns:
True on Success, raise SubCommandFailure on fa... | "
"then src route addr is mandatory \n")
elif ping_context['src_route_addr'] != "":
raise SubCommandFailure("If src route addr is set, "
"then src route type is mandatory \n")
# Stringify the command in case it is a... | 255 | 256 | 1,511 | 5 | 250 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Copy | Copy | 1,289 | 1,490 | 1,289 | 1,289 | 728739e6901d1e5077c96cb875a1686cfe34f576 | bigcode/the-stack | train |
1c4ee0db8fc859013cf1ebe0 | train | class | class SyncState(BaseService):
"""Bring the device to stable state and re-designate the handles role.
Returns:
True on Success, raises SubcommandFailure exception on failure
Example:
.. code-block:: python
rtr.sync_state()
"""
def __init__(self, connection, context, **... | class SyncState(BaseService):
| """Bring the device to stable state and re-designate the handles role.
Returns:
True on Success, raises SubcommandFailure exception on failure
Example:
.. code-block:: python
rtr.sync_state()
"""
def __init__(self, connection, context, **kwargs):
super().__ini... | _service(self,
target='active',
timeout=None,
*args,
**kwargs):
try:
self.result = self.connection.execute("show running-config",
target=target,
... | 72 | 72 | 243 | 6 | 65 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | SyncState | SyncState | 1,629 | 1,666 | 1,629 | 1,629 | 563c3b2f6b510e76c4a3942b36bec6fc2f8a13a9 | bigcode/the-stack | train |
87aa104963982083c4282e37 | train | class | class ResetStandbyRP(BaseService):
""" Service to reset the standby rp.
Arguments:
command: command to reset standby, default is"redundancy reload peer"
reply: Dialog which include list of Statements for
additional dialogs prompted by standby reset command,
in... | class ResetStandbyRP(BaseService):
| """ Service to reset the standby rp.
Arguments:
command: command to reset standby, default is"redundancy reload peer"
reply: Dialog which include list of Statements for
additional dialogs prompted by standby reset command,
in-case it is not in the current list... | .settings.HA_INIT_CONFIG_COMMANDS
config_retry = 0
while config_retry < 20:
try:
con.configure(config_commands,
prompt_recovery=self.prompt_recovery)
except Exception as err:
if re.search("C... | 256 | 256 | 939 | 8 | 247 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | ResetStandbyRP | ResetStandbyRP | 2,155 | 2,281 | 2,155 | 2,155 | 0dc1b72b85f997eb13869a0af20c8bde6f64f987 | bigcode/the-stack | train |
1535a942544372ed8aeb3243 | train | class | class LogFile(BaseService):
""" Service to get or change Device FileHandler file.
If no argument passed then it return current filename of FileHandler.
Return True, if file handlers updated with new filename.
Arguments:
filename: file name in which device logs to dump.
Example:
... | class LogFile(BaseService):
| """ Service to get or change Device FileHandler file.
If no argument passed then it return current filename of FileHandler.
Return True, if file handlers updated with new filename.
Arguments:
filename: file name in which device logs to dump.
Example:
.. code-block:: python
... | conn.log.addHandler(logs.UniconScreenHandler())
else:
conn.log.info("+++ log_user: disable +++")
for hdlr in conn.log.handlers:
if type(hdlr) in (logs.UniconStreamHandler,
logs.UniconScreenHandler):
... | 93 | 93 | 313 | 6 | 86 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | LogFile | LogFile | 356 | 403 | 356 | 356 | 280fe4b0c6348d3dff32cf536963bf09d79bda0d | bigcode/the-stack | train |
7efab7180837cf222c6b5191 | train | function | def invalid_state_change_action(spawn, err_state, sm):
msg = "Expected device to reach '{}' state, but landed on '{}' state."\
.format(sm.current_state, err_state.name)
# Update device current state with unexpected state.
sm.update_cur_state(err_state)
raise StateMachineError(msg)
| def invalid_state_change_action(spawn, err_state, sm):
| msg = "Expected device to reach '{}' state, but landed on '{}' state."\
.format(sm.current_state, err_state.name)
# Update device current state with unexpected state.
sm.update_cur_state(err_state)
raise StateMachineError(msg)
| unicon import logs
from unicon.plugins.generic.utils import GenericUtils
from .service_statements import execution_statement_list, configure_statement_list
utils = GenericUtils()
ReloadResult = collections.namedtuple('ReloadResult', ['result', 'output'])
def invalid_state_change_action(spawn, err_state, sm):
| 63 | 64 | 67 | 13 | 50 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | invalid_state_change_action | invalid_state_change_action | 47 | 52 | 47 | 47 | 1810902be7ac12aa7b8fd8e9113ae0dc20cfed39 | bigcode/the-stack | train |
531448e8ee922e0487d026c9 | train | class | class LogUser(BaseService):
""" Service to enable or disable a device logs on screen.
Arguments:
enable: True/False
Example:
.. code-block:: python
rtr.log_user(enable=True)
rtr.log_user(enable=False)
"""
def log_service_call(self):
pass
def p... | class LogUser(BaseService):
| """ Service to enable or disable a device logs on screen.
Arguments:
enable: True/False
Example:
.. code-block:: python
rtr.log_user(enable=True)
rtr.log_user(enable=False)
"""
def log_service_call(self):
pass
def pre_service(self, *args, **kw... | def call_service(self):
try:
self.result = self.connection.receiveBuffer
except AttributeError as err:
raise SubCommandFailure("receive_buffer should be invoked after receive call", err)
except Exception as err:
raise SubCommandFailure("Error in receive_bu... | 99 | 99 | 331 | 6 | 92 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | LogUser | LogUser | 299 | 353 | 299 | 299 | 040dfa416b14fcda4d39d12b7659e84d4bf91782 | bigcode/the-stack | train |
d2c888c3421cc19f64a11f4c | train | class | class Ping(BaseService):
""" Service to issue ping response request to another network from device.
Returns:
ping command response on Success
Raises:
SubCommandFailure on failure
Example:
.. code-block:: python
ping(addr="9.33.11.41")
ping(addr="10.2.1... | class Ping(BaseService):
| """ Service to issue ping response request to another network from device.
Returns:
ping command response on Success
Raises:
SubCommandFailure on failure
Example:
.. code-block:: python
ping(addr="9.33.11.41")
ping(addr="10.2.1.1", extd_ping='y')
... | con.log.warning("Unsupported traceroute option {}, ignoring".format(key))
# Validate Inputs
if addr:
# Do string conversion on addr, if specified,
# in case the user passes in an ipaddress object instead of a
# string.
trace_route_context['addr'] = str(a... | 255 | 256 | 1,100 | 5 | 250 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Ping | Ping | 1,161 | 1,286 | 1,161 | 1,161 | 2908ad8837ae4feb5a85d826d2d0c49d0ed282b1 | bigcode/the-stack | train |
8ad2f6eeee4d986c00d21c82 | train | class | class HAReloadService(BaseService):
""" Service to reload the device.
Arguments:
reload_command: reload command to be used. default "redundancy reload shelf"
reload_creds: credential or list of credentials to use to respond to
username/password prompts.
reply: Addi... | class HAReloadService(BaseService):
| """ Service to reload the device.
Arguments:
reload_command: reload command to be used. default "redundancy reload shelf"
reload_creds: credential or list of credentials to use to respond to
username/password prompts.
reply: Additional Dialog( i.e patterns) to be h... | commands : list/single config command
reply: Addition Dialogs for interactive config commands.
timeout : Timeout value in sec, Default Value is 30 sec
target: Target RP where to execute service
lock_retries: retry times if config mode is locked, default is 0
lock_retry_sl... | 256 | 256 | 1,469 | 7 | 248 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | HAReloadService | HAReloadService | 1,785 | 1,965 | 1,785 | 1,785 | 69c4b61beca237168158a13db52cdb8a62222f8f | bigcode/the-stack | train |
1feb3a3a5aafdeae543e8992 | train | class | class Switchto(BaseService):
""" Switch to a certain CLI state that is known to the statemachine
"""
def __init__(self, connection, context, **kwargs):
# Connection object will have all the received details
super().__init__(connection, context, **kwargs)
self.service_name = 'switcht... | class Switchto(BaseService):
| """ Switch to a certain CLI state that is known to the statemachine
"""
def __init__(self, connection, context, **kwargs):
# Connection object will have all the received details
super().__init__(connection, context, **kwargs)
self.service_name = 'switchto'
self.timeout = con... | elif self.target == 'active':
conn = self.conn.active
else:
conn = self.conn
sm = conn.state_machine
sm.go_to('enable', conn.spawn)
# do not suppress
return False
def __getattr__(self, attr):
... | 116 | 116 | 389 | 6 | 110 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Switchto | Switchto | 2,475 | 2,532 | 2,475 | 2,475 | 102f200702cef3f5b21312b4211995e8b082de24 | bigcode/the-stack | train |
bbbe1dd99487b9245c248b47 | train | class | class Enable(BaseService):
""" Brings device to enable
Service to change the device mode to enable from any state.
Brings the standby handle to enable state, if standby is passed as input.
Arguments:
target= Target connection, Defaults to active
Returns:
True on Success, raise Sub... | class Enable(BaseService):
| """ Brings device to enable
Service to change the device mode to enable from any state.
Brings the standby handle to enable state, if standby is passed as input.
Arguments:
target= Target connection, Defaults to active
Returns:
True on Success, raise SubCommandFailure on failure
... | def call_service(self, enable=False,
*args, **kwargs):
con = self.connection
if enable:
con.log.info("+++ enable debug logging +++")
con.log.setLevel(logging.DEBUG)
else:
con.log.info("+++ disable debug logging +++")
con.l... | 92 | 92 | 309 | 5 | 86 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Enable | Enable | 445 | 488 | 445 | 445 | 71720014e4e380e465cc659e00bddabe5cfe8693 | bigcode/the-stack | train |
da57987772d50f6482621eae | train | class | class BashService(BaseService):
""" Service to provide an console to do shell commands
Arguments:
None
Returns:
AttributeError: No attributes
Example:
.. code-block:: python
rtr.bash_console(timeout=60).execute('ls')
"""
def __init__(self, *args, **kwargs... | class BashService(BaseService):
| """ Service to provide an console to do shell commands
Arguments:
None
Returns:
AttributeError: No attributes
Example:
.. code-block:: python
rtr.bash_console(timeout=60).execute('ls')
"""
def __init__(self, *args, **kwargs):
super().__init__(*arg... | _state):
sleep(2)
counter += 1
continue
else:
reloadGood = True
counter = 0
if re.search('STANDBY HOT', rp_state):
counter = reset_counter + 1
... | 177 | 177 | 591 | 6 | 170 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | BashService | BashService | 2,284 | 2,370 | 2,284 | 2,284 | 4300ad0522fdd13408c4c1e85a11a11b6606889a | bigcode/the-stack | train |
8d8f6122e31f30b3c0836482 | train | class | class GetRPState(BaseService):
""" Get Rp state
Service to get the redundancy state of the device rp.
Returns standby rp state if standby is passed as input.
Arguments:
target: Service target, by default active
Returns:
Expected return values are ACTIVE, STANDBY COLD, STANDBY HOT... | class GetRPState(BaseService):
| """ Get Rp state
Service to get the redundancy state of the device rp.
Returns standby rp state if standby is passed as input.
Arguments:
target: Service target, by default active
Returns:
Expected return values are ACTIVE, STANDBY COLD, STANDBY HOT
raise SubCommandFailur... | utils,
*args,
**kwargs):
timeout = timeout or self.timeout
try:
self.result = utils.get_redundancy_details(self.connection,
timeout=timeout)
except Exception as err:
raise Su... | 98 | 98 | 329 | 7 | 91 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | GetRPState | GetRPState | 1,532 | 1,581 | 1,532 | 1,532 | fc7150f0dbee2f9c77d1aee1798b35336f24c6a6 | bigcode/the-stack | train |
71da5ee23376b6f6ae17a67b | train | class | class GetConfig(BaseService):
"""Service return running configuration of the device.
Returns:
standby running configuration if standby is passed as input.
Arguments:
target: Service target, by default active
Returns:
running configuration on Success, raise SubCommandFailure on f... | class GetConfig(BaseService):
| """Service return running configuration of the device.
Returns:
standby running configuration if standby is passed as input.
Arguments:
target: Service target, by default active
Returns:
running configuration on Success, raise SubCommandFailure on failure.
Example:
... | ancy_details(self.connection, timeout=timeout, who=red_handle)
except Exception as err:
raise SubCommandFailure("get_rp_state failed", err) from err
def get_service_result(self):
if 'state' in self.result:
return self.result.state
else:
return "None"
clas... | 73 | 73 | 246 | 6 | 67 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | GetConfig | GetConfig | 1,584 | 1,626 | 1,584 | 1,584 | 972fcf3494516c1e1a934d1567b5765953a0ec35 | bigcode/the-stack | train |
a62ec8864f1666b82b7cd226 | train | class | class ReceiveBufferService(BaseService):
"""Returns data match by receive() service pattern.
Returns:
String: Data matched by receive() service pattern.
Raises:
SubCommandFailure: If this is called without calling receive() service.
Example:
.. code-block:: python
... | class ReceiveBufferService(BaseService):
| """Returns data match by receive() service pattern.
Returns:
String: Data matched by receive() service pattern.
Raises:
SubCommandFailure: If this is called without calling receive() service.
Example:
.. code-block:: python
rtr.sendline("a command")
rt... | Buffer = spawn.expect(pattern, timeout, size, *args, **kwargs).match_output
self.result = True
except TimeoutError:
pass
except Exception as err:
raise SubCommandFailure("Receive service failed", err) from err
def get_service_result(self):
return self... | 73 | 73 | 246 | 7 | 65 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | ReceiveBufferService | ReceiveBufferService | 259 | 296 | 259 | 259 | 848993e06490aa6ba0accc2573e572ca7e9e5b4a | bigcode/the-stack | train |
689122a7a7b50fda3875d81e | train | class | class HaConfigureService(Configure):
"""DualRp configure service
Service to configure device with single or list of `commands`.
Config without config_command will take device to config mode.
Commands Should be list, if `config_command` are more than one.
reply option can be passed for the interacti... | class HaConfigureService(Configure):
| """DualRp configure service
Service to configure device with single or list of `commands`.
Config without config_command will take device to config mode.
Commands Should be list, if `config_command` are more than one.
reply option can be passed for the interactive config command.
Command can be... | = self.get_handle(target)
self.result = handle.execute(command,
reply=reply,
timeout=timeout,
error_pattern=error_pattern,
search_size=search_size,
... | 80 | 80 | 269 | 7 | 73 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | HaConfigureService | HaConfigureService | 1,743 | 1,773 | 1,743 | 1,743 | 2e8336921c45d54784b9e8473034dce0660b8635 | bigcode/the-stack | train |
36dfa78e8f7cd78d079b65b9 | train | class | class SwitchoverService(BaseService):
""" Service to switchover the device.
Arguments:
command: command to do switchover. default
"redundancy force-switchover"
switchover_creds: credential or list of credentials to use to respond to
username/password promp... | class SwitchoverService(BaseService):
| """ Service to switchover the device.
Arguments:
command: command to do switchover. default
"redundancy force-switchover"
switchover_creds: credential or list of credentials to use to respond to
username/password prompts.
dialog: Dialog which inclu... | con.settings.CONFIG_LOCK_RETRIES = config_lock_retries_ori
con.settings.CONFIG_LOCK_RETRY_SLEEP = config_lock_retry_sleep_ori
# best effort for 'STANDBY HOT', consider argument for mandatory/ignore
while counter < 31:
try:
# TODO need fix iosxr get_rp_state serv... | 256 | 256 | 1,417 | 9 | 247 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | SwitchoverService | SwitchoverService | 1,968 | 2,152 | 1,968 | 1,968 | f430025a52b24e1c6fc9110e622b59b56b3e230b | bigcode/the-stack | train |
e1b317cdab80c9012295d069 | train | class | class HaExecService(BaseService):
""" DualRp execute service
Service to executes exec_commands on the device and return the
console output. reply option can be passed for the interactive exec
command. Command will be executed on standby if target is specified
as standby.
Arguments:
co... | class HaExecService(BaseService):
| """ DualRp execute service
Service to executes exec_commands on the device and return the
console output. reply option can be passed for the interactive exec
command. Command will be executed on standby if target is specified
as standby.
Arguments:
command: exec command
target... | self.timeout = connection.settings.EXEC_TIMEOUT
self.__dict__.update(kwargs)
def pre_service(self, *args, **kwargs):
self.prompt_recovery = kwargs.get('prompt_recovery', False)
def call_service(self,
target='active',
timeout=None,
... | 151 | 151 | 505 | 7 | 143 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | HaExecService | HaExecService | 1,669 | 1,740 | 1,669 | 1,669 | 6c91f73ae85322042e404bb1def4b10ef7601eec | bigcode/the-stack | train |
36c0737db6a2bd4a5fefe11e | train | class | class Sendline(BaseService):
""" Sendline Service
Service to send the command/string to spawned channel,
"\\r" will be appended to command by sendline. If target
is passed as standby, command will be sent to standby
spawn.
Arguments:
command: Command to be sent
target: Target ... | class Sendline(BaseService):
| """ Sendline Service
Service to send the command/string to spawned channel,
"\\r" will be appended to command by sendline. If target
is passed as standby, command will be sent to standby
spawn.
Arguments:
command: Command to be sent
target: Target connection, Defaults to activ... | args, **kwargs):
spawn = self.get_spawn(target)
try:
spawn.send(command, *args, **kwargs)
except Exception as err:
raise SubCommandFailure("Failed to send the command to spawn",
err) from err
self.result = True
def get_serv... | 77 | 77 | 259 | 6 | 70 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Sendline | Sendline | 100 | 144 | 100 | 100 | 25f4894ff067836027af1d800fc11c8038a41d44 | bigcode/the-stack | train |
3c92ff398ba90ba113a722c1 | train | class | class Expect(BaseService):
"""match a list of pattern again the buffer
Arguments:
patterns: list of patterns.
timeout: time to wait for any of the patterns to match.
size: read size in bytes for reading the buffer.
trim_buffer: whether to trim the buffer after a successful match... | class Expect(BaseService):
| """match a list of pattern again the buffer
Arguments:
patterns: list of patterns.
timeout: time to wait for any of the patterns to match.
size: read size in bytes for reading the buffer.
trim_buffer: whether to trim the buffer after a successful match.
target: ``standby... | post_service(self, *args, **kwargs):
pass
def call_service(self, command='', target=None, *args, **kwargs):
spawn = self.get_spawn(target)
try:
spawn.sendline(command, *args, **kwargs)
except Exception as err:
raise SubCommandFailure("Failed to send the comm... | 102 | 102 | 343 | 5 | 96 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Expect | Expect | 147 | 196 | 147 | 147 | b43ea4718c36cb4cab79b53bb6d97fd3a8e7c2d5 | bigcode/the-stack | train |
d3d4a35d98516124b2a6441a | train | class | class GetMode(BaseService):
""" Service to get the redundancy mode of the device.
Returns:
'sso', 'rpr' or raise SubCommandFailure on failure.
Example ::
.. code-block:: python
rtr.get_mode()
"""
def __init__(self, connection, context, **kwargs):
super().__ini... | class GetMode(BaseService):
| """ Service to get the redundancy mode of the device.
Returns:
'sso', 'rpr' or raise SubCommandFailure on failure.
Example ::
.. code-block:: python
rtr.get_mode()
"""
def __init__(self, connection, context, **kwargs):
super().__init__(connection, context, **k... | Exception:
pass
raise SubCommandFailure("Copy failed", err) from err
else:
break
self.result = self.result.match_output
if self.result.rfind(self.connection.hostname):
self.result = self.result[:self.result.rfind(self.connecti... | 65 | 66 | 220 | 6 | 59 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | GetMode | GetMode | 1,493 | 1,529 | 1,493 | 1,493 | 3692a9132902f8301cd32eaf9f44a115843e0e8a | bigcode/the-stack | train |
9f6cdefc9e2b3d8eb5395a63 | train | class | class Configure(BaseService):
"""Service to configure device with single or list of `commands`.
Config without config_command will take device to config mode.
Commands Should be list, if `config_command` are more than one.
reply option can be passed for the interactive config command.
Arguments:
... | class Configure(BaseService):
| """Service to configure device with single or list of `commands`.
Config without config_command will take device to config mode.
Commands Should be list, if `config_command` are more than one.
reply option can be passed for the interactive config command.
Arguments:
commands : list/single ... | (r"^\r?\r\n", "", output, 1)
output = output.rstrip()
if command in command_output:
if isinstance(command_output[command], list):
command_output[command].append(output)
else:
command_output[command] ... | 256 | 256 | 1,598 | 5 | 251 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Configure | Configure | 753 | 963 | 753 | 753 | 9603e372ad1dc0023cd58ad111eb55d426f4e596 | bigcode/the-stack | train |
f2136e1ee0ea1b55cfac7881 | train | class | class Reload(BaseService):
"""Service to reload the device.
Arguments:
reload_command: reload command to be issued. default is "reload"
reload_creds: credential or list of credentials to use to respond to
username/password prompts.
dialog: Dialog which include list... | class Reload(BaseService):
| """Service to reload the device.
Arguments:
reload_command: reload command to be issued. default is "reload"
reload_creds: credential or list of credentials to use to respond to
username/password prompts.
dialog: Dialog which include list of Statements for
... | :
raise SubCommandFailure('Configuration failed', err) \
from err
cmd_result = self.utils.truncate_trailing_prompt(
handle.state_machine.get_state(handle.state_machine.current_state),
cmd_result.match_output,
hostname=handle.hostname,
... | 219 | 219 | 731 | 5 | 214 | leoanez/unicon.plugins | src/unicon/plugins/generic/service_implementation.py | Python | Reload | Reload | 973 | 1,074 | 973 | 973 | a921a810a07d22ca8909ffd4b0094ac308e1c2fc | bigcode/the-stack | train |
7aab02231c069984e114bd57 | train | function | def test_sum_up():
x = 1
y = 2
assert sum_up(x,y) == 3
| def test_sum_up():
| x = 1
y = 2
assert sum_up(x,y) == 3
| from src.sum_up import *
def test_sum_up():
| 11 | 64 | 28 | 5 | 6 | marco-a-wagner/nirvana | test/test_sum_up.py | Python | test_sum_up | test_sum_up | 3 | 6 | 3 | 3 | 23adb16ce75b256e4667f053ad7de7c07a9306eb | bigcode/the-stack | train |
170cd305ccdcd9de3ef8c832 | train | function | def test_sum_up3():
assert sum_up3(1,2,3) == 6 | def test_sum_up3():
| assert sum_up3(1,2,3) == 6 | from src.sum_up import *
def test_sum_up():
x = 1
y = 2
assert sum_up(x,y) == 3
def test_sum_up3():
| 40 | 64 | 21 | 6 | 33 | marco-a-wagner/nirvana | test/test_sum_up.py | Python | test_sum_up3 | test_sum_up3 | 8 | 9 | 8 | 8 | 00408ba24a399236e8e75dcefbfadf6cfb14e5d6 | bigcode/the-stack | train |
b4c45ed9f6be52c474e7222e | train | function | def main():
in_dtype = 'float32'
input_shape = (1, 2, 3, 4, 5)
pad = [1, 2, 1, 1, 3, 4]
mode = 'constant'
data_format = 'NCDHW'
value = 100
input_data = np.random.rand(*input_shape).astype(np.float32)
pad3d("pad3d_test1", input_data, in_dtype, pad, data_format, mode, value)
input_s... | def main():
| in_dtype = 'float32'
input_shape = (1, 2, 3, 4, 5)
pad = [1, 2, 1, 1, 3, 4]
mode = 'constant'
data_format = 'NCDHW'
value = 100
input_data = np.random.rand(*input_shape).astype(np.float32)
pad3d("pad3d_test1", input_data, in_dtype, pad, data_format, mode, value)
input_shape = (2, 3... | data_format=data_format)
out = pad_other_mode(node_x)
cpu = paddle.static.cpu_places(1)
exe = paddle.static.Executor(cpu[0])
# startup program will call initializer to initialize the parameters.
exe.run(paddle.static.default_startup_program())
outs = exe.run(
... | 119 | 119 | 399 | 3 | 116 | ryanloney/openvino-1 | src/core/tests/frontend/paddle/test_models/gen_scripts/generate_pad3d.py | Python | main | main | 38 | 68 | 38 | 38 | b5b6502d215c5bf635586ca53dd3fb9613fb4a1c | bigcode/the-stack | train |
7e819b77c42d78a8d1809b5f | train | function | def pad3d(name : str, x, in_dtype, pad, data_format, mode, value = 0):
import paddle
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()):
node_x = paddle.static.data(name = 'x', shape = x.shape, dtype = in_dtype)
if mode == 'constant':
... | def pad3d(name : str, x, in_dtype, pad, data_format, mode, value = 0):
| import paddle
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()):
node_x = paddle.static.data(name = 'x', shape = x.shape, dtype = in_dtype)
if mode == 'constant':
pad_constant = paddle.nn.Pad3D(padding=pad, mode=mode, valu... | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# pad3d paddle model generator
#
import numpy as np
from save_model import saveModel
import sys
def pad3d(name : str, x, in_dtype, pad, data_format, mode, value = 0):
| 75 | 75 | 252 | 25 | 49 | ryanloney/openvino-1 | src/core/tests/frontend/paddle/test_models/gen_scripts/generate_pad3d.py | Python | pad3d | pad3d | 11 | 35 | 11 | 11 | cb9383a352d960912cd73b70cd5a972a4475ed85 | bigcode/the-stack | train |
25d2332c41572da7bb7b7ce3 | train | function | @app.route('/pdf_to_stream', methods=['GET', 'POST'])
def pdf_to_stream():
url = request.args.get('url')
pages = request.args.get('pages', 'all')
df = tabula.read_pdf(url, pages=pages, stream=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
| @app.route('/pdf_to_stream', methods=['GET', 'POST'])
def pdf_to_stream():
| url = request.args.get('url')
pages = request.args.get('pages', 'all')
df = tabula.read_pdf(url, pages=pages, stream=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
| ('pages', 'all')
df = tabula.read_pdf(url, pages=pages, lattice=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
@app.route('/pdf_to_stream', methods=['GET', 'POST'])
def pdf_to_stream():
| 64 | 64 | 78 | 19 | 45 | surekap/tabula-server | app.py | Python | pdf_to_stream | pdf_to_stream | 16 | 24 | 16 | 17 | 20e1df14174eee6a5661426fb7ab950fc08ba6b4 | bigcode/the-stack | train |
f4f6b7191531ac721c289100 | train | function | @app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
who = request.args.get('name')
return Response("Hello " + str(who))
| @app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
| who = request.args.get('name')
return Response("Hello " + str(who))
|
df = tabula.read_pdf(url, pages=pages, stream=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
| 64 | 64 | 44 | 25 | 39 | surekap/tabula-server | app.py | Python | index | index | 27 | 31 | 27 | 29 | 1c0b35d39b6ba93edc47ad683dcd0e2cd234e4e9 | bigcode/the-stack | train |
c32b463534e35ef92c01b205 | train | function | @app.route('/pdf_to_lattice', methods=['GET', 'POST'])
def pdf_to_lattice():
url = request.args.get('url')
pages = request.args.get('pages', 'all')
df = tabula.read_pdf(url, pages=pages, lattice=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
| @app.route('/pdf_to_lattice', methods=['GET', 'POST'])
def pdf_to_lattice():
| url = request.args.get('url')
pages = request.args.get('pages', 'all')
df = tabula.read_pdf(url, pages=pages, lattice=True)
data = [x.to_csv() for x in df]
csv = json.dumps(data)
return Response(csv)
| from flask import Flask, request, Response
import tabula, json
app = Flask(__name__)
@app.route('/pdf_to_lattice', methods=['GET', 'POST'])
def pdf_to_lattice():
| 42 | 64 | 80 | 21 | 21 | surekap/tabula-server | app.py | Python | pdf_to_lattice | pdf_to_lattice | 6 | 14 | 6 | 7 | 8d5a28f6e6bc29e41a943169a458faf623f2918f | bigcode/the-stack | train |
620a3a63d9ed9b6bcd51bf88 | train | class | class BaseModel:
"""Public instance attributes:
id (str): assign with an uuid when an instance is created.
created_at: current datetime when an instance is created
updated_at: current datetime when an instance is created and it will
be updated every time the object changes.
"""
... | class BaseModel:
| """Public instance attributes:
id (str): assign with an uuid when an instance is created.
created_at: current datetime when an instance is created
updated_at: current datetime when an instance is created and it will
be updated every time the object changes.
"""
def __init__... | #!/usr/bin/env python3
'''This module contains a base class called 'BaseModel'that defines all common
attributes/methods for other classes.
'''
import uuid
from datetime import datetime
from models import storage
class BaseModel:
| 50 | 154 | 516 | 4 | 45 | malu17/AirBnB_clone | models/base_model.py | Python | BaseModel | BaseModel | 10 | 77 | 10 | 10 | 306fb78bd6ef0088e4786eb1d6ebee1b793a9c24 | bigcode/the-stack | train |
8ad0fb964c516e369bb012b3 | train | function | def _get_n_from_n_timepoints(n_timepoints, n="sqrt"):
"""
Get number of intervals from number of time points for various allowed
input arguments.
Helpful to compute number of intervals relative to time series length,
e.g. using floats or functions.
Parameters
----------
n_timepoints : i... | def _get_n_from_n_timepoints(n_timepoints, n="sqrt"):
| """
Get number of intervals from number of time points for various allowed
input arguments.
Helpful to compute number of intervals relative to time series length,
e.g. using floats or functions.
Parameters
----------
n_timepoints : int
n : {int, float, str, callable}
Returns
... | # -*- coding: utf-8 -*-
__all__ = [
"_get_n_from_n_timepoints",
"time_series_slope",
"fit_trend",
]
__author__ = ["Markus Löning"]
import numpy as np
from sklearn.utils import check_array
def _get_n_from_n_timepoints(n_timepoints, n="sqrt"):
| 74 | 190 | 636 | 16 | 57 | bmurdata/sktime | sktime/utils/time_series.py | Python | _get_n_from_n_timepoints | _get_n_from_n_timepoints | 13 | 89 | 13 | 13 | 936b27c888465d621ac309c56d58a1eb87db7aa7 | bigcode/the-stack | train |
abc43ff0e4304b4d6baed4cb | train | function | def time_series_slope(y, axis=0):
"""Find the slope for each series of y
Parameters
----------
y: np.ndarray
Time series
axis : int, optional (default=0)
Axis along which to compute slope
Returns
----------
slope : np.ndarray
Time series slope
"""
# Make ... | def time_series_slope(y, axis=0):
| """Find the slope for each series of y
Parameters
----------
y: np.ndarray
Time series
axis : int, optional (default=0)
Axis along which to compute slope
Returns
----------
slope : np.ndarray
Time series slope
"""
# Make sure y is always at least 2-dimens... | dot(x.T).T
coefs, _, _, _ = np.linalg.lstsq(poly_terms, x.T, rcond=None)
# returning fitted coefficients in expected format with samples in rows
coefs = coefs.T
return coefs
def time_series_slope(y, axis=0):
| 66 | 66 | 222 | 11 | 54 | bmurdata/sktime | sktime/utils/time_series.py | Python | time_series_slope | time_series_slope | 134 | 163 | 134 | 134 | 827e03c43b568e5cfdbfa934600ccb078574e823 | bigcode/the-stack | train |
435cc9789f4abe8cc4408379 | train | function | def fit_trend(x, order=0):
"""Fit linear regression with polynomial terms of given order
x : array_like, shape=[n_samples, n_obs]
Time series data, each sample is fitted separately
order : int
The polynomial order of the trend, zero is constant (mean), one is
linear trend, two i... | def fit_trend(x, order=0):
| """Fit linear regression with polynomial terms of given order
x : array_like, shape=[n_samples, n_obs]
Time series data, each sample is fitted separately
order : int
The polynomial order of the trend, zero is constant (mean), one is
linear trend, two is quadratic trend, and so o... | :
raise ValueError(
f"`n_intervals` must be either one of the allowed string options "
f"in "
f"{allowed_strings}, an integer or a float number."
)
# make sure n_intervals is an integer and there is at least one interval
n_intervals_ = np.maximum(1, np.int(n_... | 94 | 95 | 319 | 10 | 84 | bmurdata/sktime | sktime/utils/time_series.py | Python | fit_trend | fit_trend | 92 | 131 | 92 | 92 | 1140a54948441a20571ce5b7e6693c5418242355 | bigcode/the-stack | train |
c22b0154e55cee477ac3de0d | train | function | def compute_triangles():
triangles = []
#brute force search
edge_dict = {}
for i in range(frame_connections_len,all_connections_len):
edge_dict[(all_connections[i,0]),all_connections[i,1]] = 1
for i in range(frame_connections_len,all_connections_len):
t1 = all_connections[i,0]
t2 = all_connections[i,1]
for... | def compute_triangles():
| triangles = []
#brute force search
edge_dict = {}
for i in range(frame_connections_len,all_connections_len):
edge_dict[(all_connections[i,0]),all_connections[i,1]] = 1
for i in range(frame_connections_len,all_connections_len):
t1 = all_connections[i,0]
t2 = all_connections[i,1]
for j in range(frame_connect... | _idx]=all_connections[all_connections_len-1]
return all_connections_len-1
else:
all_connections[all_connections_len,0] = p1i
all_connections[all_connections_len,1] = p2i
return all_connections_len+1
def compute_triangles():
| 64 | 64 | 189 | 5 | 58 | lwkobe/NMC | tessellation/tessellation_NMC/configs_done/000001012022220.py | Python | compute_triangles | compute_triangles | 438 | 454 | 438 | 438 | 665b5bbf0995129d7986732346c8530724c839cf | bigcode/the-stack | train |
0cb451c7b292e24fbd16f67c | train | function | def mouse_ops(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
mouse_xyd[0] = x
mouse_xyd[1] = y
mouse_xyd[2] = 1
elif event == cv2.EVENT_RBUTTONDOWN:
mouse_xyd[0] = x
mouse_xyd[1] = y
mouse_xyd[3] = 1
elif event == cv2.EVENT_MOUSEMOVE:
if mouse_xyd[2] == 1 or mouse_xyd[3] == 1:
mouse_xyd[... | def mouse_ops(event,x,y,flags,param):
| if event == cv2.EVENT_LBUTTONDOWN:
mouse_xyd[0] = x
mouse_xyd[1] = y
mouse_xyd[2] = 1
elif event == cv2.EVENT_RBUTTONDOWN:
mouse_xyd[0] = x
mouse_xyd[1] = y
mouse_xyd[3] = 1
elif event == cv2.EVENT_MOUSEMOVE:
if mouse_xyd[2] == 1 or mouse_xyd[3] == 1:
mouse_xyd[0] = x
mouse_xyd[1] = y
elif event... | np.int32)
all_triangles_len = 0
all_triangles_len = compute_triangles()
# ---------- capture mouse events ----------
mouse_xyd = np.zeros([4], np.int32)
mouse_xyd_backup = np.zeros([4], np.int32)
def mouse_ops(event,x,y,flags,param):
| 64 | 64 | 185 | 10 | 54 | lwkobe/NMC | tessellation/tessellation_NMC/configs_done/000001012022220.py | Python | mouse_ops | mouse_ops | 466 | 482 | 466 | 466 | a47821d3eb4995f43add8c38d9436c584dd44fde | bigcode/the-stack | train |
d76a0fb2c1da44554a9eb1d4 | train | function | def append_new_line(p1i,p2i):
if p1i>p2i:
p1i,p2i = p2i,p1i
repeat_idx = -1
for i in range(frame_connections_len,all_connections_len):
if all_connections[i,0]==p1i and all_connections[i,1]==p2i:
repeat_idx = i
break
if repeat_idx>=0:
all_connections[repeat_idx]=all_connections[all_connections_len-1]
r... | def append_new_line(p1i,p2i):
| if p1i>p2i:
p1i,p2i = p2i,p1i
repeat_idx = -1
for i in range(frame_connections_len,all_connections_len):
if all_connections[i,0]==p1i and all_connections[i,1]==p2i:
repeat_idx = i
break
if repeat_idx>=0:
all_connections[repeat_idx]=all_connections[all_connections_len-1]
return all_connections_len-1
e... | 1]-y)**2
#consider all_points_visibility
distance = distance+(1-all_points_visibility)*10000
min_idx = np.argmin(distance)
if distance[min_idx]<=100:
return min_idx
else:
return -1
def append_new_line(p1i,p2i):
| 64 | 64 | 156 | 11 | 52 | lwkobe/NMC | tessellation/tessellation_NMC/configs_done/000001012022220.py | Python | append_new_line | append_new_line | 422 | 436 | 422 | 422 | 310cc6a0e10e46893ff95026354b150f459470f1 | bigcode/the-stack | train |
81c88505c5e0e5ac93d75bee | train | function | def detect_clicked_point(x,y):
distance = (all_points_transformed[:,0]-x)**2 + (all_points_transformed[:,1]-y)**2
#consider all_points_visibility
distance = distance+(1-all_points_visibility)*10000
min_idx = np.argmin(distance)
if distance[min_idx]<=100:
return min_idx
else:
return -1
| def detect_clicked_point(x,y):
| distance = (all_points_transformed[:,0]-x)**2 + (all_points_transformed[:,1]-y)**2
#consider all_points_visibility
distance = distance+(1-all_points_visibility)*10000
min_idx = np.argmin(distance)
if distance[min_idx]<=100:
return min_idx
else:
return -1
| 2 = (int(tmp_line_p2_x),int(tmp_line_p2_y))
color = (255,0,0)
line_size = 2
cv2.line(img, p1, p2, color, line_size, cv2.LINE_AA)
def detect_clicked_point(x,y):
| 64 | 64 | 81 | 7 | 57 | lwkobe/NMC | tessellation/tessellation_NMC/configs_done/000001012022220.py | Python | detect_clicked_point | detect_clicked_point | 412 | 420 | 412 | 412 | 912b109305ffaa55f5c4678c2510d6569dedd578 | bigcode/the-stack | train |
fefbd2c6329b29d5a820383a | train | function | def render(cam_alpha,cam_beta,img):
sin_alpha = np.sin(cam_alpha)
cos_alpha = np.cos(cam_alpha)
sin_beta = np.sin(cam_beta)
cos_beta = np.cos(cam_beta)
points_x = all_points[:,0]
points_y = all_points[:,1]
points_z = all_points[:,2]
points_x2 = cos_alpha*points_x - sin_alpha*points_z
points_y2 = points_y
... | def render(cam_alpha,cam_beta,img):
| sin_alpha = np.sin(cam_alpha)
cos_alpha = np.cos(cam_alpha)
sin_beta = np.sin(cam_beta)
cos_beta = np.cos(cam_beta)
points_x = all_points[:,0]
points_y = all_points[:,1]
points_z = all_points[:,2]
points_x2 = cos_alpha*points_x - sin_alpha*points_z
points_y2 = points_y
points_z2 = sin_alpha*points_x + cos... | p1i-(8+8+12))%8+8
all_points_visibility[p2i] = 1
# ---------- load ----------
prepared_connections_ = prepared_connections
if len(load_connections)>0:
print("\n\nConnections loaded")
prepared_connections_ = load_connections
#check if the used points are valid according to all_points_visibility
for i in range(l... | 256 | 256 | 1,738 | 9 | 246 | lwkobe/NMC | tessellation/tessellation_NMC/configs_done/000001012022220.py | Python | render | render | 284 | 409 | 284 | 284 | 76a00a51c3aa368922e262372ad981eba3df3688 | bigcode/the-stack | train |
936d6d072e28f4e594cd9083 | train | class | class TLClassifier(object):
def __init__(self):
#TODO load classifier
self.input_height = 320
self.input_width = 432
self.config = tf.ConfigProto()
self.config.gpu_options.allow_growth = True
self.sess = tf.Session(config=self.config)
signatu... | class TLClassifier(object):
| def __init__(self):
#TODO load classifier
self.input_height = 320
self.input_width = 432
self.config = tf.ConfigProto()
self.config.gpu_options.allow_growth = True
self.sess = tf.Session(config=self.config)
signature_key = tf.saved_model.sign... | #!/usr/bin/env python
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import cv2
import numpy as np
import os
import time
class TLClassifier(object):
| 40 | 176 | 587 | 5 | 34 | Pedrous/CarND-Capstone | ros/src/tl_detector/light_classification/tl_classifier_BASE_21582.py | Python | TLClassifier | TLClassifier | 9 | 78 | 9 | 9 | 126de52292965fd818e072550b940cab91065b69 | bigcode/the-stack | train |
9cd884a5d0ef1be5245cc909 | train | class | class ExtraCMakeModulesConan(ConanFile):
name = "extra-cmake-modules"
version = "5.56.0"
license = "BSD 3-Clause"
url = "https://api.kde.org/frameworks/extra-cmake-modules/html/index.html"
settings = "os", "compiler", "arch", "build_type"
description = "Extra CMake modules"
no_copy_source = ... | class ExtraCMakeModulesConan(ConanFile):
| name = "extra-cmake-modules"
version = "5.56.0"
license = "BSD 3-Clause"
url = "https://api.kde.org/frameworks/extra-cmake-modules/html/index.html"
settings = "os", "compiler", "arch", "build_type"
description = "Extra CMake modules"
no_copy_source = True
def source(self):
short... | from conans import ConanFile, CMake, tools
class ExtraCMakeModulesConan(ConanFile):
| 24 | 81 | 270 | 12 | 11 | mmha/conan-ecm | conanfile.py | Python | ExtraCMakeModulesConan | ExtraCMakeModulesConan | 4 | 29 | 4 | 4 | 77fa2e15d39a54c98d81548a68ece40fdfdbce3e | bigcode/the-stack | train |
42cd6bbca0f84587038298ac | train | class | class DescribeLiveStreamTranscodeInfoRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'live', '2016-11-01', 'DescribeLiveStreamTranscodeInfo','live')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
set... | class DescribeLiveStreamTranscodeInfoRequest(RpcRequest):
| def __init__(self):
RpcRequest.__init__(self, 'live', '2016-11-01', 'DescribeLiveStreamTranscodeInfo','live')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRe... | OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdklive.endpoint import endpoint_data
class DescribeLiveStreamTranscodeInfoRequest(RpcRequest):
| 64 | 64 | 193 | 12 | 51 | liumihust/aliyun-openapi-python-sdk | aliyun-python-sdk-live/aliyunsdklive/request/v20161101/DescribeLiveStreamTranscodeInfoRequest.py | Python | DescribeLiveStreamTranscodeInfoRequest | DescribeLiveStreamTranscodeInfoRequest | 23 | 43 | 23 | 24 | 547fd1cee57edbf32cf5753a7bb7608988d4d09c | bigcode/the-stack | train |
124012fa87de1315d53c88b8 | train | class | class AST(dict):
"""
A dictionary with attribute-style access. It maps attribute access to
the real dictionary.
"""
# ActiveState Recipe:
# http://code.activestate.com/recipes/473786-dictionary-with-attribute-style-access/
def __init__(self, *args, **kwargs):
super(AST, self).__init... | class AST(dict):
| """
A dictionary with attribute-style access. It maps attribute access to
the real dictionary.
"""
# ActiveState Recipe:
# http://code.activestate.com/recipes/473786-dictionary-with-attribute-style-access/
def __init__(self, *args, **kwargs):
super(AST, self).__init__(*args, **kwarg... | # -*- coding: utf-8 -*-
"""
Define the AST class, a direct descendant of dict that's used during parsing
to store the values of named elements of grammar rules.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
__all__ = ['AST']
class AST(dict):
| 63 | 121 | 405 | 4 | 59 | alyosha1879/grako | grako/ast.py | Python | AST | AST | 11 | 68 | 11 | 11 | c04e789d7baae9f819366f37f311d75ad5477e23 | bigcode/the-stack | train |
c554ec31ebd391de8f605cc8 | train | class | class Module(Struct):
_fields = [
('code', [Uint8])
]
| class Module(Struct):
| _fields = [
('code', [Uint8])
]
| from canoser import Struct, Uint8
class Module(Struct):
| 14 | 64 | 20 | 5 | 8 | MaslDi/libra-client | libra/transaction/module.py | Python | Module | Module | 3 | 6 | 3 | 3 | 060132bebd9580aba5b3a7b1501a1c92b3587407 | bigcode/the-stack | train |
e829f145b465e8600fe50b55 | train | class | class SynthDef:
"""Wrapper for SuperCollider SynthDef"""
synth_descs = {}
@classmethod
def get_description(cls, name: str) -> Optional[Dict[str, "SynthArgument"]]:
"""Get Synth description
Parameters
----------
name : str
name of SynthDef
Returns
... | class SynthDef:
| """Wrapper for SuperCollider SynthDef"""
synth_descs = {}
@classmethod
def get_description(cls, name: str) -> Optional[Dict[str, "SynthArgument"]]:
"""Get Synth description
Parameters
----------
name : str
name of SynthDef
Returns
-------
... | """Module to for using SuperCollider SynthDefs and Synths in Python"""
import re
import sys
import warnings
from enum import Enum, unique
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
if sys.version_info < (3, 9):
# `importlib.resources` backported to PY<37 as `import... | 233 | 256 | 2,005 | 4 | 229 | interactive-sonification/sc3nb | src/sc3nb/sc_objects/synthdef.py | Python | SynthDef | SynthDef | 37 | 346 | 37 | 37 | 1d4352c39c501930ab5e46930e86012e22b033d1 | bigcode/the-stack | train |
d6269c980418ffa0dd40fdaf | train | class | @unique
class SynthDefinitionCommand(str, Enum):
"""OSC Commands for Synth Definitions"""
RECV = "/d_recv"
LOAD = "/d_load"
LOAD_DIR = "/d_loadDir"
FREE = "/d_free"
| @unique
class SynthDefinitionCommand(str, Enum):
| """OSC Commands for Synth Definitions"""
RECV = "/d_recv"
LOAD = "/d_load"
LOAD_DIR = "/d_loadDir"
FREE = "/d_free"
| nb.resources
from sc3nb.util import parse_pyvars, replace_vars
if TYPE_CHECKING:
from sc3nb.sc import SC
from sc3nb.sc_objects.server import SCServer
from sc3nb.sclang import SynthArgument
@unique
class SynthDefinitionCommand(str, Enum):
| 64 | 64 | 50 | 11 | 52 | interactive-sonification/sc3nb | src/sc3nb/sc_objects/synthdef.py | Python | SynthDefinitionCommand | SynthDefinitionCommand | 27 | 34 | 27 | 28 | 28412704af192aa70f7b0af9cb35ebb5263cff41 | bigcode/the-stack | train |
d18076112ccdeb193ab31aee | train | function | def run():
dataframe = pd.read_csv("../data/depression/train.tsv", sep="\t")
train_sequences = dataframe['text_a'][0:]
train_targets = dataframe['label'][0:]
autoBOTLibObj = autoBOTLib.GAlearner(
train_sequences, train_targets,
time_constraint=0.1).evolve(representation_step_only=True)
... | def run():
| dataframe = pd.read_csv("../data/depression/train.tsv", sep="\t")
train_sequences = dataframe['text_a'][0:]
train_targets = dataframe['label'][0:]
autoBOTLibObj = autoBOTLib.GAlearner(
train_sequences, train_targets,
time_constraint=0.1).evolve(representation_step_only=True)
input_... | ## What if we only wish to obtain the representation?
import autoBOTLib
import pandas as pd
import umap
import matplotlib.pyplot as plt
import seaborn as sns
def run():
| 40 | 64 | 206 | 3 | 36 | EMBEDDIA/autoBOT | examples/example_representation_visualization.py | Python | run | run | 8 | 28 | 8 | 8 | ccd540448c8d9f966c01bf2d69c4260f4745d1f9 | bigcode/the-stack | train |
7c27f2fd83a5384401fd10da | train | function | @tf_export("get_collection_ref")
def get_collection_ref(key):
"""Wrapper for `Graph.get_collection_ref()` using the default graph.
See @{tf.Graph.get_collection_ref}
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collectio... | @tf_export("get_collection_ref")
def get_collection_ref(key):
| """Wrapper for `Graph.get_collection_ref()` using the default graph.
See @{tf.Graph.get_collection_ref}
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
Returns:
The list of values in the collection with ... | value: The value to add to the collections.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
get_default_graph().add_to_collections(names, value)
@tf_export("get_collection_ref")
def get_collection_ref(key):
| 64 | 64 | 169 | 14 | 50 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | get_collection_ref | get_collection_ref | 5,850 | 5,871 | 5,850 | 5,851 | d9830aeed189d2f5f29e707f71bfa310a1a2b508 | bigcode/the-stack | train |
11f9228a2026afa037bd9b6f | train | function | def _eval_using_default_session(tensors, feed_dict, graph, session=None):
"""Uses the default session to evaluate one or more tensors.
Args:
tensors: A single Tensor, or a list of Tensor objects.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos... | def _eval_using_default_session(tensors, feed_dict, graph, session=None):
| """Uses the default session to evaluate one or more tensors.
Args:
tensors: A single Tensor, or a list of Tensor objects.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos, or strings.
graph: The graph in which the tensors are defined.
s... | or `Session.as_default()` context has been entered.
NOTE: The default session is a property of the current thread. If you
create a new thread, and wish to use the default session in that
thread, you must explicitly add a `with sess.as_default():` in that
thread's function.
Returns:
The default `Session... | 111 | 111 | 373 | 17 | 94 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | _eval_using_default_session | _eval_using_default_session | 5,168 | 5,205 | 5,168 | 5,168 | 7d74fffa9ced49193437d0ad2aab88f1f330f0a9 | bigcode/the-stack | train |
310ff3fd6bbf58d2d3618c87 | train | function | def _override_helper(clazz_object, operator, func):
"""Overrides (string) operator on Tensors to call func.
Args:
clazz_object: the class to override for; either Tensor or SparseTensor.
operator: the string name of the operator to override.
func: the function that replaces the overridden operator.
R... | def _override_helper(clazz_object, operator, func):
| """Overrides (string) operator on Tensors to call func.
Args:
clazz_object: the class to override for; either Tensor or SparseTensor.
operator: the string name of the operator to override.
func: the function that replaces the overridden operator.
Raises:
ValueError: If operator has already been ... | # pylint: disable=protected-access
class _NullContextmanager(object):
def __enter__(self):
pass
def __exit__(self, type_arg, value_arg, traceback_arg):
return False # False values do not suppress exceptions
def _override_helper(clazz_object, operator, func):
| 64 | 64 | 215 | 11 | 52 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | _override_helper | _override_helper | 85 | 106 | 85 | 85 | c2f50d5d883c4e69feaeb754e3e739f27a2f36c9 | bigcode/the-stack | train |
e483ef8cb8cdbfaabebbedcd | train | function | def internal_convert_n_to_tensor(values,
dtype=None,
name=None,
as_ref=False,
preferred_dtype=None,
ctx=None):
"""Converts `values` to a list of `Tensor`... | def internal_convert_n_to_tensor(values,
dtype=None,
name=None,
as_ref=False,
preferred_dtype=None,
ctx=None):
| """Converts `values` to a list of `Tensor` objects.
Args:
values: A list of objects that can be consumed by `tf.convert_to_tensor()`.
dtype: (Optional.) The required `DType` of the returned `Tensor` objects.
name: (Optional.) A name prefix to used when a new `Tensor` is
created, in which case ele... | sConversion function %r for type %s returned incompatible "
"dtype: requested = %s, actual = %s" %
(_error_prefix(name), conversion_func, base_type, dtype.name,
ret.dtype.name))
return ret
raise TypeError("%sCannot convert %r with type %s to Tensor: "
"no conversio... | 119 | 119 | 397 | 30 | 89 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | internal_convert_n_to_tensor | internal_convert_n_to_tensor | 1,131 | 1,176 | 1,131 | 1,136 | 5da3ff739ae3ca8610719fcbf77b17dccf8a3c47 | bigcode/the-stack | train |
7c5634ac3be1c79261b8d8a1 | train | function | def default_session(session):
"""Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session... | def default_session(session):
| """Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session.run() interface.
Use with ... | yield default
finally:
# stack may be empty if reset() was called
if self.stack:
if self._enforce_nesting:
if self.stack[-1] is not default:
raise AssertionError(
"Nesting violated for default stack of %s objects" %
type(default))
... | 103 | 103 | 345 | 5 | 97 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | default_session | default_session | 5,102 | 5,147 | 5,102 | 5,102 | a63f8dbbefa1e00d021bd5bf36b7ae873945c713 | bigcode/the-stack | train |
e607d6c65a9c1f61d27d4d1e | train | function | def numpy_text(tensor, is_repr=False):
"""Human readable representation of a tensor's numpy value."""
if tensor.dtype.is_numpy_compatible:
text = repr(tensor.numpy()) if is_repr else str(tensor.numpy())
else:
text = "<unprintable>"
if "\n" in text:
text = "\n" + text
return text
| def numpy_text(tensor, is_repr=False):
| """Human readable representation of a tensor's numpy value."""
if tensor.dtype.is_numpy_compatible:
text = repr(tensor.numpy()) if is_repr else str(tensor.numpy())
else:
text = "<unprintable>"
if "\n" in text:
text = "\n" + text
return text
| _TENSOR_LIKE_TYPES
_TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type])
def uid():
"""A unique (within this program execution) integer."""
return c_api.TFE_Py_UID()
def numpy_text(tensor, is_repr=False):
| 64 | 64 | 80 | 10 | 54 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | numpy_text | numpy_text | 181 | 189 | 181 | 181 | ba599e069757be5ddd91b6a2ee2f4d910d505d95 | bigcode/the-stack | train |
7a00cbf58df0b2c216eb28ee | train | class | class OpStats(object):
"""A holder for statistics about an operator.
This class holds information about the resource requirements for an op,
including the size of its weight parameters on-disk and how many FLOPS it
requires to execute forward inference.
If you define a new operation, you can create a functi... | class OpStats(object):
| """A holder for statistics about an operator.
This class holds information about the resource requirements for an op,
including the size of its weight parameters on-disk and how many FLOPS it
requires to execute forward inference.
If you define a new operation, you can create a function that will return a
... | (op.outputs) != len(shapes):
raise RuntimeError(
"Shape function for op %s returned %d shapes but expected %d %s %s" %
(op, len(shapes), len(op.outputs), shape_func.__name__, str(shapes)))
for output, s in zip(op.outputs, shapes):
output._shape_val = tensor_shape.unknown_shape()
output._sh... | 99 | 99 | 333 | 5 | 94 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | OpStats | OpStats | 2,629 | 2,673 | 2,629 | 2,629 | 4c1e374dbea8343a5e80618fbf40f8574e948410 | bigcode/the-stack | train |
70b099a2773223d08a6bad44 | train | function | def _operation_conversion_error(op, dtype=None, name=None, as_ref=False):
"""Produce a nice error if someone converts an Operation to a Tensor."""
raise TypeError(("Can't convert Operation '%s' to Tensor "
"(target dtype=%r, name=%r, as_ref=%r)") % (op.name, dtype,
... | def _operation_conversion_error(op, dtype=None, name=None, as_ref=False):
| """Produce a nice error if someone converts an Operation to a Tensor."""
raise TypeError(("Can't convert Operation '%s' to Tensor "
"(target dtype=%r, name=%r, as_ref=%r)") % (op.name, dtype,
name, as_ref))
| .executing_eagerly():
if collection_name in GraphKeys._VARIABLE_COLLECTIONS: # pylint: disable=protected-access
raise ValueError(
"variable collections are not supported when eager execution is enabled."
)
def _operation_conversion_error(op, dtype=None, name=None, as_ref=False):
| 64 | 64 | 75 | 17 | 47 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | _operation_conversion_error | _operation_conversion_error | 6,145 | 6,149 | 6,145 | 6,145 | 6775805cf1ae96741edd09a3d7baeffa6dd705e2 | bigcode/the-stack | train |
dfbf7a16631e4856c831c5c8 | train | class | @tf_export("RegisterGradient")
class RegisterGradient(object):
"""A decorator for registering the gradient function for an op type.
This decorator is only used when defining a new op type. For an op
with `m` inputs and `n` outputs, the gradient function is a function
that takes the original `Operation` and `n`... | @tf_export("RegisterGradient")
class RegisterGradient(object):
| """A decorator for registering the gradient function for an op type.
This decorator is only used when defining a new op type. For an op
with `m` inputs and `n` outputs, the gradient function is a function
that takes the original `Operation` and `n` `Tensor` objects
(representing the gradients with respect to... | `session` must be specified explicitly.
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
See @{tf.Session.run}
for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default sessio... | 113 | 113 | 377 | 12 | 101 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | RegisterGradient | RegisterGradient | 2,407 | 2,447 | 2,407 | 2,408 | 09a92a3078c6b0093b41fca6ecf8e30f5487e8cd | bigcode/the-stack | train |
02fb7bf5d50cfa22f20e379f | train | function | @tf_export("get_default_session")
def get_default_session():
"""Returns the default session for the current thread.
The returned `Session` will be the innermost session on which a
`Session` or `Session.as_default()` context has been entered.
NOTE: The default session is a property of the current thread. If yo... | @tf_export("get_default_session")
def get_default_session():
| """Returns the default session for the current thread.
The returned `Session` will be the innermost session on which a
`Session` or `Session.as_default()` context has been entered.
NOTE: The default session is a property of the current thread. If you
create a new thread, and wish to use the default session ... | .default_session(...):
c.eval(session=sess)
Args:
session: The session to be installed as the default session.
Returns:
A context manager for the default session.
"""
return _default_session_stack.get_controller(session)
@tf_export("get_default_session")
def get_default_session():
| 64 | 64 | 139 | 13 | 51 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | get_default_session | get_default_session | 5,150 | 5,165 | 5,150 | 5,151 | 1946d208c9ab031b63c6f6a12e951591f859543f | bigcode/the-stack | train |
125827ca542e4748be957be6 | train | function | def get_all_collection_keys():
"""Returns a list of collections used in the default graph."""
return get_default_graph().get_all_collection_keys()
| def get_all_collection_keys():
| """Returns a list of collections used in the default graph."""
return get_default_graph().get_all_collection_keys()
| . The
list contains the values in the order under which they were
collected.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
return get_default_graph().get_collection(key, scope)
def get_all_collection_keys():
| 64 | 64 | 30 | 6 | 58 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | get_all_collection_keys | get_all_collection_keys | 5,903 | 5,905 | 5,903 | 5,903 | f8677ad75a6c2679d063f828d864fede921f8b4f | bigcode/the-stack | train |
6cd339244d143d27068f3a51 | train | function | def register_proto_function(collection_name,
proto_type=None,
to_proto=None,
from_proto=None):
"""Registers `to_proto` and `from_proto` functions for collection_name.
`to_proto` function converts a Python object to the correspondin... | def register_proto_function(collection_name,
proto_type=None,
to_proto=None,
from_proto=None):
| """Registers `to_proto` and `from_proto` functions for collection_name.
`to_proto` function converts a Python object to the corresponding protocol
buffer, and returns the protocol buffer.
`from_proto` function converts protocol buffer into a Python object, and
returns the object..
Args:
collection_na... | use tf.name_scope(name, default_name, values)")
with name_scope(name, default_name=default_name, values=values) as scope:
yield scope
_proto_function_registry = registry.Registry("proto functions")
def register_proto_function(collection_name,
proto_type=None,
... | 66 | 66 | 223 | 22 | 44 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | register_proto_function | register_proto_function | 6,085 | 6,110 | 6,085 | 6,088 | f0fa563fb43aac9de552f3ac415d58af9548c4b2 | bigcode/the-stack | train |
939d161598fac16661fdec98 | train | function | def get_gradient_function(op):
"""Returns the function that computes gradients for "op"."""
if not op.inputs:
return None
try:
op_type = op.get_attr("_gradient_op_type")
except ValueError:
op_type = op.type
return _gradient_registry.lookup(op_type)
| def get_gradient_function(op):
| """Returns the function that computes gradients for "op"."""
if not op.inputs:
return None
try:
op_type = op.get_attr("_gradient_op_type")
except ValueError:
op_type = op.type
return _gradient_registry.lookup(op_type)
| a string.
"""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string")
_gradient_registry.register(None, op_type)
# Alias for the old name, will be eventually removed.
NoGradient = NotDifferentiable
def get_gradient_function(op):
| 64 | 64 | 65 | 6 | 57 | P-Hidringer/tensorflow | tensorflow/python/framework/ops.py | Python | get_gradient_function | get_gradient_function | 2,488 | 2,496 | 2,488 | 2,488 | 3f83d0bb2cf5681b47daf1daacac23e39b2d4507 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.