Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
reload(sys)
sys.setdefaultencoding('utf-8')
# python manage.py runspider -a url=https://item.jd.com/11478178241.html -a name=jd
class JDCommentSpider(Spider):
name = 'jd_comment'
def __init__(self, name = None, **kwargs):
super(JDCommentSpider, self).__init__(name, **kwargs)
self.url = kwargs.get("url")
self.guid = kwargs.get('guid', 'guid')
self.product_id = kwargs.get('product_id')
# self.url = 'https://item.jd.com/11478178241.html'
# self.url = 'https://item.jd.com/4142680.html'
# self.url = 'https://item.jd.com/3133859.html'
# self.url = 'https://item.jd.com/3995645.html'
# self.product_id = 3995645
self.log('product_id:%s' % self.product_id)
self.item_table = 'item_%s' % self.product_id
self.urls_key = '%s_urls' % self.product_id
self.log_dir = 'log/%s' % self.product_id
self.is_record_page = False
self.sql = kwargs.get('sql')
self.red = kwargs.get('red')
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import chardet
import re
import json
import datetime
import logging
import config
import utils
from scrapy import Spider
from scrapy import Request
from ..proxymanager import proxymng
and context (classes, functions, sometimes code) from other files:
# Path: jd/proxymanager.py
# class ProxyManager(object):
# def __init__(self):
# def update_proxy(self, count = 100):
# def push_proxy(self, proxy):
# def get_proxy(self):
# def delete_proxy(self, proxy):
. Output only the next line. | proxymng.red = self.red |
Here is a snippet: <|code_start|># coding=utf-8
logger = logging.getLogger(__name__)
class ProxyMiddleware(object):
def process_request(self, request, spider):
try:
request.meta['req_count'] = request.meta.get('req_count', 0) + 1
if request.meta.get('is_proxy', False):
<|code_end|>
. Write the next line using the current file imports:
import logging
from twisted.internet import defer
from twisted.internet.error import TimeoutError, DNSLookupError, \
ConnectionRefusedError, ConnectionDone, ConnectError, \
ConnectionLost, TCPTimedOutError
from scrapy.exceptions import NotConfigured
from scrapy.utils.response import response_status_message
from scrapy.xlib.tx import ResponseFailed
from scrapy.core.downloader.handlers.http11 import TunnelError
from jd.proxymanager import proxymng
and context from other files:
# Path: jd/proxymanager.py
# class ProxyManager(object):
# def __init__(self):
# def update_proxy(self, count = 100):
# def push_proxy(self, proxy):
# def get_proxy(self):
# def delete_proxy(self, proxy):
, which may include functions, classes, or code. Output only the next line. | request.meta['proxy'] = proxymng.get_proxy() |
Continue the code snippet: <|code_start|> main_data = formatted_data_list
else:
main_data = data_list
else:
column = get_object_or_404(DataColumn, id = column_id)
main_data = column.get_data()
if not encode:
return main_data
# Encode it in the appropriate format
if element.get_type() == "graph":
data = json_graph_encoder.encode(main_data)
elif element.get_type() == "table":
data = json_table_encoder.encode(main_data)
else:
data = simplejson.JSONEncoder.encode(main_data)
return data
### Redirections ###
def redirect_to_design():
return HttpResponseRedirect('/dashboard/design/')
def redirect_to_edit_element(element):
return HttpResponseRedirect('/dashboard/design/edit_element/%d/' % element.id)
### Design-mode views ###
<|code_end|>
. Use current file imports:
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core import serializers
from django.utils import simplejson
from django.template import RequestContext
from models import *
from forms import *
from querybuilder.models import *
from querybuilder.decorators import superuser_only
from encoders import json_table_encoder, json_graph_encoder
from querybuilder.models import get_apps, get_models_in_app
import re
and context (classes, functions, or code) from other files:
# Path: querybuilder/decorators.py
# def superuser_only(function):
# def _inner(request, *args, **kwargs):
# if not request.user.is_superuser:
# raise PermissionDenied
#
# return function(request, *args, **kwargs)
# return _inner
. Output only the next line. | @superuser_only |
Given snippet: <|code_start|>#!/usr/bin/python
setup_environ(settings)
while True:
ping_hosts = PingHost.objects.filter(active = True)
time.sleep(5)
for ping_host in ping_hosts:
logging.debug(u"Pinging: " + ping_host.hostname)
result = pinger.ping(ping_host.hostname)
if result != False:
logging.debug(u"Ping success:")
logging.debug(result)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management import setup_environ
from ping.models import PingHost, PingResult
import settings
import time
import ping.ping as pinger
import logging
and context:
# Path: ping/models.py
# class PingHost(models.Model):
# hostname = models.CharField(max_length = global_max_length)
# active = models.BooleanField(default = True)
#
# def __unicode__(self):
# return self.hostname
#
# class PingResult(models.Model):
# host = models.ForeignKey(PingHost)
# min_delay = models.DecimalField(max_digits = 10, decimal_places = 3)
# avg_delay = models.DecimalField(max_digits = 10, decimal_places = 3)
# max_delay = models.DecimalField(max_digits = 10, decimal_places = 3)
# stddev = models.DecimalField(max_digits = 10, decimal_places = 3)
# at = models.DateTimeField(auto_now_add = True)
#
# def __unicode__(self):
# return unicode(self.host) + u" " + str(self.avg_delay) + " at " + str(self.at)
which might include code, classes, or functions. Output only the next line. | p_result = PingResult(min_delay = result[0], avg_delay = result[1], max_delay = result[2], stddev = result[3]) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
filename = './test/test/'
if len(sys.argv)>1:
filename += sys.argv[1]
else:
print('Please input filename!')
exit(1)
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from pingphp.helper import read
from pingphp.lexer import PingLexer
and context (classes, functions, sometimes code) from other files:
# Path: pingphp/helper.py
# def read(path):
# result = ''
# try:
# file_ = open(path, 'rU')
# result = file_.read()
# if len(result) != 0 and result[-1] != '\n':
# result += '\n'
# except:
# logging.error('Read file: ' + path + ' fail')
# finally:
# file_.close()
# return result
#
# Path: pingphp/lexer.py
# class PingLexer(object):
# def __init__(self, inputStr):
# lexer = lex.lex()
# lexer.input(inputStr)
# self.tokList = tokenList(lexer)
# self.tokList = changeTokenList(self.tokList)
# self.nowIndex = 0
#
# def token(self):
# if self.nowIndex < len(self.tokList):
# result = self.tokList[self.nowIndex]
# self.nowIndex += 1
# return result
#
# def __iter__(self):
# return self
#
# def next(self):
# t = self.token()
# if t is None:
# raise StopIteration
# return t
#
# __next__ = next
. Output only the next line. | lexer = PingLexer(read(filename)) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
filename = './test/test/'
if len(sys.argv)>1:
filename += sys.argv[1]
else:
print('Please input filename!')
exit(1)
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from pingphp.helper import read
from pingphp.lexer import PingLexer
and context (classes, functions, sometimes code) from other files:
# Path: pingphp/helper.py
# def read(path):
# result = ''
# try:
# file_ = open(path, 'rU')
# result = file_.read()
# if len(result) != 0 and result[-1] != '\n':
# result += '\n'
# except:
# logging.error('Read file: ' + path + ' fail')
# finally:
# file_.close()
# return result
#
# Path: pingphp/lexer.py
# class PingLexer(object):
# def __init__(self, inputStr):
# lexer = lex.lex()
# lexer.input(inputStr)
# self.tokList = tokenList(lexer)
# self.tokList = changeTokenList(self.tokList)
# self.nowIndex = 0
#
# def token(self):
# if self.nowIndex < len(self.tokList):
# result = self.tokList[self.nowIndex]
# self.nowIndex += 1
# return result
#
# def __iter__(self):
# return self
#
# def next(self):
# t = self.token()
# if t is None:
# raise StopIteration
# return t
#
# __next__ = next
. Output only the next line. | lexer = PingLexer(read(filename)) |
Using the snippet: <|code_start|> Returns:
np.array: Random rotation matrix ``R``.
"""
if rng is None:
rng = np.random.RandomState(42)
assert D >= 2
D = int(D) # make sure that the dimension is an integer
# induction start: uniform draw from D=2 Haar measure
t = 2 * np.pi * rng.uniform()
R = [[np.cos(t), np.sin(t)], [-np.sin(t), np.cos(t)]]
for d in range(2, D):
v = rng.normal(size=(d + 1, 1))
# draw on S_d the unit sphere
v = np.divide(v, np.sqrt(np.transpose(v).dot(v)))
e = np.concatenate((np.array([[1.0]]), np.zeros((d, 1))), axis=0)
# random coset location of SO(d-1) in SO(d)
x = np.divide((e - v), (np.sqrt(np.transpose(e - v).dot(e - v))))
D = np.vstack([
np.hstack([[[1.0]], np.zeros((1, d))]),
np.hstack([np.zeros((d, 1)), R])
])
R = D - 2 * np.outer(x, np.transpose(x).dot(D))
# return negative to fix determinant
return np.negative(R)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from ._quadratic import _quadratic_base
and context (class names, function names, or code) available:
# Path: deepobs/tensorflow/testproblems/_quadratic.py
# class _quadratic_base(TestProblem):
# r"""DeepOBS base class for a stochastic quadratic test problems creating loss\
# functions of the form
#
# :math:`0.5* (\theta - x)^T * Q * (\theta - x)`
#
# with Hessian ``Q`` and "data" ``x`` coming from the quadratic data set, i.e.,
# zero-mean normal.
#
# Args:
# batch_size (int): Batch size to use.
# weight_decay (float): No weight decay (L2-regularization) is used in this
# test problem. Defaults to ``None`` and any input here is ignored.
# hessian (np.array): Hessian of the quadratic problem.
# Defaults to the ``100`` dimensional identity.
#
# Attributes:
# dataset: The DeepOBS data set class for the quadratic test problem.
# train_init_op: A tensorflow operation initializing the test problem for the
# training phase.
# train_eval_init_op: A tensorflow operation initializing the test problem for
# evaluating on training data.
# test_init_op: A tensorflow operation initializing the test problem for
# evaluating on test data.
# losses: A tf.Tensor of shape (batch_size, ) containing the per-example loss
# values.
# regularizer: A scalar tf.Tensor containing a regularization term.
# Will always be ``0.0`` since no regularizer is used.
# """
#
# def __init__(self, batch_size, weight_decay=None, hessian=np.eye(100)):
# """Create a new quadratic test problem instance.
#
# Args:
# batch_size (int): Batch size to use.
# weight_decay (float): No weight decay (L2-regularization) is used in this
# test problem. Defaults to ``None`` and any input here is ignored.
# hessian (np.array): Hessian of the quadratic problem.
# Defaults to the ``100`` dimensional identity.
# """
# super(_quadratic_base, self).__init__(batch_size, weight_decay)
# self._hessian = hessian
# if weight_decay is not None:
# print(
# "WARNING: Weight decay is non-zero but no weight decay is used",
# "for this model."
# )
#
# def set_up(self):
# """Sets up the stochastic quadratic test problem. The parameter ``Theta``
# will be initialized to (a vector of) ``1.0``.
# """
# self.dataset = quadratic(self._batch_size)
# self.train_init_op = self.dataset.train_init_op
# self.train_eval_init_op = self.dataset.train_eval_init_op
# self.test_init_op = self.dataset.test_init_op
#
# x = self.dataset.batch
# hessian = tf.convert_to_tensor(self._hessian, dtype=tf.float32)
# theta = tf.get_variable("theta", shape=(1, hessian.shape[0]),
# initializer=tf.constant_initializer(1.0))
#
# self.losses = tf.linalg.tensor_diag_part(0.5 * tf.matmul(
# tf.subtract(theta, x),
# tf.matmul(hessian, tf.transpose(tf.subtract(theta, x)))))
# self.regularizer = tf.losses.get_regularization_loss()
. Output only the next line. | class quadratic_deep(_quadratic_base): |
Using the snippet: <|code_start|> Return the storage.vars[''] variable that contains the values
Parameters
----------
cv : :class:`openpathsampling.netcdf.PseudoAttribute`
the objectdict you request the attached variable store
template : :obj:`openpathsampling.engines.BaseSnapshot`
an optional snapshot to be used to compute a test value of the CV.
This will determine the type and shape of the
allow_incomplete : bool
if `True` the added store can hold a part of all values. Useful if
the values are large and/or complex and you do not need them for all
snapshots
chunksize : int
for partial storage you can set a chunksize and speedup
"""
if template is None:
if cv.diskcache_template is not None:
template = cv.diskcache_template
elif len(self.key_store(cv)) > 0:
template = self.key_store(cv)[0]
else:
raise RuntimeError(
'Need either at least one stored object to use as a '
'template to determine type and shape of the CV. '
'No items in store: ' + str(self.key_store(cv)))
self.key_store(cv).add_attribute(
<|code_end|>
, determine the next line of code. You have imports:
from .named import UniqueNamedObjectStore
from openpathsampling.netcdfplus.attribute import PseudoAttribute
from openpathsampling.netcdfplus.stores.value import ValueStore
and context (class names, function names, or code) available:
# Path: openpathsampling/netcdfplus/stores/value.py
# class ValueStore(ObjectStore):
# """
# Store that stores a value by integer index
#
# Usually used to save additional attributes for objects
#
# See Also
# --------
# `PseudoAttribute`, `PseudoAttributeStore`
# """
# def __init__(
# self,
# key_class,
# allow_incomplete=False,
# chunksize=256
# ):
# super(ValueStore, self).__init__(None)
# self.key_class = key_class
# self.object_index = None
# self.allow_incomplete = allow_incomplete
# self.chunksize = chunksize
#
# self.object_pos = None
# self._len = 0
#
# def to_dict(self):
# return {
# 'key_class': self.key_class,
# 'allow_incomplete': self.allow_incomplete,
# 'chunksize': self.chunksize
# }
#
# def create_uuid_index(self):
# return dict()
#
# def register(self, storage, prefix):
# super(ValueStore, self).register(storage, prefix)
# self.object_pos = self.storage._objects[self.key_class].pos
#
# def __len__(self):
# return len(self.variables['value'])
#
# # ==========================================================================
# # LOAD/SAVE DECORATORS FOR CACHE HANDLING
# # ==========================================================================
#
# def load(self, idx):
# pos = self.object_pos(idx)
# if pos is None:
# return None
#
# if self.allow_incomplete:
# # we want to load by uuid and it was not in cache.
# if pos in self.index:
# n_idx = self.index[pos]
# else:
# return None
# if n_idx < 0:
# return None
# else:
# if pos < self._len:
# n_idx = pos
# else:
# return None
#
# # if it is in the cache, return it
# try:
# obj = self.cache[n_idx]
# return obj
#
# except KeyError:
# pass
#
# obj = self.vars['value'][n_idx]
#
# self.cache[n_idx] = obj
#
# return obj
#
# def __setitem__(self, idx, value):
# pos = self.object_pos(idx)
#
# if pos is None:
# return
#
# if self.allow_incomplete:
# if pos in self.index:
# return
#
# n_idx = len(self.index)
#
# self.cache.update_size(n_idx)
#
# else:
# if pos < self._len:
# return
#
# n_idx = idx
#
# if self.allow_incomplete:
# # only if partial storage is used store index and update
# self.vars['index'][n_idx] = pos
# self.index[pos] = n_idx
#
# self.vars['value'][n_idx] = value
# self.cache[n_idx] = value
# self._len = max(self._len, n_idx + 1)
#
# def fill_cache(self):
# self.cache.load_max()
#
# def restore(self):
# if self.allow_incomplete: # only if partial storage is used
# for pos, idx in enumerate(self.vars['index'][:]):
# self.index[idx] = pos
#
# self._len = len(self)
# self.initialize_cache()
#
# def initialize(self):
# self.initialize_cache()
#
# def initialize_cache(self):
# self.cache = LRUChunkLoadingCache(
# chunksize=self.chunksize,
# variable=self.vars['value']
# )
# self.cache.update_size()
#
# def __getitem__(self, item):
# # enable numpy style selection of objects in the store
# try:
# if isinstance(item, self.key_class):
# return self.load(item)
# elif type(item) is list:
# return [self.load(idx) for idx in item]
# except KeyError:
# pass
#
# return None
#
# def get(self, item):
# if self.allow_incomplete:
# try:
# return self.load(item)
# except KeyError:
# return None
# else:
# return self.load(item)
. Output only the next line. | ValueStore, |
Predict the next line for this snippet: <|code_start|>
logging.getLogger('openpathsampling.ensemble').setLevel(logging.CRITICAL)
logging.getLogger('openpathsampling.netcdfplus').setLevel(logging.CRITICAL)
engine_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"external_engine")
class ExampleExternalEngine(peng.ExternalEngine):
"""Trivial external engine for engine.c in the tests.
"""
<|code_end|>
with the help of current file imports:
from .test_helpers import assert_items_equal
from openpathsampling.engines.toy import ToySnapshot
from openpathsampling.engines.external_engine import *
from openpathsampling.engines.snapshot import SnapshotDescriptor
import openpathsampling as paths
import openpathsampling.engines as peng
import numpy as np
import pytest
import psutil
import os
import glob
import linecache
import logging
and context from other files:
# Path: openpathsampling/engines/toy/snapshot.py
# class ToySnapshot(BaseSnapshot):
# """
# Simulation snapshot. Only references to coordinates and velocities
# """
#
# @property
# def topology(self):
# return self.engine.topology
#
# @property
# def masses(self):
# return self.topology.masses
, which may contain function names, class names, or code. Output only the next line. | SnaphotClass = ToySnapshot |
Given the following code snippet before the placeholder: <|code_start|> def to_dict(self):
out = dict()
atom_data = []
for atom in self.mdtraj.atoms:
if atom.element is None:
element_symbol = ""
else:
element_symbol = atom.element.symbol
if hasattr(atom, 'segment_id'):
atom_data.append((
atom.serial, atom.name, element_symbol,
int(atom.residue.resSeq), atom.residue.name,
atom.residue.chain.index, atom.segment_id))
else:
atom_data.append((
atom.serial, atom.name, element_symbol,
int(atom.residue.resSeq), atom.residue.name,
atom.residue.chain.index, ''))
out['atom_columns'] = ["serial", "name", "element", "resSeq",
"resName", "chainID", "segmentID"]
out['atoms'] = atom_data
out['bonds'] = [(a.index, b.index) for (a, b) in self.mdtraj.bonds]
return {'mdtraj': out}
@classmethod
def from_dict(cls, dct):
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import pandas as pd
import logging
from openpathsampling.netcdfplus import StorableNamedObject
from openpathsampling.integration_tools import error_if_no_mdtraj, md
and context including class names, function names, and sometimes code from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
. Output only the next line. | error_if_no_mdtraj("MDTrajTopology") |
Next line prediction: <|code_start|> element_symbol = atom.element.symbol
if hasattr(atom, 'segment_id'):
atom_data.append((
atom.serial, atom.name, element_symbol,
int(atom.residue.resSeq), atom.residue.name,
atom.residue.chain.index, atom.segment_id))
else:
atom_data.append((
atom.serial, atom.name, element_symbol,
int(atom.residue.resSeq), atom.residue.name,
atom.residue.chain.index, ''))
out['atom_columns'] = ["serial", "name", "element", "resSeq",
"resName", "chainID", "segmentID"]
out['atoms'] = atom_data
out['bonds'] = [(a.index, b.index) for (a, b) in self.mdtraj.bonds]
return {'mdtraj': out}
@classmethod
def from_dict(cls, dct):
error_if_no_mdtraj("MDTrajTopology")
top_dict = dct['mdtraj']
atoms = pd.DataFrame(
top_dict['atoms'], columns=top_dict['atom_columns'])
bonds = np.array(top_dict['bonds'])
try:
<|code_end|>
. Use current file imports:
(import numpy as np
import pandas as pd
import logging
from openpathsampling.netcdfplus import StorableNamedObject
from openpathsampling.integration_tools import error_if_no_mdtraj, md)
and context including class names, function names, or small code snippets from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
. Output only the next line. | md_topology = md.Topology.from_dataframe(atoms, bonds) |
Next line prediction: <|code_start|># REPLICA EXCHANGE GENERATORS
###############################################################################
class ReplicaExchangeMover(SampleMover):
"""
A Sample Mover implementing a standard Replica Exchange
"""
_is_ensemble_change_mover = True
def __init__(self, ensemble1, ensemble2, bias=None):
"""
Parameters
----------
ensemble1 : openpathsampling.Ensemble
one of the ensemble between to make the repex move
ensemble2 : openpathsampling.Ensemble
one of the ensemble between to make the repex move
bias : list of float
bias is not used yet
"""
# either replicas or ensembles must be a list of pairs; more
# complicated filtering can be done with a wrapper class
super(ReplicaExchangeMover, self).__init__()
# TODO: add support for bias; cf EnsembleHopMover
self.bias = bias
self.ensemble1 = ensemble1
self.ensemble2 = ensemble2
self._trust_candidate = True
<|code_end|>
. Use current file imports:
(import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass)
and context including class names, function names, or small code snippets from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
. Output only the next line. | initialization_logging(logger=init_log, obj=self, |
Given the code snippet: <|code_start|> return list(map(PathReversalMover, ensembles))
class Details(StorableObject):
"""Details of an object. Can contain any data
"""
def __init__(self, **kwargs):
super(Details, self).__init__()
for key, value in kwargs.items():
setattr(self, key, value)
_print_repr_types = [paths.Ensemble]
_print_nothing_keys = ["__uuid__"]
def __str__(self):
# primarily for debugging/interactive use
mystr = ""
for key in self.__dict__.keys():
obj = self.__dict__[key]
if key in self._print_nothing_keys:
pass # do nothing!
elif any([isinstance(obj, tt) for tt in self._print_repr_types]):
mystr += str(key) + " = " + repr(obj) + '\n'
else:
mystr += str(key) + " = " + str(self.__dict__[key]) + '\n'
return mystr
@has_deprecations
<|code_end|>
, generate the next line using the imports in this file:
import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass
and context (functions, classes, or occasionally code) from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
. Output only the next line. | @deprecate(MOVE_DETAILS) |
Predict the next line for this snippet: <|code_start|>def PathReversalSet(ensembles):
return list(map(PathReversalMover, ensembles))
class Details(StorableObject):
"""Details of an object. Can contain any data
"""
def __init__(self, **kwargs):
super(Details, self).__init__()
for key, value in kwargs.items():
setattr(self, key, value)
_print_repr_types = [paths.Ensemble]
_print_nothing_keys = ["__uuid__"]
def __str__(self):
# primarily for debugging/interactive use
mystr = ""
for key in self.__dict__.keys():
obj = self.__dict__[key]
if key in self._print_nothing_keys:
pass # do nothing!
elif any([isinstance(obj, tt) for tt in self._print_repr_types]):
mystr += str(key) + " = " + repr(obj) + '\n'
else:
mystr += str(key) + " = " + str(self.__dict__[key]) + '\n'
return mystr
<|code_end|>
with the help of current file imports:
import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass
and context from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
, which may contain function names, class names, or code. Output only the next line. | @has_deprecations |
Given the following code snippet before the placeholder: <|code_start|> def __str__(self):
# primarily for debugging/interactive use
mystr = ""
for key in self.__dict__.keys():
obj = self.__dict__[key]
if key in self._print_nothing_keys:
pass # do nothing!
elif any([isinstance(obj, tt) for tt in self._print_repr_types]):
mystr += str(key) + " = " + repr(obj) + '\n'
else:
mystr += str(key) + " = " + str(self.__dict__[key]) + '\n'
return mystr
@has_deprecations
@deprecate(MOVE_DETAILS)
class MoveDetails(Details):
"""Details of the move as applied to a given replica
Specific move types may have add several other attributes for each
MoveDetails object. For example, shooting moves will also include
information about the shooting point selection, etc.
"""
def __init__(self, **kwargs):
super(MoveDetails, self).__init__(**kwargs)
# leave this for potential backwards compatibility
@has_deprecations
<|code_end|>
, predict the next line using imports from the current file:
import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass
and context including class names, function names, and sometimes code from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
. Output only the next line. | @deprecate(SAMPLE_DETAILS) |
Given the following code snippet before the placeholder: <|code_start|> return list(map(PathReversalMover, ensembles))
class Details(StorableObject):
"""Details of an object. Can contain any data
"""
def __init__(self, **kwargs):
super(Details, self).__init__()
for key, value in kwargs.items():
setattr(self, key, value)
_print_repr_types = [paths.Ensemble]
_print_nothing_keys = ["__uuid__"]
def __str__(self):
# primarily for debugging/interactive use
mystr = ""
for key in self.__dict__.keys():
obj = self.__dict__[key]
if key in self._print_nothing_keys:
pass # do nothing!
elif any([isinstance(obj, tt) for tt in self._print_repr_types]):
mystr += str(key) + " = " + repr(obj) + '\n'
else:
mystr += str(key) + " = " + str(self.__dict__[key]) + '\n'
return mystr
@has_deprecations
<|code_end|>
, predict the next line using imports from the current file:
import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass
and context including class names, function names, and sometimes code from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
. Output only the next line. | @deprecate(MOVE_DETAILS) |
Predict the next line after this snippet: <|code_start|> def _build_sample(
self,
input_sample,
shooting_index,
trial_trajectory,
stopping_reason=None,
run_details={}
):
# TODO OPS 2.0: the passing of run_details is a hack and should be
# properly refactored
initial_trajectory = input_sample.trajectory
if stopping_reason is None:
bias = 1.0
old_snapshot = initial_trajectory[shooting_index]
new_snapshot = run_details.get("modified_shooting_snapshot",
old_snapshot)
# Selector bias
try:
bias *= self.selector.probability_ratio(
initial_trajectory[shooting_index],
initial_trajectory,
trial_trajectory,
new_snapshot=new_snapshot
)
except TypeError:
bias *= self.selector.probability_ratio(
initial_trajectory[shooting_index],
initial_trajectory,
trial_trajectory)
<|code_end|>
using the current file's imports:
import abc
import logging
import numpy as np
import random
import openpathsampling as paths
from openpathsampling.netcdfplus import StorableNamedObject, StorableObject
from openpathsampling.pathmover_inout import InOutSet, InOut
from openpathsampling.rng import default_rng
from .ops_logging import initialization_logging
from .treelogic import TreeMixin
from openpathsampling.deprecations import deprecate, has_deprecations
from openpathsampling.deprecations import (SAMPLE_DETAILS, MOVE_DETAILS,
NEW_SNAPSHOT_KWARG_SELECTOR)
from future.utils import with_metaclass
and any relevant context from other files:
# Path: openpathsampling/ops_logging.py
# def initialization_logging(logger, obj, entries):
# # this works with either a list of attributes of a dictionary of
# # variable name : attribute value
# try:
# entries.keys()
# working_dict = entries
# except AttributeError:
# working_dict = {}
# for entry in entries:
# working_dict[entry] = obj.__dict__[entry]
#
# logger.info("Initializing <%s> (%s)",
# str(hex(id(obj))), str(obj.__class__.__name__))
# for entry in working_dict.keys():
# logger.info("Parameter: %s : %s", str(entry), str(working_dict[entry]))
#
# Path: openpathsampling/deprecations.py
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# Path: openpathsampling/deprecations.py
# SAMPLE_DETAILS = Deprecation(
# problem="SampleDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# MOVE_DETAILS = Deprecation(
# problem="MoveDetails will be removed in {OPS} {version}.",
# remedy="Use generic Details class instead.",
# remove_version=(2, 0),
# deprecated_in=(0, 9, 3)
# )
#
# NEW_SNAPSHOT_KWARG_SELECTOR = Deprecation(
# problem=("'new_snapshot' should be a supported keyword in "
# "selector.probability_ratio(); If snapshot has been copied or "
# "modified we can't reliably find it in trial_trajectory. This "
# "keyword must be supported in the expected signature: "
# "(old_snapshot, old_trajectory, new_snapshot, new_trajectory) "
# "in {OPS} {version}. "),
# remedy=("kwarg 'new_snapshot' must to be supported, implement it as "
# "new_snapshot=old_snapshot if new_traj is not used to calculate "
# "the weight of old_snapshot"),
# remove_version=(2, 0),
# deprecated_in=(1, 6, 0)
# )
. Output only the next line. | NEW_SNAPSHOT_KWARG_SELECTOR.warn() |
Here is a snippet: <|code_start|> # test uses snapshots with different velocities
self.initial_snapshots = [toys.Snapshot(
coordinates=np.array([[0.0]]),
velocities=np.array([[1.0]]),
engine=self.engine),
toys.Snapshot(
coordinates=np.array([[0.1]]),
velocities=np.array([[-1.0]]),
engine=self.engine),
toys.Snapshot(
coordinates=np.array([[-0.2]]),
velocities=np.array([[2.0]]),
engine=self.engine)]
# trajectory length is set to 100 steps
self.l = 100
# reaction coordinate is just x coordinate
rc = paths.FunctionCV("Id", lambda snap : snap.coordinates[0][0])
# state S: [-0.5, 0.5]
self.state_S = paths.CVDefinedVolume(rc, -0.5, 0.5)
# define state labels
self.state_labels = {
"S" : self.state_S,
"NotS" :~self.state_S}
# velocities are not randomized
randomizer = paths.NoModification()
self.filename = data_filename("sshooting_test.nc")
self.storage = paths.Storage(self.filename, mode="w")
self.storage.save(self.initial_snapshots)
<|code_end|>
. Write the next line using the current file imports:
from openpathsampling.tests.test_helpers import (data_filename)
from openpathsampling.pathsimulators.sshooting_simulator import SShootingSimulation
import openpathsampling as paths
import openpathsampling.engines.toy as toys
import numpy as np
import os
and context from other files:
# Path: openpathsampling/pathsimulators/sshooting_simulator.py
# class SShootingSimulation(ShootFromSnapshotsSimulation):
# """ S-Shooting simulations.
#
# Parameters
# ----------
# storage : :class:`.Storage`
# the file to store simulations in
# engine : :class:`.DynamicsEngine`
# the dynamics engine to use to run the simulation
# state_S : :class:`.Volume`
# the volume representing saddle region S.
# randomizer : :class:`.SnapshotModifier`
# the method used to modify the input snapshot before each shot
# initial_snapshots : list of :class:`.Snapshot`
# initial snapshots to use.
# trajectory_length : int
# Trajectory length l of backward/forward shot, total length of generated
# trajectories is 2*l+1. The harvested subtrajectories have length l+1.
# """
# def __init__(self, storage, engine=None, state_S=None, randomizer=None,
# initial_snapshots=None, trajectory_length=None):
#
# # Defintion of state S (A and B are only required for analysis).
# self.state_S = state_S
#
# # Set forward/backward shot length.
# self.trajectory_length = trajectory_length
# l = self.trajectory_length
#
# # Define backward ensemble:
# # trajectory starts in S and has fixed length l.
# backward_ensemble = paths.SequentialEnsemble([
# paths.LengthEnsemble(l),
# paths.AllInXEnsemble(state_S) & paths.LengthEnsemble(1)
# ])
#
# # Define forward ensemble:
# # CAUTION: first trajectory is in backward ensemble,
# # then continues with fixed length l.
# forward_ensemble = paths.SequentialEnsemble([
# paths.LengthEnsemble(l),
# paths.AllInXEnsemble(state_S) & paths.LengthEnsemble(1),
# paths.LengthEnsemble(l)
# ])
#
# super(SShootingSimulation, self).__init__(
# storage=storage,
# engine=engine,
# starting_volume=state_S,
# forward_ensemble=forward_ensemble,
# backward_ensemble=backward_ensemble,
# randomizer=randomizer,
# initial_snapshots=initial_snapshots
# )
#
# # Create backward mover (starting from single point).
# self.backward_mover = paths.BackwardExtendMover(
# ensemble=self.starting_ensemble,
# target_ensemble=self.backward_ensemble
# )
#
# # Create forward mover (starting from the backward ensemble).
# self.forward_mover = paths.ForwardExtendMover(
# ensemble=self.backward_ensemble,
# target_ensemble=self.forward_ensemble
# )
#
# # Create mover combining forward and backward shooting. No condition
# # here, shots in both directions are executed in any case.
# self.mover = paths.NonCanonicalConditionalSequentialMover([
# self.backward_mover,
# self.forward_mover
# ])
#
# def to_dict(self):
# ret_dict = {
# 'state_S' : self.state_S,
# 'trajectory_length' : self.trajectory_length
# }
# return ret_dict
#
# @classmethod
# def from_dict(cls, dct):
# sshooting = cls.__new__(cls)
#
# # replace automatically created attributes with stored ones
# sshooting.state_S = dct['state_S']
# sshooting.trajectory_length = dct['trajectory_length']
# return sshooting
, which may include functions, classes, or code. Output only the next line. | self.simulation = SShootingSimulation( |
Based on the snippet: <|code_start|> for subtrj in subtrajectories]
# ==========================================================================
# UTILITY FUNCTIONS
# ==========================================================================
def to_mdtraj(self, topology=None):
"""
Construct a mdtraj.Trajectory object from the Trajectory itself
Parameters
----------
topology : :class:`mdtraj.Topology`
If not None this topology will be used to construct the mdtraj
objects otherwise the topology object will be taken from the
configurations in the trajectory snapshots.
Returns
-------
:class:`mdtraj.Trajectory`
the trajectory
Notes
-----
If the OPS trajectory is zero-length (has no snapshots), then this
fails. OPS cannot currently convert zero-length trajectories to
MDTraj, because an OPS zero-length trajectory cannot determine its
MDTraj topology.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import openpathsampling as paths
from openpathsampling.integration_tools import (
error_if_no_mdtraj, is_simtk_quantity_type, md
)
from openpathsampling.netcdfplus import StorableObject, LoaderProxy
and context (classes, functions, sometimes code) from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
. Output only the next line. | error_if_no_mdtraj("Converting to mdtraj") |
Next line prediction: <|code_start|> If not None this topology will be used to construct the mdtraj
objects otherwise the topology object will be taken from the
configurations in the trajectory snapshots.
Returns
-------
:class:`mdtraj.Trajectory`
the trajectory
Notes
-----
If the OPS trajectory is zero-length (has no snapshots), then this
fails. OPS cannot currently convert zero-length trajectories to
MDTraj, because an OPS zero-length trajectory cannot determine its
MDTraj topology.
"""
error_if_no_mdtraj("Converting to mdtraj")
try:
snap = self[0]
except IndexError:
raise ValueError("Cannot convert zero-length trajectory "
+ "to MDTraj")
if topology is None:
# TODO: maybe add better error output?
# if AttributeError here, engine doesn't support mdtraj
topology = snap.engine.mdtraj_topology
output = self.xyz
<|code_end|>
. Use current file imports:
(import numpy as np
import openpathsampling as paths
from openpathsampling.integration_tools import (
error_if_no_mdtraj, is_simtk_quantity_type, md
)
from openpathsampling.netcdfplus import StorableObject, LoaderProxy)
and context including class names, function names, or small code snippets from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
. Output only the next line. | traj = md.Trajectory(output, topology) |
Given the following code snippet before the placeholder: <|code_start|> """
Returns
-------
n_degrees_of_freedom: int
number of degrees of freedom in this system (after accounting for
constraints)
"""
return snapshot.engine.n_degrees_of_freedom()
@property
def instantaneous_temperature(snapshot):
"""
Returns
-------
instantaneous_temperature : openmm.unit.Quantity (temperature)
instantaneous temperature from the kinetic energy of this snapshot
"""
# TODO: this can be generalized as a feature that works with any
# snapshot that has features for KE (in units of kB) and n_dofs
# if no engine, error here; don't get caught in try/except below
engine = snapshot.engine
try:
old_snap = engine.current_snapshot
except Exception: # openmm doesn't use a custom exception class yet
# Exception: Particle positions have not been set
old_snap = None
engine.current_snapshot = snapshot
state = engine.simulation.context.getState(getEnergy=True)
# divide by Avogadro b/c OpenMM reports energy/mole
<|code_end|>
, predict the next line using imports from the current file:
from openpathsampling.integration_tools import openmm as mm
from openpathsampling.integration_tools import unit as u
and context including class names, function names, and sometimes code from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
#
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
. Output only the next line. | ke_in_energy = state.getKineticEnergy() / u.AVOGADRO_CONSTANT_NA |
Given the following code snippet before the placeholder: <|code_start|> cv_requires_lists=cv_requires_lists,
cv_wrap_numpy_array=cv_wrap_numpy_array,
cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons,
**kwargs
)
self.topology = topology
def _eval(self, items):
trajectory = paths.Trajectory(items)
t = trajectory_to_mdtraj(trajectory, self.topology.mdtraj)
return self.cv_callable(t, **self.kwargs)
@property
def mdtraj_function(self):
return self.cv_callable
def to_dict(self):
return {
'name': self.name,
'f': ObjectJSON.callable_to_dict(self.f),
'topology': self.topology,
'kwargs': self.kwargs,
'cv_requires_lists': self.cv_requires_lists,
'cv_wrap_numpy_array': self.cv_wrap_numpy_array,
'cv_scalarize_numpy_singletons': self.cv_scalarize_numpy_singletons
}
<|code_end|>
, predict the next line using imports from the current file:
import openpathsampling as paths
import openpathsampling.netcdfplus.chaindict as cd
import sys
import pyemma.coordinates
from openpathsampling.integration_tools import md, error_if_no_mdtraj
from openpathsampling.engines.openmm.tools import trajectory_to_mdtraj
from openpathsampling.netcdfplus import WeakKeyCache, \
ObjectJSON, create_to_dict, ObjectStore, PseudoAttribute
from openpathsampling.deprecations import (has_deprecations, deprecate,
MSMBUILDER)
and context including class names, function names, and sometimes code from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
#
# Path: openpathsampling/deprecations.py
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# MSMBUILDER = Deprecation(
# problem=("MSMBuilder is no longer maintained. "
# + "MSMBFeaturizer is no longer officially supported."),
# remedy="Create a CoordinateFunctionCV based on MSMBuilderFeaturizers.",
# remove_version=(2, 0),
# deprecated_in=(1, 1, 0)
# )
. Output only the next line. | @has_deprecations |
Based on the snippet: <|code_start|> cv_wrap_numpy_array=cv_wrap_numpy_array,
cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons,
**kwargs
)
self.topology = topology
def _eval(self, items):
trajectory = paths.Trajectory(items)
t = trajectory_to_mdtraj(trajectory, self.topology.mdtraj)
return self.cv_callable(t, **self.kwargs)
@property
def mdtraj_function(self):
return self.cv_callable
def to_dict(self):
return {
'name': self.name,
'f': ObjectJSON.callable_to_dict(self.f),
'topology': self.topology,
'kwargs': self.kwargs,
'cv_requires_lists': self.cv_requires_lists,
'cv_wrap_numpy_array': self.cv_wrap_numpy_array,
'cv_scalarize_numpy_singletons': self.cv_scalarize_numpy_singletons
}
@has_deprecations
<|code_end|>
, predict the immediate next line with the help of imports:
import openpathsampling as paths
import openpathsampling.netcdfplus.chaindict as cd
import sys
import pyemma.coordinates
from openpathsampling.integration_tools import md, error_if_no_mdtraj
from openpathsampling.engines.openmm.tools import trajectory_to_mdtraj
from openpathsampling.netcdfplus import WeakKeyCache, \
ObjectJSON, create_to_dict, ObjectStore, PseudoAttribute
from openpathsampling.deprecations import (has_deprecations, deprecate,
MSMBUILDER)
and context (classes, functions, sometimes code) from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
#
# Path: openpathsampling/deprecations.py
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# MSMBUILDER = Deprecation(
# problem=("MSMBuilder is no longer maintained. "
# + "MSMBFeaturizer is no longer officially supported."),
# remedy="Create a CoordinateFunctionCV based on MSMBuilderFeaturizers.",
# remove_version=(2, 0),
# deprecated_in=(1, 1, 0)
# )
. Output only the next line. | @deprecate(MSMBUILDER) |
Predict the next line after this snippet: <|code_start|> cv_wrap_numpy_array=cv_wrap_numpy_array,
cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons,
**kwargs
)
self.topology = topology
def _eval(self, items):
trajectory = paths.Trajectory(items)
t = trajectory_to_mdtraj(trajectory, self.topology.mdtraj)
return self.cv_callable(t, **self.kwargs)
@property
def mdtraj_function(self):
return self.cv_callable
def to_dict(self):
return {
'name': self.name,
'f': ObjectJSON.callable_to_dict(self.f),
'topology': self.topology,
'kwargs': self.kwargs,
'cv_requires_lists': self.cv_requires_lists,
'cv_wrap_numpy_array': self.cv_wrap_numpy_array,
'cv_scalarize_numpy_singletons': self.cv_scalarize_numpy_singletons
}
@has_deprecations
<|code_end|>
using the current file's imports:
import openpathsampling as paths
import openpathsampling.netcdfplus.chaindict as cd
import sys
import pyemma.coordinates
from openpathsampling.integration_tools import md, error_if_no_mdtraj
from openpathsampling.engines.openmm.tools import trajectory_to_mdtraj
from openpathsampling.netcdfplus import WeakKeyCache, \
ObjectJSON, create_to_dict, ObjectStore, PseudoAttribute
from openpathsampling.deprecations import (has_deprecations, deprecate,
MSMBUILDER)
and any relevant context from other files:
# Path: openpathsampling/integration_tools.py
# def error_if_no(name, package_name, has_package):
# def _chain_import(*packages):
# def error_if_no_simtk_unit(name):
# def error_if_no_mdtraj(name):
# def error_if_to_openmm(name):
# HAS_SIMTK_UNIT = False
# HAS_SIMTK_UNIT = True
# HAS_MDTRAJ = False
# HAS_MDTRAJ = True
# HAS_OPENMM = False
# HAS_OPENMM = True
#
# Path: openpathsampling/deprecations.py
# def has_deprecations(cls):
# """Decorator to ensure that docstrings get updated for wrapped class"""
# for obj in [cls] + list(vars(cls).values()):
# if callable(obj) and hasattr(obj, '__new_docstring'):
# try:
# obj.__doc__ = obj.__new_docstring
# except AttributeError:
# # probably Python 2; we can't update docstring in Py2
# # see https://github.com/Chilipp/docrep/pull/9 and related
# pass
# del obj.__new_docstring
# return cls
#
# def deprecate(deprecation):
# """Decorator to deprecate a class/method
#
# Note
# ----
# Properties can be particularly challenging. First, you must put the
# @property decorator outside (above) the @deprecate decorator.
# Second, this does not (yet) change the docstrings of properties.
# However, it will raise a warning when the property is used.
# """
# def decorator(dep_obj):
# dep_obj.__new_docstring = update_docstring(dep_obj, deprecation)
# wrap_class = isclass(dep_obj)
# to_wrap = dep_obj.__init__ if wrap_class else dep_obj
#
# @wraps(to_wrap)
# def wrapper(*args, **kwargs):
# deprecation.warn()
# return to_wrap(*args, **kwargs)
#
# if wrap_class:
# dep_obj.__init__ = wrapper
# return dep_obj
# else:
# return wrapper
# return decorator
#
# MSMBUILDER = Deprecation(
# problem=("MSMBuilder is no longer maintained. "
# + "MSMBFeaturizer is no longer officially supported."),
# remedy="Create a CoordinateFunctionCV based on MSMBuilderFeaturizers.",
# remove_version=(2, 0),
# deprecated_in=(1, 1, 0)
# )
. Output only the next line. | @deprecate(MSMBUILDER) |
Next line prediction: <|code_start|>def interpolate_slice(f3d, rot, pfac=2, size=None):
nhalf = f3d.shape[0] / 2
if size is None:
phalf = nhalf
else:
phalf = size / 2
qot = rot * pfac # Scaling!
px, py, pz = np.meshgrid(np.arange(-phalf, phalf), np.arange(-phalf, phalf), 0)
pr = np.sqrt(px ** 2 + py ** 2 + pz ** 2)
pcoords = np.vstack([px.reshape(-1), py.reshape(-1), pz.reshape(-1)])
mcoords = qot.T.dot(pcoords)
mcoords = mcoords[:, pr.reshape(-1) < nhalf]
pvals = map_coordinates(np.real(f3d), mcoords, order=1, mode="wrap") + \
1j * map_coordinates(np.imag(f3d), mcoords, order=1, mode="wrap")
pslice = np.zeros(pr.shape, dtype=np.complex)
pslice[pr < nhalf] = pvals
return pslice
def vol_ft(vol, pfac=2, threads=1, normfft=1):
""" Returns a centered, Nyquist-limited, zero-padded, interpolation-ready 3D Fourier transform.
:param vol: Volume to be Fourier transformed.
:param pfac: Size factor for zero-padding.
:param threads: Number of threads for pyFFTW.
:param normfft: Normalization constant for Fourier transform.
"""
vol = grid_correct(vol, pfac=pfac, order=1)
padvol = np.pad(vol, int((vol.shape[0] * pfac - vol.shape[0]) // 2), "constant")
ft = rfftn(np.fft.ifftshift(padvol), padvol.shape, threads=threads)
ftc = np.zeros((ft.shape[0] + 3, ft.shape[1] + 3, ft.shape[2]), dtype=ft.dtype)
<|code_end|>
. Use current file imports:
(import numpy as np
import numpy.ma as ma
from scipy.ndimage import map_coordinates
from pyfftw.interfaces.numpy_fft import rfftn
from .vop_numba import fill_ft)
and context including class names, function names, or small code snippets from other files:
# Path: pyem/vop/vop_numba.py
# @numba.jit(cache=True, nopython=True, nogil=True)
# def fill_ft(ft, ftc, rmax, normfft=1):
# rmax2 = rmax ** 2
# for k in range(ft.shape[0]):
# kp = k if k < ft.shape[2] else k - ft.shape[0]
# for i in range(ft.shape[1]):
# ip = i if i < ft.shape[2] else i - ft.shape[1]
# for j in range(ft.shape[2]):
# jp = j
# r2 = ip**2 + jp**2 + kp**2
# if r2 <= rmax2:
# ftc[kp + ftc.shape[0]//2, ip + ftc.shape[1]//2, jp] = ft[k, i, j] * normfft
. Output only the next line. | fill_ft(ft, ftc, vol.shape[0], normfft=normfft) |
Given the following code snippet before the placeholder: <|code_start|> for r in refs:
if args.class_3d is not None:
refmap = EMData(r)
com = Vec3f(*refmap.phase_cog()[:3])
shifts.append(com)
else:
stack = EMData.read_images(r)
for im in stack:
com = Vec2f(*im.phase_cog()[:2])
shifts.append(com)
if args.class_2d is None and args.class_3d is None:
for ptcl in star.rows:
im = EMData.read_image(ptcl)
com = im.phase_cog()
ptcl["rlnOriginX"] += com[0]
ptcl["rlnOriginY"] += com[1]
else:
for ptcl in star.rows:
com = shifts[ptcl["rlnClassNumber"]]
xshift, yshift = transform_com(com, ptcl)
ptcl["rlnOriginX"] += xshift
ptcl["rlnOriginY"] += yshift
if args.zero_origin:
star["rlnCoordinateX"] = star["rlnCoordinateX"] - star["rlnOriginX"]
star["rlnCoordinateY"] = star["rlnCoordinateY"] - star["rlnOriginY"]
star["rlnOriginX"] = 0
star["rlnOriginY"] = 0
<|code_end|>
, predict the next line using imports from the current file:
import glob
import logging
import sys
import numpy as np
import argparse
from star import parse_star, write_star
from EMAN2 import EMData, Vec3f, Transform
and context including class names, function names, and sometimes code from other files:
# Path: star.py
# def main(args):
. Output only the next line. | write_star(args.output, star, reindex=True) |
Continue the code snippet: <|code_start|>def sc2dq(theta, d, l, m):
q = np.zeros((4,), dtype=np.complex128)
theta_half = 0.5 * theta
sin_theta_half = np.sin(theta_half)
cos_theta_half = np.cos(theta_half)
d_half = 0.5 * d
q.real[0] = cos_theta_half
q.real[:1] = sin_theta_half * l
q.imag[0] = - d_half * sin_theta_half
q.imag[1:] = sin_theta_half * m + d_half * cos_theta_half * l
return q
# @numba.jit(nopython=True, cache=False, nogil=True)
# def dqpower(q, t):
# theta, d, l, m = dq2sc(q)
# theta_half = 0.5 * theta
# d_half = 0.5 * d
# da_real = t * np.cos(theta_half)
# da_dual = t * -d_half * np.sin(theta_half)
@numba.jit(nopython=True, cache=False, parallel=True)
def pdistdq(q, d):
relq = np.zeros((4,), dtype=np.complex128)
for i in numba.prange(d.shape[0]):
# relq = geom.dqtimes(geom.dqconj(q[i, None]), q)
for j in range(i + 1, d.shape[1]):
relq[:] = dqtimes_sca(dqconj_sca(q[i]), q[j])
theta, dax, l, m = dq2sc(relq)
<|code_end|>
. Use current file imports:
import numba
import numpy as np
from .geom_numba import cross3_sca
and context (classes, functions, or code) from other files:
# Path: pyem/geom/geom_numba.py
# @numba.jit(nopython=True, cache=False, nogil=True)
# def cross3_sca(u, v):
# w = np.zeros_like(u)
# w[0] = u[1] * v[2] - u[2] * v[1]
# w[1] = u[2] * v[0] - u[0] * v[2]
# w[2] = u[0] * v[1] - u[1] * v[0]
# return w
. Output only the next line. | p0 = cross3_sca(l, m) |
Using the snippet: <|code_start|> print("No CTF resolution field found in input")
return 1
df = df.loc[ind]
if args.max_ctf_fom is not None:
ind = df["rlnCtfFigureOfMerit"] <= args.max_ctf_fom
df = df.loc[ind]
if args.min_ctf_fom is not None:
ind = df["rlnCtfFigureOfMerit"] >= args.min_ctf_fom
df = df.loc[ind]
if args.min_particles is not None:
counts = df["rlnMicrographName"].value_counts()
subset = df.set_index("rlnMicrographName").loc[counts.index[counts > args.min_particles]]
df = subset.reset_index()
if args.subsample is not None:
if args.subsample < 1:
args.subsample = np.max(np.round(args.subsample * df.shape[0]), 1)
if args.bootstrap is not None:
print("Not implemented yet")
return 1
inds = np.random.choice(df.shape[0],
size=(np.int(args.subsample),
df.shape[0]/np.int(args.subsample)),
replace=True)
else:
df = df.sample(np.int(args.subsample), random_state=args.seed)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import sys
import argparse
from pyem.star import parse_star
from pyem.star import write_star
and context (class names, function names, or code) available:
# Path: pyem/star.py
# def parse_star(starfile, keep_index=False, augment=True, nrows=sys.maxsize):
# tables = star_table_offsets(starfile)
# dfs = {t: parse_star_table(starfile, offset=tables[t][0], nrows=min(tables[t][3], nrows), keep_index=keep_index)
# for t in tables}
# if Relion.OPTICDATA in dfs:
# if Relion.PARTICLEDATA in dfs:
# data_table = Relion.PARTICLEDATA
# elif Relion.MICROGRAPHDATA in dfs:
# data_table = Relion.MICROGRAPHDATA
# elif Relion.IMAGEDATA in dfs:
# data_table = Relion.IMAGEDATA
# else:
# data_table = None
# if data_table is not None:
# df = pd.merge(dfs[Relion.OPTICDATA], dfs[data_table], on=Relion.OPTICSGROUP)
# else:
# df = dfs[Relion.OPTICDATA]
# else:
# df = dfs[next(iter(dfs))]
# df = check_defaults(df, inplace=True)
# if augment:
# augment_star_ucsf(df, inplace=True)
# return df
#
# Path: pyem/star.py
# def write_star(starfile, df, resort_fields=True, resort_records=False, simplify=True, optics=True):
# if not starfile.endswith(".star"):
# starfile += ".star"
# if resort_records:
# df = sort_records(df, inplace=True)
# if simplify and len([c for c in df.columns if "ucsf" in c or "eman" in c]) > 0:
# df = simplify_star_ucsf(df)
#
# if optics:
# if Relion.OPTICSGROUP not in df:
# df[Relion.OPTICSGROUP] = 1
# gb = df.groupby(Relion.OPTICSGROUP)
# df_optics = gb[df.columns.intersection(Relion.OPTICSGROUPTABLE)].first().reset_index(drop=False)
# df = df.drop(columns=Relion.OPTICSGROUPTABLE, errors="ignore")
# data_table = Relion.PARTICLEDATA if is_particle_star(df) else Relion.MICROGRAPHDATA
# dfs = {Relion.OPTICDATA: df_optics, data_table: df}
# write_star_tables(starfile, dfs, resort_fields=resort_fields)
# else:
# write_star_table(starfile, df, table=Relion.IMAGEDATA, resort_fields=resort_fields)
. Output only the next line. | write_star(args.output, df) |
Continue the code snippet: <|code_start|> assert arr.ndim == 2
if reference is None:
mu0 = np.mean(arr, axis=0, keepdims=True)
mu = np.mean(arr)
else:
mu0 = np.mean(reference, axis=0, keepdims=True)
mu = np.mean(reference)
mu1 = np.mean(arr, axis=1, keepdims=True)
if inplace:
arr -= mu0
arr -= mu1
arr += mu
else:
arr = arr - mu0
arr -= mu1
arr += mu
return arr
def isrotation(r, tol=1e-6):
"""Check for valid rotation matrix"""
check = np.identity(3, dtype=r.dtype) - np.dot(r.T, r)
if tol is None:
return check
return np.linalg.norm(check) < tol
def qslerp_mult_balanced(keyq, steps_per_deg=10):
qexp = []
for i in range(0, len(keyq) - 1):
<|code_end|>
. Use current file imports:
import numpy as np
from .quat_numba import distq
from .quat_numba import qslerp
from .quat_numba import qtimes
from .quat import meanq
and context (classes, functions, or code) from other files:
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=False, nopython=True, nogil=True)
# def distq(q1, q2):
# pi_half = np.pi / 2
# v = np.abs(np.sum(q1 * q2))
# v = np.clip(0, 1.0, v)
# v = np.arccos(v)
# v *= 2
# # msk = v > pi_half
# # v[msk] = np.pi - v[msk]
# return v
#
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=True, nopython=True, nogil=True)
# def qslerp(q1, q2, t, longest=False):
# cos_half_theta = np.dot(q1, q2)
# if cos_half_theta >= 1.0:
# return q1.copy()
# if longest:
# if cos_half_theta > 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# elif cos_half_theta < 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# half_theta = np.arccos(cos_half_theta)
# sin_half_theta = np.sqrt(1 - cos_half_theta * cos_half_theta)
# if np.abs(sin_half_theta) < 1E-12:
# return (q1 + q2) / 2
# a = np.sin((1 - t) * half_theta)
# b = np.sin(t * half_theta)
# return (q1 * a + q2 * b) / sin_half_theta
#
# Path: pyem/geom/quat_numba.py
# @numba.guvectorize(["void(float64[:], float64[:], float64[:])"],
# "(m),(m)->(m)", nopython=True, cache=False)
# def qtimes(q1, q2, q3):
# _qtimes(q1, q2, q3)
#
# Path: pyem/geom/quat.py
# def meanq(q, w=None):
# if w is None:
# return np.linalg.eigh(np.einsum('ij,ik->...jk', q, q))[1][:, -1]
# else:
# return np.linalg.eigh(np.einsum('ij,ik,i->...jk', q, q, w))[1][:, -1]
. Output only the next line. | ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg) |
Continue the code snippet: <|code_start|> mu0 = np.mean(arr, axis=0, keepdims=True)
mu = np.mean(arr)
else:
mu0 = np.mean(reference, axis=0, keepdims=True)
mu = np.mean(reference)
mu1 = np.mean(arr, axis=1, keepdims=True)
if inplace:
arr -= mu0
arr -= mu1
arr += mu
else:
arr = arr - mu0
arr -= mu1
arr += mu
return arr
def isrotation(r, tol=1e-6):
"""Check for valid rotation matrix"""
check = np.identity(3, dtype=r.dtype) - np.dot(r.T, r)
if tol is None:
return check
return np.linalg.norm(check) < tol
def qslerp_mult_balanced(keyq, steps_per_deg=10):
qexp = []
for i in range(0, len(keyq) - 1):
ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg)
for t in np.arange(0, 1, 1 / ninterp):
<|code_end|>
. Use current file imports:
import numpy as np
from .quat_numba import distq
from .quat_numba import qslerp
from .quat_numba import qtimes
from .quat import meanq
and context (classes, functions, or code) from other files:
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=False, nopython=True, nogil=True)
# def distq(q1, q2):
# pi_half = np.pi / 2
# v = np.abs(np.sum(q1 * q2))
# v = np.clip(0, 1.0, v)
# v = np.arccos(v)
# v *= 2
# # msk = v > pi_half
# # v[msk] = np.pi - v[msk]
# return v
#
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=True, nopython=True, nogil=True)
# def qslerp(q1, q2, t, longest=False):
# cos_half_theta = np.dot(q1, q2)
# if cos_half_theta >= 1.0:
# return q1.copy()
# if longest:
# if cos_half_theta > 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# elif cos_half_theta < 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# half_theta = np.arccos(cos_half_theta)
# sin_half_theta = np.sqrt(1 - cos_half_theta * cos_half_theta)
# if np.abs(sin_half_theta) < 1E-12:
# return (q1 + q2) / 2
# a = np.sin((1 - t) * half_theta)
# b = np.sin(t * half_theta)
# return (q1 * a + q2 * b) / sin_half_theta
#
# Path: pyem/geom/quat_numba.py
# @numba.guvectorize(["void(float64[:], float64[:], float64[:])"],
# "(m),(m)->(m)", nopython=True, cache=False)
# def qtimes(q1, q2, q3):
# _qtimes(q1, q2, q3)
#
# Path: pyem/geom/quat.py
# def meanq(q, w=None):
# if w is None:
# return np.linalg.eigh(np.einsum('ij,ik->...jk', q, q))[1][:, -1]
# else:
# return np.linalg.eigh(np.einsum('ij,ik,i->...jk', q, q, w))[1][:, -1]
. Output only the next line. | qexp.append(qslerp(keyq[i], keyq[i + 1], t)) |
Predict the next line after this snippet: <|code_start|> qexp = []
for i in range(0, len(keyq) - 1):
ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg)
for t in np.arange(0, 1, 1 / ninterp):
qexp.append(qslerp(keyq[i], keyq[i + 1], t))
qexp.append(keyq[-1])
return np.array(qexp)
def findkeyq(qarr, kpcs, nkey=10, pc_cyl_ptile=25, pc_ptile=99, pc=0):
otherpcs = list(set(np.arange(kpcs.shape[1])) - {pc})
pcr = np.sqrt(np.sum(kpcs[:, otherpcs] ** 2, axis=1))
mask = (pcr < np.percentile(pcr, pc_cyl_ptile)) & (
np.abs(kpcs[:, pc]) < np.percentile(np.abs(kpcs[:, pc]), pc_ptile))
mn, mx = np.min(kpcs[mask, pc]), np.max(kpcs[mask, pc])
bins = np.linspace(mn, mx, nkey)
idx = np.digitize(kpcs[mask, pc], bins) - 1
uidx, uidxcnt = np.unique(idx, return_counts=True)
keyq = []
for i in uidx[uidxcnt >= 10]:
kq = meanq(qarr[mask, :][idx == i, :])
keyq.append(kq)
return np.array(keyq)
def dualquat(q, t):
assert q.shape[0] == t.shape[0]
dq = np.zeros(q.shape, dtype=np.complex128)
dq.real = q
dq.imag[:, 1:] = t
<|code_end|>
using the current file's imports:
import numpy as np
from .quat_numba import distq
from .quat_numba import qslerp
from .quat_numba import qtimes
from .quat import meanq
and any relevant context from other files:
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=False, nopython=True, nogil=True)
# def distq(q1, q2):
# pi_half = np.pi / 2
# v = np.abs(np.sum(q1 * q2))
# v = np.clip(0, 1.0, v)
# v = np.arccos(v)
# v *= 2
# # msk = v > pi_half
# # v[msk] = np.pi - v[msk]
# return v
#
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=True, nopython=True, nogil=True)
# def qslerp(q1, q2, t, longest=False):
# cos_half_theta = np.dot(q1, q2)
# if cos_half_theta >= 1.0:
# return q1.copy()
# if longest:
# if cos_half_theta > 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# elif cos_half_theta < 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# half_theta = np.arccos(cos_half_theta)
# sin_half_theta = np.sqrt(1 - cos_half_theta * cos_half_theta)
# if np.abs(sin_half_theta) < 1E-12:
# return (q1 + q2) / 2
# a = np.sin((1 - t) * half_theta)
# b = np.sin(t * half_theta)
# return (q1 * a + q2 * b) / sin_half_theta
#
# Path: pyem/geom/quat_numba.py
# @numba.guvectorize(["void(float64[:], float64[:], float64[:])"],
# "(m),(m)->(m)", nopython=True, cache=False)
# def qtimes(q1, q2, q3):
# _qtimes(q1, q2, q3)
#
# Path: pyem/geom/quat.py
# def meanq(q, w=None):
# if w is None:
# return np.linalg.eigh(np.einsum('ij,ik->...jk', q, q))[1][:, -1]
# else:
# return np.linalg.eigh(np.einsum('ij,ik,i->...jk', q, q, w))[1][:, -1]
. Output only the next line. | dq.imag = qtimes(dq.imag, dq.real) * 0.5 |
Using the snippet: <|code_start|>
def isrotation(r, tol=1e-6):
"""Check for valid rotation matrix"""
check = np.identity(3, dtype=r.dtype) - np.dot(r.T, r)
if tol is None:
return check
return np.linalg.norm(check) < tol
def qslerp_mult_balanced(keyq, steps_per_deg=10):
qexp = []
for i in range(0, len(keyq) - 1):
ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg)
for t in np.arange(0, 1, 1 / ninterp):
qexp.append(qslerp(keyq[i], keyq[i + 1], t))
qexp.append(keyq[-1])
return np.array(qexp)
def findkeyq(qarr, kpcs, nkey=10, pc_cyl_ptile=25, pc_ptile=99, pc=0):
otherpcs = list(set(np.arange(kpcs.shape[1])) - {pc})
pcr = np.sqrt(np.sum(kpcs[:, otherpcs] ** 2, axis=1))
mask = (pcr < np.percentile(pcr, pc_cyl_ptile)) & (
np.abs(kpcs[:, pc]) < np.percentile(np.abs(kpcs[:, pc]), pc_ptile))
mn, mx = np.min(kpcs[mask, pc]), np.max(kpcs[mask, pc])
bins = np.linspace(mn, mx, nkey)
idx = np.digitize(kpcs[mask, pc], bins) - 1
uidx, uidxcnt = np.unique(idx, return_counts=True)
keyq = []
for i in uidx[uidxcnt >= 10]:
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from .quat_numba import distq
from .quat_numba import qslerp
from .quat_numba import qtimes
from .quat import meanq
and context (class names, function names, or code) available:
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=False, nopython=True, nogil=True)
# def distq(q1, q2):
# pi_half = np.pi / 2
# v = np.abs(np.sum(q1 * q2))
# v = np.clip(0, 1.0, v)
# v = np.arccos(v)
# v *= 2
# # msk = v > pi_half
# # v[msk] = np.pi - v[msk]
# return v
#
# Path: pyem/geom/quat_numba.py
# @numba.jit(cache=True, nopython=True, nogil=True)
# def qslerp(q1, q2, t, longest=False):
# cos_half_theta = np.dot(q1, q2)
# if cos_half_theta >= 1.0:
# return q1.copy()
# if longest:
# if cos_half_theta > 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# elif cos_half_theta < 0:
# cos_half_theta = -cos_half_theta
# q1 = -q1
# half_theta = np.arccos(cos_half_theta)
# sin_half_theta = np.sqrt(1 - cos_half_theta * cos_half_theta)
# if np.abs(sin_half_theta) < 1E-12:
# return (q1 + q2) / 2
# a = np.sin((1 - t) * half_theta)
# b = np.sin(t * half_theta)
# return (q1 * a + q2 * b) / sin_half_theta
#
# Path: pyem/geom/quat_numba.py
# @numba.guvectorize(["void(float64[:], float64[:], float64[:])"],
# "(m),(m)->(m)", nopython=True, cache=False)
# def qtimes(q1, q2, q3):
# _qtimes(q1, q2, q3)
#
# Path: pyem/geom/quat.py
# def meanq(q, w=None):
# if w is None:
# return np.linalg.eigh(np.einsum('ij,ik->...jk', q, q))[1][:, -1]
# else:
# return np.linalg.eigh(np.einsum('ij,ik,i->...jk', q, q, w))[1][:, -1]
. Output only the next line. | kq = meanq(qarr[mask, :][idx == i, :]) |
Given the following code snippet before the placeholder: <|code_start|>
class TestUnordered:
class UnorderedSchema(Schema):
name = fields.Str()
email = fields.Str()
class Meta:
ordered = False
def test_unordered_dump_returns_dict(self):
schema = self.UnorderedSchema()
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from marshmallow import fields, Schema, EXCLUDE
from tests.base import User
import datetime as dt
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: tests/base.py
# class User:
# SPECIES = "Homo sapiens"
#
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# self.name = name
# self.age = age
# # A naive datetime
# self.created = dt.datetime(2013, 11, 10, 14, 20, 58)
# # A TZ-aware datetime
# self.updated = central.localize(
# dt.datetime(2013, 11, 10, 14, 20, 58), is_dst=False
# )
# self.id = id_
# self.homepage = homepage
# self.email = email
# self.balance = balance
# self.registered = True
# self.hair_colors = ["black", "brown", "blond", "redhead"]
# self.sex_choices = ("male", "female")
# self.finger_count = 10
# self.uid = uuid.uuid1()
# self.time_registered = time_registered or dt.time(1, 23, 45, 6789)
# self.birthdate = birthdate or dt.date(2013, 1, 23)
# self.birthtime = birthtime or dt.time(0, 1, 2, 3333)
# self.activation_date = dt.date(2013, 12, 11)
# self.sex = sex
# self.employer = employer
# self.relatives = []
# self.various_data = various_data or {
# "pets": ["cat", "dog"],
# "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006",
# }
#
# @property
# def since_created(self):
# return dt.datetime(2013, 11, 24) - self.created
#
# def __repr__(self):
# return f"<User {self.name}>"
. Output only the next line. | u = User("steve", email="steve@steve.steve") |
Based on the snippet: <|code_start|>"""Tests for field serialization."""
class DateTimeList:
def __init__(self, dtimes):
self.dtimes = dtimes
class IntegerList:
def __init__(self, ints):
self.ints = ints
class DateTimeIntegerTuple:
def __init__(self, dtime_int):
self.dtime_int = dtime_int
class TestFieldSerialization:
@pytest.fixture
def user(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple, OrderedDict
from marshmallow import Schema, fields, missing as missing_
from tests.base import User, ALL_FIELDS, central
import datetime as dt
import itertools
import decimal
import uuid
import ipaddress
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | return User("Foo", email="foo@bar.com", age=42) |
Predict the next line for this snippet: <|code_start|> 'Elements of "tuple_fields" must be subclasses or '
"instances of marshmallow.base.FieldABC."
)
with pytest.raises(ValueError, match=expected_msg):
fields.Tuple([ASchema])
def test_serialize_does_not_apply_validators(self, user):
field = fields.Field(validate=lambda x: False)
# No validation error raised
assert field.serialize("age", user) == user.age
def test_constant_field_serialization(self, user):
field = fields.Constant("something")
assert field.serialize("whatever", user) == "something"
def test_constant_is_always_included_in_serialized_data(self):
class MySchema(Schema):
foo = fields.Constant(42)
sch = MySchema()
assert sch.dump({"bar": 24})["foo"] == 42
assert sch.dump({"foo": 24})["foo"] == 42
def test_constant_field_serialize_when_omitted(self):
class MiniUserSchema(Schema):
name = fields.Constant("bill")
s = MiniUserSchema()
assert s.dump({})["name"] == "bill"
<|code_end|>
with the help of current file imports:
from collections import namedtuple, OrderedDict
from marshmallow import Schema, fields, missing as missing_
from tests.base import User, ALL_FIELDS, central
import datetime as dt
import itertools
import decimal
import uuid
import ipaddress
import pytest
and context from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
, which may contain function names, class names, or code. Output only the next line. | @pytest.mark.parametrize("FieldClass", ALL_FIELDS) |
Given the code snippet: <|code_start|> name = fields.Field(data_key="")
schema = MySchema()
assert schema.dump({"name": "Grace"}) == {"": "Grace"}
def test_serialize_with_attribute_and_data_key_uses_data_key(self):
class ConfusedDumpToAndAttributeSerializer(Schema):
name = fields.String(data_key="FullName")
username = fields.String(attribute="uname", data_key="UserName")
years = fields.Integer(attribute="le_wild_age", data_key="Years")
data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999}
result = ConfusedDumpToAndAttributeSerializer().dump(data)
assert result == {
"FullName": "Mick",
"UserName": "mick_the_awesome",
"Years": 999,
}
@pytest.mark.parametrize("fmt", ["rfc", "rfc822"])
@pytest.mark.parametrize(
("value", "expected"),
[
(dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"),
(
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
"Sun, 10 Nov 2013 01:23:45 +0000",
),
(
<|code_end|>
, generate the next line using the imports in this file:
from collections import namedtuple, OrderedDict
from marshmallow import Schema, fields, missing as missing_
from tests.base import User, ALL_FIELDS, central
import datetime as dt
import itertools
import decimal
import uuid
import ipaddress
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False), |
Continue the code snippet: <|code_start|> assert result.microseconds == 0
field = fields.TimeDelta(fields.TimeDelta.MINUTES)
result = field.deserialize(1441)
assert isinstance(result, dt.timedelta)
assert result.days == 1
assert result.seconds == 60
assert result.microseconds == 0
field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS)
result = field.deserialize(123456)
assert isinstance(result, dt.timedelta)
assert result.days == 0
assert result.seconds == 123
assert result.microseconds == 456000
@pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999])
def test_invalid_timedelta_field_deserialization(self, in_value):
field = fields.TimeDelta(fields.TimeDelta.DAYS)
with pytest.raises(ValidationError) as excinfo:
field.deserialize(in_value)
assert excinfo.value.args[0] == "Not a valid period of time."
@pytest.mark.parametrize("format", (None, "%Y-%m-%d"))
def test_date_field_deserialization(self, format):
field = fields.Date(format=format)
d = dt.date(2014, 8, 21)
iso_date = d.isoformat()
result = field.deserialize(iso_date)
assert type(result) == dt.date
<|code_end|>
. Use current file imports:
import datetime as dt
import uuid
import ipaddress
import decimal
import math
import pytest
from marshmallow import EXCLUDE, INCLUDE, RAISE, fields, Schema, validate
from marshmallow.exceptions import ValidationError
from marshmallow.validate import Equal
from tests.base import assert_date_equal, assert_time_equal, central, ALL_FIELDS
and context (classes, functions, or code) from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | assert_date_equal(result, d) |
Given the code snippet: <|code_start|> ),
(
"rfc",
central,
"Sun, 10 Nov 2013 01:23:45 -0300",
dt.datetime(2013, 11, 9, 22, 23, 45),
),
],
)
def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected):
field = fields.NaiveDateTime(format=fmt, timezone=timezone)
assert field.deserialize(value) == expected
@pytest.mark.parametrize("timezone", (dt.timezone.utc, central))
@pytest.mark.parametrize(
("fmt", "value"),
[("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")],
)
def test_aware_datetime_default_timezone(self, fmt, timezone, value):
field = fields.AwareDateTime(format=fmt, default_timezone=timezone)
assert field.deserialize(value) == dt.datetime(
2013, 11, 10, 1, 23, 45, tzinfo=timezone
)
def test_time_field_deserialization(self):
field = fields.Time()
t = dt.time(1, 23, 45)
t_formatted = t.isoformat()
result = field.deserialize(t_formatted)
assert isinstance(result, dt.time)
<|code_end|>
, generate the next line using the imports in this file:
import datetime as dt
import uuid
import ipaddress
import decimal
import math
import pytest
from marshmallow import EXCLUDE, INCLUDE, RAISE, fields, Schema, validate
from marshmallow.exceptions import ValidationError
from marshmallow.validate import Equal
from tests.base import assert_date_equal, assert_time_equal, central, ALL_FIELDS
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | assert_time_equal(result, t) |
Given the code snippet: <|code_start|> field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d")
assert field.deserialize(datestring) == dt.datetime(
2019, 1, 2, 10, 11, 12, 123456
)
field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d")
assert field.deserialize(datestring) == dt.datetime(
2019, 1, 2, 10, 11, 12, 123456
)
field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d")
with pytest.raises(ValidationError, match="Not a valid aware datetime."):
field.deserialize(datestring)
@pytest.mark.parametrize("fmt", ["rfc", "rfc822"])
@pytest.mark.parametrize(
("value", "expected", "aware"),
[
(
"Sun, 10 Nov 2013 01:23:45 -0000",
dt.datetime(2013, 11, 10, 1, 23, 45),
False,
),
(
"Sun, 10 Nov 2013 01:23:45 +0000",
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
True,
),
(
"Sun, 10 Nov 2013 01:23:45 -0600",
<|code_end|>
, generate the next line using the imports in this file:
import datetime as dt
import uuid
import ipaddress
import decimal
import math
import pytest
from marshmallow import EXCLUDE, INCLUDE, RAISE, fields, Schema, validate
from marshmallow.exceptions import ValidationError
from marshmallow.validate import Equal
from tests.base import assert_date_equal, assert_time_equal, central, ALL_FIELDS
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False), |
Predict the next line after this snippet: <|code_start|>
def test_is_keyed_tuple():
Point = namedtuple("Point", ["x", "y"])
p = Point(24, 42)
assert utils.is_keyed_tuple(p) is True
t = (24, 42)
assert utils.is_keyed_tuple(t) is False
d = {"x": 42, "y": 24}
assert utils.is_keyed_tuple(d) is False
s = "xy"
assert utils.is_keyed_tuple(s) is False
lst = [24, 42]
assert utils.is_keyed_tuple(lst) is False
def test_is_collection():
assert utils.is_collection([1, "foo", {}]) is True
assert utils.is_collection(("foo", 2.3)) is True
assert utils.is_collection({"foo": "bar"}) is False
@pytest.mark.parametrize(
("value", "expected"),
[
(dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"),
(
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
"Sun, 10 Nov 2013 01:23:45 +0000",
),
(
<|code_end|>
using the current file's imports:
import datetime as dt
import pytest
from collections import namedtuple
from functools import partial
from copy import copy, deepcopy
from marshmallow import utils, fields, Schema
from tests.base import central, assert_time_equal, assert_date_equal
and any relevant context from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
. Output only the next line. | central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False), |
Here is a snippet: <|code_start|> (
"2013-11-10T01:23:45+00:00",
dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc),
),
(
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251
"2013-11-10T01:23:45.123+00:00",
dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc),
),
(
"2013-11-10T01:23:45.123456+00:00",
dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc),
),
(
"2013-11-10T01:23:45-06:00",
central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False),
),
],
)
def test_from_iso_datetime(value, expected):
result = utils.from_iso_datetime(value)
assert type(result) == dt.datetime
assert result == expected
def test_from_iso_time_with_microseconds():
t = dt.time(1, 23, 45, 6789)
formatted = t.isoformat()
result = utils.from_iso_time(formatted)
assert type(result) == dt.time
<|code_end|>
. Write the next line using the current file imports:
import datetime as dt
import pytest
from collections import namedtuple
from functools import partial
from copy import copy, deepcopy
from marshmallow import utils, fields, Schema
from tests.base import central, assert_time_equal, assert_date_equal
and context from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
, which may include functions, classes, or code. Output only the next line. | assert_time_equal(result, t) |
Predict the next line for this snippet: <|code_start|> ),
],
)
def test_from_iso_datetime(value, expected):
result = utils.from_iso_datetime(value)
assert type(result) == dt.datetime
assert result == expected
def test_from_iso_time_with_microseconds():
t = dt.time(1, 23, 45, 6789)
formatted = t.isoformat()
result = utils.from_iso_time(formatted)
assert type(result) == dt.time
assert_time_equal(result, t)
def test_from_iso_time_without_microseconds():
t = dt.time(1, 23, 45)
formatted = t.isoformat()
result = utils.from_iso_time(formatted)
assert type(result) == dt.time
assert_time_equal(result, t)
def test_from_iso_date():
d = dt.date(2014, 8, 21)
iso_date = d.isoformat()
result = utils.from_iso_date(iso_date)
assert type(result) == dt.date
<|code_end|>
with the help of current file imports:
import datetime as dt
import pytest
from collections import namedtuple
from functools import partial
from copy import copy, deepcopy
from marshmallow import utils, fields, Schema
from tests.base import central, assert_time_equal, assert_date_equal
and context from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
# SPECIES = "Homo sapiens"
# def assert_date_equal(d1, d2):
# def assert_time_equal(t1, t2):
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# def since_created(self):
# def __repr__(self):
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# def __contains__(self, item):
# def __init__(self, foo):
# def __eq__(self, other):
# def __str__(self):
# def _serialize(self, value, attr, obj):
# def get_lowername(obj):
# def get_is_old(self, obj):
# def make_user(self, data, **kwargs):
# def get_is_old(self, obj):
# def dumps(val):
# def loads(val):
# class User:
# class Blog:
# class DummyModel:
# class Uppercased(fields.Field):
# class UserSchema(Schema):
# class Meta:
# class UserMetaSchema(Schema):
# class Meta:
# class UserExcludeSchema(UserSchema):
# class Meta:
# class UserAdditionalSchema(Schema):
# class Meta:
# class UserIntSchema(UserSchema):
# class UserFloatStringSchema(UserSchema):
# class ExtendedUserSchema(UserSchema):
# class UserRelativeUrlSchema(UserSchema):
# class BlogSchema(Schema):
# class BlogUserMetaSchema(Schema):
# class BlogSchemaMeta(Schema):
# class Meta:
# class BlogOnlySchema(Schema):
# class BlogSchemaExclude(BlogSchema):
# class BlogSchemaOnlyExclude(BlogSchema):
# class mockjson: # noqa
, which may contain function names, class names, or code. Output only the next line. | assert_date_equal(result, d) |
Predict the next line after this snippet: <|code_start|> assert schema2.fields["foo"].value_field.root == schema2
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357
def test_datetime_list_inner_format(self, schema):
class MySchema(Schema):
foo = fields.List(fields.DateTime())
bar = fields.Tuple((fields.DateTime(),))
baz = fields.List(fields.Date())
qux = fields.Tuple((fields.Date(),))
class Meta:
datetimeformat = "iso8601"
dateformat = "iso8601"
schema = MySchema()
for field_name in ("foo", "baz"):
assert schema.fields[field_name].inner.format == "iso8601"
for field_name in ("bar", "qux"):
assert schema.fields[field_name].tuple_fields[0].format == "iso8601"
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/1808
def test_field_named_parent_has_root(self, schema):
class MySchema(Schema):
parent = fields.Field()
schema = MySchema()
assert schema.fields["parent"].root == schema
class TestMetadata:
<|code_end|>
using the current file's imports:
import pytest
from marshmallow import (
fields,
Schema,
ValidationError,
EXCLUDE,
INCLUDE,
RAISE,
missing,
)
from marshmallow.exceptions import StringNotCollectionError
from tests.base import ALL_FIELDS
and any relevant context from other files:
# Path: tests/base.py
# ALL_FIELDS = [
# fields.String,
# fields.Integer,
# fields.Boolean,
# fields.Float,
# fields.Number,
# fields.DateTime,
# fields.Time,
# fields.Date,
# fields.TimeDelta,
# fields.Dict,
# fields.Url,
# fields.Email,
# fields.UUID,
# fields.Decimal,
# fields.IP,
# fields.IPv4,
# fields.IPv6,
# fields.IPInterface,
# fields.IPv4Interface,
# fields.IPv6Interface,
# ]
. Output only the next line. | @pytest.mark.parametrize("FieldClass", ALL_FIELDS) |
Given the code snippet: <|code_start|>"""Pytest fixtures that are available in all test modules."""
@pytest.fixture
def user():
return User(name="Monty", age=42.3, homepage="http://monty.python.org/")
@pytest.fixture
def blog(user):
col1 = User(name="Mick", age=123)
col2 = User(name="Keith", age=456)
return Blog(
"Monty's blog",
user=user,
categories=["humor", "violence"],
collaborators=[col1, col2],
)
@pytest.fixture
def serialized_user(user):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from tests.base import User, UserSchema, Blog
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# class User:
# SPECIES = "Homo sapiens"
#
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# self.name = name
# self.age = age
# # A naive datetime
# self.created = dt.datetime(2013, 11, 10, 14, 20, 58)
# # A TZ-aware datetime
# self.updated = central.localize(
# dt.datetime(2013, 11, 10, 14, 20, 58), is_dst=False
# )
# self.id = id_
# self.homepage = homepage
# self.email = email
# self.balance = balance
# self.registered = True
# self.hair_colors = ["black", "brown", "blond", "redhead"]
# self.sex_choices = ("male", "female")
# self.finger_count = 10
# self.uid = uuid.uuid1()
# self.time_registered = time_registered or dt.time(1, 23, 45, 6789)
# self.birthdate = birthdate or dt.date(2013, 1, 23)
# self.birthtime = birthtime or dt.time(0, 1, 2, 3333)
# self.activation_date = dt.date(2013, 12, 11)
# self.sex = sex
# self.employer = employer
# self.relatives = []
# self.various_data = various_data or {
# "pets": ["cat", "dog"],
# "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006",
# }
#
# @property
# def since_created(self):
# return dt.datetime(2013, 11, 24) - self.created
#
# def __repr__(self):
# return f"<User {self.name}>"
#
# class UserSchema(Schema):
# name = fields.String()
# age = fields.Float() # type: fields.Field
# created = fields.DateTime()
# created_formatted = fields.DateTime(
# format="%Y-%m-%d", attribute="created", dump_only=True
# )
# created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
# updated = fields.DateTime()
# species = fields.String(attribute="SPECIES")
# id = fields.String(dump_default="no-id")
# uppername = Uppercased(attribute="name", dump_only=True)
# homepage = fields.Url()
# email = fields.Email()
# balance = fields.Decimal()
# is_old = fields.Method("get_is_old") # type: fields.Field
# lowername = fields.Function(get_lowername)
# registered = fields.Boolean()
# hair_colors = fields.List(fields.Raw)
# sex_choices = fields.List(fields.Raw)
# finger_count = fields.Integer()
# uid = fields.UUID()
# time_registered = fields.Time()
# birthdate = fields.Date()
# birthtime = fields.Time()
# activation_date = fields.Date()
# since_created = fields.TimeDelta()
# sex = fields.Str(validate=validate.OneOf(["male", "female"]))
# various_data = fields.Dict()
#
# class Meta:
# render_module = simplejson
#
# def get_is_old(self, obj):
# if obj is None:
# return missing
# if isinstance(obj, dict):
# age = obj.get("age")
# else:
# age = obj.age
# try:
# return age > 80
# except TypeError as te:
# raise ValidationError(str(te)) from te
#
# @post_load
# def make_user(self, data, **kwargs):
# return User(**data)
#
# class Blog:
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# self.title = title
# self.user = user
# self.collaborators = collaborators or [] # List/tuple of users
# self.categories = categories
# self.id = id_
#
# def __contains__(self, item):
# return item.name in [each.name for each in self.collaborators]
. Output only the next line. | return UserSchema().dump(user) |
Given the following code snippet before the placeholder: <|code_start|>"""Pytest fixtures that are available in all test modules."""
@pytest.fixture
def user():
return User(name="Monty", age=42.3, homepage="http://monty.python.org/")
@pytest.fixture
def blog(user):
col1 = User(name="Mick", age=123)
col2 = User(name="Keith", age=456)
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from tests.base import User, UserSchema, Blog
and context including class names, function names, and sometimes code from other files:
# Path: tests/base.py
# class User:
# SPECIES = "Homo sapiens"
#
# def __init__(
# self,
# name,
# age=0,
# id_=None,
# homepage=None,
# email=None,
# registered=True,
# time_registered=None,
# birthdate=None,
# birthtime=None,
# balance=100,
# sex="male",
# employer=None,
# various_data=None,
# ):
# self.name = name
# self.age = age
# # A naive datetime
# self.created = dt.datetime(2013, 11, 10, 14, 20, 58)
# # A TZ-aware datetime
# self.updated = central.localize(
# dt.datetime(2013, 11, 10, 14, 20, 58), is_dst=False
# )
# self.id = id_
# self.homepage = homepage
# self.email = email
# self.balance = balance
# self.registered = True
# self.hair_colors = ["black", "brown", "blond", "redhead"]
# self.sex_choices = ("male", "female")
# self.finger_count = 10
# self.uid = uuid.uuid1()
# self.time_registered = time_registered or dt.time(1, 23, 45, 6789)
# self.birthdate = birthdate or dt.date(2013, 1, 23)
# self.birthtime = birthtime or dt.time(0, 1, 2, 3333)
# self.activation_date = dt.date(2013, 12, 11)
# self.sex = sex
# self.employer = employer
# self.relatives = []
# self.various_data = various_data or {
# "pets": ["cat", "dog"],
# "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006",
# }
#
# @property
# def since_created(self):
# return dt.datetime(2013, 11, 24) - self.created
#
# def __repr__(self):
# return f"<User {self.name}>"
#
# class UserSchema(Schema):
# name = fields.String()
# age = fields.Float() # type: fields.Field
# created = fields.DateTime()
# created_formatted = fields.DateTime(
# format="%Y-%m-%d", attribute="created", dump_only=True
# )
# created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
# updated = fields.DateTime()
# species = fields.String(attribute="SPECIES")
# id = fields.String(dump_default="no-id")
# uppername = Uppercased(attribute="name", dump_only=True)
# homepage = fields.Url()
# email = fields.Email()
# balance = fields.Decimal()
# is_old = fields.Method("get_is_old") # type: fields.Field
# lowername = fields.Function(get_lowername)
# registered = fields.Boolean()
# hair_colors = fields.List(fields.Raw)
# sex_choices = fields.List(fields.Raw)
# finger_count = fields.Integer()
# uid = fields.UUID()
# time_registered = fields.Time()
# birthdate = fields.Date()
# birthtime = fields.Time()
# activation_date = fields.Date()
# since_created = fields.TimeDelta()
# sex = fields.Str(validate=validate.OneOf(["male", "female"]))
# various_data = fields.Dict()
#
# class Meta:
# render_module = simplejson
#
# def get_is_old(self, obj):
# if obj is None:
# return missing
# if isinstance(obj, dict):
# age = obj.get("age")
# else:
# age = obj.age
# try:
# return age > 80
# except TypeError as te:
# raise ValidationError(str(te)) from te
#
# @post_load
# def make_user(self, data, **kwargs):
# return User(**data)
#
# class Blog:
# def __init__(self, title, user, collaborators=None, categories=None, id_=None):
# self.title = title
# self.user = user
# self.collaborators = collaborators or [] # List/tuple of users
# self.categories = categories
# self.id = id_
#
# def __contains__(self, item):
# return item.name in [each.name for each in self.collaborators]
. Output only the next line. | return Blog( |
Using the snippet: <|code_start|># FIXME: param _raise ??
def merge(repository, ref, msg='automerge', commit_msg='',
no_ff=False, _raise=True, _env=None):
# msg, commit_msg makes multiline commit message
git = git_with_repo(repository)
git_merge = git.bake('merge', ref, no_ff=no_ff)
if msg:
git_merge = git_merge.bake(m=msg)
if commit_msg:
git_merge = git_merge.bake(m=commit_msg)
return git_merge(env=_env)
def merge_tree(repository, ours, theirs):
theirs = repository.revparse_single(theirs)
theirs_tree = theirs.tree
ours = repository.revparse_single(ours)
ours_tree = ours.tree
merge_base_oid = repository.merge_base(str(theirs.id),
str(ours.id))
merge_base_tree = repository.get(str(merge_base_oid)).tree \
if merge_base_oid else ours_tree
index = ours_tree.merge(theirs_tree, merge_base_tree)
return format_index(index)
def merge_head(repository, ref):
target = repository.revparse_single(ref)
oid = target.id
analysis = repository.merge_analysis(oid)
<|code_end|>
, determine the next line of code. You have imports:
from ellen.utils.process import git_with_repo
from ellen.utils.format import format_merge_analysis, format_index
and context (class names, function names, or code) available:
# Path: ellen/utils/process.py
# def git_with_repo(repository):
# git_dir = repository.path
# work_tree = repository.workdir
# return git_with_path(git_dir, work_tree)
#
# Path: ellen/utils/format.py
# def format_merge_analysis(analysis):
# from pygit2 import GIT_MERGE_ANALYSIS_FASTFORWARD, GIT_MERGE_ANALYSIS_UP_TO_DATE
# d = {}
# d['is_uptodate'] = analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE
# d['is_fastforward'] = analysis & GIT_MERGE_ANALYSIS_FASTFORWARD
# return d
#
# def format_index(merge_index):
# d = {}
# d['has_conflicts'] = merge_index.has_conflicts
# return d
. Output only the next line. | return format_merge_analysis(analysis) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# FIXME: param _raise ??
def merge(repository, ref, msg='automerge', commit_msg='',
no_ff=False, _raise=True, _env=None):
# msg, commit_msg makes multiline commit message
git = git_with_repo(repository)
git_merge = git.bake('merge', ref, no_ff=no_ff)
if msg:
git_merge = git_merge.bake(m=msg)
if commit_msg:
git_merge = git_merge.bake(m=commit_msg)
return git_merge(env=_env)
def merge_tree(repository, ours, theirs):
theirs = repository.revparse_single(theirs)
theirs_tree = theirs.tree
ours = repository.revparse_single(ours)
ours_tree = ours.tree
merge_base_oid = repository.merge_base(str(theirs.id),
str(ours.id))
merge_base_tree = repository.get(str(merge_base_oid)).tree \
if merge_base_oid else ours_tree
index = ours_tree.merge(theirs_tree, merge_base_tree)
<|code_end|>
, predict the next line using imports from the current file:
from ellen.utils.process import git_with_repo
from ellen.utils.format import format_merge_analysis, format_index
and context including class names, function names, and sometimes code from other files:
# Path: ellen/utils/process.py
# def git_with_repo(repository):
# git_dir = repository.path
# work_tree = repository.workdir
# return git_with_path(git_dir, work_tree)
#
# Path: ellen/utils/format.py
# def format_merge_analysis(analysis):
# from pygit2 import GIT_MERGE_ANALYSIS_FASTFORWARD, GIT_MERGE_ANALYSIS_UP_TO_DATE
# d = {}
# d['is_uptodate'] = analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE
# d['is_fastforward'] = analysis & GIT_MERGE_ANALYSIS_FASTFORWARD
# return d
#
# def format_index(merge_index):
# d = {}
# d['has_conflicts'] = merge_index.has_conflicts
# return d
. Output only the next line. | return format_index(index) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def list_tags(repository, name_only=None):
"""git tag command, pygit2 wrapper"""
tags = []
refs = repository.listall_references()
for ref in refs:
if ref.startswith("refs/tags/"):
if name_only:
tags.append(ref.rpartition('/')[-1])
continue
# this is a tag but maybe a lightweight tag
tag_obj = repository.revparse_single(ref)
if tag_obj and tag_obj.type == GIT_OBJ_COMMIT:
# lightweight tag
tags.append(format_lw_tag(ref, tag_obj, repository))
elif tag_obj and tag_obj.type == GIT_OBJ_TAG:
<|code_end|>
, generate the next line using the imports in this file:
from pygit2 import GIT_OBJ_TAG
from pygit2 import GIT_OBJ_COMMIT
from pygit2 import Signature
from ellen.utils.format import format_tag
from ellen.utils.format import format_lw_tag
and context (functions, classes, or occasionally code) from other files:
# Path: ellen/utils/format.py
# def format_tag(tag, repository):
# d = {}
# d['name'] = tag.name
# d['tag'] = tag.name
# d['target'] = str(tag.target)
# d['type'] = 'tag'
# d['tagger'] = _format_pygit2_signature(tag.tagger)
# d['message'], _, d['body'] = tag.message.strip().partition('\n\n')
# d['sha'] = str(tag.id)
# return d
#
# Path: ellen/utils/format.py
# def format_lw_tag(ref, tag, repository):
# """format lightweight tag"""
# d = {}
# d['name'] = _format_short_reference_name(ref)
# d['tag'] = d['name']
# d['object'] = str(tag.id)
# d['type'] = 'commit' # really useful ?
# d['commit'] = format_commit(tag, repository)
# return d
. Output only the next line. | tags.append(format_tag(tag_obj, repository)) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def list_tags(repository, name_only=None):
"""git tag command, pygit2 wrapper"""
tags = []
refs = repository.listall_references()
for ref in refs:
if ref.startswith("refs/tags/"):
if name_only:
tags.append(ref.rpartition('/')[-1])
continue
# this is a tag but maybe a lightweight tag
tag_obj = repository.revparse_single(ref)
if tag_obj and tag_obj.type == GIT_OBJ_COMMIT:
# lightweight tag
<|code_end|>
, generate the next line using the imports in this file:
from pygit2 import GIT_OBJ_TAG
from pygit2 import GIT_OBJ_COMMIT
from pygit2 import Signature
from ellen.utils.format import format_tag
from ellen.utils.format import format_lw_tag
and context (functions, classes, or occasionally code) from other files:
# Path: ellen/utils/format.py
# def format_tag(tag, repository):
# d = {}
# d['name'] = tag.name
# d['tag'] = tag.name
# d['target'] = str(tag.target)
# d['type'] = 'tag'
# d['tagger'] = _format_pygit2_signature(tag.tagger)
# d['message'], _, d['body'] = tag.message.strip().partition('\n\n')
# d['sha'] = str(tag.id)
# return d
#
# Path: ellen/utils/format.py
# def format_lw_tag(ref, tag, repository):
# """format lightweight tag"""
# d = {}
# d['name'] = _format_short_reference_name(ref)
# d['tag'] = d['name']
# d['object'] = str(tag.id)
# d['type'] = 'commit' # really useful ?
# d['commit'] = format_commit(tag, repository)
# return d
. Output only the next line. | tags.append(format_lw_tag(ref, tag_obj, repository)) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from ellen.utils.text import highlight_code # no use yet
m = magic._get_magic_type(True)
magic.magic_setflags(m.cookie,
magic.MAGIC_NONE |
magic.MAGIC_NO_CHECK_COMPRESS |
magic.MAGIC_NO_CHECK_TAR |
magic.MAGIC_NO_CHECK_SOFT |
magic.MAGIC_NO_CHECK_APPTYPE |
magic.MAGIC_NO_CHECK_ELF |
magic.MAGIC_NO_CHECK_FORTRAN |
magic.MAGIC_NO_CHECK_TROFF |
magic.MAGIC_NO_CHECK_TOKENS |
magic.MAGIC_MIME)
def format_obj(obj, repository):
<|code_end|>
, generate the next line using the imports in this file:
import re
import sys
import mime
import magic
from datetime import datetime
from ellen.utils.git import PYGIT2_OBJ_TYPE
from ellen.utils.text import trunc_utf8
from pygit2 import GIT_MERGE_ANALYSIS_FASTFORWARD, GIT_MERGE_ANALYSIS_UP_TO_DATE
and context (functions, classes, or occasionally code) from other files:
# Path: ellen/utils/git.py
# PYGIT2_OBJ_TYPE = {
# GIT_OBJ_COMMIT: 'commit',
# GIT_OBJ_BLOB: 'blob',
# GIT_OBJ_TREE: 'tree',
# GIT_OBJ_TAG: 'tag',
# }
#
# Path: ellen/utils/text.py
# def trunc_utf8(string, num, etc="..."):
# """truncate a utf-8 string, show as num chars.
# arg: string, a utf-8 encoding string; num, look like num chars
# return: a utf-8 string
# """
# try:
# gb = string.decode("utf8", "ignore")
# except UnicodeEncodeError: # Already decoded
# gb = string
# gb = gb.encode("gb18030", "ignore")
# if num >= len(gb):
# return string
# if etc:
# etc_len = len(etc.decode("utf8", "ignore").encode("gb18030", "ignore"))
# trunc_idx = num - etc_len
# else:
# trunc_idx = num
# ret = gb[:trunc_idx].decode("gb18030", "ignore").encode("utf8")
# if etc:
# ret += etc
# return ret
. Output only the next line. | func_name = 'format_' + PYGIT2_OBJ_TYPE[obj.type] |
Using the snippet: <|code_start|> # return hl_lines
res = text
res = res.splitlines()
#hl_lines = _blame_src_highlighted_lines(ref, path)
hl_lines = {}
blame = []
rev_data = {}
new_block = True
for line in res:
if new_block:
sha, old_no, line_no = line.split()[:3]
if sha not in rev_data:
rev_data[sha] = {}
rev_data[sha]['line_no'] = line_no
rev_data[sha]['old_no'] = old_no
new_block = False
elif line.startswith('author '):
_, _, author = line.partition(' ')
rev_data[sha]['author'] = author.strip()
elif line.startswith('author-time '):
_, _, time = line.partition(' ')
time = datetime.fromtimestamp(float(time)).strftime('%Y-%m-%d')
rev_data[sha]['time'] = time
elif line.startswith('author-mail '):
_, _, email = line.partition(' ')
email = RE_EMAIL.match(email).group('email')
rev_data[sha]['email'] = email
elif line.startswith('summary '):
_, _, summary = line.partition(' ')
rev_data[sha]['summary'] = summary.strip()
<|code_end|>
, determine the next line of code. You have imports:
import re
import sys
import mime
import magic
from datetime import datetime
from ellen.utils.git import PYGIT2_OBJ_TYPE
from ellen.utils.text import trunc_utf8
from pygit2 import GIT_MERGE_ANALYSIS_FASTFORWARD, GIT_MERGE_ANALYSIS_UP_TO_DATE
and context (class names, function names, or code) available:
# Path: ellen/utils/git.py
# PYGIT2_OBJ_TYPE = {
# GIT_OBJ_COMMIT: 'commit',
# GIT_OBJ_BLOB: 'blob',
# GIT_OBJ_TREE: 'tree',
# GIT_OBJ_TAG: 'tag',
# }
#
# Path: ellen/utils/text.py
# def trunc_utf8(string, num, etc="..."):
# """truncate a utf-8 string, show as num chars.
# arg: string, a utf-8 encoding string; num, look like num chars
# return: a utf-8 string
# """
# try:
# gb = string.decode("utf8", "ignore")
# except UnicodeEncodeError: # Already decoded
# gb = string
# gb = gb.encode("gb18030", "ignore")
# if num >= len(gb):
# return string
# if etc:
# etc_len = len(etc.decode("utf8", "ignore").encode("gb18030", "ignore"))
# trunc_idx = num - etc_len
# else:
# trunc_idx = num
# ret = gb[:trunc_idx].decode("gb18030", "ignore").encode("utf8")
# if etc:
# ret += etc
# return ret
. Output only the next line. | disp_summary = trunc_utf8( |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def blame_(repository, ref, path, lineno=None):
""" git blame """
git = git_with_repo(repository)
if lineno:
cmdstr = ('-L %s,%s --porcelain %s -- %s'
% (lineno, lineno, ref, path)) # start == end
else:
cmdstr = '-p -CM %s -- %s' % (ref, path)
ret = git.blame.call(cmdstr)
<|code_end|>
. Use current file imports:
(from ellen.utils.process import git_with_repo
from ellen.utils.format import (format_blame,
format_blame_hunk,
format_blob,
is_blob_binary)
from pygit2 import (GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES,
GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES))
and context including class names, function names, or small code snippets from other files:
# Path: ellen/utils/process.py
# def git_with_repo(repository):
# git_dir = repository.path
# work_tree = repository.workdir
# return git_with_path(git_dir, work_tree)
#
# Path: ellen/utils/format.py
# def format_blame(text, repository):
# RE_EMAIL = re.compile(r'<(?P<email>.*)>')
# # FIXME: highlight_code
# #def _blame_src_highlighted_lines(self, ref, path):
# # HIGHLIGHT_PATN = re.compile(
# # r'<a name="L-(\d+)"></a>(.*?)(?=<a name="L-(?:\d+)">)', re.DOTALL)
# # source_code = repository.show('%s:%s' % (ref, path))
# # source_code = source_code['data']
# # # TODO try to avoid having highlighted content here
# # hl_source_code = highlight_code(path, source_code)
# # hl_lines = dict(re.findall(HIGHLIGHT_PATN, hl_source_code))
# # return hl_lines
# res = text
# res = res.splitlines()
# #hl_lines = _blame_src_highlighted_lines(ref, path)
# hl_lines = {}
# blame = []
# rev_data = {}
# new_block = True
# for line in res:
# if new_block:
# sha, old_no, line_no = line.split()[:3]
# if sha not in rev_data:
# rev_data[sha] = {}
# rev_data[sha]['line_no'] = line_no
# rev_data[sha]['old_no'] = old_no
# new_block = False
# elif line.startswith('author '):
# _, _, author = line.partition(' ')
# rev_data[sha]['author'] = author.strip()
# elif line.startswith('author-time '):
# _, _, time = line.partition(' ')
# time = datetime.fromtimestamp(float(time)).strftime('%Y-%m-%d')
# rev_data[sha]['time'] = time
# elif line.startswith('author-mail '):
# _, _, email = line.partition(' ')
# email = RE_EMAIL.match(email).group('email')
# rev_data[sha]['email'] = email
# elif line.startswith('summary '):
# _, _, summary = line.partition(' ')
# rev_data[sha]['summary'] = summary.strip()
# disp_summary = trunc_utf8(
# summary.encode('utf-8'), 20).decode('utf-8', 'ignore')
# rev_data[sha]['disp_summary'] = disp_summary
# elif line.startswith('filename'):
# _, _, filename = line.partition(' ')
# rev_data[sha]['filename'] = filename
# filename = trunc_utf8(
# filename.strip().encode('utf-8'), 30).decode('utf-8', 'ignore')
# rev_data[sha]['disp_name'] = filename
# elif line.startswith('\t'):
# # Try to get an highlighted line of source code
# code_line = hl_lines.get(str(
# line_no), '').replace('\n', '').decode('utf-8', 'ignore')
# if not code_line:
# code_line = line[1:]
# blame.append((
# sha,
# rev_data[sha]['author'],
# rev_data[sha]['email'],
# rev_data[sha]['time'],
# rev_data[sha]['disp_summary'],
# rev_data[sha]['summary'],
# rev_data[sha]['line_no'],
# rev_data[sha]['old_no'],
# rev_data[sha]['filename'],
# rev_data[sha]['disp_name'],
# code_line,
# ))
# new_block = True
# return blame
#
# def format_blame_hunk(hunk, repository):
# d = {}
# d['lines_in_hunk'] = hunk.lines_in_hunk
# d['final_commit_id'] = hunk.final_commit_id
# d['final_start_line_number'] = hunk.final_start_line_number
# d['final_committer'] = _format_pygit2_signature(hunk.final_committer)
# d['orig_commit_id'] = hunk.orig_commit_id
# d['orig_path'] = hunk.orig_path
# d['orig_start_line_number'] = hunk.orig_start_line_number
# d['orig_committer'] = _format_pygit2_signature(hunk.orig_committer)
# d['boundary'] = hunk.boundary
# return d
#
# def format_blob(blob, repository):
# d = {}
# d['sha'] = str(blob.id)
# d['type'] = 'blob'
# d['data'] = blob.data
# d['size'] = blob.size
# d['binary'] = is_blob_binary(blob)
# return d
#
# def is_blob_binary(blob):
# is_binary = blob.is_binary
# if is_binary:
# content_type = magic.from_buffer(blob.data[:1024], mime=True)
# # FIXME: dirty hack for 'text/x-python'
# if content_type and content_type.startswith('text/'):
# is_binary = False
# else:
# plaintext = mime.Types[content_type] if content_type else None
# text = plaintext[0] if plaintext else None
# is_binary = text.is_binary if text else is_binary
# return is_binary
. Output only the next line. | result = format_blame(ret['stdout'], repository) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def clone_repository(url, path, bare=None, checkout_branch=None, mirror=None,
env=None, shared=None):
"""git clone command
NOTE: 因为`git clone`在本机上直接做硬链接,速度比pygit2.clone_repository快
"""
<|code_end|>
using the current file's imports:
from ellen.utils.process import git, git_with_repo
and any relevant context from other files:
# Path: ellen/utils/process.py
# def _shlex_split(cmd):
# def _call(cmd, env=None):
# def __init__(self, cmds=None):
# def __getattr__(self, name):
# def __call__(self, *a, **kw):
# def _parse_args(self, *a, **kw):
# def bake(self, *a, **kw):
# def call(self, cmdstr='', env=None):
# def git_with_path(git_dir=None, work_tree=None):
# def git_with_repo(repository):
# class Process(object):
. Output only the next line. | return git.clone(url, path, |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def clone_repository(url, path, bare=None, checkout_branch=None, mirror=None,
env=None, shared=None):
"""git clone command
NOTE: 因为`git clone`在本机上直接做硬链接,速度比pygit2.clone_repository快
"""
return git.clone(url, path,
b=checkout_branch,
bare=bare,
mirror=mirror,
env=env,
shared=shared)
def update_server_info(repository):
<|code_end|>
. Write the next line using the current file imports:
from ellen.utils.process import git, git_with_repo
and context from other files:
# Path: ellen/utils/process.py
# def _shlex_split(cmd):
# def _call(cmd, env=None):
# def __init__(self, cmds=None):
# def __getattr__(self, name):
# def __call__(self, *a, **kw):
# def _parse_args(self, *a, **kw):
# def bake(self, *a, **kw):
# def call(self, cmdstr='', env=None):
# def git_with_path(git_dir=None, work_tree=None):
# def git_with_repo(repository):
# class Process(object):
, which may include functions, classes, or code. Output only the next line. | git = git_with_repo(repository) |
Continue the code snippet: <|code_start|> except (KeyError, ValueError):
from_commit = None
if max_count:
length = max_count + skip if skip else max_count
else:
length = 0
for c in walker:
if all([_check_author(c, author),
_check_file_change(c, path),
_check_message(c, query),
_check_date(c, since),
_check_no_merges(c, no_merges)]):
index = c.hex
if first_parent:
if next_commit and next_commit.hex != c.hex:
continue
if len(c.parents) == 0:
next_commit = None
elif len(c.parents) >= 1:
next_commit = c.parents[0]
else:
continue
if index not in commits_index_list:
commits_index_list.append(index)
commits_dict[index] = c
if length and len(commits_index_list) >= length:
break
if skip:
commits_index_list = commits_index_list[skip:]
<|code_end|>
. Use current file imports:
from pygit2 import GIT_OBJ_TAG
from pygit2 import GIT_SORT_TIME
from pygit2 import GIT_SORT_TOPOLOGICAL
from ellen.utils.format import format_commit
and context (classes, functions, or code) from other files:
# Path: ellen/utils/format.py
# def format_commit(commit, repository):
# d = {}
# d['type'] = 'commit'
# # FIXME: use parents
# try:
# d['parent'] = [str(p.id) for p in commit.parents] if commit.parents else []
# d['parents'] = [str(p.id) for p in commit.parents] if commit.parents else []
# except KeyError:
# # FIXME: pygit2 commit.parents
# d['parent'] = []
# d['parents'] = []
# d['tree'] = str(commit.tree.id)
# d['committer'] = _format_pygit2_signature(commit.committer)
# d['author'] = _format_pygit2_signature(commit.author)
# d['email'] = commit.author.email # FIXME
# d['commit'] = str(commit.id) # FIXME
# d['message'], _, d['body'] = commit.message.strip().partition('\n\n')
# d['sha'] = str(commit.id)
# return d
. Output only the next line. | return [format_commit(commits_dict[i], repository) |
Next line prediction: <|code_start|>
here_dir = os.path.dirname(os.path.abspath(__file__))
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
<|code_end|>
. Use current file imports:
(import os
import boto
import loadsbroker.aws
from mock import Mock, PropertyMock, patch
from moto import mock_ec2
from tornado.testing import AsyncTestCase, gen_test
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.broker import Broker
from tornado.concurrent import Future
from loadsbroker.db import Database
from loadsbroker.db import setup_database
from loadsbroker.broker import RunManager, RunHelpers
from loadsbroker.extensions import (
Docker, DNSMasq, InfluxDB, SSH, Telegraf, Watcher)
from loadsbroker.aws import EC2Pool
from loadsbroker.db import Plan, Run
from loadsbroker.db import RUNNING, INITIALIZING
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING, COMPLETED
)
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING
))
and context including class names, function names, or small code snippets from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
. Output only the next line. | _OLD_CONTEXT[:] = list(clear_boto_context()) |
Next line prediction: <|code_start|>
here_dir = os.path.dirname(os.path.abspath(__file__))
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
_OLD_CONTEXT[:] = list(clear_boto_context())
ec2_mocker.start()
create_image()
def tearDown():
ec2_mocker.stop()
<|code_end|>
. Use current file imports:
(import os
import boto
import loadsbroker.aws
from mock import Mock, PropertyMock, patch
from moto import mock_ec2
from tornado.testing import AsyncTestCase, gen_test
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.broker import Broker
from tornado.concurrent import Future
from loadsbroker.db import Database
from loadsbroker.db import setup_database
from loadsbroker.broker import RunManager, RunHelpers
from loadsbroker.extensions import (
Docker, DNSMasq, InfluxDB, SSH, Telegraf, Watcher)
from loadsbroker.aws import EC2Pool
from loadsbroker.db import Plan, Run
from loadsbroker.db import RUNNING, INITIALIZING
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING, COMPLETED
)
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING
))
and context including class names, function names, or small code snippets from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
. Output only the next line. | load_boto_context(*_OLD_CONTEXT) |
Given the following code snippet before the placeholder: <|code_start|>
here_dir = os.path.dirname(os.path.abspath(__file__))
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
_OLD_CONTEXT[:] = list(clear_boto_context())
ec2_mocker.start()
<|code_end|>
, predict the next line using imports from the current file:
import os
import boto
import loadsbroker.aws
from mock import Mock, PropertyMock, patch
from moto import mock_ec2
from tornado.testing import AsyncTestCase, gen_test
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.broker import Broker
from tornado.concurrent import Future
from loadsbroker.db import Database
from loadsbroker.db import setup_database
from loadsbroker.broker import RunManager, RunHelpers
from loadsbroker.extensions import (
Docker, DNSMasq, InfluxDB, SSH, Telegraf, Watcher)
from loadsbroker.aws import EC2Pool
from loadsbroker.db import Plan, Run
from loadsbroker.db import RUNNING, INITIALIZING
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING, COMPLETED
)
from loadsbroker.db import (
RUNNING, INITIALIZING, TERMINATING
)
and context including class names, function names, and sometimes code from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
. Output only the next line. | create_image() |
Predict the next line after this snippet: <|code_start|>
class TestRetry(unittest.TestCase):
def test_retry_on_result(self):
attempts = []
<|code_end|>
using the current file's imports:
import unittest
from operator import not_
from loadsbroker.util import retry
and any relevant context from other files:
# Path: loadsbroker/util.py
# def retry(attempts=3,
# on_exception=None,
# on_result=None):
# """Retry a function multiple times, logging failures."""
# assert on_exception or on_result
#
# def __retry(func):
# @wraps(func)
# def ___retry(*args, **kw):
# attempt = 0
# while True:
# attempt += 1
# try:
# result = func(*args, **kw)
# except Exception as exc:
# if (on_exception is None or not on_exception(exc) or
# attempt == attempts):
# logger.debug('Failed (%d/%d)' % (attempt, attempts),
# exc_info=True)
# raise
# else:
# if (on_result is None or not on_result(result) or
# attempt == attempts):
# return result
# return ___retry
# return __retry
. Output only the next line. | @retry(attempts=4, on_result=not_) |
Continue the code snippet: <|code_start|> s.seek(0)
boto.config.clear()
return s.read(), endpoints
def load_boto_context(config, endpoints=None):
s = StringIO()
s.write(config)
boto.config.clear()
boto.config.read(s)
if endpoints is not None:
os.environ['BOTO_ENDPOINTS'] = endpoints
def boto_cleared(func):
@wraps(func)
def _cleared(*args, **kwargs):
context, endpoints = clear_boto_context()
try:
return func(*args, **kwargs)
finally:
load_boto_context(context, endpoints)
return _cleared
def create_images():
logging.getLogger('boto').setLevel(logging.CRITICAL)
# late import so BOTO_ENDPOINTS is seen
<|code_end|>
. Use current file imports:
from io import StringIO
from functools import wraps
from loadsbroker.aws import AWS_REGIONS
from boto.ec2 import connect_to_region
import sys
import subprocess
import requests
import time
import os
import boto
import logging
and context (classes, functions, or code) from other files:
# Path: loadsbroker/aws.py
# AWS_REGIONS = (
# # "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", # speeding up
# "eu-west-1",
# # "sa-east-1", # this one times out
# "us-east-1",
# "us-west-1",
# "us-west-2"
# )
. Output only the next line. | for region in AWS_REGIONS: |
Predict the next line for this snippet: <|code_start|>
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
<|code_end|>
with the help of current file imports:
import unittest
import boto
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
from datetime import datetime, timedelta
from tornado.testing import AsyncTestCase, gen_test
from moto import mock_ec2
from freezegun import freeze_time
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.aws import available_instance
from loadsbroker.aws import EC2Collection
from loadsbroker.aws import EC2Pool
and context from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
, which may contain function names, class names, or code. Output only the next line. | _OLD_CONTEXT[:] = list(clear_boto_context()) |
Here is a snippet: <|code_start|>
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
_OLD_CONTEXT[:] = list(clear_boto_context())
ec2_mocker.start()
create_image()
def tearDown():
ec2_mocker.stop()
<|code_end|>
. Write the next line using the current file imports:
import unittest
import boto
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
from datetime import datetime, timedelta
from tornado.testing import AsyncTestCase, gen_test
from moto import mock_ec2
from freezegun import freeze_time
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.aws import available_instance
from loadsbroker.aws import EC2Collection
from loadsbroker.aws import EC2Pool
and context from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
, which may include functions, classes, or code. Output only the next line. | load_boto_context(*_OLD_CONTEXT) |
Continue the code snippet: <|code_start|>
ec2_mocker = mock_ec2()
_OLD_CONTEXT = []
def setUp():
_OLD_CONTEXT[:] = list(clear_boto_context())
ec2_mocker.start()
<|code_end|>
. Use current file imports:
import unittest
import boto
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
import loadsbroker.aws
from datetime import datetime, timedelta
from tornado.testing import AsyncTestCase, gen_test
from moto import mock_ec2
from freezegun import freeze_time
from loadsbroker.tests.util import (clear_boto_context, load_boto_context,
create_image)
from loadsbroker.aws import available_instance
from loadsbroker.aws import EC2Collection
from loadsbroker.aws import EC2Pool
and context (classes, functions, or code) from other files:
# Path: loadsbroker/tests/util.py
# def clear_boto_context():
# endpoints = os.environ.get('BOTO_ENDPOINTS')
# if endpoints is not None:
# del os.environ['BOTO_ENDPOINTS']
# s = StringIO()
# boto.config.write(s)
# s.seek(0)
# boto.config.clear()
# return s.read(), endpoints
#
# def load_boto_context(config, endpoints=None):
# s = StringIO()
# s.write(config)
# boto.config.clear()
# boto.config.read(s)
# if endpoints is not None:
# os.environ['BOTO_ENDPOINTS'] = endpoints
#
# def create_image(region="us-west-2"):
# conn = boto.ec2.connect_to_region(region)
# reservation = conn.run_instances('ami-1234abcd')
# instance = reservation.instances[0]
# conn.create_image(instance.id, "Core OS stable")
. Output only the next line. | create_image() |
Next line prediction: <|code_start|>
# Make vocabulary files
char_vocab_file_path = mkdir_join(vocab_file_save_path, 'character.txt')
char_capital_vocab_file_path = mkdir_join(
vocab_file_save_path, 'character_capital_divide.txt')
# Reserve some indices
char_set.discard(SPACE)
char_set.discard(APOSTROPHE)
char_capital_set.discard(APOSTROPHE)
# for debug
# print(sorted(list(char_set)))
# print(sorted(list(char_capital_set)))
if save_vocab_file:
# character-level
with open(char_vocab_file_path, 'w') as f:
char_list = sorted(list(char_set)) + [SPACE, APOSTROPHE]
for char in char_list:
f.write('%s\n' % char)
# character-level (capital-divided)
with open(char_capital_vocab_file_path, 'w') as f:
char_capital_list = sorted(list(char_capital_set)) + [APOSTROPHE]
for char in char_capital_list:
f.write('%s\n' % char)
# Tokenize
print('=====> Tokenize...')
<|code_end|>
. Use current file imports:
(from os.path import basename
from tqdm import tqdm
from utils.labels.character import Char2idx
from utils.util import mkdir_join
import re)
and context including class names, function names, or small code snippets from other files:
# Path: utils/labels/character.py
# class Char2idx(object):
# """Convert from character to index.
# Args:
# vocab_file_path (string): path to the vocabulary file
# space_mark (string, optional): the space mark to divide a sequence into words
# capital_divide (bool, optional): if True, words will be divided by
# capital letters. This is used for English.
# double_letter (bool, optional): if True, group repeated letters.
# This is used for Japanese.
# remove_list (list, optional): characters to neglect
# """
#
# def __init__(self, vocab_file_path, space_mark='_', capital_divide=False,
# double_letter=False, remove_list=[]):
# self.space_mark = space_mark
# self.capital_divide = capital_divide
# self.double_letter = double_letter
# self.remove_list = remove_list
#
# # Read the vocabulary file
# self.map_dict = {}
# vocab_count = 0
# with open(vocab_file_path, 'r') as f:
# for line in f:
# char = line.strip()
# if char in remove_list:
# continue
# self.map_dict[char] = vocab_count
# vocab_count += 1
#
# # Add <SOS> & <EOS>
# self.map_dict['<'] = vocab_count
# self.map_dict['>'] = vocab_count + 1
#
# def __call__(self, str_char):
# """
# Args:
# str_char (string): a sequence of characters
# Returns:
# index_list (list): character indices
# """
# index_list = []
#
# # Convert from character to index
# if self.capital_divide:
# for word in str_char.split(self.space_mark):
# # Replace the first character with the capital letter
# index_list.append(self.map_dict[word[0].upper()])
#
# # Check double-letters
# skip_flag = False
# for i in range(1, len(word) - 1, 1):
# if skip_flag:
# skip_flag = False
# continue
#
# if not skip_flag and word[i:i + 2] in self.map_dict.keys():
# index_list.append(self.map_dict[word[i:i + 2]])
# skip_flag = True
# else:
# index_list.append(self.map_dict[word[i]])
#
# # Final character
# if not skip_flag:
# index_list.append(self.map_dict[word[-1]])
#
# elif self.double_letter:
# skip_flag = False
# for i in range(len(str_char) - 1):
# if skip_flag:
# skip_flag = False
# continue
#
# if not skip_flag and str_char[i:i + 2] in self.map_dict.keys():
# index_list.append(self.map_dict[str_char[i:i + 2]])
# skip_flag = True
# else:
# index_list.append(self.map_dict[str_char[i]])
#
# # Final character
# if not skip_flag:
# index_list.append(self.map_dict[str_char[-1]])
#
# else:
# index_list = list(map(lambda x: self.map_dict[x], list(str_char)))
#
# return np.array(index_list)
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
. Output only the next line. | char2idx = Char2idx(char_vocab_file_path) |
Predict the next line after this snippet: <|code_start|> # Check double-letters
skip_flag = False
for i in range(1, len(word) - 1, 1):
if skip_flag:
skip_flag = False
continue
if not skip_flag and word[i:i + 2] in DOUBLE_LETTERS:
char_capital_set.add(word[i:i + 2])
skip_flag = True
else:
char_capital_set.add(word[i])
# Final character
if not skip_flag:
char_capital_set.add(word[-1])
# Convert space to "_"
transcript = re.sub(r'\s', SPACE, transcript)
for c in list(transcript):
char_set.add(c)
trans_dict[utt_name] = transcript
# for debug
# print(transcript)
# print(trans_char_capital_divide)
# Make vocabulary files
<|code_end|>
using the current file's imports:
from os.path import basename
from tqdm import tqdm
from utils.labels.character import Char2idx
from utils.util import mkdir_join
import re
and any relevant context from other files:
# Path: utils/labels/character.py
# class Char2idx(object):
# """Convert from character to index.
# Args:
# vocab_file_path (string): path to the vocabulary file
# space_mark (string, optional): the space mark to divide a sequence into words
# capital_divide (bool, optional): if True, words will be divided by
# capital letters. This is used for English.
# double_letter (bool, optional): if True, group repeated letters.
# This is used for Japanese.
# remove_list (list, optional): characters to neglect
# """
#
# def __init__(self, vocab_file_path, space_mark='_', capital_divide=False,
# double_letter=False, remove_list=[]):
# self.space_mark = space_mark
# self.capital_divide = capital_divide
# self.double_letter = double_letter
# self.remove_list = remove_list
#
# # Read the vocabulary file
# self.map_dict = {}
# vocab_count = 0
# with open(vocab_file_path, 'r') as f:
# for line in f:
# char = line.strip()
# if char in remove_list:
# continue
# self.map_dict[char] = vocab_count
# vocab_count += 1
#
# # Add <SOS> & <EOS>
# self.map_dict['<'] = vocab_count
# self.map_dict['>'] = vocab_count + 1
#
# def __call__(self, str_char):
# """
# Args:
# str_char (string): a sequence of characters
# Returns:
# index_list (list): character indices
# """
# index_list = []
#
# # Convert from character to index
# if self.capital_divide:
# for word in str_char.split(self.space_mark):
# # Replace the first character with the capital letter
# index_list.append(self.map_dict[word[0].upper()])
#
# # Check double-letters
# skip_flag = False
# for i in range(1, len(word) - 1, 1):
# if skip_flag:
# skip_flag = False
# continue
#
# if not skip_flag and word[i:i + 2] in self.map_dict.keys():
# index_list.append(self.map_dict[word[i:i + 2]])
# skip_flag = True
# else:
# index_list.append(self.map_dict[word[i]])
#
# # Final character
# if not skip_flag:
# index_list.append(self.map_dict[word[-1]])
#
# elif self.double_letter:
# skip_flag = False
# for i in range(len(str_char) - 1):
# if skip_flag:
# skip_flag = False
# continue
#
# if not skip_flag and str_char[i:i + 2] in self.map_dict.keys():
# index_list.append(self.map_dict[str_char[i:i + 2]])
# skip_flag = True
# else:
# index_list.append(self.map_dict[str_char[i]])
#
# # Final character
# if not skip_flag:
# index_list.append(self.map_dict[str_char[-1]])
#
# else:
# index_list = list(map(lambda x: self.map_dict[x], list(str_char)))
#
# return np.array(index_list)
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
. Output only the next line. | char_vocab_file_path = mkdir_join(vocab_file_save_path, 'character.txt') |
Based on the snippet: <|code_start|> char_set (set):
char_capital_set (set):
word_count_dict (dict):
key => word
value => the number of words in Fisher corpus
"""
print('=====> Processing target labels...')
speaker_dict = OrderedDict()
char_set, char_capital_set = set([]), set([])
word_count_dict = {}
vocab_set = set([])
for label_path in tqdm(label_paths):
utterance_dict = OrderedDict()
with open(label_path, 'r') as f:
utt_index = 0
session = basename(label_path).split('.')[0]
for line in f:
line = line.strip().split(' ')
if line[0] in ['#', '']:
continue
start_frame = int(float(line[0]) * 100 + 0.05)
end_frame = int(float(line[1]) * 100 + 0.05)
which_speaker = line[2].replace(':', '')
if which_speaker != target_speaker:
continue
speaker = session + '-' + which_speaker
# Clean transcript
transcript_original = ' '.join(line[3:]).lower()
<|code_end|>
, predict the immediate next line with the help of imports:
from os.path import basename
from tqdm import tqdm
from collections import OrderedDict
from swbd.labels.fisher.fix_trans import fix_transcript
import re
and context (classes, functions, sometimes code) from other files:
# Path: swbd/labels/fisher/fix_trans.py
# def fix_transcript(transcript):
#
# # Replace with special symbols
# transcript = re.sub(r'\[laughter\]', LAUGHTER, transcript)
# transcript = re.sub(r'\[laugh\]', LAUGHTER, transcript)
# transcript = re.sub(r'\[noise\]', NOISE, transcript)
# transcript = re.sub(r'\[sigh\]', NOISE, transcript)
# transcript = re.sub(r'\[cough\]', NOISE, transcript)
# transcript = re.sub(r'\[mn\]', NOISE, transcript)
# transcript = re.sub(r'\[breath\]', NOISE, transcript)
# transcript = re.sub(r'\[lipsmack\]', NOISE, transcript)
# transcript = re.sub(r'\[sneeze\]', NOISE, transcript)
# transcript = re.sub('&', ' and ', transcript)
#
# # Remove
# transcript = re.sub(r'\[pause\]', '', transcript)
# transcript = re.sub(r'\[\[skip\]\]', '', transcript)
# transcript = re.sub(r'\?', '', transcript)
# transcript = re.sub(r'\*', '', transcript)
# transcript = re.sub(r'~', '', transcript)
# transcript = re.sub(r'\,', '', transcript)
# transcript = re.sub(r'\.', '', transcript)
#
# # Remove sentences which include german words
# german = re.match(r'(.*)<german (.+)>(.*)', transcript)
# if german is not None:
# transcript = ''
#
# # Remove (( ))
# transcript = re.sub(r'\(\([\s]+\)\)', '', transcript)
# kakko_expr = re.compile(r'(.*)\(\( ([^(]+) \)\)(.*)')
# while re.match(kakko_expr, transcript) is not None:
# kakko = re.match(kakko_expr, transcript)
# transcript = kakko.group(1) + kakko.group(2) + kakko.group(3)
#
# # remove "/"
# # transcript = re.sub('/', '', transcript)
#
# # Remove double spaces
# while ' ' in transcript:
# transcript = re.sub(r'[\s]+', ' ', transcript)
#
# return transcript
. Output only the next line. | transcript = fix_transcript(transcript_original) |
Given the following code snippet before the placeholder: <|code_start|>
phone61_list = []
with open(label_path, 'r') as f:
for line in f:
line = line.strip().split(' ')
# start_frame = line[0]
# end_frame = line[1]
phone61_list.append(line[2])
# Map from 61 phones to the corresponding phones
phone48_list = map_phone2phone(phone61_list, 'phone48',
phone2phone_map_file_path)
phone39_list = map_phone2phone(phone61_list, 'phone39',
phone2phone_map_file_path)
# Convert to string
trans_phone61 = ' '.join(phone61_list)
trans_phone48 = ' '.join(phone48_list)
trans_phone39 = ' '.join(phone39_list)
# for debug
# print(trans_phone61)
# print(trans_phone48)
# print(trans_phone39)
# print('-----')
trans_dict[utt_name] = [trans_phone61, trans_phone48, trans_phone39]
# Tokenize
print('=====> Tokenize...')
<|code_end|>
, predict the next line using imports from the current file:
from os.path import join, basename
from tqdm import tqdm
from utils.labels.phone import Phone2idx
from utils.util import mkdir_join
from timit.util import map_phone2phone
and context including class names, function names, and sometimes code from other files:
# Path: utils/labels/phone.py
# class Phone2idx(object):
# """Convert from phone to index.
# Args:
# vocab_file_path (string): path to the vocabulary file
# remove_list (list, optional): phones to neglect
# """
#
# def __init__(self, vocab_file_path, remove_list=[]):
# # Read the vocabulary file
# self.map_dict = {}
# vocab_count = 0
# with open(vocab_file_path, 'r') as f:
# for line in f:
# phone = line.strip()
# if phone in remove_list:
# continue
# self.map_dict[phone] = vocab_count
# vocab_count += 1
#
# # Add <SOS> & <EOS>
# self.map_dict['<'] = vocab_count
# self.map_dict['>'] = vocab_count + 1
#
# def __call__(self, str_phone):
# """
# Args:
# str_phone (string): string of space-divided phones
# Returns:
# index_list (np.ndarray): phone indices
# """
# # Convert from phone to the corresponding indices
# phone_list = str_phone.split(' ')
# index_list = list(map(lambda x: self.map_dict[x], phone_list))
#
# return np.array(index_list)
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# Path: timit/util.py
# def map_phone2phone(phone_list, label_type, map_file_path):
# """Map from 61 phones to 39 or 48 phones.
# Args:
# phone_list (list): list of 61 phones (string)
# label_type (string): phone39 or phone48 or phone61
# map_file_path (string): path to the phone2phone mapping file
# Returns:
# mapped_phone_list (list): list of phones (string)
# """
# if label_type == 'phone61':
# return phone_list
#
# # read a mapping file
# map_dict = {}
# with open(map_file_path, 'r') as f:
# for line in f:
# line = line.strip().split()
# if line[1] != 'nan':
# if label_type == 'phone48':
# map_dict[line[0]] = line[1]
# elif label_type == 'phone39':
# map_dict[line[0]] = line[2]
# else:
# map_dict[line[0]] = ''
#
# # mapping from 61 phones to 39 or 48 phones
# mapped_phone_list = []
# for i in range(len(phone_list)):
# if phone_list[i] in map_dict.keys():
# mapped_phone_list.append(map_dict[phone_list[i]])
# else:
# mapped_phone_list.append(phone_list[i])
#
# # ignore "q"
# while '' in mapped_phone_list:
# mapped_phone_list.remove('')
#
# return mapped_phone_list
. Output only the next line. | phone2idx_61 = Phone2idx(phone61_vocab_map_file_path) |
Here is a snippet: <|code_start|>def read_phone(label_paths, vocab_file_save_path, save_vocab_file=False,
is_test=False):
"""Read phone transcript.
Args:
label_paths (list): list of paths to label files
vocab_file_save_path (string): path to vocabulary files
save_vocab_file (bool, optional): if True, save vocabulary files
is_test (bool, optional): set True in case of the test set
Returns:
text_dict (dict):
key (string) => utterance name
value (list) => list of [phone61_indices, phone48_indices, phone39_indices]
"""
print('=====> Reading target labels...')
# Make the mapping file (from phone to index)
phone2phone_map_file_path = join(
vocab_file_save_path, '../phone2phone.txt')
phone61_set, phone48_set, phone39_set = set([]), set([]), set([])
with open(phone2phone_map_file_path, 'r') as f:
for line in f:
line = line.strip().split()
if line[1] != 'nan':
phone61_set.add(line[0])
phone48_set.add(line[1])
phone39_set.add(line[2])
else:
# Ignore "q" if phone39 or phone48
phone61_set.add(line[0])
<|code_end|>
. Write the next line using the current file imports:
from os.path import join, basename
from tqdm import tqdm
from utils.labels.phone import Phone2idx
from utils.util import mkdir_join
from timit.util import map_phone2phone
and context from other files:
# Path: utils/labels/phone.py
# class Phone2idx(object):
# """Convert from phone to index.
# Args:
# vocab_file_path (string): path to the vocabulary file
# remove_list (list, optional): phones to neglect
# """
#
# def __init__(self, vocab_file_path, remove_list=[]):
# # Read the vocabulary file
# self.map_dict = {}
# vocab_count = 0
# with open(vocab_file_path, 'r') as f:
# for line in f:
# phone = line.strip()
# if phone in remove_list:
# continue
# self.map_dict[phone] = vocab_count
# vocab_count += 1
#
# # Add <SOS> & <EOS>
# self.map_dict['<'] = vocab_count
# self.map_dict['>'] = vocab_count + 1
#
# def __call__(self, str_phone):
# """
# Args:
# str_phone (string): string of space-divided phones
# Returns:
# index_list (np.ndarray): phone indices
# """
# # Convert from phone to the corresponding indices
# phone_list = str_phone.split(' ')
# index_list = list(map(lambda x: self.map_dict[x], phone_list))
#
# return np.array(index_list)
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# Path: timit/util.py
# def map_phone2phone(phone_list, label_type, map_file_path):
# """Map from 61 phones to 39 or 48 phones.
# Args:
# phone_list (list): list of 61 phones (string)
# label_type (string): phone39 or phone48 or phone61
# map_file_path (string): path to the phone2phone mapping file
# Returns:
# mapped_phone_list (list): list of phones (string)
# """
# if label_type == 'phone61':
# return phone_list
#
# # read a mapping file
# map_dict = {}
# with open(map_file_path, 'r') as f:
# for line in f:
# line = line.strip().split()
# if line[1] != 'nan':
# if label_type == 'phone48':
# map_dict[line[0]] = line[1]
# elif label_type == 'phone39':
# map_dict[line[0]] = line[2]
# else:
# map_dict[line[0]] = ''
#
# # mapping from 61 phones to 39 or 48 phones
# mapped_phone_list = []
# for i in range(len(phone_list)):
# if phone_list[i] in map_dict.keys():
# mapped_phone_list.append(map_dict[phone_list[i]])
# else:
# mapped_phone_list.append(phone_list[i])
#
# # ignore "q"
# while '' in mapped_phone_list:
# mapped_phone_list.remove('')
#
# return mapped_phone_list
, which may include functions, classes, or code. Output only the next line. | phone61_vocab_map_file_path = mkdir_join( |
Given snippet: <|code_start|> phone39_vocab_map_file_path = mkdir_join(
vocab_file_save_path, 'phone39.txt')
# Save mapping file
if save_vocab_file:
with open(phone61_vocab_map_file_path, 'w') as f:
for phone in sorted(list(phone61_set)):
f.write('%s\n' % phone)
with open(phone48_vocab_map_file_path, 'w') as f:
for phone in sorted(list(phone48_set)):
f.write('%s\n' % phone)
with open(phone39_vocab_map_file_path, 'w') as f:
for phone in sorted(list(phone39_set)):
f.write('%s\n' % phone)
trans_dict = {}
for label_path in tqdm(label_paths):
speaker = label_path.split('/')[-2]
utt_index = basename(label_path).split('.')[0]
utt_name = speaker + '_' + utt_index
phone61_list = []
with open(label_path, 'r') as f:
for line in f:
line = line.strip().split(' ')
# start_frame = line[0]
# end_frame = line[1]
phone61_list.append(line[2])
# Map from 61 phones to the corresponding phones
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from os.path import join, basename
from tqdm import tqdm
from utils.labels.phone import Phone2idx
from utils.util import mkdir_join
from timit.util import map_phone2phone
and context:
# Path: utils/labels/phone.py
# class Phone2idx(object):
# """Convert from phone to index.
# Args:
# vocab_file_path (string): path to the vocabulary file
# remove_list (list, optional): phones to neglect
# """
#
# def __init__(self, vocab_file_path, remove_list=[]):
# # Read the vocabulary file
# self.map_dict = {}
# vocab_count = 0
# with open(vocab_file_path, 'r') as f:
# for line in f:
# phone = line.strip()
# if phone in remove_list:
# continue
# self.map_dict[phone] = vocab_count
# vocab_count += 1
#
# # Add <SOS> & <EOS>
# self.map_dict['<'] = vocab_count
# self.map_dict['>'] = vocab_count + 1
#
# def __call__(self, str_phone):
# """
# Args:
# str_phone (string): string of space-divided phones
# Returns:
# index_list (np.ndarray): phone indices
# """
# # Convert from phone to the corresponding indices
# phone_list = str_phone.split(' ')
# index_list = list(map(lambda x: self.map_dict[x], phone_list))
#
# return np.array(index_list)
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# Path: timit/util.py
# def map_phone2phone(phone_list, label_type, map_file_path):
# """Map from 61 phones to 39 or 48 phones.
# Args:
# phone_list (list): list of 61 phones (string)
# label_type (string): phone39 or phone48 or phone61
# map_file_path (string): path to the phone2phone mapping file
# Returns:
# mapped_phone_list (list): list of phones (string)
# """
# if label_type == 'phone61':
# return phone_list
#
# # read a mapping file
# map_dict = {}
# with open(map_file_path, 'r') as f:
# for line in f:
# line = line.strip().split()
# if line[1] != 'nan':
# if label_type == 'phone48':
# map_dict[line[0]] = line[1]
# elif label_type == 'phone39':
# map_dict[line[0]] = line[2]
# else:
# map_dict[line[0]] = ''
#
# # mapping from 61 phones to 39 or 48 phones
# mapped_phone_list = []
# for i in range(len(phone_list)):
# if phone_list[i] in map_dict.keys():
# mapped_phone_list.append(map_dict[phone_list[i]])
# else:
# mapped_phone_list.append(phone_list[i])
#
# # ignore "q"
# while '' in mapped_phone_list:
# mapped_phone_list.remove('')
#
# return mapped_phone_list
which might include code, classes, or functions. Output only the next line. | phone48_list = map_phone2phone(phone61_list, 'phone48', |
Predict the next line after this snippet: <|code_start|>
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def split_wav(wav_paths, save_path, speaker_dict):
"""Read WAV files & divide them with respect to each utterance.
Args:
wav_paths (list): path to WAV files
save_path (string): path to save WAV files
speaker_dict (dict): the dictionary of utterances of each speaker
key => speaker
value => the dictionary of utterance information of each speaker
key => utterance index
value => [start_frame, end_frame, transcript]
"""
# Read each WAV file
print('==> Reading WAV files...')
print(speaker_dict.keys())
for wav_path in tqdm(wav_paths):
speaker = basename(wav_path).split('.')[0]
# NOTE: For Switchboard
speaker = speaker.replace('sw0', 'sw')
speaker = speaker.replace('sw_', 'sw')
speaker = speaker.replace('en_', 'en')
utt_dict = speaker_dict[speaker]
<|code_end|>
using the current file's imports:
from os.path import basename, join
from tqdm import tqdm
from utils.util import mkdir_join
import numpy as np
import wave
and any relevant context from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
. Output only the next line. | wav_utt_save_path = mkdir_join(save_path, speaker) |
Continue the code snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
sys.path.append('../../')
fisher_path = '/n/sd8/inaguma/corpus/swbd/data/fisher'
# Search paths to transcript
label_paths = []
for trans_path in glob(join(fisher_path, 'data/trans/*/*.txt')):
label_paths.append(trans_path)
label_paths = sorted(label_paths)
class TestLabelFisher(unittest.TestCase):
def test(self):
self.check()
@measure_time
def check(self):
<|code_end|>
. Use current file imports:
from os.path import join
from glob import glob
from swbd.labels.fisher.character import read_trans
from utils.measure_time_func import measure_time
from utils.util import mkdir_join
import sys
import unittest
and context (classes, functions, or code) from other files:
# Path: swbd/labels/fisher/character.py
# def read_trans(label_paths, target_speaker):
# """Read transcripts (*_trans.txt) & save files (.npy).
# Args:
# label_paths: list of paths to label files
# target_speaker: A or B
# Returns:
# speaker_dict: dictionary of speakers
# key (string) => speaker
# value (dict) => dictionary of utterance infomation of each speaker
# key => utterance index
# value => [start_frame, end_frame, transcript]
# char_set (set):
# char_capital_set (set):
# word_count_dict (dict):
# key => word
# value => the number of words in Fisher corpus
# """
# print('=====> Processing target labels...')
# speaker_dict = OrderedDict()
# char_set, char_capital_set = set([]), set([])
# word_count_dict = {}
# vocab_set = set([])
#
# for label_path in tqdm(label_paths):
# utterance_dict = OrderedDict()
# with open(label_path, 'r') as f:
# utt_index = 0
# session = basename(label_path).split('.')[0]
# for line in f:
# line = line.strip().split(' ')
# if line[0] in ['#', '']:
# continue
# start_frame = int(float(line[0]) * 100 + 0.05)
# end_frame = int(float(line[1]) * 100 + 0.05)
# which_speaker = line[2].replace(':', '')
# if which_speaker != target_speaker:
# continue
# speaker = session + '-' + which_speaker
#
# # Clean transcript
# transcript_original = ' '.join(line[3:]).lower()
# transcript = fix_transcript(transcript_original)
#
# # Convert space to "_"
# transcript = re.sub(r'\s', SPACE, transcript)
#
# # Skip silence, laughter, noise, vocalized-noise only utterance
# if transcript.replace(NOISE, '').replace(LAUGHTER, '').replace(VOCALIZED_NOISE, '').replace(SPACE, '') != '':
#
# # Remove the first and last space
# if transcript[0] == SPACE:
# transcript = transcript[1:]
# if transcript[-1] == SPACE:
# transcript = transcript[:-1]
#
# # Count words
# for word in transcript.split(SPACE):
# vocab_set.add(word)
# if word not in word_count_dict.keys():
# word_count_dict[word] = 0
# word_count_dict[word] += 1
#
# # Capital-divided
# transcript_capital = ''
# for word in transcript.split(SPACE):
# if len(word) == 1:
# char_capital_set.add(word)
# transcript_capital += word
# else:
# # Replace the first character with the capital
# # letter
# word = word[0].upper() + word[1:]
#
# # Check double-letters
# for i in range(0, len(word) - 1, 1):
# if word[i:i + 2] in DOUBLE_LETTERS:
# char_capital_set.add(word[i:i + 2])
# else:
# char_capital_set.add(word[i])
# transcript_capital += word
#
# for c in list(transcript):
# char_set.add(c)
#
# utterance_dict[str(utt_index).zfill(4)] = [
# start_frame, end_frame, transcript]
#
# # for debug
# # print(transcript_original)
# # print(transcript)
#
# utt_index += 1
#
# speaker_dict[speaker] = utterance_dict
#
# # Reserve some indices
# for mark in [SPACE, HYPHEN, APOSTROPHE, LAUGHTER, NOISE, VOCALIZED_NOISE]:
# for c in list(mark):
# char_set.discard(c)
# char_capital_set.discard(c)
#
# # for debug
# # print(sorted(list(char_set)))
# # print(sorted(list(char_capital_set)))
#
# return speaker_dict, char_set, char_capital_set, word_count_dict
#
# Path: utils/measure_time_func.py
# def measure_time(func):
# @functools.wraps(func)
# def _measure_time(*args, **kwargs):
# start = time.time()
# func(*args, **kwargs)
# elapse = time.time() - start
# print("Takes {} seconds.".format(elapse))
# return _measure_time
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
. Output only the next line. | read_trans(label_paths=label_paths, target_speaker='A') |
Given the code snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
sys.path.append('../../')
fisher_path = '/n/sd8/inaguma/corpus/swbd/data/fisher'
# Search paths to transcript
label_paths = []
for trans_path in glob(join(fisher_path, 'data/trans/*/*.txt')):
label_paths.append(trans_path)
label_paths = sorted(label_paths)
class TestLabelFisher(unittest.TestCase):
def test(self):
self.check()
<|code_end|>
, generate the next line using the imports in this file:
from os.path import join
from glob import glob
from swbd.labels.fisher.character import read_trans
from utils.measure_time_func import measure_time
from utils.util import mkdir_join
import sys
import unittest
and context (functions, classes, or occasionally code) from other files:
# Path: swbd/labels/fisher/character.py
# def read_trans(label_paths, target_speaker):
# """Read transcripts (*_trans.txt) & save files (.npy).
# Args:
# label_paths: list of paths to label files
# target_speaker: A or B
# Returns:
# speaker_dict: dictionary of speakers
# key (string) => speaker
# value (dict) => dictionary of utterance infomation of each speaker
# key => utterance index
# value => [start_frame, end_frame, transcript]
# char_set (set):
# char_capital_set (set):
# word_count_dict (dict):
# key => word
# value => the number of words in Fisher corpus
# """
# print('=====> Processing target labels...')
# speaker_dict = OrderedDict()
# char_set, char_capital_set = set([]), set([])
# word_count_dict = {}
# vocab_set = set([])
#
# for label_path in tqdm(label_paths):
# utterance_dict = OrderedDict()
# with open(label_path, 'r') as f:
# utt_index = 0
# session = basename(label_path).split('.')[0]
# for line in f:
# line = line.strip().split(' ')
# if line[0] in ['#', '']:
# continue
# start_frame = int(float(line[0]) * 100 + 0.05)
# end_frame = int(float(line[1]) * 100 + 0.05)
# which_speaker = line[2].replace(':', '')
# if which_speaker != target_speaker:
# continue
# speaker = session + '-' + which_speaker
#
# # Clean transcript
# transcript_original = ' '.join(line[3:]).lower()
# transcript = fix_transcript(transcript_original)
#
# # Convert space to "_"
# transcript = re.sub(r'\s', SPACE, transcript)
#
# # Skip silence, laughter, noise, vocalized-noise only utterance
# if transcript.replace(NOISE, '').replace(LAUGHTER, '').replace(VOCALIZED_NOISE, '').replace(SPACE, '') != '':
#
# # Remove the first and last space
# if transcript[0] == SPACE:
# transcript = transcript[1:]
# if transcript[-1] == SPACE:
# transcript = transcript[:-1]
#
# # Count words
# for word in transcript.split(SPACE):
# vocab_set.add(word)
# if word not in word_count_dict.keys():
# word_count_dict[word] = 0
# word_count_dict[word] += 1
#
# # Capital-divided
# transcript_capital = ''
# for word in transcript.split(SPACE):
# if len(word) == 1:
# char_capital_set.add(word)
# transcript_capital += word
# else:
# # Replace the first character with the capital
# # letter
# word = word[0].upper() + word[1:]
#
# # Check double-letters
# for i in range(0, len(word) - 1, 1):
# if word[i:i + 2] in DOUBLE_LETTERS:
# char_capital_set.add(word[i:i + 2])
# else:
# char_capital_set.add(word[i])
# transcript_capital += word
#
# for c in list(transcript):
# char_set.add(c)
#
# utterance_dict[str(utt_index).zfill(4)] = [
# start_frame, end_frame, transcript]
#
# # for debug
# # print(transcript_original)
# # print(transcript)
#
# utt_index += 1
#
# speaker_dict[speaker] = utterance_dict
#
# # Reserve some indices
# for mark in [SPACE, HYPHEN, APOSTROPHE, LAUGHTER, NOISE, VOCALIZED_NOISE]:
# for c in list(mark):
# char_set.discard(c)
# char_capital_set.discard(c)
#
# # for debug
# # print(sorted(list(char_set)))
# # print(sorted(list(char_capital_set)))
#
# return speaker_dict, char_set, char_capital_set, word_count_dict
#
# Path: utils/measure_time_func.py
# def measure_time(func):
# @functools.wraps(func)
# def _measure_time(*args, **kwargs):
# start = time.time()
# func(*args, **kwargs)
# elapse = time.time() - start
# print("Takes {} seconds.".format(elapse))
# return _measure_time
#
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
. Output only the next line. | @measure_time |
Based on the snippet: <|code_start|>parser.add_argument('--energy', type=int, help='if 1, add the energy feature')
parser.add_argument('--delta', type=int, help='if 1, add the energy feature')
parser.add_argument('--deltadelta', type=int,
help='if 1, double delta features are also extracted')
parser.add_argument('--fisher', type=int,
help='If True, create large-size dataset (2000h).')
def main():
args = parser.parse_args()
htk_save_path = mkdir(args.htk_save_path)
# HTK settings
save_config(audio_file_type='wav',
feature_type=args.feature_type,
channels=args.channels,
config_save_path='./config',
sampling_rate=8000,
window=args.window,
slide=args.slide,
energy=bool(args.energy),
delta=bool(args.delta),
deltadelta=bool(args.deltadelta))
# NOTE: 120-dim features are extracted by default
# Switchboard
with open('./config/wav2htk_swbd.scp', 'w') as f:
for wav_path in glob(join(args.wav_save_path, 'swbd/*.wav')):
# ex.) wav_path: wav/swbd/*.wav
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config
and context (classes, functions, sometimes code) from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | save_path = mkdir_join( |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
sys.path.append('../')
parser = argparse.ArgumentParser()
parser.add_argument('--wav_save_path', type=str, help='path to audio files')
parser.add_argument('--htk_save_path', type=str, help='path to save htk files')
parser.add_argument('--run_root_path', type=str,
help='path to run this script')
parser.add_argument('--feature_type', type=str, help='fbank or mfcc')
parser.add_argument('--channels', type=int,
help='the number of frequency channels')
parser.add_argument('--window', type=float,
help='window width to extract features')
parser.add_argument('--slide', type=float, help='extract features per slide')
parser.add_argument('--energy', type=int, help='if 1, add the energy feature')
parser.add_argument('--delta', type=int, help='if 1, add the energy feature')
parser.add_argument('--deltadelta', type=int,
help='if 1, double delta features are also extracted')
parser.add_argument('--fisher', type=int,
help='If True, create large-size dataset (2000h).')
def main():
args = parser.parse_args()
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config
and context including class names, function names, and sometimes code from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | htk_save_path = mkdir(args.htk_save_path) |
Given the following code snippet before the placeholder: <|code_start|>
sys.path.append('../')
parser = argparse.ArgumentParser()
parser.add_argument('--wav_save_path', type=str, help='path to audio files')
parser.add_argument('--htk_save_path', type=str, help='path to save htk files')
parser.add_argument('--run_root_path', type=str,
help='path to run this script')
parser.add_argument('--feature_type', type=str, help='fbank or mfcc')
parser.add_argument('--channels', type=int,
help='the number of frequency channels')
parser.add_argument('--window', type=float,
help='window width to extract features')
parser.add_argument('--slide', type=float, help='extract features per slide')
parser.add_argument('--energy', type=int, help='if 1, add the energy feature')
parser.add_argument('--delta', type=int, help='if 1, add the energy feature')
parser.add_argument('--deltadelta', type=int,
help='if 1, double delta features are also extracted')
parser.add_argument('--fisher', type=int,
help='If True, create large-size dataset (2000h).')
def main():
args = parser.parse_args()
htk_save_path = mkdir(args.htk_save_path)
# HTK settings
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config
and context including class names, function names, and sometimes code from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | save_config(audio_file_type='wav', |
Using the snippet: <|code_start|>
# HTK settings
save_config(audio_file_type='wav',
feature_type=args.feature_type,
channels=args.channels,
config_save_path='./config',
sampling_rate=16000,
window=args.window,
slide=args.slide,
energy=bool(args.energy),
delta=bool(args.delta),
deltadelta=bool(args.deltadelta))
# NOTE: 120-dim features are extracted by default
parts = ['train-clean-100', 'dev-clean', 'dev-other',
'test-clean', 'test-other']
if bool(args.large):
parts += ['train-clean-360', 'train-other-500']
elif bool(args.medium):
parts += ['train-clean-360']
for part in parts:
# part/speaker/book/*.wav
wav_paths = [p for p in glob(join(args.data_path, part, '*/*/*.wav'))]
with open('./config/wav2htk_' + part + '.scp', 'w') as f:
for wav_path in wav_paths:
# ex.) wav_path: speaker/book/speaker-book-utt_index.wav
speaker, book, utt_index = basename(
wav_path).split('.')[0].split('-')
<|code_end|>
, determine the next line of code. You have imports:
import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config
and context (class names, function names, or code) available:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | save_path = mkdir_join( |
Predict the next line after this snippet: <|code_start|>from __future__ import division
from __future__ import print_function
sys.path.append('../')
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', type=str,
help='path to Librispeech dataset')
parser.add_argument('--htk_save_path', type=str, help='path to save htk files')
parser.add_argument('--feature_type', type=str, help='fbank or mfcc')
parser.add_argument('--channels', type=int,
help='the number of frequency channels')
parser.add_argument('--window', type=float,
help='window width to extract features')
parser.add_argument('--slide', type=float, help='extract features per slide')
parser.add_argument('--energy', type=int, help='if 1, add the energy feature')
parser.add_argument('--delta', type=int, help='if 1, add the energy feature')
parser.add_argument('--deltadelta', type=int,
help='if 1, double delta features are also extracted')
parser.add_argument('--medium', type=int,
help='If True, create medium-size dataset (460h).')
parser.add_argument('--large', type=int,
help='If True, create large-size dataset (960h).')
def main():
args = parser.parse_args()
<|code_end|>
using the current file's imports:
import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config
and any relevant context from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | htk_save_path = mkdir(args.htk_save_path) |
Next line prediction: <|code_start|>
sys.path.append('../')
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', type=str,
help='path to Librispeech dataset')
parser.add_argument('--htk_save_path', type=str, help='path to save htk files')
parser.add_argument('--feature_type', type=str, help='fbank or mfcc')
parser.add_argument('--channels', type=int,
help='the number of frequency channels')
parser.add_argument('--window', type=float,
help='window width to extract features')
parser.add_argument('--slide', type=float, help='extract features per slide')
parser.add_argument('--energy', type=int, help='if 1, add the energy feature')
parser.add_argument('--delta', type=int, help='if 1, add the energy feature')
parser.add_argument('--deltadelta', type=int,
help='if 1, double delta features are also extracted')
parser.add_argument('--medium', type=int,
help='If True, create medium-size dataset (460h).')
parser.add_argument('--large', type=int,
help='If True, create large-size dataset (960h).')
def main():
args = parser.parse_args()
htk_save_path = mkdir(args.htk_save_path)
# HTK settings
<|code_end|>
. Use current file imports:
(import sys
import argparse
from os.path import join, basename
from glob import glob
from utils.util import mkdir_join, mkdir
from utils.inputs.htk import save_config)
and context including class names, function names, or small code snippets from other files:
# Path: utils/util.py
# def mkdir_join(path_to_dir, *dir_name):
# """Concatenate root path and 1 or more paths, and make a new direcory if
# the direcory does not exist.
# Args:
# path_to_dir (string): path to a diretcory
# dir_name (string): a direcory name
# Returns:
# path to the new directory
# """
# if path_to_dir is None:
# return path_to_dir
#
# path_to_dir = mkdir(path_to_dir)
# for i in range(len(dir_name)):
# if i == len(dir_name) - 1 and '.' in dir_name[i]:
# path_to_dir = os.path.join(path_to_dir, dir_name[i])
# else:
# path_to_dir = mkdir(os.path.join(path_to_dir, dir_name[i]))
# return path_to_dir
#
# def mkdir(path_to_dir):
# """Make a new directory if the directory does not exist.
# Args:
# path_to_dir (string): path to a directory
# Returns:
# path (string): path to the new directory
# """
# if path_to_dir is not None and (not os.path.isdir(path_to_dir)):
# os.mkdir(path_to_dir)
# return path_to_dir
#
# Path: utils/inputs/htk.py
# def save_config(audio_file_type, feature_type, channels, config_save_path,
# sampling_rate=16000, window=0.025, slide=0.01,
# energy=True, delta=True, deltadelta=True):
# """Save a configuration file for HTK.
# Args:
# audio_file_type (string): nist or wav
# feature_type (string): the type of features, logmelfbank or mfcc
# channels (int): the number of frequency channels
# config_save_path (string): path to save the config file
# sampling_rate (float, optional):
# window (float, optional): window width to extract features
# slide (float, optional): extract features per 'slide'
# energy (bool, optional): if True, add the energy feature
# delta (bool, optional): if True, delta features are also extracted
# deltadelta (bool, optional): if True, double delta features are also extracted
# """
# with open(join(config_save_path, feature_type + '.conf'), 'w') as f:
# if audio_file_type not in ['nist', 'wav']:
# raise ValueError('audio_file_type must be nist or wav.')
# f.write('SOURCEFORMAT = %s\n' % audio_file_type.upper())
#
# # Sampling rate
# if sampling_rate == 16000:
# f.write('SOURCERATE = 625\n')
# elif sampling_rate == 8000:
# f.write('SOURCERATE = 1250\n')
#
# # Target features
# if feature_type == 'fbank':
# feature_type = 'FBANK' # log mel-filter bank channel outputs
# elif feature_type == 'mfcc':
# feature_type = 'MFCC' # mel-frequency cepstral coefficients
# # elif feature_type == 'linearmelfbank':
# # feature_type = 'MELSPEC' # linear mel-filter bank channel outputs
# else:
# raise ValueError('feature_type must be fbank or mfcc.')
#
# if energy:
# feature_type += '_E'
# if delta:
# feature_type += '_D'
# if deltadelta:
# feature_type += '_A'
# f.write('TARGETKIND = %s\n' % feature_type)
#
# # f.write('DELTAWINDOW = 2')
# # f.write('ACCWINDOW = 2')
#
# # Extract features per slide
# f.write('TARGETRATE = %.1f\n' % (slide * 10000000))
#
# f.write('SAVECOMPRESSED = F\n')
# f.write('SAVEWITHCRC = F\n')
#
# # Window size
# f.write('WINDOWSIZE = %.1f\n' % (window * 10000000))
#
# f.write('USEHAMMING = T\n')
# f.write('PREEMCOEF = 0.97\n')
# f.write('NUMCHANS = %d\n' % channels)
# f.write('ENORMALISE = F\n')
# f.write('ZMEANSOURCE = T\n')
. Output only the next line. | save_config(audio_file_type='wav', |
Predict the next line after this snippet: <|code_start|> rpcServerScript = os.path.abspath(__file__).replace("\\", "/")
scriptCmd = "python %s --port=%d --logLevel=%d" %(rpcServerScript, self.port, self.logLevel)
self.proc = subprocess.Popen(shlex.split(scriptCmd))
self.__lock.release();
def close(self):
if self.proc:
subprocess.Popen.terminate(self.proc)
class PollSimThread(threading.Thread):
def __init__(self, pyscardRpc, index, pollRate=400):
threading.Thread.__init__(self)
self.pyscardRpc = pyscardRpc
self.index = index
self.pollRate = pollRate
self.poll = False
self.startTime = 0
self.lastUpdate = 0
self.pattern = 0
threading.Thread.setName(self, 'PollSimThread')
self.__lock = threading.Lock()
def run(self):
self.__lock.acquire()
self.poll = True
while (self.poll):
self.startTime = time.time()
if self.startTime - self.lastUpdate > (self.pollRate / 1000.0 - 0.1):
try:
<|code_end|>
using the current file's imports:
import sys,os.path
import logging
import inspect
import os
import shlex
import smartcard
import subprocess
import threading
import time
import zerorpc
import zmq
from optparse import OptionParser
from smartcard.Exceptions import CardConnectionException
from util import hextools
and any relevant context from other files:
# Path: util/hextools.py
# def bytes2hex(bytes, separator=""):
# def hex2bytes(hex):
# def bytes2string(bytes):
# def bytes(x):
# def hex(x):
# def string(x):
# def le_int_bytes(i):
# def be_int_bytes(i):
# def strip(str):
# def __init__(self, lst, nb):
# def __iter__(self):
# def next(self):
# def le_u32(val):
# def u32(val):
# def be_u16(val):
# def le_int(lst):
# def be_int(lst):
# def all_FF(msg):
# def pathstring(path):
# def decode_BCD(data=[]):
# def encode_BCD(data=[]):
# def test():
# class chunks:
. Output only the next line. | sw1 = self.pyscardRpc.c_transmit(hextools.hex2bytes(POLL_STATUS_PATTERN[self.pattern]), |
Using the snippet: <|code_start|>startDir = dir
def setupLogger(loggingLevel):
if not os.path.exists(resultDir):
os.makedirs(resultDir)
resultFile = os.path.join(resultDir, "result.txt")
# create logger with 'root'
logger = logging.getLogger()
logger.handlers = []
logger.setLevel(loggingLevel)
# create file handler which logs even debug messages
fileHandler = logging.FileHandler(resultFile)
fileHandler.setLevel(loggingLevel)
# create console handler with a higher log level
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(loggingLevel)
# create ext handler with a higher log level
# use this handler to redirect streaming in html_test_runner
extHandler = logging.StreamHandler(stream=html_test_runner.stdout_redirector)
extHandler.setLevel(loggingLevel)
# create formatter and add it to the handlers
formatterConsole = logging.Formatter(fmt='%(message)s')
formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%H:%M:%S')
consoleHandler.setFormatter(formatterConsole)
fileHandler.setFormatter(formatter)
extHandler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
logger.addHandler(extHandler)
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import unittest
import logging
import traceback
import html_test_runner
import java.lang.System
from optparse import OptionParser
from sim import sim_router
and context (class names, function names, or code) available:
# Path: sim/sim_router.py
# ROUTER_MODE_DISABLED = 0
# ROUTER_MODE_INTERACTIVE = 1
# ROUTER_MODE_TELNET = 2
# ROUTER_MODE_DBUS = 3
# CMD_SET_ATR = 0
# CMD_SET_SKIP = 1
# CMD_HALT = 2
# CMD_POLL = 3
# CMD_R_APDU = 4
# EVT_UNKNOWN = 0
# EVT_RESET = 2
# EVT_C_APDU = 4
# SIMTRACE_OFFLINE = 0
# SIMTRACE_ONLINE = 1
# MAIN_INTERFACE = 0
# CTRL_INTERFACE = 1
# INJECT_READY = 0
# INJECT_NO_FORWARD = 1
# INJECT_WITH_FORWARD = 2
# INJECT_RESET = 3
# TRY_ANOTHER_CARD_ON_AUTH_FAILURE = True
# LOG_NONE_APDU_IN_FILE = True
# LIBUSB_PATH = "/usr/lib/libusb-1.0.so"
# class SimRouter(object):
# class MainLoopThread(threading.Thread):
# class ResetThread(threading.Thread):
# def __init__(self,
# cards,
# atr=None,
# type=types.TYPE_USIM,
# mode=SIMTRACE_ONLINE):
# def addControlCard(self, cards):
# def usbCtrlOut(self, req, buf):
# def usbCtrlIn(self, req):
# def receiveData(self, cmd):
# def sendData(self, msg):
# def resetCards(self, soft=True):
# def receiveCommandApdu(self):
# def sendResponseApdu(self, msg):
# def command(self, tag, payload=[]): # dummy byte
# def aidCommon(self, card):
# def getSoftCardDict(self):
# def getFileHandler(self, file):
# def getInsHandler(self, ins, apdu):
# def addLeftHandlers(self, cards):
# def getHandlers(self, apdu, inject=None):
# def handleApdu(self, cardData, apdu):
# def updateHandler(self, cardData, apdu, rapdu):
# def tick(self):
# def mainloop(self):
# def getNbrOfCards(self):
# def getSimId(self, card):
# def getCardDictFromId(self, simId):
# def isCardCtrl(self, card):
# def getMainCard(self, simId):
# def getCtrlCard(self, simId):
# def getRelatedMainCard(self, cardCtrl):
# def getRelatedCtrlCard(self, cardMain):
# def swapCards(self, simId1, simId2):
# def copyFiles(self, cardMainFrom, cardMainTo, files):
# def getATR(self):
# def waitInjectReady(self, timeout=15):
# def waitRapduInject(self, timeout=30):
# def injectApdu(self, apdu, card, mode=INJECT_NO_FORWARD):
# def setPowerSkip(self, skip):
# def powerHalt(self):
# def run(self, mode=ROUTER_MODE_INTERACTIVE):
# def getInteractiveFromMode(self, mode):
# def startPlacServer(self, mode):
# def setShellPrompt(self, prompt):
# def setupLogger(self):
# def fileName(self, apdu):
# def pretty_apdu(self, apdu):
# def usb_find(self, idVendor, idProduct):
# def setLoggerExtHandler(handler):
# def __init__(self, simRouter):
# def run(self):
# def stop(self):
# def __init__(self, simRouter):
# def run(self):
# def softReset(self):
# def stop(self):
. Output only the next line. | sim_router.setLoggerExtHandler(extHandler) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# LICENSE: GPL2
# (c) 2015 Kamil Wartanowicz
# (c) 2015 Mikolaj Bartnicki
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
class TestAuthentication(unittest.TestCase):
def test_1_dummy_xor(self):
# input:
key = "00112233445566778899AABBCCDDEEFF"
rand = "31323131353836343132313135383634"
sqn = "000000000000"
amf = "0000"
# expected output
res = "31231302716D5043B9AB9B8AF9E5D8CB"
ck = "231302716D5043B9AB9B8AF9E5D8CB31"
ik = "1302716D5043B9AB9B8AF9E5D8CB3123"
kc = "0000000000000000"
autn = "02716D5043B9000031231302716D5043"
logging.info("Codes to check:\n"
"key=%s\n"
"rand=%s\n"
"sqn=%s\n"
"amf=%s\n"
%(key, rand, sqn, amf))
<|code_end|>
with the help of current file imports:
import sys
import os.path
import logging
import unittest
from sim_soft import sim_auth
and context from other files:
# Path: sim_soft/sim_auth.py
# MASK_48_BIT = 0xFFFFFFFFFFFF
# MASK_64_BIT = 0xFFFFFFFFFFFFFFFF
# MASK_128_BIT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
# AUTH_RESULT_OK = 0xDB
# AUTH_RESULT_SYNCHORNISATION_FAILURE = 0xDC
# def rotateLeft128bit(i, n):
# def dummyXor(key, rand, sqn, amf, autn):
# def dummyXorHex(key, rand, sqn, amf, autn):
# def keyHex(key, length=16):
# def dummyXorData(rand, key, sqn, amf, autn=None):
# def authenticateDummyXor(rand, key, sqn, amf, autn=None):
, which may contain function names, class names, or code. Output only the next line. | result = sim_auth.dummyXorHex(key, rand, sqn, amf, None) |
Given the code snippet: <|code_start|> except KeyboardInterrupt:
pass
class DbusProcess(multiprocessing.Process):
def __init__(self, taskQueue, resultQueue):
multiprocessing.Process.__init__(self)
self.taskQueue = taskQueue
self.resultQueue = resultQueue
@staticmethod
def _idleQueueSync():
time.sleep(0.01) # just to synchronize queue, otherwise task can be dropped
return True
def run(self):
logging.info('D-Bus process started')
GLib.threads_init() # allow threads in GLib
GLib.idle_add(self._idleQueueSync)
DBusGMainLoop(set_as_default=True)
dbusService = SessionDBus(self.taskQueue, self.resultQueue)
try:
GLib.MainLoop().run()
except KeyboardInterrupt:
logging.debug("\nThe MainLoop will close...")
GLib.MainLoop().quit()
return
<|code_end|>
, generate the next line using the imports in this file:
import logging
import time
import multiprocessing
import Queue
import dbus
import dbus.service
import gevent
import sys
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from gevent import select as geventSelect
from sim import sim_shell
and context (functions, classes, or occasionally code) from other files:
# Path: sim/sim_shell.py
# def setupLogger():
# def __init__(self, simCtrl, interactive=False):
# def select_sim_card(self, simId):
# def apdu(self, data, channel=None, mode=None):
# def set_active_channel(self, channel):
# def query_code_status(self, name):
# def force_security_codes(self, state):
# def verify_code(self, name):
# def validate_pin1(self, state):
# def get_plmn(self):
# def set_plmn(self, value):
# def pwd(self):
# def cd(self, path):
# def ls(self):
# def read(self, path):
# def readi(self, path):
# def write(self, path, data):
# def writei(self, path, value):
# def create(self, path, param=None):
# def create_arr(self, path, fileParam=None):
# def delete(self, path):
# def resize(self, path, newFileSize, fillPattern=None):
# def extend(self, path, sizeToExtend):
# def get_ust(self, serviceId):
# def set_ust(self, serviceId, value):
# def open_channel(self, originChannel, targetChannel):
# def close_channel(self, originChannel, targetChannel):
# def log_level(self, level):
# def backup(self):
# def sat(self, param, value=None):
# def updateInteractive(self, interactive):
# def queryUser(self, question, default=''):
# def verifyCode(self, pinId):
# def updatePrompt(self):
# def responseOk(self, out=None):
# def responseNok(self, out=None):
# def getValue(self, cmd):
# def getIntValue(self, cmd):
# def statusOk(self, status):
# def assertOk(self, status, out=None):
# def assertNok(self, status, out=None):
# def checkFileConditions(self, path, accessMode):
# def modifyArrConditions(self, arrPath, arrRecord, arrValue, accessMode):
# def restoreArrConditions(self, arrPath, arrRecord, previousArrValue):
# def restorePath(self, path):
# def selectFile(self, path):
# def getAbsolutePath(self, pathName):
# def verifyCondition(self, condition):
# def verifyConditions(self, conditions, mode):
# def deleteRaw(self, path, accessMode=types.AM_EF_DELETE):
# def readRaw(self, path, forceAccess=False):
# def writeRaw(self, path, data):
# def resizeRaw(self, path, newFileSize, fillPattern):
# def extendRaw(self, path, sizeToExtend):
# def createRaw(self, path, fileParam):
# def createFile(self, path, fileParam=None):
# def createDirectory(self, path, fileParam=None):
# def createArr(self, path, fileParam):
# def _backup(self, path, node):
# def __init__(self, ss, path, accessMode, forceAccess=True):
# def __enter__(self):
# def __exit__(self, type, value, traceback):
# class SimShell(object):
# class FileAccessCondition(object):
. Output only the next line. | class SessionDBus(dbus.service.Object, sim_shell.SimShell): |
Given the code snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
patch()
class ParserTests(unittest.TestCase):
def test_parser(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from asn1crypto import parser
from ._unittest_compat import patch
and context (functions, classes, or occasionally code) from other files:
# Path: asn1crypto/parser.py
# _PY2 = sys.version_info <= (3,)
# _INSUFFICIENT_DATA_MESSAGE = 'Insufficient data - %s bytes requested but only %s available'
# _MAX_DEPTH = 10
# def emit(class_, method, tag, contents):
# def parse(contents, strict=False):
# def peek(contents):
# def _parse(encoded_data, data_len, pointer=0, lengths_only=False, depth=0):
# def _dump_header(class_, method, tag, contents):
. Output only the next line. | result = parser.parse(b'\x02\x01\x00') |
Given the code snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
patch()
if sys.version_info < (3,):
byte_cls = str
else:
byte_cls = bytes
tests_root = os.path.dirname(__file__)
fixtures_dir = os.path.join(tests_root, 'fixtures')
class OCSPTests(unittest.TestCase):
def test_parse_request(self):
with open(os.path.join(fixtures_dir, 'ocsp_request'), 'rb') as f:
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import sys
import os
from datetime import datetime
from asn1crypto import ocsp, util
from ._unittest_compat import patch
and context (functions, classes, or occasionally code) from other files:
# Path: asn1crypto/ocsp.py
# class Version(Integer):
# class CertId(Sequence):
# class ServiceLocator(Sequence):
# class RequestExtensionId(ObjectIdentifier):
# class RequestExtension(Sequence):
# class RequestExtensions(SequenceOf):
# class Request(Sequence):
# class Requests(SequenceOf):
# class ResponseType(ObjectIdentifier):
# class AcceptableResponses(SequenceOf):
# class PreferredSignatureAlgorithm(Sequence):
# class PreferredSignatureAlgorithms(SequenceOf):
# class TBSRequestExtensionId(ObjectIdentifier):
# class TBSRequestExtension(Sequence):
# class TBSRequestExtensions(SequenceOf):
# class TBSRequest(Sequence):
# class Certificates(SequenceOf):
# class Signature(Sequence):
# class OCSPRequest(Sequence):
# class OCSPResponseStatus(Enumerated):
# class ResponderId(Choice):
# class StatusGood(Null):
# class StatusUnknown(Null):
# class RevokedInfo(Sequence):
# class CertStatus(Choice):
# class CrlId(Sequence):
# class SingleResponseExtensionId(ObjectIdentifier):
# class SingleResponseExtension(Sequence):
# class SingleResponseExtensions(SequenceOf):
# class SingleResponse(Sequence):
# class Responses(SequenceOf):
# class ResponseDataExtensionId(ObjectIdentifier):
# class ResponseDataExtension(Sequence):
# class ResponseDataExtensions(SequenceOf):
# class ResponseData(Sequence):
# class BasicOCSPResponse(Sequence):
# class ResponseBytes(Sequence):
# class OCSPResponse(Sequence):
# def _set_extensions(self):
# def critical_extensions(self):
# def service_locator_value(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def nonce_value(self):
# def acceptable_responses_value(self):
# def preferred_signature_algorithms_value(self):
# def set(self, value):
# def native(self):
# def set(self, value):
# def native(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def crl_value(self):
# def archive_cutoff_value(self):
# def crl_reason_value(self):
# def invalidity_date_value(self):
# def certificate_issuer_value(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def nonce_value(self):
# def extended_revoke_value(self):
# def basic_ocsp_response(self):
# def response_data(self):
#
# Path: asn1crypto/util.py
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def __init__(self, offset, name=None):
# def __eq__(self, other):
# def __getinitargs__(self):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def _format_offset(off):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def create_timezone(offset):
# def __init__(self, year, month, day):
# def year(self):
# def month(self):
# def day(self):
# def strftime(self, format):
# def isoformat(self):
# def replace(self, year=None, month=None, day=None):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __init__(self, year, *args, **kwargs):
# def year(self):
# def month(self):
# def day(self):
# def hour(self):
# def minute(self):
# def second(self):
# def microsecond(self):
# def tzinfo(self):
# def utcoffset(self):
# def time(self):
# def date(self):
# def strftime(self, format):
# def isoformat(self, sep='T'):
# def replace(self, year=None, *args, **kwargs):
# def astimezone(self, tz):
# def timestamp(self):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __sub__(self, other):
# def __rsub__(self, other):
# def from_y2k(cls, value):
# class timezone(tzinfo): # noqa
# class _UtcWithDst(tzinfo):
# class extended_date(object):
# class extended_datetime(object):
# DAYS_IN_400_YEARS = 400 * 365 + 97
# DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
. Output only the next line. | request = ocsp.OCSPRequest.load(f.read()) |
Based on the snippet: <|code_start|>
self.assertEqual(
'successful',
response['response_status'].native
)
self.assertEqual(
'basic_ocsp_response',
response_bytes['response_type'].native
)
self.assertEqual(
'sha1_rsa',
basic_ocsp_response['signature_algorithm']['algorithm'].native
)
self.assertEqual(
None,
basic_ocsp_response['signature_algorithm']['parameters'].native
)
self.assertEqual(
'v1',
tbs_response_data['version'].native
)
self.assertEqual(
b'\x4E\xC5\x63\xD6\xB2\x05\x05\xD7\x76\xF0\x07\xED\xAC\x7D\x5A\x56\x97\x7B\xBD\x3C',
responder_id.native
)
self.assertEqual(
'by_key',
responder_id.name
)
self.assertEqual(
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import sys
import os
from datetime import datetime
from asn1crypto import ocsp, util
from ._unittest_compat import patch
and context (classes, functions, sometimes code) from other files:
# Path: asn1crypto/ocsp.py
# class Version(Integer):
# class CertId(Sequence):
# class ServiceLocator(Sequence):
# class RequestExtensionId(ObjectIdentifier):
# class RequestExtension(Sequence):
# class RequestExtensions(SequenceOf):
# class Request(Sequence):
# class Requests(SequenceOf):
# class ResponseType(ObjectIdentifier):
# class AcceptableResponses(SequenceOf):
# class PreferredSignatureAlgorithm(Sequence):
# class PreferredSignatureAlgorithms(SequenceOf):
# class TBSRequestExtensionId(ObjectIdentifier):
# class TBSRequestExtension(Sequence):
# class TBSRequestExtensions(SequenceOf):
# class TBSRequest(Sequence):
# class Certificates(SequenceOf):
# class Signature(Sequence):
# class OCSPRequest(Sequence):
# class OCSPResponseStatus(Enumerated):
# class ResponderId(Choice):
# class StatusGood(Null):
# class StatusUnknown(Null):
# class RevokedInfo(Sequence):
# class CertStatus(Choice):
# class CrlId(Sequence):
# class SingleResponseExtensionId(ObjectIdentifier):
# class SingleResponseExtension(Sequence):
# class SingleResponseExtensions(SequenceOf):
# class SingleResponse(Sequence):
# class Responses(SequenceOf):
# class ResponseDataExtensionId(ObjectIdentifier):
# class ResponseDataExtension(Sequence):
# class ResponseDataExtensions(SequenceOf):
# class ResponseData(Sequence):
# class BasicOCSPResponse(Sequence):
# class ResponseBytes(Sequence):
# class OCSPResponse(Sequence):
# def _set_extensions(self):
# def critical_extensions(self):
# def service_locator_value(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def nonce_value(self):
# def acceptable_responses_value(self):
# def preferred_signature_algorithms_value(self):
# def set(self, value):
# def native(self):
# def set(self, value):
# def native(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def crl_value(self):
# def archive_cutoff_value(self):
# def crl_reason_value(self):
# def invalidity_date_value(self):
# def certificate_issuer_value(self):
# def _set_extensions(self):
# def critical_extensions(self):
# def nonce_value(self):
# def extended_revoke_value(self):
# def basic_ocsp_response(self):
# def response_data(self):
#
# Path: asn1crypto/util.py
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def __init__(self, offset, name=None):
# def __eq__(self, other):
# def __getinitargs__(self):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def _format_offset(off):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def create_timezone(offset):
# def __init__(self, year, month, day):
# def year(self):
# def month(self):
# def day(self):
# def strftime(self, format):
# def isoformat(self):
# def replace(self, year=None, month=None, day=None):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __init__(self, year, *args, **kwargs):
# def year(self):
# def month(self):
# def day(self):
# def hour(self):
# def minute(self):
# def second(self):
# def microsecond(self):
# def tzinfo(self):
# def utcoffset(self):
# def time(self):
# def date(self):
# def strftime(self, format):
# def isoformat(self, sep='T'):
# def replace(self, year=None, *args, **kwargs):
# def astimezone(self, tz):
# def timestamp(self):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __sub__(self, other):
# def __rsub__(self, other):
# def from_y2k(cls, value):
# class timezone(tzinfo): # noqa
# class _UtcWithDst(tzinfo):
# class extended_date(object):
# class extended_datetime(object):
# DAYS_IN_400_YEARS = 400 * 365 + 97
# DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
. Output only the next line. | datetime(2015, 5, 22, 16, 24, 8, tzinfo=util.timezone.utc), |
Continue the code snippet: <|code_start|>the following items:
- iri_to_uri()
- uri_to_iri()
"""
from __future__ import unicode_literals, division, absolute_import, print_function
if sys.version_info < (3,):
else:
def iri_to_uri(value, normalize=False):
"""
Encodes a unicode IRI into an ASCII byte string URI
:param value:
A unicode string of an IRI
:param normalize:
A bool that controls URI normalization
:return:
A byte string of the ASCII-encoded URI
"""
if not isinstance(value, str_cls):
<|code_end|>
. Use current file imports:
from encodings import idna # noqa
from ._errors import unwrap
from ._types import byte_cls, str_cls, type_name, bytes_to_list, int_types
from urlparse import urlsplit, urlunsplit
from urllib import (
quote as urlquote,
unquote as unquote_to_bytes,
)
from urllib.parse import (
quote as urlquote,
unquote_to_bytes,
urlsplit,
urlunsplit,
)
import codecs
import re
import sys
and context (classes, functions, or code) from other files:
# Path: asn1crypto/_errors.py
# def unwrap(string, *params):
# """
# Takes a multi-line string and does the following:
#
# - dedents
# - converts newlines with text before and after into a single line
# - strips leading and trailing whitespace
#
# :param string:
# The string to format
#
# :param *params:
# Params to interpolate into the string
#
# :return:
# The formatted string
# """
#
# output = textwrap.dedent(string)
#
# # Unwrap lines, taking into account bulleted lists, ordered lists and
# # underlines consisting of = signs
# if output.find('\n') != -1:
# output = re.sub('(?<=\\S)\n(?=[^ \n\t\\d\\*\\-=])', ' ', output)
#
# if params:
# output = output % params
#
# output = output.strip()
#
# return output
. Output only the next line. | raise TypeError(unwrap( |
Given the following code snippet before the placeholder: <|code_start|> tag = 0
while True:
if data_len < pointer + 1:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer))
num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer]
pointer += 1
if num == 0x80 and tag == 0:
raise ValueError('Non-minimal tag encoding')
tag *= 128
tag += num & 127
if num >> 7 == 0:
break
if tag < 31:
raise ValueError('Non-minimal tag encoding')
if data_len < pointer + 1:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer))
length_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer]
pointer += 1
trailer = b''
if length_octet >> 7 == 0:
contents_end = pointer + (length_octet & 127)
else:
length_octets = length_octet & 127
if length_octets:
if data_len < pointer + length_octets:
raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (length_octets, data_len - pointer))
pointer += length_octets
<|code_end|>
, predict the next line using imports from the current file:
import sys
from ._types import byte_cls, chr_cls, type_name
from .util import int_from_bytes, int_to_bytes
and context including class names, function names, and sometimes code from other files:
# Path: asn1crypto/util.py
# def int_from_bytes(value, signed=False):
# """
# Converts a byte string to an integer
#
# :param value:
# The byte string to convert
#
# :param signed:
# If the byte string should be interpreted using two's complement
#
# :return:
# An integer
# """
#
# if value == b'':
# return 0
#
# num = long(value.encode("hex"), 16) # noqa
#
# if not signed:
# return num
#
# # Check for sign bit and handle two's complement
# if ord(value[0:1]) & 0x80:
# bit_len = len(value) * 8
# return num - (1 << bit_len)
#
# return num
#
# def int_to_bytes(value, signed=False, width=None):
# """
# Converts an integer to a byte string
#
# :param value:
# The integer to convert
#
# :param signed:
# If the byte string should be encoded using two's complement
#
# :param width:
# If None, the minimal possible size (but at least 1),
# otherwise an integer of the byte width for the return value
#
# :return:
# A byte string
# """
#
# if value == 0 and width == 0:
# return b''
#
# # Handle negatives in two's complement
# is_neg = False
# if signed and value < 0:
# is_neg = True
# bits = int(math.ceil(len('%x' % abs(value)) / 2.0) * 8)
# value = (value + (1 << bits)) % (1 << bits)
#
# hex_str = '%x' % value
# if len(hex_str) & 1:
# hex_str = '0' + hex_str
#
# output = hex_str.decode('hex')
#
# if signed and not is_neg and ord(output[0:1]) & 0x80:
# output = b'\x00' + output
#
# if width is not None:
# if len(output) > width:
# raise OverflowError('int too big to convert')
# if is_neg:
# pad_char = b'\xFF'
# else:
# pad_char = b'\x00'
# output = (pad_char * (width - len(output))) + output
# elif is_neg and ord(output[0:1]) & 0x80 == 0:
# output = b'\xFF' + output
#
# return output
. Output only the next line. | contents_end = pointer + int_from_bytes(encoded_data[pointer - length_octets:pointer], signed=False) |
Given the code snippet: <|code_start|> An integer ASN.1 tag value
:param contents:
A byte string of the encoded byte contents
:return:
A byte string of the ASN.1 DER header
"""
header = b''
id_num = 0
id_num |= class_ << 6
id_num |= method << 5
if tag >= 31:
cont_bit = 0
while tag > 0:
header = chr_cls(cont_bit | (tag & 0x7f)) + header
if not cont_bit:
cont_bit = 0x80
tag = tag >> 7
header = chr_cls(id_num | 31) + header
else:
header += chr_cls(id_num | tag)
length = len(contents)
if length <= 127:
header += chr_cls(length)
else:
<|code_end|>
, generate the next line using the imports in this file:
import sys
from ._types import byte_cls, chr_cls, type_name
from .util import int_from_bytes, int_to_bytes
and context (functions, classes, or occasionally code) from other files:
# Path: asn1crypto/util.py
# def int_from_bytes(value, signed=False):
# """
# Converts a byte string to an integer
#
# :param value:
# The byte string to convert
#
# :param signed:
# If the byte string should be interpreted using two's complement
#
# :return:
# An integer
# """
#
# if value == b'':
# return 0
#
# num = long(value.encode("hex"), 16) # noqa
#
# if not signed:
# return num
#
# # Check for sign bit and handle two's complement
# if ord(value[0:1]) & 0x80:
# bit_len = len(value) * 8
# return num - (1 << bit_len)
#
# return num
#
# def int_to_bytes(value, signed=False, width=None):
# """
# Converts an integer to a byte string
#
# :param value:
# The integer to convert
#
# :param signed:
# If the byte string should be encoded using two's complement
#
# :param width:
# If None, the minimal possible size (but at least 1),
# otherwise an integer of the byte width for the return value
#
# :return:
# A byte string
# """
#
# if value == 0 and width == 0:
# return b''
#
# # Handle negatives in two's complement
# is_neg = False
# if signed and value < 0:
# is_neg = True
# bits = int(math.ceil(len('%x' % abs(value)) / 2.0) * 8)
# value = (value + (1 << bits)) % (1 << bits)
#
# hex_str = '%x' % value
# if len(hex_str) & 1:
# hex_str = '0' + hex_str
#
# output = hex_str.decode('hex')
#
# if signed and not is_neg and ord(output[0:1]) & 0x80:
# output = b'\x00' + output
#
# if width is not None:
# if len(output) > width:
# raise OverflowError('int too big to convert')
# if is_neg:
# pad_char = b'\xFF'
# else:
# pad_char = b'\x00'
# output = (pad_char * (width - len(output))) + output
# elif is_neg and ord(output[0:1]) & 0x80 == 0:
# output = b'\xFF' + output
#
# return output
. Output only the next line. | length_bytes = int_to_bytes(length) |
Given the code snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
patch()
if sys.version_info < (3,):
py2 = True
byte_cls = str
num_cls = long # noqa
else:
py2 = False
byte_cls = bytes
num_cls = int
tests_root = os.path.dirname(__file__)
fixtures_dir = os.path.join(tests_root, 'fixtures')
<|code_end|>
, generate the next line using the imports in this file:
import os
import platform
import sys
import unittest
from datetime import date, datetime, time, timedelta
from asn1crypto import util
from .unittest_data import data_decorator
from ._unittest_compat import patch
and context (functions, classes, or occasionally code) from other files:
# Path: asn1crypto/util.py
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def __init__(self, offset, name=None):
# def __eq__(self, other):
# def __getinitargs__(self):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def _format_offset(off):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def create_timezone(offset):
# def __init__(self, year, month, day):
# def year(self):
# def month(self):
# def day(self):
# def strftime(self, format):
# def isoformat(self):
# def replace(self, year=None, month=None, day=None):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __init__(self, year, *args, **kwargs):
# def year(self):
# def month(self):
# def day(self):
# def hour(self):
# def minute(self):
# def second(self):
# def microsecond(self):
# def tzinfo(self):
# def utcoffset(self):
# def time(self):
# def date(self):
# def strftime(self, format):
# def isoformat(self, sep='T'):
# def replace(self, year=None, *args, **kwargs):
# def astimezone(self, tz):
# def timestamp(self):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __sub__(self, other):
# def __rsub__(self, other):
# def from_y2k(cls, value):
# class timezone(tzinfo): # noqa
# class _UtcWithDst(tzinfo):
# class extended_date(object):
# class extended_datetime(object):
# DAYS_IN_400_YEARS = 400 * 365 + 97
# DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
. Output only the next line. | utc = util.timezone.utc |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
patch()
if sys.version_info < (3,):
byte_cls = str
num_cls = long # noqa
else:
byte_cls = bytes
num_cls = int
tests_root = os.path.dirname(__file__)
fixtures_dir = os.path.join(tests_root, 'fixtures')
class CSRTests(unittest.TestCase):
def test_parse_csr(self):
with open(os.path.join(fixtures_dir, 'test-inter-der.csr'), 'rb') as f:
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import sys
import os
from asn1crypto import csr, util
from ._unittest_compat import patch
and context including class names, function names, and sometimes code from other files:
# Path: asn1crypto/csr.py
# class Version(Integer):
# class CSRAttributeType(ObjectIdentifier):
# class SetOfDirectoryString(SetOf):
# class Attribute(Sequence):
# class SetOfAttributes(SetOf):
# class SetOfExtensions(SetOf):
# class MicrosoftEnrollmentCSProvider(Sequence):
# class SetOfMicrosoftEnrollmentCSProvider(SetOf):
# class MicrosoftRequestClientInfo(Sequence):
# class SetOfMicrosoftRequestClientInfo(SetOf):
# class CRIAttribute(Sequence):
# class CRIAttributes(SetOf):
# class CertificationRequestInfo(Sequence):
# class CertificationRequest(Sequence):
#
# Path: asn1crypto/util.py
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def __init__(self, offset, name=None):
# def __eq__(self, other):
# def __getinitargs__(self):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def _format_offset(off):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def create_timezone(offset):
# def __init__(self, year, month, day):
# def year(self):
# def month(self):
# def day(self):
# def strftime(self, format):
# def isoformat(self):
# def replace(self, year=None, month=None, day=None):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __init__(self, year, *args, **kwargs):
# def year(self):
# def month(self):
# def day(self):
# def hour(self):
# def minute(self):
# def second(self):
# def microsecond(self):
# def tzinfo(self):
# def utcoffset(self):
# def time(self):
# def date(self):
# def strftime(self, format):
# def isoformat(self, sep='T'):
# def replace(self, year=None, *args, **kwargs):
# def astimezone(self, tz):
# def timestamp(self):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __sub__(self, other):
# def __rsub__(self, other):
# def from_y2k(cls, value):
# class timezone(tzinfo): # noqa
# class _UtcWithDst(tzinfo):
# class extended_date(object):
# class extended_datetime(object):
# DAYS_IN_400_YEARS = 400 * 365 + 97
# DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
. Output only the next line. | certification_request = csr.CertificationRequest.load(f.read()) |
Given snippet: <|code_start|>
patch()
if sys.version_info < (3,):
byte_cls = str
num_cls = long # noqa
else:
byte_cls = bytes
num_cls = int
tests_root = os.path.dirname(__file__)
fixtures_dir = os.path.join(tests_root, 'fixtures')
class CSRTests(unittest.TestCase):
def test_parse_csr(self):
with open(os.path.join(fixtures_dir, 'test-inter-der.csr'), 'rb') as f:
certification_request = csr.CertificationRequest.load(f.read())
cri = certification_request['certification_request_info']
self.assertEqual(
'v1',
cri['version'].native
)
self.assertEqual(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import sys
import os
from asn1crypto import csr, util
from ._unittest_compat import patch
and context:
# Path: asn1crypto/csr.py
# class Version(Integer):
# class CSRAttributeType(ObjectIdentifier):
# class SetOfDirectoryString(SetOf):
# class Attribute(Sequence):
# class SetOfAttributes(SetOf):
# class SetOfExtensions(SetOf):
# class MicrosoftEnrollmentCSProvider(Sequence):
# class SetOfMicrosoftEnrollmentCSProvider(SetOf):
# class MicrosoftRequestClientInfo(Sequence):
# class SetOfMicrosoftRequestClientInfo(SetOf):
# class CRIAttribute(Sequence):
# class CRIAttributes(SetOf):
# class CertificationRequestInfo(Sequence):
# class CertificationRequest(Sequence):
#
# Path: asn1crypto/util.py
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def __init__(self, offset, name=None):
# def __eq__(self, other):
# def __getinitargs__(self):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def int_to_bytes(value, signed=False, width=None):
# def int_from_bytes(value, signed=False):
# def _format_offset(off):
# def tzname(self, dt):
# def utcoffset(self, dt):
# def dst(self, dt):
# def create_timezone(offset):
# def __init__(self, year, month, day):
# def year(self):
# def month(self):
# def day(self):
# def strftime(self, format):
# def isoformat(self):
# def replace(self, year=None, month=None, day=None):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __init__(self, year, *args, **kwargs):
# def year(self):
# def month(self):
# def day(self):
# def hour(self):
# def minute(self):
# def second(self):
# def microsecond(self):
# def tzinfo(self):
# def utcoffset(self):
# def time(self):
# def date(self):
# def strftime(self, format):
# def isoformat(self, sep='T'):
# def replace(self, year=None, *args, **kwargs):
# def astimezone(self, tz):
# def timestamp(self):
# def __str__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def _comparison_error(self, other):
# def __cmp__(self, other):
# def __lt__(self, other):
# def __le__(self, other):
# def __gt__(self, other):
# def __ge__(self, other):
# def __add__(self, other):
# def __sub__(self, other):
# def __rsub__(self, other):
# def from_y2k(cls, value):
# class timezone(tzinfo): # noqa
# class _UtcWithDst(tzinfo):
# class extended_date(object):
# class extended_datetime(object):
# DAYS_IN_400_YEARS = 400 * 365 + 97
# DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
which might include code, classes, or functions. Output only the next line. | util.OrderedDict([ |
Here is a snippet: <|code_start|>
DEFAULTSPACING = 1.0 / 10
class Label(BaseControl):
"""
Text displayer.
@rtype : Label
"""
def __init__(self, left, top, width, text, parent, pinning=PinningEnum.TopLeft, fontSize=10, fontID='default',
color=None, ID=None, imgID=None,
rotation=None, outlineLength=OutlineLenghtEnum.NoOutline, style=None):
"""
:param borderSize:
:type borderSize:
"""
<|code_end|>
. Write the next line using the current file imports:
from .SingleCharClass import *
from .Styling import DefaultStyle
from .TextEnums import *
and context from other files:
# Path: e3d/gui/Styling/StyleClass.py
# class DefaultStyle(object):
# def __init__(self, baseColor=None):
# if baseColor is None:
# baseColor = RGBA255(30, 30, 30, 255)
#
# self._baseColor = vec4(0)
# self.activeColor = RGB1(.8, .4, 0)
# self.name = 'Default'
# self.raisedGradientColor0 = WHITE
# self.raisedGradientColor1 = BLACK
# self.sunkenGradientColor0 = BLACK
# self.sunkenGradientColor1 = WHITE
# self.pressedGradientColor0 = BLACK
# self.pressedGradientColor1 = WHITE
# self.hoverGradientColor0 = WHITE
# self.hoverGradientColor1 = BLACK
# self.autoRaiseGradientColor0 = WHITE
# self.autoRaiseGradientColor1 = BLACK
# self.baseColor = baseColor
#
# def _buildGradients(self):
# baseColor = self._baseColor
# color0 = (baseColor + WHITE / 2.0) / 2.0
# color0.w = baseColor.w
# color1 = baseColor / 4.0
# color1.w = baseColor.w
# color2 = (baseColor + WHITE / 3.0) / 2.0
# color2.w = baseColor.w
# color3 = baseColor / 6.0
# color3.w = baseColor.w
# color4 = (baseColor + WHITE / 4.0) / 2.0
# color4.w = baseColor.w
# color5 = baseColor / 8.0
# color5.w = baseColor.w
# color6 = (baseColor + WHITE / 1.8) / 2.0
# color6.w = baseColor.w
# color7 = baseColor / 1.4
# color7.w = baseColor.w
#
# self.raisedGradientColor0 = color2
# self.raisedGradientColor1 = color3
# self.sunkenGradientColor0 = color3
# self.sunkenGradientColor1 = color2
# self.pressedGradientColor0 = color4
# self.pressedGradientColor1 = color5
# self.hoverGradientColor0 = color0
# self.hoverGradientColor1 = color1
# self.autoRaiseGradientColor0 = color6
# self.autoRaiseGradientColor1 = color7
#
# def __repr__(self):
# return str(self.name)
#
# def saveToFile(self, path):
# vals = {}
# with open(path, 'w') as file:
# attribs = dir(self)
# for att in attribs:
# if not att.startswith('_'):
# vals[att] = getattr(self, att)
# dump(vals, file, indent=4)
#
# @staticmethod
# def readFromFile(path):
# style = DefaultStyle()
# with open(path) as file:
# vals = load(file)
# for att in vals.keys:
# setattr(style, att, vals[att])
#
# return style
#
# @property
# def baseColor(self):
# return self._baseColor
#
# @baseColor.setter
# def baseColor(self, value):
# baseColor = vec4(value)
# self._baseColor = value
# self.backgroundColor = vec4(baseColor)
# self.fontColor = WHITE
# self.fontOutlineColor = BLUE
# self.fontSize = 10
# self.borderSize = 1
# self.borderColor = fromRGB1_A(baseColor / 4.0, 1)
# self.focusBorderColor = ORANGE
# self.hoverBorderColor = GREEN
# self.gradientType = GradientTypesEnum.noGradient
# self.hoverColor = fromRGB1_A((baseColor + (WHITE / 10.0)), baseColor.w)
# self.pressedColor = fromRGB1_A(baseColor / 1.5, baseColor.w)
# self.buttonStyleHint = StyleHintsEnum.Raised
# self.controlStyleHint = StyleHintsEnum.Raised
#
# self._buildGradients()
#
# def _copy(self):
# return copy(self)
, which may include functions, classes, or code. Output only the next line. | style = style or DefaultStyle(color) |
Based on the snippet: <|code_start|> filename extension and see if an unpacker was registered for that
extension.
In case none is found, a ValueError is raised.
"""
if extract_dir is None:
extract_dir = os.getcwd()
if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("Unknown unpack format '{0}'".format(format))
func = format_info[1]
func(filename, extract_dir, **dict(format_info[2]))
else:
# we need to look at the registered unpackers supported extensions
format = _find_unpack_format(filename)
if format is None:
raise ReadError("Unknown archive format '{0}'".format(filename))
func = _UNPACK_FORMATS[format][1]
kwargs = dict(_UNPACK_FORMATS[format][2])
func(filename, extract_dir, **kwargs)
else:
if version_info[1] < 5:
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context (classes, functions, sometimes code) from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
. Output only the next line. | class PluginsManager(BaseManager): |
Given snippet: <|code_start|> def __init__(self):
super(PluginsManager, self).__init__()
self._pluginPaths = {}
self._tempPluginPaths = {}
self._enabled = {}
self._plugins = {}
def addPlugin(self, ID, pluginPath, isEnabled=True):
if ID in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) already exist.'.format(ID))
self._pluginPaths[ID] = pluginPath
self._enabled[ID] = isEnabled
self._plugins[ID] = self._injectPlugin(ID, pluginPath)
def removePlugin(self, ID):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled.pop(ID)
self._pluginPaths.pop(ID)
self._plugins.pop(ID)
def setPluginEnableState(self, ID, stateBool):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled[ID] = bool(stateBool)
def _injectPlugin(self, ID, pluginPath):
tempDir = mkdtemp(prefix='e3d_' + ID + '_')
self._tempPluginPaths[ID] = tempDir
unpack_archive(pluginPath, tempDir, 'gztar')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
which might include code, classes, or functions. Output only the next line. | plugDesc = PluginDescription.fromDisk(tempDir) |
Here is a snippet: <|code_start|> self._plugins[ID] = self._injectPlugin(ID, pluginPath)
def removePlugin(self, ID):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled.pop(ID)
self._pluginPaths.pop(ID)
self._plugins.pop(ID)
def setPluginEnableState(self, ID, stateBool):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled[ID] = bool(stateBool)
def _injectPlugin(self, ID, pluginPath):
tempDir = mkdtemp(prefix='e3d_' + ID + '_')
self._tempPluginPaths[ID] = tempDir
unpack_archive(pluginPath, tempDir, 'gztar')
plugDesc = PluginDescription.fromDisk(tempDir)
module_name = plugDesc.name.lower().replace(' ', '_')
mainFilePath = path.join(tempDir, MAINFILENAME)
plugin_module = self._loadModule(mainFilePath, module_name)
mainClass = getattr(plugin_module, MAINCLASSNAME)(self._engine)
if not issubclass(type(mainClass), Runnable):
raise TypeError('main class of plugin \'{}\' must inherith from Runnable'.format(plugDesc.name))
data = {'name': ID, 'path': pluginPath}
mainClass.preparePlugin(data)
<|code_end|>
. Write the next line using the current file imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
, which may include functions, classes, or code. Output only the next line. | return _Plugin(plugDesc, mainClass, pluginPath) |
Based on the snippet: <|code_start|> self._pluginPaths = {}
self._tempPluginPaths = {}
self._enabled = {}
self._plugins = {}
def addPlugin(self, ID, pluginPath, isEnabled=True):
if ID in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) already exist.'.format(ID))
self._pluginPaths[ID] = pluginPath
self._enabled[ID] = isEnabled
self._plugins[ID] = self._injectPlugin(ID, pluginPath)
def removePlugin(self, ID):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled.pop(ID)
self._pluginPaths.pop(ID)
self._plugins.pop(ID)
def setPluginEnableState(self, ID, stateBool):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled[ID] = bool(stateBool)
def _injectPlugin(self, ID, pluginPath):
tempDir = mkdtemp(prefix='e3d_' + ID + '_')
self._tempPluginPaths[ID] = tempDir
unpack_archive(pluginPath, tempDir, 'gztar')
plugDesc = PluginDescription.fromDisk(tempDir)
module_name = plugDesc.name.lower().replace(' ', '_')
<|code_end|>
, predict the immediate next line with the help of imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context (classes, functions, sometimes code) from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
. Output only the next line. | mainFilePath = path.join(tempDir, MAINFILENAME) |
Continue the code snippet: <|code_start|> self._plugins = {}
def addPlugin(self, ID, pluginPath, isEnabled=True):
if ID in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) already exist.'.format(ID))
self._pluginPaths[ID] = pluginPath
self._enabled[ID] = isEnabled
self._plugins[ID] = self._injectPlugin(ID, pluginPath)
def removePlugin(self, ID):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled.pop(ID)
self._pluginPaths.pop(ID)
self._plugins.pop(ID)
def setPluginEnableState(self, ID, stateBool):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled[ID] = bool(stateBool)
def _injectPlugin(self, ID, pluginPath):
tempDir = mkdtemp(prefix='e3d_' + ID + '_')
self._tempPluginPaths[ID] = tempDir
unpack_archive(pluginPath, tempDir, 'gztar')
plugDesc = PluginDescription.fromDisk(tempDir)
module_name = plugDesc.name.lower().replace(' ', '_')
mainFilePath = path.join(tempDir, MAINFILENAME)
plugin_module = self._loadModule(mainFilePath, module_name)
<|code_end|>
. Use current file imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context (classes, functions, or code) from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
. Output only the next line. | mainClass = getattr(plugin_module, MAINCLASSNAME)(self._engine) |
Based on the snippet: <|code_start|>
def addPlugin(self, ID, pluginPath, isEnabled=True):
if ID in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) already exist.'.format(ID))
self._pluginPaths[ID] = pluginPath
self._enabled[ID] = isEnabled
self._plugins[ID] = self._injectPlugin(ID, pluginPath)
def removePlugin(self, ID):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled.pop(ID)
self._pluginPaths.pop(ID)
self._plugins.pop(ID)
def setPluginEnableState(self, ID, stateBool):
if ID not in self._pluginPaths.keys():
raise RuntimeError('the specified ID ({}) does not exist.'.format(ID))
self._enabled[ID] = bool(stateBool)
def _injectPlugin(self, ID, pluginPath):
tempDir = mkdtemp(prefix='e3d_' + ID + '_')
self._tempPluginPaths[ID] = tempDir
unpack_archive(pluginPath, tempDir, 'gztar')
plugDesc = PluginDescription.fromDisk(tempDir)
module_name = plugDesc.name.lower().replace(' ', '_')
mainFilePath = path.join(tempDir, MAINFILENAME)
plugin_module = self._loadModule(mainFilePath, module_name)
mainClass = getattr(plugin_module, MAINCLASSNAME)(self._engine)
<|code_end|>
, predict the immediate next line with the help of imports:
from .._baseManager import BaseManager
from .PluginHandlers import PluginDescription, _Plugin
from .RunnableClass import MAINFILENAME, MAINCLASSNAME, Runnable
from sys import version_info
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from shutil import unpack_archive
from importlib.machinery import SourceFileLoader
from importlib import util
import imp
and context (classes, functions, sometimes code) from other files:
# Path: e3d/_baseManager.py
# class BaseManager(object):
# def __init__(self):
# self._engine = None
#
# def initialize(self, engine):
# self._engine = engine
#
# def terminate(self):
# pass
#
# Path: e3d/plugin_management/PluginHandlers.py
# class PluginDescription(object):
# def __init__(self, name='', description='', authorName='', authorEmail=''):
# self.name = name
# self.description = description
# self.authorName = authorName
# self.authorEmail = authorEmail
#
# def __repr__(self):
# return self.name
#
# def _toDict(self):
# d = dir(self)
# dd = {v: getattr(self, v) for v in d if not v.startswith('_') and not callable(getattr(self, v))}
# return dd
#
# def saveToDisk(self, destFolder):
# try:
# finalPath = path.abspath(path.join(destFolder, DESCRIPTIONNAME + '.json'))
# with open(finalPath, 'w') as dest:
# dump(self._toDict(), dest, indent=4)
# except:
# raise
#
# @staticmethod
# def fromDisk(folderPath):
# descriptionPath = path.abspath(path.join(folderPath, DESCRIPTIONNAME + '.json'))
# if not path.exists(descriptionPath):
# raise FileNotFoundError('required plugin description file not found.')
# with open(descriptionPath) as desc:
# data = load(desc)
#
# description = PluginDescription(**data)
# return description
#
# class _Plugin(object):
# def __init__(self, description, mainClass, pluginPath):
# self.description = description
# self.mainClass = mainClass
# self.pluginPath = pluginPath
#
# Path: e3d/plugin_management/RunnableClass.py
# MAINFILENAME = 'main.py'
#
# MAINCLASSNAME = 'MAIN'
#
# class Runnable(object):
# def __init__(self, engine):
# self.engine = engine
# self.repiteCurrentPass = False
#
# def preparePlugin(self, data):
# pass
#
# def onDrawPass(self, passNumber):
# pass
#
# def onPreUpdate(self):
# pass
#
# def onPostUpdate(self):
# pass
#
# def terminate(self):
# pass
. Output only the next line. | if not issubclass(type(mainClass), Runnable): |
Using the snippet: <|code_start|>
class ColorfullStyle(DefaultStyle):
def __init__(self):
super(ColorfullStyle, self).__init__(RGB1(.5, 0, .5))
self.name = 'Colorfull'
self.baseColor = fromRGB1_A(RED / 2.0 + BLUE, 1)
self.borderColor = YELLOW
self.borderSize = 3
self.fontColor = ORANGE
<|code_end|>
, determine the next line of code. You have imports:
from .StyleClass import DefaultStyle, GradientTypesEnum
from ...Colors import *
from cycgkit.cgtypes import vec4
and context (class names, function names, or code) available:
# Path: e3d/gui/Styling/StyleClass.py
# class StyleHintsEnum(object):
# class DefaultStyle(object):
# def __init__(self, baseColor=None):
# def _buildGradients(self):
# def __repr__(self):
# def saveToFile(self, path):
# def readFromFile(path):
# def baseColor(self):
# def baseColor(self, value):
# def _copy(self):
. Output only the next line. | self.gradientType = GradientTypesEnum.LeftCorner |
Given the code snippet: <|code_start|>
class SoundsManager(Manager):
def __init__(self):
"""
Keeps references to sounds in use.
@rtype : SoundsManager
"""
super(SoundsManager, self).__init__()
self._soundIDs = {}
self._lastListenerPosition = vec3(0)
self._lastListenerOrientation = [0, 0, 1, 0, 1, 0]
self._used = {}
# al.alDistanceModel(al.AL_LINEAR_DISTANCE_CLAMPED)
# al.alDistanceModel(al.AL_LINEAR_DISTANCE)
# al.alDistanceModel(al.AL_INVERSE_DISTANCE_CLAMPED)
# al.alDistanceModel(al.AL_EXPONENT_DISTANCE) # << realistic
# al.alDistanceModel(al.AL_EXPONENT_DISTANCE_CLAMPED)
def idExists(self, ID):
return ID in self._soundIDs
def load(self, ID, filePath, parent=None, isStream=False, bufferSize=48000, maxBufferNumber=3):
if self.idExists(ID):
raise RuntimeError('the ID is in use.')
<|code_end|>
, generate the next line using the imports in this file:
from hissing import Manager
from cycgkit.cgtypes import vec3
from .SoundClass import Sound
and context (functions, classes, or occasionally code) from other files:
# Path: e3d/sound_management/SoundClass.py
# class Sound(HS, Attachable):
# def __init__(self, parent, manager, filePath, isStream, bufferSize, maxBufferNumber):
# """
#
# @type buffer: audio.SoundData
# """
# HS.__init__(self, manager, filePath, isStream, bufferSize, maxBufferNumber)
# Attachable.__init__(self, parent)
#
# # looped = property(fget=_get_looped, fset=_set_looped)
#
# # channelCount = property(fget=_get_ChannelCount)
#
# # minDistance = property(_getMinDistance, _setMinDistance)
#
# # maxDistance = property(_getMaxDistance, _setMaxDistance)
. Output only the next line. | sound = Sound(parent, self, filePath, isStream, bufferSize, maxBufferNumber) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.