Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of th... | settings = QtCore.QSettings(_organization, _application_name) |
Predict the next line for this snippet: <|code_start|> self.finished.emit()
def abort(self):
pass
class PickingStreamTask(QtCore.QObject):
"""A class to handle an event picking/detection task.
PickingTask objects are meant to be passed to a QThread instance
that controls their exe... | detect_command = commands.DetectStreamEvents(self.trace_selector, |
Given snippet: <|code_start|> attribute = self.attributes[index.column()]
data = None
if attribute['type'] == 'event':
data = self.record.events[index.row()].__getattribute__(attribute['attribute_name'])
if attribute.get('attribute_type') == 'date':
... | self.color_key = COLOR_KEYS[int(settings.value(key))] |
Using the snippet: <|code_start|> if dateformat is not None:
data = data.strftime(dateformat)
rep_format = attribute.get('format', '{}')
return rep_format.format(data)
elif role == QtCore.Qt.BackgroundRole:
return self.calculateEventColor(in... | self.color_key = DEFAULT_COLOR_KEY |
Predict the next line for this snippet: <|code_start|> data = data.strftime(dateformat)
rep_format = attribute.get('format', '{}')
return rep_format.format(data)
elif role == QtCore.Qt.BackgroundRole:
return self.calculateEventColor(index)
else:
... | for key, color in DEFAULT_COLOR_SCHEME: |
Given the code snippet: <|code_start|>@copyright: Copyright 2013-2014, Jose Emilio Romero Lopez.
@license: GPL
@contact: jemromerol@gmail.com
This file is part of APASVO.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publish... | eventCreated = QtCore.Signal(rc.ApasvoEvent) |
Given the code snippet: <|code_start|> def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.attributes)
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
elif role == QtCore.Qt.DisplayRole:
attribute = self.attri... | settings = QtCore.QSettings(_organization, _application_name) |
Predict the next line after this snippet: <|code_start|> def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.attributes)
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
elif role == QtCore.Qt.DisplayRole:
attr... | settings = QtCore.QSettings(_organization, _application_name) |
Given the code snippet: <|code_start|>
This file is part of APASVO.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... | xres, yres = plotting.reduce_data(self.xdata, self.ydata, self.width, |
Continue the code snippet: <|code_start|> # Analytic signal
y0 = np.sqrt((xa ** 2) + (xao ** 2))
# Fix a threshold to modify the energies in the channels
thr = prctile(y0, noise_thr)
# Here we modify the amplitudes of the analytic signal. The amplitudes
# below the thresho... | event_t = findpeaks.find_peaks(ZTOT, threshold, order=peak_window * fs) |
Continue the code snippet: <|code_start|> lta = min(len(x), lta_length * fs + 1)
peak_window = int(peak_window * fs / 2.)
x_norm = np.abs(x - np.mean(x))
cf = np.zeros(len(x))
if len(cf) > 0:
if method == 'strides':
sta_win = stride_tricks.as_strided(np.concatenate((x_norm, np.ze... | event_t = findpeaks.find_peaks(cf, threshold, order=peak_window * fs) |
Predict the next line after this snippet: <|code_start|> but WITHOUT ANY WARRANTY; without even the implied warranty of
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 p... | class SaveDialog(QtGui.QDialog, ui_savedialog.Ui_SaveDialog): |
Given the code snippet: <|code_start|> signal, i.e.:
Format: Binary or text format.
Data-type: PCM 16, PCM 32, PCM 64, Float16, Float32 or Float64,
Endianness: Little-endian or big-endian.
Attributes:
fmt: Default file format. Available values are 'binary' and 'text'.
... | if futils.is_little_endian(): |
Given the following code snippet before the placeholder: <|code_start|># encoding: utf-8
'''
@author: Jose Emilio Romero Lopez
@copyright: Copyright 2013-2014, Jose Emilio Romero Lopez.
@license: GPL
@contact: jemromerol@gmail.com
This file is part of APASVO.
This program is free software: you can r... | FORMATS = (rawfile.format_binary, rawfile.format_text) |
Given the following code snippet before the placeholder: <|code_start|> self.label_text = label_text
self.cancel_button_text = cancel_button_text
self.cancel_label_text = cancel_label_text
self._init_ui()
def _init_ui(self):
self.label = QtGui.QLabel(self.label_text)
... | self._task.error.connect(self.on_error) |
Given the code snippet: <|code_start|>
def __init__(self, bfirls=None, fs=50.0, P_noise_db=0.0,
low_period=50.0, high_period=10.0, bandwidth=4.0,
overlap=1.0, f_low=2.0, f_high=18.0,
low_amp=0.2, high_amp=0.1, **kwargs):
super(EarthquakeGenerator, self).__i... | fhandler = rawfile.get_file_handler(fileobj, dtype=dtype, |
Here is a snippet: <|code_start|> self.ax.grid(True, which='both')
# Set event markers
self.marker_select_color = 'r'
self.marker_color = 'b'
self.markers = {}
self.update_markers()
# Selection parameters
self.selected = False
self.selector = self.a... | x_data, y_data = plotting.reduce_data(self.time, self.trace.signal, pixel_width, xmin, xmax) |
Given snippet: <|code_start|> You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
matplotlib.rcParams['backend'] = 'qt4agg'
matplotlib.rcParams['backend.qt4'] = 'PySide'
matplotlib.rcParams['patch.antialiased'] = False
matplotl... | axes_formatter = FuncFormatter(lambda x, pos: clt.float_secs_2_string_date(x, trace.starttime)) |
Predict the next line for this snippet: <|code_start|> elif case ==3:
conns = np.array([[0,1],[1,2],[1,3],[2,4], [3,4],[4,5]])
nodeTypes = getNodeTypes(conns)
Np = np.shape(conns)[0]
Nn = len(np.unique(conns))
Ls = [50,150,25,25,25,50]
Ns = [Ls[k]*2 for k in range(Np)]... | (fi, fc) = writePipes(fn,conns, xs,ys, Ns, Ls, Mrs, Ds, jt, bt, bv, r, h0s, q0s, T, M, a, elevs) |
Given the code snippet: <|code_start|>
class EmailRequestHandler(webapp2.RequestHandler):
def post(self):
inbound_message = mail.InboundEmailMessage(self.request.body)
logging.info("Email request! Sent from %s with message subject %s" % (inbound_message.sender,inbound_message.subject))
body = ... | response = api_bridge.getparking() |
Predict the next line for this snippet: <|code_start|>
class XmppHandler(webapp2.RequestHandler):
def post(self):
message = xmpp.Message(self.request.POST)
logging.info("XMPP request! Sent form %s with message %s" % (message.sender,message.body))
# normalize the XMPP requests
if message.... | response = api_bridge.getparking() |
Given the code snippet: <|code_start|>
class XmppHandler(webapp2.RequestHandler):
def post(self):
message = xmpp.Message(self.request.POST)
logging.info("XMPP request! Sent form %s with message %s" % (message.sender,message.body))
# normalize the XMPP requests
if message.sender.find('@')... | response = meta.getStats(caller) |
Given the code snippet: <|code_start|>
class SMSRequestHandler(webapp2.RequestHandler):
def post(self):
# validate it is in fact coming from twilio
if config.ACCOUNT_SID != self.request.get('AccountSid'):
logging.error("Inbound request was NOT VALID. It might have been spoofed!")
self... | response = api_bridge.getparking() |
Here is a snippet: <|code_start|>class SMSRequestHandler(webapp2.RequestHandler):
def post(self):
# validate it is in fact coming from twilio
if config.ACCOUNT_SID != self.request.get('AccountSid'):
logging.error("Inbound request was NOT VALID. It might have been spoofed!")
self.respons... | response = meta.getStats(phone) |
Predict the next line for this snippet: <|code_start|> 'To' : friend.phone,
'Body' : self.request.get('text'),
}
try:
account.request('/%s/Accounts/%s/SMS/Messages' % (config.API_VERSION, config.ACCOUNT_SID),
'POST', sms)
... | q = PhoneLog.all() |
Given the following code snippet before the placeholder: <|code_start|> (self.request.get('sid'), self.request.get('phone')))
account = twilio.Account(config.ACCOUNT_SID, config.ACCOUNT_TOKEN)
sms = {
'From' : config.CALLER_ID,
'To' : self.request.get('phone'),
... | new_user = Caller() |
Predict the next line after this snippet: <|code_start|>
class MainHandler(webapp2.RequestHandler):
def post(self):
# this handler should never get called
logging.error("The MainHandler should never get called... %s" % self.request)
self.error(204)
def get(self):
self.post()
## end Main... | log = PhoneLog() |
Using the snippet: <|code_start|>
## end PhoneRequestBusHandler
class PhoneRequestStopHandler(webapp2.RequestHandler):
def get(self):
# validate it is in fact coming from twilio
if config.ACCOUNT_SID == self.request.get('AccountSid'):
logging.debug("PHONE request was confirmed to have come fr... | textBody = api_bridge.getarrivals(requestArgs, 1) |
Here is a snippet: <|code_start|> if study == 'brainpedia':
this_study = meta['study']
subject = meta['name'].split('_')[-1]
contrast = '_'.join(meta['task'].split('_')[1:])
task = meta['task'].split('_')[0]
else:
this_study = study
... | for study in STUDY_LIST: |
Given the code snippet: <|code_start|> contrast = '_'.join(meta['task'].split('_')[1:])
task = meta['task'].split('_')[0]
else:
this_study = study
subject = meta['name'].split('_')[0]
contrast = meta['contrast_definition']
task = meta['task'... | ys = add_study_contrast(ys) |
Continue the code snippet: <|code_start|> Takes a collection of datasets and split them into a test and train
collection.
Parameters
----------
data : Dict[str, np.ndarray]
Collection of input data (one for each study)
target : Dict[str, pd.DataFrame]
Collection of targe... | data = zip_data(data, target) |
Continue the code snippet: <|code_start|> train_data : Dict[str, np.ndarray]
test_data : Dict[str, np.ndarray]
train_target : Dict[str, pd.DataFrame]
test_target : Dict[str, pd.DataFrame]
"""
data = zip_data(data, target)
datasets = {'train': {}, 'test': {}}
if isinstance(test_size, (... | train_data, train_target = unzip_data(datasets['train']) |
Using the snippet: <|code_start|>
idx = pd.IndexSlice
def single_mask(masker, imgs):
return masker.transform(imgs)
def single_reduce(components, data, lstsq=False):
if not lstsq:
return data.dot(components.T)
else:
X, _, _, _ = np.linalg.lstsq(components.T, data.T)
return X.T
... | data = fetch_contrasts(studies) |
Here is a snippet: <|code_start|>
idx = pd.IndexSlice
def single_mask(masker, imgs):
return masker.transform(imgs)
def single_reduce(components, data, lstsq=False):
if not lstsq:
return data.dot(components.T)
else:
X, _, _, _ = np.linalg.lstsq(components.T, data.T)
return X.T
... | data = fetch_all() |
Predict the next line after this snippet: <|code_start|> 'contrast': contrast,
'z_map': join(subject_dir, this_map)})
df = pd.DataFrame(rec)
df.set_index(['study', 'subject', 'task', 'contrast', 'direction'],
inplace=True)
if drop_some:... | res = hcp_builder_fetch_hcp(data_dir=source_dir, n_subjects=n_subjects, |
Predict the next line for this snippet: <|code_start|>
def fetch_contrasts(study, data_dir=None):
if study == 'archi':
return fetch_archi(data_dir=data_dir)
elif study == 'brainomics':
return fetch_brainomics(data_dir=data_dir)
elif study == 'la5c':
return fetch_la5c(data_dir=data_di... | data_dir = get_data_dir(data_dir) |
Given the following code snippet before the placeholder: <|code_start|>"""
Analyse a model trained on data provided by load_reduced_loadings().
"""
# Note that 'components_453_gm' is currently hard-coded there
def compute_components(estimator, config, return_type='img'):
"""Compute components from a Factore... | modl_atlas = fetch_atlas_modl() |
Given snippet: <|code_start|>"""
Analyse a model trained on data provided by load_reduced_loadings().
"""
# Note that 'components_453_gm' is currently hard-coded there
def compute_components(estimator, config, return_type='img'):
"""Compute components from a FactoredClassifier estimator"""
module = cura... | mask = fetch_mask() |
Continue the code snippet: <|code_start|>
warnings.filterwarnings('ignore', category=FutureWarning, module='h5py')
def fetch_atlas_modl(data_dir=None,
url=None,
resume=True, verbose=1):
"""Download and load a multi-scale atlas computed using MODL over HCP900.
Param... | data_dir = get_data_dir(data_dir) |
Here is a snippet: <|code_start|> contrasts_metrics.to_pickle(join(save_dir, 'contrasts_metrics.pkl'))
baseline = 'logistic'
accuracies.set_index(['estimator', 'study', 'seed'], inplace=True)
accuracies.sort_index(inplace=True)
median = accuracies['accuracy'].loc[baseline].groupby(
level='st... | info = get_study_info() |
Given the code snippet: <|code_start|>
estimators = accuracies['estimator'].unique()
y_labels = {}
y_labels['multi_study'] = ('Decoding from\nmulti-study\ntask-optimized\n'
'networks')
y_labels['ensemble'] = ('Decoding from\nmulti-study\ntask-optimized\n'
... | output_dir = join(get_output_dir(output_dir=None), 'normalized', 'split_by_task') |
Here is a snippet: <|code_start|> i = 0
while True:
yield '%s_%i' % (name, i)
i += 1
def plot_4d_image(img, names=None, output_dir=None,
colors=None,
view_types=['stat_map'],
threshold=True,
n_jobs=1, verbose=10):
if no... | mask = fetch_mask() |
Here is a snippet: <|code_start|>
def test_atlas_modl():
"""Download the dataset in default directory and check success.
"""
atlas = fetch_atlas_modl()
keys = ['components_64',
'components_128',
'components_453_gm',
]
assert all(os.path.exists(atlas[key]) for ... | df = fetch_contrasts('brainpedia') |
Given the following code snippet before the placeholder: <|code_start|>
def test_atlas_modl():
"""Download the dataset in default directory and check success.
"""
atlas = fetch_atlas_modl()
keys = ['components_64',
'components_128',
'components_453_gm',
]
asse... | loadings = fetch_reduced_loadings() |
Predict the next line for this snippet: <|code_start|>
def test_atlas_modl():
"""Download the dataset in default directory and check success.
"""
atlas = fetch_atlas_modl()
keys = ['components_64',
'components_128',
'components_453_gm',
]
assert all(os.path.ex... | fetch_mask() |
Given the following code snippet before the placeholder: <|code_start|>
def test_atlas_modl():
"""Download the dataset in default directory and check success.
"""
atlas = fetch_atlas_modl()
keys = ['components_64',
'components_128',
'components_453_gm',
]
asse... | keys = STUDY_LIST |
Given the code snippet: <|code_start|>#
# Copyright (C) 2013 Savoir-Faire Linux Inc.
#
# This file is part of Sageo
#
# Sageo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | def set_filters(self, filters): |
Given the code snippet: <|code_start|>
tablename = datasource["table"]
add_headers += datasource.get("add_headers", "")
merge_column = datasource.get("merge_by")
if merge_column:
columns = [merge_column] + columns
# Most layouts need current state of object in order to
# choose backgrou... | live.set_prepend_site(True) |
Continue the code snippet: <|code_start|>migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec old_model in ... | script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, Base.metadata) |
Given snippet: <|code_start|> context = {}
host_query = \
"GET hosts\n" \
"Stats: state >= 0\n" \
"Stats: state > 0\n" \
"Stats: scheduled_downtime_depth = 0\n" \
"StatsAnd: 2\n" \
"Stats: state > 0\n" \
"Stats: scheduled... | context['hstdata'] = live.query_summed_stats(host_query) |
Given snippet: <|code_start|>
class Router(routers.DefaultRouter):
root_view_name = "api.root"
APIRootView = APIRoot
router = Router()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rest_framework import routers
from django.conf.urls import include
from django.url... | router.register("actions", Actions, basename="api.action") |
Given snippet: <|code_start|>
class Router(routers.DefaultRouter):
root_view_name = "api.root"
APIRootView = APIRoot
router = Router()
router.register("actions", Actions, basename="api.action")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rest_framework import r... | router.register("cases", Cases, basename="api.case") |
Predict the next line after this snippet: <|code_start|>
class Router(routers.DefaultRouter):
root_view_name = "api.root"
APIRootView = APIRoot
router = Router()
router.register("actions", Actions, basename="api.action")
router.register("cases", Cases, basename="api.case")
<|code_end|>
using the current f... | router.register("labels", Labels, basename="api.label") |
Here is a snippet: <|code_start|>
class Router(routers.DefaultRouter):
root_view_name = "api.root"
APIRootView = APIRoot
router = Router()
router.register("actions", Actions, basename="api.action")
router.register("cases", Cases, basename="api.case")
router.register("labels", Labels, basename="api.label")
... | router.register("partners", Partners, basename="api.partner") |
Given the code snippet: <|code_start|> cleaned_data = super(UserForm, self).clean()
# if a user is updating their own password, need to provide current password
new_password = cleaned_data.get("new_password")
if new_password and self.instance == self.user:
current_password = ... | partner = forms.ModelChoiceField(label=_("Partner Organization"), queryset=Partner.objects.none(), required=False) |
Based on the snippet: <|code_start|> password = cleaned_data.get("password") or cleaned_data.get("new_password")
if password:
confirm_password = cleaned_data.get("confirm_password", "")
if password != confirm_password:
self.add_error("confirm_password", _("Password... | if cleaned_data.get("role") in PARTNER_ROLES and not cleaned_data.get("partner"): |
Here is a snippet: <|code_start|>
def clean(self):
cleaned_data = super(UserForm, self).clean()
# if a user is updating their own password, need to provide current password
new_password = cleaned_data.get("new_password")
if new_password and self.instance == self.user:
cu... | role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True) |
Next line prediction: <|code_start|> model = User
exclude = ()
class OrgUserForm(UserForm):
"""
Form for user editing at org-level
"""
role = forms.ChoiceField(label=_("Role"), choices=ROLE_ORG_CHOICES, required=True)
partner = forms.ModelChoiceField(label=_("Partner Organization"... | role = forms.ChoiceField(label=_("Role"), choices=ROLE_PARTNER_CHOICES, required=True) |
Predict the next line for this snippet: <|code_start|> widget=forms.Textarea,
help_text=_("Banner text displayed to all users"),
required=False,
)
contact_fields = forms.MultipleChoiceField(
choices=(), label=_("Contact fields"), help_text=_("Contact fields to display"), required... | for field in Field.objects.filter(org=org, is_active=True).order_by("label"): |
Predict the next line after this snippet: <|code_start|> )
suspend_groups = forms.MultipleChoiceField(
choices=(),
label=_("Suspend groups"),
help_text=_("Groups to remove contacts from when creating cases"),
required=False,
)
followup_flow = forms.ChoiceField(
c... | for group in Group.get_all(org, dynamic=False).order_by("name"): |
Using the snippet: <|code_start|>
urlpatterns = DailyCountExportCRUDL().as_urlpatterns()
urlpatterns += [
re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"),
re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"),
re_path(r... | re_path(r"^cases_closed_chart/$", CasesClosedPerMonthChart.as_view(), name="statistics.cases_closed_chart"), |
Continue the code snippet: <|code_start|>
urlpatterns = DailyCountExportCRUDL().as_urlpatterns()
urlpatterns += [
re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"),
re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"),
r... | re_path(r"^cases_opened_chart/$", CasesOpenedPerMonthChart.as_view(), name="statistics.cases_opened_chart"), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = DailyCountExportCRUDL().as_urlpatterns()
urlpatterns += [
re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"),
re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="sta... | re_path(r"^labels_pie_chart/$", MostUsedLabelsChart.as_view(), name="statistics.labels_pie_chart"), |
Using the snippet: <|code_start|>
urlpatterns = DailyCountExportCRUDL().as_urlpatterns()
urlpatterns += [
re_path(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"),
<|code_end|>
, determine the next line of code. You have imports:
from django.urls import re_path
from .views i... | re_path(r"^replies_chart/$", RepliesPerMonthChart.as_view(), name="statistics.replies_chart"), |
Next line prediction: <|code_start|> queue.appendleft(n)
#search the relatives of the current node according to relative_fxn
#for each relative, if we haven't traversed it, add it to the queue
for n in relative_fxn(current):
if n not in already_visited:
already_visited.a... | tokens = BasLexer.tokens |
Predict the next line after this snippet: <|code_start|>
@coroutine
def invoke(handler, parameters):
def respond(params):
sleep(0.1)
return {'parameters': parameters}
def return_true():
sleep(0.1)
return True
<|code_end|>
using the current file's imports:
from toto.invocation import *
from toto.t... | response = TaskQueue.instance('test1').yield_task(respond, parameters) |
Predict the next line after this snippet: <|code_start|>
@coroutine
def invoke(handler, parameters):
def respond(params):
sleep(0.1)
raise TotoException(4242, 'Test Toto Exception')
<|code_end|>
using the current file's imports:
from toto.invocation import *
from toto.tasks import TaskQueue
from time import... | raise Return((yield TaskQueue.instance('test1').yield_task(respond, parameters))) |
Given the code snippet: <|code_start|>
class TestSession(unittest.TestCase):
def test_generate_id(self):
session_id = TotoSession.generate_id()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import urllib2
import urllib
import urlparse
import json
import os
import signal
i... | self.assertEqual(len(session_id), SESSION_ID_LENGTH) |
Predict the next line after this snippet: <|code_start|>
@coroutine
def invoke(handler, parameters):
def respond(params):
sleep(0.1)
raise Exception('Test Exception')
<|code_end|>
using the current file's imports:
from toto.invocation import *
from toto.tasks import TaskQueue
from time import sleep
from tor... | raise Return((yield TaskQueue.instance('test1').yield_task(respond, parameters))) |
Next line prediction: <|code_start|>
@asynchronous
def invoke(handler, parameters):
def respond(params):
sleep(0.1)
handler.respond({'parameters': parameters})
<|code_end|>
. Use current file imports:
(from toto.invocation import *
from toto.tasks import TaskQueue
from time import sleep)
and context includi... | TaskQueue.instance('test').add_task(respond, parameters) |
Using the snippet: <|code_start|>
class _Request(object):
def __init__(self, headers, body, timeout, retry_count, future, callback=None):
self.headers = headers
self.body = body
self.timeout = timeout
self.retry_count = retry_count
self.callback = callback
self.future = future
self.request... | class HTTPWorkerConnection(WorkerConnection): |
Continue the code snippet: <|code_start|> 'The MIT License (MIT)', # The MIT License
'GNU LESSER GENERAL PUBLIC LICENSE', # GNU LGPL
(
'THE SOFTWARE IS PROVIDED \"AS IS\" AND THE '
'AUTHOR DISCLAIMS ALL WARRANTIES'
), ... | full_url = utilities.TOKENIZER.tokenize(record[0].rstrip()) |
Here is a snippet: <|code_start|> path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
os.pardir
)
)... | (result, value) = main.run(project_id, '', cursor, **options) |
Predict the next line after this snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
... | self.database = database.Database(settings) |
Continue the code snippet: <|code_start|>
"""
The documentation attribute measures the ratio of comment lines of code to
non-blank lines of code (sloc + cloc) as determined by the `cloc` tool
(http://cloc.sourceforge.net/). Even though GitHub determines the primary
language of each repository, this module will consider... | util = utilities.get_loc(repo_path) |
Predict the next line after this snippet: <|code_start|> 'authentication.'
)
for token in tokens:
self.available_tokens.put(token)
def tokenize(self, url):
if url.startswith('https://api.github.com'):
if self.have_tokens:
token = s... | status = url_to_json(rate_limit_url) |
Using the snippet: <|code_start|>class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | actual = main.run(project_id, '', cursor, **options) |
Next line prediction: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | self.database = database.Database(settings) |
Here is a snippet: <|code_start|> attribute.reference.global_init(cursor, samples)
finally:
self.database.disconnect()
def run(self, project_id, repository_root):
rresults = dict()
repository_home = os.path.join(repository_root, str(project_id))
ou... | timeout = utilities.parse_datetime_delta(attribute.timeout) |
Using the snippet: <|code_start|> path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
os.pardir
)
)... | (result, value) = main.run(project_id, '', cursor, **options) |
Given the code snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | self.database = database.Database(settings) |
Predict the next line for this snippet: <|code_start|>
def run(project_id, repo_path, cursor, **options):
threshold = options.get('threshold', 0)
cursor.execute('SELECT url FROM projects WHERE id = {}'.format(project_id))
record = cursor.fetchone()
<|code_end|>
with the help of current file imports:
i... | full_url = utilities.TOKENIZER.tokenize(record[0].rstrip()) |
Next line prediction: <|code_start|> path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
os.pardir
)
... | actual = main.run(project_id, '', cursor, **options) |
Here is a snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | core.config = config |
Given the code snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | self.database = database.Database(config['options']['datasource']) |
Next line prediction: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | config = utilities.read(file_) |
Predict the next line after this snippet: <|code_start|> dest='plugins_dir',
help='Path to the folder containing your set of attribute plugins.'
)
parser.add_argument(
'repository_id',
type=int,
nargs=1,
help='Identifier for a project as it appears in the \
... | connection = establish_database_connection(config['options']['datasource']) |
Given the code snippet: <|code_start|> parser.add_argument(
'repository_id',
type=int,
nargs=1,
help='Identifier for a project as it appears in the \
GHTorrent database.'
)
parser.add_argument(
'repository_path',
type=is_dir,
nargs=1,
... | init_attribute_plugins(attributes, connection) |
Based on the snippet: <|code_start|> )
parser.add_argument(
'repository_id',
type=int,
nargs=1,
help='Identifier for a project as it appears in the \
GHTorrent database.'
)
parser.add_argument(
'repository_path',
type=is_dir,
nargs=1,
... | load_attribute_plugins(args.plugins_dir, attributes) |
Continue the code snippet: <|code_start|> default='attributes',
dest='plugins_dir',
help='Path to the folder containing your set of attribute plugins.'
)
parser.add_argument(
'repository_id',
type=int,
nargs=1,
help='Identifier for a project as it appears i... | config = process_configuration(args.config_file) |
Given snippet: <|code_start|> type=int,
nargs=1,
help='Identifier for a project as it appears in the \
GHTorrent database.'
)
parser.add_argument(
'repository_path',
type=is_dir,
nargs=1,
help='Path to the repository source code.'
)
i... | score, results = process_repository( |
Given the code snippet: <|code_start|>
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
return parser.parse_args()
def main():
"""
Main execution flow.
"""
args = process_arguments()
config = process_configuration(args.config_file)
connection = establish_database_... | save_result(run_id, args.repository_id, results, cursor) |
Continue the code snippet: <|code_start|> )
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
return parser.parse_args()
def main():
"""
Main execution flow.
"""
args = process_arguments()
config = process_configuration(args.config_file)
connection = establish_... | run_id = get_run_id() |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
def process_arguments():
"""
Uses the argparse module to parse commandline arguments.
Returns:
Dictionary of parsed commandline arguments.
"""
parser = argparse.ArgumentParser(
description='Calculate the score of a r... | type=is_dir, |
Given the following code snippet before the placeholder: <|code_start|> jsondata = dict()
try:
if jsonfile:
jsondata = json.load(jsonfile)
return jsondata
except:
raise Exception('Failure in loading JSON data {0}'.format(
jsonfile.name
))
finally:
... | delta = dateutil.relativedelta() |
Continue the code snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | (result, value) = main.run(project_id, '', cursor, **options) |
Here is a snippet: <|code_start|>
class MainTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.pardir,
... | self.database = database.Database(settings) |
Given the code snippet: <|code_start|>
MAP = {
'C': ['C', 'C/C++ Header'],
'C++': ['C++', 'C/C++ Header'],
'Objective C': ['Objective C', 'C/C++ Header']
}
def run(project_id, repo_path, cursor, **options):
threshold = options.get('threshold', 0)
query = 'SELECT language FROM projects WHERE id =... | sloc = utilities.get_loc(repo_path) |
Given snippet: <|code_start|>
QUERY = '''
SELECT MAX(c.created_at)
FROM commits c
JOIN project_commits pc ON pc.commit_id = c.id
WHERE pc.project_id = {0} and c.created_at > 0
'''
def run(project_id, repo_path, cursor, **options):
bresult = False
rresult = 'dormant'
cursor.execute(QU... | delta = dateutil.relativedelta(today, last_commit_date) |
Predict the next line after this snippet: <|code_start|>
QUERY = '''
SELECT MAX(c.created_at)
FROM commits c
JOIN project_commits pc ON pc.commit_id = c.id
WHERE pc.project_id = {0} and c.created_at > 0
'''
def run(project_id, repo_path, cursor, **options):
bresult = False
rresult = 'dorm... | threshold = utilities.parse_datetime_delta(options['threshold']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.