Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>@raises(LoomError)
def test_csv_repeated_column_error(**kwargs):
modify = lambda data: [row + row for row in data]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_garbage_header_error(**kwargs):
modify = lambda data: [[GARBAGE] * len(data[0])] + data[1:]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_short_row_error(**kwargs):
modify = lambda data: data + [data[1][:1]]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_long_row_error(**kwargs):
modify = lambda data: data + [data[1] + data[1]]
_test_modify_csv(modify, **kwargs)
def _test_modify_schema(modify, name, schema, rows_csv, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR) as store:
with mock.patch('loom.store.STORE', new=store):
<|code_end|>
. Use current file imports:
import os
import csv
import mock
import numpy.random
import loom.store
import loom.format
import loom.datasets
import loom.tasks
from nose.tools import raises
from distributions.io.stream import open_compressed, json_load, json_dump
from loom.util import LoomError, tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR
and context (classes, functions, or code) from other files:
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# @contextlib.contextmanager
# def tempdir(cleanup_on_error=True):
# oldwd = os.getcwd()
# wd = tempfile.mkdtemp()
# try:
# os.chdir(wd)
# yield wd
# cleanup_on_error = True
# finally:
# os.chdir(oldwd)
# if cleanup_on_error:
# shutil.rmtree(wd)
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
. Output only the next line. | modified_schema = os.path.join(store, 'schema.json') |
Based on the snippet: <|code_start|># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
GARBAGE = 'XXX garbage XXX'
def csv_load(filename):
with open_compressed(filename) as f:
reader = csv.reader(f)
return list(reader)
def csv_dump(data, filename):
with open_compressed(filename, 'w') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
@for_each_dataset
@raises(LoomError)
def test_missing_schema_error(name, rows_csv, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR) as store:
with mock.patch('loom.store.STORE', new=store):
schema = os.path.join(store, 'missing.schema.json')
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import csv
import mock
import numpy.random
import loom.store
import loom.format
import loom.datasets
import loom.tasks
from nose.tools import raises
from distributions.io.stream import open_compressed, json_load, json_dump
from loom.util import LoomError, tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR
and context (classes, functions, sometimes code) from other files:
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# @contextlib.contextmanager
# def tempdir(cleanup_on_error=True):
# oldwd = os.getcwd()
# wd = tempfile.mkdtemp()
# try:
# os.chdir(wd)
# yield wd
# cleanup_on_error = True
# finally:
# os.chdir(oldwd)
# if cleanup_on_error:
# shutil.rmtree(wd)
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
. Output only the next line. | loom.tasks.ingest(name, schema, rows_csv, debug=True) |
Here is a snippet: <|code_start|> modify = lambda data: [row + [GARBAGE] for row in data]
_test_modify_csv(modify, **kwargs)
modify = lambda data: [[GARBAGE] + row for row in data]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_missing_column_error(**kwargs):
modify = lambda data: [row[:-1] for row in data]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_missing_header_error(**kwargs):
modify = lambda data: data[1:]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_repeated_column_error(**kwargs):
modify = lambda data: [row + row for row in data]
_test_modify_csv(modify, **kwargs)
@for_each_dataset
@raises(LoomError)
def test_csv_garbage_header_error(**kwargs):
<|code_end|>
. Write the next line using the current file imports:
import os
import csv
import mock
import numpy.random
import loom.store
import loom.format
import loom.datasets
import loom.tasks
from nose.tools import raises
from distributions.io.stream import open_compressed, json_load, json_dump
from loom.util import LoomError, tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR
and context from other files:
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# @contextlib.contextmanager
# def tempdir(cleanup_on_error=True):
# oldwd = os.getcwd()
# wd = tempfile.mkdtemp()
# try:
# os.chdir(wd)
# yield wd
# cleanup_on_error = True
# finally:
# os.chdir(oldwd)
# if cleanup_on_error:
# shutil.rmtree(wd)
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
, which may include functions, classes, or code. Output only the next line. | modify = lambda data: [[GARBAGE] * len(data[0])] + data[1:] |
Predict the next line for this snippet: <|code_start|>
def for_each_dataset(fun):
@functools.wraps(fun)
def test_one(dataset):
paths = loom.store.get_paths(dataset, sample_count=2)
for key, path in loom.store.iter_paths(dataset, paths):
if not os.path.exists(path):
raise ValueError(
'missing {} at {},\n first `python -m loom.datasets test`'
.format(key, path))
kwargs = {'name': dataset}
kwargs.update(paths['query'])
kwargs.update(paths['consensus'])
kwargs.update(paths['samples'][0])
kwargs.update(paths['ingest'])
kwargs.update(paths)
fun(**kwargs)
@functools.wraps(fun)
def test_all():
for dataset in loom.datasets.TEST_CONFIGS:
yield test_one, dataset
return test_all
def load_rows(filename):
rows = []
for string in protobuf_stream_load(filename):
row = Row()
<|code_end|>
with the help of current file imports:
import os
import functools
import loom.datasets
import loom.store
from nose.tools import assert_true
from distributions.io.stream import protobuf_stream_load
from loom.util import csv_reader
from loom.schema_pb2 import Row
and context from other files:
# Path: loom/util.py
# @contextlib.contextmanager
# def csv_reader(filename):
# with open_compressed(filename, 'rb') as f:
# yield csv.reader(f)
, which may contain function names, class names, or code. Output only the next line. | row.ParseFromString(string) |
Given snippet: <|code_start|># - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def generate_cell(possible_values, observed_prob=0.5):
if numpy.random.random() <= observed_prob:
return numpy.random.choice(possible_values)
else:
return None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy.random
import loom.store
import loom.transforms
import loom.tasks
from itertools import izip
from distributions.fileutil import tempdir
from loom.transforms import EXAMPLE_VALUES
and context:
# Path: loom/transforms.py
# EXAMPLE_VALUES = {
# 'boolean': ['0', '1', 'true', 'false'],
# 'categorical': ['Monday', 'June'],
# 'unbounded_categorical': ['CRM', '90210'],
# 'count': ['0', '1', '2', '3', '4'],
# 'real': ['-100.0', '1e-4'],
# 'sparse_real': ['0', '0', '0', '0', '123456.78', '0', '0', '0'],
# 'date': ['2014-03-31', '10pm, August 1, 1979'],
# 'text': ['This is a text feature.', 'Hello World!'],
# 'tags': ['', 'big_data machine_learning platform'],
# }
which might include code, classes, or functions. Output only the next line. | def generate_example(schema_csv, rows_csv, row_count=100): |
Next line prediction: <|code_start|> tares_in=tares,
model_in=init,
model_out=model_out,
groups_out=groups_out,
assign_out=assign_out,
log_out=log_out,
debug=True,)
if kind_structure_is_fixed:
assert_equal(len(os.listdir(groups_out)), kind_count)
group_counts = get_group_counts(groups_out)
assign_count = sum(1 for _ in protobuf_stream_load(assign_out))
assert_equal(assign_count, row_count)
print 'row_count: {}'.format(row_count)
print 'group_counts: {}'.format(' '.join(map(str, group_counts)))
for group_count in group_counts:
assert_true(
group_count <= row_count,
'groups are all singletons')
@for_each_dataset
def test_posterior_enum(name, tares, diffs, init, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
config_in = os.path.abspath('config.pb.gz')
config = {
'posterior_enum': {
<|code_end|>
. Use current file imports:
(import os
import loom.config
import loom.runner
from nose.tools import assert_equal
from nose.tools import assert_true
from loom.test.util import assert_found
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from distributions.fileutil import tempdir
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from loom.schema_pb2 import CrossCat
from loom.schema_pb2 import ProductModel)
and context including class names, function names, or small code snippets from other files:
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
. Output only the next line. | 'sample_count': 7, |
Based on the snippet: <|code_start|> 'empty_group_count': 1,
'row_queue_capacity': 0,
},
'kind': {
'iterations': 1,
'empty_kind_count': 1,
'row_queue_capacity': 0,
'score_parallel': False,
},
},
},
{
'schedule': {'extra_passes': 1.5, 'max_reject_iters': 100},
'kernels': {
'cat': {
'empty_group_count': 1,
'row_queue_capacity': 0,
},
'kind': {
'iterations': 1,
'empty_kind_count': 1,
'row_queue_capacity': 8,
'score_parallel': True,
},
},
},
]
def get_group_counts(groups_out):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import loom.config
import loom.runner
from nose.tools import assert_equal
from nose.tools import assert_true
from loom.test.util import assert_found
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from distributions.fileutil import tempdir
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from loom.schema_pb2 import CrossCat
from loom.schema_pb2 import ProductModel
and context (classes, functions, sometimes code) from other files:
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
. Output only the next line. | group_counts = [] |
Given the following code snippet before the placeholder: <|code_start|> loom.runner.shuffle(
rows_in=diffs,
rows_out=rows_out,
seed=seed)
assert_found(rows_out)
@for_each_dataset
def test_infer(name, tares, shuffled, init, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
row_count = sum(1 for _ in protobuf_stream_load(shuffled))
with open_compressed(init) as f:
message = CrossCat()
message.ParseFromString(f.read())
kind_count = len(message.kinds)
for config in CONFIGS:
loom.config.fill_in_defaults(config)
schedule = config['schedule']
print 'config: {}'.format(config)
greedy = (schedule['extra_passes'] == 0)
kind_iters = config['kernels']['kind']['iterations']
kind_structure_is_fixed = greedy or kind_iters == 0
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
config_in = os.path.abspath('config.pb.gz')
model_out = os.path.abspath('model.pb.gz')
groups_out = os.path.abspath('groups')
assign_out = os.path.abspath('assign.pbs.gz')
<|code_end|>
, predict the next line using imports from the current file:
import os
import loom.config
import loom.runner
from nose.tools import assert_equal
from nose.tools import assert_true
from loom.test.util import assert_found
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from distributions.fileutil import tempdir
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from loom.schema_pb2 import CrossCat
from loom.schema_pb2 import ProductModel
and context including class names, function names, and sometimes code from other files:
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
. Output only the next line. | log_out = os.path.abspath('log.pbs.gz') |
Given the code snippet: <|code_start|>
def synthesize_search(name, image_pos):
shape = IMAGE.shape
image = IMAGE.reshape(shape[0], shape[1], 1).repeat(3, 2)
image[image_pos] = [0, 255, 0]
with csv_reader(SAMPLES) as reader:
rows = list(reader)[1:]
rows = [map(float, r) for r in rows]
root = loom.store.get_paths(name)['root']
with loom.preql.get_server(root) as server:
x, y = to_loom_coordinates(*image_pos)
search = server.search((str(x), str(y)))
search = csv.reader(StringIO(search))
search.next()
for row_id, score in search:
score = numpy.exp(float(score))
if score < 1.:
return image
row_id = int(row_id.split(':')[1])
sample_x, sample_y = rows[row_id]
x, y = to_image_coordinates(sample_x, sample_y)
image[x, y] = [255 * (1 - 1/score), 0, 0]
return image
def synthesize_clusters(name, sample_count, cluster_count, pixel_count):
with csv_reader(SAMPLES) as reader:
reader.next()
samples = map(tuple, reader)
pts = random.sample(samples, sample_count)
<|code_end|>
, generate the next line using the imports in this file:
import os
import csv
import shutil
import random
import numpy
import numpy.random
import scipy
import scipy.misc
import scipy.ndimage
import loom.tasks
import loom.query
import loom.preql
import loom.store
import loom.datasets
import parsable
from StringIO import StringIO
from matplotlib import pyplot
from distributions.dbg.random import sample_discrete
from distributions.io.stream import open_compressed
from loom.util import csv_reader
and context (functions, classes, or occasionally code) from other files:
# Path: loom/util.py
# @contextlib.contextmanager
# def csv_reader(filename):
# with open_compressed(filename, 'rb') as f:
# yield csv.reader(f)
. Output only the next line. | samples = random.sample(samples, pixel_count) |
Here is a snippet: <|code_start|>
@for_each_dataset
def test_one_to_one(rows, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows_out.pbs.gz')
loom.runner.shuffle(
rows_in=rows,
rows_out=rows_out,
seed=seed)
assert_found(rows_out)
original = load_rows(rows)
shuffled = load_rows(rows_out)
assert_equal(len(shuffled), len(original))
assert_not_equal(shuffled, original)
actual = sorted(shuffled, key=lambda row: row.id)
expected = sorted(original, key=lambda row: row.id)
assert_list_equal(expected, actual)
@for_each_dataset
def test_chunking(rows, **unused):
targets = [10.0 ** i for i in xrange(6)]
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows.out.{}.pbs.gz')
<|code_end|>
. Write the next line using the current file imports:
import os
import loom.runner
from nose.tools import assert_equal, assert_not_equal, assert_list_equal
from loom.test.util import (
for_each_dataset,
CLEANUP_ON_ERROR,
assert_found,
load_rows,
load_rows_raw,
)
from distributions.fileutil import tempdir
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
#
# def load_rows_raw(filename):
# return list(protobuf_stream_load(filename))
, which may include functions, classes, or code. Output only the next line. | for i, target in enumerate(targets): |
Here is a snippet: <|code_start|>@for_each_dataset
def test_one_to_one(rows, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows_out.pbs.gz')
loom.runner.shuffle(
rows_in=rows,
rows_out=rows_out,
seed=seed)
assert_found(rows_out)
original = load_rows(rows)
shuffled = load_rows(rows_out)
assert_equal(len(shuffled), len(original))
assert_not_equal(shuffled, original)
actual = sorted(shuffled, key=lambda row: row.id)
expected = sorted(original, key=lambda row: row.id)
assert_list_equal(expected, actual)
@for_each_dataset
def test_chunking(rows, **unused):
targets = [10.0 ** i for i in xrange(6)]
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows.out.{}.pbs.gz')
for i, target in enumerate(targets):
loom.runner.shuffle(
<|code_end|>
. Write the next line using the current file imports:
import os
import loom.runner
from nose.tools import assert_equal, assert_not_equal, assert_list_equal
from loom.test.util import (
for_each_dataset,
CLEANUP_ON_ERROR,
assert_found,
load_rows,
load_rows_raw,
)
from distributions.fileutil import tempdir
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
#
# def load_rows_raw(filename):
# return list(protobuf_stream_load(filename))
, which may include functions, classes, or code. Output only the next line. | rows_in=rows, |
Based on the snippet: <|code_start|># may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@for_each_dataset
def test_one_to_one(rows, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows_out.pbs.gz')
loom.runner.shuffle(
rows_in=rows,
rows_out=rows_out,
seed=seed)
assert_found(rows_out)
original = load_rows(rows)
shuffled = load_rows(rows_out)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import loom.runner
from nose.tools import assert_equal, assert_not_equal, assert_list_equal
from loom.test.util import (
for_each_dataset,
CLEANUP_ON_ERROR,
assert_found,
load_rows,
load_rows_raw,
)
from distributions.fileutil import tempdir
and context (classes, functions, sometimes code) from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
#
# def load_rows_raw(filename):
# return list(protobuf_stream_load(filename))
. Output only the next line. | assert_equal(len(shuffled), len(original)) |
Given the following code snippet before the placeholder: <|code_start|>
original = load_rows(rows)
shuffled = load_rows(rows_out)
assert_equal(len(shuffled), len(original))
assert_not_equal(shuffled, original)
actual = sorted(shuffled, key=lambda row: row.id)
expected = sorted(original, key=lambda row: row.id)
assert_list_equal(expected, actual)
@for_each_dataset
def test_chunking(rows, **unused):
targets = [10.0 ** i for i in xrange(6)]
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows.out.{}.pbs.gz')
for i, target in enumerate(targets):
loom.runner.shuffle(
rows_in=rows,
rows_out=rows_out.format(i),
seed=seed,
target_mem_bytes=target)
results = [
load_rows_raw(rows_out.format(i))
for i in xrange(len(targets))
]
for i, actual in enumerate(results):
<|code_end|>
, predict the next line using imports from the current file:
import os
import loom.runner
from nose.tools import assert_equal, assert_not_equal, assert_list_equal
from loom.test.util import (
for_each_dataset,
CLEANUP_ON_ERROR,
assert_found,
load_rows,
load_rows_raw,
)
from distributions.fileutil import tempdir
and context including class names, function names, and sometimes code from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
#
# def load_rows_raw(filename):
# return list(protobuf_stream_load(filename))
. Output only the next line. | for expected in results[:i]: |
Given the code snippet: <|code_start|># BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@for_each_dataset
def test_one_to_one(rows, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
seed = 12345
rows_out = os.path.abspath('rows_out.pbs.gz')
loom.runner.shuffle(
rows_in=rows,
rows_out=rows_out,
seed=seed)
assert_found(rows_out)
original = load_rows(rows)
shuffled = load_rows(rows_out)
assert_equal(len(shuffled), len(original))
assert_not_equal(shuffled, original)
actual = sorted(shuffled, key=lambda row: row.id)
expected = sorted(original, key=lambda row: row.id)
assert_list_equal(expected, actual)
@for_each_dataset
<|code_end|>
, generate the next line using the imports in this file:
import os
import loom.runner
from nose.tools import assert_equal, assert_not_equal, assert_list_equal
from loom.test.util import (
for_each_dataset,
CLEANUP_ON_ERROR,
assert_found,
load_rows,
load_rows_raw,
)
from distributions.fileutil import tempdir
and context (functions, classes, or occasionally code) from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
#
# def load_rows_raw(filename):
# return list(protobuf_stream_load(filename))
. Output only the next line. | def test_chunking(rows, **unused): |
Here is a snippet: <|code_start|>METIS_ARGS_TEMPFILE = 'temp.metis_args.json'
Row = namedtuple('Row', ['row_id', 'group_id', 'confidence'])
def collate(pairs):
groups = defaultdict(lambda: [])
for key, value in pairs:
groups[key].append(value)
return groups.values()
def group(root, feature_name, parallel=False):
paths = loom.store.get_paths(root, sample_count=None)
map_ = parallel_map if parallel else map
groupings = map_(group_sample, [
(sample, feature_name)
for sample in paths['samples']
])
return group_reduce(groupings)
def group_sample((sample, featureid)):
model = CrossCat()
with open_compressed(sample['model']) as f:
model.ParseFromString(f.read())
for kindid, kind in enumerate(model.kinds):
if featureid in kind.featureids:
break
assignments = assignment_stream_load(sample['assign'])
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy
import pymetis
import pymetis._internal # HACK to avoid errors finding .so files in path
import loom.store
from itertools import izip
from collections import defaultdict
from collections import namedtuple
from distributions.io.stream import json_dump
from distributions.io.stream import open_compressed
from loom.schema_pb2 import CrossCat
from loom.cFormat import assignment_stream_load
from loom.util import LoomError
from loom.util import parallel_map
and context from other files:
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# Path: loom/util.py
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
, which may include functions, classes, or code. Output only the next line. | return collate((a.groupids(kindid), a.rowid) for a in assignments) |
Predict the next line after this snippet: <|code_start|>#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
METIS_ARGS_TEMPFILE = 'temp.metis_args.json'
Row = namedtuple('Row', ['row_id', 'group_id', 'confidence'])
def collate(pairs):
groups = defaultdict(lambda: [])
for key, value in pairs:
groups[key].append(value)
return groups.values()
def group(root, feature_name, parallel=False):
paths = loom.store.get_paths(root, sample_count=None)
map_ = parallel_map if parallel else map
groupings = map_(group_sample, [
<|code_end|>
using the current file's imports:
import os
import numpy
import pymetis
import pymetis._internal # HACK to avoid errors finding .so files in path
import loom.store
from itertools import izip
from collections import defaultdict
from collections import namedtuple
from distributions.io.stream import json_dump
from distributions.io.stream import open_compressed
from loom.schema_pb2 import CrossCat
from loom.cFormat import assignment_stream_load
from loom.util import LoomError
from loom.util import parallel_map
and any relevant context from other files:
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# Path: loom/util.py
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
. Output only the next line. | (sample, feature_name) |
Given the following code snippet before the placeholder: <|code_start|># notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
parsable = parsable.Parsable()
def crossvalidate_one(
seed,
test_count,
train_count,
inputs,
results,
extra_passes,
debug):
LOG('running seed {}:'.format(seed))
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy
import numpy.random
import loom.store
import loom.config
import loom.runner
import loom.generate
import loom.query
import parsable
from itertools import izip
from distributions.io.stream import (
protobuf_stream_load,
protobuf_stream_dump,
json_dump,
)
from loom.util import LOG
and context including class names, function names, and sometimes code from other files:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
. Output only the next line. | results['train'] = os.path.join( |
Predict the next line after this snippet: <|code_start|># - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
parsable = parsable.Parsable()
DEFAULTS = {
'sample_count': 10,
}
@parsable.command
def transform(
name,
schema_csv='schema.csv',
<|code_end|>
using the current file's imports:
import os
import copy
import loom
import loom.transforms
import loom.format
import loom.generate
import loom.config
import loom.consensus
import loom.runner
import loom.preql
import loom.documented
import parsable
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from loom.util import LOG
from loom.util import LoomError
from loom.util import parallel_map
and any relevant context from other files:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
#
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# Path: loom/util.py
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
. Output only the next line. | rows_csv='rows.csv.gz'): |
Given the following code snippet before the placeholder: <|code_start|># notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
parsable = parsable.Parsable()
DEFAULTS = {
'sample_count': 10,
}
@parsable.command
def transform(
name,
<|code_end|>
, predict the next line using imports from the current file:
import os
import copy
import loom
import loom.transforms
import loom.format
import loom.generate
import loom.config
import loom.consensus
import loom.runner
import loom.preql
import loom.documented
import parsable
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from loom.util import LOG
from loom.util import LoomError
from loom.util import parallel_map
and context including class names, function names, and sometimes code from other files:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
#
# Path: loom/util.py
# class LoomError(Exception):
# pass
#
# Path: loom/util.py
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
. Output only the next line. | schema_csv='schema.csv', |
Predict the next line after this snippet: <|code_start|># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SAMPLE_COUNT = 2
CONFIG = {'schedule': {'extra_passes': 2}}
@for_each_dataset
def test_all(name, schema, rows_csv, **unused):
name = os.path.join(name, 'test_tasks')
paths = loom.store.get_paths(name)
loom.datasets.clean(name)
loom.tasks.ingest(name, schema, rows_csv, debug=True)
loom.tasks.infer(
name,
sample_count=SAMPLE_COUNT,
config=CONFIG,
debug=True)
loom.tasks.make_consensus(name, debug=True)
LOG('querying')
requests = get_example_requests(
paths['samples'][0]['model'],
paths['ingest']['rows'])
with loom.tasks.query(paths['root'], debug=True) as server:
<|code_end|>
using the current file's imports:
import os
import loom.store
import loom.datasets
import loom.tasks
import loom.query
from loom.util import LOG
from loom.test.util import for_each_dataset
from loom.test.test_query import get_example_requests, check_response
and any relevant context from other files:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/test_query.py
# def get_example_requests(model, rows, query_type='mixed'):
# assert query_type in ['sample', 'score', 'mixed']
# cross_cat = CrossCat()
# with open_compressed(model, 'rb') as f:
# cross_cat.ParseFromString(f.read())
# feature_count = sum(len(kind.featureids) for kind in cross_cat.kinds)
# featureids = range(feature_count)
#
# nontrivials = [True] * feature_count
# for kind in cross_cat.kinds:
# fs = iter(kind.featureids)
# for model in loom.schema.MODELS.iterkeys():
# for shared in getattr(kind.product_model, model):
# f = fs.next()
# if model == 'dd':
# if len(shared.alphas) == 0:
# nontrivials[f] = False
# elif model == 'dpd':
# if len(shared.betas) == 0:
# nontrivials[f] = False
# all_observed = nontrivials[:]
# none_observed = [False] * feature_count
#
# observeds = []
# observeds.append(all_observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = all_observed[:]
# observed[f] = False
# observeds.append(observed)
# for f in featureids:
# observed = [
# nontrivial and sample_bernoulli(0.5)
# for nontrivial in nontrivials
# ]
# observeds.append(observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = none_observed[:]
# observed[f] = True
# observeds.append(observed)
# observeds.append(none_observed)
#
# requests = []
# for i, observed in enumerate(observeds):
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# set_diff(request.sample.data, none_observed)
# request.sample.to_sample.sparsity = DENSE
# request.sample.to_sample.dense[:] = observed
# request.sample.sample_count = 1
# if query_type in ['score', 'mixed']:
# set_diff(request.score.data, none_observed)
# requests.append(request)
# for row in load_rows(rows)[:20]:
# i += 1
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# request.sample.sample_count = 1
# request.sample.data.MergeFrom(row.diff)
# request.sample.to_sample.sparsity = DENSE
# conditions = izip(nontrivials, row.diff.pos.observed.dense)
# to_sample = [
# nontrivial and not is_observed
# for nontrivial, is_observed in conditions
# ]
# set_observed(request.sample.to_sample, to_sample)
# if query_type in ['score', 'mixed']:
# request.score.data.MergeFrom(row.diff)
# requests.append(request)
# return requests
#
# def check_response(request, response):
# assert_equal(request.id, response.id)
# assert_equal(len(response.error), 0)
. Output only the next line. | pbserver = server._query_server.protobuf_server |
Using the snippet: <|code_start|># OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SAMPLE_COUNT = 2
CONFIG = {'schedule': {'extra_passes': 2}}
@for_each_dataset
def test_all(name, schema, rows_csv, **unused):
name = os.path.join(name, 'test_tasks')
paths = loom.store.get_paths(name)
loom.datasets.clean(name)
loom.tasks.ingest(name, schema, rows_csv, debug=True)
loom.tasks.infer(
name,
sample_count=SAMPLE_COUNT,
config=CONFIG,
debug=True)
loom.tasks.make_consensus(name, debug=True)
LOG('querying')
requests = get_example_requests(
paths['samples'][0]['model'],
paths['ingest']['rows'])
with loom.tasks.query(paths['root'], debug=True) as server:
pbserver = server._query_server.protobuf_server
for request in requests:
<|code_end|>
, determine the next line of code. You have imports:
import os
import loom.store
import loom.datasets
import loom.tasks
import loom.query
from loom.util import LOG
from loom.test.util import for_each_dataset
from loom.test.test_query import get_example_requests, check_response
and context (class names, function names, or code) available:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/test_query.py
# def get_example_requests(model, rows, query_type='mixed'):
# assert query_type in ['sample', 'score', 'mixed']
# cross_cat = CrossCat()
# with open_compressed(model, 'rb') as f:
# cross_cat.ParseFromString(f.read())
# feature_count = sum(len(kind.featureids) for kind in cross_cat.kinds)
# featureids = range(feature_count)
#
# nontrivials = [True] * feature_count
# for kind in cross_cat.kinds:
# fs = iter(kind.featureids)
# for model in loom.schema.MODELS.iterkeys():
# for shared in getattr(kind.product_model, model):
# f = fs.next()
# if model == 'dd':
# if len(shared.alphas) == 0:
# nontrivials[f] = False
# elif model == 'dpd':
# if len(shared.betas) == 0:
# nontrivials[f] = False
# all_observed = nontrivials[:]
# none_observed = [False] * feature_count
#
# observeds = []
# observeds.append(all_observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = all_observed[:]
# observed[f] = False
# observeds.append(observed)
# for f in featureids:
# observed = [
# nontrivial and sample_bernoulli(0.5)
# for nontrivial in nontrivials
# ]
# observeds.append(observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = none_observed[:]
# observed[f] = True
# observeds.append(observed)
# observeds.append(none_observed)
#
# requests = []
# for i, observed in enumerate(observeds):
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# set_diff(request.sample.data, none_observed)
# request.sample.to_sample.sparsity = DENSE
# request.sample.to_sample.dense[:] = observed
# request.sample.sample_count = 1
# if query_type in ['score', 'mixed']:
# set_diff(request.score.data, none_observed)
# requests.append(request)
# for row in load_rows(rows)[:20]:
# i += 1
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# request.sample.sample_count = 1
# request.sample.data.MergeFrom(row.diff)
# request.sample.to_sample.sparsity = DENSE
# conditions = izip(nontrivials, row.diff.pos.observed.dense)
# to_sample = [
# nontrivial and not is_observed
# for nontrivial, is_observed in conditions
# ]
# set_observed(request.sample.to_sample, to_sample)
# if query_type in ['score', 'mixed']:
# request.score.data.MergeFrom(row.diff)
# requests.append(request)
# return requests
#
# def check_response(request, response):
# assert_equal(request.id, response.id)
# assert_equal(len(response.error), 0)
. Output only the next line. | pbserver.send(request) |
Given the code snippet: <|code_start|># may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SAMPLE_COUNT = 2
CONFIG = {'schedule': {'extra_passes': 2}}
@for_each_dataset
def test_all(name, schema, rows_csv, **unused):
name = os.path.join(name, 'test_tasks')
paths = loom.store.get_paths(name)
loom.datasets.clean(name)
loom.tasks.ingest(name, schema, rows_csv, debug=True)
loom.tasks.infer(
name,
sample_count=SAMPLE_COUNT,
config=CONFIG,
<|code_end|>
, generate the next line using the imports in this file:
import os
import loom.store
import loom.datasets
import loom.tasks
import loom.query
from loom.util import LOG
from loom.test.util import for_each_dataset
from loom.test.test_query import get_example_requests, check_response
and context (functions, classes, or occasionally code) from other files:
# Path: loom/util.py
# def LOG(message):
# if VERBOSITY:
# sys.stdout.write('{}\n'.format(message))
# sys.stdout.flush()
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/test_query.py
# def get_example_requests(model, rows, query_type='mixed'):
# assert query_type in ['sample', 'score', 'mixed']
# cross_cat = CrossCat()
# with open_compressed(model, 'rb') as f:
# cross_cat.ParseFromString(f.read())
# feature_count = sum(len(kind.featureids) for kind in cross_cat.kinds)
# featureids = range(feature_count)
#
# nontrivials = [True] * feature_count
# for kind in cross_cat.kinds:
# fs = iter(kind.featureids)
# for model in loom.schema.MODELS.iterkeys():
# for shared in getattr(kind.product_model, model):
# f = fs.next()
# if model == 'dd':
# if len(shared.alphas) == 0:
# nontrivials[f] = False
# elif model == 'dpd':
# if len(shared.betas) == 0:
# nontrivials[f] = False
# all_observed = nontrivials[:]
# none_observed = [False] * feature_count
#
# observeds = []
# observeds.append(all_observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = all_observed[:]
# observed[f] = False
# observeds.append(observed)
# for f in featureids:
# observed = [
# nontrivial and sample_bernoulli(0.5)
# for nontrivial in nontrivials
# ]
# observeds.append(observed)
# for f, nontrivial in izip(featureids, nontrivials):
# if nontrivial:
# observed = none_observed[:]
# observed[f] = True
# observeds.append(observed)
# observeds.append(none_observed)
#
# requests = []
# for i, observed in enumerate(observeds):
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# set_diff(request.sample.data, none_observed)
# request.sample.to_sample.sparsity = DENSE
# request.sample.to_sample.dense[:] = observed
# request.sample.sample_count = 1
# if query_type in ['score', 'mixed']:
# set_diff(request.score.data, none_observed)
# requests.append(request)
# for row in load_rows(rows)[:20]:
# i += 1
# request = Query.Request()
# request.id = "example-{}".format(i)
# if query_type in ['sample', 'mixed']:
# request.sample.sample_count = 1
# request.sample.data.MergeFrom(row.diff)
# request.sample.to_sample.sparsity = DENSE
# conditions = izip(nontrivials, row.diff.pos.observed.dense)
# to_sample = [
# nontrivial and not is_observed
# for nontrivial, is_observed in conditions
# ]
# set_observed(request.sample.to_sample, to_sample)
# if query_type in ['score', 'mixed']:
# request.score.data.MergeFrom(row.diff)
# requests.append(request)
# return requests
#
# def check_response(request, response):
# assert_equal(request.id, response.id)
# assert_equal(len(response.error), 0)
. Output only the next line. | debug=True) |
Using the snippet: <|code_start|># FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SAMPLE_COUNT = 1000
class CsvWriter(object):
def __init__(self, outfile, returns=None):
writer = csv.writer(outfile)
self.writerow = writer.writerow
self.writerows = writer.writerows
self.result = returns if returns else lambda: None
@contextmanager
def csv_output(arg):
if arg is None:
outfile = StringIO()
yield CsvWriter(outfile, returns=outfile.getvalue)
elif hasattr(arg, 'write'):
yield CsvWriter(arg)
else:
with open_compressed(arg, 'w') as outfile:
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy
from contextlib import contextmanager
from itertools import izip
from collections import Counter
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from StringIO import StringIO
from sklearn.cluster import SpectralClustering
from loom.format import load_decoder
from loom.format import load_encoder
import csv
import math
import numpy
import loom.store
import loom.query
import loom.group
and context (class names, function names, or code) available:
# Path: loom/format.py
# def load_decoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# decoder = {value: key for key, value in encoder['symbols'].iteritems()}
# decode = decoder.__getitem__
# elif model == 'bb':
# decode = ('0', '1').__getitem__
# else:
# decode = str
# return decode
#
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
. Output only the next line. | yield CsvWriter(outfile) |
Using the snippet: <|code_start|># FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SAMPLE_COUNT = 1000
class CsvWriter(object):
def __init__(self, outfile, returns=None):
writer = csv.writer(outfile)
self.writerow = writer.writerow
self.writerows = writer.writerows
self.result = returns if returns else lambda: None
@contextmanager
def csv_output(arg):
if arg is None:
outfile = StringIO()
yield CsvWriter(outfile, returns=outfile.getvalue)
elif hasattr(arg, 'write'):
yield CsvWriter(arg)
else:
with open_compressed(arg, 'w') as outfile:
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy
from contextlib import contextmanager
from itertools import izip
from collections import Counter
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from StringIO import StringIO
from sklearn.cluster import SpectralClustering
from loom.format import load_decoder
from loom.format import load_encoder
import csv
import math
import numpy
import loom.store
import loom.query
import loom.group
and context (class names, function names, or code) available:
# Path: loom/format.py
# def load_decoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# decoder = {value: key for key, value in encoder['symbols'].iteritems()}
# decode = decoder.__getitem__
# elif model == 'bb':
# decode = ('0', '1').__getitem__
# else:
# decode = str
# return decode
#
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
. Output only the next line. | yield CsvWriter(outfile) |
Using the snippet: <|code_start|>def test_relate(root, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
with loom.preql.get_server(root, debug=True) as preql:
result_out = 'related_out.csv'
preql.relate(preql.feature_names, result_out, sample_count=10)
with open(result_out, 'r') as f:
reader = csv.reader(f)
header = reader.next()
columns = header[1:]
assert_equal(columns, preql.feature_names)
zmatrix = numpy.zeros((len(columns), len(columns)))
for i, row in enumerate(reader):
column = row.pop(0)
assert_equal(column, preql.feature_names[i])
for j, score in enumerate(row):
score = float(score)
zmatrix[i][j] = score
assert_close(zmatrix, zmatrix.T)
@for_each_dataset
def test_relate_pandas(root, rows_csv, schema, **unused):
feature_count = len(json_load(schema))
with loom.preql.get_server(root, debug=True) as preql:
result_string = preql.relate(preql.feature_names)
result_df = pandas.read_csv(StringIO(result_string), index_col=0)
print 'result_df ='
print result_df
assert_equal(result_df.ndim, 2)
assert_equal(result_df.shape[0], feature_count)
<|code_end|>
, determine the next line of code. You have imports:
import os
import csv
import numpy
import pandas
import loom.preql
from itertools import izip
from StringIO import StringIO
from nose import SkipTest
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import assert_true
from distributions.fileutil import tempdir
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.format import load_encoder
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from loom.test.util import load_rows_csv
and context (class names, function names, or code) available:
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# def load_rows_csv(dirname):
# filenames = os.listdir(dirname)
# rows = [None]
# for filename in filenames:
# filename = os.path.join(dirname, filename)
# with csv_reader(filename) as reader:
# header = reader.next()
# rows += reader
# rows[0] = header
# return rows
. Output only the next line. | assert_equal(result_df.shape[1], feature_count) |
Based on the snippet: <|code_start|> if observed:
assert_almost_equal(
encode(in_val),
encode(out_val))
else:
assert_true(bool(out_val.strip()))
@for_each_dataset
def test_predict(root, rows_csv, encoding, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
with loom.preql.get_server(root, debug=True) as preql:
result_out = 'predictions_out.csv'
rows_in = os.listdir(rows_csv)[0]
rows_in = os.path.join(rows_csv, rows_in)
preql.predict(rows_in, COUNT, result_out, id_offset=True)
print 'DEBUG', open_compressed(rows_in).read()
print 'DEBUG', open_compressed(result_out).read()
_check_predictions(rows_in, result_out, encoding)
@for_each_dataset
def test_predict_pandas(root, rows_csv, schema, **unused):
feature_count = len(json_load(schema))
with loom.preql.get_server(root, debug=True) as preql:
rows_filename = os.path.join(rows_csv, os.listdir(rows_csv)[0])
with open_compressed(rows_filename) as f:
rows_df = pandas.read_csv(
f,
converters=preql.converters,
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import csv
import numpy
import pandas
import loom.preql
from itertools import izip
from StringIO import StringIO
from nose import SkipTest
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import assert_true
from distributions.fileutil import tempdir
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.format import load_encoder
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from loom.test.util import load_rows_csv
and context (classes, functions, sometimes code) from other files:
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# def load_rows_csv(dirname):
# filenames = os.listdir(dirname)
# rows = [None]
# for filename in filenames:
# filename = os.path.join(dirname, filename)
# with csv_reader(filename) as reader:
# header = reader.next()
# rows += reader
# rows[0] = header
# return rows
. Output only the next line. | index_col='_id') |
Here is a snippet: <|code_start|> [features[0], features[1]],
[features[2]]]
observed_feature_sets = [
[features[0], features[1]],
[features[2]],
[features[3]]]
preql.support(
target_feature_sets,
observed_feature_sets,
conditions)
conditions[5] = None
preql.support(
target_feature_sets,
observed_feature_sets,
conditions)
conditions[0] = None
assert_raises(
ValueError,
preql.support,
target_feature_sets,
observed_feature_sets,
conditions)
@for_each_dataset
def test_support_shape(root, rows_csv, **unused):
with loom.preql.get_server(root, debug=True) as preql:
features = preql.feature_names
conditioning_row = make_fully_observed_row(rows_csv)
target_sets = [
<|code_end|>
. Write the next line using the current file imports:
import os
import csv
import numpy
import pandas
import loom.preql
from itertools import izip
from StringIO import StringIO
from nose import SkipTest
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import assert_true
from distributions.fileutil import tempdir
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.format import load_encoder
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from loom.test.util import load_rows_csv
and context from other files:
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# def load_rows_csv(dirname):
# filenames = os.listdir(dirname)
# rows = [None]
# for filename in filenames:
# filename = os.path.join(dirname, filename)
# with csv_reader(filename) as reader:
# header = reader.next()
# rows += reader
# rows[0] = header
# return rows
, which may include functions, classes, or code. Output only the next line. | features[2 * i: 2 * (i + 1)] |
Predict the next line after this snippet: <|code_start|> continue
encode = name_to_encoder[name]
observed = bool(in_val.strip())
if observed:
assert_almost_equal(
encode(in_val),
encode(out_val))
else:
assert_true(bool(out_val.strip()))
@for_each_dataset
def test_predict(root, rows_csv, encoding, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
with loom.preql.get_server(root, debug=True) as preql:
result_out = 'predictions_out.csv'
rows_in = os.listdir(rows_csv)[0]
rows_in = os.path.join(rows_csv, rows_in)
preql.predict(rows_in, COUNT, result_out, id_offset=True)
print 'DEBUG', open_compressed(rows_in).read()
print 'DEBUG', open_compressed(result_out).read()
_check_predictions(rows_in, result_out, encoding)
@for_each_dataset
def test_predict_pandas(root, rows_csv, schema, **unused):
feature_count = len(json_load(schema))
with loom.preql.get_server(root, debug=True) as preql:
rows_filename = os.path.join(rows_csv, os.listdir(rows_csv)[0])
with open_compressed(rows_filename) as f:
<|code_end|>
using the current file's imports:
import os
import csv
import numpy
import pandas
import loom.preql
from itertools import izip
from StringIO import StringIO
from nose import SkipTest
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import assert_true
from distributions.fileutil import tempdir
from distributions.io.stream import json_load
from distributions.io.stream import open_compressed
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.format import load_encoder
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import for_each_dataset
from loom.test.util import load_rows_csv
and any relevant context from other files:
# Path: loom/format.py
# def load_encoder(encoder):
# model = encoder['model']
# if 'symbols' in encoder:
# encode = encoder['symbols'].__getitem__
# elif model == 'bb':
# encode = BOOLEAN_SYMBOLS.__getitem__
# else:
# encode = loom.schema.MODELS[model].Value
# return encode
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# def load_rows_csv(dirname):
# filenames = os.listdir(dirname)
# rows = [None]
# for filename in filenames:
# filename = os.path.join(dirname, filename)
# with csv_reader(filename) as reader:
# header = reader.next()
# rows += reader
# rows[0] = header
# return rows
. Output only the next line. | rows_df = pandas.read_csv( |
Predict the next line for this snippet: <|code_start|># FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
S3_URL = 's3://pk-dsp/taxi-data/partitioned/geocoded'
ROOT = os.path.dirname(os.path.abspath(__file__))
SCHEMA = os.path.join(ROOT, 'schema.json')
EXAMPLE = os.path.join(ROOT, 'example.csv')
ROWS_CSV = os.path.join(ROOT, 'rows_csv')
def s3_split(url):
bucket, path = re.match(r's3://([^/]*)/(.*)', S3_URL).group(1, 2)
return bucket, path
def s3_get((bucket, source, destin)):
try:
print 'starting {}'.format(source)
conn = boto.connect_s3().get_bucket(bucket)
key = conn.get_key(source)
key.get_contents_to_filename(destin)
print 'finished {}'.format(source)
<|code_end|>
with the help of current file imports:
import os
import re
import parsable
import loom.datasets
import loom.tasks
import boto
import boto
from itertools import izip
from loom.util import mkdir_p, rm_rf, parallel_map
and context from other files:
# Path: loom/util.py
# def mkdir_p(dirname):
# 'like mkdir -p'
# if not os.path.exists(dirname):
# try:
# os.makedirs(dirname)
# except OSError as e:
# if not os.path.exists(dirname):
# raise e
#
# def rm_rf(path):
# 'like rm -rf'
# if os.path.exists(path):
# if os.path.isdir(path):
# shutil.rmtree(path)
# else:
# os.remove(path)
#
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
, which may contain function names, class names, or code. Output only the next line. | except: |
Given the following code snippet before the placeholder: <|code_start|># Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
S3_URL = 's3://pk-dsp/taxi-data/partitioned/geocoded'
ROOT = os.path.dirname(os.path.abspath(__file__))
SCHEMA = os.path.join(ROOT, 'schema.json')
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import parsable
import loom.datasets
import loom.tasks
import boto
import boto
from itertools import izip
from loom.util import mkdir_p, rm_rf, parallel_map
and context including class names, function names, and sometimes code from other files:
# Path: loom/util.py
# def mkdir_p(dirname):
# 'like mkdir -p'
# if not os.path.exists(dirname):
# try:
# os.makedirs(dirname)
# except OSError as e:
# if not os.path.exists(dirname):
# raise e
#
# def rm_rf(path):
# 'like rm -rf'
# if os.path.exists(path):
# if os.path.isdir(path):
# shutil.rmtree(path)
# else:
# os.remove(path)
#
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
. Output only the next line. | EXAMPLE = os.path.join(ROOT, 'example.csv') |
Predict the next line after this snippet: <|code_start|># may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
S3_URL = 's3://pk-dsp/taxi-data/partitioned/geocoded'
ROOT = os.path.dirname(os.path.abspath(__file__))
SCHEMA = os.path.join(ROOT, 'schema.json')
EXAMPLE = os.path.join(ROOT, 'example.csv')
ROWS_CSV = os.path.join(ROOT, 'rows_csv')
def s3_split(url):
bucket, path = re.match(r's3://([^/]*)/(.*)', S3_URL).group(1, 2)
return bucket, path
def s3_get((bucket, source, destin)):
<|code_end|>
using the current file's imports:
import os
import re
import parsable
import loom.datasets
import loom.tasks
import boto
import boto
from itertools import izip
from loom.util import mkdir_p, rm_rf, parallel_map
and any relevant context from other files:
# Path: loom/util.py
# def mkdir_p(dirname):
# 'like mkdir -p'
# if not os.path.exists(dirname):
# try:
# os.makedirs(dirname)
# except OSError as e:
# if not os.path.exists(dirname):
# raise e
#
# def rm_rf(path):
# 'like rm -rf'
# if os.path.exists(path):
# if os.path.isdir(path):
# shutil.rmtree(path)
# else:
# os.remove(path)
#
# def parallel_map(fun, args):
# if not isinstance(args, list):
# args = list(args)
# is_daemon = multiprocessing.current_process().daemon
# if THREADS == 1 or len(args) < 2 or is_daemon:
# print 'Running {} in this thread'.format(fun.__name__)
# return map(fun, args)
# else:
# print 'Running {} in {:d} threads'.format(fun.__name__, THREADS)
# pool = multiprocessing.Pool(THREADS)
# fun_args = [(fun, arg) for arg in args]
# return pool.map(print_trace, fun_args, chunksize=1)
. Output only the next line. | try: |
Next line prediction: <|code_start|># TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
FEATURE_TYPES = loom.schema.MODELS.keys()
FEATURE_TYPES += ['mixed']
def test_generate():
for feature_type in FEATURE_TYPES:
yield _test_generate, feature_type
def _test_generate(feature_type):
root = os.getcwd()
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
init_out = os.path.abspath('init.pb.gz')
rows_out = os.path.abspath('rows.pbs.gz')
model_out = os.path.abspath('model.pb.gz')
groups_out = os.path.abspath('groups')
os.chdir(root)
loom.generate.generate(
feature_type=feature_type,
row_count=100,
feature_count=100,
density=0.5,
init_out=init_out,
rows_out=rows_out,
model_out=model_out,
groups_out=groups_out,
<|code_end|>
. Use current file imports:
(import os
import loom.generate
from distributions.fileutil import tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR, assert_found)
and context including class names, function names, or small code snippets from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
. Output only the next line. | debug=True, |
Predict the next line for this snippet: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
FEATURE_TYPES = loom.schema.MODELS.keys()
FEATURE_TYPES += ['mixed']
def test_generate():
for feature_type in FEATURE_TYPES:
yield _test_generate, feature_type
def _test_generate(feature_type):
root = os.getcwd()
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
init_out = os.path.abspath('init.pb.gz')
rows_out = os.path.abspath('rows.pbs.gz')
model_out = os.path.abspath('model.pb.gz')
groups_out = os.path.abspath('groups')
os.chdir(root)
loom.generate.generate(
<|code_end|>
with the help of current file imports:
import os
import loom.generate
from distributions.fileutil import tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR, assert_found
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
, which may contain function names, class names, or code. Output only the next line. | feature_type=feature_type, |
Predict the next line for this snippet: <|code_start|># BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
FEATURE_TYPES = loom.schema.MODELS.keys()
FEATURE_TYPES += ['mixed']
def test_generate():
for feature_type in FEATURE_TYPES:
yield _test_generate, feature_type
def _test_generate(feature_type):
root = os.getcwd()
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
init_out = os.path.abspath('init.pb.gz')
rows_out = os.path.abspath('rows.pbs.gz')
model_out = os.path.abspath('model.pb.gz')
groups_out = os.path.abspath('groups')
os.chdir(root)
loom.generate.generate(
feature_type=feature_type,
row_count=100,
feature_count=100,
density=0.5,
init_out=init_out,
<|code_end|>
with the help of current file imports:
import os
import loom.generate
from distributions.fileutil import tempdir
from loom.test.util import for_each_dataset, CLEANUP_ON_ERROR, assert_found
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
, which may contain function names, class names, or code. Output only the next line. | rows_out=rows_out, |
Here is a snippet: <|code_start|>@for_each_dataset
def test_score_derivative_against_existing_runs(root, rows, **unused):
with loom.query.get_server(root, debug=True) as server:
rows = load_rows(rows)
target_row = protobuf_to_data_row(rows[0].diff)
results = server.score_derivative(
target_row,
score_rows=None)
assert len(rows) == len(results)
results = server.score_derivative(
target_row,
score_rows=None,
row_limit=1)
assert len(results) == 1
@for_each_dataset
def test_seed(root, model, rows, **unused):
requests = get_example_requests(model, rows, 'mixed')
with tempdir():
loom.config.config_dump({'seed': 0}, 'config.pb.gz')
with loom.query.ProtobufServer(root, config='config.pb.gz') as server:
responses1 = [get_response(server, req) for req in requests]
with tempdir():
loom.config.config_dump({'seed': 0}, 'config.pb.gz')
with loom.query.ProtobufServer(root, config='config.pb.gz') as server:
responses2 = [get_response(server, req) for req in requests]
with tempdir():
<|code_end|>
. Write the next line using the current file imports:
from itertools import izip
from nose.tools import assert_true, assert_equal, assert_not_equal
from distributions.dbg.random import sample_bernoulli
from distributions.io.stream import open_compressed
from distributions.fileutil import tempdir
from loom.schema_pb2 import ProductValue, CrossCat, Query
from loom.test.util import for_each_dataset
from loom.query import protobuf_to_data_row
from loom.test.util import load_rows
import loom.query
import loom.config
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/query.py
# def protobuf_to_data_row(diff):
# assert isinstance(diff, ProductValue.Diff)
# assert diff.neg.observed.sparsity == NONE
# data = diff.pos
# packed = chain(data.booleans, data.counts, data.reals)
# return [
# packed.next() if observed else None
# for observed in data.observed.dense
# ]
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
, which may include functions, classes, or code. Output only the next line. | loom.config.config_dump({'seed': 10}, 'config.pb.gz') |
Predict the next line for this snippet: <|code_start|> target_row = protobuf_to_data_row(rows[0].diff)
score_rows = [protobuf_to_data_row(r.diff) for r in rows[:2]]
results = server.score_derivative(target_row, score_rows)
assert len(results) == len(score_rows)
@for_each_dataset
def test_score_derivative_against_existing_runs(root, rows, **unused):
with loom.query.get_server(root, debug=True) as server:
rows = load_rows(rows)
target_row = protobuf_to_data_row(rows[0].diff)
results = server.score_derivative(
target_row,
score_rows=None)
assert len(rows) == len(results)
results = server.score_derivative(
target_row,
score_rows=None,
row_limit=1)
assert len(results) == 1
@for_each_dataset
def test_seed(root, model, rows, **unused):
requests = get_example_requests(model, rows, 'mixed')
with tempdir():
loom.config.config_dump({'seed': 0}, 'config.pb.gz')
with loom.query.ProtobufServer(root, config='config.pb.gz') as server:
responses1 = [get_response(server, req) for req in requests]
<|code_end|>
with the help of current file imports:
from itertools import izip
from nose.tools import assert_true, assert_equal, assert_not_equal
from distributions.dbg.random import sample_bernoulli
from distributions.io.stream import open_compressed
from distributions.fileutil import tempdir
from loom.schema_pb2 import ProductValue, CrossCat, Query
from loom.test.util import for_each_dataset
from loom.query import protobuf_to_data_row
from loom.test.util import load_rows
import loom.query
import loom.config
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/query.py
# def protobuf_to_data_row(diff):
# assert isinstance(diff, ProductValue.Diff)
# assert diff.neg.observed.sparsity == NONE
# data = diff.pos
# packed = chain(data.booleans, data.counts, data.reals)
# return [
# packed.next() if observed else None
# for observed in data.observed.dense
# ]
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
, which may contain function names, class names, or code. Output only the next line. | with tempdir(): |
Given snippet: <|code_start|> request.sample.sample_count = 1
if query_type in ['score', 'mixed']:
set_diff(request.score.data, none_observed)
requests.append(request)
for row in load_rows(rows)[:20]:
i += 1
request = Query.Request()
request.id = "example-{}".format(i)
if query_type in ['sample', 'mixed']:
request.sample.sample_count = 1
request.sample.data.MergeFrom(row.diff)
request.sample.to_sample.sparsity = DENSE
conditions = izip(nontrivials, row.diff.pos.observed.dense)
to_sample = [
nontrivial and not is_observed
for nontrivial, is_observed in conditions
]
set_observed(request.sample.to_sample, to_sample)
if query_type in ['score', 'mixed']:
request.score.data.MergeFrom(row.diff)
requests.append(request)
return requests
def check_response(request, response):
assert_equal(request.id, response.id)
assert_equal(len(response.error), 0)
def get_response(server, request):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from itertools import izip
from nose.tools import assert_true, assert_equal, assert_not_equal
from distributions.dbg.random import sample_bernoulli
from distributions.io.stream import open_compressed
from distributions.fileutil import tempdir
from loom.schema_pb2 import ProductValue, CrossCat, Query
from loom.test.util import for_each_dataset
from loom.query import protobuf_to_data_row
from loom.test.util import load_rows
import loom.query
import loom.config
and context:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/query.py
# def protobuf_to_data_row(diff):
# assert isinstance(diff, ProductValue.Diff)
# assert diff.neg.observed.sparsity == NONE
# data = diff.pos
# packed = chain(data.booleans, data.counts, data.reals)
# return [
# packed.next() if observed else None
# for observed in data.observed.dense
# ]
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
which might include code, classes, or functions. Output only the next line. | server.send(request) |
Predict the next line after this snippet: <|code_start|> args = map(str, command[1:])
command = PROFILERS[profile] + bin_ + args
return subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
bufsize=-1)
def check_call(command, debug, profile, **kwargs):
profile = str(profile).lower()
if command[0] == 'python':
bin_ = [PYTHON] if debug else [PYTHON, '-O']
else:
bin_pattern = 'loom_{}_debug' if debug else 'loom_{}'
bin_ = [which(bin_pattern.format(command[0]))]
args = map(str, command[1:])
command = PROFILERS[profile] + bin_ + args
if profile != 'none':
retcode = subprocess.Popen(command, **kwargs).wait()
print 'Program returned {}'.format(retcode)
else:
if debug:
print ' \\\n '.join(command)
subprocess.check_call(command, **kwargs)
def check_call_files(command, debug, profile, infiles=[], outfiles=[]):
assert_found(infiles)
make_dirs_for(outfiles)
<|code_end|>
using the current file's imports:
import os
import sys
import subprocess
import parsable
import loom.documented
import loom.config
import loom.store
from loom.config import DEFAULTS
and any relevant context from other files:
# Path: loom/config.py
# DEFAULTS = {
# 'seed': 0,
# 'target_mem_bytes': 4e9,
# 'schedule': {
# 'extra_passes': 500.0,
# 'small_data_size': 4e3,
# 'big_data_size': 1e9,
# 'max_reject_iters': 100,
# 'checkpoint_period_sec': 1e9,
# },
# 'kernels': {
# 'cat': {
# 'empty_group_count': 1,
# 'row_queue_capacity': 255,
# 'parser_threads': 6,
# },
# 'hyper': {
# 'run': True,
# 'parallel': True,
# },
# 'kind': {
# 'iterations': 32,
# 'empty_kind_count': 32,
# 'row_queue_capacity': 255,
# 'parser_threads': 6,
# 'score_parallel': True,
# },
# },
# 'posterior_enum': {
# 'sample_count': 100,
# 'sample_skip': 10,
# },
# 'generate': {
# 'row_count': 100,
# 'density': 0.5,
# 'sample_skip': 10,
# },
# 'query': {
# 'parallel': True,
# },
# }
. Output only the next line. | check_call(command, debug, profile) |
Predict the next line for this snippet: <|code_start|>
SAMPLE_COUNT = 500
# tests are inaccurate with highly imbalanced data
MIN_CATEGORICAL_PROB = .03
SEED = 1234
@for_each_dataset
def test_score_none(root, encoding, **unused):
with loom.query.get_server(root, debug=True) as server:
preql = loom.preql.PreQL(server, encoding)
fnames = preql.feature_names
assert_less(
abs(server.score([None for _ in fnames])),
SCORE_TOLERANCE)
def _check_marginal_samples_match_scores(server, row, fi):
row = loom.query.protobuf_to_data_row(row.diff)
row[fi] = None
to_sample = [i == fi for i in range(len(row))]
samples = server.sample(to_sample, row, SAMPLE_COUNT)
val = samples[0][fi]
base_score = server.score(row)
if isinstance(val, bool) or isinstance(val, int):
probs_dict = {}
samples = [sample[fi] for sample in samples]
for sample in set(samples):
<|code_end|>
with the help of current file imports:
import numpy
import loom.datasets
import loom.preql
import loom.query
from math import log
from nose.tools import assert_almost_equal
from nose.tools import assert_greater
from nose.tools import assert_less
from nose.tools import assert_less_equal
from distributions.fileutil import tempdir
from distributions.util import density_goodness_of_fit
from distributions.util import discrete_goodness_of_fit
from loom.test.util import for_each_dataset, load_rows
and context from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
, which may contain function names, class names, or code. Output only the next line. | row[fi] = sample |
Given the code snippet: <|code_start|> to_sample = [i == fi for i in range(len(row))]
samples = server.sample(to_sample, row, SAMPLE_COUNT)
val = samples[0][fi]
base_score = server.score(row)
if isinstance(val, bool) or isinstance(val, int):
probs_dict = {}
samples = [sample[fi] for sample in samples]
for sample in set(samples):
row[fi] = sample
probs_dict[sample] = numpy.exp(
server.score(row) - base_score)
if len(probs_dict) == 1:
assert_almost_equal(probs_dict[sample], 1., places=SCORE_PLACES)
return
if min(probs_dict.values()) < MIN_CATEGORICAL_PROB:
return
gof = discrete_goodness_of_fit(samples, probs_dict, plot=True)
elif isinstance(val, float):
probs = numpy.exp([
server.score(sample) - base_score
for sample in samples
])
samples = [sample[fi] for sample in samples]
gof = density_goodness_of_fit(samples, probs, plot=True)
assert_greater(gof, MIN_GOODNESS_OF_FIT)
@for_each_dataset
def test_samples_match_scores(root, rows, **unused):
rows = load_rows(rows)
<|code_end|>
, generate the next line using the imports in this file:
import numpy
import loom.datasets
import loom.preql
import loom.query
from math import log
from nose.tools import assert_almost_equal
from nose.tools import assert_greater
from nose.tools import assert_less
from nose.tools import assert_less_equal
from distributions.fileutil import tempdir
from distributions.util import density_goodness_of_fit
from distributions.util import discrete_goodness_of_fit
from loom.test.util import for_each_dataset, load_rows
and context (functions, classes, or occasionally code) from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
. Output only the next line. | rows = rows[::len(rows) / 5] |
Here is a snippet: <|code_start|> 'alpha': [0.5, 2.0],
'beta': [0.5, 2.0],
},
'dd': {
'alpha': [.5, 1.5],
},
'dpd': {
'alpha': [.5, 1.5],
'gamma': [.5, 1.5],
},
'gp': {
'alpha': [.5, 1.5],
'inv_beta': [.5, 1.5],
},
'nich': {
'kappa': [.5, 1.5],
'mu': [-1., 1.],
'nu': [.5, 1.5],
'sigmasq': [.5, 1.5],
}
}
CLUSTERING = PitmanYor.from_dict({'alpha': 2.0, 'd': 0.1})
if __name__ == '__main__' and sys.stdout.isatty():
colorize = {
'Info': '\x1b[34mInfo\x1b[0m',
'Warn': '\x1b[33mWarn\x1b[0m',
'Fail': '\x1b[31mFail\x1b[0m',
'Pass': '\x1b[32mPass\x1b[0m',
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import numpy
import numpy.random
import loom.schema_pb2
import loom.schema
import loom.format
import loom.runner
import loom.util
import loom.test.util
import parsable
from itertools import imap, product
from nose import SkipTest
from nose.tools import assert_true, assert_false, assert_equal
from distributions.tests.util import seed_all
from distributions.util import scores_to_probs
from distributions.io.stream import protobuf_stream_load, protobuf_stream_dump
from distributions.lp.clustering import PitmanYor
from distributions.util import multinomial_goodness_of_fit
from loom.util import tempdir
and context from other files:
# Path: loom/util.py
# @contextlib.contextmanager
# def tempdir(cleanup_on_error=True):
# oldwd = os.getcwd()
# wd = tempfile.mkdtemp()
# try:
# os.chdir(wd)
# yield wd
# cleanup_on_error = True
# finally:
# os.chdir(oldwd)
# if cleanup_on_error:
# shutil.rmtree(wd)
, which may include functions, classes, or code. Output only the next line. | } |
Continue the code snippet: <|code_start|>
@for_each_dataset
def test_make_schema(model, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
schema_out = os.path.abspath('schema.json.gz')
loom.format.make_schema(
model_in=model,
schema_out=schema_out)
assert_found(schema_out)
@for_each_dataset
def test_make_fake_encoding(schema, model, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
encoding_out = os.path.abspath('encoding.json.gz')
loom.format.make_fake_encoding(
schema_in=schema,
model_in=model,
encoding_out=encoding_out)
assert_found(encoding_out)
@for_each_dataset
def test_make_encoding(schema, rows_csv, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
encoding = os.path.abspath('encoding.json.gz')
rows = os.path.abspath('rows.pbs.gz')
loom.format.make_encoding(
schema_in=schema,
rows_in=rows_csv,
<|code_end|>
. Use current file imports:
import os
import loom.format
import loom.util
from nose.tools import assert_equal
from distributions.fileutil import tempdir
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.test.util import for_each_dataset
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import assert_found
from loom.test.util import load_rows
and context (classes, functions, or code) from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
. Output only the next line. | encoding_out=encoding) |
Given the following code snippet before the placeholder: <|code_start|> assert_equal(encode(key), value)
def test_load_decoder():
encoder = loom.format.EXAMPLE_CATEGORICAL_ENCODER
decode = loom.format.load_decoder(encoder)
for key, value in encoder['symbols'].iteritems():
assert_equal(decode(value), key)
@for_each_dataset
def test_import_rows(encoding, rows, rows_csv, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
rows_pbs = os.path.abspath('rows.pbs.gz')
loom.format.import_rows(
encoding_in=encoding,
rows_csv_in=rows_csv,
rows_out=rows_pbs)
assert_found(rows_pbs)
expected_count = sum(1 for _ in protobuf_stream_load(rows))
actual_count = sum(1 for _ in protobuf_stream_load(rows_pbs))
assert_equal(actual_count, expected_count)
@for_each_dataset
def test_export_rows(encoding, rows, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
rows_csv = os.path.abspath('rows_csv')
rows_pbs = os.path.abspath('rows.pbs.gz')
loom.format.export_rows(
<|code_end|>
, predict the next line using imports from the current file:
import os
import loom.format
import loom.util
from nose.tools import assert_equal
from distributions.fileutil import tempdir
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.test.util import for_each_dataset
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import assert_found
from loom.test.util import load_rows
and context including class names, function names, and sometimes code from other files:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
. Output only the next line. | encoding_in=encoding, |
Using the snippet: <|code_start|> with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
encoding = os.path.abspath('encoding.json.gz')
rows = os.path.abspath('rows.pbs.gz')
loom.format.make_encoding(
schema_in=schema,
rows_in=rows_csv,
encoding_out=encoding)
assert_found(encoding)
loom.format.import_rows(
encoding_in=encoding,
rows_csv_in=rows_csv,
rows_out=rows)
assert_found(rows)
def test_load_encoder():
encoder = loom.format.EXAMPLE_CATEGORICAL_ENCODER
encode = loom.format.load_encoder(encoder)
for key, value in encoder['symbols'].iteritems():
assert_equal(encode(key), value)
def test_load_decoder():
encoder = loom.format.EXAMPLE_CATEGORICAL_ENCODER
decode = loom.format.load_decoder(encoder)
for key, value in encoder['symbols'].iteritems():
assert_equal(decode(value), key)
@for_each_dataset
<|code_end|>
, determine the next line of code. You have imports:
import os
import loom.format
import loom.util
from nose.tools import assert_equal
from distributions.fileutil import tempdir
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.test.util import for_each_dataset
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import assert_found
from loom.test.util import load_rows
and context (class names, function names, or code) available:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
. Output only the next line. | def test_import_rows(encoding, rows, rows_csv, **unused): |
Given snippet: <|code_start|>#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@for_each_dataset
def test_make_schema(model, **unused):
with tempdir(cleanup_on_error=CLEANUP_ON_ERROR):
schema_out = os.path.abspath('schema.json.gz')
loom.format.make_schema(
model_in=model,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import loom.format
import loom.util
from nose.tools import assert_equal
from distributions.fileutil import tempdir
from distributions.io.stream import protobuf_stream_load
from distributions.tests.util import assert_close
from loom.test.util import for_each_dataset
from loom.test.util import CLEANUP_ON_ERROR
from loom.test.util import assert_found
from loom.test.util import load_rows
and context:
# Path: loom/test/util.py
# def for_each_dataset(fun):
# @functools.wraps(fun)
# def test_one(dataset):
# paths = loom.store.get_paths(dataset, sample_count=2)
# for key, path in loom.store.iter_paths(dataset, paths):
# if not os.path.exists(path):
# raise ValueError(
# 'missing {} at {},\n first `python -m loom.datasets test`'
# .format(key, path))
# kwargs = {'name': dataset}
# kwargs.update(paths['query'])
# kwargs.update(paths['consensus'])
# kwargs.update(paths['samples'][0])
# kwargs.update(paths['ingest'])
# kwargs.update(paths)
# fun(**kwargs)
#
# @functools.wraps(fun)
# def test_all():
# for dataset in loom.datasets.TEST_CONFIGS:
# yield test_one, dataset
#
# return test_all
#
# Path: loom/test/util.py
# CLEANUP_ON_ERROR = int(os.environ.get('CLEANUP_ON_ERROR', 1))
#
# Path: loom/test/util.py
# def assert_found(*filenames):
# for name in filenames:
# assert_true(os.path.exists(name), 'missing file: {}'.format(name))
#
# Path: loom/test/util.py
# def load_rows(filename):
# rows = []
# for string in protobuf_stream_load(filename):
# row = Row()
# row.ParseFromString(string)
# rows.append(row)
# return rows
which might include code, classes, or functions. Output only the next line. | schema_out=schema_out) |
Given snippet: <|code_start|>
class Command(BaseCommand):
help = 'This command will add grammars to the database, starting from <num> grammars and gradually filtering them down to a valid set (which may be much less than <num>)'
def add_arguments(self, parser):
parser.add_argument('num', type=int)
parser.add_argument('--reset',
action='store_true',
dest='reset_db',
default=False,
help='Clear database and repopulate it',
)
parser.add_argument('--silent',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand, CommandError
from LL1_Academy.tools import MassGrammarGenerator
from LL1_Academy.models import Grammar
from django.core.management import call_command
import os
import sys
import time
and context:
# Path: LL1_Academy/tools/MassGrammarGenerator.py
# class MassGrammarGenerator:
#
# def __init__(self, n):
# self.statusSummary = {"LL1":0, "non-LL1":0}
# self.gc = GrammarChecker.GrammarChecker()
# self.g = SingleGrammarGenerator.SingleGrammarGenerator()
#
# #builds the ML model using our trainingData
# fI = os.path.join(script_dir, 'trainingData/'+str(n)+'var-interesting')
# fN = os.path.join(script_dir, 'trainingData/'+str(n)+'var-not-interesting')
# self.learnModel = SvmLearn.SvmLearn(n,fI,fN)
#
# def run(self,num, nonTerminals, terminals):
# self.nonTerminals = nonTerminals
# self.terminals =terminals
#
# #generate num grammars, filter them and write the good ones to DB
# for i in range(0,num):
# self.createOneGrammar()
#
# #prints a small report
# print(str(len(self.nonTerminals)) + " Variables: "
# + str(self.statusSummary["LL1"] + self.statusSummary["non-LL1"])
# + " interesting grammars picked out of "+str(num)+"\n\tLL1: " + str(self.statusSummary["LL1"])
# + "\n\tnot LL(1): " + str(self.statusSummary["non-LL1"]))
#
# def createOneGrammar(self):
# #This function randomly generates a single grammar, and saves it to the DB if
# #it is not left-recursion and interesting
#
# #generate a single grammar randomly
# grammar = self.g.generate(self.nonTerminals, self.terminals)
#
# #get answers using the checker
# #result = firstSets, followSets, parsingTable, status, reachable
# result = self.gc.solve(grammar,'A',False)
#
# #Abandon left recursive grammars and grammars with non-reachable variables
# if (result[3] == -1) or (not result[4]):
# return
#
# #If the ML model decidese it's interesting, save to DB
# prediction = self.learnModel.predictGrammar(grammar,result[0],result[1])
# if prediction[0]==1:
# self.saveToDB(grammar,result)
# print("YES: "+str(grammar)+"\n\tFirst: "+str(result[0])+"\n\tFollow: "+str(result[1]))
# else:
# print("NO: "+str(grammar)+"\n\tFirst: "+str(result[0])+"\n\tFollow: "+str(result[1]))
#
#
# def saveToDB(self,grammar,result):
# #This function takes the grammar and the result returned by gc.solve. It
# #populates the Grammar and Question table in DB with the correct fields
#
# firstSets, followSets, parsingTable, status, reachable, terminals = result
# newG = Grammar(prods=str(grammar), nonTerminals=''.join(self.nonTerminals),
# terminals=''.join(terminals), startSymbol='A')
# newG.save()
#
# #First and Follow Set
# qnum = 0
# for v in self.nonTerminals:
# qFirst = Question(gid=newG,qnum=qnum,category='FI',
# symbol=v,answer=''.join(firstSets[v]))
# qFirst.save()
# qnum +=1
#
# for v in self.nonTerminals:
# qFollow = Question(gid=newG,qnum=qnum,category='FO',
# symbol=v,answer=''.join(followSets[v]))
# qFollow.save()
# qnum +=1
#
# #Parse Table Question
# qPT = Question(gid=newG,qnum=qnum,category='PT',answer=str(parsingTable))
# qPT.save()
# qnum+=1
#
# #LL1 Question
# if status == 0:
# ans = 'True'
# self.statusSummary["LL1"]+=1
# else:
# ans = 'False'
# self.statusSummary["non-LL1"]+=1
# qLL = Question(gid=newG,qnum=qnum,category='LL',answer=ans)
# qLL.save()
#
# Path: LL1_Academy/models.py
# class Grammar(models.Model):
#
# gid = models.AutoField(primary_key = True)
# prods = models.CharField(max_length=200)
# nonTerminals = models.CharField(max_length=4)
# terminals = models.CharField(max_length=4)
# startSymbol = models.CharField(max_length=1)
# nStart = models.IntegerField(default=0)
# nComplete = models.IntegerField(default=0)
# nSkip = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid) + ' ' + self.prods
which might include code, classes, or functions. Output only the next line. | action='store_true', |
Given snippet: <|code_start|>
class Command(BaseCommand):
help = 'This command will add grammars to the database, starting from <num> grammars and gradually filtering them down to a valid set (which may be much less than <num>)'
def add_arguments(self, parser):
parser.add_argument('num', type=int)
parser.add_argument('--reset',
action='store_true',
dest='reset_db',
default=False,
help='Clear database and repopulate it',
)
parser.add_argument('--silent',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand, CommandError
from LL1_Academy.tools import MassGrammarGenerator
from LL1_Academy.models import Grammar
from django.core.management import call_command
import os
import sys
import time
and context:
# Path: LL1_Academy/tools/MassGrammarGenerator.py
# class MassGrammarGenerator:
#
# def __init__(self, n):
# self.statusSummary = {"LL1":0, "non-LL1":0}
# self.gc = GrammarChecker.GrammarChecker()
# self.g = SingleGrammarGenerator.SingleGrammarGenerator()
#
# #builds the ML model using our trainingData
# fI = os.path.join(script_dir, 'trainingData/'+str(n)+'var-interesting')
# fN = os.path.join(script_dir, 'trainingData/'+str(n)+'var-not-interesting')
# self.learnModel = SvmLearn.SvmLearn(n,fI,fN)
#
# def run(self,num, nonTerminals, terminals):
# self.nonTerminals = nonTerminals
# self.terminals =terminals
#
# #generate num grammars, filter them and write the good ones to DB
# for i in range(0,num):
# self.createOneGrammar()
#
# #prints a small report
# print(str(len(self.nonTerminals)) + " Variables: "
# + str(self.statusSummary["LL1"] + self.statusSummary["non-LL1"])
# + " interesting grammars picked out of "+str(num)+"\n\tLL1: " + str(self.statusSummary["LL1"])
# + "\n\tnot LL(1): " + str(self.statusSummary["non-LL1"]))
#
# def createOneGrammar(self):
# #This function randomly generates a single grammar, and saves it to the DB if
# #it is not left-recursion and interesting
#
# #generate a single grammar randomly
# grammar = self.g.generate(self.nonTerminals, self.terminals)
#
# #get answers using the checker
# #result = firstSets, followSets, parsingTable, status, reachable
# result = self.gc.solve(grammar,'A',False)
#
# #Abandon left recursive grammars and grammars with non-reachable variables
# if (result[3] == -1) or (not result[4]):
# return
#
# #If the ML model decidese it's interesting, save to DB
# prediction = self.learnModel.predictGrammar(grammar,result[0],result[1])
# if prediction[0]==1:
# self.saveToDB(grammar,result)
# print("YES: "+str(grammar)+"\n\tFirst: "+str(result[0])+"\n\tFollow: "+str(result[1]))
# else:
# print("NO: "+str(grammar)+"\n\tFirst: "+str(result[0])+"\n\tFollow: "+str(result[1]))
#
#
# def saveToDB(self,grammar,result):
# #This function takes the grammar and the result returned by gc.solve. It
# #populates the Grammar and Question table in DB with the correct fields
#
# firstSets, followSets, parsingTable, status, reachable, terminals = result
# newG = Grammar(prods=str(grammar), nonTerminals=''.join(self.nonTerminals),
# terminals=''.join(terminals), startSymbol='A')
# newG.save()
#
# #First and Follow Set
# qnum = 0
# for v in self.nonTerminals:
# qFirst = Question(gid=newG,qnum=qnum,category='FI',
# symbol=v,answer=''.join(firstSets[v]))
# qFirst.save()
# qnum +=1
#
# for v in self.nonTerminals:
# qFollow = Question(gid=newG,qnum=qnum,category='FO',
# symbol=v,answer=''.join(followSets[v]))
# qFollow.save()
# qnum +=1
#
# #Parse Table Question
# qPT = Question(gid=newG,qnum=qnum,category='PT',answer=str(parsingTable))
# qPT.save()
# qnum+=1
#
# #LL1 Question
# if status == 0:
# ans = 'True'
# self.statusSummary["LL1"]+=1
# else:
# ans = 'False'
# self.statusSummary["non-LL1"]+=1
# qLL = Question(gid=newG,qnum=qnum,category='LL',answer=ans)
# qLL.save()
#
# Path: LL1_Academy/models.py
# class Grammar(models.Model):
#
# gid = models.AutoField(primary_key = True)
# prods = models.CharField(max_length=200)
# nonTerminals = models.CharField(max_length=4)
# terminals = models.CharField(max_length=4)
# startSymbol = models.CharField(max_length=1)
# nStart = models.IntegerField(default=0)
# nComplete = models.IntegerField(default=0)
# nSkip = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid) + ' ' + self.prods
which might include code, classes, or functions. Output only the next line. | action='store_true', |
Given snippet: <|code_start|> for nt in non_terminals:
feedback[nt] = []
for t in terminals:
# case 1: t in true_answer, not in answer
if t in true_answer[nt] and t not in answer[nt]:
feedback[nt].append(1)
isCorrect = False
# case 2: t not in true_answer, in answer
elif t not in true_answer[nt] and t in answer[nt]:
feedback[nt].append(1)
isCorrect = False
else:
# case 3: t in neither
if t not in answer[nt]:
feedback[nt].append(0)
# case 4: t in both -- check if same
else:
if set(answer[nt][t]) == set(true_answer[nt][t]):
feedback[nt].append(0)
else:
feedback[nt].append(1)
isCorrect = False
return isCorrect, feedback
def give_up(request):
if 'gid' in request.session and 'curQ' in request.session:
gid = request.session['gid']
currentQ = request.session['curQ']
question = Question.objects.filter(gid__gid__exact=gid, qnum=currentQ).first()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import ast
import json
from django.shortcuts import render
from django.http import JsonResponse, HttpRequest, HttpResponseRedirect, Http404, HttpResponseBadRequest
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.forms.models import model_to_dict
from LL1_Academy.views import stats
from LL1_Academy.models import *
and context:
# Path: LL1_Academy/views/stats.py
# def log_start_grammar(gid):
# def log_complete_grammar(request):
# def log_skip_grammar(request):
which might include code, classes, or functions. Output only the next line. | score = "" |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(t_grammar.nComplete, 0)
self.assertEqual(t_grammar.nSkip, 0)
def test_question(self):
g = Grammar(prods="{'A': ['xA', 'Bz'],'B': ['yB']}", nonTerminals="AB", terminals="xyz", startSymbol="A")
g.save()
q = Question(gid=g, qnum=0, category="FI", symbol="A", answer="xy")
q.save()
t_question = Question.objects.get(pk=q.pk)
self.assertEqual(t_question.gid, g)
self.assertEqual(t_question.qnum, 0)
self.assertEqual(t_question.category, "FI")
self.assertEqual(t_question.symbol, "A")
self.assertEqual(t_question.answer, "xy")
self.assertEqual(t_question.nCorrect, 0)
self.assertEqual(t_question.nWrong, 0)
self.assertEqual(t_question.nGiveUp, 0)
def test_user_history(self):
g = Grammar(prods="{'A': ['xA', 'Bz'],'B': ['yB']}", nonTerminals="AB", terminals="xyz", startSymbol="A")
g.save()
u = User.objects.get(username="test")
t_user_history = UserHistory(user=u, grammar=g)
self.assertEqual(t_user_history.user, u)
self.assertEqual(t_user_history.grammar, g)
self.assertEqual(t_user_history.complete, False)
self.assertEqual(t_user_history.score, -1)
class PracticeTest(TestData):
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase, Client
from django.http import HttpRequest
from django.urls import reverse
from LL1_Academy.models import Grammar, Question, UserHistory
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django.conf import settings
from importlib import import_module
import LL1_Academy.views.practice as practice
import LL1_Academy.views.tutorial as tutorial
import LL1_Academy.views.views as views
import LL1_Academy.views.stats as stats
import LL1_Academy.views.userProfile as user_profile
import LL1_Academy.tools.GrammarChecker as grammar_checker
import LL1_Academy.tools.MassGrammarGenerator as mass_grammar_generator
import LL1_Academy.tools.SingleGrammarGenerator as single_grammar_generator
import LL1_Academy.tools.SvmLearn as svm_learn
and context including class names, function names, and sometimes code from other files:
# Path: LL1_Academy/models.py
# class Grammar(models.Model):
#
# gid = models.AutoField(primary_key = True)
# prods = models.CharField(max_length=200)
# nonTerminals = models.CharField(max_length=4)
# terminals = models.CharField(max_length=4)
# startSymbol = models.CharField(max_length=1)
# nStart = models.IntegerField(default=0)
# nComplete = models.IntegerField(default=0)
# nSkip = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid) + ' ' + self.prods
#
# class Question(models.Model):
#
# QUESTION_TYPES = (
# ('FI', 'first'),
# ('FO','follow'),
# ('LL','isLL1'),
# ('PT','parseTable'),
# )
# gid = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# qnum = models.IntegerField()
# category = models.CharField(max_length = 2, choices = QUESTION_TYPES)
# symbol = models.CharField(max_length = 1, blank = True)
# answer = models.CharField(max_length = 300)
# nCorrect = models.IntegerField(default=0)
# nWrong = models.IntegerField(default=0)
# nGiveUp = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid.gid) + ' ' + str(self.qnum) + ' ' + self.category
#
# class Meta:
# unique_together = (("gid","qnum"))
#
# class UserHistory(models.Model):
# user = models.ForeignKey(User, on_delete = models.CASCADE)
# grammar = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# complete = models.BooleanField(default=False)
# score = models.IntegerField(default=-1)
# updateTime = models.DateTimeField()
#
# def __str__(self):
# return str(self.user) + ' ' + str(self.grammar.gid)
#
# def save(self, *args, **kwargs):
# if self.complete and self.score < 0:
# raise Exception("Score cannot be blank for a completed question")
# self.updateTime = timezone.now()
# super(UserHistory, self).save(*args, **kwargs)
#
# class Meta:
# unique_together = (("user","grammar"))
. Output only the next line. | def test_get_random_grammar_unit_test(self): |
Given the following code snippet before the placeholder: <|code_start|> checker = grammar_checker.GrammarChecker()
result = checker.solve({'A': ['xA', 'Bz'],'B': ['yB']},'A',False)
first_sets = result[0]
self.assertEqual(first_sets, {'A': ['x', 'y'], 'B': ['y']})
def test_solve_follow_sets(self):
checker = grammar_checker.GrammarChecker()
result = checker.solve({'A': ['xA', 'Bz'],'B': ['yB']},'A',False)
follow_sets = result[1]
self.assertEqual(follow_sets, {'A': ['$'], 'B': ['z']})
def test_solve_parsing_table(self):
checker = grammar_checker.GrammarChecker()
result = checker.solve({'A': ['xA', 'Bz'],'B': ['yB']},'A',False)
parsing_table = result[2]
self.assertEqual(parsing_table, {'A': {'x': ['xA'], 'y': ['Bz']}, 'B': {'y': ['yB']}})
def test_solve_status(self):
checker = grammar_checker.GrammarChecker()
result = checker.solve({'A': ['xA', 'Bz'],'B': ['yB']},'A',False)
status = result[3]
self.assertEqual(status, 0)
def test_solve_reachability(self):
checker = grammar_checker.GrammarChecker()
result = checker.solve({'A': ['xA', 'Bz'],'B': ['yB']},'A',False)
reachability = result[4]
self.assertEqual(reachability, True)
def test_solve_terminals(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase, Client
from django.http import HttpRequest
from django.urls import reverse
from LL1_Academy.models import Grammar, Question, UserHistory
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django.conf import settings
from importlib import import_module
import LL1_Academy.views.practice as practice
import LL1_Academy.views.tutorial as tutorial
import LL1_Academy.views.views as views
import LL1_Academy.views.stats as stats
import LL1_Academy.views.userProfile as user_profile
import LL1_Academy.tools.GrammarChecker as grammar_checker
import LL1_Academy.tools.MassGrammarGenerator as mass_grammar_generator
import LL1_Academy.tools.SingleGrammarGenerator as single_grammar_generator
import LL1_Academy.tools.SvmLearn as svm_learn
and context including class names, function names, and sometimes code from other files:
# Path: LL1_Academy/models.py
# class Grammar(models.Model):
#
# gid = models.AutoField(primary_key = True)
# prods = models.CharField(max_length=200)
# nonTerminals = models.CharField(max_length=4)
# terminals = models.CharField(max_length=4)
# startSymbol = models.CharField(max_length=1)
# nStart = models.IntegerField(default=0)
# nComplete = models.IntegerField(default=0)
# nSkip = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid) + ' ' + self.prods
#
# class Question(models.Model):
#
# QUESTION_TYPES = (
# ('FI', 'first'),
# ('FO','follow'),
# ('LL','isLL1'),
# ('PT','parseTable'),
# )
# gid = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# qnum = models.IntegerField()
# category = models.CharField(max_length = 2, choices = QUESTION_TYPES)
# symbol = models.CharField(max_length = 1, blank = True)
# answer = models.CharField(max_length = 300)
# nCorrect = models.IntegerField(default=0)
# nWrong = models.IntegerField(default=0)
# nGiveUp = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid.gid) + ' ' + str(self.qnum) + ' ' + self.category
#
# class Meta:
# unique_together = (("gid","qnum"))
#
# class UserHistory(models.Model):
# user = models.ForeignKey(User, on_delete = models.CASCADE)
# grammar = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# complete = models.BooleanField(default=False)
# score = models.IntegerField(default=-1)
# updateTime = models.DateTimeField()
#
# def __str__(self):
# return str(self.user) + ' ' + str(self.grammar.gid)
#
# def save(self, *args, **kwargs):
# if self.complete and self.score < 0:
# raise Exception("Score cannot be blank for a completed question")
# self.updateTime = timezone.now()
# super(UserHistory, self).save(*args, **kwargs)
#
# class Meta:
# unique_together = (("user","grammar"))
. Output only the next line. | checker = grammar_checker.GrammarChecker() |
Using the snippet: <|code_start|> g.save()
t_grammar = Grammar.objects.get(pk=g.pk)
self.assertEqual(t_grammar.prods, "{'A': ['xA', 'Bz'],'B': ['yB']}")
self.assertEqual(t_grammar.nonTerminals, "AB")
self.assertEqual(t_grammar.terminals, "xyz")
self.assertEqual(t_grammar.startSymbol, "A")
self.assertEqual(t_grammar.nStart, 0)
self.assertEqual(t_grammar.nComplete, 0)
self.assertEqual(t_grammar.nSkip, 0)
def test_question(self):
g = Grammar(prods="{'A': ['xA', 'Bz'],'B': ['yB']}", nonTerminals="AB", terminals="xyz", startSymbol="A")
g.save()
q = Question(gid=g, qnum=0, category="FI", symbol="A", answer="xy")
q.save()
t_question = Question.objects.get(pk=q.pk)
self.assertEqual(t_question.gid, g)
self.assertEqual(t_question.qnum, 0)
self.assertEqual(t_question.category, "FI")
self.assertEqual(t_question.symbol, "A")
self.assertEqual(t_question.answer, "xy")
self.assertEqual(t_question.nCorrect, 0)
self.assertEqual(t_question.nWrong, 0)
self.assertEqual(t_question.nGiveUp, 0)
def test_user_history(self):
g = Grammar(prods="{'A': ['xA', 'Bz'],'B': ['yB']}", nonTerminals="AB", terminals="xyz", startSymbol="A")
g.save()
u = User.objects.get(username="test")
t_user_history = UserHistory(user=u, grammar=g)
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase, Client
from django.http import HttpRequest
from django.urls import reverse
from LL1_Academy.models import Grammar, Question, UserHistory
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django.conf import settings
from importlib import import_module
import LL1_Academy.views.practice as practice
import LL1_Academy.views.tutorial as tutorial
import LL1_Academy.views.views as views
import LL1_Academy.views.stats as stats
import LL1_Academy.views.userProfile as user_profile
import LL1_Academy.tools.GrammarChecker as grammar_checker
import LL1_Academy.tools.MassGrammarGenerator as mass_grammar_generator
import LL1_Academy.tools.SingleGrammarGenerator as single_grammar_generator
import LL1_Academy.tools.SvmLearn as svm_learn
and context (class names, function names, or code) available:
# Path: LL1_Academy/models.py
# class Grammar(models.Model):
#
# gid = models.AutoField(primary_key = True)
# prods = models.CharField(max_length=200)
# nonTerminals = models.CharField(max_length=4)
# terminals = models.CharField(max_length=4)
# startSymbol = models.CharField(max_length=1)
# nStart = models.IntegerField(default=0)
# nComplete = models.IntegerField(default=0)
# nSkip = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid) + ' ' + self.prods
#
# class Question(models.Model):
#
# QUESTION_TYPES = (
# ('FI', 'first'),
# ('FO','follow'),
# ('LL','isLL1'),
# ('PT','parseTable'),
# )
# gid = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# qnum = models.IntegerField()
# category = models.CharField(max_length = 2, choices = QUESTION_TYPES)
# symbol = models.CharField(max_length = 1, blank = True)
# answer = models.CharField(max_length = 300)
# nCorrect = models.IntegerField(default=0)
# nWrong = models.IntegerField(default=0)
# nGiveUp = models.IntegerField(default=0)
#
# def __str__(self):
# return str(self.gid.gid) + ' ' + str(self.qnum) + ' ' + self.category
#
# class Meta:
# unique_together = (("gid","qnum"))
#
# class UserHistory(models.Model):
# user = models.ForeignKey(User, on_delete = models.CASCADE)
# grammar = models.ForeignKey(Grammar, on_delete = models.CASCADE)
# complete = models.BooleanField(default=False)
# score = models.IntegerField(default=-1)
# updateTime = models.DateTimeField()
#
# def __str__(self):
# return str(self.user) + ' ' + str(self.grammar.gid)
#
# def save(self, *args, **kwargs):
# if self.complete and self.score < 0:
# raise Exception("Score cannot be blank for a completed question")
# self.updateTime = timezone.now()
# super(UserHistory, self).save(*args, **kwargs)
#
# class Meta:
# unique_together = (("user","grammar"))
. Output only the next line. | self.assertEqual(t_user_history.user, u) |
Given the code snippet: <|code_start|>
def samples(self, nsamples, ctrs, rstate=None):
"""
Draw `nsamples` samples uniformly distributed within the *union* of
balls.
Returns
-------
xs : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the set of balls.
"""
xs = np.array(
[self.sample(ctrs, rstate=rstate) for i in range(nsamples)])
return xs
def monte_carlo_logvol(self,
ctrs,
ndraws=10000,
rstate=None,
return_overlap=True):
"""Using `ndraws` Monte Carlo draws, estimate the log volume of the
*union* of balls. If `return_overlap=True`, also returns the
estimated fractional overlap with the unit cube."""
# Estimate volume using Monte Carlo integration.
samples = [
self.sample(ctrs, rstate=rstate, return_q=True)
<|code_end|>
, generate the next line using the imports in this file:
import warnings
import math
import numpy as np
from numpy import linalg
from numpy import cov as mle_cov
from scipy import spatial
from scipy import cluster
from scipy import linalg as lalg
from scipy.special import logsumexp, gammaln
from .utils import unitcheck, get_seed_sequence, get_random_generator
from scipy.cluster.vq import kmeans2
and context (functions, classes, or occasionally code) from other files:
# Path: py/dynesty/utils.py
# def unitcheck(u, nonbounded=None):
# """Check whether `u` is inside the unit cube. Given a masked array
# `nonbounded`, also allows periodic boundaries conditions to exceed
# the unit cube."""
#
# if nonbounded is None:
# # No periodic boundary conditions provided.
# return np.min(u) > 0 and np.max(u) < 1
# else:
# # Alternating periodic and non-periodic boundary conditions.
# unb = u[nonbounded]
# # pylint: disable=invalid-unary-operand-type
# ub = u[~nonbounded]
# return (unb.min() > 0 and unb.max() < 1 and ub.min() > -0.5
# and ub.max() < 1.5)
#
# def get_seed_sequence(rstate, nitems):
# """
# Return the list of seeds to initialize random generators
# This is useful when distributing work across a pool
# """
# seeds = np.random.SeedSequence(rstate.integers(0, 2**63 - 1,
# size=4)).spawn(nitems)
# return seeds
#
# def get_random_generator(seed=None):
# """
# Return a random generator (using the seed provided if available)
# """
# return np.random.Generator(np.random.PCG64(seed))
. Output only the next line. | for i in range(ndraws) |
Given snippet: <|code_start|> ndraws=10000,
rstate=None,
return_overlap=True):
"""Using `ndraws` Monte Carlo draws, estimate the log volume of the
*union* of balls. If `return_overlap=True`, also returns the
estimated fractional overlap with the unit cube."""
# Estimate volume using Monte Carlo integration.
samples = [
self.sample(ctrs, rstate=rstate, return_q=True)
for i in range(ndraws)
]
qsum = sum([q for (x, q) in samples])
logvol = np.log(1. * ndraws / qsum * len(ctrs)) + self.logvol_ball
if return_overlap:
# Estimate the fractional amount of overlap with the
# unit cube using the same set of samples.
qin = sum([q * unitcheck(x) for (x, q) in samples])
overlap = 1. * qin / qsum
return logvol, overlap
else:
return logvol
def update(self,
points,
rstate=None,
bootstrap=0,
pool=None,
mc_integrate=False,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import warnings
import math
import numpy as np
from numpy import linalg
from numpy import cov as mle_cov
from scipy import spatial
from scipy import cluster
from scipy import linalg as lalg
from scipy.special import logsumexp, gammaln
from .utils import unitcheck, get_seed_sequence, get_random_generator
from scipy.cluster.vq import kmeans2
and context:
# Path: py/dynesty/utils.py
# def unitcheck(u, nonbounded=None):
# """Check whether `u` is inside the unit cube. Given a masked array
# `nonbounded`, also allows periodic boundaries conditions to exceed
# the unit cube."""
#
# if nonbounded is None:
# # No periodic boundary conditions provided.
# return np.min(u) > 0 and np.max(u) < 1
# else:
# # Alternating periodic and non-periodic boundary conditions.
# unb = u[nonbounded]
# # pylint: disable=invalid-unary-operand-type
# ub = u[~nonbounded]
# return (unb.min() > 0 and unb.max() < 1 and ub.min() > -0.5
# and ub.max() < 1.5)
#
# def get_seed_sequence(rstate, nitems):
# """
# Return the list of seeds to initialize random generators
# This is useful when distributing work across a pool
# """
# seeds = np.random.SeedSequence(rstate.integers(0, 2**63 - 1,
# size=4)).spawn(nitems)
# return seeds
#
# def get_random_generator(seed=None):
# """
# Return a random generator (using the seed provided if available)
# """
# return np.random.Generator(np.random.PCG64(seed))
which might include code, classes, or functions. Output only the next line. | use_clustering=True): |
Here is a snippet: <|code_start|> return x
def samples(self, nsamples, ctrs, rstate=None):
"""
Draw `nsamples` samples uniformly distributed within the *union* of
balls.
Returns
-------
xs : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the set of balls.
"""
xs = np.array(
[self.sample(ctrs, rstate=rstate) for i in range(nsamples)])
return xs
def monte_carlo_logvol(self,
ctrs,
ndraws=10000,
rstate=None,
return_overlap=True):
"""Using `ndraws` Monte Carlo draws, estimate the log volume of the
*union* of balls. If `return_overlap=True`, also returns the
estimated fractional overlap with the unit cube."""
# Estimate volume using Monte Carlo integration.
samples = [
<|code_end|>
. Write the next line using the current file imports:
import warnings
import math
import numpy as np
from numpy import linalg
from numpy import cov as mle_cov
from scipy import spatial
from scipy import cluster
from scipy import linalg as lalg
from scipy.special import logsumexp, gammaln
from .utils import unitcheck, get_seed_sequence, get_random_generator
from scipy.cluster.vq import kmeans2
and context from other files:
# Path: py/dynesty/utils.py
# def unitcheck(u, nonbounded=None):
# """Check whether `u` is inside the unit cube. Given a masked array
# `nonbounded`, also allows periodic boundaries conditions to exceed
# the unit cube."""
#
# if nonbounded is None:
# # No periodic boundary conditions provided.
# return np.min(u) > 0 and np.max(u) < 1
# else:
# # Alternating periodic and non-periodic boundary conditions.
# unb = u[nonbounded]
# # pylint: disable=invalid-unary-operand-type
# ub = u[~nonbounded]
# return (unb.min() > 0 and unb.max() < 1 and ub.min() > -0.5
# and ub.max() < 1.5)
#
# def get_seed_sequence(rstate, nitems):
# """
# Return the list of seeds to initialize random generators
# This is useful when distributing work across a pool
# """
# seeds = np.random.SeedSequence(rstate.integers(0, 2**63 - 1,
# size=4)).spawn(nitems)
# return seeds
#
# def get_random_generator(seed=None):
# """
# Return a random generator (using the seed provided if available)
# """
# return np.random.Generator(np.random.PCG64(seed))
, which may include functions, classes, or code. Output only the next line. | self.sample(ctrs, rstate=rstate, return_q=True) |
Continue the code snippet: <|code_start|>
def test_default_poolname():
class Test(Pool):
pass
pool = Test()
assert pool.pool_key == 'TestPool'
def test_manual_poolname():
class Test(Pool):
<|code_end|>
. Use current file imports:
from hystrix.pool import Pool
and context (classes, functions, or code) from other files:
# Path: hystrix/pool.py
# class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)):
#
# pool_key = None
#
# def __init__(self, pool_key=None, max_workers=5):
# super(Pool, self).__init__(max_workers)
. Output only the next line. | pool_key = 'MyTestPool' |
Based on the snippet: <|code_start|>
def test_default_pool_metrics_name():
class Test(PoolMetrics):
pass
poolmetrics = Test()
assert poolmetrics.pool_metrics_key == 'TestPoolMetrics'
def test_manual_pool_metrics_name():
class Test(PoolMetrics):
<|code_end|>
, predict the immediate next line with the help of imports:
from hystrix.pool_metrics import PoolMetrics
and context (classes, functions, sometimes code) from other files:
# Path: hystrix/pool_metrics.py
# class PoolMetrics(six.with_metaclass(PoolMetricsMetaclass, object)):
#
# pool_metrics_key = None
. Output only the next line. | pool_metrics_key = 'MyTestPoolMetrics' |
Predict the next line after this snippet: <|code_start|>
def __init__(self, _time, milliseconds, bucket_numbers,
bucket_data_length, enabled):
self.time = _time
self.milliseconds = milliseconds
self.buckets = BucketCircular(bucket_numbers)
self.bucket_numbers = bucket_numbers
self.bucket_data_length = bucket_data_length
self.enabled = enabled
self.snapshot = PercentileSnapshot(0)
self._new_bucket_lock = RLock()
def buckets_size_in_milliseconds(self):
return self.milliseconds / self.bucket_numbers
def current_bucket(self):
current_time = self.time.current_time_in_millis()
current_bucket = self.buckets.peek_last()
if current_bucket is not None and current_time < (current_bucket.window_start + self.buckets_size_in_milliseconds()):
return current_bucket
with self._new_bucket_lock:
# If we didn't find the current bucket above, then we have to
# create one.
if self.buckets.peek_last() is None:
new_bucket = Bucket(current_time, self.bucket_data_length)
self.buckets.add_last(new_bucket)
return new_bucket
else:
<|code_end|>
using the current file's imports:
from multiprocessing import RLock, Array
from hystrix.rolling_number import BucketCircular
import itertools
import logging
import time
import math
and any relevant context from other files:
# Path: hystrix/rolling_number.py
# class BucketCircular(deque):
# ''' This is a circular array acting as a FIFO queue. '''
#
# def __init__(self, size):
# super(BucketCircular, self).__init__(maxlen=size)
#
# @property
# def size(self):
# return len(self)
#
# def last(self):
# return self.peek_last()
#
# def peek_last(self):
# try:
# return self[0]
# except IndexError:
# return None
#
# def add_last(self, bucket):
# self.appendleft(bucket)
. Output only the next line. | for i in range(self.bucket_numbers): |
Given the code snippet: <|code_start|>
def test_default_circuitbreakername():
class Test(CircuitBreaker):
pass
circuitbreaker = Test()
assert circuitbreaker.circuit_breaker_name == 'TestCircuitBreaker'
def test_manual_circuitbreakername():
class Test(CircuitBreaker):
<|code_end|>
, generate the next line using the imports in this file:
from hystrix.circuitbreaker import CircuitBreaker
and context (functions, classes, or occasionally code) from other files:
# Path: hystrix/circuitbreaker.py
# class CircuitBreaker(six.with_metaclass(CircuitBreakerMetaclass, object)):
#
# __circuit_breaker_name__ = None
. Output only the next line. | __circuit_breaker_name__ = 'MyTestCircuitBreaker' |
Next line prediction: <|code_start|>from __future__ import absolute_import
log = logging.getLogger(__name__)
class GroupMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Group', 'GroupMetaclass')
def __new__(cls, name, bases, attrs):
<|code_end|>
. Use current file imports:
(import logging
import six
from .pool import Pool)
and context including class names, function names, or small code snippets from other files:
# Path: hystrix/pool.py
# class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)):
#
# pool_key = None
#
# def __init__(self, pool_key=None, max_workers=5):
# super(Pool, self).__init__(max_workers)
. Output only the next line. | if name in cls.__blacklist__: |
Using the snippet: <|code_start|> with pytest.raises(RuntimeError):
command.cache()
def test_default_groupname():
class RunCommand(Command):
pass
command = RunCommand()
assert command.group_key == 'RunCommandGroup'
def test_manual_groupname():
class RunCommand(Command):
group_key = 'MyRunGroup'
pass
command = RunCommand()
assert command.group_key == 'MyRunGroup'
def test_command_hello_synchronous():
command = HelloCommand()
result = command.execute()
assert 'Hello Run' == result
def test_command_hello_asynchronous():
command = HelloCommand()
future = command.queue()
<|code_end|>
, determine the next line of code. You have imports:
from hystrix.command import Command
import pytest
and context (class names, function names, or code) available:
# Path: hystrix/command.py
# class Command(six.with_metaclass(CommandMetaclass, object)):
#
# command_key = None
# group_key = None
#
# def __init__(self, group_key=None, command_key=None,
# pool_key=None, circuit_breaker=None, pool=None,
# command_properties_defaults=None,
# pool_properties_defaults=None, metrics=None,
# fallback_semaphore=None, execution_semaphore=None,
# properties_strategy=None, execution_hook=None, timeout=None):
# self.timeout = timeout
#
# def run(self):
# raise NotImplementedError('Subclasses must implement this method.')
#
# def fallback(self):
# raise NotImplementedError('Subclasses must implement this method.')
#
# def cache(self):
# raise NotImplementedError('Subclasses must implement this method.')
#
# def execute(self, timeout=None):
# timeout = timeout or self.timeout
# future = self.group.pool.submit(self.run)
# try:
# return future.result(timeout)
# except Exception:
# log.exception('exception calling run for {}'.format(self))
# log.info('run raises {}'.format(future.exception))
# try:
# log.info('trying fallback for {}'.format(self))
# future = self.group.pool.submit(self.fallback)
# return future.result(timeout)
# except Exception:
# log.exception('exception calling fallback for {}'.format(self))
# log.info('run() raised {}'.format(future.exception))
# log.info('trying cache for {}'.format(self))
# future = self.group.pool.submit(self.cache)
# return future.result(timeout)
#
# def observe(self, timeout=None):
# timeout = timeout or self.timeout
# return self.__async(timeout=timeout)
#
# def queue(self, timeout=None):
# timeout = timeout or self.timeout
# return self.__async(timeout=timeout)
#
# def __async(self, timeout=None):
# timeout = timeout or self.timeout
# future = self.group.pool.submit(self.run)
# try:
# # Call result() to check for exception
# future.result(timeout)
# return future
# except Exception:
# log.exception('exception calling run for {}'.format(self))
# log.info('run raised {}'.format(future.exception))
# try:
# log.info('trying fallback for {}'.format(self))
# future = self.group.pool.submit(self.fallback)
# # Call result() to check for exception
# future.result(timeout)
# return future
# except Exception:
# log.exception('exception calling fallback for {}'.format(self))
# log.info('fallback raised {}'.format(future.exception))
# log.info('trying cache for {}'.format(self))
# return self.group.pool.submit(self.cache)
. Output only the next line. | assert 'Hello Run' == future.result() |
Next line prediction: <|code_start|> ctx.release_version = re.sub(r"^v", "", ctx.release_tag)
click.secho(f"Package version: {ctx.release_version}.")
def get_release_notes(ctx: TagContext) -> None:
click.secho("> Grabbing the release notes.")
changelog_path = "CHANGELOG.md"
changelog = ctx.github.get_contents(
ctx.upstream_repo, changelog_path, ref=ctx.release_pr["merge_commit_sha"]
).decode("utf-8")
_get_latest_release_notes(ctx, changelog)
def _get_latest_release_notes(ctx: TagContext, changelog: str):
match = re.search(
rf"## v?\[?{ctx.release_version}[^\n]*\n(?P<notes>.+?)(\n##\s|\n### \[?[0-9]+\.|\Z)",
changelog,
re.DOTALL | re.MULTILINE,
)
if match is not None:
ctx.release_notes = match.group("notes").strip()
else:
ctx.release_notes = ""
def create_release(ctx: TagContext) -> None:
click.secho("> Creating the release.")
<|code_end|>
. Use current file imports:
(import getpass
import re
import click
import releasetool.circleci
import releasetool.git
import releasetool.github
import releasetool.secrets
import releasetool.commands.common
from typing import List, Union
from releasetool.commands.common import TagContext)
and context including class names, function names, or small code snippets from other files:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | release_name = f"v{ctx.release_version}" |
Here is a snippet: <|code_start|>
def get_release_notes(ctx: TagContext) -> None:
click.secho("> Grabbing the release notes.")
changelog = ctx.github.get_contents(
ctx.upstream_repo, "CHANGELOG.md", ref=ctx.release_pr["merge_commit_sha"]
).decode("utf-8")
match = re.search(
rf"## {ctx.release_version}\n(?P<notes>.+?)(\n##\s|\Z)",
changelog,
re.DOTALL | re.MULTILINE,
)
if match is not None:
ctx.release_notes = match.group("notes").strip()
else:
ctx.release_notes = ""
def create_release(ctx: TagContext) -> None:
click.secho("> Creating the release.")
ctx.github_release = ctx.github.create_release(
repository=ctx.upstream_repo,
tag_name=ctx.release_tag,
target_commitish=ctx.release_pr["merge_commit_sha"],
name=f"{ctx.package_name} {ctx.release_version}",
<|code_end|>
. Write the next line using the current file imports:
import getpass
import re
import click
import releasetool.commands.common
from typing import Union
from releasetool.commands.common import TagContext
from releasetool.commands.tag import python
and context from other files:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
#
# Path: releasetool/commands/tag/python.py
# def determine_release_pr(ctx: TagContext) -> None:
# def determine_release_tag(ctx: TagContext) -> None:
# def determine_package_version(ctx: TagContext) -> None:
# def get_release_notes(ctx: TagContext) -> None:
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# def create_release(ctx: TagContext) -> None:
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# def package_name(pull: dict) -> Union[str, None]:
# def tag(ctx: TagContext = None) -> TagContext:
, which may include functions, classes, or code. Output only the next line. | body=ctx.release_notes, |
Continue the code snippet: <|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
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_release_notes(ctx: TagContext) -> None:
click.secho("> Grabbing the release notes.")
changelog = ctx.github.get_contents(
ctx.upstream_repo, "CHANGELOG.md", ref=ctx.release_pr["merge_commit_sha"]
).decode("utf-8")
match = re.search(
rf"## {ctx.release_version}\n(?P<notes>.+?)(\n##\s|\Z)",
changelog,
re.DOTALL | re.MULTILINE,
)
if match is not None:
ctx.release_notes = match.group("notes").strip()
<|code_end|>
. Use current file imports:
import getpass
import re
import click
import releasetool.commands.common
from typing import Union
from releasetool.commands.common import TagContext
from releasetool.commands.tag import python
and context (classes, functions, or code) from other files:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
#
# Path: releasetool/commands/tag/python.py
# def determine_release_pr(ctx: TagContext) -> None:
# def determine_release_tag(ctx: TagContext) -> None:
# def determine_package_version(ctx: TagContext) -> None:
# def get_release_notes(ctx: TagContext) -> None:
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# def create_release(ctx: TagContext) -> None:
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# def package_name(pull: dict) -> Union[str, None]:
# def tag(ctx: TagContext = None) -> TagContext:
. Output only the next line. | else: |
Continue the code snippet: <|code_start|># Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
release_triggering_lines = [
("Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
(
"Release Google.LongRunning version 1.2.3-beta01",
"Google.LongRunning",
"1.2.3-beta01",
),
("- Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
]
non_release_triggering_lines = [
("Release new version of all OsLogin packages"),
<|code_end|>
. Use current file imports:
import pytest
import re
from releasetool.commands.tag.dotnet import (
RELEASE_LINE_PATTERN,
kokoro_job_name,
package_name,
)
and context (classes, functions, or code) from other files:
# Path: releasetool/commands/tag/dotnet.py
# RELEASE_LINE_PATTERN = r"^(?:- )?Release ([^ ]*) version (\d+\.\d+.\d+(-[^ ]*)?)$"
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return None
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | ("Release all OsLogin packages version 1.2.3"), |
Given the code snippet: <|code_start|># https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
release_triggering_lines = [
("Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
(
"Release Google.LongRunning version 1.2.3-beta01",
"Google.LongRunning",
"1.2.3-beta01",
),
("- Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
]
non_release_triggering_lines = [
("Release new version of all OsLogin packages"),
("Release all OsLogin packages version 1.2.3"),
("Release Google.LongRunning version 1.0"),
("Release Google.LongRunning version 1.2.3 and 1.2.4"),
]
@pytest.mark.parametrize("line,package,version", release_triggering_lines)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import re
from releasetool.commands.tag.dotnet import (
RELEASE_LINE_PATTERN,
kokoro_job_name,
package_name,
)
and context (functions, classes, or occasionally code) from other files:
# Path: releasetool/commands/tag/dotnet.py
# RELEASE_LINE_PATTERN = r"^(?:- )?Release ([^ ]*) version (\d+\.\d+.\d+(-[^ ]*)?)$"
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return None
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | def test_release_line_regex_matching(line, package, version): |
Given the code snippet: <|code_start|># Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
release_triggering_lines = [
("Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
(
"Release Google.LongRunning version 1.2.3-beta01",
"Google.LongRunning",
"1.2.3-beta01",
),
("- Release Google.LongRunning version 1.2.3", "Google.LongRunning", "1.2.3"),
]
non_release_triggering_lines = [
("Release new version of all OsLogin packages"),
("Release all OsLogin packages version 1.2.3"),
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import re
from releasetool.commands.tag.dotnet import (
RELEASE_LINE_PATTERN,
kokoro_job_name,
package_name,
)
and context (functions, classes, or occasionally code) from other files:
# Path: releasetool/commands/tag/dotnet.py
# RELEASE_LINE_PATTERN = r"^(?:- )?Release ([^ ]*) version (\d+\.\d+.\d+(-[^ ]*)?)$"
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return None
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | ("Release Google.LongRunning version 1.0"), |
Given the following code snippet before the placeholder: <|code_start|>
### Bug Fixes
- fix: throw on invalid credentials ([#281](https://github.com/googleapis/nodejs-dialogflow/pull/281))
## v0.8.1
01-28-2019 13:24 PST
### Documentation
- fix(docs): dialogflow inn't published under @google-cloud scope ([#266](https://github.com/googleapis/nodejs-dialogflow/pull/266))
## v0.8.0
"""
fixture_new_and_old_style_changelog = """
# Changelog
[npm history][1]
[1]: https://www.npmjs.com/package/@google-cloud/os-login?activeTab=versions
### [0.3.3](https://www.github.com/googleapis/nodejs-os-login/compare/v0.3.2...v0.3.3) (2019-04-30)
### Bug Fixes
* include 'x-goog-request-params' header in requests ([#167](https://www.github.com/googleapis/nodejs-os-login/issues/167)) ([074051d](https://www.github.com/googleapis/nodejs-os-login/commit/074051d))
## v0.3.2
<|code_end|>
, predict the next line using imports from the current file:
from releasetool.commands.tag.nodejs import (
_get_latest_release_notes,
kokoro_job_name,
package_name,
)
from releasetool.commands.common import TagContext
and context including class names, function names, and sometimes code from other files:
# Path: releasetool/commands/tag/nodejs.py
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# # the 'v' prefix is not used in the conventional-changelog templates
# # used in automated CHANGELOG generation:
# version = re.sub(r"^v", "", ctx.release_version)
# match = re.search(
# rf"## v?\[?{version}[^\n]*\n(?P<notes>.+?)(\n##\s|\n### \[?[0-9]+\.|\Z)",
# changelog,
# re.DOTALL | re.MULTILINE,
# )
# if match is not None:
# ctx.release_notes = match.group("notes").strip()
# else:
# ctx.release_notes = ""
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/nodejs/release/{upstream_repo}/publish"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
#
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | 03-18-2019 13:47 PDT |
Predict the next line after this snippet: <|code_start|>
### BREAKING CHANGES
* this fancy new feature breaks things
* disclaimer breaks everything"""
ctx = TagContext(release_version="v2.0.0")
_get_latest_release_notes(ctx, fixture_new_style_changelog)
assert ctx.release_notes == expected
def test_extracts_appropriate_release_notes_when_prior_release_is_patch():
"""
see: https://github.com/googleapis/release-please/issues/140
"""
ctx = TagContext(release_version="v5.0.0")
_get_latest_release_notes(ctx, fixture_new_style_patch)
expected = """### ⚠ BREAKING CHANGES
* temp directory now defaults to setting for report directory
### Features
* default temp directory to report directory ([#102](https://www.github.com/bcoe/c8/issues/102)) ([8602f4a](https://www.github.com/bcoe/c8/commit/8602f4a))
* load .nycrc/.nycrc.json to simplify migration ([#100](https://www.github.com/bcoe/c8/issues/100)) ([bd7484f](https://www.github.com/bcoe/c8/commit/bd7484f))"""
assert ctx.release_notes == expected
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
<|code_end|>
using the current file's imports:
from releasetool.commands.tag.nodejs import (
_get_latest_release_notes,
kokoro_job_name,
package_name,
)
from releasetool.commands.common import TagContext
and any relevant context from other files:
# Path: releasetool/commands/tag/nodejs.py
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# # the 'v' prefix is not used in the conventional-changelog templates
# # used in automated CHANGELOG generation:
# version = re.sub(r"^v", "", ctx.release_version)
# match = re.search(
# rf"## v?\[?{version}[^\n]*\n(?P<notes>.+?)(\n##\s|\n### \[?[0-9]+\.|\Z)",
# changelog,
# re.DOTALL | re.MULTILINE,
# )
# if match is not None:
# ctx.release_notes = match.group("notes").strip()
# else:
# ctx.release_notes = ""
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/nodejs/release/{upstream_repo}/publish"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
#
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | assert ( |
Here is a snippet: <|code_start|>
def test_new_style_release_notes_patch():
"""
In the conventional-commits template (see: https://github.com/conventional-changelog/conventional-changelog),
patches are an H3 header and are linked to the underlying issue that created the release.
"""
expected = """### Bug Fixes
* include 'x-goog-request-params' header in requests ([#167](https://www.github.com/googleapis/nodejs-os-login/issues/167)) ([074051d](https://www.github.com/googleapis/nodejs-os-login/commit/074051d))"""
ctx = TagContext(release_version="v0.3.3")
_get_latest_release_notes(ctx, fixture_new_and_old_style_changelog)
assert ctx.release_notes == expected
def test_new_style_release_notes_breaking():
"""
in the conventional-commits template, features/breaking-changes use an H2 header.
"""
expected = """### Features
* added the most amazing feature ever ([42f90e2](https://www.github.com/bcoe/examples-conventional-commits/commit/42f90e2))
* adds a fancy new feature ([c46bfa3](https://www.github.com/bcoe/examples-conventional-commits/commit/c46bfa3))
### BREAKING CHANGES
* this fancy new feature breaks things
* disclaimer breaks everything"""
ctx = TagContext(release_version="v2.0.0")
_get_latest_release_notes(ctx, fixture_new_style_changelog)
<|code_end|>
. Write the next line using the current file imports:
from releasetool.commands.tag.nodejs import (
_get_latest_release_notes,
kokoro_job_name,
package_name,
)
from releasetool.commands.common import TagContext
and context from other files:
# Path: releasetool/commands/tag/nodejs.py
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# # the 'v' prefix is not used in the conventional-changelog templates
# # used in automated CHANGELOG generation:
# version = re.sub(r"^v", "", ctx.release_version)
# match = re.search(
# rf"## v?\[?{version}[^\n]*\n(?P<notes>.+?)(\n##\s|\n### \[?[0-9]+\.|\Z)",
# changelog,
# re.DOTALL | re.MULTILINE,
# )
# if match is not None:
# ctx.release_notes = match.group("notes").strip()
# else:
# ctx.release_notes = ""
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/nodejs/release/{upstream_repo}/publish"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
#
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
, which may include functions, classes, or code. Output only the next line. | assert ctx.release_notes == expected |
Continue the code snippet: <|code_start|>
### Bug Fixes
- fix: throw on invalid credentials ([#281](https://github.com/googleapis/nodejs-dialogflow/pull/281))
## v0.8.1
01-28-2019 13:24 PST
### Documentation
- fix(docs): dialogflow inn't published under @google-cloud scope ([#266](https://github.com/googleapis/nodejs-dialogflow/pull/266))
## v0.8.0
"""
fixture_new_and_old_style_changelog = """
# Changelog
[npm history][1]
[1]: https://www.npmjs.com/package/@google-cloud/os-login?activeTab=versions
### [0.3.3](https://www.github.com/googleapis/nodejs-os-login/compare/v0.3.2...v0.3.3) (2019-04-30)
### Bug Fixes
* include 'x-goog-request-params' header in requests ([#167](https://www.github.com/googleapis/nodejs-os-login/issues/167)) ([074051d](https://www.github.com/googleapis/nodejs-os-login/commit/074051d))
## v0.3.2
<|code_end|>
. Use current file imports:
from releasetool.commands.tag.nodejs import (
_get_latest_release_notes,
kokoro_job_name,
package_name,
)
from releasetool.commands.common import TagContext
and context (classes, functions, or code) from other files:
# Path: releasetool/commands/tag/nodejs.py
# def _get_latest_release_notes(ctx: TagContext, changelog: str):
# # the 'v' prefix is not used in the conventional-changelog templates
# # used in automated CHANGELOG generation:
# version = re.sub(r"^v", "", ctx.release_version)
# match = re.search(
# rf"## v?\[?{version}[^\n]*\n(?P<notes>.+?)(\n##\s|\n### \[?[0-9]+\.|\Z)",
# changelog,
# re.DOTALL | re.MULTILINE,
# )
# if match is not None:
# ctx.release_notes = match.group("notes").strip()
# else:
# ctx.release_notes = ""
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/nodejs/release/{upstream_repo}/publish"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
#
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | 03-18-2019 13:47 PDT |
Using the snippet: <|code_start|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert job_name is None
def test_package_name():
name = package_name({"head": {"ref": "release-storage-v1.2.3"}})
<|code_end|>
, determine the next line of code. You have imports:
from releasetool.commands.tag.php import kokoro_job_name, package_name
and context (class names, function names, or code) available:
# Path: releasetool/commands/tag/php.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return None
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | assert name is None |
Here is a snippet: <|code_start|> "skipping tests that require a valid github token", allow_module_level=True
)
def repo_name_to_test_name(repo_name: str) -> str:
letters = []
for letter in repo_name:
if letter in string.ascii_lowercase:
letters.append(letter)
elif letter in string.ascii_uppercase:
if letters:
letters.append("_")
letters.append(letter.lower())
else:
letters.append("_")
return "test_guess_" + "".join(letters)
def test_determine_language():
# determine_language() is the old function that depends on sloth's repo.json.
# Use it to generate the code for test_guess_language() so we can confirm
# the output is 100% the same.
repos_json = (pathlib.Path(__file__).parent / "testdata" / "repos.json").read_text()
repos = json.loads(repos_json)["repos"]
python_tools_repo_names = [
"googleapis/releasetool",
"googleapis/synthtool",
]
<|code_end|>
. Write the next line using the current file imports:
import json
import os
import pathlib
import pytest
import string
from autorelease import github
from autorelease.common import _determine_language, guess_language
and context from other files:
# Path: autorelease/github.py
# _GITHUB_ROOT: str = "https://api.github.com"
# _MAGIC_GITHUB_PROXY_ROOT: str = (
# "https://magic-github-proxy.endpoints.devrel-prod.cloud.goog"
# )
# def _find_devrel_api_key() -> str:
# def __init__(self, token: str, use_proxy: bool = False) -> None:
# def get_url(self, url: str = None, **kwargs) -> dict:
# def list_org_repos(self, org: str, type: str = None) -> Generator[dict, None, None]:
# def list_org_issues(
# self, org: str, state: str = None, labels: str = None, created_after: str = None
# ) -> Generator[dict, None, None]:
# def list_pull_requests(self, repository: str, **kwargs) -> Sequence[Dict]:
# def create_pull_request(
# self, repository: str, branch: str, title: str, body: str = None
# ) -> dict:
# def replace_issue_labels(
# self, owner: str, repository: str, number: str, labels: Sequence[str]
# ) -> dict:
# def update_pull_labels(
# self, pull: dict, add: Sequence[str] = None, remove: Sequence[str] = None
# ) -> dict:
# def get_tree(self, repository: str, tree_sha: str = "master") -> Sequence[dict]:
# def get_contents(self, repository: str, path: str, ref: str = None) -> bytes:
# def get_issue(self, repository: str, number: int) -> dict:
# def list_files(self, repository: str, path: str, ref: str = None) -> Sequence[dict]:
# def check_for_file(self, repository: str, path: str, ref: str = None) -> bool:
# def create_release(
# self,
# repository: str,
# tag_name: str,
# target_commitish: str,
# name: str,
# body: str,
# ) -> Dict:
# def create_pull_request_comment(
# self, repository: str, pull_request_number: int, comment: str
# ) -> Dict:
# def get_languages(self, repository) -> Dict[str, int]:
# class GitHub:
#
# Path: autorelease/common.py
# def _determine_language(
# fetch_repos_json: Callable[[], str], repo_full_name: str
# ) -> str:
# python_tools = ["synthtool"]
#
# if repo_full_name.split("/")[1] in python_tools:
# return "python_tool"
#
# repos = json.loads(fetch_repos_json())["repos"]
# for repo in repos:
# if repo_full_name == repo["repo"]:
# return repo["language"]
#
# raise Exception("Unable to determine repository language.")
#
# def guess_language(gh: GitHub, repo_full_name: str) -> str:
# special_cases = {
# # 1 special case inherited from the original determine_language() code.
# "googleapis/synthtool": "python_tool",
# # 2 more special cases where the most prevalent language is not the same as
# # what was declared in the old repos.json.
# "GoogleCloudPlatform/cloud-code-samples": "dotnet",
# "googleapis/doc-templates": "python",
# }
# special_case = special_cases.get(repo_full_name)
# if special_case:
# return special_case
#
# # Does the repo name have a language name in it?
# lang_names = {
# "cpp",
# "dotnet",
# "elixir",
# "go",
# "java",
# "nodejs",
# "php",
# "python",
# "python_tool",
# "ruby",
# }
# chunks = set(re.split("/|-", repo_full_name))
# x = lang_names.intersection(chunks)
# if 1 == len(x):
# return x.pop() # Found the language name in the repo name
#
# # Fetch how many lines of each language are found in the repo.
# languages = gh.get_languages(repo_full_name)
# ranks = [
# (count, lang)
# for (lang, count) in languages.items()
# # Ignore languages we don't care about, like Shell.
# if lang in _SILVER_LANGUAGE_NAMES
# ]
# ranks.sort(reverse=True)
# if ranks:
# # Return the most prevalent language in the repo.
# return _SILVER_LANGUAGE_NAMES[ranks[0][1]]
# else:
# raise Exception("Unable to determine repository language.")
, which may include functions, classes, or code. Output only the next line. | repo_names = python_tools_repo_names + [repo["repo"] for repo in repos] |
Predict the next line for this snippet: <|code_start|> letters.append(letter)
elif letter in string.ascii_uppercase:
if letters:
letters.append("_")
letters.append(letter.lower())
else:
letters.append("_")
return "test_guess_" + "".join(letters)
def test_determine_language():
# determine_language() is the old function that depends on sloth's repo.json.
# Use it to generate the code for test_guess_language() so we can confirm
# the output is 100% the same.
repos_json = (pathlib.Path(__file__).parent / "testdata" / "repos.json").read_text()
repos = json.loads(repos_json)["repos"]
python_tools_repo_names = [
"googleapis/releasetool",
"googleapis/synthtool",
]
repo_names = python_tools_repo_names + [repo["repo"] for repo in repos]
languages = set()
for name in repo_names:
language = _determine_language(lambda: repos_json, name)
languages.add((language, name))
for language, name in sorted(languages):
test_name = repo_name_to_test_name(name)
print(
<|code_end|>
with the help of current file imports:
import json
import os
import pathlib
import pytest
import string
from autorelease import github
from autorelease.common import _determine_language, guess_language
and context from other files:
# Path: autorelease/github.py
# _GITHUB_ROOT: str = "https://api.github.com"
# _MAGIC_GITHUB_PROXY_ROOT: str = (
# "https://magic-github-proxy.endpoints.devrel-prod.cloud.goog"
# )
# def _find_devrel_api_key() -> str:
# def __init__(self, token: str, use_proxy: bool = False) -> None:
# def get_url(self, url: str = None, **kwargs) -> dict:
# def list_org_repos(self, org: str, type: str = None) -> Generator[dict, None, None]:
# def list_org_issues(
# self, org: str, state: str = None, labels: str = None, created_after: str = None
# ) -> Generator[dict, None, None]:
# def list_pull_requests(self, repository: str, **kwargs) -> Sequence[Dict]:
# def create_pull_request(
# self, repository: str, branch: str, title: str, body: str = None
# ) -> dict:
# def replace_issue_labels(
# self, owner: str, repository: str, number: str, labels: Sequence[str]
# ) -> dict:
# def update_pull_labels(
# self, pull: dict, add: Sequence[str] = None, remove: Sequence[str] = None
# ) -> dict:
# def get_tree(self, repository: str, tree_sha: str = "master") -> Sequence[dict]:
# def get_contents(self, repository: str, path: str, ref: str = None) -> bytes:
# def get_issue(self, repository: str, number: int) -> dict:
# def list_files(self, repository: str, path: str, ref: str = None) -> Sequence[dict]:
# def check_for_file(self, repository: str, path: str, ref: str = None) -> bool:
# def create_release(
# self,
# repository: str,
# tag_name: str,
# target_commitish: str,
# name: str,
# body: str,
# ) -> Dict:
# def create_pull_request_comment(
# self, repository: str, pull_request_number: int, comment: str
# ) -> Dict:
# def get_languages(self, repository) -> Dict[str, int]:
# class GitHub:
#
# Path: autorelease/common.py
# def _determine_language(
# fetch_repos_json: Callable[[], str], repo_full_name: str
# ) -> str:
# python_tools = ["synthtool"]
#
# if repo_full_name.split("/")[1] in python_tools:
# return "python_tool"
#
# repos = json.loads(fetch_repos_json())["repos"]
# for repo in repos:
# if repo_full_name == repo["repo"]:
# return repo["language"]
#
# raise Exception("Unable to determine repository language.")
#
# def guess_language(gh: GitHub, repo_full_name: str) -> str:
# special_cases = {
# # 1 special case inherited from the original determine_language() code.
# "googleapis/synthtool": "python_tool",
# # 2 more special cases where the most prevalent language is not the same as
# # what was declared in the old repos.json.
# "GoogleCloudPlatform/cloud-code-samples": "dotnet",
# "googleapis/doc-templates": "python",
# }
# special_case = special_cases.get(repo_full_name)
# if special_case:
# return special_case
#
# # Does the repo name have a language name in it?
# lang_names = {
# "cpp",
# "dotnet",
# "elixir",
# "go",
# "java",
# "nodejs",
# "php",
# "python",
# "python_tool",
# "ruby",
# }
# chunks = set(re.split("/|-", repo_full_name))
# x = lang_names.intersection(chunks)
# if 1 == len(x):
# return x.pop() # Found the language name in the repo name
#
# # Fetch how many lines of each language are found in the repo.
# languages = gh.get_languages(repo_full_name)
# ranks = [
# (count, lang)
# for (lang, count) in languages.items()
# # Ignore languages we don't care about, like Shell.
# if lang in _SILVER_LANGUAGE_NAMES
# ]
# ranks.sort(reverse=True)
# if ranks:
# # Return the most prevalent language in the repo.
# return _SILVER_LANGUAGE_NAMES[ranks[0][1]]
# else:
# raise Exception("Unable to determine repository language.")
, which may contain function names, class names, or code. Output only the next line. | f"""def {test_name}(): |
Based on the snippet: <|code_start|># limitations under the License.
if not os.environ.get("GITHUB_TOKEN"):
pytest.skip(
"skipping tests that require a valid github token", allow_module_level=True
)
def repo_name_to_test_name(repo_name: str) -> str:
letters = []
for letter in repo_name:
if letter in string.ascii_lowercase:
letters.append(letter)
elif letter in string.ascii_uppercase:
if letters:
letters.append("_")
letters.append(letter.lower())
else:
letters.append("_")
return "test_guess_" + "".join(letters)
def test_determine_language():
# determine_language() is the old function that depends on sloth's repo.json.
# Use it to generate the code for test_guess_language() so we can confirm
# the output is 100% the same.
repos_json = (pathlib.Path(__file__).parent / "testdata" / "repos.json").read_text()
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import os
import pathlib
import pytest
import string
from autorelease import github
from autorelease.common import _determine_language, guess_language
and context (classes, functions, sometimes code) from other files:
# Path: autorelease/github.py
# _GITHUB_ROOT: str = "https://api.github.com"
# _MAGIC_GITHUB_PROXY_ROOT: str = (
# "https://magic-github-proxy.endpoints.devrel-prod.cloud.goog"
# )
# def _find_devrel_api_key() -> str:
# def __init__(self, token: str, use_proxy: bool = False) -> None:
# def get_url(self, url: str = None, **kwargs) -> dict:
# def list_org_repos(self, org: str, type: str = None) -> Generator[dict, None, None]:
# def list_org_issues(
# self, org: str, state: str = None, labels: str = None, created_after: str = None
# ) -> Generator[dict, None, None]:
# def list_pull_requests(self, repository: str, **kwargs) -> Sequence[Dict]:
# def create_pull_request(
# self, repository: str, branch: str, title: str, body: str = None
# ) -> dict:
# def replace_issue_labels(
# self, owner: str, repository: str, number: str, labels: Sequence[str]
# ) -> dict:
# def update_pull_labels(
# self, pull: dict, add: Sequence[str] = None, remove: Sequence[str] = None
# ) -> dict:
# def get_tree(self, repository: str, tree_sha: str = "master") -> Sequence[dict]:
# def get_contents(self, repository: str, path: str, ref: str = None) -> bytes:
# def get_issue(self, repository: str, number: int) -> dict:
# def list_files(self, repository: str, path: str, ref: str = None) -> Sequence[dict]:
# def check_for_file(self, repository: str, path: str, ref: str = None) -> bool:
# def create_release(
# self,
# repository: str,
# tag_name: str,
# target_commitish: str,
# name: str,
# body: str,
# ) -> Dict:
# def create_pull_request_comment(
# self, repository: str, pull_request_number: int, comment: str
# ) -> Dict:
# def get_languages(self, repository) -> Dict[str, int]:
# class GitHub:
#
# Path: autorelease/common.py
# def _determine_language(
# fetch_repos_json: Callable[[], str], repo_full_name: str
# ) -> str:
# python_tools = ["synthtool"]
#
# if repo_full_name.split("/")[1] in python_tools:
# return "python_tool"
#
# repos = json.loads(fetch_repos_json())["repos"]
# for repo in repos:
# if repo_full_name == repo["repo"]:
# return repo["language"]
#
# raise Exception("Unable to determine repository language.")
#
# def guess_language(gh: GitHub, repo_full_name: str) -> str:
# special_cases = {
# # 1 special case inherited from the original determine_language() code.
# "googleapis/synthtool": "python_tool",
# # 2 more special cases where the most prevalent language is not the same as
# # what was declared in the old repos.json.
# "GoogleCloudPlatform/cloud-code-samples": "dotnet",
# "googleapis/doc-templates": "python",
# }
# special_case = special_cases.get(repo_full_name)
# if special_case:
# return special_case
#
# # Does the repo name have a language name in it?
# lang_names = {
# "cpp",
# "dotnet",
# "elixir",
# "go",
# "java",
# "nodejs",
# "php",
# "python",
# "python_tool",
# "ruby",
# }
# chunks = set(re.split("/|-", repo_full_name))
# x = lang_names.intersection(chunks)
# if 1 == len(x):
# return x.pop() # Found the language name in the repo name
#
# # Fetch how many lines of each language are found in the repo.
# languages = gh.get_languages(repo_full_name)
# ranks = [
# (count, lang)
# for (lang, count) in languages.items()
# # Ignore languages we don't care about, like Shell.
# if lang in _SILVER_LANGUAGE_NAMES
# ]
# ranks.sort(reverse=True)
# if ranks:
# # Return the most prevalent language in the repo.
# return _SILVER_LANGUAGE_NAMES[ranks[0][1]]
# else:
# raise Exception("Unable to determine repository language.")
. Output only the next line. | repos = json.loads(repos_json)["repos"] |
Given snippet: <|code_start|> "ruby-spanner-activerecord",
"ruby-style",
"signet",
]
# Standard Ruby repos in the GoogleCloudPlatform org
RUBY_CLOUD_REPOS = [
"appengine-ruby",
"functions-framework-ruby",
"serverless-exec-ruby",
]
# Standard Ruby monorepos with gems located in subdirectories
RUBY_MONO_REPOS = [
"common-protos-ruby",
"gapic-generator-ruby",
"google-api-ruby-client",
"google-cloud-ruby",
]
def determine_release_pr(ctx: TagContext) -> None:
click.secho(
"> Let's figure out which pull request corresponds to your release.", fg="cyan"
)
pulls = ctx.github.list_pull_requests(ctx.upstream_repo, state="closed")
pulls = [pull for pull in pulls if "release" in pull["title"].lower()][:30]
click.secho("> Please pick one of the following PRs:\n")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import getpass
import re
import click
import releasetool.circleci
import releasetool.git
import releasetool.github
import releasetool.secrets
import releasetool.commands.common
from typing import Union
from requests import HTTPError
from releasetool.commands.common import TagContext
and context:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
which might include code, classes, or functions. Output only the next line. | for n, pull in enumerate(pulls, 1): |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
RELEASE_PLEASE_OUTPUT = """
✔ creating release v1.20.0
✔ Created release: https://github.com/googleapis/java-bigtable/releases/tag/v1.20.0.
<|code_end|>
, predict the next line using imports from the current file:
from releasetool.commands.tag.java import (
_parse_release_tag,
kokoro_job_name,
package_name,
)
and context including class names, function names, and sometimes code from other files:
# Path: releasetool/commands/tag/java.py
# def _parse_release_tag(output: str) -> str:
# match = re.search("creating release (v.*)", output)
# if match:
# return match[1]
# return None
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# repo_short_name = upstream_repo.split("/")[-1]
# return f"cloud-devrel/client-libraries/java/{repo_short_name}/release/stage"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | ✔ adding comment to https://github.com/googleapis/java-bigtable/issue/610 |
Predict the next line for this snippet: <|code_start|># Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
RELEASE_PLEASE_OUTPUT = """
✔ creating release v1.20.0
✔ Created release: https://github.com/googleapis/java-bigtable/releases/tag/v1.20.0.
✔ adding comment to https://github.com/googleapis/java-bigtable/issue/610
<|code_end|>
with the help of current file imports:
from releasetool.commands.tag.java import (
_parse_release_tag,
kokoro_job_name,
package_name,
)
and context from other files:
# Path: releasetool/commands/tag/java.py
# def _parse_release_tag(output: str) -> str:
# match = re.search("creating release (v.*)", output)
# if match:
# return match[1]
# return None
#
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# repo_short_name = upstream_repo.split("/")[-1]
# return f"cloud-devrel/client-libraries/java/{repo_short_name}/release/stage"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
, which may contain function names, class names, or code. Output only the next line. | ✔ adding label autorelease: tagged to https://github.com/googleapis/java-bigtable/pull/610 |
Here is a snippet: <|code_start|> }
pr2 = {
"base": {"ref": "def456", "repo": {"full_name": "googleapis/nodejs-container"}},
"pull_request": {
"url": "https://api.github.com/repos/googleapis/nodejs-container/pull/234",
"html_url": "https://github.com/nodejs/nodejs-container",
},
"title": "chore: release 1.0.0",
}
list_org_issues.side_effect = [[pr1, pr2]]
with requests_mock.Mocker() as m:
m.get(
"https://api.github.com/repos/googleapis/java-asset/pull/123",
json={
"merged_at": "2021-01-01T09:00:00.000Z",
"base": {"repo": {"full_name": "googleapis/java-asset"}},
},
)
m.get(
"https://api.github.com/repos/googleapis/nodejs-container/pull/234",
json={
"merged_at": "2021-01-01T09:00:00.000Z",
"base": {"repo": {"full_name": "googleapis/nodejs-container"}},
},
)
tag.main("github-token", "kokoro-credentials")
list_org_issues.assert_any_call(
org="googleapis", state="closed", labels="autorelease: pending"
)
list_org_issues.assert_any_call(
<|code_end|>
. Write the next line using the current file imports:
import requests_mock
from unittest.mock import patch, Mock
from autorelease import tag
and context from other files:
# Path: autorelease/tag.py
# LANGUAGE_ALLOWLIST = [
# "dotnet",
# "ruby",
# ]
# ORGANIZATIONS_TO_SCAN = ["googleapis", "GoogleCloudPlatform"]
# def run_releasetool_tag(lang: str, gh: github.GitHub, pull: dict) -> TagContext:
# def process_issue(
# kokoro_session, gh: github.GitHub, issue: dict, result: reporter.Result
# ) -> None:
# def main(github_token: str, kokoro_credentials: str) -> reporter.Reporter:
, which may include functions, classes, or code. Output only the next line. | org="GoogleCloudPlatform", state="closed", labels="autorelease: pending" |
Predict the next line after this snippet: <|code_start|># Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
RELEASE_LINE_PATTERN = r"^(?:- )?Release ([^ ]*) version (\d+\.\d+.\d+(-[^ ]*)?)$"
def determine_release_pr(ctx: TagContext) -> None:
click.secho(
"> Let's figure out which pull request corresponds to your release.", fg="cyan"
)
pulls = ctx.github.list_pull_requests(ctx.upstream_repo, state="closed")
pulls = [pull for pull in pulls if "release" in pull["title"].lower()][:30]
click.secho("> Please pick one of the following PRs:\n")
<|code_end|>
using the current file's imports:
import getpass
import re
import click
import releasetool.git
import releasetool.github
import releasetool.secrets
import releasetool.commands.common
from typing import Union
from releasetool.commands.common import TagContext
and any relevant context from other files:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | for n, pull in enumerate(pulls, 1): |
Continue 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 and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert job_name == "cloud-devrel/client-libraries/some-package-name/release"
def test_kokoro_job_name_gapic():
job_name = kokoro_job_name(
"googleapis/google-cloud-ruby", "google-cloud-video-intelligence"
)
assert job_name == "cloud-devrel/client-libraries/google-cloud-ruby/release"
def test_kokoro_job_name_functions_framework():
job_name = kokoro_job_name(
"GoogleCloud/functions-framework-ruby", "functions_framework"
)
assert job_name == "cloud-devrel/ruby/functions-framework-ruby/release"
def test_kokoro_job_name_apiary():
job_name = kokoro_job_name("googleapis/google-api-ruby-client", "youtube")
<|code_end|>
. Use current file imports:
from releasetool.commands.tag.ruby import kokoro_job_name, package_name
and context (classes, functions, or code) from other files:
# Path: releasetool/commands/tag/ruby.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
#
# for name in RUBY_CLIENT_REPOS:
# if name in upstream_repo:
# return f"cloud-devrel/client-libraries/{name}/release"
# for name in RUBY_CLOUD_REPOS:
# if name in upstream_repo:
# return f"cloud-devrel/ruby/{name}/release"
#
# return f"cloud-devrel/client-libraries/{package_name}/release"
#
# def package_name(pull: dict) -> Union[str, None]:
# head_ref = pull["head"]["ref"]
# click.secho(f"PR head ref is {head_ref}")
# match = re.match(r"release-(.+)-v(\d+\.\d+\.\d+)", head_ref)
# if match is None:
# return None
#
# return match.group(1)
. Output only the next line. | assert job_name == "cloud-devrel/client-libraries/google-api-ruby-client/release" |
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert job_name == "cloud-devrel/client-libraries/some-package-name/release"
def test_kokoro_job_name_gapic():
job_name = kokoro_job_name(
"googleapis/google-cloud-ruby", "google-cloud-video-intelligence"
)
assert job_name == "cloud-devrel/client-libraries/google-cloud-ruby/release"
<|code_end|>
with the help of current file imports:
from releasetool.commands.tag.ruby import kokoro_job_name, package_name
and context from other files:
# Path: releasetool/commands/tag/ruby.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
#
# for name in RUBY_CLIENT_REPOS:
# if name in upstream_repo:
# return f"cloud-devrel/client-libraries/{name}/release"
# for name in RUBY_CLOUD_REPOS:
# if name in upstream_repo:
# return f"cloud-devrel/ruby/{name}/release"
#
# return f"cloud-devrel/client-libraries/{package_name}/release"
#
# def package_name(pull: dict) -> Union[str, None]:
# head_ref = pull["head"]["ref"]
# click.secho(f"PR head ref is {head_ref}")
# match = re.match(r"release-(.+)-v(\d+\.\d+\.\d+)", head_ref)
# if match is None:
# return None
#
# return match.group(1)
, which may contain function names, class names, or code. Output only the next line. | def test_kokoro_job_name_functions_framework(): |
Predict the next line after this 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 and
# limitations under the License.
# Repos that have their publication process handled by GitHub actions:
manifest_release = [
"googleapis/google-api-nodejs-client",
"googleapis/repo-automation-bots",
]
def determine_release_pr(ctx: TagContext) -> None:
click.secho(
"> Let's figure out which pull request corresponds to your release.", fg="cyan"
)
pulls = ctx.github.list_pull_requests(ctx.upstream_repo, state="closed")
pulls = [pull for pull in pulls if "release" in pull["title"].lower()][:30]
click.secho("> Please pick one of the following PRs:\n")
for n, pull in enumerate(pulls, 1):
print(f"\t{n}: {pull['title']} ({pull['number']})")
pull_idx = click.prompt(
"\nWhich one do you want to tag and release?", type=click.INT
<|code_end|>
using the current file's imports:
import getpass
import re
import click
import releasetool.circleci
import releasetool.git
import releasetool.github
import releasetool.secrets
import releasetool.commands.common
import subprocess
import tempfile
from typing import Union
from releasetool.commands.common import TagContext
and any relevant context from other files:
# Path: releasetool/commands/common.py
# class TagContext(GitHubContext):
# release_pr: Optional[dict] = None
# release_tag: Optional[str] = None
# release_version: Optional[str] = None
# github_release: Optional[dict] = None
# kokoro_job_name: Optional[str] = None
# fusion_url: Optional[str] = None
# token: Optional[str] = None
. Output only the next line. | ) |
Given the code snippet: <|code_start|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert (
job_name
<|code_end|>
, generate the next line using the imports in this file:
from releasetool.commands.tag.python import kokoro_job_name, package_name
and context (functions, classes, or occasionally code) from other files:
# Path: releasetool/commands/tag/python.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# if upstream_repo in release_pool_repos:
# return f"cloud-devrel/client-libraries/release/python/{upstream_repo}/release"
# else:
# return f"cloud-devrel/client-libraries/python/{upstream_repo}/release/release"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | == "cloud-devrel/client-libraries/python/upstream-owner/upstream-repo/release/release" |
Given the code snippet: <|code_start|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert job_name == "cloud-devrel/client-libraries/some-package-name/release"
def test_package_name():
name = package_name({"head": {"ref": "release-storage-v1.2.3"}})
<|code_end|>
, generate the next line using the imports in this file:
from releasetool.commands.tag.python_tool import kokoro_job_name, package_name
and context (functions, classes, or occasionally code) from other files:
# Path: releasetool/commands/tag/python_tool.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/{package_name}/release"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
. Output only the next line. | assert name is None |
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_kokoro_job_name():
job_name = kokoro_job_name("upstream-owner/upstream-repo", "some-package-name")
assert job_name == "cloud-devrel/client-libraries/some-package-name/release"
<|code_end|>
with the help of current file imports:
from releasetool.commands.tag.python_tool import kokoro_job_name, package_name
and context from other files:
# Path: releasetool/commands/tag/python_tool.py
# def kokoro_job_name(upstream_repo: str, package_name: str) -> Union[str, None]:
# """Return the Kokoro job name.
#
# Args:
# upstream_repo (str): The GitHub repo in the form of `<owner>/<repo>`
# package_name (str): The name of package to release
#
# Returns:
# The name of the Kokoro job to trigger or None if there is no job to trigger
# """
# return f"cloud-devrel/client-libraries/{package_name}/release"
#
# def package_name(pull: dict) -> Union[str, None]:
# return None
, which may contain function names, class names, or code. Output only the next line. | def test_package_name(): |
Given the following code snippet before the placeholder: <|code_start|>@patch("autorelease.kokoro.trigger_build")
def test_trigger_single_bad_url(trigger_build, make_authorized_session):
kokoro_session = Mock()
make_authorized_session.return_value = kokoro_session
pull_request_url = "https://github.com/googleapis/java-trace/issues/1234"
reporter = trigger.trigger_single(
"fake-github-token", "fake-kokoro-credentials", pull_request_url
)
assert len(reporter.results) == 1
trigger_build.assert_not_called()
@patch("autorelease.kokoro.make_authorized_session")
@patch("autorelease.github.GitHub.get_issue")
@patch("autorelease.github.GitHub.get_url")
@patch("autorelease.github.GitHub.update_pull_labels")
@patch("autorelease.kokoro.trigger_build")
def test_trigger_single_skips_already_triggered(
trigger_build, update_pull_labels, get_url, get_issue, make_authorized_session
):
kokoro_session = Mock()
make_authorized_session.return_value = kokoro_session
get_issue.return_value = {
"title": "chore: release 1.2.3",
"pull_request": {
"html_url": "https://github.com/googleapis/java-trace/pull/1234",
"url": "https://api.github.com/repos/googleapis/java-trace/pulls/1234",
},
<|code_end|>
, predict the next line using imports from the current file:
from unittest.mock import patch, Mock
from autorelease import trigger
and context including class names, function names, and sometimes code from other files:
# Path: autorelease/trigger.py
# LANGUAGE_ALLOWLIST = []
# ORGANIZATIONS_TO_SCAN = ["googleapis", "GoogleCloudPlatform"]
# CREATED_AFTER = "2021-04-01"
# def trigger_kokoro_build_for_pull_request(
# kokoro_session,
# gh: github.GitHub,
# issue: dict,
# result,
# update_labels: bool = True,
# use_allowlist: bool = True,
# ) -> None:
# def _parse_issue(pull_request_url: str) -> Tuple[str, int]:
# def trigger_single(
# github_token: str, kokoro_credentials: str, pull_request_url: str
# ) -> reporter.Reporter:
# def main(github_token: str, kokoro_credentials: str) -> reporter.Reporter:
. Output only the next line. | } |
Predict the next line after this snippet: <|code_start|>
def determine_release_version(ctx: Context) -> None:
ctx.release_version = (
datetime.datetime.now(datetime.timezone.utc)
.astimezone(tz.gettz("US/Pacific"))
.strftime("%Y.%m.%d")
)
if ctx.release_version in ctx.last_release_version:
click.secho(
f"The release version {ctx.release_version} is already used.", fg="red"
)
ctx.release_version = click.prompt("Please input another version: ")
click.secho(f"Releasing {ctx.release_version}.")
def start() -> None:
# Python tools use calver, otherwise the process is the same as python
# libraries.
ctx = Context()
click.secho(f"o/ Hey, {getpass.getuser()}, let's release some stuff!", fg="magenta")
releasetool.commands.common.setup_github_context(ctx)
releasetool.commands.start.python.determine_package_name(ctx)
releasetool.commands.start.python.determine_last_release(ctx)
releasetool.commands.start.python.gather_changes(ctx)
releasetool.commands.common.edit_release_notes(ctx)
<|code_end|>
using the current file's imports:
import getpass
import datetime
import click
import releasetool.commands.start.python
from dateutil import tz
from releasetool.commands.start.python import Context
and any relevant context from other files:
# Path: releasetool/commands/start/python.py
# class Context(releasetool.commands.common.GitHubContext):
# last_release_version: Optional[str] = None
# last_release_committish: Optional[str] = None
# release_version: Optional[str] = None
# release_branch: Optional[str] = None
# pull_request: Optional[dict] = None
# monorepo: bool = False # true only when releasing from google-cloud-python
. Output only the next line. | determine_release_version(ctx) |
Continue the code snippet: <|code_start|>
if TYPE_CHECKING:
logger = logging.getLogger(__name__)
User = get_user_model()
DEFAULT_PROCESSOR = 'djangosaml2idp.processors.BaseProcessor'
DEFAULT_ATTRIBUTE_MAPPING = {
# DJANGO: SAML
'email': 'email',
'first_name': 'first_name',
'last_name': 'last_name',
'is_staff': 'is_staff',
'is_superuser': 'is_superuser',
}
def get_default_processor() -> str:
if hasattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_PROCESSOR'):
return getattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_PROCESSOR')
return DEFAULT_PROCESSOR
def get_default_attribute_mapping() -> str:
if hasattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_ATTRIBUTE_MAPPING'):
return json.dumps(getattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_ATTRIBUTE_MAPPING'))
<|code_end|>
. Use current file imports:
import datetime
import json
import logging
import uuid
import os
import pytz
from typing import Dict
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from saml2 import xmldsig
from .idp import IDP
from .utils import (extract_validuntil_from_metadata, fetch_metadata,
validate_metadata)
from typing import TYPE_CHECKING
from .processors import BaseProcessor
from .processors import validate_processor_path, instantiate_processor
and context (classes, functions, or code) from other files:
# Path: djangosaml2idp/idp.py
# class IDP:
# """ Access point for the IDP Server instance
# """
# _server_instance: Server = None
#
# @classmethod
# def construct_metadata(cls, with_local_sp: bool = True) -> dict:
# """ Get the config including the metadata for all the configured service providers. """
# from .models import ServiceProvider
# idp_config = copy.deepcopy(settings.SAML_IDP_CONFIG)
# if idp_config:
# idp_config['metadata'] = { # type: ignore
# 'local': (
# [sp.metadata_path() for sp in ServiceProvider.objects.filter(active=True)]
# if with_local_sp else []),
# }
# return idp_config
#
# @classmethod
# def load(cls, force_refresh: bool = False) -> Server:
# """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
# Throws an ImproperlyConfigured exception if it could not do so for any reason.
# """
# if cls._server_instance is None or force_refresh:
# conf = IdPConfig()
# md = cls.construct_metadata()
# try:
# conf.load(md)
# cls._server_instance = Server(config=conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return cls._server_instance
#
# @classmethod
# def metadata(cls) -> str:
# """ Get the IDP metadata as a string. """
# conf = IdPConfig()
# try:
# conf.load(cls.construct_metadata(with_local_sp=False))
# metadata = entity_descriptor(conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return str(metadata)
#
# Path: djangosaml2idp/utils.py
# def extract_validuntil_from_metadata(metadata: str) -> datetime.datetime:
# ''' Extract the ValidUntil timestamp from the given metadata. Returns that timestamp if successfully, raise a ValidationError otherwise.
# '''
# try:
# metadata_expiration_dt = arrow.get(ET.fromstring(metadata).attrib['validUntil']).datetime
# except Exception as e:
# fallback = getattr(settings, "SAML_IDP_FALLBACK_EXPIRATION_DAYS", 0)
# if fallback:
# return now() + datetime.timedelta(days=fallback)
# raise ValidationError(f'Could not extra ValidUntil timestamp from metadata: {e}')
#
# if not settings.USE_TZ:
# return metadata_expiration_dt.replace(tzinfo=None)
# if is_naive(metadata_expiration_dt):
# return make_aware(metadata_expiration_dt)
# return metadata_expiration_dt
#
# def fetch_metadata(remote_metadata_url: str) -> str:
# ''' Fetch remote metadata. Raise a ValidationError if it could not successfully fetch something from the url '''
# try:
# content = requests.get(remote_metadata_url, timeout=(3, 10))
# if content.status_code != 200:
# raise Exception(f'Non-successful request, received status code {content.status_code}')
# except Exception as e:
# raise ValidationError(f'Could not fetch metadata from {remote_metadata_url}: {e}')
# return content.text
#
# def validate_metadata(metadata: str) -> str:
# ''' Validate if the given metadata is valid xml, raise a ValidationError otherwise. Returns the metadata string back.
# '''
# try:
# ET.fromstring(metadata)
# except Exception as e:
# raise ValidationError(f'Metadata is not valid metadata xml: {e}')
# return metadata
. Output only the next line. | return json.dumps(DEFAULT_ATTRIBUTE_MAPPING) |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
logger = logging.getLogger(__name__)
User = get_user_model()
DEFAULT_PROCESSOR = 'djangosaml2idp.processors.BaseProcessor'
DEFAULT_ATTRIBUTE_MAPPING = {
# DJANGO: SAML
'email': 'email',
'first_name': 'first_name',
'last_name': 'last_name',
'is_staff': 'is_staff',
'is_superuser': 'is_superuser',
}
def get_default_processor() -> str:
if hasattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_PROCESSOR'):
return getattr(settings, 'SAML_IDP_SP_FIELD_DEFAULT_PROCESSOR')
<|code_end|>
with the help of current file imports:
import datetime
import json
import logging
import uuid
import os
import pytz
from typing import Dict
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from saml2 import xmldsig
from .idp import IDP
from .utils import (extract_validuntil_from_metadata, fetch_metadata,
validate_metadata)
from typing import TYPE_CHECKING
from .processors import BaseProcessor
from .processors import validate_processor_path, instantiate_processor
and context from other files:
# Path: djangosaml2idp/idp.py
# class IDP:
# """ Access point for the IDP Server instance
# """
# _server_instance: Server = None
#
# @classmethod
# def construct_metadata(cls, with_local_sp: bool = True) -> dict:
# """ Get the config including the metadata for all the configured service providers. """
# from .models import ServiceProvider
# idp_config = copy.deepcopy(settings.SAML_IDP_CONFIG)
# if idp_config:
# idp_config['metadata'] = { # type: ignore
# 'local': (
# [sp.metadata_path() for sp in ServiceProvider.objects.filter(active=True)]
# if with_local_sp else []),
# }
# return idp_config
#
# @classmethod
# def load(cls, force_refresh: bool = False) -> Server:
# """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
# Throws an ImproperlyConfigured exception if it could not do so for any reason.
# """
# if cls._server_instance is None or force_refresh:
# conf = IdPConfig()
# md = cls.construct_metadata()
# try:
# conf.load(md)
# cls._server_instance = Server(config=conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return cls._server_instance
#
# @classmethod
# def metadata(cls) -> str:
# """ Get the IDP metadata as a string. """
# conf = IdPConfig()
# try:
# conf.load(cls.construct_metadata(with_local_sp=False))
# metadata = entity_descriptor(conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return str(metadata)
#
# Path: djangosaml2idp/utils.py
# def extract_validuntil_from_metadata(metadata: str) -> datetime.datetime:
# ''' Extract the ValidUntil timestamp from the given metadata. Returns that timestamp if successfully, raise a ValidationError otherwise.
# '''
# try:
# metadata_expiration_dt = arrow.get(ET.fromstring(metadata).attrib['validUntil']).datetime
# except Exception as e:
# fallback = getattr(settings, "SAML_IDP_FALLBACK_EXPIRATION_DAYS", 0)
# if fallback:
# return now() + datetime.timedelta(days=fallback)
# raise ValidationError(f'Could not extra ValidUntil timestamp from metadata: {e}')
#
# if not settings.USE_TZ:
# return metadata_expiration_dt.replace(tzinfo=None)
# if is_naive(metadata_expiration_dt):
# return make_aware(metadata_expiration_dt)
# return metadata_expiration_dt
#
# def fetch_metadata(remote_metadata_url: str) -> str:
# ''' Fetch remote metadata. Raise a ValidationError if it could not successfully fetch something from the url '''
# try:
# content = requests.get(remote_metadata_url, timeout=(3, 10))
# if content.status_code != 200:
# raise Exception(f'Non-successful request, received status code {content.status_code}')
# except Exception as e:
# raise ValidationError(f'Could not fetch metadata from {remote_metadata_url}: {e}')
# return content.text
#
# def validate_metadata(metadata: str) -> str:
# ''' Validate if the given metadata is valid xml, raise a ValidationError otherwise. Returns the metadata string back.
# '''
# try:
# ET.fromstring(metadata)
# except Exception as e:
# raise ValidationError(f'Metadata is not valid metadata xml: {e}')
# return metadata
, which may contain function names, class names, or code. Output only the next line. | return DEFAULT_PROCESSOR |
Based on the snippet: <|code_start|>
if TYPE_CHECKING:
logger = logging.getLogger(__name__)
User = get_user_model()
DEFAULT_PROCESSOR = 'djangosaml2idp.processors.BaseProcessor'
DEFAULT_ATTRIBUTE_MAPPING = {
# DJANGO: SAML
'email': 'email',
'first_name': 'first_name',
'last_name': 'last_name',
'is_staff': 'is_staff',
'is_superuser': 'is_superuser',
}
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import json
import logging
import uuid
import os
import pytz
from typing import Dict
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from saml2 import xmldsig
from .idp import IDP
from .utils import (extract_validuntil_from_metadata, fetch_metadata,
validate_metadata)
from typing import TYPE_CHECKING
from .processors import BaseProcessor
from .processors import validate_processor_path, instantiate_processor
and context (classes, functions, sometimes code) from other files:
# Path: djangosaml2idp/idp.py
# class IDP:
# """ Access point for the IDP Server instance
# """
# _server_instance: Server = None
#
# @classmethod
# def construct_metadata(cls, with_local_sp: bool = True) -> dict:
# """ Get the config including the metadata for all the configured service providers. """
# from .models import ServiceProvider
# idp_config = copy.deepcopy(settings.SAML_IDP_CONFIG)
# if idp_config:
# idp_config['metadata'] = { # type: ignore
# 'local': (
# [sp.metadata_path() for sp in ServiceProvider.objects.filter(active=True)]
# if with_local_sp else []),
# }
# return idp_config
#
# @classmethod
# def load(cls, force_refresh: bool = False) -> Server:
# """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
# Throws an ImproperlyConfigured exception if it could not do so for any reason.
# """
# if cls._server_instance is None or force_refresh:
# conf = IdPConfig()
# md = cls.construct_metadata()
# try:
# conf.load(md)
# cls._server_instance = Server(config=conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return cls._server_instance
#
# @classmethod
# def metadata(cls) -> str:
# """ Get the IDP metadata as a string. """
# conf = IdPConfig()
# try:
# conf.load(cls.construct_metadata(with_local_sp=False))
# metadata = entity_descriptor(conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return str(metadata)
#
# Path: djangosaml2idp/utils.py
# def extract_validuntil_from_metadata(metadata: str) -> datetime.datetime:
# ''' Extract the ValidUntil timestamp from the given metadata. Returns that timestamp if successfully, raise a ValidationError otherwise.
# '''
# try:
# metadata_expiration_dt = arrow.get(ET.fromstring(metadata).attrib['validUntil']).datetime
# except Exception as e:
# fallback = getattr(settings, "SAML_IDP_FALLBACK_EXPIRATION_DAYS", 0)
# if fallback:
# return now() + datetime.timedelta(days=fallback)
# raise ValidationError(f'Could not extra ValidUntil timestamp from metadata: {e}')
#
# if not settings.USE_TZ:
# return metadata_expiration_dt.replace(tzinfo=None)
# if is_naive(metadata_expiration_dt):
# return make_aware(metadata_expiration_dt)
# return metadata_expiration_dt
#
# def fetch_metadata(remote_metadata_url: str) -> str:
# ''' Fetch remote metadata. Raise a ValidationError if it could not successfully fetch something from the url '''
# try:
# content = requests.get(remote_metadata_url, timeout=(3, 10))
# if content.status_code != 200:
# raise Exception(f'Non-successful request, received status code {content.status_code}')
# except Exception as e:
# raise ValidationError(f'Could not fetch metadata from {remote_metadata_url}: {e}')
# return content.text
#
# def validate_metadata(metadata: str) -> str:
# ''' Validate if the given metadata is valid xml, raise a ValidationError otherwise. Returns the metadata string back.
# '''
# try:
# ET.fromstring(metadata)
# except Exception as e:
# raise ValidationError(f'Metadata is not valid metadata xml: {e}')
# return metadata
. Output only the next line. | def get_default_processor() -> str: |
Predict the next line for this snippet: <|code_start|>
if TYPE_CHECKING:
logger = logging.getLogger(__name__)
User = get_user_model()
DEFAULT_PROCESSOR = 'djangosaml2idp.processors.BaseProcessor'
DEFAULT_ATTRIBUTE_MAPPING = {
# DJANGO: SAML
'email': 'email',
'first_name': 'first_name',
'last_name': 'last_name',
'is_staff': 'is_staff',
'is_superuser': 'is_superuser',
}
<|code_end|>
with the help of current file imports:
import datetime
import json
import logging
import uuid
import os
import pytz
from typing import Dict
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from saml2 import xmldsig
from .idp import IDP
from .utils import (extract_validuntil_from_metadata, fetch_metadata,
validate_metadata)
from typing import TYPE_CHECKING
from .processors import BaseProcessor
from .processors import validate_processor_path, instantiate_processor
and context from other files:
# Path: djangosaml2idp/idp.py
# class IDP:
# """ Access point for the IDP Server instance
# """
# _server_instance: Server = None
#
# @classmethod
# def construct_metadata(cls, with_local_sp: bool = True) -> dict:
# """ Get the config including the metadata for all the configured service providers. """
# from .models import ServiceProvider
# idp_config = copy.deepcopy(settings.SAML_IDP_CONFIG)
# if idp_config:
# idp_config['metadata'] = { # type: ignore
# 'local': (
# [sp.metadata_path() for sp in ServiceProvider.objects.filter(active=True)]
# if with_local_sp else []),
# }
# return idp_config
#
# @classmethod
# def load(cls, force_refresh: bool = False) -> Server:
# """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
# Throws an ImproperlyConfigured exception if it could not do so for any reason.
# """
# if cls._server_instance is None or force_refresh:
# conf = IdPConfig()
# md = cls.construct_metadata()
# try:
# conf.load(md)
# cls._server_instance = Server(config=conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return cls._server_instance
#
# @classmethod
# def metadata(cls) -> str:
# """ Get the IDP metadata as a string. """
# conf = IdPConfig()
# try:
# conf.load(cls.construct_metadata(with_local_sp=False))
# metadata = entity_descriptor(conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return str(metadata)
#
# Path: djangosaml2idp/utils.py
# def extract_validuntil_from_metadata(metadata: str) -> datetime.datetime:
# ''' Extract the ValidUntil timestamp from the given metadata. Returns that timestamp if successfully, raise a ValidationError otherwise.
# '''
# try:
# metadata_expiration_dt = arrow.get(ET.fromstring(metadata).attrib['validUntil']).datetime
# except Exception as e:
# fallback = getattr(settings, "SAML_IDP_FALLBACK_EXPIRATION_DAYS", 0)
# if fallback:
# return now() + datetime.timedelta(days=fallback)
# raise ValidationError(f'Could not extra ValidUntil timestamp from metadata: {e}')
#
# if not settings.USE_TZ:
# return metadata_expiration_dt.replace(tzinfo=None)
# if is_naive(metadata_expiration_dt):
# return make_aware(metadata_expiration_dt)
# return metadata_expiration_dt
#
# def fetch_metadata(remote_metadata_url: str) -> str:
# ''' Fetch remote metadata. Raise a ValidationError if it could not successfully fetch something from the url '''
# try:
# content = requests.get(remote_metadata_url, timeout=(3, 10))
# if content.status_code != 200:
# raise Exception(f'Non-successful request, received status code {content.status_code}')
# except Exception as e:
# raise ValidationError(f'Could not fetch metadata from {remote_metadata_url}: {e}')
# return content.text
#
# def validate_metadata(metadata: str) -> str:
# ''' Validate if the given metadata is valid xml, raise a ValidationError otherwise. Returns the metadata string back.
# '''
# try:
# ET.fromstring(metadata)
# except Exception as e:
# raise ValidationError(f'Metadata is not valid metadata xml: {e}')
# return metadata
, which may contain function names, class names, or code. Output only the next line. | def get_default_processor() -> str: |
Given snippet: <|code_start|>
class TestIDP:
@pytest.mark.django_db
def test_idp_load_default_settings_defined_and_valid(self):
IDP._server_instance = None
srv = IDP.load()
assert isinstance(srv, Server)
@pytest.mark.django_db
def test_idp_load_no_settings_defined(self, settings):
IDP._server_instance = None
settings.SAML_IDP_CONFIG = None
with pytest.raises(ImproperlyConfigured):
IDP.load()
@pytest.mark.django_db
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest.mock import patch, Mock
from django.core.exceptions import ImproperlyConfigured
from saml2.server import Server
from djangosaml2idp.idp import IDP
import pytest
and context:
# Path: djangosaml2idp/idp.py
# class IDP:
# """ Access point for the IDP Server instance
# """
# _server_instance: Server = None
#
# @classmethod
# def construct_metadata(cls, with_local_sp: bool = True) -> dict:
# """ Get the config including the metadata for all the configured service providers. """
# from .models import ServiceProvider
# idp_config = copy.deepcopy(settings.SAML_IDP_CONFIG)
# if idp_config:
# idp_config['metadata'] = { # type: ignore
# 'local': (
# [sp.metadata_path() for sp in ServiceProvider.objects.filter(active=True)]
# if with_local_sp else []),
# }
# return idp_config
#
# @classmethod
# def load(cls, force_refresh: bool = False) -> Server:
# """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
# Throws an ImproperlyConfigured exception if it could not do so for any reason.
# """
# if cls._server_instance is None or force_refresh:
# conf = IdPConfig()
# md = cls.construct_metadata()
# try:
# conf.load(md)
# cls._server_instance = Server(config=conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return cls._server_instance
#
# @classmethod
# def metadata(cls) -> str:
# """ Get the IDP metadata as a string. """
# conf = IdPConfig()
# try:
# conf.load(cls.construct_metadata(with_local_sp=False))
# metadata = entity_descriptor(conf)
# except Exception as e:
# raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
# return str(metadata)
which might include code, classes, or functions. Output only the next line. | def test_metadata_no_sp_defined_valid(self): |
Continue the code snippet: <|code_start|> '_attribute_mapping': json.dumps({
'name': 'fullName',
'email': 'emailAddress',
'other_setting': 'otherSetting',
'random_method': 'randomMethodTest'
}),
})
assert form.is_valid() is True
instance = form.save()
assert instance.remote_metadata_url == 'https://ok'
assert instance.local_metadata == sp_metadata_xml
assert instance.metadata_expiration_dt == datetime.datetime(2099, 2, 14, 17, 43, 34, tzinfo=tzinfo)
@pytest.mark.django_db
@mock.patch('requests.get')
def test_invalid_remote_metadata_url(self, mock_get):
mock_get.return_value = mock.Mock(status_code=200, text='BOGUS DATA')
form = ServiceProviderAdminForm({
'entity_id': 'entity-id',
'_processor': 'djangosaml2idp.processors.BaseProcessor',
'remote_metadata_url': 'https://ok',
'_attribute_mapping': json.dumps({
'name': 'fullName',
'email': 'emailAddress',
'other_setting': 'otherSetting',
'random_method': 'randomMethodTest'
}),
})
<|code_end|>
. Use current file imports:
import datetime
import json
import pytest
from unittest import mock
from django.contrib.auth import get_user_model
from django.utils import timezone
from djangosaml2idp.forms import ServiceProviderAdminForm
and context (classes, functions, or code) from other files:
# Path: djangosaml2idp/forms.py
# class ServiceProviderAdminForm(forms.ModelForm):
#
# class Meta:
# model = ServiceProvider
# # Keep in sync with readonly_fields on admin class.
# exclude = ('dt_created', 'dt_updated', 'resulting_config', 'metadata_expiration_dt')
# widgets = {
# '_encrypt_saml_responses': forms.Select(choices=boolean_form_select_choices),
# '_sign_response': forms.Select(choices=boolean_form_select_choices),
# '_sign_assertion': forms.Select(choices=boolean_form_select_choices),
# }
#
# def clean__attribute_mapping(self):
# value_as_string = self.cleaned_data['_attribute_mapping']
# try:
# value = json.loads(value_as_string)
# except Exception as e:
# raise ValidationError('The provided string could not be parsed with json. ({})'.format(e))
# if not isinstance(value, dict):
# raise ValidationError('The provided attribute_mapping should be a string representing a dict.')
# for k, v in value.items():
# if not isinstance(k, str) or not isinstance(v, str):
# raise ValidationError('The provided attribute_mapping should be a dict with strings for both all keys and values.')
# return json.dumps(value, indent=4)
#
# def clean__processor(self):
# value = self.cleaned_data['_processor']
# validate_processor_path(value)
# return value
#
# def clean(self):
# cleaned_data = super().clean()
#
# if not (cleaned_data.get('remote_metadata_url') or cleaned_data.get('local_metadata')):
# raise ValidationError('Either a remote metadata URL, or a local metadata xml needs to be provided.')
#
# if '_processor' in cleaned_data:
# processor_path = cleaned_data['_processor']
# entity_id = cleaned_data['entity_id']
#
# processor_cls = validate_processor_path(processor_path)
# instantiate_processor(processor_cls, entity_id)
#
# # Call the validation methods to catch ValidationErrors here, so they get displayed cleanly in the admin UI
# if cleaned_data.get('remote_metadata_url'):
# self.instance.remote_metadata_url = cleaned_data.get('remote_metadata_url')
# self.instance._refresh_from_remote()
# else:
# self.instance.local_metadata = cleaned_data.get('local_metadata')
# self.instance._refresh_from_local()
#
# # Replace the form value with the refreshed metadata.
# cleaned_data['local_metadata'] = self.instance.local_metadata
. Output only the next line. | assert form.is_valid() is False |
Using the snippet: <|code_start|>
class TestSAMLEncodeAndDecode:
@staticmethod
def prettify(xml_str: str) -> str:
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import xml
import pytest
from unittest import mock
from django.core.exceptions import ValidationError
from django.utils import timezone
from djangosaml2idp.utils import (encode_saml,
extract_validuntil_from_metadata,
fetch_metadata, repr_saml, validate_metadata,
verify_request_signature)
from .testing_utilities import mocked_requests_get
and context (class names, function names, or code) available:
# Path: djangosaml2idp/utils.py
# def encode_saml(saml_envelope: str, use_zlib: bool = False) -> bytes:
# # Not sure where 2:-4 came from, but that's how pysaml2 does it, and it works
# before_base64 = zlib.compress(saml_envelope.encode())[2:-4] if use_zlib else saml_envelope.encode()
# return base64.b64encode(before_base64)
#
# def extract_validuntil_from_metadata(metadata: str) -> datetime.datetime:
# ''' Extract the ValidUntil timestamp from the given metadata. Returns that timestamp if successfully, raise a ValidationError otherwise.
# '''
# try:
# metadata_expiration_dt = arrow.get(ET.fromstring(metadata).attrib['validUntil']).datetime
# except Exception as e:
# fallback = getattr(settings, "SAML_IDP_FALLBACK_EXPIRATION_DAYS", 0)
# if fallback:
# return now() + datetime.timedelta(days=fallback)
# raise ValidationError(f'Could not extra ValidUntil timestamp from metadata: {e}')
#
# if not settings.USE_TZ:
# return metadata_expiration_dt.replace(tzinfo=None)
# if is_naive(metadata_expiration_dt):
# return make_aware(metadata_expiration_dt)
# return metadata_expiration_dt
#
# def fetch_metadata(remote_metadata_url: str) -> str:
# ''' Fetch remote metadata. Raise a ValidationError if it could not successfully fetch something from the url '''
# try:
# content = requests.get(remote_metadata_url, timeout=(3, 10))
# if content.status_code != 200:
# raise Exception(f'Non-successful request, received status code {content.status_code}')
# except Exception as e:
# raise ValidationError(f'Could not fetch metadata from {remote_metadata_url}: {e}')
# return content.text
#
# def repr_saml(saml: str, b64: bool = False):
# """ Decode SAML from b64 and b64 deflated and return a pretty printed representation
# """
# try:
# msg = base64.b64decode(saml).decode() if b64 else saml
# dom = xml.dom.minidom.parseString(msg)
# except (UnicodeDecodeError, ExpatError):
# # in HTTP-REDIRECT the base64 must be inflated
# compressed = base64.b64decode(saml)
# inflated = zlib.decompress(compressed, -15)
# dom = xml.dom.minidom.parseString(inflated.decode())
# return dom.toprettyxml()
#
# def validate_metadata(metadata: str) -> str:
# ''' Validate if the given metadata is valid xml, raise a ValidationError otherwise. Returns the metadata string back.
# '''
# try:
# ET.fromstring(metadata)
# except Exception as e:
# raise ValidationError(f'Metadata is not valid metadata xml: {e}')
# return metadata
#
# def verify_request_signature(req_info: StatusResponse) -> None:
# """ Signature verification for authn request signature_check is at
# saml2.sigver.SecurityContext.correctly_signed_authn_request
# """
# if not req_info.signature_check(req_info.xmlstr):
# raise ValueError(_("Message signature verification failure"))
#
# Path: tests/testing_utilities.py
# def mocked_requests_get(*args, **kwargs):
# class MockResponse:
# def __init__(self, text, status_code):
# self.text = text
# self.status_code = status_code
#
# if args[0] == 'http://not_found':
# return MockResponse('not found', 404)
#
# return MockResponse('ok', 200)
. Output only the next line. | return xml.dom.minidom.parseString(xml_str).toprettyxml() |
Predict the next line for this snippet: <|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 express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
nova_opts = [
cfg.StrOpt('nova_overcloud_config',
default='etc/tuskar/nova_overcloud_config.yml',
help='nova overcloud keystone uri and credentials'),
]
LOG = log.getLogger(__name__)
CONF = cfg.CONF
CONF.register_opts(nova_opts)
class NovaClient(object):
def __init__(self):
#grab client params from nova_overcloud_config.yml:
try:
config_file = open(CONF.nova_overcloud_config)
client_params = simpleyaml.safe_load(config_file)
config_file.close()
except Exception:
<|code_end|>
with the help of current file imports:
from novaclient.v1_1 import client
from oslo.config import cfg
from tuskar.common import exception
from tuskar.openstack.common import jsonutils
from tuskar.openstack.common import log
import simpleyaml
and context from other files:
# Path: tuskar/common/exception.py
# LOG = logging.getLogger(__name__)
# CONF = cfg.CONF
# class ProcessExecutionError(IOError):
# class TuskarException(Exception):
# class NotAuthorized(TuskarException):
# class AdminRequired(NotAuthorized):
# class PolicyNotAuthorized(NotAuthorized):
# class Invalid(TuskarException):
# class InvalidCPUInfo(Invalid):
# class InvalidIpAddressError(Invalid):
# class InvalidDiskFormat(Invalid):
# class InvalidUUID(Invalid):
# class InvalidMAC(Invalid):
# class InvalidParameterValue(Invalid):
# class NotFound(TuskarException):
# class DiskNotFound(NotFound):
# class ImageNotFound(NotFound):
# class HostNotFound(NotFound):
# class ConsoleNotFound(NotFound):
# class FileNotFound(NotFound):
# class NoValidHost(NotFound):
# class InstanceNotFound(NotFound):
# class RackNotFound(NotFound):
# class FlavorNotFound(NotFound):
# class NodeLocked(NotFound):
# class PortNotFound(NotFound):
# class PowerStateFailure(TuskarException):
# class ExclusiveLockRequired(NotAuthorized):
# class IPMIFailure(TuskarException):
# def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
# description=None):
# def _cleanse_dict(original):
# def wrap_exception(notifier=None, publisher_id=None, event_type=None,
# level=None):
# def inner(f):
# def wrapped(self, context, *args, **kw):
# def __init__(self, message=None, **kwargs):
# def format_message(self):
#
# Path: tuskar/openstack/common/jsonutils.py
# def to_primitive(value, convert_instances=False, convert_datetime=True,
# level=0, max_depth=3):
# def dumps(value, default=to_primitive, **kwargs):
# def loads(s):
# def load(s):
#
# Path: tuskar/openstack/common/log.py
# _DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
# CONF = cfg.CONF
# LEVEL_COLORS = {
# logging.DEBUG: '\033[00;32m', # GREEN
# logging.INFO: '\033[00;36m', # CYAN
# logging.AUDIT: '\033[01;36m', # BOLD CYAN
# logging.WARN: '\033[01;33m', # BOLD YELLOW
# logging.ERROR: '\033[01;31m', # BOLD RED
# logging.CRITICAL: '\033[01;31m', # BOLD RED
# }
# class NullHandler(logging.Handler):
# class BaseLoggerAdapter(logging.LoggerAdapter):
# class LazyAdapter(BaseLoggerAdapter):
# class ContextAdapter(BaseLoggerAdapter):
# class JSONFormatter(logging.Formatter):
# class LogConfigError(Exception):
# class WritableLogger(object):
# class ContextFormatter(logging.Formatter):
# class ColorHandler(logging.StreamHandler):
# class DeprecatedConfig(Exception):
# def handle(self, record):
# def emit(self, record):
# def createLock(self):
# def _dictify_context(context):
# def _get_binary_name():
# def _get_log_file_path(binary=None):
# def audit(self, msg, *args, **kwargs):
# def __init__(self, name='unknown', version='unknown'):
# def logger(self):
# def __init__(self, logger, project_name, version_string):
# def handlers(self):
# def deprecated(self, msg, *args, **kwargs):
# def process(self, msg, kwargs):
# def __init__(self, fmt=None, datefmt=None):
# def formatException(self, ei, strip_newlines=True):
# def format(self, record):
# def _create_logging_excepthook(product_name):
# def logging_excepthook(type, value, tb):
# def __init__(self, log_config, err_msg):
# def __str__(self):
# def _load_log_config(log_config):
# def setup(product_name):
# def set_defaults(logging_context_format_string):
# def _find_facility_from_conf():
# def _setup_logging_from_conf():
# def getLogger(name='unknown', version='unknown'):
# def getLazyLogger(name='unknown', version='unknown'):
# def __init__(self, logger, level=logging.INFO):
# def write(self, msg):
# def format(self, record):
# def formatException(self, exc_info, record=None):
# def format(self, record):
# def __init__(self, msg):
, which may contain function names, class names, or code. Output only the next line. | raise |
Predict the next line for this snippet: <|code_start|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# -*- encoding: utf-8 -*-
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class DbSyncTestCase(base.DbTestCase):
def setUp(self):
super(DbSyncTestCase, self).setUp()
def test_sync_and_version(self):
migration.db_sync()
v = migration.db_version()
<|code_end|>
with the help of current file imports:
from tuskar.db import migration
from tuskar.tests.db import base
and context from other files:
# Path: tuskar/tests/db/base.py
# class DbTestCase(base.TestCase):
# def setUp(self):
, which may contain function names, class names, or code. Output only the next line. | self.assertTrue(v > migration.INIT_VERSION) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
project = 'tuskar'
setuptools.setup(
name=project,
version=common_setup.get_version(project, '2013.1'),
description='An OpenStack Management Service',
classifiers=[
'Environment :: OpenStack',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
<|code_end|>
with the help of current file imports:
import setuptools
from tuskar.openstack.common import setup as common_setup
and context from other files:
# Path: tuskar/openstack/common/setup.py
# def parse_mailmap(mailmap='.mailmap'):
# def _parse_git_mailmap(git_dir, mailmap='.mailmap'):
# def canonicalize_emails(changelog, mapping):
# def get_reqs_from_files(requirements_files):
# def parse_requirements(requirements_files=['requirements.txt',
# 'tools/pip-requires']):
# def parse_dependency_links(requirements_files=['requirements.txt',
# 'tools/pip-requires']):
# def _run_shell_command(cmd, throw_on_error=False):
# def _get_git_directory():
# def write_git_changelog():
# def generate_authors():
# def get_cmdclass():
# def _find_modules(arg, dirname, files):
# def run(self):
# def generate_autoindex(self):
# def run(self):
# def _get_revno(git_dir):
# def _get_version_from_git(pre_version):
# def _get_version_from_pkg_info(package_name):
# def get_version(package_name, pre_version=None):
# class LocalSDist(sdist.sdist):
# class LocalBuildDoc(BuildDoc):
# class LocalBuildLatex(LocalBuildDoc):
, which may contain function names, class names, or code. Output only the next line. | 'License :: OSI Approved :: Apache Software License', |
Given snippet: <|code_start|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
CONF = cfg.CONF
CONF.import_opt('use_ipv6', 'tuskar.netconf')
CONF.import_opt('host', 'tuskar.common.service')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import fixtures
from oslo.config import cfg
from tuskar.common import config
and context:
# Path: tuskar/common/config.py
# _DEFAULT_SQL_CONNECTION = 'sqlite:///' + paths.state_path_def('$sqlite_db')
# def parse_args(argv, default_config_files=None):
which might include code, classes, or functions. Output only the next line. | class ConfFixture(fixtures.Fixture): |
Using the snippet: <|code_start|># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
CONF = cfg.CONF
ironic_opts = [
cfg.StrOpt('ironic_url',
default='http://ironic.local:6543/v1',
help='Ironic API entrypoint URL'),
<|code_end|>
, determine the next line of code. You have imports:
from oslo.config import cfg
from wsme import types as wtypes
from tuskar.api.controllers.v1.types.base import Base
import wsme
and context (class names, function names, or code) available:
# Path: tuskar/api/controllers/v1/types/base.py
# class Base(wsme.types.Base):
#
# def __init__(self, **kwargs):
# self.fields = list(kwargs)
# for k, v in kwargs.iteritems():
# setattr(self, k, v)
#
# @classmethod
# def from_db_model(cls, m):
# return cls(**m.as_dict())
#
# @classmethod
# def from_db_and_links(cls, m, links):
# return cls(links=links, **(m.as_dict()))
#
# def as_dict(self):
# return dict((k, getattr(self, k))
# for k in self.fields
# if hasattr(self, k) and
# getattr(self, k) != wsme.Unset)
#
# def get_id(self):
# """Returns the ID of this resource as specified in the self link."""
#
# # FIXME(mtaylor) We should use a more robust method for parsing the URL
# if not isinstance(self.id, wtypes.UnsetType):
# return self.id
# elif not isinstance(self.links, wtypes.UnsetType):
# return self.links[0].href.split("/")[-1]
# else:
# raise wsme.exc.ClientSideError(_("No ID or URL Set for Resource"))
. Output only the next line. | ] |
Given the code snippet: <|code_start|>
def get_pecan_config():
# Set up the pecan configuration
filename = config.__file__.replace('.pyc', '.py')
return pecan.configuration.conf_from_file(filename)
def setup_app(pecan_config=None, extra_hooks=None):
app_hooks = [hooks.ConfigHook(),
hooks.DBHook()]
if extra_hooks:
app_hooks.extend(extra_hooks)
if not pecan_config:
pecan_config = get_pecan_config()
if pecan_config.app.enable_acl:
app_hooks.append(acl.AdminAuthHook())
pecan.configuration.set_config(dict(pecan_config), overwrite=True)
# TODO(deva): add middleware.ParsableErrorMiddleware from Ceilometer
app = pecan.make_app(
pecan_config.app.root,
custom_renderers=dict(wsmejson=renderers.JSonRenderer),
static_root=pecan_config.app.static_root,
template_path=pecan_config.app.template_path,
debug=CONF.debug,
force_canonical=getattr(pecan_config.app, 'force_canonical', True),
hooks=app_hooks,
<|code_end|>
, generate the next line using the imports in this file:
from oslo.config import cfg
from tuskar.api import acl
from tuskar.api import config
from tuskar.api import hooks
from tuskar.api import renderers
import pecan
and context (functions, classes, or occasionally code) from other files:
# Path: tuskar/api/acl.py
# OPT_GROUP_NAME = 'keystone_authtoken'
# def register_opts(conf):
# def install(app, conf):
# def before(self, state):
# class AdminAuthHook(hooks.PecanHook):
#
# Path: tuskar/api/config.py
#
# Path: tuskar/api/hooks.py
# class ConfigHook(hooks.PecanHook):
# class DBHook(hooks.PecanHook):
# def before(self, state):
# def before(self, state):
#
# Path: tuskar/api/renderers.py
# class JSonRenderer(object):
# def __init__(self, path, extra_vars):
# def render(self, template_path, namespace):
. Output only the next line. | ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.