Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
recursion_warning = '''\
WARNING: The peru module '{}' doesn't specify the 'recursive' field,
but its contents include a peru.yaml file. Peru's behavior here changed
<|code_end|>
. Write the next line using the current file imports:
import json
import os
import textwrap
from .cache i... | in version 0.4: modules with peru.yaml files are *no longer* recursive |
Given snippet: <|code_start|>
recursion_warning = '''\
WARNING: The peru module '{}' doesn't specify the 'recursive' field,
but its contents include a peru.yaml file. Peru's behavior here changed
in version 0.4: modules with peru.yaml files are *no longer* recursive
<|code_end|>
, continue by predicting the next line.... | by default. Add 'recursive: true' to the module definition to re-enable |
Given snippet: <|code_start|>class ArticlePipeline(object):
def get_media_request(self,item,info):
for url in item['file_urls']:
yield scrapy.Request(url)
def process_item(self,item,spider):
try:
self._mysqldb_insertitem(item)
logging.info(item)
r... | return '|'.join(source),htmlreplace |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class AutoSpider(scrapy.Spider):
name = 'autoSpider'
def __init__(self,rule):
self.rule=rule
self.allowed_domains = rule.allow_domains.split(',')
self.urllist=[]
super(AutoSpider,se... | finally: |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class ArticleSpider(CrawlSpider):
name = 'articleSpider'
def __init__(self,rule):
self.rule=rule
self.start_urls=rule.start_urls.split(',')
self.allowed_domains=rule.allow_domains.split(',')
rule_lis... | self.log('this is a list page %s'% response.url) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class BasespiderTemplate(scrapy.Spider):
def __init__(self,rule):
self.rule=rule
self.name = rule.name
self.allowed_domains = rule.allow_domains.split(',')
self.urllist=[]
super(B... | except: |
Using the snippet: <|code_start|> logger = logging.getLogger(gen_restricted_reference.__name__)
reference_handle = pysam.Fastafile(reference)
regions_bedtool = pybedtools.BedTool(regions_bed)
with open(out_reference, "w") as out_fasta:
for region_index, region in enumerate(regions_bedtool, star... | reference_handle = pysam.Fastafile(restricted_reference) |
Given the code snippet: <|code_start|>
targets = []
for x in rtorrent_config:
try:
info = parse_config_part(rtorrent_config[x], x)
except RTorrentConfigException as e:
print('Invalid config: ', e)
sys.exit(1)
targets.append(info)
for x in targets:
r = RTorrent(x)
<|code_end|>... | try: |
Next line prediction: <|code_start|>
targets = []
for x in rtorrent_config:
try:
info = parse_config_part(rtorrent_config[x], x)
except RTorrentConfigException as e:
print('Invalid config: ', e)
sys.exit(1)
<|code_end|>
. Use current file imports:
(from model.rtorrent import RTorrent
... | targets.append(info) |
Here is a snippet: <|code_start|>
targets = []
for x in rtorrent_config:
try:
info = parse_config_part(rtorrent_config[x], x)
except RTorrentConfigException as e:
print('Invalid config: ', e)
sys.exit(1)
targets.append(info)
for x in targets:
r = RTorrent(x)
try:
... | print('Failed to connect to libTorrent:', str(e)) |
Here is a snippet: <|code_start|>
targets = []
for x in rtorrent_config:
try:
info = parse_config_part(rtorrent_config[x], x)
except RTorrentConfigException as e:
print('Invalid config: ', e)
sys.exit(1)
targets.append(info)
for x in targets:
r = RTorrent(x)
<|code_end|>
. Wr... | try: |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
_default_logger_name = os.path.basename(sys.argv[0]).replace('.py', '')
def add_arguments(argument_parser):
argument_parser.add_argument(
'--quiet', '-q',
action = 'count',
default = 0,
help = 'Be less verbose.',
<... | ) |
Given snippet: <|code_start|>#!/usr/bin/env python3
_default_session_name = os.path.basename(sys.argv[0]).replace('.py', '')
def add_arguments(argument_parser):
argument_parser.add_argument(
'--profile', '-p',
metavar = 'NAME',
default = None,
help = unwrap("""
Use a... | specified, the default credential search order is used. If a role |
Predict the next line for this snippet: <|code_start|>
class Type (Item):
template = 'out/type.sql'
directory = 'types'
<|code_end|>
with the help of current file imports:
from pg_export.pg_items.item import Item
from pg_export.acl import acl_to_grants
and context from other files:
# Path: pg_export/pg_it... | def __init__(self, src, version): |
Given snippet: <|code_start|>
class Function (Item):
template = 'out/function.sql'
template_signature = 'out/_signature.sql'
directory = 'functions'
def __init__(self, src, version):
super(Function, self).__init__(src, version)
self.with_out_args = any(True
... | if a['name'])) |
Given the following code snippet before the placeholder: <|code_start|>
class Function (Item):
template = 'out/function.sql'
template_signature = 'out/_signature.sql'
directory = 'functions'
def __init__(self, src, version):
super(Function, self).__init__(src, version)
self.with_out_a... | for a in self.arguments |
Next line prediction: <|code_start|>
class View (Item):
template = 'out/view.sql'
directory = 'views'
def __init__(self, src, version):
super(View, self).__init__(src, version)
self.grants = acl_to_grants(self.acl, 'table', self.full_name)
self.query = self.query[:-1] # drop ";"
... | 'column', |
Next line prediction: <|code_start|># -*- coding:utf-8 -*-
class Renderer:
def __init__(self, fork, version):
base_path = os.path.join(os.path.dirname(__file__), 'templates')
path = [fork + '.'.join(version)]
for i in reversed(range(1, len(version))):
<|code_end|>
. Use current file impo... | path.append(fork + '.'.join(version[:i] + ('x',))) |
Continue the code snippet: <|code_start|> def __init__(self, fork, version):
base_path = os.path.join(os.path.dirname(__file__), 'templates')
path = [fork + '.'.join(version)]
for i in reversed(range(1, len(version))):
path.append(fork + '.'.join(version[:i] + ('x',)))
p... | return path.replace('\\', '/') |
Given the code snippet: <|code_start|> if not any(os.path.isdir(p) for p in path):
raise Exception('Version not suported: template not found:\n' +
'\n'.join(path))
path.append(os.path.join(base_path, 'base'))
self.env = Environment(
loader=Fil... | return res |
Here is a snippet: <|code_start|> self.join_path(os.path.dirname(__file__), 'templates', p)
for p in path]))
self.env.filters['untype_default'] = untype_default
self.env.filters['ljust'] = ljust
self.env.filters['rjust'] = rjust
self.env.filters['join_attr... | self.render(template_name, context).encode('utf8')) |
Predict the next line after this snippet: <|code_start|>
path = [fork + '.'.join(version)]
for i in reversed(range(1, len(version))):
path.append(fork + '.'.join(version[:i] + ('x',)))
path = [os.path.join(base_path, p) for p in path]
if not any(os.path.isdir(p) for p in pa... | def render(self, template_name, context): |
Given the code snippet: <|code_start|>
class Server (Item):
template = 'out/server.sql'
directory = 'servers'
schema = '.'
<|code_end|>
, generate the next line using the imports in this file:
from pg_export.pg_items.item import Item
from pg_export.acl import acl_to_grants
and context (functions, classe... | def __init__(self, src, version): |
Using the snippet: <|code_start|>
class Server (Item):
template = 'out/server.sql'
directory = 'servers'
schema = '.'
def __init__(self, src, version):
<|code_end|>
, determine the next line of code. You have imports:
from pg_export.pg_items.item import Item
from pg_export.acl import acl_to_grants
a... | super(Server, self).__init__(src, version) |
Here is a snippet: <|code_start|>
class Table (Item):
template = 'out/table.sql'
directory = 'tables'
def __init__(self, src, version):
super(Table, self).__init__(src, version)
self.primary_key = self.get_constraints('p')
self.primary_key = self.primary_key and self.primary_key[0... | self.inherits = [] |
Continue the code snippet: <|code_start|>
class Table (Item):
template = 'out/table.sql'
directory = 'tables'
def __init__(self, src, version):
super(Table, self).__init__(src, version)
self.primary_key = self.get_constraints('p')
<|code_end|>
. Use current file imports:
from pg_export.p... | self.primary_key = self.primary_key and self.primary_key[0] or None |
Based on the snippet: <|code_start|>
class Table (Item):
template = 'out/table.sql'
directory = 'tables'
def __init__(self, src, version):
super(Table, self).__init__(src, version)
self.primary_key = self.get_constraints('p')
self.primary_key = self.primary_key and self.primary_ke... | self.exclusions = self.get_constraints('x') |
Using the snippet: <|code_start|>
class Operator (Item):
template = 'out/operator.sql'
directory = 'operators'
<|code_end|>
, determine the next line of code. You have imports:
from pg_export.pg_items.item import Item
and context (class names, function names, or code) available:
# Path: pg_export/pg_items/... | def dump(self, root): |
Given snippet: <|code_start|>
def main():
arg_parser = argparse.ArgumentParser(
description='Export structure of databese to object '
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import shutil
import argparse
import psycopg2
from pg_export.extractor import ... | 'files for control version system', |
Given the code snippet: <|code_start|>
class Schema (Item):
template = 'out/schema.sql'
directory = ''
<|code_end|>
, generate the next line using the imports in this file:
from pg_export.pg_items.item import Item
from pg_export.acl import acl_to_grants
and context (functions, classes, or occasionally code)... | def __init__(self, src, version): |
Continue the code snippet: <|code_start|>
class Schema (Item):
template = 'out/schema.sql'
directory = ''
def __init__(self, src, version):
super(Schema, self).__init__(src, version)
<|code_end|>
. Use current file imports:
from pg_export.pg_items.item import Item
from pg_export.acl import acl_to... | self.schema = self.name |
Given the code snippet: <|code_start|>
class Cast (Item):
template = 'out/cast.sql'
directory = 'casts'
schema = '.'
<|code_end|>
, generate the next line using the imports in this file:
from pg_export.pg_items.item import Item
and context (functions, classes, or occasionally code) from other files:
# ... | def __init__(self, src, version): |
Using the snippet: <|code_start|>
class Extension (Item):
template = 'out/extension.sql'
directory = 'extensions'
<|code_end|>
, determine the next line of code. You have imports:
from pg_export.pg_items.item import Item
and context (class names, function names, or code) available:
# Path: pg_export/pg_item... | schema = '.' |
Based on the snippet: <|code_start|>
class Aggregate (Function):
template = 'out/aggregate.sql'
directory = 'aggregates'
columns = []
returns_type = None
returns_type_name = ''
language = 'sql'
<|code_end|>
, predict the immediate next line with the help of imports:
from pg_export.pg_items.fun... | kind = 'a' |
Given the following code snippet before the placeholder: <|code_start|> target_cmd = 'ls'
timeout_secs = 3
self.assertEqual((['testdata/sync/fuzz000/fuzzer_stats'], []),
afl_vcrash.verify_samples(num_threads, samples, target_cmd, timeout_secs))
# test for timeou... | self.assertEqual(2, se.exception.code) |
Continue the code snippet: <|code_start|> 'fuzzers': len(sum_stats),
'fuzzer_pid': 0,
'execs_done': 0,
'execs_per_sec': 0,
'paths_total': 0,
'paths_favored': 0,
'pending_favs': 0,
'pending_total': 0,
'unique_crash... | ds_alive = "" |
Given the following code snippet before the placeholder: <|code_start|> if not os.path.isdir(fuzzer_dir):
print_warn("Invalid fuzzing directory specified: " + clr.GRA + "%s" % fuzzer_dir + clr.RST)
return None
fuzzer_stats = []
if os.path.isfile(os.path.join(fuzzer_dir, "fuzzer_stats")):
... | 'execs_per_sec': 0, |
Using the snippet: <|code_start|> stats[k] = l[19:].strip(": %\r\n")
return stats
except FileNotFoundError as e:
print_warn("Stat file " + clr.GRA + "%s" % e.filename + clr.RST + " not found!")
return None
def load_stats(fuzzer_dir, summary=True):
fuzzer_dir = os.p... | stats = parse_stat_file(stat_file, summary) |
Using the snippet: <|code_start|> if not database.dataset_exists(table, fuzzer, ['last_update', 'afl_banner']):
database.insert_dataset(table, fuzzer)
def fetch_stats(config_settings, twitter_inst):
stat_dict = dict()
for fuzzer in config_settings['fuzz_dirs']:
stats = load_... | tweet = prettify_stat(sum_stats, stat_change, False) |
Predict the next line for this snippet: <|code_start|> table = 'aflutils_fuzzerstats'
database.init_database(table, db_table_spec)
if not database.dataset_exists(table, fuzzer, ['last_update', 'afl_banner']):
database.insert_dataset(table, fuzzer)
def fetch_stats(con... | print(prettify_stat(sum_stats, stat_change, True)) |
Using the snippet: <|code_start|> self.assertIsNone(afl_minimize.main(argv))
argv = ['afl-minimize', '-c', collection_dir, 'testdata/sync', '--', '/bin/echo']
self.assertIsNone(afl_minimize.main(argv))
argv = ['afl-minimize', '-c', collection_new, 'testdata/sync', '--', '/bin/echo']
... | argv = ['afl-minimize', '--dry-run', 'testdata/sync', '--', '/bin/echo'] |
Using the snippet: <|code_start|>
class SampleIndexTestCase(unittest.TestCase):
def setUp(self):
# Use to set up test environment prior to test case
# invocation
pass
def tearDown(self):
# Use for clean up after tests have run
pass
def prepare_SampleIndex(self):
... | test_fuzzers = ['fuzz01', 'fuzz02', 'fuzz03'] |
Here is a snippet: <|code_start|> self.assertTrue(afl_multicore.has_master(conf_settings, 11))
# negative test
self.assertFalse(afl_multicore.has_master(conf_settings, 12))
conf_settings = {
'session': 'fuzz',
'output': 'testdata/sync',
'master_instan... | self.assertEqual(1, se.exception.code) |
Based on the snippet: <|code_start|>
try:
except ImportError:
test_conf_settings = {
'twitter_creds_file': '.afl-stats.creds',
'twitter_consumer_key': 'your_consumer_key_here',
'twitter_consumer_secret': 'your_consumer_secret_here',
'fuzz_dirs': [
'/path/to/fuzz/dir/0',
'/path/to/fuzz/d... | 'fuzzer_pid': 0, |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
test_conf_settings = {
'twitter_creds_file': '.afl-stats.creds',
'twitter_consumer_key': 'your_consumer_key_here',
'twitter_consumer_secret': 'your_consumer_secret_here',
'fuzz_dirs': [
'/path/to/fuzz/dir/0',
... | 'fuzzer_pid': 0, |
Using the snippet: <|code_start|> pass
def tearDown(self):
# Use for clean up after tests have run
pass
def setup_testprocess(self, session):
# spawn dummy process in a new process group
new_proc = subprocess.Popen(['setsid', 'setsid', 'python', 'testdata/dummy_process/d... | def test_main(self): |
Here is a snippet: <|code_start|> ('fuzz001', ['queue'])
]
sync_dir = os.path.abspath('testdata/sync')
self.assertListEqual(fuzzer_inst, sorted(afl_collect.get_queue_directories(sync_dir, fuzzer_inst)))
def test_get_samples_from_dir(self):
sample_dir = 'testdata/queue'
... | sync_dir = 'testdata/sync' |
Predict the next line for this snippet: <|code_start|> self.assertDictEqual(config, cron.config)
def test_get_module(self):
module_path = 'afl_utils.afl_sync'
module = afl_sync
cron = AflCronDaemon(g_config_file)
self.assertEqual(module, cron.get_module(module_path))
... | cron.get_member(module, 'invalid_class') |
Predict the next line after this snippet: <|code_start|>
g_config_file = 'config/afl-cron.conf.sample'
class AflSyncTestCase(unittest.TestCase):
def setUp(self):
# Use to set up test environment prior to test case
# invocation
pass
def tearDown(self):
# Use for clean up after ... | os.remove(file) |
Here is a snippet: <|code_start|>
def tearDown(self):
# Use for clean up after tests have run
pass
def clean_remove(self, file):
if os.path.exists(file):
os.remove(file)
def clean_remove_dir(self, dir):
if os.path.exists(dir):
shutil.rmtree(dir)
... | def test_get_module(self): |
Given snippet: <|code_start|>
transforms = game_object_utils.get_game_object_positions_from_map(
ascii_map, 'W')
self.assertSameElements(
[
# Top walls
get_transform(0, 0, game_object_utils.Orientation.NORTH),
get_transform(1, 0, game_object_utils.Orientation.... | W A W |
Here is a snippet: <|code_start|>
#: Pattern that matches both SubStation and SubRip timestamps.
TIMESTAMP = re.compile(r"(\d{1,2}):(\d{2}):(\d{2})[.,](\d{2,3})")
Times = namedtuple("Times", ["h", "m", "s", "ms"])
def make_time(h: IntOrFloat=0, m: IntOrFloat=0, s: IntOrFloat=0, ms: IntOrFloat=0,
<|code_end|>
. Wr... | frames: Optional[int]=None, fps: Optional[float]=None): |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
try:
except ImportError:
setup(
name = "pysubs2",
packages = ["pysubs2"],
version = VERSION,
author = "Tomas Karabela",
<|code_end|>
with the help of current file imports:
from setuptools import setup
from distutils.... | author_email = "tkarabela@seznam.cz", |
Given the following code snippet before the placeholder: <|code_start|>
def test_repr_plain():
ev = SSAStyle(fontname="Calibri", fontsize=36)
ref = "<SSAStyle 36px 'Calibri'>"
assert repr(ev) == ref
def test_repr_italic():
ev = SSAStyle(fontname="Calibri", fontsize=36, italic=True)
ref = "<SSAStyl... | with pytest.warns(DeprecationWarning): |
Next line prediction: <|code_start|>
Classes = CollectorGroup()
@Classes.fragments.fragment
class WarpAnchorFragment(BaseConstructFragment):
base_container = Section.base(Magic[2], 0x6e)
container_versions = 18
<|code_end|>
. Use current file imports:
(from construct import Enum
from distance.bytes impo... | is_interesting = True |
Continue the code snippet: <|code_start|>
Classes = CollectorGroup()
@Classes.fragments.fragment
class WarpAnchorFragment(BaseConstructFragment):
base_container = Section.base(Magic[2], 0x6e)
container_versions = 18
<|code_end|>
. Use current file imports:
from construct import Enum
from distance.bytes ... | is_interesting = True |
Predict the next line for this snippet: <|code_start|>
def mkargs(maxrecurse=-1, type=[], numbers=[], section=[],
print_=False, invert=False):
return Namespace(**locals())
class RemoveTest(unittest.TestCase):
<|code_end|>
with the help of current file imports:
from argparse import Namespace
from d... | def test_by_type(self): |
Predict the next line after this snippet: <|code_start|>
class SplitArgsTest(unittest.TestCase):
def test_empty(self):
self.assertEqual([], make_arglist(""))
def test_single(self):
self.assertEqual([":all"], make_arglist("all"))
def test_value(self):
self.assertEqual([":num=2"],... | def test_escape(self): |
Given snippet: <|code_start|>
class DstBytesTest(unittest.TestCase):
def test_from_arg_dstbytes(self):
with open("tests/in/customobject/2cubes.bytes", 'rb') as f:
dbytes = DstBytes(f)
res = DstBytes.from_arg(dbytes)
self.assertIs(dbytes, res)
<|code_end|>
, continue... | def test_from_arg_filename(self): |
Given the code snippet: <|code_start|> self.assertIs(dbytes, res)
def test_from_arg_filename(self):
res = DstBytes.from_arg("tests/in/customobject/2cubes.bytes")
self.assertEqual(Magic[6], res.read_uint())
def test_from_arg_file(self):
with open("tests/in/customobject/2cube... | self.assertEqual(sec.name, None) |
Here is a snippet: <|code_start|> with p.tree_children():
p.tree_next_child()
p(f"First")
p.tree_next_child()
with p.tree_children():
p.tree_next_child()
p(f"Second")
p(f"Third")
self.assertResult("""
Root... | └─ Second |
Given snippet: <|code_start|> p(f"First")
p.tree_next_child()
with p.tree_children():
p.tree_next_child()
p(f"Second")
with p.tree_children():
p.tree_next_child()
self.assertResult("""
Root
└─ ... | ├─ First |
Predict the next line for this snippet: <|code_start|>
class LazySequenceTest(unittest.TestCase):
def test_empty(self):
self.assertRaises(IndexError, LazySequence([], 0).__getitem__, 0)
class LazySequenceIndexTest(unittest.TestCase):
def setUp(self):
self.orig = [10, 11, 12, 13, 14]
... | with self.subTest(index=index): |
Given the code snippet: <|code_start|>
class LazySequenceTest(unittest.TestCase):
def test_empty(self):
self.assertRaises(IndexError, LazySequence([], 0).__getitem__, 0)
class LazySequenceIndexTest(unittest.TestCase):
def setUp(self):
self.orig = [10, 11, 12, 13, 14]
self.iter = it... | self.assertEqual(self.orig.__getitem__(index), |
Predict the next line after this snippet: <|code_start|>class Base(object):
class WriteReadTest(common.WriteReadTest):
read_obj = Level
class StraightroadTest(Base.WriteReadTest):
filename = "tests/in/level/test-straightroad.bytes"
def verify_obj(self, level):
self.assertEqual("Test-s... | filename = "tests/in/level/test straightroad v26 author.bytes" |
Given snippet: <|code_start|>
"""Converts the given vetices representing a right triangle to a
transform for a WedgeGS GoldenSimple."""
pr, pa, pb = verts
rot = rangle_to_vers(pa - pr, pb - pr)
pos = (pa + pb) / 2
scale = [1e-5, length(pr - pb) / SIMPLE_SIZE, length(pr - pa) / SIMPLE_SIZE]
... | objs.append(_mkwedge(transform=transform, **simple_args)) |
Given snippet: <|code_start|>
def mkargs(maxrecurse=-1, collision=True, color=True, debug=False):
return Namespace(**locals())
class UnkillTest(unittest.TestCase):
def test_replace(self):
l = Level("tests/in/level/finite grids.bytes")
f = UnkillFilter(mkargs())
f.apply(l)
... | self.assertFalse(any('Kill' in t for t in types)) |
Predict the next line for this snippet: <|code_start|>
Classes = CollectorGroup()
@Classes.fragments.fragment
class SetAbilitiesTriggerFragment(BaseConstructFragment):
base_container = Section.base(Magic[2], 0xad)
<|code_end|>
with the help of current file imports:
from distance.bytes import Section, Magic
... | container_versions = 7 |
Based on the snippet: <|code_start|> for key, value in page.items():
setattr(self, key, value)
self.md_content = self.content
self.content = markdown(self.content)
return None
def attached_files(self):
files = query_db('SELECT id FROM uploads WHERE wiki_id = ?', [self.id])
if files == None:
retur... | def __str__(self): |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#taken from Pegasos algorithm by avaitla
def SGD(a, lab, Q, lr):
for i in range(20):
iterations = 1
for tau in range(len(a)):
if a[tau] > 0:
wx = a @ Q[:,tau]
a[tau] *= (1 ... | for i in range(5): |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#taken from Pegasos algorithm by avaitla
def SGD(a, lab, Q, lr):
for i in range(20):
iterations = 1
for tau in range(len(a)):
if a[tau] > 0:
wx = a @ Q[:,tau]
a[tau] *= (1 ... | a[tau] -= ql |
Given snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#taken from Pegasos algorithm by avaitla
def SGD(a, lab, Q, lr):
for i in range(20):
iterations = 1
for tau in range(len(a)):
if a[tau] > 0:
wx = a @ Q[:,tau]
a[tau] *= (1 - 1/ite... | iterations += 1 |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#taken from Pegasos algorithm by avaitla
def SGD(a, lab, Q, lr):
for i in range(20):
iterations = 1
for tau in range(len(a)):
if a[tau] > 0:
wx = a @ Q[:,tau]
a[tau] *= (... | s_max = 1.5 |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#taken from Pegasos algorithm by avaitla
def SGD(a, lab, Q, lr):
for i in range(20):
iterations = 1
for tau in range(len(a)):
if a[tau] > 0:
wx = a @ Q[:,tau]
a[tau] *= (1 ... | return a |
Given snippet: <|code_start|>#hiss removal (a noise reduction algorithm working on signal samples to reduce its hissings)
def hiss_removal(audio):
pend = len(audio)-(4410+1102)
song = sonify(audio, 44100)
song.FrameGenerator().__next__()
song.window()
song.Spectrum()
noise_fft = song.fft(song... | song.AttackTime() |
Given the code snippet: <|code_start|> h_sig_L = lfilter(left.flatten(), 1., audio)
h_sig_R = lfilter(right.flatten(), 1., audio)
del hissless
result = np.float32([h_sig_L, h_sig_R]).T
neg_angle = re... | print(( "Rewriting without silence in %s"%f )) |
Based on the snippet: <|code_start|> del hissless
result = np.float32([h_sig_L, h_sig_R]).T
neg_angle = result[:,(1,0)]
panned = result + neg_angle
normalized = normalize(panned)
del normalized ... | loud_audio = np.delete(without_rumble, np.where(db_mag < silence_threshold))#remove it |
Given the following code snippet before the placeholder: <|code_start|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def get_desc_pair(descriptors, files_features, keys):
print(np.vstack((descriptors,keys)).T)
input1 = input("Key of ... | def plot_similarity_clusters(desc1, desc2, files, plot = None): |
Given the code snippet: <|code_start|>
def attention_sga(x,y,a=None):
if a == None:
a = np.zeros(x.shape[1])
else:
<|code_end|>
, generate the next line using the imports in this file:
from .subproblem import s, sigmoid, attention
import numpy as np
and context (functions, classes, or occasionally cod... | a = np.resize(a,x.shape[1]) |
Using the snippet: <|code_start|>
def attention_sga(x,y,a=None):
if a == None:
a = np.zeros(x.shape[1])
else:
a = np.resize(a,x.shape[1])
for i in range(5):
for tau in range(x.shape[1]):
gh = abs(1-np.min(attention(np.mat(x),np.mat(y),a[tau]))) * np.gradient(x.T*a... | ql =(s_max * np.abs(np.cosh(s1 * et)+1)) / (s1*np.abs(np.cosh(s1 * et)+1)) |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
ext_filter = ['.mp3','.ogg','.wav','.wma', '.amr'] # check if all extensions are supported by the library
#ext_filter = ['.mp3','.ogg','.undefined','.wav'... | 'metadata.duration', |
Here is a snippet: <|code_start|>
def auth_url(regex, view, *args, **kwargs):
return url(regex, login_required(view), *args, **kwargs)
urlpatterns = [
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.contri... | url(r'^grappelli/', include('grappelli.urls')), |
Given the following code snippet before the placeholder: <|code_start|>
def auth_url(regex, view, *args, **kwargs):
return url(regex, login_required(view), *args, **kwargs)
urlpatterns = [
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url, include
from d... | url(r'^grappelli/', include('grappelli.urls')), |
Predict the next line for this snippet: <|code_start|>
def auth_url(regex, view, *args, **kwargs):
return url(regex, login_required(view), *args, **kwargs)
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
<|code_end|>
with the help of current file imports:
from django.conf.urls import url, ... | url(r'^admin/', admin.site.urls), |
Given the following code snippet before the placeholder: <|code_start|>
def auth_url(regex, view, *args, **kwargs):
return url(regex, login_required(view), *args, **kwargs)
urlpatterns = [
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url, include
from d... | url(r'^grappelli/', include('grappelli.urls')), |
Based on the snippet: <|code_start|>
def auth_url(regex, view, *args, **kwargs):
return url(regex, login_required(view), *args, **kwargs)
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url... | url(r'^admin/', admin.site.urls), |
Next line prediction: <|code_start|>
class NetworkInterfaceInline(admin.TabularInline):
model = NetworkInterface
extra = 0
readonly_fields = ('network', 'minion', 'ip_address', 'mac_address', 'name')
def has_add_permission(self, request):
return False
def has_delete_permission(self, requ... | readonly_fields = ('fqdn', 'data', 'last_updated') |
Continue the code snippet: <|code_start|>
class NetworkInterfaceInline(admin.TabularInline):
model = NetworkInterface
extra = 0
readonly_fields = ('network', 'minion', 'ip_address', 'mac_address', 'name')
def has_add_permission(self, request):
return False
def has_delete_permission(self,... | readonly_fields = ('fqdn', 'data', 'last_updated') |
Using the snippet: <|code_start|>
class NetworkInterfaceInline(admin.TabularInline):
model = NetworkInterface
extra = 0
readonly_fields = ('network', 'minion', 'ip_address', 'mac_address', 'name')
def has_add_permission(self, request):
return False
def has_delete_permission(self, request... | readonly_fields = ('ipv4', 'mask', 'last_updated') |
Predict the next line after this snippet: <|code_start|>
class MarkdownFormMixin(forms.ModelForm):
md_content = forms.CharField(
widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 15, 'autofocus': 'True', 'placeholder': '# Some Markdown'}),
label='',
required=False
)
... | class Meta: |
Next line prediction: <|code_start|> Div(StrictButton('Save', type='submit', css_class='btn-primary'))
)
class Meta:
abstract = True
fields = ['md_content']
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... | PrependedText('password', '<i class="fa fa-unlock-alt fa-fw"></i>', placeholder='Password'), |
Based on the snippet: <|code_start|>
class MarkdownFormMixin(forms.ModelForm):
md_content = forms.CharField(
widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 15, 'autofocus': 'True', 'placeholder': '# Some Markdown'}),
label='',
required=False
)
def __init__(self, *... | abstract = True |
Using the snippet: <|code_start|> while self.pc < len(self.code):
op = self.code[self.pc]
if type(op) == ops.BinaryAdd:
x = self.stack.pop()
y = self.stack.pop()
v = obj.LNumber(y.value + x.value)
self.stack.append(v)
... | self.stack.append(value) |
Using the snippet: <|code_start|> v = obj.LNumber(y.value + x.value)
self.stack.append(v)
elif type(op) == ops.BinarySubtract:
x = self.stack.pop()
y = self.stack.pop()
v = obj.LNumber(y.value - x.value)
self.sta... | val = self.env[val] |
Here is a snippet: <|code_start|> obj.LVar('a'),
]
def test_arith1(compile_expr):
frame = compile_expr('1 - 2')
assert frame.code == [
ops.LoadConst(0),
ops.LoadConst(1),
ops.BinarySubtract(),
]
assert frame.consts == [
obj.LNumber(1.0),
obj.LNumber(... | def test_arith3(compile_expr): |
Given the following code snippet before the placeholder: <|code_start|>
def test_ass1(compile_stmt):
frame = compile_stmt('a = 1')
assert frame.code == [
ops.LoadConst(0),
ops.StoreName(0),
]
assert frame.consts == [
obj.LNumber(1.0),
]
<|code_end|>
, predict the next line ... | assert frame.vars == [ |
Given the code snippet: <|code_start|>
def lua_print(luavalue):
pyvalue = 'nil'
if type(luavalue) == obj.LString:
pyvalue = luavalue.value
elif type(luavalue) == obj.LNumber:
pyvalue = luavalue.value
<|code_end|>
, generate the next line using the imports in this file:
from luna import o... | if int(pyvalue) == pyvalue: |
Continue the code snippet: <|code_start|> ops.LoadConst(1),
ops.StoreName(),
]
assert frame.consts == [
obj.LVar('a'),
obj.LNumber(1.0),
]
def test_binop1(compile_expr):
frame = compile_expr('1 + 2')
assert frame.code == [
ops.LoadConst(0),
ops.LoadC... | ] |
Here is a snippet: <|code_start|>
def test_ass1(compile_stmt):
frame = compile_stmt('a = 1')
assert frame.code == [
ops.LoadConst(0),
ops.LoadConst(1),
ops.StoreName(),
]
assert frame.consts == [
obj.LVar('a'),
obj.LNumber(1.0),
<|code_end|>
. Write the next lin... | ] |
Using the snippet: <|code_start|>
def test_ass1(interp_stmt):
frame = interp_stmt('a = 1')
assert frame.env == {
obj.LVar('a'): obj.LNumber(1.0),
<|code_end|>
, determine the next line of code. You have imports:
from luna import objects as obj
and context (class names, function names, or code) availa... | } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.