Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
def StripLabel(self,line,line_num,col_num,next):
# deferred to subclass
return line
# ---------------------------------------------------------------------------
def StripContMark(self,line,line_num,col_num,next):
# deferred to subclass
return line
# --------... | if att.__class__==ContMarker: |
Continue the code snippet: <|code_start|> specific tokens
"""
text = self.GetLines()
# some aspects of fortran are context dependant, eg in free form only
# look for a label at the start of a statement, and a leading continuation
# marker if a trailing one was found on the previous line. li... | self.AppendAttribute(CommentLine(line)) |
Based on the snippet: <|code_start|> var=Variable(sName, self.dVarsData[sName.lower()])
for k,v in d.items():
var.SetAttribute(k,v)
# If the variable was undefined up to now, remove the
# undefined attribute. This happens e.g. for arguments,
... | self.dImplicit[i] = Type('REAL') |
Given the following code snippet before the placeholder: <|code_start|> # --------------------------------------------------------------------------
# Adds a sqrt:
# | a |
def abs(self):
self.MoveRight(1)
for i in range(self.nHeight):
self.lElements.insert(0, "|")
... | if type(o) is StringType or type(o) is AttributeString: |
Given the code snippet: <|code_start|># Since this can be ignored for the scanner tests (project is only needed
# for include file name resolution), we just 'pass' in case of an error.
try:
except ImportError:
pass
class Project:
dConfig = {}
dAddFileInfo = {'amip1sst.F' : {'linelength':132},
... | self.Cache = Cache(nSize=10, sProject=sProject) |
Given the code snippet: <|code_start|>#! /usr/bin/env python
# This is the base class for all output functions
class Output(Config):
# Constructor. Parameter:
#
# f -- file object to output
def __init__(self, f, nMaxCols=72, sFormat='fixed'):
dClass2Func = { Comment : self.CommentLine,
<|cod... | Subroutine: self.Subroutine, |
Here is a snippet: <|code_start|> # Adds a sqrt:
# | a |
def abs(self):
self.MoveRight(1)
for i in range(self.nHeight):
self.lElements.insert(0, "|")
self.lPosX.insert(0, 0)
self.lPosY.insert(0, i)
self.lElements.append("|")
self.lPo... | if type(o) is StringType or type(o) is AttributeString: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
class ControlLessDo(BasicNamedStatement):
# Stores a Do loop without loop control
def __init__(self, sLabel=None, sName=None, loc=None,
sDo="DO", sDoLabel=None, nIndent=0):
self.sDo = sDo
self... | class Exit(BasicStatement): |
Here is a snippet: <|code_start|>
- Training ans segmentation on separate files:
Specify <input-text> and --train-file <training-file>. Both texts must be in
phonologized form. The PUDDLE model is trained offline on <training-file>,
before the segmentation of <input-text>. In this mode --nfolds and --njobs
opti... | def __init__(self, window=2, by_frequency=False, log=utils.null_logger()): |
Next line prediction: <|code_start|> When True choose the word candidates by filterring them by frequency.
Default to False.
nfolds : int, optional
The number of folds to segment the `text` on. This option is ignored if
a `train_text` is provided.
njobs : int, optional
The... | folded_texts, fold_index = folding.fold(text, nfolds) |
Next line prediction: <|code_start|>"""Test of the wordseg.algos.baseline module"""
@pytest.mark.parametrize('p', (1.01, -1, 'a', True, 1))
def test_proba_bad(p):
with pytest.raises(ValueError):
<|code_end|>
. Use current file imports:
(import pytest
from wordseg.algos.baseline import segment)
and context inc... | list(segment('a b c', probability=p)) |
Predict the next line for this snippet: <|code_start|> for bigram, freq in bigrams.items()})
elif dependency == 'btp':
tps = collections.defaultdict(lambda: 0, {
bigram: float(freq) / unigrams[bigram[1]]
for bigram, freq in bigrams.items()})
else: # dependency == 'mi'... | log=utils.null_logger()): |
Here is a snippet: <|code_start|> original Gibbs sampler (*flip sampler*) as well as a sentence-based
Gibbs sampler that uses dynamic programming (*tree sampler*) and a
similar dynamic programming algorithm that chooses the best
segmentation of each utterance rather than a sample. The latter
two algorithm... | utils.Argument( |
Next line prediction: <|code_start|> if process.returncode:
raise RuntimeError(
'failed with error code {}'.format(process.returncode))
tmp_output.seek(0)
return tmp_output.read().decode('utf8').split('\n')
def segment(text, nfolds=5, njobs=1,
args='--ng... | unicode_text, folding.boundaries(unicode_text, nfolds), log) |
Given snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class CategoryManager(base_manager.BaseManager):
""" Handle category related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
"""
def __init__(self... | cat = category.Category(name=name) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class CategoryManager(base_manager.BaseManager):
""" Handle category related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
"... | self.hints.append(hint.Hint(hint_text)) |
Continue the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class CategoryManager(base_manager.BaseManager):
""" Handle category related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
"""
def _... | _ = translator.Translator.instance(language) |
Based on the snippet: <|code_start|> # Version 12 -> 13
current = 12
# Finished
db.close()
def __create_db(self):
""" Create database file if not existing. """
if not os.path.exists(self.db_file):
shutil.copy(self.home+self.EMPTY_DB_FILE, self.db_file)
... | config = config_entity.Configuration.find_name(db, self.CONFIG_VERSION) |
Given the following code snippet before the placeholder: <|code_start|> current = 10
if self.__is_version(db, current):
self.__create_tags(db, tag_lists.tags_008)
current += 1
self.__update_version(db, current)
# Version 11 -> 12
current = 11
i... | tag = tag_entity.Tag(name=tag_name, synonym_of=parent_id) |
Continue the code snippet: <|code_start|>
class MigrationManager:
""" Checks current version and migrates if necessary.
Constants:
CONFIG_VERSION -- The version name in configuration table (string).
EMPTY_DB_FILE -- Name of empty database file (string).
Member:
home -- The home directory (stri... | self.__create_tags(db, tag_lists.tags_001) |
Predict the next line for this snippet: <|code_start|> query = 'SELECT description, id, info, ingredients, rating, ' \
'serving_size, title, user_id ' \
'FROM recipes ' \
'WHERE id = ?'
params = [id]
return Recipe.__generic_find(db, query, params)
... | recipe.categories = category_entity.Category.find_recipe(db, recipe) |
Here is a snippet: <|code_start|> 'serving_size, title, user_id ' \
'FROM recipes ' \
'WHERE id = ?'
params = [id]
return Recipe.__generic_find(db, query, params)
@staticmethod
def find_random(db, num):
""" Find random entities in database.... | recipe.images = image_entity.Image.find_recipe(db, recipe) |
Predict the next line after this snippet: <|code_start|> 'FROM recipes ' \
'WHERE id = ?'
params = [id]
return Recipe.__generic_find(db, query, params)
@staticmethod
def find_random(db, num):
""" Find random entities in database. Returns list of found
... | recipe.synonyms = synonym_entity.Synonym.find_recipe(db, recipe) |
Using the snippet: <|code_start|> 'WHERE id = ?'
params = [id]
return Recipe.__generic_find(db, query, params)
@staticmethod
def find_random(db, num):
""" Find random entities in database. Returns list of found
entities ordered by name ascending."""
query ... | recipe.tags = tag_entity.Tag.find_recipe(db, recipe) |
Predict the next line for this snippet: <|code_start|> params = [id]
return Recipe.__generic_find(db, query, params)
@staticmethod
def find_random(db, num):
""" Find random entities in database. Returns list of found
entities ordered by name ascending."""
query = 'SELECT ... | recipe.urls = url_entity.Url.find_recipe(db, recipe) |
Predict the next line after this snippet: <|code_start|>
@staticmethod
def find_random(db, num):
""" Find random entities in database. Returns list of found
entities ordered by name ascending."""
query = 'SELECT description, id, info, ingredients, ' \
'rating, serving_siz... | recipe.author = user_entity.User.find_pk(db, row[7]) |
Given the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class ExportManager(base_manager.BaseManager):
""" Handles export actions.
Member:
db -- The database connection.
"""
def __init__(self, db):
self.db = db
def action(self, static_path, image_path, id, r... | recipe = recipe_entity.Recipe.find_pk(self.db, id) |
Next line prediction: <|code_start|> # Convert recipe to json compatible object.
images = [image.path.replace(image_path, '')
for image in recipe.images]
urls = [{'name': url.name, 'url': url.url} for url in recipe.urls]
synonyms = [synonym.name for synonym in recipe.syn... | name = url_helper.Url.slugify(recipe.title) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class TagManager(base_manager.BaseManager):
""" Handle tag related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).... | tag = tag_entity.Tag(name=name) |
Given snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class TagManager(base_manager.BaseManager):
""" Handle tag related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
"""
def __init__(self, db):
... | self.hints.append(hint.Hint(hint_text)) |
Using the snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class TagManager(base_manager.BaseManager):
""" Handle tag related actions.
Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
"""
def __init__(self, db):
... | _ = translator.Translator.instance(language) |
Given snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class Searcher:
""" Searcher class.
Constants:
DEFAULT_FIELD -- Name of the default field to search (string).
Member:
_indexer -- The indexer (indexer).
"""
DEFAULT_FIELD = 'titletags'
def __init__(self, indexer... | recipe = recipe_entity.Recipe.find_pk(db, hit['id']) |
Predict the next line after this snippet: <|code_start|> Member:
db -- The database connection.
hints -- List of hints which occurred during action handling (list hint).
_current_user -- Cache for current user (user).
"""
SESSION_COOKIE = 'session'
USER_NAME_COOKIE = 'user'
def __init__... | self._current_user = user_entity.User.find_name(self.db, user_name) |
Based on the snippet: <|code_start|> self._current_user = None
def action(self, language, pw_hash_iterations, admin_user):
""" Handle actions. Returns users or redirects. """
# Validate user and initialize admin user if necessary.
self.validate_login(pw_hash_iterations, admin_user)
... | self.hints.append(hint.Hint(hint_text)) |
Continue the code snippet: <|code_start|>
SESSION_COOKIE = 'session'
USER_NAME_COOKIE = 'user'
def __init__(self, db):
self.db = db
self.hints = []
self._current_user = None
def action(self, language, pw_hash_iterations, admin_user):
""" Handle actions. Returns users or... | _ = translator.Translator.instance(language) |
Given the code snippet: <|code_start|> is_admin = (self.current_user().name == admin_user)
if is_admin:
users = self.__action_admin(language, pw_hash_iterations)
else:
users = self.__action_user(language, pw_hash_iterations)
return users
def current_user(self)... | redirect_url = url.Url.from_path(['']) |
Here is a snippet: <|code_start|># accordance with Section 6 of the License, the provision of commercial
# support services in conjunction with a version of OpenCenter which includes
# Rackspace trademarks and logos is prohibited. OpenCenter source code and
# details are available at: # https://github.com/rcbops/openc... | m = manager.Manager(path) |
Given the following code snippet before the placeholder: <|code_start|># OpenCenter is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. This
# version of OpenCenter includes Rackspace trademarks and logos, and in
# accordance with Sectio... | with utils.temporary_directory() as path: |
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 permission... | trace = utils.detailed_exception() |
Given snippet: <|code_start|>
class FakeSocket(object):
def __init__(self, protocol, transport):
self.sent = []
def connect(self, ip_port):
pass
def shutdown(self, kind):
pass
def close(self):
pass
def send(self, data):
self.sent.append(data)
re... | om = output_manager.OutputManager(path) |
Given the code snippet: <|code_start|>#
class FakeSocket(object):
def __init__(self, protocol, transport):
self.sent = []
def connect(self, ip_port):
pass
def shutdown(self, kind):
pass
def close(self):
pass
def send(self, data):
self.sent.append(data)... | with utils.temporary_directory() as path: |
Here is a snippet: <|code_start|> ns['result_str'] = 'fail'
ns['result_code'] = 254
ns['result_data'] = {}
ns['sm_description'] = adventure_dsl
LOG.debug('About to run the following dsl: %s' % adventure_dsl)
node_list = {}
ns['input_data']['fails'] = []
for node in initial_state['node... | return _retval(1, result_data=detailed_exception()) |
Continue the code snippet: <|code_start|> plan['states'][state] = state_value
input_state['rollback_plan'][node_id] = plan
self.logger.debug('new rollback plan for node %s: %s' % (node_id,
plan))
return input_state
def... | 'result_data': detailed_exception()} |
Here is a snippet: <|code_start|> self._set_mixing = set_mixing
def get_parameters(self, map0, map1):
"""Get the required parameters to initialise ContactDifference"""
failed = map0._check_compatibility(map1, err=None)
return self._fix_parameters(map0, map1, failed)
def _fix_par... | all_atoms_ok, all_res_ok, topology = check_topologies( |
Continue the code snippet: <|code_start|>
# matplotlib is technically optional, but required for plotting
try:
except ImportError:
HAS_MATPLOTLIB = False
else:
HAS_MATPLOTLIB = True
try:
except ImportError:
HAS_NETWORKX = False
else:
HAS_NETWORKX = True
# pandas 0.25 not available on py27; can drop th... | cb = ranged_colorbar(cmap_f, norm, cbmin, cbmax, ax=ax) |
Based on the snippet: <|code_start|>
In general, instances of this class shouldn't be created by a user using
``__init__``; instead, they will be returned by other methods. So users
will often need to use this object for analysis.
Parameters
----------
counter : :class:`collections.Counter`
... | self.n_x, self.n_y = make_x_y_ranges(n_x, n_y, counter) |
Based on the snippet: <|code_start|> fig, ax = plt.subplots(**kwargs)
# Check the number of pixels of the figure
self._check_number_of_pixels(fig)
self.plot_axes(ax=ax, cmap=cmap, diverging_cmap=diverging_cmap,
with_colorbar=with_colorbar)
return (fig, ax)... | diverging_cmap = is_cmap_diverging(cmap) |
Predict the next line for this snippet: <|code_start|> 'red': [[0.0, 0.0, 0.0],
[0.5, 1.0, 1.0],
[1.0, 1.0, 1.0]],
'green': [[0.0, 0.0, 0.0],
[0.25, 0.0, 0.0],
[0.75, 1.0, 1.0],
... | self.cr = _ContactPlotRange(5) |
Given the code snippet: <|code_start|>
class Graphx:
"""Main class of the graphx engine"""
def __init__(self):
#glutInit(sys.argv)
self.width, self.height = 1280, 800
pygame.init()
self.screen = pygame.display.set_mode((self.width, self.height), OPENGL | DOUBLEBUF)
glMatrixMode(GL_PROJECTION)
glLoa... | vertices = np.array([[100.0, -10.0, 100.0, Conf.GRAPHX.BASE_COLOR[0],Conf.GRAPHX.BASE_COLOR[1],Conf.GRAPHX.BASE_COLOR[2]], \ |
Given the code snippet: <|code_start|> print "Error: no argument found for inst `"+char+"' in: ", self.LSCode[dbg:dbg+10]
return;
# if we are executing a parametized rule:
# replace each variable by its value in the params array
for param in self.LSParams:
if param in arg:
arg = arg.replace(par... | Conf.LSYSTEM.AUTORUN_STEP *= 10 |
Given snippet: <|code_start|> if not 'help' in sys.argv:
self.gx = Graphx()
[self.fractal, steps] = self.parse_input()
self.fractal.setSteps(steps)
self.quit = False
self.follow_building = False
# The function called whenever a key is pressed
# it propagates the events to the fractal and the graphx
d... | print Conf.HELP |
Predict the next line for this snippet: <|code_start|>
class Turtle:
"""This class is the turtle that will draw the fractals"""
class State:
"""This class represent a state of the turtle, for push and pop"""
def __init__(self, pos, heading, color):
self.pos = Vector().set(pos)
self.heading = Vector().set(... | self.pos = Vector(Conf.TURTLE.INIT_POS) |
Here is a snippet: <|code_start|> self.autorun = not self.autorun
def runTurtleRun(self, stepbystep=False):
# gestion de l'autorun : si 'vrai', chaque appel lance automatiquement la tortue une etape plus loin
if self.autorun:
self.inc_max_step()
# lancement de la tortue
self.turtle.begin()
if stepbys... | if 'lsystem' in Conf.DEBUG and Conf.DEBUG['lsystem'] >= 1: |
Using the snippet: <|code_start|>]
class Main:
"""Entry point"""
def __init__(self):
print "===== 3D L-system FOREST creator - call 'help' for usage information ==="
if not 'help' in sys.argv:
self.gx = Graphx()
self.quit = False
self.fractals = []
self.turtles = []
self.grid_prec = None
self.fra... | print Conf.FOREST_HELP |
Predict the next line for this snippet: <|code_start|>
class Camera:
"""Represent the camera"""
def __init__(self, pos, look):
self.pos = Vector((pos[0], pos[1], pos[2]))
self.lookat = Vector((look[0], look[1], look[2]))
self.angleY = 0
self.angleX = 0
self.angleZ = 0
self.distance = 100
gluLookAt(0.0... | self.angleY -= Conf.GRAPHX.CAMERA_ROTATION_VELOC |
Continue the code snippet: <|code_start|>""" test/imputation/ts/test_moving_window.py """
#pylint:disable=missing-docstring, redefined-outer-name
@pytest.mark.parametrize(
'pos1,pos2,expected',
[
(2, 0, 11.5),
(2, 2, 12),
(2, -1, 12.5)]
)
def test_defaults_impute(pos1, pos2, expect... | return_na_check(imputed) |
Using the snippet: <|code_start|>
@wrapper.wrappers
@wrapper.checks
def em(data, eps=0.1):
""" Imputes given data using expectation maximization.
E-step: Calculates the expected complete data log likelihood ratio.
M-step: Finds the parameters that maximize the log likelihood of the
complete data.
... | nan_xy = matrix.nan_indices(data) |
Next line prediction: <|code_start|>
SHAPE = (5, 5)
def test_complete_case_(test_data):
data = test_data(SHAPE)
<|code_end|>
. Use current file imports:
(import numpy as np
from impyute.deletion import complete_case
from impyute.ops.testing import return_na_check)
and context including class names, function nam... | imputed = complete_case(data) |
Predict the next line for this snippet: <|code_start|>
SHAPE = (5, 5)
def test_complete_case_(test_data):
data = test_data(SHAPE)
imputed = complete_case(data)
<|code_end|>
with the help of current file imports:
import numpy as np
from impyute.deletion import complete_case
from impyute.ops.testing import re... | return_na_check(imputed) |
Using the snippet: <|code_start|>"""test_random_imputation.py"""
SHAPE = (3, 3)
def test_random_(test_data):
data = test_data(SHAPE)
imputed = impy.random(data)
<|code_end|>
, determine the next line of code. You have imports:
import impyute as impy
from impyute.ops.testing import return_na_check
and conte... | return_na_check(imputed) |
Continue the code snippet: <|code_start|> Whether to return a copy or run on the passed-in array
Returns
-------
numpy.ndarray
Imputed data.
"""
if errors == "ignore":
raise Exception("`errors` value `ignore` not implemented yet. Sorry!")
if not inplace:
data = ... | nan_xy = matrix.nan_indices(data) |
Predict the next line for this snippet: <|code_start|>""" Shared functions to load/generate data """
def randu(bound=(0, 10), shape=(5, 5), missingness="mcar", thr=0.2, dtype="int"):
""" Return randomly generated dataset of numbers with uniformly
distributed values between bound[0] and bound[1]
Parameters... | corruptor = Corruptor(data, thr=thr) |
Predict the next line after this snippet: <|code_start|> """
mean, sigma = theta
data = np.random.normal(mean, sigma, size=shape)
if dtype == "int":
data = np.round(data)
elif dtype == "float":
pass
corruptor = Corruptor(data, thr=thr)
raw_data = getattr(corruptor, missingness... | raise error.BadInputError("nlevel exceeds the size of desired dataset. Please decrease the nlevel or increase the shape") |
Next line prediction: <|code_start|> The data you want to get a description from
verbose: boolean(optional)
Decides whether the description is short or long form
Returns
-------
dict
missingness: list
Confidence interval of data being MCAR, MAR or MNAR - in that order... | nan_xy = matrix.nan_indices(data) |
Continue the code snippet: <|code_start|>""" impyute.contrib.count_missing.py """
def count_missing(data):
""" Calculate the total percentage of missing values and also the
percentage in each column.
Parameters
----------
data: np.array
Data to impute.
Returns
-------
dict
... | nan_xy = matrix.nan_indices(data) |
Using the snippet: <|code_start|>
@wrapper.wrappers
@wrapper.checks
def random(data):
""" Fill missing values in with a randomly selected value from the same
column.
Parameters
----------
data: numpy.ndarray
Data to impute.
Returns
-------
numpy.ndarray
Imputed data.
... | nan_xy = matrix.nan_indices(data) |
Given the following code snippet before the placeholder: <|code_start|>
def _add_one(x):
""" """
return x + 1
def _square(x):
return x * x
def test_thread():
assert 10 == util.thread(3, _square, _add_one)
assert 100 == util.thread(3, _square, _add_one, _square) #4
assert 82 == util.thread(3, _... | assert matrix.every_nd(bool, expected == actual) |
Based on the snippet: <|code_start|>
def _add_one(x):
""" """
return x + 1
def _square(x):
return x * x
def test_thread():
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from impyute.ops import matrix
from impyute.ops import util
and context (classes, functio... | assert 10 == util.thread(3, _square, _add_one) |
Continue the code snippet: <|code_start|>
@wrapper.wrappers
def wrappers_mul(arr):
"""Some function that performs an inplace operation on the input. Accepts kwargs"""
arr *= 25
return arr
def test_wrappers_inplace_false():
"""Input should be unchanged if inplace set to false"""
A = np.ones((5, 5))
... | assert isinstance(mean(A), pd.DataFrame) |
Predict the next line after this snippet: <|code_start|> """Input may be changed if inplace set to true and operation is inplace"""
A = np.ones((5, 5))
A_copy = A.copy()
wrappers_mul(A, inplace=True)
assert A[0, 0] != A_copy[0, 0]
def test_wrappers_pandas_input():
""" Input: DataFrame, Output: D... | except error.BadInputError: |
Predict the next line for this snippet: <|code_start|>
# pylint:disable=redefined-builtin
try:
raise ModuleNotFoundError
except NameError:
class ModuleNotFoundError(Exception):
"placeholder required for python2.7"
pass
except ModuleNotFoundError:
pass
<|code_end|>
with the help of current ... | @wrapper.wrappers |
Predict the next line for this snippet: <|code_start|> >>> data[0][2] = np.nan
>>> data
array([[ 0., 1., nan, 3., 4.],
[ 5., 6., 7., 8., 9.],
[10., 11., 12., 13., 14.],
[15., 16., 17., 18., 19.],
[20., 21., 22., 23., 24.]])
... | nan_xy = matrix.nan_indices(data) |
Given snippet: <|code_start|>
# pylint: disable=too-many-arguments
@wrapper.wrappers
@wrapper.checks
def fast_knn(data, k=3, eps=0, p=2, distance_upper_bound=np.inf, leafsize=10,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from scipy.spatial import KDTree
fro... | idw_fn=idw.shepards, init_impute_fn=mean): |
Predict the next line for this snippet: <|code_start|>
# pylint: disable=too-many-arguments
@wrapper.wrappers
@wrapper.checks
def fast_knn(data, k=3, eps=0, p=2, distance_upper_bound=np.inf, leafsize=10,
<|code_end|>
with the help of current file imports:
import numpy as np
from scipy.spatial import KDTree
from impy... | idw_fn=idw.shepards, init_impute_fn=mean): |
Given snippet: <|code_start|>
pytest.skip("takes ~30 sec each test", allow_module_level=True)
data = mnist()["X"]
def test_return_type():
""" Check return type, should return an np.ndarray"""
assert isinstance(data, np.ndarray)
def test_missing_values_present():
""" Check that the dataset is corrupted (mi... | assert matrix.nan_indices(data).size != 0 |
Continue the code snippet: <|code_start|>"""test_fast_knn.py"""
# pylint:disable=invalid-name
SHAPE = (5, 5)
def test_return_type(knn_test_data):
imputed = impy.fast_knn(knn_test_data)
<|code_end|>
. Use current file imports:
import functools
import numpy as np
import impyute as impy
from impyute.ops.testing im... | return_na_check(imputed) |
Next line prediction: <|code_start|>def locf(data, axis=0):
""" Last Observation Carried Forward
For each set of missing indices, use the value of one row before(same
column). In the case that the missing value is the first row, look one
row ahead instead. If this next row is also NaN, look to the next... | nan_xy = matrix.nan_indices(data) |
Given the code snippet: <|code_start|>@wrapper.wrappers
@wrapper.checks
def locf(data, axis=0):
""" Last Observation Carried Forward
For each set of missing indices, use the value of one row before(same
column). In the case that the missing value is the first row, look one
row ahead instead. If this ne... | raise error.BadInputError("Error: Axis value is invalid, please use either 0 (row format) or 1 (column format)") |
Using the snippet: <|code_start|>"""test_locf.py"""
SHAPE = (5, 5)
def test_locf_(test_data):
data = test_data(SHAPE)
imputed = impy.locf(data)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import impyute as impy
from impyute.ops.testing import return_na_check
from imp... | return_na_check(imputed) |
Given the code snippet: <|code_start|> imputed = impy.locf(data)
return_na_check(imputed)
def test_na_at_i_start(test_data):
data = test_data(SHAPE)
actual = impy.locf(data, axis=1)
data[0, 0] = data[1, 0]
assert np.array_equal(actual, data)
def test_na_at_i(test_data):
data = test_data(S... | with np.testing.assert_raises(error.BadInputError): |
Continue the code snippet: <|code_start|>"""test_em.py"""
SHAPE = (5, 5)
def test_em_(test_data):
data = test_data(SHAPE)
imputed = impy.em(data)
<|code_end|>
. Use current file imports:
import impyute as impy
from impyute.ops.testing import return_na_check
and context (classes, functions, or code) from ot... | return_na_check(imputed) |
Using the snippet: <|code_start|>
@wrapper.wrappers
@wrapper.checks
def mean(data):
""" Substitute missing values with the mean of that column.
Parameters
----------
data: numpy.ndarray
Data to impute.
Returns
-------
numpy.ndarray
Imputed data.
"""
<|code_end|>
, dete... | nan_xy = matrix.nan_indices(data) |
Next line prediction: <|code_start|># pylint: disable=too-many-locals
@wrapper.wrappers
@wrapper.checks
def buck_iterative(data):
""" Iterative variant of buck's method
- Variable to regress on is chosen at random.
- EM type infinite regression loop stops after change in prediction from
previous pre... | nan_xy = matrix.nan_indices(data) |
Predict the next line for this snippet: <|code_start|>"""test_averagings.py"""
SHAPE = (5, 5)
def test_mean(test_data):
data = test_data(SHAPE)
imputed = impy.mean(data)
<|code_end|>
with the help of current file imports:
import impyute as impy
from impyute.ops.testing import return_na_check
and context f... | return_na_check(imputed) |
Continue the code snippet: <|code_start|>
def _is_gt_5(x):
return x > 5
def test_map_nd_2d():
arr = np.arange(10).reshape([5, 2])
expected = np.array([
[False, False],
[False, False],
[False, False],
[True, True],
[True, True],
])
<|code_end|>
. Use current file ... | actual = matrix.map_nd(_is_gt_5, arr) |
Predict the next line after this snippet: <|code_start|>
def func(*args):
pass
def PublishKernels(context):
<|code_end|>
using the current file's imports:
from pyvx import vx
and any relevant context from other files:
# Path: pyvx/vx.py
# def _get_attribute(func, ref, attribute, c_type, python_type):
# def _se... | enum = vx.KERNEL_BASE(vx.ID_DEFAULT, 8) + 1 |
Given the following code snippet before the placeholder: <|code_start|>
if sys.version_info > (3,):
unicode = str
class TestVX(object):
def test_context(self):
<|code_end|>
, predict the next line using imports from the current file:
from array import array
from py.test import raises
from pyvx import vx
... | c = vx.CreateContext() |
Given the code snippet: <|code_start|>
class TestDemo(object):
def test_sobel(self):
c = vx.CreateContext()
img = vx.CreateImage(c, 640, 480, vx.DF_IMAGE_U8)
dx = vx.CreateImage(c, 640, 480, vx.DF_IMAGE_S16)
dy = vx.CreateImage(c, 640, 480, vx.DF_IMAGE_S16)
<|code_end|>
, generate th... | assert vxu.Sobel3x3(c, img, dx, dy) == vx.SUCCESS |
Given the code snippet: <|code_start|>@api('QueryConvolution', on_exception=return_errno_and_none, returns='status, value')
@api('QueryPyramid', on_exception=return_errno_and_none, returns='status, value')
@api('QueryRemap', on_exception=return_errno_and_none, returns='status, value')
@api('QueryArray', on_exception=re... | raise VxError("Bad size %d in query, expected %d\n" % ( |
Here is a snippet: <|code_start|> fn.apis = []
fn.apis.append(self)
return fn
class capi(object):
def __init__(self, cdecl):
self.cdecl = cdecl
def __call__(self, fn):
if not hasattr(fn, 'capis'):
fn.capis = []
fn.capis.append(self)
retu... | raise types.InvalidParametersError(msg, self) |
Given snippet: <|code_start|>
class VXError(Exception): # FIXME: use different exceptions for different errors
pass
def _check_status(status):
if status != 0: # FIXME vx.SUCCSES
raise VXError(status)
class attribute(object):
def __init__(self, ctype, enum=None, query=None):
self.ctype = ... | a.query = getattr(vx, 'Query' + name) |
Given the code snippet: <|code_start|>
TIMEZONE = pytz.timezone("US/Eastern")
class TestCommand(TestCase):
def setUp(self):
self.command = fix_timezone_for_period_data.Command()
flow_event = FlowEventFactory(timestamp=TIMEZONE.localize(
datetime.datetime(2014, 1, 31, 17, 0, 0)))
... | period_models.FlowEvent.objects.all().delete() |
Based on the snippet: <|code_start|>
TIMEZONE = pytz.timezone("US/Eastern")
class TestCommand(TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import pytz
from django.test import TestCase
from periods import models as period_models
from period... | self.command = fix_timezone_for_period_data.Command() |
Using the snippet: <|code_start|>
TIMEZONE = pytz.timezone("US/Eastern")
class TestCommand(TestCase):
def setUp(self):
self.command = fix_timezone_for_period_data.Command()
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import pytz
from django.test import TestCase
fro... | flow_event = FlowEventFactory(timestamp=TIMEZONE.localize( |
Given the code snippet: <|code_start|>
class NullableEnumField(serializers.ChoiceField):
"""
Field that handles empty entries for EnumFields
"""
def __init__(self, enum, **kwargs):
super(NullableEnumField, self).__init__(enum.choices(), allow_blank=True, required=False)
def to_internal_v... | clots = NullableEnumField(period_models.ClotSize) |
Next line prediction: <|code_start|>
class PeriodForm(forms.ModelForm):
comment = forms.CharField(widget=forms.Textarea(attrs={'rows': 3}))
class Meta:
<|code_end|>
. Use current file imports:
(import floppyforms.__future__ as forms
from periods import models as period_models)
and context including class n... | model = period_models.FlowEvent |
Here is a snippet: <|code_start|>
class Command(BaseCommand):
help = 'Update FlowEvent data to match User timezone'
def add_arguments(self, parser):
parser.add_argument('--noinput', '--no-input',
action='store_false', dest='interactive', default=True,
... | users = period_models.User.objects.filter( |
Predict the next line after this snippet: <|code_start|>
class LoggedInUserTestCase(TestCase):
def setUp(self):
self.user = UserFactory()
self.client = Client()
<|code_end|>
using the current file's imports:
import datetime
import json
import pytz
from django.core.urlresolvers import reverse
f... | self.client.login(email=self.user.email, password=PASSWORD) |
Given snippet: <|code_start|>
class TestCommand(TestCase):
EMAIL_FOOTER = ('Check your calendar: http://example.com/calendar/\nFound a bug? Have a '
'feature request? Please let us know: https://github.com/jessamynsmith/'
'eggtimer-server/issues\nDisable email notification... | period_models.FlowEvent.objects.all().delete() |
Continue the code snippet: <|code_start|>
class TestCommand(TestCase):
EMAIL_FOOTER = ('Check your calendar: http://example.com/calendar/\nFound a bug? Have a '
'feature request? Please let us know: https://github.com/jessamynsmith/'
'eggtimer-server/issues\nDisable email ... | self.command = notify_upcoming_period.Command() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.