Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> m = self.counts
score = sum(gammaln(a[k] + m[k]) - gammaln(a[k]) for k in xrange(dim))
score += gammaln(a.sum())
score -= gammaln(a.sum() + m.sum())
return score
def sample_value(self, shared):
sampler = Sampler()
sampler.init(sh... | self.ps = sample_dirichlet(shared.alphas) |
Based on the snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT ... | probs = scores_to_probs(scores) |
Given the code snippet: <|code_start|>
# create a new partition
large_shape = (1,) + small_shape
prob += large_probs[large_shape] / large_counts[large_shape]
# add to each existing partition
for i in xrange(len(small_shape)):
large_shape = list(small_shape)
... | flat = json_stream_load(cache_file) |
Continue the code snippet: <|code_start|> large_shape.sort()
large_shape = tuple(large_shape)
prob += large_probs[large_shape] / large_counts[large_shape]
small_probs[small_shape] = count * prob
return small_probs
def get_counts(size):
'''
Count partition shapes... | json_stream_dump(large.iteritems(), cache_file) |
Given the following code snippet before the placeholder: <|code_start|> def dump(self):
return {
'alpha': self.alpha,
'inv_beta': self.inv_beta,
}
def protobuf_load(self, message):
self.alpha = float(message.alpha)
self.inv_beta = float(message.inv_beta)
... | self.log_prod += log(factorial(value)) |
Predict the next line after this snippet: <|code_start|> def dump(self):
return {
'alpha': self.alpha,
'inv_beta': self.inv_beta,
}
def protobuf_load(self, message):
self.alpha = float(message.alpha)
self.inv_beta = float(message.inv_beta)
def protobu... | self.log_prod += log(factorial(value)) |
Given the following code snippet before the placeholder: <|code_start|> self.sum = None
self.log_prod = None
def init(self, shared):
self.count = 0
self.sum = 0
self.log_prod = 0.
def add_value(self, shared, value):
self.count += 1
self.sum += int(value)
... | return gammaln(post.alpha + value) - gammaln(post.alpha) \ |
Given the code snippet: <|code_start|> sampler = Sampler()
sampler.init(shared, self)
return sampler.eval(shared)
def load(self, raw):
self.count = int(raw['count'])
self.sum = int(raw['sum'])
self.log_prod = float(raw['log_prod'])
def dump(self):
return ... | self.lambda_ = sample_gamma(post.alpha, 1.0 / post.inv_beta) |
Given the code snippet: <|code_start|>
def load(self, raw):
self.count = int(raw['count'])
self.sum = int(raw['sum'])
self.log_prod = float(raw['log_prod'])
def dump(self):
return {
'count': self.count,
'sum': self.sum,
'log_prod': self.log_pr... | return sample_poisson(self.lambda_) |
Given the following code snippet before the placeholder: <|code_start|># - Neither the name of Salesforce.com nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ... | assert_all_close([m.NAME for m in modules], err_msg='Model.__name__') |
Given snippet: <|code_start|>#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentat... | for spec in list_models(): |
Continue the code snippet: <|code_start|>@parsable.command
def flavors_by_model():
'''
List flavors implemented of each model.
'''
models = defaultdict(lambda: [])
for spec in list_models():
models[spec['name']].append(spec['flavor'])
for model in sorted(models):
print 'model {}:... | Model = import_model(spec).Model |
Given the code snippet: <|code_start|> assert value in shared.betas, 'unknown value: {}'.format(value)
if count:
self.total += count
try:
count += self.counts[value]
if count:
self.counts[value] = count
else:
... | return log(numer / denom) |
Given the following code snippet before the placeholder: <|code_start|>
def add_value(self, shared, value):
self.add_repeated_value(shared, value, 1)
def remove_value(self, shared, value):
self.add_repeated_value(shared, value, -1)
def score_value(self, shared, value):
"""
... | score += gammaln(prior_i + count) - gammaln(prior_i) |
Given snippet: <|code_start|> self.counts = {}
self.total = 0
for i, count in izip(message.keys, message.values):
if count:
self.counts[int(i)] = int(count)
self.total += count
def protobuf_dump(self, message):
message.Clear()
for i... | index = sample_discrete(self.probs) |
Predict the next line after this snippet: <|code_start|> return {'counts': counts}
def protobuf_load(self, message):
self.counts = {}
self.total = 0
for i, count in izip(message.keys, message.values):
if count:
self.counts[int(i)] = int(count)
... | self.probs = sample_dirichlet(post) |
Using the snippet: <|code_start|>
def protobuf_load(self, message):
assert len(message.betas) == len(message.values), "invalid message"
assert len(message.counts) == len(message.values), "invalid message"
self.gamma = float(message.gamma)
self.alpha = float(message.alpha)
sel... | beta = self.beta0 * sample_beta(1.0, self.gamma) |
Given the following code snippet before the placeholder: <|code_start|> self.sum_xxT = np.zeros((shared.dim(), shared.dim()))
def add_value(self, shared, value):
self.count += 1
self.sum_x += value
self.sum_xxT += np.outer(value, value)
def add_repeated_value(self, shared, value... | return score_student_t(value, dof, mu_n, sigma_n) |
Predict the next line after this snippet: <|code_start|> assert self.sum_xxT.shape == (D, D)
def dump(self):
return {
'count': self.count,
'sum_x': self.sum_x.copy(),
'sum_xxT': self.sum_xxT.copy(),
}
def protobuf_load(self, message):
self.cou... | self.mu, self.sigma = sample_normal_inverse_wishart( |
Using the snippet: <|code_start|> counts[sample] += 1
probs[sample] += prob
for key, count in counts.iteritems():
probs[key] /= count
total_prob = sum(probs.itervalues())
assert_close(total_prob, 1.0, tol=1e-2, err_msg='total_prob is biased')
return counts, probs
def assert_co... | gof = multinomial_goodness_of_fit(probs, counts, total_count) |
Predict the next line for this snippet: <|code_start|>
def _test_normals(nich, niw):
mu = np.array([30.0])
kappa = 0.3
psi = np.array([[2.]])
nu = 3
# make the NIW case
niw_shared = niw.Shared()
niw_shared.load({'mu': mu, 'kappa': kappa, 'psi': psi, 'nu': nu})
niw_group = niw.Group()
... | assert_close(niw_group.score_data(niw_shared), |
Continue the code snippet: <|code_start|>
class Group(GroupIoMixin):
def __init__(self):
self.count = None
self.sum = None
def init(self, shared):
self.count = 0
self.sum = 0
def add_value(self, shared, value):
self.count += 1
self.sum += int(value)
def... | score = gammaln(post.alpha + post.beta) |
Continue the code snippet: <|code_start|> score += gammaln(post.beta) - gammaln(shared.beta)
return score
def sample_value(self, shared):
sampler = Sampler()
sampler.init(shared, self)
return sampler.eval(shared)
def dump(self):
return {
'count': self... | self.p = sample_beta(post.alpha, post.beta) |
Predict the next line after this snippet: <|code_start|> def sample_value(self, shared):
sampler = Sampler()
sampler.init(shared, self)
return sampler.eval(shared)
def dump(self):
return {
'count': self.count,
'sum': self.sum,
}
def load(self,... | return sample_negative_binomial(self.p, shared.r) |
Next line prediction: <|code_start|>"""Setup Celery."""
_logger = logging.getLogger(__name__)
def _use_sqs():
"""Check if worker should use Amazon SQS.
:return: True if worker should use Amazon SQS
"""
<|code_end|>
. Use current file imports:
(import os
import logging
from urllib.parse import quote
fr... | has_key_id = configuration.AWS_SQS_ACCESS_KEY_ID is not None |
Based on the snippet: <|code_start|>"""Git Operations Task."""
_dir_path = "/tmp/clonedRepos"
worker_count = int(os.getenv('FUTURES_SESSION_WORKER_COUNT', '100'))
_session = FuturesSession(max_workers=worker_count)
F8_API_BACKBONE_HOST = os.getenv('F8_API_BACKBONE_HOST', 'http://f8a-server-backbone:5000')
GEMINI_SER... | class GitOperationTask(BaseTask): |
Given snippet: <|code_start|>
@pytest.mark.parametrize('data, expected', [
({'pom.xml': {'dependencies': {'compile': {'g:a::': '1.0'}}}},
{'dependencies': ['g:a 1.0']}),
({'pom.xml': {'dependencies': {'runtime': {'g:a::': '1.0'}}}},
{'dependencies': ['g:a 1.0']}),
({'pom.xml': {'dependencies': {'... | transformed_data = MavenDataNormalizer(data).normalize() |
Continue the code snippet: <|code_start|>"""Tests for NewInitPackageFlow module."""
data_v1 = {
"ecosystem": "dummy_eco",
"name": "dummy_name"
}
data_v2 = {
"ecosystem": "golang",
"name": "dummy_name"
}
class TestInitPackageFlowNew(TestCase):
"""Tests for the NewInitPackageFlow... | self.assertRaises(FatalTaskError, NewInitPackageAnlysisFlow.execute, self, data_v1) |
Next line prediction: <|code_start|>assert fieldGreaterEqual
assert fieldInt
assert fieldLenEqual
assert fieldLenGreater
assert fieldLenGreaterEqual
assert fieldLenLess
assert fieldLenNotEqual
assert fieldLess
assert fieldLessEqual
assert fieldList
assert fieldNone
assert fieldNotEqual
assert fieldStr
assert fieldUrlNe... | if parse_gh_repo(val): |
Next line prediction: <|code_start|> if isinstance(name_email_dict.get(email_key), str):
if name_email_str:
name_email_str += ' '
name_email_str += '<' + name_email_dict[email_key] + '>'
return name_email_str
@staticmethod
def _rf(iterable):
"""Rem... | if parse_gh_repo(homepage): |
Using the snippet: <|code_start|> "ecosystem": "golang",
"name": "dummy_name",
"version": "dummy_version"
}
data_v3 = {
"ecosystem": "golang",
"version": "dummy_version"
}
data_v4 = {
"name": "dummy_name",
"version": "dummy_version"
}
data_v5 = {
"ecosys... | self.assertRaises(FatalTaskError, NewInitPackageFlow.execute, self, data_v1) |
Based on the snippet: <|code_start|>"""Tests covering code in start.py."""
_SQS_MSG_LIFETIME_IN_SEC = (int(os.environ.get('SQS_MSG_LIFETIME', '24')) + 1) * 60 * 60
class TestStartFunctions():
"""Test functions from start.py."""
def test_check_hung_task(self):
"""Test _check_hung_task."""
fl... | _check_hung_task(self, flow_info) |
Given the code snippet: <|code_start|> "ecosystem": "dummy_eco",
"name": "dummy_name",
"version": "dummy_version"
}
class Response:
"""Custom response class."""
status_code = 200
text = 'dummy_data'
class ErrorResponse:
"""Custom response class for error."""
status_code ... | self.assertRaises(RuntimeError, NewPackageAnalysisGraphImporterTask.execute, self, data) |
Predict the next line after this snippet: <|code_start|>
class TestNewPackageAnalysisGraphImporterTask(TestCase):
"""Tests for the NewGraphImporterTask task."""
def _strict_assert(self, assert_cond):
if not assert_cond:
False
@mock.patch('f8a_worker.workers.new_graph_importer.requests... | self.assertRaises(RuntimeError, NewPackageGraphImporterTask.execute, self, data) |
Given the code snippet: <|code_start|>"""Ingest to graph task."""
logger = logging.getLogger(__name__)
_SERVICE_HOST = environ.get("BAYESIAN_DATA_IMPORTER_SERVICE_HOST", "bayesian-data-importer")
_SERVICE_PORT = environ.get("BAYESIAN_DATA_IMPORTER_SERVICE_PORT", "9192")
_SELECTIVE_SERVICE_ENDPOINT = "api/v1/selectiv... | class NewPackageGraphImporterTask(BaseTask): |
Here is a snippet: <|code_start|> configuration.select_random_github_token.return_value = ['a', 'b']
GITHUB_API_URL = 'https://api.github.com/repos/'
GITHUB_URL = 'https://github.com/'
GITHUB_TOKEN = ''
get_response_issues = mock.Mock()
get_response_issues.return_value = {
"url": "https:/... | results = gocve.execute(self, arguments={}) |
Given the following code snippet before the placeholder: <|code_start|> "from": "normalize-registry-metadata@^1.1.2",
"resolved": "https://registry.npmjs.org/normalize-registry-metadata-1.1.2.tgz",
"dependencies": {
"semver": {
"version": "5.5.1",
... | instance = go.GitOperationTask.create_test_instance() |
Predict the next line after this snippet: <|code_start|>"""Functions for dispatcher."""
logger = logging.getLogger(__name__)
def _create_analysis_arguments(ecosystem, name, version):
"""Create arguments for analysis."""
return {
'ecosystem': ecosystem,
<|code_end|>
using the current file's import... | 'name': MavenCoordinates.normalize_str(name) if Ecosystem.by_name( |
Next line prediction: <|code_start|>"""Functions for dispatcher."""
logger = logging.getLogger(__name__)
def _create_analysis_arguments(ecosystem, name, version):
"""Create arguments for analysis."""
return {
'ecosystem': ecosystem,
<|code_end|>
. Use current file imports:
(import logging
from ur... | 'name': MavenCoordinates.normalize_str(name) if Ecosystem.by_name( |
Using the snippet: <|code_start|>"""Computes various Issues and PRS for Golang Packages repositories.
output: cve format containing PR,Issues for the a golang package/repositories
sample output:
{'status': 'success','package': '','summary': [],'details': {}}
"""
<|code_end|>
, determine the next line of code. You h... | class GitIssuesPRsTask(BaseTask): |
Next line prediction: <|code_start|>"""SQLAlchemy domain models."""
def create_db_scoped_session(connection_string=None):
"""Create scoped session."""
# we use NullPool, so that SQLAlchemy doesn't pool local connections
# and only really uses connections while writing results
return scoped_session(... | connection_string or configuration.POSTGRES_CONNECTION, |
Given snippet: <|code_start|> return None
class S3():
"""Dummy Class."""
def store_data(self, arguments, result):
"""Test Function."""
pass
class TestNewMetaDataTask(TestCase):
"""Tests for the NewInitPackageFlow task."""
def store_data_to_s3(self, arguments, s3, result)... | result = NewMetaDataTask.execute(self, data_v1) |
Given the code snippet: <|code_start|>"""Tests for Java data normalizers."""
@pytest.mark.parametrize('data,keymap,expected', [
# pick one key which IS there
({'author': 'me', 'version': '0.1.2'}, (('author',),), {'author': 'me'}),
# pick one key which IS NOT there
({'author-name': 'me', 'version': '... | dn = PythonDataNormalizer(data) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""Start the application."""
class SentryCelery(celery.Celery):
"""Celery class to configure sentry."""
def on_configure(self):
"""Set up sentry client."""
dsn = os.environ.get("SENTRY_DSN")
client = raven.Client(dsn)
re... | patch(self) |
Predict the next line for this snippet: <|code_start|> remove weird-looking errors like (un-committed changes due to errors
in init task):
DETAIL: Key (package_analysis_id)=(1113452) is not present in table "package_analyses".
"""
if task_name in ('InitPackageFlow', 'InitAnalysi... | return Ecosystem.by_name(PostgresBase.session, name) |
Given snippet: <|code_start|>#!/usr/bin/env python3
"""Basic interface to the Amazon S3 database."""
class AmazonS3(DataStorage):
"""Basic interface to the Amazon S3 database."""
_DEFAULT_REGION_NAME = 'us-east-1'
_DEFAULT_BUCKET_NAME = 'bayesian-core-unknown'
_DEFAULT_LOCAL_ENDPOINT = 'http://core... | self.region_name = configuration.AWS_S3_REGION or region_name or self._DEFAULT_REGION_NAME |
Here is a snippet: <|code_start|>"""Tests for abstract data normalizer."""
@pytest.mark.parametrize('args, expected', [
({'keywords': None},
[]),
({'keywords': []},
[]),
({'keywords': ['x', 'y']},
['x', 'y']),
({'keywords': ''},
['']),
({'keywords': 'one'},
['one']),
... | assert AbstractDataNormalizer._split_keywords(**args) == expected |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
"""Tests for the GithubTask worker task."""
@pytest.mark.usefixtures("dispatcher_setup")
class TestGithuber(object):
"""Tests for the GithubTask worker task."""
@pytest.mark.parametrize(('repo_name', 'repo_url'), [
('projectatomic/atomic-rea... | task = GithubTask.create_test_instance(repo_name, repo_url) |
Predict the next line after this snippet: <|code_start|> def stable_lhs(self):
assert not (self._stable_lhs & self._cond_lhs)
return self._stable_lhs
@property
def stable_rhs(self):
assert not (self._stable_rhs & self._cond_rhs)
return self._stable_rhs
@property
def ... | values = get_symbols(node.value) |
Given the code snippet: <|code_start|> for attr in ('starargs', 'kwargs'):
child = getattr(node, attr)
if child:
right.update(self.visit(child))
for src in left | right:
if not self.graph.has_node(src):
self.undefined.add(src)
... | get_symbols(generator, _ast.Load) |
Given the code snippet: <|code_start|> interfaces", ... }
:rtype: dict
"""
self._connect()
confs = {} # used by the threads to return the confs
threads = []
self.log = logger
args = [(confs, hn, 'firelet') for hn in self._targets ]
Forker(self._ge... | d = Bunch(iptables=iptables_p, ip_a_s=ip_a_s_p) |
Given the code snippet: <|code_start|> def __init__(self):
deb("Mocking say()...")
self.reset_history()
def __call__(self, s):
"""Append one or more lines to the history"""
self._output_history.extend(s.split('\n'))
def hist(self):
return '\n-----\n' + '\n'.join(self... | monkeypatch.setattr(cli, "say", MockSay()) |
Based on the snippet: <|code_start|> def flush(self):
self._output_history = []
@property
def output_history(self):
return self._output_history
@property
def last(self):
return self._output_history[-1]
def reset_history(self):
self._output_history = []
@pyte... | return DemoGitFireSet(repodir=repodir) |
Given the code snippet: <|code_start|> ctx = xmlsec.SignatureContext(key_mgr)
try:
ctx.verify(signode)
except xmlsec.error.Error:
validity = (ref.attrib['URI'], False)
else:
validity = (ref.attrib['URI'], True)
results.append(validity)
re... | schema_pth = resolve_schema(doc_xml) |
Here is a snippet: <|code_start|>""" SII Document Signature Verification Process Functions
"""
__all__ = [
'validate_signatures',
'validate_schema'
]
def validate_signatures(xml):
""" Validate internal Document Signatures. Public Key are provided by them, so no need for
anything else than the XML i... | xml = prepend_dtd(xml) |
Predict the next line after this snippet: <|code_start|>""" SII Document Signature Verification Process Functions
"""
__all__ = [
'validate_signatures',
'validate_schema'
]
def validate_signatures(xml):
""" Validate internal Document Signatures. Public Key are provided by them, so no need for
anyth... | signodes = extract_signodes(xml) |
Predict the next line after this snippet: <|code_start|>""" SII Document Signature Verification Process Functions
"""
__all__ = [
'validate_signatures',
'validate_schema'
]
def validate_signatures(xml):
""" Validate internal Document Signatures. Public Key are provided by them, so no need for
anyth... | cert = extract_signode_certificate(signode) |
Next line prediction: <|code_start|>""" SII Document Signature Verification Process Functions
"""
__all__ = [
'validate_signatures',
'validate_schema'
]
def validate_signatures(xml):
""" Validate internal Document Signatures. Public Key are provided by them, so no need for
anything else than the XM... | ref = extract_signode_reference(signode) |
Given the code snippet: <|code_start|> 46 : "FACTURA DE COMPRA ELECTRÓNICA",
50 : "GUÍA DE DESPACHO.",
52 : "GUÍA DE DESPACHO ELECTRÓNICA",
55 : "NOTA DE DÉBITO",
56 : "NOTA DE DÉBITO ELECTRÓNICA",
60 : "NOTA DE CRÉDITO",
61 : "NOTA DE CRÉDITO ELECTRÓNICA",
103 : "LIQUIDACI... | class SectionReferences(TemplateElement): |
Based on the snippet: <|code_start|>""" Totals Section of the Document
Contains:
* Discount
* Net Amount
* Tax exempt Amount
* Tax
* (optional) Other Tax Types
* Total
"""
SPECIAL_TAX = {
19: ('IAH', 12, '+'),
15: ('RTT', 19, '-'),
33: ('IRM', 8, '-'),
331: ('IRM', ... | class SectionTotals(TemplateElement): |
Given the code snippet: <|code_start|>""" Payments Section of the Document
Contains:
* Payment Mode/Type
* Amount
* Descriptor (Payment Detail / further Information / Description)
"""
<|code_end|>
, generate the next line using the imports in this file:
from .TemplateElement import TemplateElement
and ... | class SectionPayments(TemplateElement): |
Given snippet: <|code_start|> \\begin{mdframed}[style=emitter]
{
\\tabulinesep=_1.0mm^1.0mm
\\vspace{1mm}
\\begin{tabu}{X[-1r] X[-1l] X[-1r] X[-1l]}
\\rowfont{\\footnotesize}
\\everyrow{\\rowfont{\\footnotesize}}
\\textbf{SE... | self._receivername = escape_tex(receivername) |
Next line prediction: <|code_start|>""" Receiver Section in the Document
Contains:
* Emission Date
* Expiration Date
* Receiver Name
* Receiver RUT
* Receiver Activity (Economic Role)
* Receiver Address
* Receiver Comune
* Receiver City
* (optional)(carta/oficio only) Emitter Salesm... | class SectionReceiver(TemplateElement): |
Predict the next line for this snippet: <|code_start|>""" Company Pool to resolve Company objects from (coming from YAML)
For a Template example look into files/companies.yml at the root of the repository. Such a file can
hold more than one instances of company metadata inside, allowing for multiple companies being
ha... | self._companies[rut] = Company(data) |
Given the code snippet: <|code_start|> 'small', 'footnotesize',
self._build_headers(),
self._build_rows(),
self._build_disclaimer()
)
@property
def thermal80mm(self):
return self.__doc__ % (
'scriptsize', 'scriptsize',
self.... | cols = ['\\textbf{%s}' % escape_tex(col['name']) for col in self._colsettings] |
Predict the next line after this snippet: <|code_start|>""" Items Section of the Document
Contains:
* Header Tags
* Item Rows
"""
GUIA_DESPACHO_TYPES = {
1: "OPERACIÓN CONSTITUYE VENTA",
2: "VENTA POR EFECTUAR",
3: "CONSIGNACION",
4: "ENTREGA GRATUITA",
5: "TRASLADO INTERNO",
6: "OTR... | class SectionItems(TemplateElement): |
Continue the code snippet: <|code_start|>""" SII Document Signing Process Functions
"""
__all__ = [
'sign_document',
'sign_document_all',
'build_template'
]
def sign_document(xml, key_path, cert_path):
""" Signs topmost XML <ds:Signature> node under the document root node.
:param `etree.Element... | xml = prepend_dtd(xml) |
Based on the snippet: <|code_start|>""" SII Document Signing Process Functions
"""
__all__ = [
'sign_document',
'sign_document_all',
'build_template'
]
def sign_document(xml, key_path, cert_path):
""" Signs topmost XML <ds:Signature> node under the document root node.
:param `etree.Element` xml... | signode = extract_signode(xml) |
Given the following code snippet before the placeholder: <|code_start|> # Load Private Key and Public Certificate
key = xmlsec.Key.from_file(key_path, xmlsec.KeyFormat.PEM)
key.load_cert_from_file(cert_path, xmlsec.KeyFormat.PEM)
# Create Crypto Context and load in Key/Cert
ctx = xmlsec.Signatur... | for signode in extract_signodes(xml): |
Based on the snippet: <|code_start|>""" Static Company Data (coming from YAML)
For a Template example look into files/companies.yml at the root of the repository.
"""
class Company(object):
def __init__(self, data):
self.__dict__.update(data)
<|code_end|>
, predict the immediate next line with the help ... | self.branches = [Branch(b) for b in self.branches] |
Predict the next line after this snippet: <|code_start|>
# Add the <ds:Reference/> node to the signature template.
ref = xmlsec.template.add_reference(signode, digest_method=xmlsec.Transform.SHA1)
# Add the enveloped transform descriptor.
xmlsec.template.add_transform(ref, transform=xml... | return with_retry(lambda: self.sii_soap.service.getToken(request_xml)) |
Based on the snippet: <|code_start|>
class CAFPool(object):
def __init__(self, dirpath):
self._path = os.path.abspath(os.path.expanduser(dirpath))
self._fnames = [fname for fname in os.listdir(self._path) if os.path.splitext(fname)[-1] == ".xml"]
self._fpaths = [os.path.join(self._path, f... | dte = xml.wrap_xml(dte) |
Next line prediction: <|code_start|>""" Wrapper around CAF File.
This is currently only a proxy to an internal object from cns.lib.sii.
"""
__all__ = [
"CAFPool"
]
read_rut = lambda raw: int(raw.split('-')[0])
class CAFPool(object):
def __init__(self, dirpath):
self._path = os.path.abspath(os... | self._cafs = [CAF(tree) for tree in self._trees] |
Next line prediction: <|code_start|>""" SII Document Patch.
Contains:
* RUT
* Document Type Name
* Document Serial Number
* SII Branch
* (thermal*mm only)(optional) Logo (path to EPS)
"""
DOC_TYPE_STRINGS = {
33: "FACTURA\\break ELECTRÓNICA",
34: "FACTURA\\break NO AFECTA O EXENTA\\bre... | class SectionSiiPatch(TemplateElement): |
Predict the next line for this snippet: <|code_start|> \\begin{center}
\\large{\\textbf{R.U.T.: %s}}\\break
\\newline
\\large{\\textbf{%s}}\\break
\\newline
\\large{\\textbf{N\\textdegree\\ %s}}
\\end{center}
... | ress.append(Resource('logo.eps', self._logo_data)) |
Given snippet: <|code_start|>""" Emitter Section of the Document
Contains:
* Emitter Name (full Version)
* Emitter Activity (Economic Role)
* Emitter HQ Address String
* Emitter emitting Branch String
* (carta/oficio only) Logo (Optional) [takes the path to the logo EPS]
* (thermal*mm only) ... | class SectionEmitter(TemplateElement): |
Given snippet: <|code_start|> """
def __init__(self, emitter_name_long, emitter_name_short,
emitter_activity,
emitter_hq_addr, emitter_branch_addr, emitter_phone,
order_number='', emitter_salesman='', licence_plate='',
lo... | ress.append(Resource('logo' + ext, self._logo_data)) |
Here is a snippet: <|code_start|> raise NotImplementedError
@property
def executable(self):
""" Path to the Executable. """
raise NotImplementedError
def check(self):
""" Check if the Executable can be found and run. This is the point we have to
fail if the program c... | return which(self.name) |
Given the code snippet: <|code_start|>""" Disclaimer Section of the Document (you might want to subclass this one)
Contains:
* Company Name
* Company Rut
* Disclaimer of the Company (subclass if you want to change this)
"""
__all__ = [
'SectionDisclaimer',
'SectionDisclaimerDummy'
]
<|code_end|>... | class SectionDisclaimer(TemplateElement): |
Predict the next line after this snippet: <|code_start|>""" Creation and management of SII Digital Stamp Utilities
"""
def build_digital_stamp(doc_xml, caf_xml):
""" Builds a digital stamp digest from a DTE.
:param `etree.Element` doc_xml: DTE Document node.
:param `etree.Element` caf_xml: Codigo autor... | caf = xml.wrap_xml(caf_xml) |
Based on the snippet: <|code_start|>""" Barcode Section of the Document
Contains:
* Barcode (PDF417)
* Resolution Number
* Resolution Date
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from .TemplateElement import TemplateElement, Resource
from .barcode import PDF4... | class SectionBarcode(TemplateElement): |
Using the snippet: <|code_start|>Contains:
* Barcode (PDF417)
* Resolution Number
* Resolution Date
"""
class SectionBarcode(TemplateElement):
"""
%% -----------------------------------------------------------------
%% SECTION - Barcode
%% --------------------------------------------------... | ress.append(Resource('barcode.eps', self._eps)) |
Given snippet: <|code_start|> @property
def carta(self):
tex = self.__doc__ % (
0.9,
self._res_number,
self._res_datestr
)
return tex
@property
def oficio(self):
tex = self.__doc__ % (
0.9,
self._res_number,
... | pdf417 = PDF417(self._data) |
Given the code snippet: <|code_start|>""" SII WebService Authentication Seed.
"""
__all__ = [
'Seed'
]
class Seed(object):
SEED_OK = 0
SEED_LINE_ERR = -1
SEED_RETURN_ERR = -2
def __init__(self, sii_host="https://palena.sii.cl/DTEWS/CrSeed.jws?wsdl"):
self.sii_host = sii_host... | return with_retry(lambda: self.sii_soap.service.getSeed()) |
Continue the code snippet: <|code_start|># module. Defaults to `os.getcwd()`.
# depends_files -- list of str, paths to Fortran files that should be
# checked for changes when compiling the final module.
# **kwargs -- Any configuration options relevant to this
# ... | print() |
Given the code snippet: <|code_start|># Making this module accessible by being called directly from command line.
# Import all of the fmodpy module
if len(sys.argv) < 2:
help(fmodpy)
exit()
else:
file_path = os.path.abspath(sys.argv[1])
# Pretty error handling when this file is executed directly
def... | fimport(file_path, **command_line_args) |
Given the code snippet: <|code_start|> for attr in dir(self):
# Skip hidden attributes.
if (attr[:1] == "_"): continue
# TODO: Come up with better general way to handle these special cases.
if (attr in {"c_type", "c_type_array", "py_type"}): continue
va... | group, line = pop_group(line) |
Using the snippet: <|code_start|> continue
# Parse the contained objects out of the file.
for (parser, name) in self.can_contain:
pre_length = len(list_of_lines)
instances = parser(list_of_lines, comments, self)
length = pre_leng... | raise(ParseError(f"\n\nEncountered unrecognized line while parsing {class_name(self)}:\n\n {str([list_of_lines.pop(0)])[1:-1]}\n\n")) |
Predict the next line for this snippet: <|code_start|>
class MethodMap(object):
def __init__(self, decorator=Identity):
super(MethodMap, self).__init__()
self._map = {}
self._decorate = decorator
def registering(self, key):
return functools.partial(self.register, key)
def reg... | return get_underlying_function(function) |
Here is a snippet: <|code_start|> def __init__(self, decorator=Identity):
super(MethodMap, self).__init__()
self._map = {}
self._decorate = decorator
def registering(self, key):
return functools.partial(self.register, key)
def register(self, key, value):
self._map[key]... | return create_bound_method( |
Next line prediction: <|code_start|>
class OriginalObject(object):
def __init__(self):
super(OriginalObject, self).__init__()
self.public_attr = 54321
self._private_attr = 12345
def method(self):
return 666
@classmethod
def classmethod(cls):
return 777
@static... | self.obj = Reprify(self.original_object, str=self.STR, repr=self.REPR) |
Using the snippet: <|code_start|>
def listdir_patch(path):
return [path]
TEST_PATH = "__infi_test"
class EnumTestCase(TestCase):
def test__patch_context(self):
<|code_end|>
, determine the next line of code. You have imports:
import os
from infi.pyutils.patch import patch
from .test_utils import TestCase
an... | with patch(os, "listdir", listdir_patch): |
Based on the snippet: <|code_start|> def get_header(self, name):
...
class UserAuth(object):
def is_authenticated(self):
auth_header = self.get_header("Authorization")
...
Now, to add the mixin to the object we'll do::
request = HttpRequest(...)
# Find out that there's a need for authe... | @cached_function |
Based on the snippet: <|code_start|> def get_self_arg_name(self):
if self.is_bound_method() and len(self._args) > 0:
return self._args[0].name
return None
def get_arg_names(self):
return (arg.name for arg in self.get_args())
def get_required_arg_names(self):
return... | raise SignatureException("%s is given more than once to %s" % (arg_name, self.func_name)) |
Predict the next line after this snippet: <|code_start|> returned = max(0, returned - 1)
return returned
def get_self_arg_name(self):
if self.is_bound_method() and len(self._args) > 0:
return self._args[0].name
return None
def get_arg_names(self):
return (a... | raise InvalidKeywordArgument("Invalid keyword argument %r" % (arg_name,)) |
Based on the snippet: <|code_start|> def get_normalized_args(self, args, kwargs):
returned = {}
self._update_normalized_positional_args(returned, args)
self._update_normalized_kwargs(returned, kwargs)
self._check_missing_arguments(returned)
self._check_unknown_arguments(return... | raise UnknownArguments("%s receives %s positional arguments (%s specified)" % (self.func_name, num_args, num_args + positional_arg_count)) |
Next line prediction: <|code_start|> return set(arg.name for arg in self.get_args() if not arg.has_default())
def has_variable_args(self):
return self._varargs_name is not None
def has_variable_kwargs(self):
return self._kwargs_name is not None
def get_normalized_args(self, args, kwar... | raise MissingArguments("The following arguments were not specified: %s" % ",".join(map(repr, missing_arguments))) |
Using the snippet: <|code_start|> iterator = enumerate(itertools.chain(iter(collection), [_NOTHING]))
prefetched = _NOTHING
while True:
index, element = next(iterator) if prefetched is _NOTHING else prefetched
if element is _NOTHING:
break
prefetched = next(iterator)
... | for index in xrange(len(seq)-1, -1, -1): |
Here is a snippet: <|code_start|>
# no named tuples for python 2.5 compliance...
class ExpectedArg(object):
def __init__(self, name, has_default, default=None):
self.name = name
self.has_default = has_default
self.default = default
class SignatureTest(TestCase):
def _assert_argument_nam... | sig = FunctionSignature(func) |
Given the code snippet: <|code_start|> kwargs.pop([e.name for e in expected_signature if not e.has_default][0])
with self.assertRaises(MissingArguments):
signature.get_normalized_args((), kwargs)
def _test_unknown_arguments(self, signature, expected_signature):
if not signature.ha... | with self.assertRaises(SignatureException): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.