Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
objects = BakeryUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password']
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.username
def get_abso... | do_vote(self, cookie) |
Predict the next line for this snippet: <|code_start|> verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse_lazy('auth:profile', kwargs={'username': self.username})
def get_full_name(sel... | for candy in CANDIES: |
Here is a snippet: <|code_start|> is_active = models.BooleanField(_('Active'), default=True)
is_organization = models.BooleanField(_('Organization'))
profile_url = models.URLField(_('Profile'), blank=True, null=True)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects ... | def get_gravatar(self): |
Based on the snippet: <|code_start|>
try:
except ValueError: # Celery doesn't work under Python 3.3 - when it does it'll test again
Celery = None
def prefix(name):
return '%s.%s' % (__name__, name)
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
from unittest import T... | @skipIf(Celery is None, 'Celery did not import correctly') |
Given the code snippet: <|code_start|>
try:
except ValueError: # Celery doesn't work under Python 3.3 - when it does it'll test again
Celery = None
def prefix(name):
return '%s.%s' % (__name__, name)
@skipIf(Celery is None, 'Celery did not import correctly')
class CeleryRouterTests(TestCase):
'tests f... | self.router = CeleryRouter(self.celery.task) |
Predict the next line for this snippet: <|code_start|>'router for emit'
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters ... | self.message_class = message_class or Message |
Using the snippet: <|code_start|> .. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
... | if item is not NoResult |
Using the snippet: <|code_start|>
try:
except ImportError:
RQRouter = None
<|code_end|>
, determine the next line of code. You have imports:
import mock
import rq
from redis import Redis
from unittest import TestCase
from .utils import skipIf
from emit.router.rq import RQRouter
and context (class names... | @skipIf(RQRouter is None, 'RQ did not import correctly') |
Based on the snippet: <|code_start|>'tests for message'
class MessageTests(TestCase):
'tests for Message'
def test_dot_access(self):
'accessing attributes'
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from unittest import TestCase
from emit.messages import Mes... | x = Message(x=1) |
Predict the next line after this snippet: <|code_start|>'simple celery app'
app = Celery(
'celery_emit_example',
broker='redis://'
)
app.conf.update(
CELERY_IMPORTS=('tasks',)
)
<|code_end|>
using the current file's imports:
from celery import Celery
from emit.router.celery import CeleryRouter
import l... | router = CeleryRouter(celery_task=app.task, node_modules=['tasks']) |
Next line prediction: <|code_start|>'simple celery app'
app = Celery(
'celery_emit_example',
broker='redis://'
)
app.conf.update(
CELERY_IMPORTS=('tasks',)
)
<|code_end|>
. Use current file imports:
(from celery import Celery
from emit.router.celery import CeleryRouter)
and context including class names... | router = CeleryRouter(celery_task=app.task, node_modules=['tasks']) |
Given snippet: <|code_start|>
# This code is mostly duplicated from the `gitlint.shell` module. We consciously duplicate this code as to not depend
# on gitlint internals for our integration testing framework.
if USE_SH_LIB:
gitlint = gitlint.bake(_unify_ttys=True, _tty_in=True) # pylint: disable=invalid-name
... | self.stdout = stdout + stderr.decode(DEFAULT_ENCODING) |
Continue the code snippet: <|code_start|>
def setUp(self):
""" Sets up the integration tests by creating a new temporary git repository """
self.tmpfiles = []
self.tmp_git_repos = []
self.tmp_git_repo = self.create_tmp_git_repo()
def tearDown(self):
# Clean up temporary ... | git("init", tmp_git_repo) |
Given snippet: <|code_start|>
@staticmethod
def get_sample_path(filename=""):
samples_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "samples")
return os.path.join(samples_dir, filename)
def get_last_commit_short_hash(self, git_repo=None):
git_repo = self.tmp_git_re... | expected_gitlint_version = gitlint("--version").replace("gitlint, version ", "").strip() |
Continue the code snippet: <|code_start|>
class BaseTestCase(TestCase):
""" Base class of which all gitlint integration test classes are derived.
Provides a number of convenience methods. """
# In case of assert failures, print the full error message
maxDiff = None
tmp_git_repo = None
G... | self.assertIsInstance(output, RunningCommand) |
Given the code snippet: <|code_start|>
class BaseTestCase(TestCase):
""" Base class of which all gitlint integration test classes are derived.
Provides a number of convenience methods. """
# In case of assert failures, print the full error message
maxDiff = None
tmp_git_repo = None
GITLI... | output = output.stdout.decode(DEFAULT_ENCODING) |
Given snippet: <|code_start|> # self.assertGreaterEqual(srv.getbalance(address), 50000000000)
# self.assertEqual(srv.getutxos(address)[0]['txid'], txid)
# self.assertEqual(srv.gettransactions(address)[0].txid, txid)
def test_service_getblock_id(self):
srv = ServiceTest(min_providers=... | self.assertEqual(to_hexstring(b.block_hash), '00000000000000000003ecd827f336c6971f6f77a0b9fba362398dd867975645') |
Based on the snippet: <|code_start|>MAXIMUM_ESTIMATED_FEE_DIFFERENCE = 3.00 # Maximum difference from average estimated fee before test_estimatefee fails.
# Use value above >0, and 1 for 100%
DATABASEFILE_CACHE_UNITTESTS = os.path.join(str(BCL_DATABASE_DIR), 'bitcoinlibcache.unittest.sqlite')
DATABASEFILE_CACHE_UNITT... | class TestService(unittest.TestCase, CustomAssertions): |
Based on the snippet: <|code_start|> self.assertEqual(s.raw, b'')
def test_script_deserialize_sig_pk(self):
scr = '493046022100cf4d7571dd47a4d47f5cb767d54d6702530a3555726b27b6ac56117f5e7808fe0221008cbb42233bb04d7f28a' \
'715cf7c938e238afde90207e9d103dd9018e12cb7180e0141042daa93315eebbe... | class TestScript(unittest.TestCase, CustomAssertions): |
Continue the code snippet: <|code_start|>
def test_hdkey_testnet_random(self):
self.k = HDKey(network='testnet')
self.assertEqual('tprv', self.k.wif(is_private=True)[:4])
self.assertEqual('tpub', self.k.wif_public()[:4])
self.assertIn(self.k.address()[:1], ['m', 'n'])
def test_... | for network in list(NETWORK_DEFINITIONS.keys()): |
Continue the code snippet: <|code_start|>def init_sqlite(_):
if os.path.isfile(SQLITE_DATABASE_FILE):
os.remove(SQLITE_DATABASE_FILE)
def init_postgresql(_):
con = psycopg2.connect(user='postgres', host='localhost', password='postgres')
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur =... | if UNITTESTS_FULL_DATABASE_TEST: |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Unit Tests for Bitcoinlib Tools
# © 2018 May - 1200 Web Development <http://1200wd.com/>
#
try:
except ImportError:
pass # Only necessary when mysql or postgres is used
<|code_end|>
, determine th... | SQLITE_DATABASE_FILE = os.path.join(str(BCL_DATABASE_DIR), 'bitcoinlib.unittest.sqlite') |
Given snippet: <|code_start|>
db_uris = (('sqlite:///' + SQLITE_DATABASE_FILE, init_sqlite),)
if UNITTESTS_FULL_DATABASE_TEST:
db_uris += (
# ('mysql://root@localhost:3306/' + DATABASE_NAME, init_mysql),
('postgresql://postgres:postgres@localhost:5432/' + DATABASE_NAME, init_postgresql),
)
@p... | self.assertIn(output_wlt_create, normalize_string(poutput[0])) |
Using the snippet: <|code_start|> :param strength: Key strength in number of bits as multiply of 32, default is 128 bits. It advised to specify 128 bits or more, i.e.: 128, 256, 512 or 1024
:type strength: int
:param add_checksum: Included a checksum? Default is True
:type add_checksum: b... | if check_on_curve and not 0 < data_int < secp256k1_n: |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Update database
# © 2017 November - 1200 Web Development <http://1200wd.com/>
#
# This script creates a database with latest structure and copies only wallets and keys from old da... | parser.add_argument('--database', '-d', default='sqlite:///' + DEFAULT_DATABASE, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Update database
# © 2017 November - 1200 Web Development <http://1200wd.com/>
#
# This script creates a database with latest structure and copies only wallets and keys from old database
# Transact... | database_file = os.path.join(BCL_DATABASE_DIR, database_file) |
Continue the code snippet: <|code_start|>
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['key']
else:
... | session.query(DbConfig).filter(DbConfig.variable == 'version').update({DbConfig.value: BITCOINLIB_VERSION}) |
Next line prediction: <|code_start|>def parse_args():
parser = argparse.ArgumentParser(description='BitcoinLib Database update script')
parser.add_argument('--database', '-d', default='sqlite:///' + DEFAULT_DATABASE,
help="Name of specific database file to use",)
pa = parser.parse_ar... | Base.metadata.create_all(engine) |
Here is a snippet: <|code_start|>
try:
# Create new database
engine = create_engine('sqlite:///%s' % database_file)
Base.metadata.create_all(engine)
# Copy wallets and keys to new database
Session = sessionmaker(bind=engine)
session = Session()
engine_backup = create_engine('sqlite:///%s' ... | db_field_names = [field[0] for field in DbWallet.__table__.columns.items()] |
Given the following code snippet before the placeholder: <|code_start|> pass
if fields['scheme'] == 'bip44':
fields['scheme'] = 'bip32'
elif fields['scheme'] == 'multisig':
fields['scheme'] = 'bip32'
fields['multisig'] = True
# Remove unused fields... | db_field_names = [field[0] for field in DbKey.__table__.columns.items()] |
Here is a snippet: <|code_start|>
session.add(DbWallet(**fields))
session.commit()
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
field... | session.add(DbKeyMultisigChildren(**fields)) |
Given the following code snippet before the placeholder: <|code_start|>
keys = session_backup.execute("SELECT * FROM keys")
for key in keys:
fields = dict(key)
# Update for 'key' field
if 'key' in fields:
if fields['is_private']:
fields['private'] = fields['k... | session.query(DbConfig).filter(DbConfig.variable == 'version').update({DbConfig.value: BITCOINLIB_VERSION}) |
Given the code snippet: <|code_start|> raise ValueError("Value uses different network (%s) then supplied network: %s" % (value.network.name, network))
value = value.value_sat
return value
class Value:
"""
Class to represent and convert cryptocurrency values
"""
@classmethod
... | dens = [den for den, symb in NETWORK_DENOMINATORS.items() if symb == denominator] |
Here is a snippet: <|code_start|> self.assertEqual(str(Quantity(121608561109507200000, 'H/s', precision=10)), '121.6085611095 EH/s')
self.assertEqual(str(Quantity(1 / 121608561109507200000, 'ots', precision=10)), '8.2231052722 zots')
self.assertEqual(str(Quantity(0.0000000001, 'm', precision=2)),... | self.assertEqual(op.op_checklocktimeverify, 177) |
Here is a snippet: <|code_start|> ('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh', 'Invalid checksum (Bech32m instead of Bech32)'),
('tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47', 'Invalid checksum (Bech32m instead of Bech32)'),
('bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow... | self.assertEqual(_bech32_polymod(hrp_expanded + data), 1, msg="Invalid checksum for address %s" % test) |
Using the snippet: <|code_start|> ('tb1z0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqglt7rf', 'Invalid checksum (Bech32 instead of Bech32m)'),
('BC1S0XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ54WELL', 'Invalid checksum (Bech32 instead of Bech32m)'),
('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeaw... | data = _codestring_to_array(test[pos + 1:], 'bech32') |
Next line prediction: <|code_start|>
def test_formatter():
"""Test if logs are being colored"""
logging.config.dictConfig(DEFAULT_LOGGING)
with LogCapture(names='bottery') as logs:
logger = logging.getLogger('bottery')
logger.debug('DEBUG')
logger.info('INFO')
logger.war... | colored_formatter = ColoredFormatter() |
Predict the next line after this snippet: <|code_start|>
logging.config.dictConfig(DEFAULT_LOGGING)
with LogCapture(names='bottery') as logs:
logger = logging.getLogger('bottery')
logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARN')
logger.error('ERROR')
... | Spinner('message') |
Given the code snippet: <|code_start|>
class CaseSensitiveOptionMixin:
def clean_case_senstive(self):
if not self.kwargs.get('case_sensitive'):
self.message.text = self.message.text.lower()
class PlatformsOptionMixin:
def clean_platforms(self):
platforms = self.kwargs.get('platfo... | raise ValidationError('message not from {}'.format(platforms)) |
Here is a snippet: <|code_start|> if inspect.iscoroutinefunction(method):
await method()
else:
method()
def sync_view(message):
return 'pong'
async def async_view(message):
return 'pong'
@pytest.mark.asyncio
@pytest.mark.parametrize('view', [sync_view, async_view], i... | assert isinstance(response, Response) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def settings():
settings = mock.Mock()
sys.modules['settings'] = settings
yield settings
del sys.modules['settings']
def test_baseengine_platform_name_not_implemented():
"""Check if attributes from the public API raise Not... | engine = BaseEngine() |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def api():
session = AsyncMock()
<|code_end|>
using the current file's imports:
import pytest
from bottery.messenger import MessengerAPI
from utils import AsyncMock
and any relevant context from other files:
# Path: bottery/messenger/api... | return MessengerAPI('token', session) |
Next line prediction: <|code_start|>
def test_startproject():
runner = CliRunner()
with runner.isolated_filesystem():
project_name = 'librarybot'
project_files = {
'handlers.py',
'settings.py',
'views.py',
'wsgi.py'
}
<|code_end|>
. Use... | result = runner.invoke(cli, ['startproject', project_name]) |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def message():
return type('Message', (), {'text': 'ping'})
@pytest.fixture
def handler():
<|code_end|>
, predict the next line using imports from the current file:
from unittest import mock
from bottery import handlers
im... | handler = type('TestHandler', (handlers.BaseHandler,), {}) |
Using the snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
<|code_end|>
, determine the next line of code. You have imports:
from django.forms.widgets import Textarea
from .._utils import HatbandTestCase
from armstrong.hatband.widgets import CKEdi... | class RichTextFieldTestCase(HatbandTestCase): |
Given the code snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
class RichTextFieldTestCase(HatbandTestCase):
def test_default(self):
ckeditor = CKEditorWidget()
<|code_end|>
, generate the next line using the imports in this file:
fr... | widget = RichTextWidget() |
Based on the snippet: <|code_start|>
TEST_SETTINGS = {
"ARMSTRONG_HATBAND_RICHTEXTEDITOR": "django.forms.widgets.Textarea",
}
class RichTextFieldTestCase(HatbandTestCase):
def test_default(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.forms.widgets import Text... | ckeditor = CKEditorWidget() |
Given the following code snippet before the placeholder: <|code_start|> ])
class ArmstrongBaseMixin(object):
url_prefix = "armstrong"
class GenericKeyFacetsMixin(ArmstrongBaseMixin):
url = "search/generickey/facets/"
def get_urls(self):
urlpatterns = patterns('',
url(r"^%s/%s$" %... | return JsonResponse(dict([(str(a), {"app_label": str(b), "id": str(c)}) |
Given the following code snippet before the placeholder: <|code_start|>
class JsonResponseTestCase(HatbandTestCase):
def test_turns_body_into_json(self):
data = {
"foo": "bar",
"random": random.randint(1000, 2000),
}
<|code_end|>
, predict the next line using imports from... | response = JsonResponse(data) |
Next line prediction: <|code_start|> float
Expected value of the metric from random ordering of targets.
"""
targets = np.copy(targets)
scores = []
for _ in range(100):
np.random.shuffle(targets)
scores.append(self.evaluate(qid, targets))
... | check_qids(qids) |
Given snippet: <|code_start|> Expected value of the metric from random ordering of targets.
"""
targets = np.copy(targets)
scores = []
for _ in range(100):
np.random.shuffle(targets)
scores.append(self.evaluate(qid, targets))
return np.mean(sco... | query_groups = get_groups(qids) |
Given snippet: <|code_start|> Returns
-------
k : int or None
Value for which ``swap_delta()[i, j] == 0 for all i, j >= k``.
None if no such value.
"""
return None
def evaluate_preds(self, qid, targets, preds):
"""Evaluates the metric on a ran... | return self.evaluate(qid, get_sorted_y(targets, preds)) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
if not len(sys.argv) > 1:
sys.stderr.write("Missing arguments\n")
sys.exit(0)
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from .reader import FileRe... | with FileReader(sys.argv[1]) as reader: |
Predict the next line for this snippet: <|code_start|>system is used to register implementations of each individual `OperationDef`.
The `OperationDef`s defined by the user in their preprocessing_fn are all
subclasses of `AnayzerDef` (except `TensorSource`, which gets converted to
`ExtractFromDict` in `tensorflow_transf... | nodes.OperationDef): |
Continue the code snippet: <|code_start|># 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.
"""Common data and utilities for tf_metadata tests."""
test_feature_spec = {
# FixedLenFeatur... | return schema_utils.schema_from_feature_spec(test_feature_spec) |
Given snippet: <|code_start|>
def schema_from_feature_spec(
feature_spec: Mapping[str, common_types.FeatureSpecType],
domains: Optional[Mapping[str, common_types.DomainType]] = None
) -> schema_pb2.Schema:
"""Convert a feature spec to a Schema proto.
Args:
feature_spec: A TensorFlow feature spec
d... | if schema_utils_legacy.should_set_generate_legacy_feature_spec(feature_spec): |
Using the snippet: <|code_start|># Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | annotators.annotate_asset('scope/my_key', 'scope/my_value') |
Predict the next line for this snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITION... | SCHEMA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... | COMPLETE_METADATA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given snippet: <|code_start|> 'native-country',
]
NUMERIC_FEATURE_KEYS = [
'age',
'capital-gain',
'capital-loss',
'hours-per-week',
]
OPTIONAL_NUMERIC_FEATURE_KEYS = [
'education-num',
]
LABEL_KEY = 'label'
ORDERED_CSV_COLUMNS = [
'age', 'workclass', 'fnlwgt', 'education', 'education-num',
... | _SCHEMA = dataset_metadata.DatasetMetadata.from_feature_spec( |
Given the code snippet: <|code_start|>class TF2UtilsTest(test_case.TransformTestCase):
def test_strip_and_get_tensors_and_control_dependencies(self):
@tf.function(input_signature=[tf.TensorSpec([], dtype=tf.int64)])
def func(x):
with tf.init_scope():
initializer_1 = tf.lookup.KeyValueTensorIni... | tf2_utils.strip_and_get_tensors_and_control_dependencies(flat_outputs)) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tensorflow_transform.tf2_utils."""
_TEST_BATCH_SIZES = [1, 10]
_TEST_DTYPES = [
tf.int16,
tf.int32,
tf.int64,
tf.float32,
tf.flo... | class TF2UtilsTest(test_case.TransformTestCase): |
Based on the snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an... | feature_spec: Mapping[str, common_types.FeatureSpecType], |
Given the code snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions a... | return cls(schema_utils.schema_from_feature_spec(feature_spec, domains)) |
Given the following code snippet before the placeholder: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either exp... | return dataset_metadata.DatasetMetadata(schema_proto) |
Continue the code snippet: <|code_start|>
def read_metadata(path):
"""Load metadata in JSON format from a path into a new DatasetMetadata."""
schema_file = os.path.join(path, 'schema.pbtxt')
legacy_schema_file = os.path.join(path, 'v1-json', 'schema.json')
if file_io.file_exists(schema_file):
text_proto = f... | return schema_utils.schema_from_feature_spec(feature_spec, domains) |
Here is a snippet: <|code_start|> x * np.exp(0.5 * hr * np.square(x)),
x * np.exp(0.5 * hl * np.square(x)))
_INVERSE_TUKEY_HH_ND_TESTS = [dict(
testcase_name='inverse_tukey_1D',
samples=np.array(
_tukey_hh(np.linspace(-5.0, 5.0, 20), 1.0, 2.0), np.float32),
hl=np.float32(1.0),
hr=np.... | outputs = gaussianization.tukey_hh_l_mean_and_scale(h_params) |
Based on the snippet: <|code_start|> expected_output=np.float32(-5.0)
)]
def _tukey_hh(x, hl, hr):
return np.where(
x > 0.0,
x * np.exp(0.5 * hr * np.square(x)),
x * np.exp(0.5 * hl * np.square(x)))
_INVERSE_TUKEY_HH_ND_TESTS = [dict(
testcase_name='inverse_tukey_1D',
samples=np.array(... | class GaussianizationTest(test_case.TransformTestCase): |
Continue the code snippet: <|code_start|># 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.
"""Tests for simple_example."""
... | class SimpleExampleTest(tft_unit.TransformTestCase): |
Based on the snippet: <|code_start|># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | saved_transform_io.write_saved_transform_from_session( |
Continue the code snippet: <|code_start|> # Check for inputs that were not part of the input signature.
unexpected_inputs = (
set(logical_input_map.keys()) - set(input_signature.keys()))
if unexpected_inputs:
raise ValueError('Unexpected inputs '
'to transform: {}'.format(unexpected_... | _ = pyfunc_helper.register_pyfuncs_from_saved_transform( |
Given the code snippet: <|code_start|> new_tensor_info.coo_sparse.indices_tensor_name = (
original_tensor_info.name)
elif original_tensor_type == 'values':
new_tensor_info.dtype = original_tensor_info.dtype
new_tensor_info.coo_sparse.values_tensor_name = (
original_t... | signature = meta_graph_def.signature_def[constants.TRANSFORM_SIGNATURE] |
Predict the next line for this snippet: <|code_start|> assert (name not in tensor_info_map or
tensor_info_map[name].WhichOneof('encoding') == 'coo_sparse')
new_tensor_info = tensor_info_map[name]
original_tensor_type = match.group(2)
if original_tensor_type == 'indices':
... | saved_model = saved_model_loader.parse_saved_model( |
Using the snippet: <|code_start|># Copyright 2022 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | test_common.test_feature_spec) |
Given the code snippet: <|code_start|> value being registered may also be a function. The registered function will
be invoked as follows:
outputs = my_function(inputs, operation, extra_args)
where inputs, operation, extra_args and outputs are the same as for the
PTransform case.
Args:
operation_def_s... | class ConstructBeamPipelineVisitor(nodes.Visitor): |
Predict the next line after this snippet: <|code_start|> return None
@classmethod
def get_passthrough_keys(cls) -> Iterable[str]:
"""Retrieves a user set passthrough_keys, None if not set."""
state = cls._get_topmost_state_frame()
if state.passthrough_keys is not None:
return state.passthrough... | return tf2_utils.use_tf_compat_v1(force_tf_compat_v1) |
Here is a snippet: <|code_start|> 'x': _FEATURE_BY_NAME['x'],
'ragged$row_lengths_1': _FEATURE_BY_NAME['ragged$row_lengths_1'],
'ragged$row_lengths_2': _FEATURE_BY_NAME['ragged$row_lengths_2'],
},
},
{
'testcase_name':
'uniform_3d',
'name':
... | if common_types.is_ragged_feature_available(): |
Given the code snippet: <|code_start|> key: "capital-gain"
value { float_list: { value: 0 } }
}
feature {
key: "capital-loss"
value { float_list: { value: 0 } }
}
feature {
key: "hours-per-week"
value { float_list: { value: 40 } }
}
feat... | class CensusExampleV2Test(tft_test_case.TransformTestCase): |
Based on the snippet: <|code_start|> # ReadTransformFn never inspects this directory.
transform_fn_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORM_FN_DIR)
transformed_metadata_dir = os.path.join(
path, tft.TFTransformOutput.TRANSFORMED_METADATA_DIR)
metadata_io.write_metadata(te... | metadata = beam_metadata_io.BeamDatasetMetadata( |
Continue the code snippet: <|code_start|># 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.
"""Tests for transform_fn_io."""
... | pipeline | transform_fn_io.ReadTransformFn(path)) |
Using the snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | metadata_io.write_metadata(test_metadata.COMPLETE_METADATA, |
Using the snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | metadata_io.write_metadata(test_metadata.COMPLETE_METADATA, |
Next line prediction: <|code_start|> @staticmethod
def _MakeAdd1CountingIdentityFn(label):
def Add1CountingIdentityFn(x_y):
(x, y) = x_y
return DeepCopyTest._CountingIdentityFn(label, (x + 1, y))
return Add1CountingIdentityFn
@staticmethod
def _InitializeCounts():
DeepCopyTest._counts ... | copied = deep_copy.deep_copy(modified) |
Using the snippet: <|code_start|># Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | return beam.Pipeline(**test_helpers.make_test_beam_pipeline_kwargs()) |
Using the snippet: <|code_start|> def tensor_fn(input1, input2):
initializer = tf.compat.v1.initializers.constant([1, 2, 3])
with tf.compat.v1.variable_scope(
'Model', reuse=None, initializer=initializer):
v1 = tf.compat.v1.get_variable('v1', [3], dtype=tf.int64)
o1 = tf.add(v1,... | output_tensor = pretrained_models.apply_saved_model( |
Based on the snippet: <|code_start|># `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
mock = tf.compat.v1.test.mock
class _Concat(
tfx_namedtuple.namedtuple('_Concat', ['label']), nodes.OperationDef):
__slots__ = ()
class _Swap(tfx_namedtuple.namedtuple('_Swap', ['label'])... | class NodesTest(test_case.TransformTestCase): |
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | saved_transform_io.write_saved_transform_from_session( |
Using the snippet: <|code_start|> def convert_dtype_and_swap(v, k):
return key_dtype_fn(k), tf.cast(v, value_dtype)
return dataset.enumerate().map(convert_dtype_and_swap)
def make_tfrecord_vocabulary_lookup_initializer(filename_tensor,
key_dtype=tf.string,... | annotators.track_object(dataset, name=None) |
Using the snippet: <|code_start|>
# TODO(https://issues.apache.org/jira/browse/SPARK-22674): Switch to
# `collections.namedtuple` or `typing.NamedTuple` once the Spark issue is
# resolved.
# pylint: disable=g-direct-tensorflow-import
# pylint: enable=g-direct-tensorflow-import
_AssetFileType = Union[tf.Tensor, str]
... | def get_values(x: common_types.TensorType) -> tf.Tensor: |
Using the snippet: <|code_start|>"""Tests for tensorflow_transform.info_theory."""
EPSILON = 1e-4
def _make_hypergeometric_pmf_sum_up_to_one_parameters():
start = 1000
end = 10000
range_length = end - start
num_chunks = 15
assert range_length % num_chunks == 0
chunk_size = int(range_length / num_chun... | results = list(info_theory._hypergeometric_pmf(4, 1, 1)) |
Predict the next line for this snippet: <|code_start|># 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.
"""Tests for tensorf... | class InfoTheoryTest(test_case.TransformTestCase): |
Based on the snippet: <|code_start|> self._schema = schema
self._delimiter = delimiter
self._secondary_delimiter = secondary_delimiter
self._encoder = self._WriterWrapper(delimiter)
if multivalent_columns is None:
multivalent_columns = []
self._multivalent_columns = multivalent_columns
... | for name, feature_spec in schema_utils.schema_as_feature_spec( |
Given snippet: <|code_start|> Args:
saved_model: A `SavedModel` protocol buffer.
tags: Set of string tags to identify the required MetaGraphDef. These should
correspond to the tags used when saving the variables using the
SavedModel `save()` API.
Returns:
The chosen `MetaGraphDef` protoco... | return _choose_meta_graph_def_internal(saved_model, [constants.TRANSFORM_TAG]) |
Using the snippet: <|code_start|>
The underlying reason for this limited support is that `tf.py_func` ops were
not designed to be serialized since they contain a reference to arbitrary
Python functions. This function pickles those functions and including them in
the graph, and `transform_raw_features` similarly... | return pyfunc_helper.insert_pyfunc(func, Tout, stateful, name, *args) |
Given snippet: <|code_start|> # TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
schema_no_sparse_features = """
{
"feature": [{
"name": "my_key",
"fixedShape": {
"axis": [{
"size": 2
}]
},
"type": "INT",
"domain... | schema=test_common.get_test_schema()) |
Given the following code snippet before the placeholder: <|code_start|> def test_read_features(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempfile.mkdtemp()
schema_no_sparse_features = """
{
"feature": [{
"name": "my_key",
"fixedShape": {
"axis": [{
... | original = dataset_metadata.DatasetMetadata( |
Continue the code snippet: <|code_start|> file_io.recursive_create_dir(version_basedir)
file_io.write_string_to_file(os.path.join(version_basedir, 'schema.json'),
schema_string)
def test_read_with_invalid_keys(self):
# TODO(b/123241798): use TEST_TMPDIR
basedir = tempf... | _ = metadata_io.read_metadata(basedir) |
Next line prediction: <|code_start|>def supply_missing_tensor(batch_size: int, tensor_shape: tf.TensorShape,
tensor_dtype: tf.DType) -> tf.Tensor:
"""Supplies a `tf.Tensor` compatible with `tensor`.
Supports only string and numeric dtypes.
Args:
batch_size: an integer representing t... | structured_inputs: Mapping[str, common_types.TensorType], |
Next line prediction: <|code_start|> """
self._schema = schema
self._serialized = serialized
# Using pre-allocated tf.train.Example and FeatureHandler objects for
# performance reasons.
#
# Since the output of "encode" is deep as opposed to shallow
# transformations, and since the schema... | elif common_types.is_ragged_feature(feature_spec): |
Next line prediction: <|code_start|> casted = self._cast_fn(values)
self._value.extend(casted)
class ExampleProtoCoder:
"""A coder between maybe-serialized TF Examples and tf.Transform datasets."""
def __init__(self, schema, serialized=True):
"""Build an ExampleProtoCoder.
Args:
schema:... | for name, feature_spec in schema_utils.schema_as_feature_spec( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.