Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|>from __future__ import division def cast_float(variable): return Variable(torch.from_numpy(variable).float(), requires_grad=True) <|code_end|> . Write the next line using the current file imports: import numpy as np import torch from torch.autograd import Variable from lxmls.de...
class PytorchMLP(MLP):
Predict the next line after this snippet: <|code_start|> # coding: utf-8 # ### Amazon Sentiment Data # In[ ]: corpus = srs.SentimentCorpus("books") data = AmazonData(corpus=corpus) # ### Train Log Linear in Pytorch # In order to learn the differences between a numpy and a Pytorch implementation, explore the reimp...
self.weight = glorot_weight_init(weight_shape, 'softmax')
Next line prediction: <|code_start|> # Softmax is computed in log-domain to prevent underflow/overflow log_tilde_z = z - logsumexp(z, axis=1, keepdims=True) return log_tilde_z, layer_inputs def cross_entropy_loss(self, input, output): """Cross entropy loss""" num_examples = ...
I = index2onehot(output, num_clases)
Based on the snippet: <|code_start|> def log_forward(self, input): """Forward pass for sigmoid hidden layers and output softmax""" # Input tilde_z = input layer_inputs = [] # Hidden layers num_hidden_layers = len(self.parameters) - 1 for n in range(num_hidde...
log_tilde_z = z - logsumexp(z, axis=1, keepdims=True)
Next line prediction: <|code_start|> def backpropagation(self, input, output): ''' Compute gradientes, with the back-propagation method inputs: x: vector with the (embedding) indicies of the words of a sentence outputs: vector with the indicies of the...
I = index2onehot(output, W_y.shape[0])
Using the snippet: <|code_start|> # Update each parameter with SGD rule num_parameters = len(self.parameters) for m in range(num_parameters): # Update weight self.parameters[m] -= learning_rate * gradients[m] def log_forward(self, input): # Get parameters and...
log_p_y = y - logsumexp(y, axis=1, keepdims=True)
Next line prediction: <|code_start|> y_pred = hmm.posterior_decode(simple.test.seq_list[0]) assert [y_pred.sequence_list.y_dict.get_label_name(yi) for yi in y_pred.y] == ['rainy', 'rainy', 'sunny', 'sunny'] y_pred = hmm.posterior_decode(simple.test.seq_list[1]) assert [y_pred.sequence_li...
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'), max_sent_len=15, max_nr_sent=1000)
Here is a snippet: <|code_start|> # perturbation of weight values perturbations = np.linspace(-span, span, 200) # Compute the loss when varying the study weight parameters = deepcopy(model.parameters) current_weight = float(get_parameter(parameters)) loss_range = [] old_parameters = list(mo...
class MLP(Model):
Here is a snippet: <|code_start|>def initialize_mlp_parameters(geometry, loaded_parameters=None, random_seed=None): """ Initialize parameters from geometry or existing weights """ num_layers = len(geometry) - 1 num_hidden_layers = num_layers - 1 activation_function...
weight = glorot_weight_init(
Next line prediction: <|code_start|> tolerance = 1e-5 @pytest.fixture(scope='module') def scr(): return srs.SentimentCorpus("books") # Exercise 1.1 def test_naive_bayes(scr): <|code_end|> . Use current file imports: (import sys import os import pytest import warnings import lxmls.classifiers.gaussian_naive_ba...
mnb = mnbb.MultinomialNaiveBayes()
Here is a snippet: <|code_start|> tolerance = 1e-5 @pytest.fixture(scope='module') def corpus_and_sequences(): corpus = pcc.PostagCorpus() <|code_end|> . Write the next line using the current file imports: import sys import os import numpy as np import pytest import lxmls.readers.pos_corpus as pcc import lxmls....
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'), max_sent_len=10, max_nr_sent=1000)
Predict the next line after this snippet: <|code_start|> # coding: utf-8 # ### Amazon Sentiment Data # To ease-up the upcoming implementation exercise, examine and comment the following implementation of a log-linear model and its gradient update rule. Start by loading Amazon sentiment corpus used in day 1 # In[ ]: ...
class NumpyLogLinear(Model):
Predict the next line after this snippet: <|code_start|># To ease-up the upcoming implementation exercise, examine and comment the following implementation of a log-linear model and its gradient update rule. Start by loading Amazon sentiment corpus used in day 1 # In[ ]: corpus = srs.SentimentCorpus("books") data = ...
self.weight = glorot_weight_init(weight_shape, 'softmax')
Given the following code snippet before the placeholder: <|code_start|> # Initialize parameters weight_shape = (config['input_size'], config['num_classes']) # after Xavier Glorot et al self.weight = glorot_weight_init(weight_shape, 'softmax') self.bias = np.zeros((1, config['num_c...
I = index2onehot(output, num_classes)
Given the code snippet: <|code_start|> MAX_SENT_SIZE = 1000 MAX_NR_SENTENCES = 100000 MODEL_DIR = "../models/wsj_postag/" def build_corpus_features(): corpus = pcc.PostagCorpus() <|code_end|> , generate the next line using the imports in this file: from lxmls import data import readers.pos_corpus as pcc import s...
train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'),
Given the following code snippet before the placeholder: <|code_start|>''' Utilities to handle embeddings ''' def download_embeddings(embbeding_name, target_file): ''' Downloads file through http with progress report Obtained in stack overflow: http://stackoverflow.com/questions/22676/how-do-i-downloa...
target_file_name = os.path.basename(data.find('senna_50'))
Given the following code snippet before the placeholder: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,...
queue_size = context.request_processor.queue_size()
Using the snippet: <|code_start|> APN = 'pushkin.sender.senders.ApnNotificationSender' GCM = 'pushkin.sender.senders.GcmNotificationSender' @mock.patch('pushkin.sender.sender_manager.config') def test_sender_manager_init_no_senders_given(mock_config): mock_config.enabled_senders.split.return_value=[] with p...
sender_manager.NotificationSenderManager()
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including with...
if not os.path.exists(os.path.dirname(config.main_log_path)):
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including with...
notification = NotificationRequestSingle(1338, "Msg title", "Text of a message.", "some_screen_id")
Given snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights t...
assert NotificationRequestBatch([notification]).validate_single(notification)
Next line prediction: <|code_start|> def test_notification_proto_without_content(mock_log): '''Test that a notification proto without content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", None, "some_screen_id") assert not NotificationRequestBatch([notification]).validate_s...
database.get_raw_messages.assert_called_with(1338, "Msg title", "Text of a message.", "", config.game,
Given snippet: <|code_start|> def test_notification_proto_without_content(mock_log): '''Test that a notification proto without content fails validation''' notification = NotificationRequestSingle(1338, "Msg title", None, "some_screen_id") assert not NotificationRequestBatch([notification]).validate_single(n...
database.get_raw_messages.assert_called_with(1338, "Msg title", "Text of a message.", "", config.game,
Continue the code snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation ...
context.main_logger.error("Request was empty in batch handler {}!".format(self.__class__.__name__))
Given snippet: <|code_start|> class NotificationSenderManager(): def __init__(self): self.sender_by_name = {} self.sender_name_by_platform = {} values = [v.strip() for v in config.enabled_senders.split('\n')] values = filter(bool, values) if not values: sys.exi...
if not issubclass(sender_cls, senders.NotificationSender):
Given snippet: <|code_start|> cls_name) if not issubclass(sender_cls, senders.NotificationSender): raise AttributeError( u"{} must be a subclass of senders.NotificationSender" u"".format(sender_cls)) ...
if config.main_log_level == context.logging.DEBUG:
Predict the next line for this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including withou...
values = [v.strip() for v in config.enabled_senders.split('\n')]
Predict the next line after this snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including with...
class EventHandlerA1(EventHandler):
Here is a snippet: <|code_start|>@pytest.fixture def mock_log(mocker): mocker.patch("pushkin.context.main_logger") @pytest.fixture def setup(mock_log): ''' Runs setup before and clean up after a test which use this fixture ''' # prepare database for test database.create_database() prepare_...
manager = EventHandlerManager()
Using the snippet: <|code_start|> pass class EventHandlerB1(EventHandler): def __init__(self): EventHandler.__init__(self, 1) def handle_event(self, event_request): pass class EventHandlerA2(EventHandler): def __init__(self): EventHandler.__init__(self, 2) def handle...
database.create_database()
Using the snippet: <|code_start|> class AbstractRequest(): def has_field(self, field): if self.__dict__.get(field) is not None and self.__dict__.get(field) != '': return True else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_...
context.main_logger.error("Notification proto is not valid: {}".format(notification))
Here is a snippet: <|code_start|> else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_id, title, content, screen=''): self.login_id = login_id self.title = title self.content = content self.screen = screen class Notific...
notification.screen, config.game, config.world_id, config.dry_run)
Based on the snippet: <|code_start|> return True else: return False class NotificationRequestSingle(AbstractRequest): def __init__(self, login_id, title, content, screen=''): self.login_id = login_id self.title = title self.content = content self.scre...
raw_messages = database.get_raw_messages(notification.login_id, notification.title, notification.content,
Using the snippet: <|code_start|>''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the righ...
event_to_message_mapping = database.get_event_to_message_mapping()
Given snippet: <|code_start|> def __init__(self): EventHandler.__init__(self, config.login_event_id) def handle_event(self, event, event_params): database.process_user_login(login_id=event.user_id, language_id=event_params.get('languageId'), platform_id=event...
context.message_blacklist[event.user_id] = blacklist
Predict the next line after this snippet: <|code_start|> def _build(self): self._add_event_handler(LoginEventHandler()) self._add_event_handler(TurnOffNotificationEventHandler()) event_to_message_mapping = database.get_event_to_message_mapping() for event_id, message_ids in event_to_...
EventHandler.__init__(self, config.login_event_id)
Next line prediction: <|code_start|> def get_event_ids(self): return self._event_handler_map.keys() class EventHandler(): def __init__(self, event_id): self.event_id = event_id def handle_event(self, event, event_params): raise Exception("Not implemented!") def validate(self, ...
result &= is_integer(event_params.get('platformId', ''))
Given the following code snippet before the placeholder: <|code_start|># Returns # ------- # An approximation to the spectral radius of A # # """ # if symmetric: # method = eigen_symmetric # else: # method = eigen # # return norm( method(A, k=1, tol=0.1, which='LM', maxiter=maxite...
breakdown = set_tol(A.dtype)
Continue the code snippet: <|code_start|> coords = list(zip(V[[i,j1], 0], V[[i,j1],1])) newobj = sg.LineString(coords) # add a line object to the list todraw.append(newobj) todraw = cascaded_union(todraw) # union all objects ...
mesh = mesh(V, E)
Predict the next line after this snippet: <|code_start|> newobj = sg.LineString(coords) # add a line object to the list todraw.append(newobj) todraw = cascaded_union(todraw) # union all objects in the aggregate todraw = todraw.buffer(0.1...
A, _ = gradgradform(mesh)
Based on the snippet: <|code_start|>"""Test basic mesh construction.""" class TestRegularTriangleMesh(TestCase): def test_1x1(self): try: <|code_end|> , predict the immediate next line with the help of imports: from pyamg.gallery.mesh import regular_triangle_mesh from numpy.testing import TestCase, asse...
regular_triangle_mesh(1, 0)
Based on the snippet: <|code_start|>"""Test stencil construction.""" class TestStencil(TestCase): def test_1d(self): stencil = np.array([1, 2, 3]) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from pyamg.gallery.stencil import stencil_grid from numpy.testin...
result = stencil_grid(stencil, (3,)).toarray()
Next line prediction: <|code_start|> self.cases.append(( csr_matrix((np.ones(4), np.array([0, 0, 1, 1]), np.arange(5)), shape=(4, 2)), (1 + 3j) * np.arange(4).reshape(4, 1))) # two aggregates two candidates self.cases.append(( csr_matrix((np.ones(4),...
Q, coarse_candidates = fit_candidates(AggOp, fine_candidates)
Predict the next line for this snippet: <|code_start|> [1, 2], [1, 1], [2, 0], [2, 1], [2, 2], [2, 3], [3, 2], [3, 1], ...
cases.append(load_example('unit_square')['A'])
Given the code snippet: <|code_start|> return 0.38783/np.sqrt(self.energy+9.78476*10**(-4)*self.energy**2) def z_slice(self,ind=-1): if len(self.array.shape)==2: raise RuntimeError('z_slice() only works for 3d wavefunctions') return Wavefunction(self.array[:,:,ind],self.energy,...
def detect(self,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None):
Given the code snippet: <|code_start|> V=1/0.07957747154594767*V # 1/epsilon0 elif units=='SI': e=1.60217662*10**(-19) epsilon0=8.854187817*10**(-12) V=e/epsilon0*V else: raise RuntimeError('Unit convention {0} not recognized.'.format(units)) return V def create_pote...
potential = Potential(V_slices,sampling)
Based on the snippet: <|code_start|> self.convergence_angle,self.focal_spread,self.aberrations) def check_recalculate(self,shape,sampling,wavelength,tol=1e-12): if np.any([None is i for i in [self.array,self.sampling,self.wavelength]]): return True ...
return [Wave(a,wave.energy,wave.sampling) for a in new_wave_array]
Given snippet: <|code_start|> self.sampling=sampling self.wavelength=wavelength self.array=ctf if len(new_wave_array.shape) > 2: return [Wave(a,wave.energy,wave.sampling) for a in new_wave_array] else: return Wave(new_wave_array,wave.en...
wavelength=energy2wavelength(energy)
Given the following code snippet before the placeholder: <|code_start|> shape = self.array.shape if sampling is None: if self.sampling is None: raise RuntimeError('Sampling not set') else: sampling = self.sampling i...
kx,ky,k2,theta,phi=spatial_frequencies(shape,sampling,wavelength=wavelength,return_polar=True)
Using the snippet: <|code_start|> def detect(img,sampling,dose=None,MTF_param=None,MTF_func=None,blur=None,resample=None): if resample is not None: if not isinstance(resample, (list, tuple)): resample=(resample,)*2 zoom=(sampling[0]/resample[0],sampling[1]/resample[1]) sampl...
kx,ky,k2=spatial_frequencies(img.shape,sampling)
Given the code snippet: <|code_start|> def __init__(self, cursor): self.cursor = cursor def execute(self, sql, params=()): return defer.maybeDeferred(self.cursor.execute, sql, params) def fetchone(self): return defer.maybeDeferred(self.cursor.fetchone) def fetchall(self): ...
implements(IRunner)
Given snippet: <|code_start|> """ The connection is bad, try the query again. """ retval = original_failure try: new_conn = yield self.makeConnection() m = getattr(new_conn, name) retval = yield m(*args, **kwargs) self.pool.remove(ba...
implements(IPool)
Given the code snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class PatcherTest(TestCase): def getPool(self): return makePool('sqlite:') @defer.inlineCallbacks def test_add(self): """ You can add patches to a patcher and apply them to ...
patcher = Patcher('_patch')
Next line prediction: <|code_start|> You can use a single string or a list/tuple of strings, instead of using SQLPatch directly. """ patcher = Patcher('_patch') patcher.add('something', [ 'create table bar (name text)', 'create table bar2 (name text)', ...
patcher.add('hello', SQLPatch(
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None) skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this ' 'postgres test') if postgres_url: skip_postgres ...
return mkConnStr(parseURI(postgres_url))
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None) skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this ' 'postgres test') if postgres_url: ...
return mkConnStr(parseURI(postgres_url))
Next line prediction: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class parseURITest(TestCase): def test_sqlite(self): """ sqlite URIs should be supported """ <|code_end|> . Use current file imports: (from twisted.trial.unittest import TestCase from norm.ur...
parsed = parseURI('sqlite:')
Given the following code snippet before the placeholder: <|code_start|> p = parseURI('postgres:///postgres') self.assertEqual(p['db'], 'postgres') self.assertFalse('user' in p) self.assertFalse('host' in p) self.assertFalse('port' in p) self.assertFalse('password' in p) ...
output = mkConnStr(parsed)
Next line prediction: <|code_start|> for cls in classes: obj = cls.__new__(cls) empty_obj = True for prop, value in class_data[cls]: if empty_obj and value is not None: empty_obj = False prop.fromDatabase(obj, value) if empty_obj: # ...
raise NotFound(obj)
Given snippet: <|code_start|> """ def __init__(self): self.converters = defaultdict(lambda: []) def when(self, key): """ """ def deco(f): self.converters[key].append(f) return f return deco def convert(self, key, value): """ ...
implements(IOperator)
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class TxPostgresCursor(txpostgres.Cursor): implements(IAsyncCursor) def execute(self, sql, params=()): <|code_end|> , continue by predicting the next line. Consider current file imports: from zope.interface import im...
sql = translateSQL(sql)
Here is a snippet: <|code_start|> __sql_table__ = 'book' id = Int(primary=True) name = Unicode() def __init__(self, name=None): self.name = name class FunctionalIOperatorTestsMixin(object): """ I am a mixin for functionally testing different database IOperators. To use me, you'll...
verifyObject(IOperator, oper)
Using the snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) <|code_end|> , determine the next line of code. You have imports: from twisted.internet import defer from zope.interface.verify import verifyObject...
name = String()
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.internet import defer from zope.in...
uni = Unicode()
Given snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.internet impor...
date = Date()
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() date = Date() <|code_end|> with the help of current file imports: from twisted.in...
dtime = DateTime()
Predict the next line for this snippet: <|code_start|># Copyright (c) Matt Haggard. # See LICENSE for details. class Empty(object): __sql_table__ = 'empty' id = Int(primary=True) name = String() uni = Unicode() date = Date() dtime = DateTime() <|code_end|> with the help of current file im...
mybool = Bool()
Given snippet: <|code_start|> @defer.inlineCallbacks def test_insert_binary(self): """ Should handle binary data okay """ oper = yield self.getOperator() pool = yield self.getPool() empty = Empty() empty.name = '\x00\x01\x02hey\x00' yield pool.runI...
items = yield pool.runInteraction(oper.query, Query(Empty))
Using the snippet: <|code_start|> e2 = Empty() e2.name = '2' yield pool.runInteraction(oper.insert, e2) items = yield pool.runInteraction(oper.query, Query(Empty)) self.assertEqual(len(items), 2) items = sorted(items, key=lambda x:x.name) self.assertTrue...
Query(Empty, Eq(Empty.id, e1.id)))
Next line prediction: <|code_start|> e1 = Empty() e1.name = '1' yield pool.runInteraction(oper.insert, e1) items = yield pool.runInteraction(oper.query, Query(Empty, Eq(Empty.name, '1'))) self.assertEqual(len(items), 1) @defer.inlineCallbacks def test_qu...
Query(Child, And(
Here is a snippet: <|code_start|> yield pool.runInteraction(oper.insert, obj) items = yield pool.runInteraction(oper.query, Query(Child, And( Eq(Child.parent_id, Parent.id), Eq(Parent.id,1)))) self.assertEqual(len(items), 1) ...
LeftJoin(Child, Child.parent_id == Parent.id)]))
Predict the next line for this snippet: <|code_start|> obj = Empty() yield pool.runInteraction(oper.insert, obj) obj.name = 'new name' obj.uni = u'unicycle' obj.date = date(2000, 1, 1) yield pool.runInteraction(oper.update, obj) obj2 = Empty() obj2.id = o...
self.assertFailure(pool.runInteraction(oper.refresh, obj2), NotFound)
Based on the snippet: <|code_start|> cursor = PostgresCursorWrapper(mock) result = getattr(cursor, name)(*args, **kwargs) getattr(mock, name).assert_called_once_with(*args, **kwargs) self.assertEqual(self.successResultOf(result), 'foo') def test_fetchone(self): self.assertCa...
wrapped = PostgresCursorWrapper(BlockingCursor(c))
Given the code snippet: <|code_start|> def assertCallThrough(self, name, *args, **kwargs): mock = MagicMock() setattr(mock, name, MagicMock(return_value=defer.succeed('foo'))) cursor = PostgresCursorWrapper(mock) result = getattr(cursor, name)(*args, **kwargs) getattr(mock, n...
connstr = postgresConnStr()
Given the following code snippet before the placeholder: <|code_start|>""" BORIS Behavioral Observation Research Interactive Software Copyright 2012-2020 Olivier Friard module for testing db_functions.py pytest -vv test_db_functions.py """ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '....
cursor = db_functions.load_events_in_db(pj, ["subject1"], ["observation #1"], ["s"])
Predict the next line after this snippet: <|code_start|> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not see <http://www.gnu.org/licenses/>. """ class...
for idx in sorted_keys(modifiers_dict):
Here is a snippet: <|code_start|> Args: pj (dict): project dictionary selected_observations (list): selected_subjects (list): selected_behaviors (list): Returns: bool: True if OK else False str: error message database connector: db connector if bool True e...
r, msg = project_functions.check_state_events_obs(obsId, pj[ETHOGRAM], pj[OBSERVATIONS][obsId], HHMMSS)
Predict the next line after this snippet: <|code_start|> else: plugin_path = os.path.dirname(p) dll = ctypes.CDLL(p) elif sys.platform.startswith('darwin'): # FIXME: should find a means to configure path d = '/Applications/VLC.app/Contents/MacOS/' c = d + 'lib...
dll, plugin_path = vlc_local.find_local_libvlc()
Predict the next line after this snippet: <|code_start|> Atomic = namedtuple('Atomic', ['left', 'lower', 'upper', 'right']) def mergeable(a, b): """ Tester whether two atomic intervals can be merged (i.e. they overlap or are adjacent). :param a: an atomic interval. :param b: an atomic interval. ...
if a.lower < b.lower or (a.lower == b.lower and a.left == Bound.CLOSED):
Continue the code snippet: <|code_start|> return Interval.from_atomic(Bound.OPEN, lower, upper, Bound.CLOSED) def closedopen(lower, upper): """ Create a right-open interval with given bounds. :param lower: value of the lower bound. :param upper: value of the upper bound. :return: an interval. ...
return Interval.from_atomic(Bound.OPEN, inf, -inf, Bound.OPEN)
Given snippet: <|code_start|> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not see <http://www.gnu.org/licenses/>. """ def check_text_file_type(rows): ...
response = dialog.MessageDialog(
Given the following code snippet before the placeholder: <|code_start|> paramPanelWindow.item = QListWidgetItem(behavior) paramPanelWindow.item.setCheckState(Qt.Unchecked) if category != "###no category###": paramPanelWindow.item.setDa...
_, _, project, _ = project_functions.open_project_json(file_name)
Given snippet: <|code_start|> subject[SUBJECT_NAME] = field.strip() if idx == 2: subject["description"] = field.strip() self.twSubjects.setRowCount(self.twSubjects.rowCount() + 1) for idx, field_name in enumerate(subjec...
paramPanelWindow = param_panel.Param_panel()
Based on the snippet: <|code_start|> This function returns a (lazy) iterator over the values of given interval, starting from its lower bound and ending on its upper bound (if interval is not open). Each returned value merely corresponds to lower + i * step, where "step" defines the step between consecut...
if (value == -inf and not reverse) or (value == inf and reverse):
Next line prediction: <|code_start|> self.hlayout1 = QHBoxLayout() self.hlayout1.addWidget(QLabel("Zoom")) self.hlayout1.addWidget(self.button_plus) self.hlayout1.addWidget(self.button_minus) self.hlayout1.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) ...
result, error_msg, data = txt2np_array(
Predict the next line after this snippet: <|code_start|>""" module for testing otx_parser.py https://realpython.com/python-continuous-integration/ pytest -s -vv test_otx_parser.py """ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) @pytest.fixture() def before(): os.system("r...
boris_project = otx_parser.otx_to_boris("files/otx_parser_test.otx")
Given the following code snippet before the placeholder: <|code_start|> def chooseColor(self): """ area color button clicked """ cd = QColorDialog() col = cd.getColor() if col.isValid(): self.btColor.setStyleSheet("QWidget {background-color:%s}" % col.nam...
response = dialog.MessageDialog("BORIS - Modifiers map creator",
Here is a snippet: <|code_start|> self.selectedPolygon.setBrush(self.areaColor) self.areasList[self.leAreaCode.text()]["color"] = self.areaColor.rgba() if self.closedPolygon: self.closedPolygon.setBrush(self.areaColor) def chooseColor(self): """ area colo...
response = dialog.MessageDialog("BORIS - Modifiers map creator",
Next line prediction: <|code_start|> pass def initialize_heuristic(self, src_sentence): """This is called after ``initialize()`` if the predictor is registered as heuristic predictor (i.e. ``estimate_future_cost()`` will be called in the future). Predictors can implement...
log_sum = utils.log_sum(scores.values())
Predict the next line after this snippet: <|code_start|> They are used in A* if the --heuristics parameter is set to predictor. This function should return the future log *cost* (i.e. the lower the better) given the current predictor state, assuming that the last word in the partial hy...
return NEG_INF
Given the following code snippet before the placeholder: <|code_start|> Args: scores (dict): unnormalized log valued scores use_weights (bool): Set to false to replace all values in ``scores`` with 0 (= log 1) normalize_scores: Set to true to m...
def notify(self, message, message_type = MESSAGE_TYPE_DEFAULT):
Given the code snippet: <|code_start|> """This class implements a predictor-level Mixture of Experts (MoE) model. In this scenario, we have a neural model which predicts predictor weights from the predictor outputs. See the sgnmt_moe project on how to train this gating network with TensorFlow. """ ...
self.sess = tf_utils.create_session(args.moe_checkpoint_dir,
Predict the next line for this snippet: <|code_start|> """Converts the target sentence represented as sequence of token IDs to a string representation. Args: trg_sentence (list): A sequence of integers (token IDs) Returns: string. """ raise NotImp...
return [src_wmap.get(w, utils.UNK_ID)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # coding=utf-8 # Copyright 2019 The SGNMT Authors. # # 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.o...
class KenLMPredictor(UnboundedVocabularyPredictor):
Given the following code snippet before the placeholder: <|code_start|> Args: path (string): Path to the ARPA language model file Raises: NameError. If KenLM is not installed """ super(KenLMPredictor, self).__init__() self.lm = kenlm.M...
"</s>" if w == utils.EOS_ID else str(w),
Predict the next line after this snippet: <|code_start|> """ def __init__(self, path, min_order, max_order): """Creates an ngram output handler. Args: path (string): Path to the ngram directory to create min_order (int): Minimum order of extracted ngrams ...
total = utils.log_sum([hypo.total_score for hypo in hypos])
Based on the snippet: <|code_start|> pass @abstractmethod def write_hypos(self, all_hypos, sen_indices=None): """This method writes output files to the file system. The configuration parameters such as output paths should already have been provided via constructor arguments. ...
self.f.write(io.decode(hypos[0].trgt_sentence))
Here is a snippet: <|code_start|># Copyright © 2014 Bart Massey # StringTable class as a hash table. class StringTable(object): def __init__(self): self.table = [] for _ in range(65536): self.table += [[]] # Return the value at position k. def lookup(self, k): <|code_end|> . W...
for kv in self.table[djb2(k)]:
Given the following code snippet before the placeholder: <|code_start|> def navbar(request): ''' Adds the needed data for the navbar context ''' return { 'navbar': { <|code_end|> , predict the next line using imports from the current file: from django.conf import settings from showing.models ...
'galleries': Gallery.objects.all()
Given the following code snippet before the placeholder: <|code_start|> def setup_attributes(self, tags): date = 0 time = 0 for code, value in super(Sun, self).setup_attributes(tags): if code == 40: self.intensity = value elif code == 63: ...
date = calendar_date(date)