Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|># coding: utf8
from __future__ import unicode_literals
class ProjectApplyForm(forms.ModelForm):
class Meta:
<|code_end|>
using the current file's imports:
from django import forms
from .models import ProjectApply
and any relevant context from other fil... | model = ProjectApply |
Given snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals
class AccountsAppConfig(AppConfig):
name = 'brasilcomvc.accounts'
verbose_name = 'Autenticação e Autorização'
def ready(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from... | city_items_pre_import.connect(filter_city_import) |
Given the code snippet: <|code_start|> date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(editable=False, default=True)
is_staff = models.BooleanField(editable=False, default=False)
# Notifications
email_newsletter = models.BooleanField(default=True)
# Verbose na... | send_template_email( |
Here is a snippet: <|code_start|>
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
twisted.internet.base.DelayedCall.debug = True
class NetworkAddressTestCase(unittest.TestCase):
def testGetNetworkAddress(self):
d = getNetworkAddress()
d.addCallback(self._testGetNetworkAddres... | n = NetworkAddressGetter() |
Given the following code snippet before the placeholder: <|code_start|>
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
twisted.internet.base.DelayedCall.debug = True
class NetworkAddressTestCase(unittest.TestCase):
def testGetNetworkAddress(self):
<|code_end|>
, predict the next line using... | d = getNetworkAddress() |
Based on the snippet: <|code_start|>
**Arguments:**
* *url* -- URL for the request.
**Keyword arguments:**
* *last_modified* -- Last modified date string to send as a request
header. (Default ``None``)
* *etag* -- Etag string to send as a request header. ... | postdata[key] = convertToUTF8(postdata[key]) |
Predict the next line after this snippet: <|code_start|>class ValueIteration(object):
"""
Implementation of the enumerative Value Iteration algorithm.
It performs successive, synchronous Bellman backups until
convergence is achieved for the given error epsilon for the
infinite-horizon MDP with disco... | states = StateSpace(self._mdp.current_state_fluents()) |
Given the code snippet: <|code_start|>
class ValueIteration(object):
"""
Implementation of the enumerative Value Iteration algorithm.
It performs successive, synchronous Bellman backups until
convergence is achieved for the given error epsilon for the
infinite-horizon MDP with discount factor gamma.... | actions = ActionSpace(self._mdp.actions()) |
Given the following code snippet before the placeholder: <|code_start|># GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with MDP-ProbLog. If not, see <http://www.gnu.org/licenses/>.
class MDP(object):
"""
Representation of an MDP and... | self._engine.add_fact(Fluent.create_fluent(term, 0), 0.5) |
Predict the next line after this snippet: <|code_start|> return self.__transition(state, action)
transition = self.__transition_cache.get(cache, None)
if transition is None:
transition = self.__transition(state, action)
self.__transition_cache[cache] = transition
... | states = StateSpace(self.current_state_fluents()) |
Predict the next line for this snippet: <|code_start|>
transition = self.__transition_cache.get(cache, None)
if transition is None:
transition = self.__transition(state, action)
self.__transition_cache[cache] = transition
return transition
def __transition(self, stat... | actions = ActionSpace(self.actions()) |
Based on the snippet: <|code_start|># This file is part of MDP-ProbLog.
# MDP-ProbLog 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.
... | fluent = Fluent.create_fluent(term, timestep) |
Given the following code snippet before the placeholder: <|code_start|> reward = self.__collect_reward(state, action)
state = self.__sample_next_state(state, action)
total += discount * reward
path.extend([action, state])
discount *= gamma
return total... | state = StateSpace.state(state) |
Based on the snippet: <|code_start|># (at your option) any later version.
# MDP-ProbLog 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.
# Y... | self.__actions = ActionSpace(mdp.actions()) |
Using the snippet: <|code_start|> self.assertEqual(value, expected_assignments[str(term)])
def test_add_assignment(self):
engine = self.engines['sysadmin']
fluents = engine.declarations('state_fluent')
for i in range(2**len(fluents)):
state = Term('__s%d__' % ... | terms = [Fluent.create_fluent(term, 0) for term in terms] |
Next line prediction: <|code_start|> def test_format(self):
"""Test number formatting function"""
tp = Template()
T = 12121414141232
G = 12121414141.235
M = 12121414
k = 12123.23
z = 12.25
m = 0.01212
u = 0.00001212
n = 0.00000001212
... | self.assertEqual(type(recast("1234")), int) |
Given the following code snippet before the placeholder: <|code_start|>''' Provides access to templates and css files '''
logger = logging.getLogger(__name__)
# Template path and templates
SmlTemplateEnv = Environment(loader = PackageLoader("snakemakelib", "_templates"))
SmlTemplateEnv.globals.update(zip=zip)
# Stat... | css_files = [join(SNAKEMAKELIB_PATH, 'static', 'basic.css')] |
Given the code snippet: <|code_start|># Copyright (C) 2014 by Per Unneberg
# pylint: disable=R0904, C0301, C0103
class TestUtils(unittest.TestCase):
"""Test snakemakelib.utils functions"""
def test_isoformat(self):
"""Test isoformatting function"""
s = "120924"
self.assertEqual(isoforma... | self.assertTrue (is_installed("ls")) |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2014 by Per Unneberg
# pylint: disable=R0904, C0301, C0103
class TestUtils(unittest.TestCase):
"""Test snakemakelib.utils functions"""
def test_isoformat(self):
"""Test isoformatting function"""
s = "120924"
<|code_end|>
wit... | self.assertEqual(isoformat(s), "2012-09-24") |
Given snippet: <|code_start|># PM Platform model. Free-form text providing further details of the platform/technology used.
# PU Platform unit (e.g. flowcell-barcode.lane for Illumina or slide for SOLiD). Unique identifier.
# SM Sample. Use pool name where a pool is being sequenced.
class ReadGroup(RunRegexp):
... | return isoformat(self[k]) |
Continue the code snippet: <|code_start|> """
if data is None:
return ""
else:
tab_tt = tt.Texttable()
tab_tt.set_precision(2)
if not header is None:
data[0] = header
w = [len(c) + 2 for c in data[0]]
for r in data:
for i in range(0, len... | _tp = Template() |
Given the code snippet: <|code_start|> Number of input reads | 4699845
Average input read length | 202
UNIQUE READS:
Uniquely mapped reads number | 4011114
Uniquely mapped read... | st = Star([(self.f, 'bar')]) |
Using the snippet: <|code_start|># Copyright (C) 2015 by Per Unneberg
# pylint: disable=R0904
logging.basicConfig(level=logging.DEBUG)
class TestRules(unittest.TestCase):
"""Test rules"""
def setUp(self):
self.workflow = Workflow("foo")
name = self.workflow.add_rule(name="bar")
self.wo... | create_rule_from_existing(name="foo", template="bar", workflow=self.workflow) |
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2015 by Per Unneberg
# pylint: disable=R0904, C0301, C0103
class TestFindFiles(unittest.TestCase):
def setUp(self):
"""Setup text fixtures"""
self.walk = [
[os.curdir, ['foo', 'bar'], ['1_121023_FLOWC... | f = find_files(regexp="\w+.fastq.gz") |
Based on the snippet: <|code_start|>def set_cmd(home, cmd, module):
"""Set the command, checking if the program is installed in the
process.
Args:
home (str): path to application
cmd (str): the actual command name
module (str): the calling module
Returns:
str: full path to the ... | if not is_installed(cmd): |
Here is a snippet: <|code_start|># Copyright (C) 2015 by Per Unneberg
# pylint: disable=R0904
logger = logging.getLogger(__name__)
class TestTuxedoReadGroup(unittest.TestCase):
"""Test TuxedoReadGroup class"""
def test_rg_init(self):
"""Test initializing TuxedoReadGroup"""
<|code_end|>
. Write the nex... | rg = TuxedoReadGroup(regexp="test", ID='test', DT="120924") |
Using the snippet: <|code_start|># Copyright (C) 2015 by Per Unneberg
# pylint: disable=R0904
logger = logging.getLogger(__name__)
class TestSraTools(unittest.TestCase):
"""Test sratools functionality"""
def setUp(self):
self.metadata = io.StringIO("\n".join(["SampleName,Run",
... | register_metadata("foo.csv", config = {}) |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2015 by Per Unneberg
# pylint: disable=R0904, C0301, C0103
class TestQualimap(unittest.TestCase):
"""Test Qualimap"""
def setUp(self):
self.data = ['>>>>>>> Globals\n',
'number of windows = 10\n',
... | qm = Qualimap([('foo', 'bar')]) |
Given the code snippet: <|code_start|> assert results == "pika/plop"
def test_007(finder):
results = finder.get_relative_from_paths("/home/foo/pika/plop", [
"/etc",
"/home/foo/pika",
"/home/bar/pika",
"/home/bar",
])
assert results == "plop"
def test_008(finder):
... | with pytest.raises(FinderException): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
def test_001_success(settings):
"""
Validate required value on dummy value
"""
processor = SettingsPostProcessor()
result = processor._validate_required({}, "DUMMY_NAME", "foo")
assert result == "foo"
def test_002_fail(settin... | with pytest.raises(SettingsInvalidError): |
Predict the next line for this snippet: <|code_start|> os.path.join(settings.lib2_path, 'addons/_some_addon.scss'),
os.path.join(settings.sample_path, 'main_basic.scss'),
os.path.join(settings.sample_path, 'components/_webfont.scss'),
os.path.join(settings.lib1_path, 'library_1_fullstack.... | with pytest.raises(UnresolvablePath): |
Based on the snippet: <|code_start|>
assert resolved_paths == [
os.path.join(settings.sample_path, '_vendor.scss'),
os.path.join(settings.sample_path, 'components/_filename_test_1.scss'),
os.path.join(settings.sample_path, '_empty.scss'),
os.path.join(settings.sample_path, 'component... | with pytest.raises(UnclearResolution): |
Given the following code snippet before the placeholder: <|code_start|> "foo.scss",
"bar/*.scss",
"*.scss",
"*.css",
],
False
),
(
"pika/bar/foo.sass",
[
"foo.sass",
"bar/*.sass",
"*.sass",
... | with pytest.raises(FinderException): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# Backend default filename shortcuts
YAML_FILENAME = SettingsBackendYaml._default_filename
JSON_FILENAME = SettingsBackendJson._default_filename
@pytest.mark.parametrize("options,filename", [
([], JSON_FILENAME),
(["--backend=y... | result = runner.invoke(cli_frontend, ["compile"]+options) |
Predict the next line for this snippet: <|code_start|> # absolute filepath
(
{"basedir": "/home/no/pasaran"},
{"filepath": "/home/bart/www/boussole_custom.txt"},
("/home/bart/www", "boussole_custom.txt"),
),
# filename and filled basedir, need normalize
(
{"basedir": "... | backend = SettingsBackendBase(**settings_kwargs) |
Given the following code snippet before the placeholder: <|code_start|>
def test_001_success(settings, temp_builds_dir):
"""
Validate existing file path
"""
basedir = temp_builds_dir.join("postprocessor_validate_path_001")
os.makedirs(basedir.strpath)
processor = SettingsPostProcessor()
f... | with pytest.raises(SettingsInvalidError): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
def test_001_success(settings, temp_builds_dir):
"""
Validate existing file path
"""
basedir = temp_builds_dir.join("postprocessor_validate_path_001")
os.makedirs(basedir.strpath)
<|code_end|>
, generate the next line using the import... | processor = SettingsPostProcessor() |
Using the snippet: <|code_start|> Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location.
"""
with open(filepath, "w") as fp:
pyaml.dump(content, dst=fp, indent=indent)
def parse(self, file... | raise SettingsBackendError(msg.format(filepath, exc)) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_self(settings, inspector):
"""
Ensure self import is detected
"""
sourcepath_0 = os.path.join(settings.sample_path, 'main_circular_0.scss')
sources = [
os.path.join(settings.sample_path, 'main_basic.scss'),
sou... | with pytest.raises(CircularImport): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def test_css_compat_ok(compiler, temp_builds_dir):
"""
Ensure CSS import compatibility is ok
"""
basedir = temp_builds_dir.join("compiler_css_compat_ok").strpath
<|code_end|>
, predict the immediate next line with the help of imports:
impo... | basic_settings = Settings(initial={ |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize("backend_engine,loader,loader_opts", [
(
SettingsBackendJson,
json.loads,
{},
),
(
<|code_end|>
, generate the next line using the imports in this file:
import os
import json
import yaml
impor... | SettingsBackendYaml, |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.mark.parametrize("backend_engine", [
SettingsBackendJson,
SettingsBackendYaml,
])
def test_basic(settings, custom_project_settings, backend_engine):
"""
Load basic settings file fail because of wrong paths
"""
backend = backend_... | with pytest.raises(SettingsInvalidError): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_ok_001(settings, parser):
"""parser.ScssImportsParser: Single quote"""
assert parser.strip_quotes("'foo'") == "foo"
def test_ok_002(settings, parser):
"""parser.ScssImportsParser: Double quotes"""
assert parser.strip_quotes('"foo"... | with pytest.raises(InvalidImportRule): |
Based on the snippet: <|code_start|> (
"/home/plop/foobar.PY",
{"*.py"},
{"*.txt"},
False,
True,
),
(
"/home/plop/foobar.txt",
{"*.py"},
{"*.txt"},
False,
False,
),
(
"/home/plop/",
{"*.py"},
{"*.t... | assert match_path(path, included, excluded, case_sensitive) is expected |
Given snippet: <|code_start|> syntax = "scss"
REGEX_IMPORT_RULE = re.compile(r'@import\s*(url)?\s*\(?([^;]+?)\)?;',
re.IGNORECASE)
# Second part (for singleline comment) contain a negative lookbehind
# assertion to avoid to match on url protocole (http://) which cause i... | raise InvalidImportRule(error_msg.format(content)) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
def test_001(compiler, temp_builds_dir):
"""
Basic sample without source map
"""
basedir = temp_builds_dir.join("compiler_safecompile").strpath
<|code_end|>
, predict the next line using imports from the c... | basic_settings = Settings(initial={ |
Continue the code snippet: <|code_start|> """
FINDER_STYLESHEET_EXTS = ["scss", "sass"]
def get_relative_from_paths(self, filepath, paths):
"""
Find the relative filepath from the most relevant multiple paths.
This is somewhat like a ``os.path.relpath(path[, start])`` but where
... | raise FinderException("'Finder.get_relative_from_paths()' could not " |
Continue the code snippet: <|code_start|>])
def test_ok(settings, sample_project_settings, backend_engine):
"""
Backend content parsing success
"""
backend = backend_engine(basedir=settings.fixtures_path)
path, filename = backend.parse_filepath()
filepath = backend.check_filepath(path, filename... | with pytest.raises(SettingsBackendError): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
def test_empty(settings, inspector):
"""inspector.ScssInspector: Some lib components used but no given library"""
sourcepath = os.path.join(settings.sample_path, 'main_using_libs.scss')
sources = [
sourcepath,
]
... | with pytest.raises(UnresolvablePath): |
Here is a snippet: <|code_start|> """
backend = SettingsBackendBase()
result = backend.check_filepath(
settings.fixtures_path,
filename=SettingsBackendBase._default_filename
)
assert result == os.path.join(settings.fixtures_path,
SettingsBackendBase... | with pytest.raises(SettingsBackendError): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
def test_001_default(settings, sample_project_settings):
"""
Create a empty Settings object width default values
"""
settings_object = Settings()
<|code_end|>
. Write the next line using the current file imports:
import copy
from boussole.con... | assert settings_object._settings == DEFAULT_SETTINGS |
Given snippet: <|code_start|> Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location.
"""
with open(filepath, "w") as fp:
json.dump(content, fp, indent=indent)
def parse(self, filepath, con... | raise SettingsBackendError(msg.format(filepath)) |
Given the following code snippet before the placeholder: <|code_start|>
# Backend default filename shortcuts
YAML_FILENAME = SettingsBackendYaml._default_filename
JSON_FILENAME = SettingsBackendJson._default_filename
def test_001(settings, caplog):
"""
Basic
"""
runner = CliRunner()
# Temporary ... | result = runner.invoke(cli_frontend, opts) |
Predict the next line after this snippet: <|code_start|> (
'/home/foo',
'/home/bar',
'/home/foo',
),
(
'/home/foo',
'/home/bar',
'/home/foo',
'/home/foo',
),
(
'/home/foo',
'/home/bar',
'/home/foo',
'/home/bar',
... | with pytest.raises(SettingsInvalidError): |
Predict the next line for this snippet: <|code_start|>
return engines, filenames, extensions
def get_engine(self, filepath, kind=None):
"""
From given filepath try to discover which backend format to use.
Discovering is pretty naive as it find format from file extension.
A... | raise SettingsDiscoveryError(msg.format(filepath)) |
Predict the next line for this snippet: <|code_start|> for k in list(library_paths):
if k not in basepaths:
basepaths.append(k)
for import_rule in paths:
candidates = self.candidate_paths(import_rule)
# Search all e... | raise UnresolvablePath( |
Based on the snippet: <|code_start|> if paths:
# Add given library paths to the basepaths for resolving
# Accept a string if not allready in basepaths
if (
library_paths and
isinstance(library_paths, str) and
library_paths not in... | raise UnclearResolution( |
Given the code snippet: <|code_start|>])
def test_init(projectstarter, name, klass):
"""
Default backend
"""
p = projectstarter(name)
assert p.backend_name == name
assert isinstance(p.backend_engine, klass)
@pytest.mark.parametrize("name,klass", [
('json', SettingsBackendJson),
('yaml... | with pytest.raises(SettingsBackendError): |
Given snippet: <|code_start|> """
if name not in self._engines:
msg = "Given settings backend is unknowed: {}"
raise SettingsBackendError(msg.format(name))
return self._engines[name](**kwargs)
class ProjectStarter(ProjectBase):
"""
Provide methods to create a ne... | raise SettingsInvalidError( |
Given the following code snippet before the placeholder: <|code_start|> _engines: Available Configuration backends. Read only.
backend_name: Backend name to use from available ones.
backend_engine: Backend engine selected from given name.
"""
_engines = {
"json": SettingsBackendJs... | raise SettingsBackendError(msg.format(name)) |
Continue the code snippet: <|code_start|>"""
Project management
==================
"""
class ProjectBase(object):
"""
Project base
Arguments:
backend_name (string): Backend name, can be either ``json`` or
``yaml``.
Attributes:
_engines: Available Configuration backends. ... | "json": SettingsBackendJson, |
Based on the snippet: <|code_start|>"""
Project management
==================
"""
class ProjectBase(object):
"""
Project base
Arguments:
backend_name (string): Backend name, can be either ``json`` or
``yaml``.
Attributes:
_engines: Available Configuration backends. Read ... | "yaml": SettingsBackendYaml, |
Continue the code snippet: <|code_start|>
assert os.path.exists(os.path.join(basedir, settings_filename))
assert os.path.exists(os.path.join(basedir, "scss"))
assert os.path.exists(os.path.join(basedir, "css"))
with open(os.path.join(basedir, settings_filename), "r") as fp:
assert module.load(f... | with pytest.raises(SettingsInvalidError): |
Next line prediction: <|code_start|>
d = {'col1' : pd.Series([1.], index=[0]),
'col2' : pd.Series([1., 2.], index=[0, 1])}
df = pd.DataFrame(d)
#--------------------------------(CSV to dataframe)-----------------------------
#test converting a CSV file to a pandas dataframe
def test_CSVtoDataframe1():
<|code_e... | testing_df = load.CSVtoDataFrame('inputCSV.csv') |
Here is a snippet: <|code_start|>
d = {'col1' : pd.Series([1, 2, 2, 2, 3, 3, 3, 4]),
'col2' : pd.Series(['hello hello', 'hello world 2', 'world world', '1 world', 'random', 'random'])}
df = pd.DataFrame(d)
#-------------------------(test analysis for string datatype)------------------------
#test min word lengt... | test_analysis = analyze.textAnalysis(test_series) |
Predict the next line for this snippet: <|code_start|>
* **useWords** : a ``bool`` flag which may be set to ``True`` to plot word frequencies instad of row value frequencies for a string column
* **cutoff** : an ``int`` specifying the top *n* values by frequency to plot, default is 50, maximum is 50
The function ... | tuples = textAnalysis(column)["word_frequencies"] |
Next line prediction: <|code_start|>
d = {'col1' : pd.Series([1., 2., 3., 4.], index=[0, 1, 3, 4]),
'col2' : pd.Series([1., 2., 2., 4.], index=[0, 1, 2, 4]),
'col3' : pd.Series([1., 2., 3., 4., 5.])}
df = pd.DataFrame(d)
#-----------------------------(fillDown)-----------------------------
#fill all column... | clean.fillDown(testing_df, 0, 1, 'pad') |
Using the snippet: <|code_start|> 'state': c['Status'],
'created': c['Created'],
}
if 'com.myaas.expiresAt' in c['Labels']:
db.update({'expires_at': c['Labels']['com.myaas.expiresAt']})
databases.append(db)
return jsonify(databases=databases)
@app.route(... | host=HOSTNAME, |
Given the code snippet: <|code_start|>
app = Flask(__name__)
logger = logging
logger.basicConfig(
format='%(asctime)s {:4} %(levelname)s: %(message)s'.format(os.getpid()),
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
from flask import Flask, Response, request, j... | level=logging.DEBUG if DEBUG else logging.WARNING) |
Predict the next line after this snippet: <|code_start|> abort(404)
if request.args.get('all'):
return jsonify(container=db.inspect())
result = dict(
database=db.database,
host=HOSTNAME,
name=db.name,
port=db.host_port,
user=db.user,
password=db.p... | ttl = int(ttl) if ttl else CONTAINER_TTL |
Here is a snippet: <|code_start|> databases=list_databases())
@app.route('/db', methods=['get'])
def show_databases():
databases = []
for c in get_myaas_containers():
db = {
'template': c['Labels']['com.myaas.template'],
'name': c['Labels']['com.myaas.instance'],
... | db = database(client, template, name) |
Continue the code snippet: <|code_start|>
app = Flask(__name__)
logger = logging
logger.basicConfig(
format='%(asctime)s {:4} %(levelname)s: %(message)s'.format(os.getpid()),
level=logging.DEBUG if DEBUG else logging.WARNING)
@app.route('/', methods=['get'])
def hello_world():
return jsonify(
s... | for c in get_myaas_containers(): |
Here is a snippet: <|code_start|> status="Service is running",
templates=list_database_templates(),
databases=list_databases())
@app.route('/db', methods=['get'])
def show_databases():
databases = []
for c in get_myaas_containers():
db = {
'template': c['Labels']['co... | database = get_enabled_backend().Database |
Given the following code snippet before the placeholder: <|code_start|>
app = Flask(__name__)
logger = logging
logger.basicConfig(
format='%(asctime)s {:4} %(levelname)s: %(message)s'.format(os.getpid()),
level=logging.DEBUG if DEBUG else logging.WARNING)
@app.route('/', methods=['get'])
def hello_world():... | databases=list_databases()) |
Here is a snippet: <|code_start|>
app = Flask(__name__)
logger = logging
logger.basicConfig(
format='%(asctime)s {:4} %(levelname)s: %(message)s'.format(os.getpid()),
level=logging.DEBUG if DEBUG else logging.WARNING)
@app.route('/', methods=['get'])
def hello_world():
return jsonify(
status="S... | templates=list_database_templates(), |
Based on the snippet: <|code_start|>
@app.route('/db', methods=['get'])
def show_databases():
databases = []
for c in get_myaas_containers():
db = {
'template': c['Labels']['com.myaas.template'],
'name': c['Labels']['com.myaas.instance'],
'state': c['Status'],
... | except NonExistentDatabase: |
Predict the next line after this snippet: <|code_start|>@app.route('/db/<template>/<name>', methods=['post'])
def create_database(template, name):
logger.debug(f'requested create DB from "{template}" as "{name}"')
form_ttl = request.form.get("ttl")
json_ttl = request.get_json(silent=True)
json_ttl = jso... | except NonExistentTemplate: |
Based on the snippet: <|code_start|> result.update({'expires_at': db.container['Labels']['com.myaas.expiresAt']})
return jsonify(result)
@app.route('/db/<template>/<name>', methods=['post'])
def create_database(template, name):
logger.debug(f'requested create DB from "{template}" as "{name}"')
for... | except ImportInProgress: |
Predict the next line after this snippet: <|code_start|>
def list_dump_files():
files_in_dir = os.listdir(settings.DUMP_DIR)
return filter(lambda x: x.endswith('.sql'), files_in_dir)
def indent(string, level=1):
spacing = " " * level
return spacing + string
def remove_recreate_database(template)... | db = backend(client, template, False) |
Predict the next line for this snippet: <|code_start|>
def list_dump_files():
files_in_dir = os.listdir(settings.DUMP_DIR)
return filter(lambda x: x.endswith('.sql'), files_in_dir)
def indent(string, level=1):
spacing = " " * level
return spacing + string
def remove_recreate_database(template):
... | backend = get_enabled_backend().Template |
Here is a snippet: <|code_start|>
def start_template_database(db_name):
print(f"- Creating database {db_name}")
db = remove_recreate_database(db_name)
print(indent("* Starting database..."))
db.start()
print(indent("* Started"))
print(indent("* Waiting for database to accept connections"))
... | if is_empty(sql_file): |
Next line prediction: <|code_start|>
print(indent("* Starting database..."))
db.start()
print(indent("* Started"))
print(indent("* Waiting for database to accept connections"))
try:
db.wait_for_service_listening()
return db
except Exception as e:
print(indent(
... | db = RetryPolicy(5, delay=2)(start_db_func) |
Based on the snippet: <|code_start|>
def list_dump_files():
files_in_dir = os.listdir(settings.DUMP_DIR)
return filter(lambda x: x.endswith('.sql'), files_in_dir)
def indent(string, level=1):
spacing = " " * level
return spacing + string
def remove_recreate_database(template):
"""
find e... | except NonExistentTemplate: |
Continue the code snippet: <|code_start|> return db
except Exception as e:
print(indent(
f"* Max time waiting for database exceeded"
", retrying..."
))
db.stop()
db.restore_backup()
print_exception()
raise e
def main():
dumps = lis... | except (ImportDataError, Exception) as e: |
Given the code snippet: <|code_start|>
def _is_dead(self, container):
return container['State'] == 'exited'
def _is_unhealthy(self, container):
return 'unhealthy' in container['Status']
def remove_database(container):
template = container['Labels']['com.myaas.template']
name = contain... | databases = cf.filter(get_myaas_containers()) |
Predict the next line after this snippet: <|code_start|> logger.info("%s is dead, queued for deletion", name)
return True
if self._unhealthy and self._is_unhealthy(container):
logger.info("%s is unhealthy, queued for deletion", name)
return True
return Fa... | backend = get_enabled_backend().Database |
Predict the next line for this snippet: <|code_start|> return True
if self._unhealthy and self._is_unhealthy(container):
logger.info("%s is unhealthy, queued for deletion", name)
return True
return False
def _is_expired(self, container):
if 'com.myaas.ex... | backend(client, template, name).remove() |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
def get_enabled_backend():
return importlib.import_module(settings.BACKEND)
def get_myaas_containers():
<|code_end|>
. Use current file imports:
(import logging
import importlib
from .. import settings
from .container import list_contai... | return filter(_is_database_container, list_containers()) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
current_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_path)
root = os.path.join(current_path, '..')
sys.path.append(root)
LOG = logging
def run_worker(name=None, logging_level='error',
... | app.worker_main(argv) |
Given the code snippet: <|code_start|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import
current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath(os.path.join(current_path, '..'))
sys.path.append(root_path)
# chagne work dir
os.chdir(root_path)
<|code_e... | tasks = app.tasks |
Given snippet: <|code_start|>
for crawler in celeryconfig.crawlers:
filepath = os.path.join(root_path, 'data/%s' % crawler.get('scheduler').filter_file_name)
filepath = os.path.abspath(filepath)
if not os.path.exists(filepath):
#tasks[crawler['name'] + '.schedule'].delay()
for task in tasks[... | if (get_message_queue_size('parse') < config.max_task_queue_size * 2 and |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
# registe all crawlers's task
for crawler in celeryconfig.crawlers:
# set the crawler_name so we know the namek when parser add new task
# and the know call corresponding registed task
crawler.get('r... | @app.task(name=crawler.get('name')+'.request', |
Here is a snippet: <|code_start|> self.scheduler.save_filter()
return
# initcail tasks:
if not tasks and not check_task:
for task in self.scheduler.init_generator():
if task.get('priority', None):
#app.tasks[self.crawler_name+'.req... | if (get_message_queue_size('request') < config.max_task_queue_size): |
Using the snippet: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
__author__ = 'stuartreid'
<|code_end|>
, determine the next line of code. You have imports:
from Optimizers.GeneticAlgorithm import Genet... | class GeneticProgramming(GeneticAlgorithm): |
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
<|code_end|>
, predict the next line using imports from the current file:
import random
from Optimiz... | class GeneticAlgorithm(Optimizer): |
Continue the code snippet: <|code_start|> :param problem:
:param parameters[0]: Crossover rate (% of the population which is used in crossover)
:param parameters[1]: Crossover strategy e.g. sexual, asexual
:param parameters[2]: Mutation rate (% of the population which is mutated)
... | class Individual(Solution): |
Given snippet: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/Page295.htm
"""
<|code_end|>
, continue by predicting the next line. Consider cu... | class Ackley(Problem): |
Based on the snippet: <|code_start|>
def __init__(self, stock_tickers=None, start_date=None, end_date=None):
self.stock_tickers = stock_tickers
self.start_date = self.get_date(start_date)
self.end_date = self.get_date(end_date)
def download_csv(self):
for ticker in self.stock_ti... | for case in switch(string_values[1]): |
Based on the snippet: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from Problems.Problem import Problem
and context (classes, fu... | class Cigar(Problem): |
Predict the next line for this snippet: <|code_start|>
__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
<|code_end|>
with the help of current file imports:
from Sorters.Sorter import Sorter
import random
and context fro... | class BitonicSorter(Sorter): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.