Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> parser = argparse.ArgumentParser(description='Analyze trace file simulating the placement of the nodes.')
#parser.add_argument('integers', metavar='N', type=int, nargs='+',
# help='an integer for the accumulator')
parser.add_argument('--trace-file', require... | manager = TopologyManager(topology_graph, social_graph, topology_coords, enable_mobility = False, topology_file=args.topology) |
Based on the snippet: <|code_start|>#
logging.basicConfig(filename='example.log',
level=logging.DEBUG,
format='%(asctime)-15s %(message)s'
)
<|code_end|>
, predict the immediate next line with the help of imports:
from cache_manager import CacheManager
import logging
and context (classes, functions, sometim... | class LCE(CacheManager): |
Using the snippet: <|code_start|> dictionary. To fix this a list of all valid keys should be created
and checked here before setting the value. These are the keys used
in the ief file.
"""
headlist = ['Title', 'Path', 'Datafile', 'Results']
if key in headlist:
... | if not uf.isNumeric(time): |
Predict the next line after this snippet: <|code_start|>
return contents
def write(self, filepath=None, overwrite=False):
"""Write the contents of this file to disk.
Writes out to file in the format required for reading by ISIS/FMP.
Note:
If a filepath is not provided ... | ft.writeFile(contents, filepath) |
Given the code snippet: <|code_start|> Summary:
Example use of the fmp package to update file paths in an .ief file
and save the ief file under a new name.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
U... | loader = fl.FileLoader() |
Given snippet: <|code_start|>
from __future__ import unicode_literals
# logging references with a __name__ set to this module.
logger = logging.getLogger(__name__)
def getFile(file_path):
"""Text file reader.
Reads a text file, appending each new line to a list.
Args:
filePath (str): File pat... | file_contents.append(uf.encodeStr(line)) |
Predict the next line for this snippet: <|code_start|> 01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
def main():
utils.assertionErrors = 0
# FMP
print ('*************************************************************')
print ('Running fmp package integration tes... | tt = tuflowload.TuflowLoadTests().runTests() |
Predict the next line after this snippet: <|code_start|>
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
def main():
utils.assertionErrors = 0
# FMP
print ('*************************************************************')
print ('Running fmp package integration tests...')
pri... | tu = tuflowupdate.TuflowUpdateTests().runTests() |
Given the following code snippet before the placeholder: <|code_start|> Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
def main():
utils.assertionErrors = 0
# FMP
print ('*************************************************************')
print ('Running fmp package integration test... | tu = tcfmodelfile.UpdateTcfModelFile().runTests() |
Predict the next line for this snippet: <|code_start|>
Note that one of the tests will attempt to write out the model to a folder
called 'test_output' in the integration_tests directory. This folder is
added to the .gitignore file. If your python path is different in may go
elsewhere as it uses... | dl = datload.DatLoadTests().runTests() |
Using the snippet: <|code_start|>
Summary:
This is the main class for the integration tests.
It calls a suite of tests that work on an actual loaded TuflowModel to
check that it functions properly in the 'real world'.
Note that one of the tests will attempt to write out the model to a f... | utils.assertionErrors = 0 |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
class DatLoadTests(object):
def runTests(self):
cwd = os.getcwd()
path = "integration_tests/test_data/model1/fmp/ship_test_v1-1.DAT"
main_path = os.path.normpath(os.path.join(cwd, path))
se... | loader = fileloader.FileLoader() |
Predict the next line for this snippet: <|code_start|> main_path = os.path.normpath(os.path.join(cwd, path))
self.loadDatModel(main_path)
self.test_unitCounts()
self.test_icsSetup()
self.test_datWrite()
def loadDatModel(self, path):
print ('Loading FMP .dat model... | utils.softAssertion(len(headers), 1) |
Given the code snippet: <|code_start|> return False
elif data in b'? ':
return None
else:
# Todo: return something? (But that would be misleading!)
message = 'Illegal value for logical field: {!r}'
raise ValueError(message.format(data))
def... | if isinstance(memo, BinaryMemo): |
Using the snippet: <|code_start|>
class TuflowLoadTests(object):
def runTests(self):
cwd = os.getcwd()
path1 = "integration_tests/test_data/model1/tuflow/runs/test_run1.tcf"
path2 = "integration_tests/test_data/model1/tuflow/runs/test_run_noexist.tcf"
main_path = os.... | loader = fileloader.FileLoader() |
Next line prediction: <|code_start|> os.path.join(cwd, 'asread/model1'),
os.path.join(cwd, 'asread/model1/tuflow'),
os.path.join(cwd, 'asread/model1/tuflow/runs'),
os.path.join(cwd, 'asread/model1/tuflow/model')
]
... | ft.writeFile(val, pkey) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
class TuflowLoadTests(object):
def runTests(self):
cwd = os.getcwd()
path1 = "integration_tests/test_data/model1/tuflow/runs/test_run1.tcf"
path2 = "integration_tests/test_data/model1/tuflow/runs/... | utils.softAssertion(self.tuflow.missing_model_files, []) |
Given the following code snippet before the placeholder: <|code_start|> return data[:end_of_memo]
# Alternative end of memo markers:
# \x1a\x1a
# \x0d\x0a
return data[:eom]
class DB4MemoFile(MemoFile):
"""dBase IV memo file"""
def __getitem__(self,... | name = ifind(dbf_filename, ext=ext) |
Given the code snippet: <|code_start|> 'tcf': tuflowloader.TuflowLoader,
'dat': datloader.DatLoader,
'ied': datloader.DatLoader}
self.warnings = []
def loadFile(self, filepath, arg_dict={}):
"""Load a file from d... | ext = uuf.fileExtensionWithoutPeriod(filepath) |
Given snippet: <|code_start|>
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
from __future__ import unicode_literals
logger = logging.getLogger(__name__)
"""logging references with a __name__ set to this module."""
class FileLoader(ob... | 'tcf': tuflowloader.TuflowLoader, |
Given snippet: <|code_start|> simple to load any type of file from one place.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
from __future__ import unicode_literals
logger = logging.getLogger(__name__)
"""logging references with a ... | self._known_files = {'ief': iefloader.IefLoader, |
Given snippet: <|code_start|> Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
from __future__ import unicode_literals
logger = logging.getLogger(__name__)
"""logging references with a __name__ set to this module."""
class FileLoader(obj... | 'dat': datloader.DatLoader, |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
class TestError(ValueError):
pass
class TuflowUpdateTests(object):
def runTests(self):
self.loadTuflowModel()
self.test_changeActiveStatus()
self.test_addPartToPartHolder()
sel... | loader = fileloader.FileLoader() |
Here is a snippet: <|code_start|>
# Make sure we know what it is before
zpt_part = control.contains(command="Set Zpts", variable="2",
parent_filename="test_trd2")
zln_part = control.contains(command="Z Line THIN", filename="zln_shiptest_trd_v2")
parts ... | varpart = factory.TuflowFactory.getTuflowPart(line, tgc)[0] |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
class TestError(ValueError):
pass
class TuflowUpdateTests(object):
def runTests(self):
self.loadTuflowModel()
self.test_changeActiveStatus()
self.test_addPartToPartHolder()
self.test_removePartFrom... | utils.softAssertion(self.tuflow.missing_model_files, []) |
Given snippet: <|code_start|>
class FunctionFamilyDetector(object):
def __init__(self,kb,language,family):
self.language = language
self.kb = kb
self.family = family
def __str__(self):
return '<' + self.language.id + ': ' + \
'function words (family=' + self.fami... | language = models.ForeignKey(Language) |
Continue the code snippet: <|code_start|> word = models.TextField()
unique_together = (('language', 'word'),)
def __str__(self):
return "<" + self.language.id + ":" + self.word + ">"
class Meta:
db_table = 'functionwords'
class FunctionFamily(models.Model):
""" defines a family of ... | predtype = models.ForeignKey(Relation) |
Here is a snippet: <|code_start|>| <NP>:t1 <ADVP>:adv (<text "contain"> | <text "contains">):x1 <NP>:t2
=> dict(frame=words(SLOT1, adv, x1, SLOT2),
relation="HasA", text1=t1, text2=t2, adv=adv)
| <NP>:t1 <BE>:x1 <ADVP>:adv <NP>:t2 <POST>
=> dict(frame=words(SLOT1, x1, adv, SLOT2),
relat... | for sent in TaggedSentence.objects.all(): |
Next line prediction: <|code_start|>
def update_scores():
queryset_foreach(Assertion, lambda x: x.update_score(),
batch_size=100)
<|code_end|>
. Use current file imports:
(from csc_utils.batch import queryset_foreach
from conceptnet.models import Sentence, Assertion, RawAssertion)
and context including class... | queryset_foreach(RawAssertion, lambda x: x.update_score(), |
Using the snippet: <|code_start|>class AssertionVote(models.Model):
"""
A vote on an Assertion by a User.
This is temporarily a view of the big Votes table:
CREATE VIEW temp_assertion_votes AS
SELECT id, user_id, object_id AS assertion_id, vote
FROM votes WHERE content_type_id=68;
""... | sentence = models.ForeignKey(Sentence, null=True) |
Continue the code snippet: <|code_start|>__version__ = "4.0rc2"
DEFAULT_LANGUAGE = en = Language(id='en', name='English')
class TimestampedModel(models.Model):
created = models.DateTimeField(default=datetime.now)
updated = models.DateTimeField()
def save(self, **kwargs):
self.updated = datet... | user = models.ForeignKey(User) |
Given snippet: <|code_start|>
# use get_or_create so it's atomic
surface_form, _ = SurfaceForm.objects.get_or_create(concept=concept,
text=text, residue=residue, language=lang)
return surface_form
def update_raw(self):
for raw in self.left... | class Assertion(models.Model, ScoredModel): |
Predict the next line after this snippet: <|code_start|>
class Relation(models.Model):
name = models.CharField(max_length=128,unique=True)
description = models.CharField(max_length=255, null=True, blank=True)
def __unicode__(self):
return self.name
@classmethod
def get(cls, name):
... | frequency = models.ForeignKey(Frequency) |
Using the snippet: <|code_start|>
def get_config_file():
return path.join(get_config_directory(), 'canaryd.conf')
def get_scripts_directory():
return path.join(get_config_directory(), 'scripts')
def _get_settings(config_file=None):
'''
Load the config from the filesystem if provided, with defaults.... | raise ConfigError('Config file error') |
Using the snippet: <|code_start|> log_file_rotation = None
# Number of files to rotate
log_file_rotation_count = 5
# syslog facility to log to
syslog_facility = None
debug = False
collect_interval_s = 30
# Only collect slow plugin data this often
slow_collect_interval_s = 900
... | logger.debug('Root user, so setting log file to /var/log/canaryd.log') |
Given the code snippet: <|code_start|>from __future__ import division
def get_ps_cpu_stats():
'''
Uses ps + awk to total CPU usage, then divide by # CPUs to get the final %.
'''
<|code_end|>
, generate the next line using the imports in this file:
import re
import sys
from multiprocessing import cpu... | output = get_command_output( |
Given the following code snippet before the placeholder: <|code_start|>
if time_taken < interval:
sleep(interval - time_taken)
def _daemon_loop(iteration, previous_states, settings):
slow_plugin_iter_interval = round(
settings.slow_collect_interval_s / settings.collect_interval_s,
)
do... | state_diff = get_state_diff(plugin, data, previous_state) |
Predict the next line after this snippet: <|code_start|>from __future__ import division
def _sleep_until_interval(start, interval):
time_taken = time() - start
if time_taken < interval:
sleep(interval - time_taken)
def _daemon_loop(iteration, previous_states, settings):
slow_plugin_iter_inter... | logger.info('Getting plugin (include_slow={0}) states...'.format(do_slow_plugins)) |
Predict the next line for this snippet: <|code_start|>from __future__ import division
def _sleep_until_interval(start, interval):
time_taken = time() - start
if time_taken < interval:
sleep(interval - time_taken)
def _daemon_loop(iteration, previous_states, settings):
slow_plugin_iter_interva... | plugins = get_and_prepare_working_plugins(settings, include_slow=do_slow_plugins) |
Predict the next line after this snippet: <|code_start|>from __future__ import division
def _sleep_until_interval(start, interval):
time_taken = time() - start
if time_taken < interval:
sleep(interval - time_taken)
def _daemon_loop(iteration, previous_states, settings):
slow_plugin_iter_inter... | states = get_plugin_states(plugins, settings) |
Given the code snippet: <|code_start|> else:
state_changes.append((plugin, ('SYNC', data)))
# Plugin state collected OK so now check for any specific events to
# send in addition.
plugin_events = plugin.get_events(settings)
if plugin_events:
... | settings_changes = backoff( |
Predict the next line for this snippet: <|code_start|> state_changes.append((plugin, ('SYNC', data)))
# Plugin state collected OK so now check for any specific events to
# send in addition.
plugin_events = plugin.get_events(settings)
if plugin_events:
... | upload_state_changes, |
Here is a snippet: <|code_start|>
DEB_REGEX = r'^[a-z]+\s+([a-zA-Z0-9\+\-\.]+):?[a-zA-Z0-9]*\s+([a-zA-Z0-9:~\.\-\+]+).+$'
RPM_REGEX = r'^([a-zA-Z0-9_\-\+]+)\-([0-9a-z\.\-]+)\.[a-z0-9_\.]+$'
PKG_REGEX = r'^([a-zA-Z0-9_\-\+]+)\-([0-9a-z\.]+)'
def get_parse_packages(timeout, package_type, command, regex, lower=True):
... | output = get_command_output( |
Here is a snippet: <|code_start|>
def check_root(message, exit=False):
# If we're root, we're all good!
if geteuid() <= 0:
return
message = click.style(message, 'yellow')
# If exit, just fail
if exit:
<|code_end|>
. Write the next line using the current file imports:
from os import get... | raise CanarydError(message) |
Given the following code snippet before the placeholder: <|code_start|>
def check_root(message, exit=False):
# If we're root, we're all good!
if geteuid() <= 0:
return
message = click.style(message, 'yellow')
# If exit, just fail
if exit:
raise CanarydError(message)
# Warn ... | raise UserCancelError() |
Given snippet: <|code_start|>
def get_docker_containers(timeout):
containers = {}
try:
output = get_command_output(
'docker inspect `docker ps -qa`',
shell=True,
timeout=timeout,
)
# Either Docker is down or there are no containers
<|code_end|>
, conti... | except CalledProcessError: |
Predict the next line after this snippet: <|code_start|>
def get_docker_containers(timeout):
containers = {}
try:
<|code_end|>
using the current file's imports:
import json
from canaryd.subprocess import CalledProcessError, get_command_output
and any relevant context from other files:
# Path: canaryd/sub... | output = get_command_output( |
Given the following code snippet before the placeholder: <|code_start|>
def setUpModule():
get_plugins()
class TestServicesEvents(TestCase):
def setUp(self):
self.plugin = get_plugin_by_name('services')
def test_should_apply_change_up_ports_only(self):
<|code_end|>
, predict the next line using... | change = Change( |
Next line prediction: <|code_start|>
def setUpModule():
get_plugins()
class TestServicesEvents(TestCase):
def setUp(self):
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from canaryd.diff import Change
from canaryd.plugin import get_plugin_by_name, get_plugins)
and context includi... | self.plugin = get_plugin_by_name('services') |
Based on the snippet: <|code_start|>
class TestPluginRealStates(TestCase):
def test_meta_plugin(self):
plugin = get_plugin_by_name('meta')
plugin.get_state({})
@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
jsontest_files = path.join('tests/plugins')
<|code_end|>
, predict ... | test_settings = CanarydSettings() |
Predict the next line for this snippet: <|code_start|>
Args:
change (Change): a change object
Returns:
status (bool): whether the change should be applied
'''
return True
@staticmethod
def generate_issues_from_change(change, settings):
'''
... | logger.debug(message) |
Predict the next line for this snippet: <|code_start|>
def get_plugins():
'''
Get the list of installed plugins.
'''
return PLUGINS
def get_plugin_names():
return six.iterkeys(NAME_TO_PLUGIN)
def get_plugin_by_name(plugin_name):
if plugin_name not in NAME_TO_PLUGIN:
raise NoPluginEr... | print_exception(debug_only=True) |
Predict the next line for this snippet: <|code_start|> def log(self, message):
message = '[{0}]: {1}'.format(self.name, message)
logger.debug(message)
def get_events(self, settings):
'''
Plugin can generate raw events here, ie for things that don't fit into
the spec/state... | data = get_command_output( |
Given the following code snippet before the placeholder: <|code_start|>
def disable_script(script, raise_if_noop=True):
scripts_directory = get_scripts_directory()
source_script = path.join(scripts_directory, 'available', script)
link_name = path.join(scripts_directory, 'enabled', script)
if not path.... | logger.debug('Creating scripts directory: {0}'.format(scripts_directory)) |
Next line prediction: <|code_start|> settings[key] = value
return settings
def _get_scripts(dirname):
scripts = []
all_settings = {}
script_names = listdir(dirname)
for name in script_names:
if any(name.endswith(e) for e in INVALID_EXTENSIONS):
continue
... | path.join(get_scripts_directory(), 'available'), |
Here is a snippet: <|code_start|> if status is not True:
continue
working_states.append((plugin, ('SYNC', data)))
# Sync this state and get settings
logger.info('Syncing initial state...')
remote_settings = backoff(
sync_states, working_states, settings,
error_me... | run_daemon(previous_states, settings, start_time=start_time) |
Given snippet: <|code_start|># Desc: entry point for canaryd
class GracefulExitRequested(Exception):
pass
def handle_graceful_quit(signum, frame):
raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option('-v', '--verbose', is_flag=True)... | logger.info('Starting canaryd v{0}'.format(__version__)) |
Based on the snippet: <|code_start|># canaryd
# File: canaryd/__main__.py
# Desc: entry point for canaryd
class GracefulExitRequested(Exception):
pass
def handle_graceful_quit(signum, frame):
raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@... | log_level = setup_logging(verbose, debug) |
Predict the next line after this snippet: <|code_start|> raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option('-v', '--verbose', is_flag=True)
@click.option('-d', '--debug', is_flag=True)
@click.version_option(
version=__version__,
prog_... | setup_logging_from_settings(settings) |
Given the following code snippet before the placeholder: <|code_start|>
log_level = setup_logging(verbose, debug)
logger.info('Starting canaryd v{0}'.format(__version__))
logger.info('Log level set to: {0}'.format(
logging.getLevelName(log_level),
))
# Ensure the config directory exists
... | plugins = get_and_prepare_working_plugins(settings) |
Based on the snippet: <|code_start|> logging.getLevelName(log_level),
))
# Ensure the config directory exists
ensure_config_directory()
# Load the settings, using our config file if provided
settings = get_settings()
# Setup any log file/syslog
setup_logging_from_settings(settings)... | states = get_plugin_states(plugins, settings) |
Predict the next line for this snippet: <|code_start|> prog_name='canaryd',
message='%(prog)s: v%(version)s',
)
def main(verbose, debug):
'''
Run the canaryd daemon.
'''
log_level = setup_logging(verbose, debug)
logger.info('Starting canaryd v{0}'.format(__version__))
logger.info('Log l... | backoff( |
Given the code snippet: <|code_start|> message='%(prog)s: v%(version)s',
)
def main(verbose, debug):
'''
Run the canaryd daemon.
'''
log_level = setup_logging(verbose, debug)
logger.info('Starting canaryd v{0}'.format(__version__))
logger.info('Log level set to: {0}'.format(
logging... | ping, settings, |
Using the snippet: <|code_start|> working_states.append((plugin, ('SYNC', data)))
# Sync this state and get settings
logger.info('Syncing initial state...')
remote_settings = backoff(
sync_states, working_states, settings,
error_message='Could not sync state',
max_wait=setti... | shutdown(settings) # we're exiting, so only one shot at this |
Given the following code snippet before the placeholder: <|code_start|> logger.info('Ping API...')
backoff(
ping, settings,
error_message='Could not ping',
max_wait=settings.collect_interval_s,
)
# Load the plugin list
plugins = get_and_prepare_working_plugins(settings)
... | sync_states, working_states, settings, |
Given the following code snippet before the placeholder: <|code_start|>
class GracefulExitRequested(Exception):
pass
def handle_graceful_quit(signum, frame):
raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option('-v', '--verbose', is_flag=... | ensure_config_directory() |
Predict the next line for this snippet: <|code_start|>
def handle_graceful_quit(signum, frame):
raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option('-v', '--verbose', is_flag=True)
@click.option('-d', '--debug', is_flag=True)
@click.version_o... | settings = get_settings() |
Next line prediction: <|code_start|># canaryd
# File: canaryd/__main__.py
# Desc: entry point for canaryd
class GracefulExitRequested(Exception):
pass
def handle_graceful_quit(signum, frame):
raise GracefulExitRequested('yawn')
@click.command(context_settings={'help_option_names': ['-h', '--help']})
@... | version=__version__, |
Predict the next line after this snippet: <|code_start|>
# We *require* procfs to check PID -> port mappings
HAS_PROCFS = path.exists('/proc')
PID_TO_PORTS = defaultdict(set)
def _get_lsof_pid_to_listens(timeout):
output = get_command_output(
'lsof -i -n -P -b -l -L -s TCP:LISTEN',
timeout=timeout... | logger.warning('Dodgy lsof line ignored: "{0}"'.format(line)) |
Next line prediction: <|code_start|> bits = line.split()
proto, _, _, local_address, _, _, program = bits
# Get the pid from PID/PROGRAM
pid = program.split('/')[0]
pid = int(pid)
# Work out the host:port bit
host, port = local_address... | except (CalledProcessError, OSError): |
Given the following code snippet before the placeholder: <|code_start|>
# We ignore these as they regularly get deleted/added as part of normal OSX
# lifecycle - and as such any events generated are not of use.
LAUNCHCTL_IGNORE_NAMES = ('oneshot', 'mdworker', 'mbfloagent')
# Systemd service types to ignore
SYSTEMD_I... | output = get_command_output( |
Using the snippet: <|code_start|>
class Change(object):
def __init__(self, plugin, type_, key, data=None):
self.plugin = plugin
self.type = type_
self.key = key
# COMPAT w/canaryd < 0.2
# Legacy support where added/deleted would either have data/None,
# rather than... | logger.info('Converted legacy data: {0}'.format(data)) |
Given the code snippet: <|code_start|>
if hasattr(obj, 'serialise'):
return obj.serialise()
if hasattr(obj, 'isoformat'):
return obj.isoformat()
if isinstance(obj, six.binary_type):
return obj.decode()
return JSONEncoder.default(self, obj)
def bac... | logger.critical('{0}, retrying in {1}s'.format(error_message, interval)) |
Given the code snippet: <|code_start|> logger.debug('Response data: {0}'.format(self.content))
def get_session():
global SESSION
if not SESSION:
SESSION = requests.Session()
return SESSION
def make_sync_or_changes_dict(states):
plugin_to_state = {}
for plugin, (status, stat... | settings = settings or get_settings() |
Given the code snippet: <|code_start|> self.name = name
self.message = message
self.content = content
def log(self):
logger.critical(
'{0}: {1}{2}'.format(
self.status_code,
self.name,
'({0})'.format(self.message) if self.me... | if status not in VALID_STATUSES: |
Next line prediction: <|code_start|>def _upload_states_return_settings(url, states, settings, json=None):
json = json or states
if json is not states:
json['states'] = states
response_data = make_api_request(
get_session().post, url,
settings=settings,
json=json,
# ... | 'canaryd_version': __version__, |
Based on the snippet: <|code_start|>
# Not ideal but using the vendored in (to requests) chardet package
if os.name == 'posix' and sys.version_info[0] < 3:
else:
def ensure_command_tuple(command):
if not isinstance(command, (list, tuple)):
return shlex.split(command)
return command
def decode_out... | logger.debug('Executing command: {0}'.format(command)) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# Run once an hour, smartctl can be intensive
# CANARYD_INTERVAL = 3600
SMART_RETURN_BITS = {
0: False, # command line parse error
1: 'device open failed',
2: 'SMART command failed',
3: 'disk failing',
# We track thre... | except (CalledProcessError, OSError): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# Run once an hour, smartctl can be intensive
# CANARYD_INTERVAL = 3600
SMART_RETURN_BITS = {
0: False, # command line parse error
1: 'device open failed',
2: 'SMART command failed',
3: 'disk failing',
# We track thresholds via stdo... | get_command_output( |
Given the following code snippet before the placeholder: <|code_start|>
class Contact(Handler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
<|code_end|>
, predict the next line using imports from the current file:
import json
from mainhandler import Handler
from ..utilities.u... | self.write(json.dumps(get_gist_data('3785786','contact_data'))) |
Given the following code snippet before the placeholder: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class Achievements(Handler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
<|code_end|>
, predict the next line using imports from the current file:
import json... | self.write(json.dumps(get_gist_data('3785895','achievements_data'))) |
Here is a snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class Experience(Handler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
<|code_end|>
. Write the next line using the current file imports:
import json
from mainhandler import Handler
from ..utiliti... | self.write(json.dumps(get_gist_data('3735396','experience_data'))) |
Given the code snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class GithubActivity(Handler):
def get(self):
activity = {}
entries = []
<|code_end|>
, generate the next line using the imports in this file:
import json
from mainhandler import Handler
from app.utilities.utils i... | user = setUser("<username>", "<password>") |
Given the code snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class GithubActivity(Handler):
def get(self):
activity = {}
entries = []
user = setUser("<username>", "<password>")
<|code_end|>
, generate the next line using the imports in this file:
import json
from ma... | entries = entries + getFollowers(user) |
Given snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class GithubActivity(Handler):
def get(self):
activity = {}
entries = []
user = setUser("<username>", "<password>")
entries = entries + getFollowers(user)
<|code_end|>
, continue by predicting the next line.... | entries = entries + getFollowing(user) |
Next line prediction: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class GithubActivity(Handler):
def get(self):
activity = {}
entries = []
user = setUser("<username>", "<password>")
entries = entries + getFollowers(user)
entries = entries + getFollowing(user... | entries = entries + getWatchedRepos(user) |
Here is a snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class Projects(Handler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
<|code_end|>
. Write the next line using the current file imports:
import json
from mainhandler import Handler
from ..utilities... | self.write(json.dumps(get_gist_data('3734919','projects_data'))) |
Here is a snippet: <|code_start|>'''
Created on Oct 1, 2012
@author: Sagar
'''
class Education(Handler):
def get(self):
self.response.headers['Content-Type'] = 'application/json'
<|code_end|>
. Write the next line using the current file imports:
import json
from mainhandler import Handler
from ..utiliti... | self.write(json.dumps(get_gist_data('3735401','education_data'))) |
Given the code snippet: <|code_start|> "media" : "",
"thumbnail" : "",
"credit" : "",
"caption" : ""
},
}
columns = row['f']
an_info['startDate'] = an_info['end... | class GithubArchiveHTML(Handler): |
Given the code snippet: <|code_start|> an_info['text'] = columns[4]['v'] + "-" + columns[7]['v']
an_info['tag'] = columns[0]['v']
an_info['asset']['caption'] = "<a href = '" + columns[8]['v'] + "' target='_blank'></a>"
an_info['asset']['credit'] = columns[6]['v']
#+ columns[5]['v... | parsed_archive = execute_bigquery_githubarchive(service) |
Given the code snippet: <|code_start|> self.response.headers['Content-Type'] = 'application/json'
"""Local_parser_result
self.write(json.dumps(local_archive))
"""
"""Remote_parser_result"""
service = build("bigquery", "v2", http=http)
parsed_archive = execu... | parsed_archive = execute_bigquery_toprepos(service) |
Given the following code snippet before the placeholder: <|code_start|>class GithubArchiveHTML(Handler):
def get(self):
#self.render_front("timeline.html")
self.render("metro_github_archive.html")
class GithubArchiveBigQuery(Handler):
def get(self):
self.response... | parsed_archive = execute_bigquery_toplanguages(service) |
Here is a snippet: <|code_start|>
timeline['date'] = info
timeline['era'] = era_info
timeline['chart'] = chart_info
data['timeline'] = timeline
return data
class GithubArchiveHTML(Handler):
def get(self):
#self.render_front("timeline.html")
self.render("... | parsed_archive = execute_bigquery_mostactive_users(service) |
Given the code snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
<|code_end|>
, generate the next line using the imports in this file:
import we... | ('/education', Education), |
Predict the next line for this snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
<|code... | ('/contact', Contact), |
Given the code snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/achievements', Achievements), |
Based on the snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/github_activity', GithubActivity), |
Using the snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/archive_data', GithubArchiveBigQuery), |
Predict the next line after this snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/github_archive', GithubArchiveHTML), |
Given snippet: <|code_start|>
app = webapp2.WSGIApplication([('/home', MainPage),
('/projects', Projects),
('/experience', Experience),
('/education', Education),
... | ('/toprepos', TopRepos), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.