Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|> self.args = args
self.model = model
self.layers = self.args.layers if layers is None else layers
self.layer_dim = self.args.layer_dim if layer_dim is None else layer_dim
self.output_dim = self.args.output_dim if output_dim is None else output_dim
self.activation = CategoricalParameter(ACTIVATIONS, self.args.activation)
self.init = CategoricalParameter(INITIALIZERS, self.args.init)
self.dropout = self.args.dropout
self.gated = 1 if self.args.gated is None else self.args.gated # None means --gated was given with no argument
self.num_labels = num_labels
self.input_dim = self.input_keys = self.weights = None
@property
def total_layers(self):
return self.layers + (1 if self.num_labels else 0)
def init_params(self, input_dim):
assert input_dim, "Zero input dimension to MLP"
self.input_dim = input_dim
if self.layers > 0:
W0 = self.params.get("W0")
if W0:
value = W0.as_array()
old_input_dim = value.shape[1]
extra_dim = self.input_dim - old_input_dim
if extra_dim: # Duplicate suffix of input dimension to accommodate extra input
assert extra_dim > 0, "%s: input dimension reduced from %d to %d" % (
"/".join(self.save_path), old_input_dim, self.input_dim)
value[:, -extra_dim:] /= 2
W0.set_value(value)
<|code_end|>
. Use current file imports:
(from itertools import groupby
from .constants import ACTIVATIONS, INITIALIZERS, CategoricalParameter
from .sub_model import SubModel
from .util import randomize_orthonormal
import dynet as dy
import re)
and context including class names, function names, or small code snippets from other files:
# Path: tupa/classifiers/nn/constants.py
# ACTIVATIONS = {
# "cube": "cube",
# "tanh": "tanh",
# "sigmoid": "logistic",
# "relu": "rectify",
# }
#
# INITIALIZERS = {
# # "saxe": "SaxeInitializer",
# "glorot_uniform": "GlorotInitializer",
# "normal": "NormalInitializer",
# }
#
# class CategoricalParameter:
# def __init__(self, values, string):
# self._value = self._string = None
# self.values = values
# self.string = string
#
# def __call__(self):
# import dynet as dy
# return getattr(dy, self._value)
#
# @property
# def string(self):
# return self._string
#
# @string.setter
# def string(self, s):
# self._string = s
# self._value = self.values.get(s)
#
# def __str__(self):
# return self._string
#
# Path: tupa/classifiers/nn/sub_model.py
# class SubModel:
# def __init__(self, params=None, save_path=(), shared=False, copy_shared=False):
# self.params = OrderedDict() if params is None else params # string (param identifier) -> parameter
# self.save_path = save_path
# self.shared = shared
# self.copy_shared = copy_shared
#
# def save_sub_model(self, d, *args):
# self.get_sub_dict(d).update(args + (("param_keys", list(self.params.keys())),))
# return list(self.params.values())
#
# def load_sub_model(self, d, *args, load_path=None):
# d = self.get_sub_dict(d, load_path=load_path)
# param_keys = d.get("param_keys", ())
# assert len(param_keys) <= len(args), "%s loaded values: expected %d, got %d" % ("/".join(self.save_path),
# len(param_keys), len(args))
# self.params.clear()
# self.params.update(zip(param_keys, args))
# return d
#
# def get_sub_dict(self, d, load_path=None):
# for element in load_path or self.save_path:
# d = d.setdefault(element, OrderedDict())
# return d
#
# def params_str(self):
# return "/".join(self.save_path) + (": " if self.save_path else "") + ", ".join(self.params.keys())
#
# def invalidate_caches(self):
# for model in self.sub_models():
# model.invalidate_caches()
#
# def sub_models(self):
# return ()
#
# Path: tupa/classifiers/nn/util.py
# def randomize_orthonormal(*parameters, activation=None): # Saxe et al., 2014 (https://arxiv.org/abs/1312.6120)
# for param in parameters:
# shape = param.shape()
# if len(shape) == 2 and shape[0] == shape[1] > 1:
# init, _, _ = np.linalg.svd(np.random.randn(*shape))
# if str(activation) == "relu":
# init *= np.sqrt(2)
# param.set_value(init)
. Output only the next line. | extra_value = value[:, -extra_dim:] |
Next line prediction: <|code_start|>
MLP_PARAM_PATTERN = re.compile(r"[Wb]\d+")
class MultilayerPerceptron(SubModel):
def __init__(self, config, args, model, layers=None, layer_dim=None, output_dim=None, num_labels=None, params=None,
**kwargs):
super().__init__(params=params, **kwargs)
self.config = config
self.args = args
self.model = model
self.layers = self.args.layers if layers is None else layers
self.layer_dim = self.args.layer_dim if layer_dim is None else layer_dim
self.output_dim = self.args.output_dim if output_dim is None else output_dim
self.activation = CategoricalParameter(ACTIVATIONS, self.args.activation)
self.init = CategoricalParameter(INITIALIZERS, self.args.init)
self.dropout = self.args.dropout
self.gated = 1 if self.args.gated is None else self.args.gated # None means --gated was given with no argument
self.num_labels = num_labels
self.input_dim = self.input_keys = self.weights = None
@property
<|code_end|>
. Use current file imports:
(from itertools import groupby
from .constants import ACTIVATIONS, INITIALIZERS, CategoricalParameter
from .sub_model import SubModel
from .util import randomize_orthonormal
import dynet as dy
import re)
and context including class names, function names, or small code snippets from other files:
# Path: tupa/classifiers/nn/constants.py
# ACTIVATIONS = {
# "cube": "cube",
# "tanh": "tanh",
# "sigmoid": "logistic",
# "relu": "rectify",
# }
#
# INITIALIZERS = {
# # "saxe": "SaxeInitializer",
# "glorot_uniform": "GlorotInitializer",
# "normal": "NormalInitializer",
# }
#
# class CategoricalParameter:
# def __init__(self, values, string):
# self._value = self._string = None
# self.values = values
# self.string = string
#
# def __call__(self):
# import dynet as dy
# return getattr(dy, self._value)
#
# @property
# def string(self):
# return self._string
#
# @string.setter
# def string(self, s):
# self._string = s
# self._value = self.values.get(s)
#
# def __str__(self):
# return self._string
#
# Path: tupa/classifiers/nn/sub_model.py
# class SubModel:
# def __init__(self, params=None, save_path=(), shared=False, copy_shared=False):
# self.params = OrderedDict() if params is None else params # string (param identifier) -> parameter
# self.save_path = save_path
# self.shared = shared
# self.copy_shared = copy_shared
#
# def save_sub_model(self, d, *args):
# self.get_sub_dict(d).update(args + (("param_keys", list(self.params.keys())),))
# return list(self.params.values())
#
# def load_sub_model(self, d, *args, load_path=None):
# d = self.get_sub_dict(d, load_path=load_path)
# param_keys = d.get("param_keys", ())
# assert len(param_keys) <= len(args), "%s loaded values: expected %d, got %d" % ("/".join(self.save_path),
# len(param_keys), len(args))
# self.params.clear()
# self.params.update(zip(param_keys, args))
# return d
#
# def get_sub_dict(self, d, load_path=None):
# for element in load_path or self.save_path:
# d = d.setdefault(element, OrderedDict())
# return d
#
# def params_str(self):
# return "/".join(self.save_path) + (": " if self.save_path else "") + ", ".join(self.params.keys())
#
# def invalidate_caches(self):
# for model in self.sub_models():
# model.invalidate_caches()
#
# def sub_models(self):
# return ()
#
# Path: tupa/classifiers/nn/util.py
# def randomize_orthonormal(*parameters, activation=None): # Saxe et al., 2014 (https://arxiv.org/abs/1312.6120)
# for param in parameters:
# shape = param.shape()
# if len(shape) == 2 and shape[0] == shape[1] > 1:
# init, _, _ = np.linalg.svd(np.random.randn(*shape))
# if str(activation) == "relu":
# init *= np.sqrt(2)
# param.set_value(init)
. Output only the next line. | def total_layers(self): |
Predict the next line for this snippet: <|code_start|>MLP_PARAM_PATTERN = re.compile(r"[Wb]\d+")
class MultilayerPerceptron(SubModel):
def __init__(self, config, args, model, layers=None, layer_dim=None, output_dim=None, num_labels=None, params=None,
**kwargs):
super().__init__(params=params, **kwargs)
self.config = config
self.args = args
self.model = model
self.layers = self.args.layers if layers is None else layers
self.layer_dim = self.args.layer_dim if layer_dim is None else layer_dim
self.output_dim = self.args.output_dim if output_dim is None else output_dim
self.activation = CategoricalParameter(ACTIVATIONS, self.args.activation)
self.init = CategoricalParameter(INITIALIZERS, self.args.init)
self.dropout = self.args.dropout
self.gated = 1 if self.args.gated is None else self.args.gated # None means --gated was given with no argument
self.num_labels = num_labels
self.input_dim = self.input_keys = self.weights = None
@property
def total_layers(self):
return self.layers + (1 if self.num_labels else 0)
def init_params(self, input_dim):
assert input_dim, "Zero input dimension to MLP"
self.input_dim = input_dim
if self.layers > 0:
W0 = self.params.get("W0")
if W0:
<|code_end|>
with the help of current file imports:
from itertools import groupby
from .constants import ACTIVATIONS, INITIALIZERS, CategoricalParameter
from .sub_model import SubModel
from .util import randomize_orthonormal
import dynet as dy
import re
and context from other files:
# Path: tupa/classifiers/nn/constants.py
# ACTIVATIONS = {
# "cube": "cube",
# "tanh": "tanh",
# "sigmoid": "logistic",
# "relu": "rectify",
# }
#
# INITIALIZERS = {
# # "saxe": "SaxeInitializer",
# "glorot_uniform": "GlorotInitializer",
# "normal": "NormalInitializer",
# }
#
# class CategoricalParameter:
# def __init__(self, values, string):
# self._value = self._string = None
# self.values = values
# self.string = string
#
# def __call__(self):
# import dynet as dy
# return getattr(dy, self._value)
#
# @property
# def string(self):
# return self._string
#
# @string.setter
# def string(self, s):
# self._string = s
# self._value = self.values.get(s)
#
# def __str__(self):
# return self._string
#
# Path: tupa/classifiers/nn/sub_model.py
# class SubModel:
# def __init__(self, params=None, save_path=(), shared=False, copy_shared=False):
# self.params = OrderedDict() if params is None else params # string (param identifier) -> parameter
# self.save_path = save_path
# self.shared = shared
# self.copy_shared = copy_shared
#
# def save_sub_model(self, d, *args):
# self.get_sub_dict(d).update(args + (("param_keys", list(self.params.keys())),))
# return list(self.params.values())
#
# def load_sub_model(self, d, *args, load_path=None):
# d = self.get_sub_dict(d, load_path=load_path)
# param_keys = d.get("param_keys", ())
# assert len(param_keys) <= len(args), "%s loaded values: expected %d, got %d" % ("/".join(self.save_path),
# len(param_keys), len(args))
# self.params.clear()
# self.params.update(zip(param_keys, args))
# return d
#
# def get_sub_dict(self, d, load_path=None):
# for element in load_path or self.save_path:
# d = d.setdefault(element, OrderedDict())
# return d
#
# def params_str(self):
# return "/".join(self.save_path) + (": " if self.save_path else "") + ", ".join(self.params.keys())
#
# def invalidate_caches(self):
# for model in self.sub_models():
# model.invalidate_caches()
#
# def sub_models(self):
# return ()
#
# Path: tupa/classifiers/nn/util.py
# def randomize_orthonormal(*parameters, activation=None): # Saxe et al., 2014 (https://arxiv.org/abs/1312.6120)
# for param in parameters:
# shape = param.shape()
# if len(shape) == 2 and shape[0] == shape[1] > 1:
# init, _, _ = np.linalg.svd(np.random.randn(*shape))
# if str(activation) == "relu":
# init *= np.sqrt(2)
# param.set_value(init)
, which may contain function names, class names, or code. Output only the next line. | value = W0.as_array() |
Predict the next line for this snippet: <|code_start|>
MLP_PARAM_PATTERN = re.compile(r"[Wb]\d+")
class MultilayerPerceptron(SubModel):
def __init__(self, config, args, model, layers=None, layer_dim=None, output_dim=None, num_labels=None, params=None,
**kwargs):
super().__init__(params=params, **kwargs)
self.config = config
self.args = args
self.model = model
self.layers = self.args.layers if layers is None else layers
self.layer_dim = self.args.layer_dim if layer_dim is None else layer_dim
self.output_dim = self.args.output_dim if output_dim is None else output_dim
self.activation = CategoricalParameter(ACTIVATIONS, self.args.activation)
self.init = CategoricalParameter(INITIALIZERS, self.args.init)
self.dropout = self.args.dropout
self.gated = 1 if self.args.gated is None else self.args.gated # None means --gated was given with no argument
self.num_labels = num_labels
self.input_dim = self.input_keys = self.weights = None
@property
def total_layers(self):
return self.layers + (1 if self.num_labels else 0)
<|code_end|>
with the help of current file imports:
from itertools import groupby
from .constants import ACTIVATIONS, INITIALIZERS, CategoricalParameter
from .sub_model import SubModel
from .util import randomize_orthonormal
import dynet as dy
import re
and context from other files:
# Path: tupa/classifiers/nn/constants.py
# ACTIVATIONS = {
# "cube": "cube",
# "tanh": "tanh",
# "sigmoid": "logistic",
# "relu": "rectify",
# }
#
# INITIALIZERS = {
# # "saxe": "SaxeInitializer",
# "glorot_uniform": "GlorotInitializer",
# "normal": "NormalInitializer",
# }
#
# class CategoricalParameter:
# def __init__(self, values, string):
# self._value = self._string = None
# self.values = values
# self.string = string
#
# def __call__(self):
# import dynet as dy
# return getattr(dy, self._value)
#
# @property
# def string(self):
# return self._string
#
# @string.setter
# def string(self, s):
# self._string = s
# self._value = self.values.get(s)
#
# def __str__(self):
# return self._string
#
# Path: tupa/classifiers/nn/sub_model.py
# class SubModel:
# def __init__(self, params=None, save_path=(), shared=False, copy_shared=False):
# self.params = OrderedDict() if params is None else params # string (param identifier) -> parameter
# self.save_path = save_path
# self.shared = shared
# self.copy_shared = copy_shared
#
# def save_sub_model(self, d, *args):
# self.get_sub_dict(d).update(args + (("param_keys", list(self.params.keys())),))
# return list(self.params.values())
#
# def load_sub_model(self, d, *args, load_path=None):
# d = self.get_sub_dict(d, load_path=load_path)
# param_keys = d.get("param_keys", ())
# assert len(param_keys) <= len(args), "%s loaded values: expected %d, got %d" % ("/".join(self.save_path),
# len(param_keys), len(args))
# self.params.clear()
# self.params.update(zip(param_keys, args))
# return d
#
# def get_sub_dict(self, d, load_path=None):
# for element in load_path or self.save_path:
# d = d.setdefault(element, OrderedDict())
# return d
#
# def params_str(self):
# return "/".join(self.save_path) + (": " if self.save_path else "") + ", ".join(self.params.keys())
#
# def invalidate_caches(self):
# for model in self.sub_models():
# model.invalidate_caches()
#
# def sub_models(self):
# return ()
#
# Path: tupa/classifiers/nn/util.py
# def randomize_orthonormal(*parameters, activation=None): # Saxe et al., 2014 (https://arxiv.org/abs/1312.6120)
# for param in parameters:
# shape = param.shape()
# if len(shape) == 2 and shape[0] == shape[1] > 1:
# init, _, _ = np.linalg.svd(np.random.randn(*shape))
# if str(activation) == "relu":
# init *= np.sqrt(2)
# param.set_value(init)
, which may contain function names, class names, or code. Output only the next line. | def init_params(self, input_dim): |
Using the snippet: <|code_start|>
def strip_multitask(model, keep):
if "amr" not in keep: # Remove AMR-specific features: node label and category
delete_if_exists((model.feature_params, model.classifier.params), (NODE_LABEL_KEY, "c"))
delete_if_exists((model.classifier.labels, model.classifier.axes), {NODE_LABEL_KEY}.union(FORMATS).difference(keep))
def delete_if_exists(dicts, keys):
for d in dicts:
for key in keys:
try:
del d[key]
except KeyError:
pass
def main(args):
os.makedirs(args.out_dir, exist_ok=True)
for filename in args.models:
model = load_model(filename)
strip_multitask(model, args.keep)
model.filename = os.path.join(args.out_dir, os.path.basename(filename))
<|code_end|>
, determine the next line of code. You have imports:
import os
from configargparse import ArgParser
from tupa.config import FORMATS
from tupa.model import NODE_LABEL_KEY
from tupa.scripts.export import load_model
and context (class names, function names, or code) available:
# Path: tupa/config.py
# FORMATS = ["ucca"] + list(CONVERTERS)
#
# Path: tupa/model.py
# NODE_LABEL_KEY = "n"
#
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
. Output only the next line. | model.save() |
Predict the next line for this snippet: <|code_start|>
def strip_multitask(model, keep):
if "amr" not in keep: # Remove AMR-specific features: node label and category
delete_if_exists((model.feature_params, model.classifier.params), (NODE_LABEL_KEY, "c"))
delete_if_exists((model.classifier.labels, model.classifier.axes), {NODE_LABEL_KEY}.union(FORMATS).difference(keep))
<|code_end|>
with the help of current file imports:
import os
from configargparse import ArgParser
from tupa.config import FORMATS
from tupa.model import NODE_LABEL_KEY
from tupa.scripts.export import load_model
and context from other files:
# Path: tupa/config.py
# FORMATS = ["ucca"] + list(CONVERTERS)
#
# Path: tupa/model.py
# NODE_LABEL_KEY = "n"
#
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
, which may contain function names, class names, or code. Output only the next line. | def delete_if_exists(dicts, keys): |
Predict the next line for this snippet: <|code_start|>
def strip_multitask(model, keep):
if "amr" not in keep: # Remove AMR-specific features: node label and category
delete_if_exists((model.feature_params, model.classifier.params), (NODE_LABEL_KEY, "c"))
delete_if_exists((model.classifier.labels, model.classifier.axes), {NODE_LABEL_KEY}.union(FORMATS).difference(keep))
def delete_if_exists(dicts, keys):
for d in dicts:
for key in keys:
try:
del d[key]
except KeyError:
pass
def main(args):
os.makedirs(args.out_dir, exist_ok=True)
for filename in args.models:
model = load_model(filename)
strip_multitask(model, args.keep)
<|code_end|>
with the help of current file imports:
import os
from configargparse import ArgParser
from tupa.config import FORMATS
from tupa.model import NODE_LABEL_KEY
from tupa.scripts.export import load_model
and context from other files:
# Path: tupa/config.py
# FORMATS = ["ucca"] + list(CONVERTERS)
#
# Path: tupa/model.py
# NODE_LABEL_KEY = "n"
#
# Path: tupa/scripts/export.py
# def load_model(filename):
# model = Model(filename=filename)
# model.load()
# return model
, which may contain function names, class names, or code. Output only the next line. | model.filename = os.path.join(args.out_dir, os.path.basename(filename)) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
__all__ = [
'CMSMenuID',
'CMSSection',
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.comments.signals import comment_was_posted
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from cms_content.settings import ROOT_URL
from cms_content.settings import UPLOAD_TO
from cms_content.manager import CMSArticlePubManager
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms_content.settings import UPLOAD_TO
from akismet import Akismet
and context from other files:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
#
# Path: cms_content/settings.py
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
#
# Path: cms_content/settings.py
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
, which may include functions, classes, or code. Output only the next line. | 'CMSCategory', |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
__all__ = [
'CMSMenuID',
'CMSSection',
'CMSCategory',
'CMSArticle',
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.comments.signals import comment_was_posted
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from cms_content.settings import ROOT_URL
from cms_content.settings import UPLOAD_TO
from cms_content.manager import CMSArticlePubManager
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms_content.settings import UPLOAD_TO
from akismet import Akismet
and context (class names, function names, or code) available:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
#
# Path: cms_content/settings.py
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
#
# Path: cms_content/settings.py
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
. Output only the next line. | ] |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#from cms_content.utils.cache import cache_nodes
#from cms_content.menu_nodes import cache_nodes
#@cache_page(60*30)
@render_to('cms_content/content_index.html')
def content_index(request):
articles = list(CMSArticle.pub_manager.all()[:10])
return {
'articles': articles,
}
@cache_page(24*60*60)
@render_to('cms_content/section_list.html')
def section_list(request):
sections = list(CMSSection.objects.all())
return {
'sections': sections,
}
@cache_page(24*60*60)
@render_to('cms_content/section_detail.html')
def section_detail(request, slug):
section = CMSSection.objects.get(slug=slug)
categories = CMSCategory.objects.select_related(depth=1).filter(section=section)
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from django.http import HttpResponseRedirect
from django.db.models import F
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import get_list_or_404
from django.template.context import RequestContext
from django.core.paginator import Paginator
from django.core.paginator import InvalidPage
from django.core.paginator import EmptyPage
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page
from django.utils.translation import ugettext_lazy as _
from cms_content.models import *
from cms_content.utils.render import render_to
from cms_content.forms import CMSArticleFrontendForm
from cms_content.settings import ROOT_URL
from cms_content.settings import ARTICLE_PERPAGE
from django.core.exceptions import ValidationError
and context (classes, functions, sometimes code) from other files:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
#
# Path: cms_content/settings.py
# ARTICLE_PERPAGE = getattr(settings, 'CMS_CONTENT_ARTICLE_PERPAGE', 10)
. Output only the next line. | return { |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#from cms_content.utils.cache import cache_nodes
#from cms_content.menu_nodes import cache_nodes
#@cache_page(60*30)
@render_to('cms_content/content_index.html')
def content_index(request):
articles = list(CMSArticle.pub_manager.all()[:10])
return {
'articles': articles,
}
@cache_page(24*60*60)
@render_to('cms_content/section_list.html')
def section_list(request):
sections = list(CMSSection.objects.all())
return {
'sections': sections,
}
@cache_page(24*60*60)
@render_to('cms_content/section_detail.html')
def section_detail(request, slug):
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from django.http import HttpResponseRedirect
from django.db.models import F
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import get_list_or_404
from django.template.context import RequestContext
from django.core.paginator import Paginator
from django.core.paginator import InvalidPage
from django.core.paginator import EmptyPage
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page
from django.utils.translation import ugettext_lazy as _
from cms_content.models import *
from cms_content.utils.render import render_to
from cms_content.forms import CMSArticleFrontendForm
from cms_content.settings import ROOT_URL
from cms_content.settings import ARTICLE_PERPAGE
from django.core.exceptions import ValidationError
and context from other files:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
#
# Path: cms_content/settings.py
# ARTICLE_PERPAGE = getattr(settings, 'CMS_CONTENT_ARTICLE_PERPAGE', 10)
, which may include functions, classes, or code. Output only the next line. | section = CMSSection.objects.get(slug=slug) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
section_info = {
'queryset': CMSSection.objects.all(),
'template_name': 'cms_content/section_list.html',
}
category_info = {
'queryset': CMSCategory.objects.all(),
'template_name': 'cms_content/category_list.html',
}
urlpatterns = patterns ('',
url(r'^$', content_index, name='cms_content_index'),
url(r'^section/$', list_detail.object_list, section_info, name='cms_content_section_list'),
url(r'^category/$', list_detail.object_list, category_info, name='cms_content_category_list'),
url(r'^section/(?P<slug>[-\w]+)/$', section_detail, name='cms_content_section_detail'),
url(r'^category/(?P<slug>[-\w]+)/$', article_list, name='cms_content_category_detail'),
url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', article_detail, name='cms_content_article_detail'),
url(r'^article/add/$', article_add, name='cms_content_article_add'),
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from cms_content.views import *
from cms_content.models import CMSSection, CMSCategory
and context including class names, function names, and sometimes code from other files:
# Path: cms_content/models.py
# class CMSSection(models.Model):
# """Models For Django CMS Sections:
#
# Section is the top level to contruct cms's content. Create a section before
# adding your categories.
# """
#
# name = models.CharField(
# _(u"Section Name"),
# max_length=255,
# blank=False,
# help_text=_(u"Section's Name"),
# )
# slug = models.SlugField(
# _(u"Slug"),
# max_length=255,
# blank=False,
# unique=True,
# help_text=_(u"Section's Slug"),
# )
# description = models.TextField(
# _(u"Section Description"),
# blank=False,
# help_text=_(u"Your Section's Description"),
# )
# image = models.ImageField(
# _(u"Image"),
# upload_to=UPLOAD_TO,
# blank=True,
# help_text=_(u"Section Image Displayed In Pages"),
# )
# created_date = models.DateTimeField(
# _(u"Create Time"),
# auto_now_add=True,
# )
# menu = models.OneToOneField(CMSMenuID)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# ordering = ['-created_date']
# verbose_name = _(u'Section')
# verbose_name_plural = _(u'Section')
#
# @property
# def url(self):
# return "%s%s/%s/" % (ROOT_URL, 'section', self.slug)
#
# @models.permalink
# def get_absolute_url(self):
# return ('cms_content_section_detail', (self.slug,))
#
# class CMSCategory(models.Model):
# """Models for CMS's Categories:
#
# Category is the second level of cms_content structure. Before publish any
# articles, you should create a category.
# """
#
# name = models.CharField(
# _(u"Category Name"),
# max_length=255,
# blank=False,
# help_text=_(u"Category's Name"),
# )
# slug = models.SlugField(
# _(u"Slug"),
# max_length=255,
# blank=False,
# unique=True,
# help_text=_(u"Category's Slug"),
# )
# section = models.ForeignKey(
# CMSSection,
# verbose_name=_(u"Section"),
# related_name="category_of_section",
# blank=False,
# help_text=_(u"Pick a Section Used as the Category's Parent Level"),
# )
# description = models.TextField(
# _(u"Category Description"),
# blank=False,
# help_text=_(u"Your Category Description")
# )
# image = models.ImageField(
# _(u"Image"),
# upload_to=UPLOAD_TO,
# blank=True,
# help_text=_(u"Category Image Display in Pages"),
# )
# created_date = models.DateTimeField(
# _(u"Create Time"),
# auto_now_add=True,
# )
# menu = models.OneToOneField(CMSMenuID)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# ordering = ['-created_date']
# verbose_name = _(u'Category')
# verbose_name_plural = _(u'Category')
#
# @property
# def url(self):
# return "%s%s/%s/" % (ROOT_URL, 'category', self.slug)
#
# @models.permalink
# def get_absolute_url(self):
# return ("cms_content_category_detail", (self.slug,))
. Output only the next line. | url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/del/$', article_del, name='cms_content_article_del'), |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
__all__ = [
'CMSMenuID',
'CMSSection',
'CMSCategory',
'CMSArticle',
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.comments.signals import comment_was_posted
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from cms_content.settings import ROOT_URL
from cms_content.settings import UPLOAD_TO
from cms_content.manager import CMSArticlePubManager
from akismet import Akismet
and context (classes, functions, sometimes code) from other files:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
#
# Path: cms_content/settings.py
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
. Output only the next line. | ] |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
register = Library()
@register.filter
@stringfilter
def code_highlight(content):
css = ''
if CODE_HIGHLIGHT:
soup = BeautifulSoup(content)
code_blocks = soup.findAll(u'pre')
if code_blocks:
<|code_end|>
with the help of current file imports:
from django.db import models
from django.db.models import Count
from django.template import Library
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
from django.template.defaultfilters import stringfilter
from templatetag_sugar.register import tag
from templatetag_sugar.parser import Name, Variable, Constant, Optional, Model
from taggit.managers import TaggableManager
from taggit.models import TaggedItem, Tag
from pygments import highlight
from pygments.lexers import LEXERS
from pygments.lexers import PythonLexer
from pygments.lexers import guess_lexer
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from BeautifulSoup import BeautifulSoup
from cms_content.settings import *
from cms_content import settings as app_settings
and context from other files:
# Path: cms_content/settings.py
# ROOT_URL = getattr(settings, 'CMS_CONTENT_ROOT_URL', '/cms/')
# CODE_HIGHLIGHT = getattr(settings, 'CMS_CONTENT_CODE_HIGHLIGHT', True)
# CODE_HIGHLIGHT_CSS = getattr(settings, 'CMS_CONTENT_CODE_HIGHLIGHT_CSS', 'code_highlight')
# CODE_HIGHLIGHT_LINENOS = getattr(settings, 'CMS_CONTENT_CODE_HIGHLIGHT_LINENOS', False)
# CODE_HIGHLIGHT_DEFAULT = getattr(settings, 'CMS_CONTENT_CODE_HIGHLIGHT_DEFAULT', 'text')
# EDITOR = getattr(settings, 'CMS_CONTENT_EDITOR', 'WYMEditor')
# ARTICLE_PERPAGE = getattr(settings, 'CMS_CONTENT_ARTICLE_PERPAGE', 10)
# AKISMET_API_KEY = '773ea92115d8'
# UPLOAD_TO = getattr(settings, 'CMS_CONTENT_UPLOAD_TO', 'upload')
# TAGCLOUD_MIN = getattr(settings, 'TAGGIT_TAGCLOUD_MIN', 1.0)
# TAGCLOUD_MAX = getattr(settings, 'TAGGIT_TAGCLOUD_MAX', 3.0)
, which may contain function names, class names, or code. Output only the next line. | if CODE_HIGHLIGHT_LINENOS: |
Next line prediction: <|code_start|>
def simple_exception_app(environ, start_response):
if environ['PATH_INFO'].startswith('/error/document'):
start_response('200 OK', [('Content-type', 'text/plain')])
return ['Made it to the error']
else:
start_response('404 Not Found', [('Content-type', 'text/plain')])
return ['No page found!']
def test_plain_wrap():
app = TestApp(StatusCodeRedirect(simple_app))
res = app.get('/')
assert res.status_int == 200
def test_status_intercept():
app = TestApp(StatusCodeRedirect(simple_exception_app))
res = app.get('/', status=404)
assert 'Made it to the error' in res
def test_original_path():
app = TestApp(StatusCodeRedirect(simple_exception_app))
res = app.get('/', status=404)
assert res.environ['PATH_INFO'] == '/'
def test_retains_response():
app = TestApp(StatusCodeRedirect(simple_exception_app))
res = app.get('/', status=404)
assert 'pylons.original_response' in res.environ
assert 'No page found!' in res.environ['pylons.original_response'].body
<|code_end|>
. Use current file imports:
(from webtest import TestApp
from pylons.middleware import StatusCodeRedirect, ErrorHandler)
and context including class names, function names, or small code snippets from other files:
# Path: pylons/middleware.py
# class StatusCodeRedirect(object):
# """Internally redirects a request based on status code
#
# StatusCodeRedirect watches the response of the app it wraps. If the
# response is an error code in the errors sequence passed the request
# will be re-run with the path URL set to the path passed in.
#
# This operation is non-recursive and the output of the second
# request will be used no matter what it is.
#
# Should an application wish to bypass the error response (ie, to
# purposely return a 401), set
# ``environ['pylons.status_code_redirect'] = True`` in the application.
#
# """
# def __init__(self, app, errors=(400, 401, 403, 404),
# path='/error/document'):
# """Initialize the ErrorRedirect
#
# ``errors``
# A sequence (list, tuple) of error code integers that should
# be caught.
# ``path``
# The path to set for the next request down to the
# application.
#
# """
# self.app = app
# self.error_path = path
#
# # Transform errors to str for comparison
# self.errors = tuple([str(x) for x in errors])
#
# def __call__(self, environ, start_response):
# status, headers, app_iter, exc_info = call_wsgi_application(
# self.app, environ, catch_exc_info=True)
# if status[:3] in self.errors and \
# 'pylons.status_code_redirect' not in environ and self.error_path:
# # Create a response object
# environ['pylons.original_response'] = Response(
# status=status, headerlist=headers, app_iter=app_iter)
# environ['pylons.original_request'] = Request(environ)
#
# # Create a new environ to avoid touching the original request data
# new_environ = environ.copy()
# new_environ['PATH_INFO'] = self.error_path
#
# newstatus, headers, app_iter, exc_info = call_wsgi_application(
# self.app, new_environ, catch_exc_info=True)
# start_response(status, headers, exc_info)
# return app_iter
#
# def ErrorHandler(app, global_conf, **errorware):
# """ErrorHandler Toggle
#
# If debug is enabled, this function will return the app wrapped in
# the WebError ``EvalException`` middleware which displays
# interactive debugging sessions when a traceback occurs.
#
# Otherwise, the app will be wrapped in the WebError
# ``ErrorMiddleware``, and the ``errorware`` dict will be passed into
# it. The ``ErrorMiddleware`` handles sending an email to the address
# listed in the .ini file, under ``email_to``.
#
# """
# if asbool(global_conf.get('debug')):
# footer = footer_html % (pylons.config.get('traceback_host',
# 'pylonshq.com'),
# pylons.__version__)
# py_media = dict(pylons=media_path)
# app = EvalException(app, global_conf,
# templating_formatters=template_error_formatters,
# media_paths=py_media, head_html=head_html,
# footer_html=footer,
# libraries=report_libs)
# else:
# app = ErrorMiddleware(app, global_conf, **errorware)
# return app
. Output only the next line. | def test_retains_request(): |
Given snippet: <|code_start|> 'footer_html', 'head_html', 'media_path']
log = logging.getLogger(__name__)
media_path = os.path.join(os.path.dirname(__file__), 'media')
head_html = """\
<link rel="stylesheet" href="{{prefix}}/media/pylons/style/itraceback.css" \
type="text/css" media="screen" />"""
footer_html = """\
<script src="{{prefix}}/media/pylons/javascripts/traceback.js"></script>
<script>
var TRACEBACK = {
uri: "{{prefix}}",
host: "%s",
traceback: "/tracebacks"
}
</script>
<div id="service_widget">
<h2 class="assistance">Online Assistance</h2>
<div id="nv">
<ul id="supportnav">
<li class="nav active"><a class="overview" href="#">Overview</a></li>
<li class="nav"><a class="search" href="#">Search Mail Lists</a></li>
<li class="nav"><a class="posttraceback" href="#">Post Traceback</a></li>
</ul>
</div>
<div class="clearfix"> </div>
<div class="overviewtab">
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os.path
import pylons
from paste.deploy.converters import asbool
from paste.urlparser import StaticURLParser
from weberror.evalexception import EvalException
from weberror.errormiddleware import ErrorMiddleware
from webob import Request, Response
from webhelpers.html import literal
from pylons.error import template_error_formatters
from pylons.util import call_wsgi_application
and context:
# Path: pylons/util.py
# def call_wsgi_application(application, environ, catch_exc_info=False):
# """
# Call the given WSGI application, returning ``(status_string,
# headerlist, app_iter)``
#
# Be sure to call ``app_iter.close()`` if it's there.
#
# If catch_exc_info is true, then returns ``(status_string,
# headerlist, app_iter, exc_info)``, where the fourth item may
# be None, but won't be if there was an exception. If you don't
# do this and there was an exception, the exception will be
# raised directly.
#
# """
# captured = []
# output = []
# def start_response(status, headers, exc_info=None):
# if exc_info is not None and not catch_exc_info:
# raise exc_info[0], exc_info[1], exc_info[2]
# captured[:] = [status, headers, exc_info]
# return output.append
# app_iter = application(environ, start_response)
# if not captured or output:
# try:
# output.extend(app_iter)
# finally:
# if hasattr(app_iter, 'close'):
# app_iter.close()
# app_iter = output
# if catch_exc_info:
# return (captured[0], captured[1], app_iter, captured[2])
# else:
# return (captured[0], captured[1], app_iter)
which might include code, classes, or functions. Output only the next line. | <b>Looking for help?</b> |
Here is a snippet: <|code_start|>
def home(request):
# chat_session_list = chatSessions.objects.order_by('start_date')[:3]
# context_dict = {'chatSessions': chat_session_list}
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
def request_session(request):
return render(request, 'session.html')
def contests(request):
contest_list = Contest.objects.all()
return render(
request, 'contests.html', context={
'contest_list': contest_list
})
def contest_new(request):
form = ContestForm()
return render(request, 'contest_edit.html', {'form': form})
def add_contest(request):
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from main.models import chatSession, Contest, Journey
from .forms import ContestForm
and context from other files:
# Path: oshc/main/forms.py
# class ContestForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(ContestForm, self).__init__(*args, **kwargs)
# self.helper = FormHelper()
# self.helper.form_tag = False
# self.helper.label_class = 'col-lg-2'
# self.helper.field_class = 'col-lg-8'
# self.fields['start_date'].widget.attrs['class'] = 'datepicker'
# self.fields['end_date'].widget.attrs['class'] = 'datepicker'
#
# class Meta:
# model = Contest
# fields = ['name', 'link', 'description', 'start_date', 'end_date']
, which may include functions, classes, or code. Output only the next line. | if request.method == 'POST': |
Predict the next line after this snippet: <|code_start|>
class ContestForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ContestForm, self).__init__(*args, **kwargs)
<|code_end|>
using the current file's imports:
from django import forms
from crispy_forms.helper import FormHelper
from .models import Contest
and any relevant context from other files:
# Path: oshc/main/models.py
# class Contest(models.Model):
# name = models.CharField(max_length=128, help_text="Contest name")
# link = models.URLField(help_text="URL of the contest's website")
# description = models.TextField(
# max_length=512, help_text="Contest details", null=True)
# start_date = models.DateField(null=True)
# end_date = models.DateField(null=True)
# approved = models.BooleanField(default=False)
#
# def __str__(self):
# return self.name
. Output only the next line. | self.helper = FormHelper() |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
def compare_version(config: dict, min_version: str, max_version: str):
version = parse_version(config['version'])
if version < parse_version(min_version):
return -1
if version > parse_version(max_version):
<|code_end|>
with the help of current file imports:
import os
import re
import yaml
from packaging.version import parse as parse_version
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error
and context from other files:
# Path: toolbox/config/common.py
# BUTTON_CONFIG_KEYS = {'text', 'hidden'}
#
# CRP_TYPES = {'docker', 'gce', 'static'}
#
# CURRENT_MAX_VERSION = 'v3.2'
#
# CURRENT_MIN_VERSION = 'v3.1'
#
# PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
#
# Path: toolbox/utils/utils.py
# def counted_error(*args, **kwargs) -> None:
# """
# Wrapper for logging.error that will increase the error_counter
# """
# global _error_counter # pylint: disable=global-statement
# _error_counter += 1
# logging.error(*args, **kwargs)
#
# def fatal_error(*args, **kwargs) -> None:
# """
# Abort execution with a fatal error
# """
# counted_error(*args, **kwargs)
# counted_error_at_exit()
, which may contain function names, class names, or code. Output only the next line. | return 1 |
Continue the code snippet: <|code_start|>
try:
except ImportError:
def compare_version(config: dict, min_version: str, max_version: str):
version = parse_version(config['version'])
if version < parse_version(min_version):
return -1
<|code_end|>
. Use current file imports:
import os
import re
import yaml
from packaging.version import parse as parse_version
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error
and context (classes, functions, or code) from other files:
# Path: toolbox/config/common.py
# BUTTON_CONFIG_KEYS = {'text', 'hidden'}
#
# CRP_TYPES = {'docker', 'gce', 'static'}
#
# CURRENT_MAX_VERSION = 'v3.2'
#
# CURRENT_MIN_VERSION = 'v3.1'
#
# PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
#
# Path: toolbox/utils/utils.py
# def counted_error(*args, **kwargs) -> None:
# """
# Wrapper for logging.error that will increase the error_counter
# """
# global _error_counter # pylint: disable=global-statement
# _error_counter += 1
# logging.error(*args, **kwargs)
#
# def fatal_error(*args, **kwargs) -> None:
# """
# Abort execution with a fatal error
# """
# counted_error(*args, **kwargs)
# counted_error_at_exit()
. Output only the next line. | if version > parse_version(max_version): |
Given snippet: <|code_start|>
try:
except ImportError:
def compare_version(config: dict, min_version: str, max_version: str):
version = parse_version(config['version'])
if version < parse_version(min_version):
return -1
if version > parse_version(max_version):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import yaml
from packaging.version import parse as parse_version
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error
and context:
# Path: toolbox/config/common.py
# BUTTON_CONFIG_KEYS = {'text', 'hidden'}
#
# CRP_TYPES = {'docker', 'gce', 'static'}
#
# CURRENT_MAX_VERSION = 'v3.2'
#
# CURRENT_MIN_VERSION = 'v3.1'
#
# PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
#
# Path: toolbox/utils/utils.py
# def counted_error(*args, **kwargs) -> None:
# """
# Wrapper for logging.error that will increase the error_counter
# """
# global _error_counter # pylint: disable=global-statement
# _error_counter += 1
# logging.error(*args, **kwargs)
#
# def fatal_error(*args, **kwargs) -> None:
# """
# Abort execution with a fatal error
# """
# counted_error(*args, **kwargs)
# counted_error_at_exit()
which might include code, classes, or functions. Output only the next line. | return 1 |
Given the code snippet: <|code_start|>
try:
except ImportError:
def compare_version(config: dict, min_version: str, max_version: str):
version = parse_version(config['version'])
if version < parse_version(min_version):
return -1
if version > parse_version(max_version):
return 1
return 0
def validate_version(config: dict):
cmp = compare_version(config, CURRENT_MIN_VERSION, CURRENT_MAX_VERSION)
if cmp < 0:
fatal_error('Please, upgrade to version %s with upgrade.py!', CURRENT_MIN_VERSION)
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import yaml
from packaging.version import parse as parse_version
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error
and context (functions, classes, or occasionally code) from other files:
# Path: toolbox/config/common.py
# BUTTON_CONFIG_KEYS = {'text', 'hidden'}
#
# CRP_TYPES = {'docker', 'gce', 'static'}
#
# CURRENT_MAX_VERSION = 'v3.2'
#
# CURRENT_MIN_VERSION = 'v3.1'
#
# PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
#
# Path: toolbox/utils/utils.py
# def counted_error(*args, **kwargs) -> None:
# """
# Wrapper for logging.error that will increase the error_counter
# """
# global _error_counter # pylint: disable=global-statement
# _error_counter += 1
# logging.error(*args, **kwargs)
#
# def fatal_error(*args, **kwargs) -> None:
# """
# Abort execution with a fatal error
# """
# counted_error(*args, **kwargs)
# counted_error_at_exit()
. Output only the next line. | if cmp > 0: |
Based on the snippet: <|code_start|>
try:
except ImportError:
def compare_version(config: dict, min_version: str, max_version: str):
version = parse_version(config['version'])
if version < parse_version(min_version):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import yaml
from packaging.version import parse as parse_version
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error
and context (classes, functions, sometimes code) from other files:
# Path: toolbox/config/common.py
# BUTTON_CONFIG_KEYS = {'text', 'hidden'}
#
# CRP_TYPES = {'docker', 'gce', 'static'}
#
# CURRENT_MAX_VERSION = 'v3.2'
#
# CURRENT_MIN_VERSION = 'v3.1'
#
# PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
#
# Path: toolbox/utils/utils.py
# def counted_error(*args, **kwargs) -> None:
# """
# Wrapper for logging.error that will increase the error_counter
# """
# global _error_counter # pylint: disable=global-statement
# _error_counter += 1
# logging.error(*args, **kwargs)
#
# def fatal_error(*args, **kwargs) -> None:
# """
# Abort execution with a fatal error
# """
# counted_error(*args, **kwargs)
# counted_error_at_exit()
. Output only the next line. | return -1 |
Given snippet: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger
and context:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
which might include code, classes, or functions. Output only the next line. | def run(*commands): |
Predict the next line after this snippet: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
<|code_end|>
using the current file's imports:
from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger
and any relevant context from other files:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
. Output only the next line. | def run(*commands): |
Next line prediction: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
def run(*commands):
init_logger()
repo_path, repo_name, repo_branch = get_sys_args()
config = read_config(repo_path)
git_submodule_init(repo_path)
<|code_end|>
. Use current file imports:
(from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger)
and context including class names, function names, or small code snippets from other files:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
. Output only the next line. | for command in commands: |
Based on the snippet: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
def run(*commands):
init_logger()
repo_path, repo_name, repo_branch = get_sys_args()
config = read_config(repo_path)
git_submodule_init(repo_path)
<|code_end|>
, predict the immediate next line with the help of imports:
from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger
and context (classes, functions, sometimes code) from other files:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
. Output only the next line. | for command in commands: |
Here is a snippet: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
def run(*commands):
init_logger()
repo_path, repo_name, repo_branch = get_sys_args()
config = read_config(repo_path)
git_submodule_init(repo_path)
for command in commands:
<|code_end|>
. Write the next line using the current file imports:
from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger
and context from other files:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
, which may include functions, classes, or code. Output only the next line. | _run_command(command, repo_path, repo_name, repo_branch, config) |
Predict the next line after this snippet: <|code_start|>
def _run_command(command: str, repo_path: str, repo_name: str, repo_branch: str, config: dict):
module_path = '.'.join(('toolbox', get_crp_type(config), command))
module = import_module(module_path)
module.run(repo_path, repo_name, repo_branch, config)
if get_error_counter() > 0:
counted_error_at_exit()
def run(*commands):
init_logger()
repo_path, repo_name, repo_branch = get_sys_args()
config = read_config(repo_path)
git_submodule_init(repo_path)
<|code_end|>
using the current file's imports:
from importlib import import_module
from .config import get_crp_type, read_config
from .utils import counted_error_at_exit, get_error_counter, get_sys_args, git_submodule_init, init_logger
and any relevant context from other files:
# Path: toolbox/utils/config.py
# def get_crp_type(config: dict) -> str:
# crp_type = config.get('crp_type') or 'static'
#
# if crp_type not in CRP_TYPES:
# fatal_error("Unknown crp_type: '%s' / %s", crp_type, CRP_TYPES)
#
# return crp_type
#
# def read_config(path: str, *, pre_validate: bool = True) -> dict:
# """
# Read the config.yml file
#
# :param path: path to the file or the base directory
# :param pre_validate: check version and crp_type fields
# :return: dict
# """
# if os.path.isdir(path):
# path = os.path.join(path, 'config.yml')
#
# try:
# with open(path, 'r') as f:
# config = yaml.safe_load(f)
#
# if pre_validate:
# validate_version(config)
# get_crp_type(config)
#
# return config
#
# except Exception as e:
# fatal_error('%s(%s)', type(e).__name__, e)
#
# Path: toolbox/utils/utils.py
# def counted_error_at_exit() -> None:
# """
# Call at the end of execution to handle errors
# """
# logging.info('Finished with %d error(s).', _error_counter)
# sys.exit(1 if _error_counter > 0 else 0)
#
# def get_error_counter() -> int:
# """
# Return the current number of non-fatal errors
# """
# return _error_counter
#
# def get_sys_args() -> Tuple[str, str, str]:
# """
# Get parsed command line arguments
#
# Absolute repository path, repository name (optional)
# :return tuple: repo_path, repo_name, repo_branch
# """
# if not 2 <= len(sys.argv) <= 4:
# logging.info('Usage: %s <repo_path> [repo_name] [repo_branch]', sys.argv[0])
# sys.exit(1)
#
# repo_path = find_repo_path(os.path.realpath(sys.argv[1]))
# repo_name = sys.argv[2] if len(sys.argv) >= 3 else os.path.basename(repo_path)
# repo_branch = sys.argv[3] if len(sys.argv) >= 4 else get_repo_branch(repo_path)
#
# return repo_path, repo_name, repo_branch
#
# def git_submodule_init(repo_path: str = None):
# if repo_path is None:
# repo_path = os.getcwd()
#
# run_cmd(
# [
# 'if git rev-parse --git-dir &>/dev/null; then '
# 'git submodule update --init --checkout --recursive; fi'
# ],
# cwd=repo_path,
# shell=True,
# )
#
# def init_logger() -> None:
# """
# Configure the default python logger
# """
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('[%(levelname)s] %(message)s')
# handler.setFormatter(formatter)
# logger.addHandler(handler)
. Output only the next line. | for command in commands: |
Continue the code snippet: <|code_start|> lssOne = lssZero + zzOne + len(ssOne)
ssTwo = '<'
zzTwo = line[lssOne:].find(ssTwo)
if zzTwo != -1:
lssTwo = lssOne + zzTwo
result = line[lssOne:lssTwo]
return result
def get_bookmark(line):
bookmark = None
s = '<DT><A HREF=\"'
ls = len(s)
z = line.find(s)
if z != -1:
ls = z + len(s)
sOne = '\"'
z1 = line[ls:].find(sOne)
if z1 != -1:
lsOne = ls + z1
url = line[ls:lsOne]
if url.startswith('http'):
bookmark = {'url':'', 'title':'', 'tags':''}
bookmark['url']=url
lsTwo = lsOne + len(sOne)
sTwo = '>'
z2 = line[lsTwo:].find(sTwo)
if z2 != -1:
lsThree = lsTwo + z2 + len(sTwo)
<|code_end|>
. Use current file imports:
import threading
import urllib2
import uuid
import os
import BeautifulSoup
from django.core.files.base import ContentFile
from webapp.apps.bookmark.models import Bookmark
and context (classes, functions, or code) from other files:
# Path: webapp/apps/bookmark/models.py
# class Bookmark(models.Model):
# owner = models.ForeignKey(User, verbose_name=_(u'Owner'), related_name='owner_bookmarks')
# url = models.URLField(verbose_name=_(u'URL'))
# title = models.CharField(verbose_name=_(u'Title'), blank=True, max_length=100,
# help_text=_(u'Limit of 100 characters'))
# tags = TaggableManager(verbose_name=_(u'Tags'), blank=True,
# help_text=_(u'A comma-separated list of tags. At most 3.'))
# public = models.BooleanField(verbose_name=_(u'Public this bookmark'), blank=True, default=True)
# screen_shot = models.ImageField(verbose_name=_(u'Screen shot'), upload_to='bookmark', blank=True)
# create_time = models.DateTimeField(verbose_name=_(u'Create time'), auto_now_add=True)
# last_modified_time = models.DateTimeField(verbose_name=_(u'Last modified time'), auto_now=True)
#
# def __unicode__(self):
# return self.url
#
# def get_absolute_url(self):
# return self.url
#
# class Meta:
# ordering = ['-create_time']
. Output only the next line. | sThree = '</A>' |
Next line prediction: <|code_start|> self._volt_del = volt_del
self._valid = valid
self._time = time
self._volt_strt = (self._volt_cen - ( self._volt_del / 2. ) )
self._volt_stop = (self._volt_cen + ( self._volt_del / 2. ) )
self._vel_strt = 1E-3*( sqrt(2.0*const['q_p']*
self['volt_strt']/const['m_p']) )
self._vel_stop = 1E-3*( sqrt((2.0*const['q_p']*
self['volt_stop']/const['m_p'])) )
# self._vel_cen = ( (self['vel_strt']+self['vel_stop'])/2. )
self._vel_cen = 1E-3*( sqrt(2.0*const['q_p']*
self['volt_cen']/const['m_p']) )
self._vel_del = ( self['vel_stop']-self['vel_strt'] )
self._curr = curr
# TODO: Confirm these two formulae
self._the = ( 90 + self._elev ) * pi/180
self._phi = ( - self._azim ) * pi/180
self._dir_x = sin( self._the ) * cos( self._phi )
self._dir_y = sin( self._the ) * sin( self._phi )
self._dir_z = cos( self._the )
self._norm_b_x = None
self._norm_b_y = None
self._norm_b_z = None
<|code_end|>
. Use current file imports:
(from math import sqrt, acos, pi
from numpy import interp, sin, cos, deg2rad, exp, array
from scipy.special import erf
from janus_const import const
from janus_helper import calc_arr_norm, calc_arr_dot)
and context including class names, function names, or small code snippets from other files:
# Path: janus_const.py
#
# Path: janus_helper.py
# def calc_arr_norm( v ):
#
# mag = sqrt( fsum( [ c**2 for c in v ]) )
#
# return tuple( [ ( c/mag) for c in v ] )
#
# def calc_arr_dot( u,v ) :
# if ( len(u) != len(v) ) :
# raise TypeError( 'Unequal lengths.' )
# return fsum([ x[0]*x[1] for x in zip(u,v) ])
. Output only the next line. | self._maglook = None |
Next line prediction: <|code_start|> #-----------------------------------------------------------------------
# DEFINE THE FUNCTION TO CALCULATE EXPECTED MAXWELLIAN CURRENT.
#-----------------------------------------------------------------------
def calc_curr( self, m, q, v0, n, dv, w ) :
# Note. This function is based on Equation 2.34 from Maruca
# (PhD thesis, 2012), but differs by a factor of $2$
# (i.e., the factor of $2$ from Equation 2.13, which is
# automatically calibrated out of the Wind/FC data).
# Check whether thermal velocity is a 2-D list, which implies
# anisotropy. If it is calculate the effective thermal velocity,
# else continue.
if ( hasattr( w, '__len__' ) and ( w is not None ) ) :
if ( w is not None ) :
ml2 = ( self['maglook'] )**2
w_eff = sqrt( ( ( 1. - ml2 ) * w[0]**2 ) +
( ml2 * w[1]**2 ) )
else :
w_eff = w
# Calculate the total velocity using drift
if ( dv is None ) :
v_vec = [ v0[i] for i in range( len( v0 ) ) ]
else :
<|code_end|>
. Use current file imports:
(from math import sqrt, acos, pi
from numpy import interp, sin, cos, deg2rad, exp, array
from scipy.special import erf
from janus_const import const
from janus_helper import calc_arr_norm, calc_arr_dot)
and context including class names, function names, or small code snippets from other files:
# Path: janus_const.py
#
# Path: janus_helper.py
# def calc_arr_norm( v ):
#
# mag = sqrt( fsum( [ c**2 for c in v ]) )
#
# return tuple( [ ( c/mag) for c in v ] )
#
# def calc_arr_dot( u,v ) :
# if ( len(u) != len(v) ) :
# raise TypeError( 'Unequal lengths.' )
# return fsum([ x[0]*x[1] for x in zip(u,v) ])
. Output only the next line. | v_vec = [ v0[i] + dv * self['norm_b'][i] |
Continue the code snippet: <|code_start|> elif ( key == 'azim' ) :
return self._azim
elif ( key == 'elev' ) :
return self._elev
elif ( key == 'time' ) :
return self._time
elif ( key == 'volt_cen' ) :
return self._volt_cen
elif ( key == 'volt_del' ) :
return self._volt_del
elif ( key == 'volt_strt' ) :
return self._volt_strt
elif ( key == 'volt_stop' ) :
return self._volt_stop
elif ( key == 'vel_strt' ) :
return self._vel_strt
elif ( key == 'vel_stop' ) :
return self._vel_stop
elif ( key == 'vel_cen' ) :
return self._vel_cen
elif ( key == 'vel_del' ) :
return self._vel_del
elif ( key == 'curr' ) :
return self._curr
elif ( key == 'curr_valid' ) :
if ( self['valid'] ) :
return self['curr']
else :
return 0.
elif ( key == 'the' ) :
<|code_end|>
. Use current file imports:
from math import sqrt, acos, pi
from numpy import interp, sin, cos, deg2rad, exp, array
from scipy.special import erf
from janus_const import const
from janus_helper import calc_arr_norm, calc_arr_dot
and context (classes, functions, or code) from other files:
# Path: janus_const.py
#
# Path: janus_helper.py
# def calc_arr_norm( v ):
#
# mag = sqrt( fsum( [ c**2 for c in v ]) )
#
# return tuple( [ ( c/mag) for c in v ] )
#
# def calc_arr_dot( u,v ) :
# if ( len(u) != len(v) ) :
# raise TypeError( 'Unequal lengths.' )
# return fsum([ x[0]*x[1] for x in zip(u,v) ])
. Output only the next line. | return self._the |
Predict the next line for this snippet: <|code_start|> ###self.grd.addWidget( self.btn_cncl, 1, 3, 1, 1 )
# Initialize the object to be returned to the user on the close
# of this dialog window.
self.resp = None
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR RESPONDING TO A USER-INITIATED EVENT.
#-----------------------------------------------------------------------
def user_event( self, event, fnc ) :
# Set the string-identifier of the button pressed to be the
# value returned by this dialog box.
self.resp = fnc
# Close this dialog box.
self.close( )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR PROMPTING THE USER FOR A RANGE OF TIMESTAMPS.
#-----------------------------------------------------------------------
def get_resp( self ) :
# Execute this dialog.
<|code_end|>
with the help of current file imports:
from PyQt4.QtGui import QDialog, QGridLayout, QLabel
from janus_event_PushButton import event_PushButton
and context from other files:
# Path: janus_event_PushButton.py
# class event_PushButton( QPushButton ) :
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc, lab='' ) :
#
#
# # Inherit all attributes of an instance of "QPushButton".
#
# super( event_PushButton, self ).__init__( lab )
#
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
#
# # Store the string indicating the function of this button.
#
# self.fnc = fnc
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO MOUSE CLICKS.
# #-----------------------------------------------------------------------
#
# def mousePressEvent( self, event ) :
#
#
# # Deligate the handling of the mouse-click event to
# # "self.owner", providing it with the details of the event and
# # also the string identifying the function of this button.
#
# self.owner.user_event( event, self.fnc )
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO KEY PRESSES.
# #-----------------------------------------------------------------------
#
# def keyPressEvent( self, event ) :
#
#
# # If the "Enter" or "Return" key was pressed, interpret this as
# # an event and deligate handling thereof to "self.owner".
#
# if ( ( event.key( ) == Qt.Key_Enter ) or
# ( event.key( ) == Qt.Key_Return ) ) :
#
# self.owner.user_event( event, self.fnc )
, which may contain function names, class names, or code. Output only the next line. | self.exec_( ) |
Given snippet: <|code_start|>
super( widget_ctrl_info, self ).__init__( )
# Store the Janus core.
self.core = core
# Initialize the the indicator of whether the text should be
# cleared the next time a message is received.
self.clear_for_next_mesg = True
# Prepare to respond to signals received from the Janus core.
self.connect( self.core, SIGNAL('janus_mesg'), self.resp_mesg )
self.connect( self.core, SIGNAL('janus_rset'), self.resp_rset )
# Set this text area as read only (for the user).
self.setReadOnly( True )
# This text area should be empty, so print a generic welcome
# statement and reset the position of the vertical scroll bar
# (in case printing the welcome statement has shifted it down).
self.prnt_htm( '<b>Welcome to Janus!</b>' )
self.prnt_brk( )
self.prnt_brk( )
self.prnt_htm( 'Version: ' + self.core.version )
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QTextCursor
from janus_format_TextEdit import format_TextEdit
and context:
# Path: janus_format_TextEdit.py
# class format_TextEdit( QTextEdit ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self ) :
#
# # Inherit all attributes of an instance of "QTextEdit".
#
# super( format_TextEdit, self ).__init__( )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INDENTATION.
# #-----------------------------------------------------------------------
#
# def prnt_tab( self, t=1 ) :
#
# # Based on the value of "t", print an appropriate number of
# # white spaces.
#
# if ( t >= 1 ) :
# self.insertHtml( ' ' )
# if ( t >= 2 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
# if ( t >= 3 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A DECIMAL NUMBER.
# #-----------------------------------------------------------------------
#
# def prnt_dcm( self, num, dig=2, unt=None ) :
#
# # Convert "dig", the number of digits after the decimal place,
# # to a string.
#
# str_dig = '{:}'.format( int( round( dig ) ) )
#
# # Print the number "num" with "dig" digits after the decimal
# # point.
#
# self.insertHtml( ( '{:.' + str_dig + 'f}' ).format( num ) )
#
# # If "str_dig" is "0", then add in a decimal place (which is
# # otherwise omitted when no decimal places are requested.
#
# if ( str_dig == '0' ) :
#
# self.insertHtml( '.' )
#
# # If a string has been provided for the unit, print it as well.
#
# if ( unt is not None ) :
#
# self.insertHtml( ' ' + unt )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INTEGER.
# #-----------------------------------------------------------------------
#
# def prnt_int( self, num ) :
#
# # In case "num" isn't already an integer, make it one by
# # rounding.
#
# int_num = int( round( num ) )
#
# # Print the integer "int_num".
#
# self.insertHtml( '{:}'.format( int_num ) )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A LINE BREAK.
# #-----------------------------------------------------------------------
#
# def prnt_brk( self ) :
#
# # Print a line break.
#
# self.insertHtml( '<br>' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING GENERAL HTML TEXT.
# #-----------------------------------------------------------------------
#
# def prnt_htm( self, s , speak=False) :
#
# # Print the string "s" (as HTML code)..
#
# self.insertHtml( s )
#
# # For analysis that can take a long time to run, this is a helpful
# # reminder to check the result.
# if speak and platform.system() == "Darwin":
# os.system('say "%s"' % s)
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR TESTING WHETHER THE TEXT AREA IS EMPTY.
# #-----------------------------------------------------------------------
#
# def is_empty( self ) :
#
# # If the text area contains no text, return "True"; otherwise,
# # return "False".
#
# if ( self.toPlainText( ) == '' ) :
# return True
# else :
# return False
which might include code, classes, or functions. Output only the next line. | self.prnt_brk( ) |
Based on the snippet: <|code_start|>################################################################################
################################################################################
## LOAD THE NECESSARY MODULES.
################################################################################
# Load the modules necessary for the graphical interface.
#from janus_widget_nln_fls import widget_opt_fls
################################################################################
## DEFINE THE "widget_opt" CLASS TO CUSTOMIZE "QTabWidget" FOR OPTIONS MENU.
################################################################################
class widget_opt( QTabWidget ) :
#-----------------------------------------------------------------------
# DEFINE THE INITIALIZATION FUNCTION.
#-----------------------------------------------------------------------
def __init__( self, core ) :
# Inherit all attributes of an instance of "QTabWidget".
super( widget_nln, self ).__init__( )
# Store the Janus core.
<|code_end|>
, predict the immediate next line with the help of imports:
from PyQt4.QtGui import QTabWidget
from janus_dialog_opt import dialog_opt
and context (classes, functions, sometimes code) from other files:
# Path: janus_dialog_opt.py
# class dialog_opt( QDialog ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, core ) :
#
# # Inherit all attributes of an instance of "QDialog".
#
# super( dialog_opt, self ).__init__( )
#
# # Store the Janus core.
#
# self.core = core
#
# # Make this a modal dialog (i.e., block user-interaction with
# # the main application window while this dialog exists).
#
# self.setModal( True )
#
# # Set the title of this dialog window.
#
# self.setWindowTitle( 'Options Menu' )
#
# # Give this widget a grid layout, "self.grd".
#
# self.grd = QGridLayout( )
#
# self.grd.setContentsMargins( 6, 6, 6, 6 )
#
# self.setLayout( self.grd )
#
# # Add a QTabWidget.
#
# self.wdg = QTabWidget( )
# self.sg = QGridLayout( )
#
# self.grd.addWidget( self.wdg, 0, 0, 1, 1 )
# self.grd.addLayout( self.sg, 2, 0, 1, 1 )
#
# self.wdg_opt_par = dialog_opt_par( self.core )
# self.wdg_opt_fls = dialog_opt_fls( self.core )
#
# self.wdg.addTab( self.wdg_opt_par, 'Results' )
# self.wdg.addTab( self.wdg_opt_fls, 'File Options' )
#
# self.btn_rstr = event_PushButton(
# self, 'rstr', 'Restore Default' )
# self.btn_close = event_PushButton( self, 'close', 'Close' )
#
# self.btn_rstr.setAutoDefault( False )
# self.btn_close.setAutoDefault( False )
#
# self.sg.addWidget( self.btn_rstr , 1, 0, 1, 1 )
# self.sg.addWidget( self.btn_close, 1, 1, 1, 1 )
#
# # Execute this dialog.
#
# self.exec_( )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO A USER-INITIATED EVENT.
# #-----------------------------------------------------------------------
#
# def user_event( self, event, fnc ) :
#
# # Take the appropriate action based on which button was pressed.
#
# if ( fnc == 'close' ) :
#
# # Close the window.
#
# self.close( )
#
# elif ( fnc == 'rstr' ) :
#
# # If no other threads are currently running, start a new
# # thread to restore the default values for all option.
#
# if ( n_thread( ) == 0 ) :
#
# Thread( target=thread_rstr_opt,
# args=( self.core, ) ).start( )
. Output only the next line. | self.core = core |
Continue the code snippet: <|code_start|> # Append the first timestamp to the file name.
name += '_' + t1
# If the provided coe only has only a signle result, return the file
# name as is.
if ( len( core.series ) == 1 ) :
return name
# Append the second timestamp to the file name.
name += '_' + t2
# Return the file name.
return name
################################################################################
## DEFINE THE FUNCTION FOR GENERATING A FULL NAME FOR A SAVE FILE.
################################################################################
def make_name_save( core ) :
# Return the the full name of the save file (complete with path and
# extension).
return os.path.join( os.path.dirname( __file__ ),
<|code_end|>
. Use current file imports:
from janus_time import calc_time_sec
import os.path
and context (classes, functions, or code) from other files:
# Path: janus_time.py
# def calc_time_sec( time ) :
#
# # If this function has been called on "None" or an empty string, simply
# # return "None".
#
# if ( ( time is None ) or ( time == '' ) ) :
# return None
#
# # Try to convert the argument "time" to a value and to round that value
# # to the nearest second. If this fails, abort (returning "None").
#
# time_val = calc_time_val( time )
#
# if ( time_val is None ) :
# return None
#
# time_val_sec = round( time_val, 0 )
#
# # Convert the rounded time value to a string and truncate it.
#
# time_str_sec = ( calc_time_str( time_val_sec ) )[0:19]
#
# # Return the truncated string.
#
# return time_str_sec
. Output only the next line. | 'results', 'save', |
Here is a snippet: <|code_start|> 'nln':QLabel( 'Non-Linear' ) }
self.lab_dyn = { 'dyn': QLabel( 'Dynamic:' ),
'mom': QLabel( 'Moments' ),
'gss': QLabel( 'Init. Guess' ),
'sel': QLabel( 'Data Sel.' ),
'nln': QLabel( 'Non-Linear' ) }
self.box_dsp = { 'mom':event_CheckBox( self, 'mom' ),
'gsl':event_CheckBox( self, 'gsl' ),
'nln':event_CheckBox( self, 'nln' ) }
self.box_dyn = { 'mom':event_CheckBox( self, 'mom' ),
'gss':event_CheckBox( self, 'gss' ),
'sel':event_CheckBox( self, 'sel' ),
'nln':event_CheckBox( self, 'nln' ) }
self.order_dsp = [ 'dsp', 'mom', 'gsl', 'nln' ]
self.order_dyn = [ 'dyn', 'mom', 'gss', 'sel', 'nln' ]
# Row by row, add the boxes to this widget's grid.
for i, key in enumerate( self.order_dsp ) :
if ( key == 'dsp') :
self.lab_dsp[key].setFont(
QFont( "Helvetica", 12, QFont.Bold ) )
<|code_end|>
. Write the next line using the current file imports:
from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QWidget, QGridLayout, QLabel, QFont
from janus_event_CheckBox import event_CheckBox
from threading import Thread
from janus_thread import n_thread, thread_chng_dsp, thread_chng_dyn
and context from other files:
# Path: janus_event_CheckBox.py
# class event_CheckBox( QCheckBox ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_CheckBox, self ).__init__( )
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
# # If the 'stateChanged()' signal is emitted (i.e., if the user
# # clicks on this check box), notify "self.owner".
#
# self.connect( self, SIGNAL('clicked(bool)'),
# self.signal_clicked )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE "clicked" SIGNAL.
# #-----------------------------------------------------------------------
#
# def signal_clicked( self ) :
#
# # Alert the object that initialized this widget (i.e., its
# # "owner") that the check box has been clicked.
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_dsp( core, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dsp( value )
#
# core.emit( SIGNAL('janus_busy_end') )
#
# def thread_chng_dyn( core, anal, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dyn( anal, value )
#
# core.emit( SIGNAL('janus_busy_end') )
, which may include functions, classes, or code. Output only the next line. | self.grd.addWidget( self.lab_dsp[key], i, 0, 1, 2 ) |
Next line prediction: <|code_start|>
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR SETTING THE VALUES OF THE TICK BOXES.
#-----------------------------------------------------------------------
def make_box( self ) :
# Set the values of the "display" tick boxes.
if ( self.core.dsp == 'mom' ) :
self.box_dsp['mom'].setChecked( True )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( False )
elif ( self.core.dsp == 'gsl' ) :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( True )
self.box_dsp['nln'].setChecked( False )
elif ( self.core.dsp == 'nln' ) :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( True )
else :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( False )
# Set the values of the "dynamic" tick boxes.
self.box_dyn['mom'].setChecked( self.core.dyn_mom )
self.box_dyn['gss'].setChecked( self.core.dyn_gss )
<|code_end|>
. Use current file imports:
(from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QWidget, QGridLayout, QLabel, QFont
from janus_event_CheckBox import event_CheckBox
from threading import Thread
from janus_thread import n_thread, thread_chng_dsp, thread_chng_dyn)
and context including class names, function names, or small code snippets from other files:
# Path: janus_event_CheckBox.py
# class event_CheckBox( QCheckBox ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_CheckBox, self ).__init__( )
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
# # If the 'stateChanged()' signal is emitted (i.e., if the user
# # clicks on this check box), notify "self.owner".
#
# self.connect( self, SIGNAL('clicked(bool)'),
# self.signal_clicked )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE "clicked" SIGNAL.
# #-----------------------------------------------------------------------
#
# def signal_clicked( self ) :
#
# # Alert the object that initialized this widget (i.e., its
# # "owner") that the check box has been clicked.
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_dsp( core, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dsp( value )
#
# core.emit( SIGNAL('janus_busy_end') )
#
# def thread_chng_dyn( core, anal, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dyn( anal, value )
#
# core.emit( SIGNAL('janus_busy_end') )
. Output only the next line. | self.box_dyn['sel'].setChecked( self.core.dyn_sel ) |
Next line prediction: <|code_start|> self.box_dyn['mom'].setChecked( self.core.dyn_mom )
self.box_dyn['gss'].setChecked( self.core.dyn_gss )
self.box_dyn['sel'].setChecked( self.core.dyn_sel )
self.box_dyn['nln'].setChecked( self.core.dyn_nln )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR RESPONDING TO A USER-INITIATED EVENT.
#-----------------------------------------------------------------------
def user_event( self, event, fnc ) :
# If a "thread_*" computation thread is already running,
# regenerate the check boxes and abort.
if ( n_thread( ) != 0 ) :
self.make_box( )
return
# If one of the "Display" boxes has been (un)checked, update the
# value of "self.core.dsp" appropriately.
# Note. When one of these boxes is checked, it is not abolutely
# necessary to uncheck the other boxes. The call to
# "self.core.chng_dsp" will emit a signal that cause
# "self.make_box" to be run. However, there tends to be
# a bit of lag in this process, so an immediate
# unchecking of these boxes is warranted.
if ( fnc == 'mom' ) :
if ( self.box_dsp['mom'].isChecked( ) ) :
<|code_end|>
. Use current file imports:
(from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QWidget, QGridLayout, QLabel, QFont
from janus_event_CheckBox import event_CheckBox
from threading import Thread
from janus_thread import n_thread, thread_chng_dsp, thread_chng_dyn)
and context including class names, function names, or small code snippets from other files:
# Path: janus_event_CheckBox.py
# class event_CheckBox( QCheckBox ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_CheckBox, self ).__init__( )
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
# # If the 'stateChanged()' signal is emitted (i.e., if the user
# # clicks on this check box), notify "self.owner".
#
# self.connect( self, SIGNAL('clicked(bool)'),
# self.signal_clicked )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE "clicked" SIGNAL.
# #-----------------------------------------------------------------------
#
# def signal_clicked( self ) :
#
# # Alert the object that initialized this widget (i.e., its
# # "owner") that the check box has been clicked.
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_dsp( core, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dsp( value )
#
# core.emit( SIGNAL('janus_busy_end') )
#
# def thread_chng_dyn( core, anal, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dyn( anal, value )
#
# core.emit( SIGNAL('janus_busy_end') )
. Output only the next line. | self.box_dsp['gsl'].setChecked( False ) |
Based on the snippet: <|code_start|>
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR SETTING THE VALUES OF THE TICK BOXES.
#-----------------------------------------------------------------------
def make_box( self ) :
# Set the values of the "display" tick boxes.
if ( self.core.dsp == 'mom' ) :
self.box_dsp['mom'].setChecked( True )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( False )
elif ( self.core.dsp == 'gsl' ) :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( True )
self.box_dsp['nln'].setChecked( False )
elif ( self.core.dsp == 'nln' ) :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( True )
else :
self.box_dsp['mom'].setChecked( False )
self.box_dsp['gsl'].setChecked( False )
self.box_dsp['nln'].setChecked( False )
# Set the values of the "dynamic" tick boxes.
self.box_dyn['mom'].setChecked( self.core.dyn_mom )
self.box_dyn['gss'].setChecked( self.core.dyn_gss )
<|code_end|>
, predict the immediate next line with the help of imports:
from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QWidget, QGridLayout, QLabel, QFont
from janus_event_CheckBox import event_CheckBox
from threading import Thread
from janus_thread import n_thread, thread_chng_dsp, thread_chng_dyn
and context (classes, functions, sometimes code) from other files:
# Path: janus_event_CheckBox.py
# class event_CheckBox( QCheckBox ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_CheckBox, self ).__init__( )
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
# # If the 'stateChanged()' signal is emitted (i.e., if the user
# # clicks on this check box), notify "self.owner".
#
# self.connect( self, SIGNAL('clicked(bool)'),
# self.signal_clicked )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE "clicked" SIGNAL.
# #-----------------------------------------------------------------------
#
# def signal_clicked( self ) :
#
# # Alert the object that initialized this widget (i.e., its
# # "owner") that the check box has been clicked.
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_dsp( core, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dsp( value )
#
# core.emit( SIGNAL('janus_busy_end') )
#
# def thread_chng_dyn( core, anal, value ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_dyn( anal, value )
#
# core.emit( SIGNAL('janus_busy_end') )
. Output only the next line. | self.box_dyn['sel'].setChecked( self.core.dyn_sel ) |
Based on the snippet: <|code_start|>
elif ( key == 'q' ) :
return self.q
elif ( key == 'n' ) :
arr_pop = self.my_plas.lst_pop( self )
if ( ( arr_pop is None ) or ( len( arr_pop ) == 0 ) ) :
return None
arr_n = [ p['n'] for p in arr_pop ]
if ( None in arr_n ) :
return None
return sum( arr_n )
elif ( ( key == 'dv' ) or ( key == 'dv_mag' )
or ( key == 'dv_par' ) ) :
arr_pop = self.my_plas.lst_pop( self )
if ( ( arr_pop is None ) or ( len( arr_pop ) == 0 ) ) :
return None
arr_n = [ p['n' ] for p in arr_pop ]
arr_dv = [ p['dv'] for p in arr_pop ]
<|code_end|>
, predict the immediate next line with the help of imports:
from math import sqrt
from datetime import datetime
from janus_const import const
and context (classes, functions, sometimes code) from other files:
# Path: janus_const.py
. Output only the next line. | if ( ( None in arr_n ) or ( None in arr_dv ) ) : |
Next line prediction: <|code_start|> ' ± ' )
self.prnt_dcm(
self.core.nln_res_plas[
'sig_v0_z'], 3 )
self.prnt_htm( 'km/s' )
elif ( pop['drift'] ) :
if ( self.core.opt['res_d'] ) :
self.prnt_brk( )
self.prnt_tab( 2 )
self.prnt_htm( lab_dv + ' = ' )
self.prnt_dcm( pop['dv'], 3 )
if( self.core.opt['res_u'] ) :
self.prnt_htm(
' ± ' )
self.prnt_dcm(
pop['sig_dv'], 3 )
self.prnt_htm( 'km/s')
# Print the population's thermal speed(s).
if ( self.core.opt['res_dw'] ) :
if ( pop['aniso'] ) :
if ( self.core.opt['res_w'] ) :
self.prnt_brk( )
self.prnt_tab( 2 )
<|code_end|>
. Use current file imports:
(from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QTextCursor
from janus_format_TextEdit import format_TextEdit
from numpy import sqrt
from math import log10, floor
from janus_helper import round_sig)
and context including class names, function names, or small code snippets from other files:
# Path: janus_format_TextEdit.py
# class format_TextEdit( QTextEdit ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self ) :
#
# # Inherit all attributes of an instance of "QTextEdit".
#
# super( format_TextEdit, self ).__init__( )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INDENTATION.
# #-----------------------------------------------------------------------
#
# def prnt_tab( self, t=1 ) :
#
# # Based on the value of "t", print an appropriate number of
# # white spaces.
#
# if ( t >= 1 ) :
# self.insertHtml( ' ' )
# if ( t >= 2 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
# if ( t >= 3 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A DECIMAL NUMBER.
# #-----------------------------------------------------------------------
#
# def prnt_dcm( self, num, dig=2, unt=None ) :
#
# # Convert "dig", the number of digits after the decimal place,
# # to a string.
#
# str_dig = '{:}'.format( int( round( dig ) ) )
#
# # Print the number "num" with "dig" digits after the decimal
# # point.
#
# self.insertHtml( ( '{:.' + str_dig + 'f}' ).format( num ) )
#
# # If "str_dig" is "0", then add in a decimal place (which is
# # otherwise omitted when no decimal places are requested.
#
# if ( str_dig == '0' ) :
#
# self.insertHtml( '.' )
#
# # If a string has been provided for the unit, print it as well.
#
# if ( unt is not None ) :
#
# self.insertHtml( ' ' + unt )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INTEGER.
# #-----------------------------------------------------------------------
#
# def prnt_int( self, num ) :
#
# # In case "num" isn't already an integer, make it one by
# # rounding.
#
# int_num = int( round( num ) )
#
# # Print the integer "int_num".
#
# self.insertHtml( '{:}'.format( int_num ) )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A LINE BREAK.
# #-----------------------------------------------------------------------
#
# def prnt_brk( self ) :
#
# # Print a line break.
#
# self.insertHtml( '<br>' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING GENERAL HTML TEXT.
# #-----------------------------------------------------------------------
#
# def prnt_htm( self, s , speak=False) :
#
# # Print the string "s" (as HTML code)..
#
# self.insertHtml( s )
#
# # For analysis that can take a long time to run, this is a helpful
# # reminder to check the result.
# if speak and platform.system() == "Darwin":
# os.system('say "%s"' % s)
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR TESTING WHETHER THE TEXT AREA IS EMPTY.
# #-----------------------------------------------------------------------
#
# def is_empty( self ) :
#
# # If the text area contains no text, return "True"; otherwise,
# # return "False".
#
# if ( self.toPlainText( ) == '' ) :
# return True
# else :
# return False
#
# Path: janus_helper.py
# def round_sig( val, sig ) :
#
# if ( val is None ) :
#
# return None
#
# elif ( val == 0. ) :
#
# return 0.
#
# else :
#
# return round( val,
# sig - int( floor( log10( abs( val ) ) ) ) - 1 )
. Output only the next line. | self.prnt_htm( |
Next line prediction: <|code_start|> self.moveCursor( QTextCursor.Start )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR RESPONDING TO THE "rset" SIGNAL.
#-----------------------------------------------------------------------
def resp_rset( self ) :
# Reset the text area.
self.clear( )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR RESPONDING TO THE "chng_opt" SIGNAL.
#-----------------------------------------------------------------------
def resp_chng_opt( self ) :
# Regenerate the text in the text area.
self.make_txt( )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR RESPONDING TO THE "chng_mfi" SIGNAL.
#-----------------------------------------------------------------------
def resp_chng_mfi( self ) :
# Replace the text in the text area.
<|code_end|>
. Use current file imports:
(from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QTextCursor
from janus_format_TextEdit import format_TextEdit)
and context including class names, function names, or small code snippets from other files:
# Path: janus_format_TextEdit.py
# class format_TextEdit( QTextEdit ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self ) :
#
# # Inherit all attributes of an instance of "QTextEdit".
#
# super( format_TextEdit, self ).__init__( )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INDENTATION.
# #-----------------------------------------------------------------------
#
# def prnt_tab( self, t=1 ) :
#
# # Based on the value of "t", print an appropriate number of
# # white spaces.
#
# if ( t >= 1 ) :
# self.insertHtml( ' ' )
# if ( t >= 2 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
# if ( t >= 3 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A DECIMAL NUMBER.
# #-----------------------------------------------------------------------
#
# def prnt_dcm( self, num, dig=2, unt=None ) :
#
# # Convert "dig", the number of digits after the decimal place,
# # to a string.
#
# str_dig = '{:}'.format( int( round( dig ) ) )
#
# # Print the number "num" with "dig" digits after the decimal
# # point.
#
# self.insertHtml( ( '{:.' + str_dig + 'f}' ).format( num ) )
#
# # If "str_dig" is "0", then add in a decimal place (which is
# # otherwise omitted when no decimal places are requested.
#
# if ( str_dig == '0' ) :
#
# self.insertHtml( '.' )
#
# # If a string has been provided for the unit, print it as well.
#
# if ( unt is not None ) :
#
# self.insertHtml( ' ' + unt )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INTEGER.
# #-----------------------------------------------------------------------
#
# def prnt_int( self, num ) :
#
# # In case "num" isn't already an integer, make it one by
# # rounding.
#
# int_num = int( round( num ) )
#
# # Print the integer "int_num".
#
# self.insertHtml( '{:}'.format( int_num ) )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A LINE BREAK.
# #-----------------------------------------------------------------------
#
# def prnt_brk( self ) :
#
# # Print a line break.
#
# self.insertHtml( '<br>' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING GENERAL HTML TEXT.
# #-----------------------------------------------------------------------
#
# def prnt_htm( self, s , speak=False) :
#
# # Print the string "s" (as HTML code)..
#
# self.insertHtml( s )
#
# # For analysis that can take a long time to run, this is a helpful
# # reminder to check the result.
# if speak and platform.system() == "Darwin":
# os.system('say "%s"' % s)
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR TESTING WHETHER THE TEXT AREA IS EMPTY.
# #-----------------------------------------------------------------------
#
# def is_empty( self ) :
#
# # If the text area contains no text, return "True"; otherwise,
# # return "False".
#
# if ( self.toPlainText( ) == '' ) :
# return True
# else :
# return False
. Output only the next line. | self.make_txt( ) |
Based on the snippet: <|code_start|>
if ( self.core.fc_spec is None ) :
return
# If a Wind/FC ion spectrum has been (successfully) loaded, but
# there are no Wind/MFI data (yet), return.
if ( self.core.n_mfi <= 0 ) :
return
# Print a summary of the Wind/MFI data.
self.prnt_htm( 'Number of Data: ' )
self.prnt_int( self.core.n_mfi )
self.prnt_brk( )
self.prnt_brk( )
self.prnt_htm( '<i>B</i> = ' )
self.prnt_dcm( self.core.mfi_avg_mag, 1, 'nT' )
self.prnt_brk( )
self.prnt_tab( 1 )
self.prnt_htm( '<i><font color="#FF0000">B<sub>x</sub></font></i> = ' )
self.prnt_dcm( self.core.mfi_avg_vec[0], 1, 'nT' )
self.prnt_brk( )
self.prnt_tab( 1 )
self.prnt_htm( '<i><font color="#00FF00">B<sub>y</sub></font></i> = ' )
self.prnt_dcm( self.core.mfi_avg_vec[1], 1, 'nT' )
<|code_end|>
, predict the immediate next line with the help of imports:
from PyQt4.QtCore import SIGNAL
from janus_format_TextEdit import format_TextEdit
and context (classes, functions, sometimes code) from other files:
# Path: janus_format_TextEdit.py
# class format_TextEdit( QTextEdit ) :
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self ) :
#
# # Inherit all attributes of an instance of "QTextEdit".
#
# super( format_TextEdit, self ).__init__( )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INDENTATION.
# #-----------------------------------------------------------------------
#
# def prnt_tab( self, t=1 ) :
#
# # Based on the value of "t", print an appropriate number of
# # white spaces.
#
# if ( t >= 1 ) :
# self.insertHtml( ' ' )
# if ( t >= 2 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
# if ( t >= 3 ) :
# self.insertHtml( ' ' )
# self.insertHtml( ' ' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A DECIMAL NUMBER.
# #-----------------------------------------------------------------------
#
# def prnt_dcm( self, num, dig=2, unt=None ) :
#
# # Convert "dig", the number of digits after the decimal place,
# # to a string.
#
# str_dig = '{:}'.format( int( round( dig ) ) )
#
# # Print the number "num" with "dig" digits after the decimal
# # point.
#
# self.insertHtml( ( '{:.' + str_dig + 'f}' ).format( num ) )
#
# # If "str_dig" is "0", then add in a decimal place (which is
# # otherwise omitted when no decimal places are requested.
#
# if ( str_dig == '0' ) :
#
# self.insertHtml( '.' )
#
# # If a string has been provided for the unit, print it as well.
#
# if ( unt is not None ) :
#
# self.insertHtml( ' ' + unt )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING AN INTEGER.
# #-----------------------------------------------------------------------
#
# def prnt_int( self, num ) :
#
# # In case "num" isn't already an integer, make it one by
# # rounding.
#
# int_num = int( round( num ) )
#
# # Print the integer "int_num".
#
# self.insertHtml( '{:}'.format( int_num ) )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING A LINE BREAK.
# #-----------------------------------------------------------------------
#
# def prnt_brk( self ) :
#
# # Print a line break.
#
# self.insertHtml( '<br>' )
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR PRINTING GENERAL HTML TEXT.
# #-----------------------------------------------------------------------
#
# def prnt_htm( self, s , speak=False) :
#
# # Print the string "s" (as HTML code)..
#
# self.insertHtml( s )
#
# # For analysis that can take a long time to run, this is a helpful
# # reminder to check the result.
# if speak and platform.system() == "Darwin":
# os.system('say "%s"' % s)
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR TESTING WHETHER THE TEXT AREA IS EMPTY.
# #-----------------------------------------------------------------------
#
# def is_empty( self ) :
#
# # If the text area contains no text, return "True"; otherwise,
# # return "False".
#
# if ( self.toPlainText( ) == '' ) :
# return True
# else :
# return False
. Output only the next line. | self.prnt_brk( ) |
Based on the snippet: <|code_start|> tmp_q = self.core.nln_plas.arr_spec[i]['q']
# Update each widget's text.
if ( tmp_name is not None ) :
self.arr_name[i].setTextUpdate( tmp_name )
if ( tmp_sym is not None ) :
self.arr_sym[i].setTextUpdate( tmp_sym )
if ( tmp_m is not None ) :
self.arr_m[i].setTextUpdate( str( tmp_m ) )
if ( tmp_q is not None ) :
self.arr_q[i].setTextUpdate( str( tmp_q ) )
# Format the text of each widget.
ss_name = 'background-color: white;\n'
ss_sym = 'background-color: white;\n'
ss_m = 'background-color: white;\n'
ss_q = 'background-color: white;\n'
if ( ( tmp_name is None ) and
( len( self.arr_name[i].text( ) ) > 0 ) ) :
ss_name += 'color: red;'
else :
ss_name += 'color: black;'
if ( ( tmp_sym is None ) and
<|code_end|>
, predict the immediate next line with the help of imports:
from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QGridLayout, QLabel, QLineEdit, QWidget
from janus_event_LineEdit import event_LineEdit
from numpy import tile
from threading import Thread
from janus_thread import n_thread, thread_chng_nln_spc
and context (classes, functions, sometimes code) from other files:
# Path: janus_event_LineEdit.py
# class event_LineEdit( QLineEdit ) :
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_LineEdit, self ).__init__( )
#
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
#
# # Intialize "text_old" with the current text in this text box.
#
# # Note. This variable is useful for establishing if and how
# # the text was changed. For example, the
# # "editingFinished()" signal is sent if a user removes
# # focus from this widget even if no actual edits were
# # made.
#
# self.text_old = self.text( )
#
#
# # If the 'editingFinished()' signal is emitted (i.e., this
# # widget looses the "focus"), notify "self.owner".
#
# self.connect( self, SIGNAL('editingFinished()'),
# self.signal_editingFinished )
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR SETTING THE TEXT AND UPDATING THE OLD TEXT.
# #-----------------------------------------------------------------------
#
# def setTextUpdate( self, text ) :
#
#
# # Set the text of this text box to that requested by the user.
#
# self.setText( text )
#
#
# # Update the record of the "old text" to the current text.
#
# self.text_old = self.text( )
#
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE SIGNAL FOR EDITING FINISHED.
# #-----------------------------------------------------------------------
#
# def signal_editingFinished( self ) :
#
#
# # If an actual change has been made to the text of this text
# # box, notify "self.owner" that this has occured.
#
# if ( self.text( ) != self.text_old ) :
#
# self.text_old = self.text( )
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_nln_spc( core, s, param, val ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_nln_spc( s, param, val )
#
# core.emit( SIGNAL('janus_busy_end') )
. Output only the next line. | ( len( self.arr_sym[i].text( ) ) > 0 ) ) : |
Next line prediction: <|code_start|>
for i in range( 6 ) :
self.grd.setColumnStretch( i, 1 )
for i in range( self.core.nln_n_spc + 1 ) :
self.grd.setRowStretch( i, 1 )
# Populate the text areas.
self.make_txt( )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR DISPLAYING TEXT AND CHECK MARKS.
#-----------------------------------------------------------------------
def make_txt( self ) :
# Display the parameters for each ion species.
for i in range( self.core.nln_n_spc ) :
# Extract the values from the core.
tmp_name = self.core.nln_plas.arr_spec[i]['name']
tmp_sym = self.core.nln_plas.arr_spec[i]['sym']
tmp_m = self.core.nln_plas.arr_spec[i]['m']
tmp_q = self.core.nln_plas.arr_spec[i]['q']
# Update each widget's text.
<|code_end|>
. Use current file imports:
(from PyQt4.QtCore import SIGNAL, Qt
from PyQt4.QtGui import QGridLayout, QLabel, QLineEdit, QWidget
from janus_event_LineEdit import event_LineEdit
from numpy import tile
from threading import Thread
from janus_thread import n_thread, thread_chng_nln_spc)
and context including class names, function names, or small code snippets from other files:
# Path: janus_event_LineEdit.py
# class event_LineEdit( QLineEdit ) :
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc ) :
#
#
# # Inherit all attributes of an instance of "QLineEdit".
#
# super( event_LineEdit, self ).__init__( )
#
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
#
# # Store the string indicating the function of this text area.
#
# self.fnc = fnc
#
#
# # Intialize "text_old" with the current text in this text box.
#
# # Note. This variable is useful for establishing if and how
# # the text was changed. For example, the
# # "editingFinished()" signal is sent if a user removes
# # focus from this widget even if no actual edits were
# # made.
#
# self.text_old = self.text( )
#
#
# # If the 'editingFinished()' signal is emitted (i.e., this
# # widget looses the "focus"), notify "self.owner".
#
# self.connect( self, SIGNAL('editingFinished()'),
# self.signal_editingFinished )
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR SETTING THE TEXT AND UPDATING THE OLD TEXT.
# #-----------------------------------------------------------------------
#
# def setTextUpdate( self, text ) :
#
#
# # Set the text of this text box to that requested by the user.
#
# self.setText( text )
#
#
# # Update the record of the "old text" to the current text.
#
# self.text_old = self.text( )
#
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE FUNCTION FOR RESPONDING TO THE SIGNAL FOR EDITING FINISHED.
# #-----------------------------------------------------------------------
#
# def signal_editingFinished( self ) :
#
#
# # If an actual change has been made to the text of this text
# # box, notify "self.owner" that this has occured.
#
# if ( self.text( ) != self.text_old ) :
#
# self.text_old = self.text( )
#
# self.owner.user_event( None, self.fnc )
#
# Path: janus_thread.py
# def n_thread( ) :
#
# n = 0
#
# for thr in ThreadList( ) :
# if ( ( thr._Thread__target is thread_load_spec ) or
# ( thr._Thread__target is thread_anls_mom ) or
# ( thr._Thread__target is thread_anls_nln ) or
# ( thr._Thread__target is thread_chng_dsp ) or
# ( thr._Thread__target is thread_chng_dyn ) or
# ( thr._Thread__target is thread_chng_opt ) or
# ( thr._Thread__target is thread_rstr_opt ) or
# ( thr._Thread__target is thread_auto_run ) or
# ( thr._Thread__target is thread_save_res ) or
# ( thr._Thread__target is thread_xprt_res ) or
# ( thr._Thread__target is thread_chng_mom_sel ) or
# ( thr._Thread__target is thread_auto_mom_sel ) or
# ( thr._Thread__target is thread_chng_nln_spc ) or
# ( thr._Thread__target is thread_chng_nln_pop ) or
# ( thr._Thread__target is thread_chng_nln_set ) or
# ( thr._Thread__target is thread_chng_nln_gss ) or
# ( thr._Thread__target is thread_chng_nln_sel ) or
# ( thr._Thread__target is thread_chng_mom_win_dir ) or
# ( thr._Thread__target is thread_chng_mom_win_bin ) ) :
# n += 1
#
# return n
#
# def thread_chng_nln_spc( core, s, param, val ) :
#
# core.emit( SIGNAL('janus_busy_end') )
# core.emit( SIGNAL('janus_busy_beg') )
#
# core.chng_nln_spc( s, param, val )
#
# core.emit( SIGNAL('janus_busy_end') )
. Output only the next line. | if ( tmp_name is not None ) : |
Based on the snippet: <|code_start|> self.lab = QLabel( 'Note: closing this window will *NOT* ' +
'interrupt the automated analysis.' )
self.lab.setWordWrap( True )
# Row by row, add the bar and buttons to the grid layout.
self.grd.addWidget( self.bar , 0, 0, 1, 1 )
self.grd.addWidget( self.btn_exit, 0, 1, 1, 1 )
self.grd.addWidget( self.lab , 1, 0, 1, 2 )
# Display this dialog.
self.show( )
#-----------------------------------------------------------------------
# DEFINE THE FUNCTION FOR UPDATING THE PROGRESS BAR.
#-----------------------------------------------------------------------
def updt_bar( self, time ) :
# Convert this functions argument (i.e., the timestamp of the
# current spectrum) to Unix time.
time_curr = calc_time_val( time )
# If necessary, adjust the minimum or maximum of the progress
# bar based on the new timestamp.
<|code_end|>
, predict the immediate next line with the help of imports:
from PyQt4.QtGui import QDialog, QGridLayout, QLabel, QProgressBar
from janus_event_PushButton import event_PushButton
from janus_time import calc_time_val
and context (classes, functions, sometimes code) from other files:
# Path: janus_event_PushButton.py
# class event_PushButton( QPushButton ) :
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc, lab='' ) :
#
#
# # Inherit all attributes of an instance of "QPushButton".
#
# super( event_PushButton, self ).__init__( lab )
#
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
#
# # Store the string indicating the function of this button.
#
# self.fnc = fnc
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO MOUSE CLICKS.
# #-----------------------------------------------------------------------
#
# def mousePressEvent( self, event ) :
#
#
# # Deligate the handling of the mouse-click event to
# # "self.owner", providing it with the details of the event and
# # also the string identifying the function of this button.
#
# self.owner.user_event( event, self.fnc )
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO KEY PRESSES.
# #-----------------------------------------------------------------------
#
# def keyPressEvent( self, event ) :
#
#
# # If the "Enter" or "Return" key was pressed, interpret this as
# # an event and deligate handling thereof to "self.owner".
#
# if ( ( event.key( ) == Qt.Key_Enter ) or
# ( event.key( ) == Qt.Key_Return ) ) :
#
# self.owner.user_event( event, self.fnc )
#
# Path: janus_time.py
# def calc_time_val( time ) :
#
# # If this function has been called on "None" or an empty string, simply
# # return "None".
#
# if ( ( time is None ) or ( time == '' ) ) :
# return None
#
# # If "time" is a "datetime" epoch or a string, compute the elapsed time
# # of "time" since "1970-01-01/00:00:00.000". Otherwise, assume that
# # "time" is a numerical quantity, and return "time" recast as a "float"
# # rounded to three decimal places (to "standardize" it).
#
# if ( ( type( time ) == datetime ) or
# ( type( time ) == str ) ) :
#
# # Attempt to standardize the "datetime" epoch "time". If this
# # fails, abort (returning "None").
#
# time_epc = calc_time_epc( time )
#
# if ( time_epc is None ) :
# return None
#
# # Create a "datetime" object for "1970-01-01/00:00:00.000".
#
# unix_epc = datetime( 1970, 1, 1, 0, 0, 0, 0 )
#
# # Return the number of seconds elased from "unix_epc" to
# # "time_epc" rounded to the thrid decimal place.
#
# return round( float(
# ( time_epc - unix_epc ).total_seconds( ) ), 3 )
#
# else :
#
# # Assume that "time" is a numerical quantity, and attempt to
# # return it recast as a "float" rounded to three decimal places.
# # If this fails, return "None" instead.
#
# try :
# return round( float( time ), 3 )
# except :
# return None
. Output only the next line. | if ( time_curr < self.bar.minimum( ) ) : |
Predict the next line after this snippet: <|code_start|>
# Set the title of this dialog window.
self.setWindowTitle( 'Progress' )
# Give this widget a grid layout, "self.grd".
self.grd = QGridLayout( )
self.grd.setContentsMargins( 6, 6, 6, 6 )
self.setLayout( self.grd )
# Initialize the progress bar and set its minimum, maximum, and
# initial values.
self.bar = QProgressBar( )
self.bar.setMinimum( calc_time_val( time_strt ) )
self.bar.setMaximum( calc_time_val( time_stop ) )
self.bar.setValue( self.bar.minimum( ) )
# Initialize the event button.
self.btn_exit = event_PushButton( self, 'exit', 'Close' )
# Initialize the label.
self.lab = QLabel( 'Note: closing this window will *NOT* ' +
<|code_end|>
using the current file's imports:
from PyQt4.QtGui import QDialog, QGridLayout, QLabel, QProgressBar
from janus_event_PushButton import event_PushButton
from janus_time import calc_time_val
and any relevant context from other files:
# Path: janus_event_PushButton.py
# class event_PushButton( QPushButton ) :
#
#
# #-----------------------------------------------------------------------
# # DEFINE THE INITIALIZATION FUNCTION.
# #-----------------------------------------------------------------------
#
# def __init__( self, owner, fnc, lab='' ) :
#
#
# # Inherit all attributes of an instance of "QPushButton".
#
# super( event_PushButton, self ).__init__( lab )
#
#
# # Store the user-provided instance of the initializing object.
#
# self.owner = owner
#
#
# # Store the string indicating the function of this button.
#
# self.fnc = fnc
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO MOUSE CLICKS.
# #-----------------------------------------------------------------------
#
# def mousePressEvent( self, event ) :
#
#
# # Deligate the handling of the mouse-click event to
# # "self.owner", providing it with the details of the event and
# # also the string identifying the function of this button.
#
# self.owner.user_event( event, self.fnc )
#
#
# #-----------------------------------------------------------------------
# # (RE)DEFINE THE FUNCTION FOR RESPONDING TO KEY PRESSES.
# #-----------------------------------------------------------------------
#
# def keyPressEvent( self, event ) :
#
#
# # If the "Enter" or "Return" key was pressed, interpret this as
# # an event and deligate handling thereof to "self.owner".
#
# if ( ( event.key( ) == Qt.Key_Enter ) or
# ( event.key( ) == Qt.Key_Return ) ) :
#
# self.owner.user_event( event, self.fnc )
#
# Path: janus_time.py
# def calc_time_val( time ) :
#
# # If this function has been called on "None" or an empty string, simply
# # return "None".
#
# if ( ( time is None ) or ( time == '' ) ) :
# return None
#
# # If "time" is a "datetime" epoch or a string, compute the elapsed time
# # of "time" since "1970-01-01/00:00:00.000". Otherwise, assume that
# # "time" is a numerical quantity, and return "time" recast as a "float"
# # rounded to three decimal places (to "standardize" it).
#
# if ( ( type( time ) == datetime ) or
# ( type( time ) == str ) ) :
#
# # Attempt to standardize the "datetime" epoch "time". If this
# # fails, abort (returning "None").
#
# time_epc = calc_time_epc( time )
#
# if ( time_epc is None ) :
# return None
#
# # Create a "datetime" object for "1970-01-01/00:00:00.000".
#
# unix_epc = datetime( 1970, 1, 1, 0, 0, 0, 0 )
#
# # Return the number of seconds elased from "unix_epc" to
# # "time_epc" rounded to the thrid decimal place.
#
# return round( float(
# ( time_epc - unix_epc ).total_seconds( ) ), 3 )
#
# else :
#
# # Assume that "time" is a numerical quantity, and attempt to
# # return it recast as a "float" rounded to three decimal places.
# # If this fails, return "None" instead.
#
# try :
# return round( float( time ), 3 )
# except :
# return None
. Output only the next line. | 'interrupt the automated analysis.' ) |
Here is a snippet: <|code_start|>
CNAME = "sendmsg"
def main(command):
args = command.replace(CNAME, "").strip().split(" ", maxsplit=1)
#print(args)
if len(args) == 2:
idstr = args[0]
if str.isnumeric(idstr):
<|code_end|>
. Write the next line using the current file imports:
import bot_header
from vk_api.api import get_api
from vk_api.api import api_request
and context from other files:
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
, which may include functions, classes, or code. Output only the next line. | idn = int(idstr) |
Predict the next line for this snippet: <|code_start|>
CNAME = "sendmsg"
def main(command):
args = command.replace(CNAME, "").strip().split(" ", maxsplit=1)
#print(args)
if len(args) == 2:
<|code_end|>
with the help of current file imports:
import bot_header
from vk_api.api import get_api
from vk_api.api import api_request
and context from other files:
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
, which may contain function names, class names, or code. Output only the next line. | idstr = args[0] |
Predict the next line after this snippet: <|code_start|>
def main(C):
print("this is horosho")
# get API instance
api = get_api(account=bot_header.CURRENT_ACCOUNT)
# get followers
fws = api_request(api, "users.getFollowers", "")
fwitems = fws['items']
for item in fwitems:
add(item, api)
def add(item, api):
try:
sleep(3)
# print("Trying 2 add %s ..." % item)
addf = api_request(api, "friends.add", "user_id=%s" % item)
print("Adding %s ... %s" % (item, str(addf)))
except Exception as e:
err = str(e)
<|code_end|>
using the current file's imports:
import bot_header
from vk_api.api import api_request
from vk_api.api import get_api
from time import sleep
and any relevant context from other files:
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
. Output only the next line. | if "per second" in err.lower(): |
Predict the next line for this snippet: <|code_start|>
CNAME = "audiobc"
def main(command):
args = command.replace(CNAME, "").strip()
msg = args
if not msg:
raise Exception("Usage: audiobc 'OID_AID'")
api = get_api(account=bot_header.CURRENT_ACCOUNT)
r = api_request(api, "audio.setBroadcast", "audio=\"%s\"" % (msg))
<|code_end|>
with the help of current file imports:
import bot_header
from vk_api.api import get_api
from vk_api.api import api_request
and context from other files:
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
, which may contain function names, class names, or code. Output only the next line. | return r |
Given snippet: <|code_start|> time_each = None
time_when = None
action = None
action_value = None
def from_json(d):
s = AutoexecRule(force=True)
s.__dict__.update(d)
return s
def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
if not force:
if not time_each:
time_each = None
if not time_when:
time_when = None
print("%s%s" % (time_each, time_when))
if time_each == None and time_when == None:
raise AttributeError("You must specify time when it action will be go")
if time_each != None and time_when != None:
raise AttributeError("You can't specify each and when parameters in the same time")
if time_when is not None:
self.time_when = time_utils.parse_time(time_when)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from utils import time_utils
and context:
# Path: utils/time_utils.py
# def parse_time(time):
which might include code, classes, or functions. Output only the next line. | if time_each is not None: |
Next line prediction: <|code_start|>
def main(cmd):
print("Starting thread...")
bot_header.SET_ONLINE_THREAD_INSTANCE = OnlineThread(account=bot_header.CURRENT_ACCOUNT, lpt=bot_header.LONG_POOL_THREAD_INSTANCE)
<|code_end|>
. Use current file imports:
(import bot_header
from vk_api.set_online import OnlineThread)
and context including class names, function names, or small code snippets from other files:
# Path: vk_api/set_online.py
# class OnlineThread(threading.Thread):
# account = None
# enabled = True
# interval = 20
#
# def __init__(self, lpt=None, account=None, enabled=True, interval=30):
# super().__init__()
#
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# self.account = lpt.account
# elif account is not None:
# self.account = account
# self.enabled = enabled
# self.interval = interval
#
#
# def print(self, text):
# print('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def v(self, text):
# bot_header.v('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def w(self, text):
# bot_header.w('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def set_online(self, online):
# if online:
# method = "account.setOnline"
# response = api_request(get_api(account=self.account), method, "voip=0")
# return response
# else:
# method = "account.setOffline"
# response = api_request(get_api(account=self.account), method, "")
# return response
#
# def stop(self):
# self.enabled = False
# self.set_online(False)
# bot_header.SET_ONLINE_THREAD_INSTANCE = None
#
# def run(self):
# self.v("Starting loop")
#
# while self.enabled:
# online = self.set_online(True)
# self.v("Set online: %s" % online)
# sleep(self.interval)
# pass
# self.print("Stopping thread...")
. Output only the next line. | bot_header.SET_ONLINE_THREAD_INSTANCE.setDaemon(True) |
Continue the code snippet: <|code_start|>
# Name for key of acc list
ACCOUNT_LIST = "account list"
class AccountManager:
def __init__(self, location=config_file.CONF_FILE):
self.location = location
# location of file with users
location = config_file.CONF_FILE
def get_account_list_raw(self, accs):
<|code_end|>
. Use current file imports:
import json as j
from utils import config_file
from vk_api.api import Account
and context (classes, functions, or code) from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# class Account(User):
# token = ''
#
# def from_json(d):
# s = Account()
# s.__dict__.update(d)
# return s
. Output only the next line. | if accs == None: |
Given snippet: <|code_start|>
# Name for key of acc list
ACCOUNT_LIST = "account list"
class AccountManager:
def __init__(self, location=config_file.CONF_FILE):
self.location = location
# location of file with users
location = config_file.CONF_FILE
def get_account_list_raw(self, accs):
if accs == None:
return []
accs = accs.replace("'", '"')
result = []
json = j.loads(accs)
for object in json:
result.append(j.loads(str(object).replace("'", '"'), object_hook=Account.from_json))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json as j
from utils import config_file
from vk_api.api import Account
and context:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# class Account(User):
# token = ''
#
# def from_json(d):
# s = Account()
# s.__dict__.update(d)
# return s
which might include code, classes, or functions. Output only the next line. | return result |
Here is a snippet: <|code_start|>
def select_acc(list, num):
if num is not '-1' and str.isnumeric(num):
val = int(num)
if len(list) < val:
print("This account is not exists")
exit(1)
acc = list[val]
return acc
else:
for acc in list:
print("[%d] %s %s" % (list.index(acc), acc.first_name, acc.last_name))
cla = config_file.get_field("last acc")
last = None
if cla is not None:
if str.isnumeric(cla):
last = int(cla)
if last > len(list) - 1:
last = None
config_file.set_field("last acc", "None")
else:
print("Default is %s (Just press ENTER)" % list[last].first_last())
<|code_end|>
. Write the next line using the current file imports:
from utils import config_file
and context from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
, which may include functions, classes, or code. Output only the next line. | id = input("Select Account: ") |
Continue the code snippet: <|code_start|> self.interval = interval
def print(self, text):
print('[::OTHD] [%s] %s' % (self.account.first_last(), text))
def v(self, text):
bot_header.v('[::OTHD] [%s] %s' % (self.account.first_last(), text))
def w(self, text):
bot_header.w('[::OTHD] [%s] %s' % (self.account.first_last(), text))
def set_online(self, online):
if online:
method = "account.setOnline"
response = api_request(get_api(account=self.account), method, "voip=0")
return response
else:
method = "account.setOffline"
response = api_request(get_api(account=self.account), method, "")
return response
def stop(self):
self.enabled = False
self.set_online(False)
bot_header.SET_ONLINE_THREAD_INSTANCE = None
def run(self):
self.v("Starting loop")
<|code_end|>
. Use current file imports:
import threading
import bot_header
from time import sleep
from vk_api.api import api_request, get_api
and context (classes, functions, or code) from other files:
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
. Output only the next line. | while self.enabled: |
Continue the code snippet: <|code_start|>
def main(cmd):
t = OnlineThread(bot_header.LONG_POOL_THREAD_INSTANCE)
r = t.set_online(1)
<|code_end|>
. Use current file imports:
import bot
import bot_header
from vk_api.set_online import OnlineThread
and context (classes, functions, or code) from other files:
# Path: vk_api/set_online.py
# class OnlineThread(threading.Thread):
# account = None
# enabled = True
# interval = 20
#
# def __init__(self, lpt=None, account=None, enabled=True, interval=30):
# super().__init__()
#
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# self.account = lpt.account
# elif account is not None:
# self.account = account
# self.enabled = enabled
# self.interval = interval
#
#
# def print(self, text):
# print('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def v(self, text):
# bot_header.v('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def w(self, text):
# bot_header.w('[::OTHD] [%s] %s' % (self.account.first_last(), text))
#
# def set_online(self, online):
# if online:
# method = "account.setOnline"
# response = api_request(get_api(account=self.account), method, "voip=0")
# return response
# else:
# method = "account.setOffline"
# response = api_request(get_api(account=self.account), method, "")
# return response
#
# def stop(self):
# self.enabled = False
# self.set_online(False)
# bot_header.SET_ONLINE_THREAD_INSTANCE = None
#
# def run(self):
# self.v("Starting loop")
#
# while self.enabled:
# online = self.set_online(True)
# self.v("Set online: %s" % online)
# sleep(self.interval)
# pass
# self.print("Stopping thread...")
. Output only the next line. | print("Setting online... %s" % r) |
Predict the next line after this snippet: <|code_start|>
def get_action_type(param):
if param == 'HC_CONSOLE':
return AutoexecActionType.ACTION_HC_CONSOLE
else:
<|code_end|>
using the current file's imports:
from optparse import OptionParser
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from utils.time_utils import parse_time
from autoexec.autoexec_action_type import AutoexecActionType
from autoexec.autoexec import AutoexecRule
import bot_header
and any relevant context from other files:
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: utils/time_utils.py
# def parse_time(time):
# if type(time) == int:
# return time
# elif type(time) == str:
# rtime = 0
# r = re.findall("(\d+)s", time)
# for o in r:
# rtime += int(o)
#
# r = re.findall("(\d+)m", time)
# for o in r:
# rtime += int(o) * 60
#
# r = re.findall("(\d+)h", time)
# for o in r:
# rtime += int(o) * 3600
#
# r = re.findall("(\d+)d", time)
# for o in r:
# rtime += int(o) * 3600 * 24
# return rtime
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
. Output only the next line. | return None |
Given the code snippet: <|code_start|>
def get_action_type(param):
if param == 'HC_CONSOLE':
return AutoexecActionType.ACTION_HC_CONSOLE
else:
return None
pass
def main(c):
parser = OptionParser()
parser.set_usage(__name__.replace(".", " ") + " [OPTIONS]")
parser.add_option("-t", "--type", dest="type", help="type of the rule (when - exec after some time and delete, each - execute each time)")
<|code_end|>
, generate the next line using the imports in this file:
from optparse import OptionParser
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from utils.time_utils import parse_time
from autoexec.autoexec_action_type import AutoexecActionType
from autoexec.autoexec import AutoexecRule
import bot_header
and context (functions, classes, or occasionally code) from other files:
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: utils/time_utils.py
# def parse_time(time):
# if type(time) == int:
# return time
# elif type(time) == str:
# rtime = 0
# r = re.findall("(\d+)s", time)
# for o in r:
# rtime += int(o)
#
# r = re.findall("(\d+)m", time)
# for o in r:
# rtime += int(o) * 60
#
# r = re.findall("(\d+)h", time)
# for o in r:
# rtime += int(o) * 3600
#
# r = re.findall("(\d+)d", time)
# for o in r:
# rtime += int(o) * 3600 * 24
# return rtime
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
. Output only the next line. | parser.add_option("-T", "--time", dest="time", help="time: format: *s/m/h/d") |
Given the code snippet: <|code_start|>
def get_action_type(param):
if param == 'HC_CONSOLE':
return AutoexecActionType.ACTION_HC_CONSOLE
else:
return None
pass
def main(c):
parser = OptionParser()
parser.set_usage(__name__.replace(".", " ") + " [OPTIONS]")
parser.add_option("-t", "--type", dest="type", help="type of the rule (when - exec after some time and delete, each - execute each time)")
parser.add_option("-T", "--time", dest="time", help="time: format: *s/m/h/d")
parser.add_option("-a", "--action-type", dest="action", help="the action type of rule (now available only HC_CONSOLE)")
parser.add_option("-A", "--action-value", dest="action_value", help="the value of action (USE /s instead of spaces) (in case of action type 'HC_CONSOLE' it's command to execute in console)")
parser.add_option("-#", "--id", dest="id", help="use specific id (not required because it will be generated automatically if not defined)")
parser.add_option("-?", "--?", default=None, action="callback", callback=help, help="show this help message")
o, a = parser.parse_args(c.split())
o = o.__dict__
type = o['type']
if str.isnumeric(o['time']):
time = int(o['time'])
else:
time = parse_time(o['time'])
<|code_end|>
, generate the next line using the imports in this file:
from optparse import OptionParser
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from utils.time_utils import parse_time
from autoexec.autoexec_action_type import AutoexecActionType
from autoexec.autoexec import AutoexecRule
import bot_header
and context (functions, classes, or occasionally code) from other files:
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: utils/time_utils.py
# def parse_time(time):
# if type(time) == int:
# return time
# elif type(time) == str:
# rtime = 0
# r = re.findall("(\d+)s", time)
# for o in r:
# rtime += int(o)
#
# r = re.findall("(\d+)m", time)
# for o in r:
# rtime += int(o) * 60
#
# r = re.findall("(\d+)h", time)
# for o in r:
# rtime += int(o) * 3600
#
# r = re.findall("(\d+)d", time)
# for o in r:
# rtime += int(o) * 3600 * 24
# return rtime
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
. Output only the next line. | a_type = get_action_type(o['action']) |
Continue the code snippet: <|code_start|>
def get_action_type(param):
if param == 'HC_CONSOLE':
return AutoexecActionType.ACTION_HC_CONSOLE
else:
return None
pass
def main(c):
parser = OptionParser()
parser.set_usage(__name__.replace(".", " ") + " [OPTIONS]")
parser.add_option("-t", "--type", dest="type", help="type of the rule (when - exec after some time and delete, each - execute each time)")
parser.add_option("-T", "--time", dest="time", help="time: format: *s/m/h/d")
parser.add_option("-a", "--action-type", dest="action", help="the action type of rule (now available only HC_CONSOLE)")
parser.add_option("-A", "--action-value", dest="action_value", help="the value of action (USE /s instead of spaces) (in case of action type 'HC_CONSOLE' it's command to execute in console)")
parser.add_option("-#", "--id", dest="id", help="use specific id (not required because it will be generated automatically if not defined)")
<|code_end|>
. Use current file imports:
from optparse import OptionParser
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from utils.time_utils import parse_time
from autoexec.autoexec_action_type import AutoexecActionType
from autoexec.autoexec import AutoexecRule
import bot_header
and context (classes, functions, or code) from other files:
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: utils/time_utils.py
# def parse_time(time):
# if type(time) == int:
# return time
# elif type(time) == str:
# rtime = 0
# r = re.findall("(\d+)s", time)
# for o in r:
# rtime += int(o)
#
# r = re.findall("(\d+)m", time)
# for o in r:
# rtime += int(o) * 60
#
# r = re.findall("(\d+)h", time)
# for o in r:
# rtime += int(o) * 3600
#
# r = re.findall("(\d+)d", time)
# for o in r:
# rtime += int(o) * 3600 * 24
# return rtime
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
. Output only the next line. | parser.add_option("-?", "--?", default=None, action="callback", callback=help, help="show this help message") |
Here is a snippet: <|code_start|>
# set current path to root of project
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
class LongPoolThread(threading.Thread):
# Account that will be used for Messages.GetLongPoolServer
# .. Method on VK API
<|code_end|>
. Write the next line using the current file imports:
import json
import os,sys,inspect
import requests
import vk
import bot_header
import vk_api
import random
import threading
import time
import mpm_manager
from long_pool.long_pool_event import LongPoolEvent
from console import bot_console
and context from other files:
# Path: long_pool/long_pool_event.py
# class LongPoolEvent(Enum):
# MESSAGE_FLAG_REPLACE = 1
# MESSAGE_FLAG_SET = 2
# MESSAGE_FLAG_RESET = 3
# MESSAGE_SEND = 4
# MESSAGE_READALL_OUT = 7
# MESSAGE_READALL_IN = 6
# FRIEND_ONLINE = 8
# FRIEND_OFFLINE = 9
# FILTER_FLAG_RESET = 10
# FILTER_FLAG_REPLACE = 11
# FILTER_FLAG_SET = 12
# MCHAT_PARAM_CHANGE = 51
# START_TYPING_C = 61
# START_TYPING_MC = 62
# UNREAD_UPDATE = 80
# UNKNOWN = -1
#
# def __str__(self):
# return '%s' % self._value_
#
#
# def process(evid, resp, lp_thread_ins):
# # get name of event by id
# method_name = LongPoolEvent(evid).name.lower()
# # execute file in $rootOfProject/long_pool_events/$nameOfMethod
# try:
# exec('from long_pool_events import module_%s' % method_name)
# exec("reload( module_" + method_name + ")")
# exec('module_%s.main(resp, lp_thread_ins)' % method_name)
# # exec("retval = LongPoolEvent.__%s__(evid)" % method_name)
# except ImportError as e:
# bot_header.v(e)
# bot_header.v("---W---[LP] define new file in long_pool_events: module_%s with method 'main'" % method_name)
# pass
# except Exception as exc:
# exceptiondata = traceback.format_exc().splitlines()
# exceptionarray = exceptiondata[-1] + " " + exceptiondata[-2] + " " + exceptiondata[-3]
# bot_header.w("[LP] Exception in modules %s:\n | %s Trace:\n | %s" % (method_name,
# str(exc),
# str(exceptionarray)))
#
# Path: console/bot_console.py
# class Console(object):
# def get_message(self):
# def exec_startup(self):
# def run_looped(self):
# def run(self, ui):
# def process_dir(self, ui, dir):
, which may include functions, classes, or code. Output only the next line. | account = None |
Based on the snippet: <|code_start|>
# execute when user started typing.
def main(message, lpt):
# get id of user
typing_id = message[1]
# get user from VK API by id
user = User.from_json(api_request(get_api(lpt=lpt), "users.get", "user_ids=%s" % typing_id)[0])
# print some message to inform user that someone started typing:)
<|code_end|>
, predict the immediate next line with the help of imports:
import bot_header
from vk_api.api import User
from vk_api.api import api_request
from vk_api.api import get_api
and context (classes, functions, sometimes code) from other files:
# Path: vk_api/api.py
# class User():
# first_name = ''
# last_name = ''
# user_id = ''
#
#
# def first_last(self):
# return "%s %s" % (self.first_name, self.last_name)
#
# def from_json(d):
# s = User()
# s.__dict__.update(d)
# return s
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
. Output only the next line. | bot_header.v("%s started typing..." % user.first_last()) |
Based on the snippet: <|code_start|>
# execute when user started typing.
def main(message, lpt):
# get id of user
typing_id = message[1]
# get user from VK API by id
user = User.from_json(api_request(get_api(lpt=lpt), "users.get", "user_ids=%s" % typing_id)[0])
# print some message to inform user that someone started typing:)
<|code_end|>
, predict the immediate next line with the help of imports:
import bot_header
from vk_api.api import User
from vk_api.api import api_request
from vk_api.api import get_api
and context (classes, functions, sometimes code) from other files:
# Path: vk_api/api.py
# class User():
# first_name = ''
# last_name = ''
# user_id = ''
#
#
# def first_last(self):
# return "%s %s" % (self.first_name, self.last_name)
#
# def from_json(d):
# s = User()
# s.__dict__.update(d)
# return s
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
. Output only the next line. | bot_header.v("%s started typing..." % user.first_last()) |
Here is a snippet: <|code_start|>
# execute when user started typing.
def main(message, lpt):
# get id of user
typing_id = message[1]
# get user from VK API by id
user = User.from_json(api_request(get_api(lpt=lpt), "users.get", "user_ids=%s" % typing_id)[0])
# print some message to inform user that someone started typing:)
<|code_end|>
. Write the next line using the current file imports:
import bot_header
from vk_api.api import User
from vk_api.api import api_request
from vk_api.api import get_api
and context from other files:
# Path: vk_api/api.py
# class User():
# first_name = ''
# last_name = ''
# user_id = ''
#
#
# def first_last(self):
# return "%s %s" % (self.first_name, self.last_name)
#
# def from_json(d):
# s = User()
# s.__dict__.update(d)
# return s
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
, which may include functions, classes, or code. Output only the next line. | bot_header.v("%s started typing..." % user.first_last()) |
Next line prediction: <|code_start|> e = message.extra
# Getting list of modules
manager = mpm_manager.ModuleManager()
modules = manager.get_modules()
# Exec each modules and get result
for module in modules:
result = module.execute_module(message, lpt)
if result is not None:
return result
pass
# entry point of MESSAGE_SEND event of long pool server
# calling from long_pool_event.py
def main(resp, lp_thread_ins):
#
# Getting message from response
message = Message()
message = Message.from_long_pool(message, resp)
#
if message.is_out():
bot_header.LP_MESSAGES_RECEIVED += 1
else:
bot_header.LP_MESSAGES_SENT += 1
# Printing message to std out
if message.is_loopback():
sep = "<->"
<|code_end|>
. Use current file imports:
(import inspect
import os
import random
import sys
import mpm_manager
import bot_header
from time import sleep
from utils import config_file
from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi)
and context including class names, function names, or small code snippets from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# class Message:
#
# class MessageAttachment:
# attachment_value = None
# attachment_type = None
#
# def __init__(self, type, value):
# self.attachment_type = type
# self.attachment_value = value
#
# mid = None # ID of message
# flag = None # message flags (See VK Long pool docs)
# pid = None # peer id (Sender id)
# ts = None # timestamp
# sub = None # subject of message (if private dialog - " ... ", if chat - chat title)
# body = None # test of message
# extra = None # extra fields (forwarded messages, etc)
# attachments = None
#
# # get specific message flag (See VK Long pool docs)
# def msgFlag(self, i, f):
# return (f & i) > 0
#
# # check is message not incoming
# def is_out(self):
# return self.msgFlag(self.flag, 2)
#
# def is_loopback(self, account=None):
# if account is None:
# account = bot_header.CURRENT_ACCOUNT
# return self.pid == account.user_id
#
# # check is message sent from chat
# def is_chat(self):
# return self.pid >= 2000000000
#
# # init
# def __init__(self, mid=None, flag=None, pid=None, ts=None, sub=None, body=None, extra=None):
# self.mid = mid
# self.flag = flag
# self.pid = pid
# self.ts = ts
# self.sub = sub
# self.body = body
# self.extra = extra
# if extra is not None:
# self.attachments = self.parse_attachments()
#
# # get message from long pool response
# def from_long_pool(self, resp):
# mid = resp[1]
# flag = resp[2]
# pid = resp[3]
# ts = resp[4]
# sub = resp[5]
# body = resp[6]
# extra = resp[7]
# return Message(mid=mid, flag=flag, pid=pid, ts=ts, sub=sub, body=body, extra=extra)
#
# def parse_attachments(self):
# # print(self.extra)
# # initialize empty list
# result = []
#
# # checking for attachments
# if not "attach1_type" in self.extra:
# return result
#
# # if message has attachs, start parsing
# # parse attachment
# i = 1
# print("id: %s" % i)
# # get attach by number
# while "attach%s_type" % i in self.extra:
# attach_type = self.extra["attach%s_type" % str(i)]
# attach_val = self.extra["attach%s" % str(i)]
# if attach_type == "doc":
# if "attach%s_kind" % str(i):
# if self.extra["attach%s_kind" % str(i)] == "audiomsg":
# attach_type = "amessage"
# print("Got id %s with data %s" % (attach_type, attach_val))
# result.append(Message.MessageAttachment(attach_type, attach_val))
# i+=1
# return result
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
. Output only the next line. | elif message.is_out(): |
Continue the code snippet: <|code_start|> # Exec each modules and get result
for module in modules:
result = module.execute_module(message, lpt)
if result is not None:
return result
pass
# entry point of MESSAGE_SEND event of long pool server
# calling from long_pool_event.py
def main(resp, lp_thread_ins):
#
# Getting message from response
message = Message()
message = Message.from_long_pool(message, resp)
#
if message.is_out():
bot_header.LP_MESSAGES_RECEIVED += 1
else:
bot_header.LP_MESSAGES_SENT += 1
# Printing message to std out
if message.is_loopback():
sep = "<->"
elif message.is_out():
sep = "->"
else:
sep = "<-"
<|code_end|>
. Use current file imports:
import inspect
import os
import random
import sys
import mpm_manager
import bot_header
from time import sleep
from utils import config_file
from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi
and context (classes, functions, or code) from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# class Message:
#
# class MessageAttachment:
# attachment_value = None
# attachment_type = None
#
# def __init__(self, type, value):
# self.attachment_type = type
# self.attachment_value = value
#
# mid = None # ID of message
# flag = None # message flags (See VK Long pool docs)
# pid = None # peer id (Sender id)
# ts = None # timestamp
# sub = None # subject of message (if private dialog - " ... ", if chat - chat title)
# body = None # test of message
# extra = None # extra fields (forwarded messages, etc)
# attachments = None
#
# # get specific message flag (See VK Long pool docs)
# def msgFlag(self, i, f):
# return (f & i) > 0
#
# # check is message not incoming
# def is_out(self):
# return self.msgFlag(self.flag, 2)
#
# def is_loopback(self, account=None):
# if account is None:
# account = bot_header.CURRENT_ACCOUNT
# return self.pid == account.user_id
#
# # check is message sent from chat
# def is_chat(self):
# return self.pid >= 2000000000
#
# # init
# def __init__(self, mid=None, flag=None, pid=None, ts=None, sub=None, body=None, extra=None):
# self.mid = mid
# self.flag = flag
# self.pid = pid
# self.ts = ts
# self.sub = sub
# self.body = body
# self.extra = extra
# if extra is not None:
# self.attachments = self.parse_attachments()
#
# # get message from long pool response
# def from_long_pool(self, resp):
# mid = resp[1]
# flag = resp[2]
# pid = resp[3]
# ts = resp[4]
# sub = resp[5]
# body = resp[6]
# extra = resp[7]
# return Message(mid=mid, flag=flag, pid=pid, ts=ts, sub=sub, body=body, extra=extra)
#
# def parse_attachments(self):
# # print(self.extra)
# # initialize empty list
# result = []
#
# # checking for attachments
# if not "attach1_type" in self.extra:
# return result
#
# # if message has attachs, start parsing
# # parse attachment
# i = 1
# print("id: %s" % i)
# # get attach by number
# while "attach%s_type" % i in self.extra:
# attach_type = self.extra["attach%s_type" % str(i)]
# attach_val = self.extra["attach%s" % str(i)]
# if attach_type == "doc":
# if "attach%s_kind" % str(i):
# if self.extra["attach%s_kind" % str(i)] == "audiomsg":
# attach_type = "amessage"
# print("Got id %s with data %s" % (attach_type, attach_val))
# result.append(Message.MessageAttachment(attach_type, attach_val))
# i+=1
# return result
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
. Output only the next line. | fpid = False |
Using the snippet: <|code_start|>
FORMAT_PID_STR = "longpool format peer id"
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
# THIS METHOD EXECUTING WHEN USER SENT A MESSAGE TO YOU
# calling from main()
<|code_end|>
, determine the next line of code. You have imports:
import inspect
import os
import random
import sys
import mpm_manager
import bot_header
from time import sleep
from utils import config_file
from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi
and context (class names, function names, or code) available:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# class Message:
#
# class MessageAttachment:
# attachment_value = None
# attachment_type = None
#
# def __init__(self, type, value):
# self.attachment_type = type
# self.attachment_value = value
#
# mid = None # ID of message
# flag = None # message flags (See VK Long pool docs)
# pid = None # peer id (Sender id)
# ts = None # timestamp
# sub = None # subject of message (if private dialog - " ... ", if chat - chat title)
# body = None # test of message
# extra = None # extra fields (forwarded messages, etc)
# attachments = None
#
# # get specific message flag (See VK Long pool docs)
# def msgFlag(self, i, f):
# return (f & i) > 0
#
# # check is message not incoming
# def is_out(self):
# return self.msgFlag(self.flag, 2)
#
# def is_loopback(self, account=None):
# if account is None:
# account = bot_header.CURRENT_ACCOUNT
# return self.pid == account.user_id
#
# # check is message sent from chat
# def is_chat(self):
# return self.pid >= 2000000000
#
# # init
# def __init__(self, mid=None, flag=None, pid=None, ts=None, sub=None, body=None, extra=None):
# self.mid = mid
# self.flag = flag
# self.pid = pid
# self.ts = ts
# self.sub = sub
# self.body = body
# self.extra = extra
# if extra is not None:
# self.attachments = self.parse_attachments()
#
# # get message from long pool response
# def from_long_pool(self, resp):
# mid = resp[1]
# flag = resp[2]
# pid = resp[3]
# ts = resp[4]
# sub = resp[5]
# body = resp[6]
# extra = resp[7]
# return Message(mid=mid, flag=flag, pid=pid, ts=ts, sub=sub, body=body, extra=extra)
#
# def parse_attachments(self):
# # print(self.extra)
# # initialize empty list
# result = []
#
# # checking for attachments
# if not "attach1_type" in self.extra:
# return result
#
# # if message has attachs, start parsing
# # parse attachment
# i = 1
# print("id: %s" % i)
# # get attach by number
# while "attach%s_type" % i in self.extra:
# attach_type = self.extra["attach%s_type" % str(i)]
# attach_val = self.extra["attach%s" % str(i)]
# if attach_type == "doc":
# if "attach%s_kind" % str(i):
# if self.extra["attach%s_kind" % str(i)] == "audiomsg":
# attach_type = "amessage"
# print("Got id %s with data %s" % (attach_type, attach_val))
# result.append(Message.MessageAttachment(attach_type, attach_val))
# i+=1
# return result
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
. Output only the next line. | def on_message_received(message, lpt): |
Next line prediction: <|code_start|>
FORMAT_PID_STR = "longpool format peer id"
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
<|code_end|>
. Use current file imports:
(import inspect
import os
import random
import sys
import mpm_manager
import bot_header
from time import sleep
from utils import config_file
from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi)
and context including class names, function names, or small code snippets from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# class Message:
#
# class MessageAttachment:
# attachment_value = None
# attachment_type = None
#
# def __init__(self, type, value):
# self.attachment_type = type
# self.attachment_value = value
#
# mid = None # ID of message
# flag = None # message flags (See VK Long pool docs)
# pid = None # peer id (Sender id)
# ts = None # timestamp
# sub = None # subject of message (if private dialog - " ... ", if chat - chat title)
# body = None # test of message
# extra = None # extra fields (forwarded messages, etc)
# attachments = None
#
# # get specific message flag (See VK Long pool docs)
# def msgFlag(self, i, f):
# return (f & i) > 0
#
# # check is message not incoming
# def is_out(self):
# return self.msgFlag(self.flag, 2)
#
# def is_loopback(self, account=None):
# if account is None:
# account = bot_header.CURRENT_ACCOUNT
# return self.pid == account.user_id
#
# # check is message sent from chat
# def is_chat(self):
# return self.pid >= 2000000000
#
# # init
# def __init__(self, mid=None, flag=None, pid=None, ts=None, sub=None, body=None, extra=None):
# self.mid = mid
# self.flag = flag
# self.pid = pid
# self.ts = ts
# self.sub = sub
# self.body = body
# self.extra = extra
# if extra is not None:
# self.attachments = self.parse_attachments()
#
# # get message from long pool response
# def from_long_pool(self, resp):
# mid = resp[1]
# flag = resp[2]
# pid = resp[3]
# ts = resp[4]
# sub = resp[5]
# body = resp[6]
# extra = resp[7]
# return Message(mid=mid, flag=flag, pid=pid, ts=ts, sub=sub, body=body, extra=extra)
#
# def parse_attachments(self):
# # print(self.extra)
# # initialize empty list
# result = []
#
# # checking for attachments
# if not "attach1_type" in self.extra:
# return result
#
# # if message has attachs, start parsing
# # parse attachment
# i = 1
# print("id: %s" % i)
# # get attach by number
# while "attach%s_type" % i in self.extra:
# attach_type = self.extra["attach%s_type" % str(i)]
# attach_val = self.extra["attach%s" % str(i)]
# if attach_type == "doc":
# if "attach%s_kind" % str(i):
# if self.extra["attach%s_kind" % str(i)] == "audiomsg":
# attach_type = "amessage"
# print("Got id %s with data %s" % (attach_type, attach_val))
# result.append(Message.MessageAttachment(attach_type, attach_val))
# i+=1
# return result
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
. Output only the next line. | sys.path.insert(0,parentdir) |
Here is a snippet: <|code_start|> # getting api instance
api = get_api(lpt=lp_thread_ins)
# looking at config file
make_typing = config_file.has("typing")
# checking typing filed in config file
if make_typing:
read_message_before_typing = config_file.has("read before typing")
###
# sets speed of typing (in seconds)
# from time
typing_speedf = config_file.get_field("typing speed from")
# to time
typing_speedt = config_file.get_field("typing speed to")
# e.g: from 1 sec to 5 sec
###
# don;t use random. use only typing_speedt
static_typing = config_file.has("typing static")
# getting random typing speed (by default)
typing_time = random.randint(1, 5)
# checking that typing_speedf and typing_speedt is number
if str.isnumeric(typing_speedf) and str.isnumeric(typing_speedt):
# checking static typing is enabled
if not static_typing:
# get random typing time
typing_time = random.randint(int(typing_speedf), int(typing_speedt))
else:
# get time only from typing_speedt
typing_time = int(typing_speedt)
<|code_end|>
. Write the next line using the current file imports:
import inspect
import os
import random
import sys
import mpm_manager
import bot_header
from time import sleep
from utils import config_file
from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi
and context from other files:
# Path: utils/config_file.py
# CONF_FILE = 'config/hcbpy.conf'
# def touch(fname, times=None):
# def __init__(self, key, val, comment):
# def get_all_data(filename=CONF_FILE):
# def get_field(field_name, filename=CONF_FILE):
# def init_field(key, val="none", filename=CONF_FILE):
# def has(field_name, filename=CONF_FILE):
# def get_lines(filename):
# def get_comment(field_name, filename=CONF_FILE):
# def set_field(field_name, value, filename=CONF_FILE):
# class ConfigEntry:
#
# Path: vk_api/api.py
# def get_api(lpt = None, account=None):
# if lpt == None and account == None:
# raise AttributeError("longpool thread or account is required")
# if lpt is not None:
# account = lpt.account
#
# return vk.API(vk.Session(access_token=account.token))
#
# Path: vk_api/api.py
# class Message:
#
# class MessageAttachment:
# attachment_value = None
# attachment_type = None
#
# def __init__(self, type, value):
# self.attachment_type = type
# self.attachment_value = value
#
# mid = None # ID of message
# flag = None # message flags (See VK Long pool docs)
# pid = None # peer id (Sender id)
# ts = None # timestamp
# sub = None # subject of message (if private dialog - " ... ", if chat - chat title)
# body = None # test of message
# extra = None # extra fields (forwarded messages, etc)
# attachments = None
#
# # get specific message flag (See VK Long pool docs)
# def msgFlag(self, i, f):
# return (f & i) > 0
#
# # check is message not incoming
# def is_out(self):
# return self.msgFlag(self.flag, 2)
#
# def is_loopback(self, account=None):
# if account is None:
# account = bot_header.CURRENT_ACCOUNT
# return self.pid == account.user_id
#
# # check is message sent from chat
# def is_chat(self):
# return self.pid >= 2000000000
#
# # init
# def __init__(self, mid=None, flag=None, pid=None, ts=None, sub=None, body=None, extra=None):
# self.mid = mid
# self.flag = flag
# self.pid = pid
# self.ts = ts
# self.sub = sub
# self.body = body
# self.extra = extra
# if extra is not None:
# self.attachments = self.parse_attachments()
#
# # get message from long pool response
# def from_long_pool(self, resp):
# mid = resp[1]
# flag = resp[2]
# pid = resp[3]
# ts = resp[4]
# sub = resp[5]
# body = resp[6]
# extra = resp[7]
# return Message(mid=mid, flag=flag, pid=pid, ts=ts, sub=sub, body=body, extra=extra)
#
# def parse_attachments(self):
# # print(self.extra)
# # initialize empty list
# result = []
#
# # checking for attachments
# if not "attach1_type" in self.extra:
# return result
#
# # if message has attachs, start parsing
# # parse attachment
# i = 1
# print("id: %s" % i)
# # get attach by number
# while "attach%s_type" % i in self.extra:
# attach_type = self.extra["attach%s_type" % str(i)]
# attach_val = self.extra["attach%s" % str(i)]
# if attach_type == "doc":
# if "attach%s_kind" % str(i):
# if self.extra["attach%s_kind" % str(i)] == "audiomsg":
# attach_type = "amessage"
# print("Got id %s with data %s" % (attach_type, attach_val))
# result.append(Message.MessageAttachment(attach_type, attach_val))
# i+=1
# return result
#
# Path: vk_api/api.py
# def api_request(api, method, params=''):
# ret = dict(api=api, ret = None)
# if params:
# a = "ret = api.%s(v='5.62', %s)" % (method, params)
# else:
# a = "ret = api.%s(v='5.62')" % (method)
#
# exec(a, ret)
#
# if 'error' in str(ret['ret']):
# bot_header.API_REQUESTS += 1
# else:
# bot_header.FAILED_API_REQUESTS += 1
#
#
# return ret['ret']
#
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
, which may include functions, classes, or code. Output only the next line. | if read_message_before_typing: |
Given snippet: <|code_start|>#-------------------------------------------------------------------------------
# Name: VK_API_CONSOLE
#
# Author: hydrogen-nt
#
# Created: 13.01.2018
# Copyright: (c) hydrogen-nt 2018
#
# implements using VK api on console
# by typing "vapi [method] [params (x='y',)]"
#-------------------------------------------------------------------------------
def print_usage():
print("vapi [method] [params]")
#main method
def main(c):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from sys import argv
from vk_api.api import vapi
and context:
# Path: vk_api/api.py
# def vapi(method, params=''):
# return api_request(get_api(account=bot_header.CURRENT_ACCOUNT), method, params)
which might include code, classes, or functions. Output only the next line. | c = c.replace("vapi", "").strip() |
Given the following code snippet before the placeholder: <|code_start|> def print(self, text):
print("[::AEXEC] %s" % text)
def v(self, text):
bot_header.v("[::AEXEC] %s" % text)
def update_rules_list(self, q=False):
if not q:
self.print("Updating rules list...")
self.aexec_rules = self.mgr.get_all_rules()
def __init__(self, interval='1s', exec_py_code=False):
super().__init__()
self.interval = time_utils.parse_time(interval)
self.exec_py_code = exec_py_code
def run(self):
self.v("run()")
self.print("Getting rules...")
while self.enabled:
for rule in self.aexec_rules:
rule = AutoexecRule.from_json(rule)
if rule.ticks == None:
rule.ticks = 0
if rule.time_when != None and rule.ticks >= rule.time_when:
self.exec_rule(rule)
<|code_end|>
, predict the next line using imports from the current file:
from threading import Thread
from time import sleep
from utils import time_utils
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from autoexec.autoexec import AutoexecRule
from autoexec.autoexec_action_type import AutoexecActionType
from console import bot_console
import bot_header
and context including class names, function names, and sometimes code from other files:
# Path: utils/time_utils.py
# def parse_time(time):
#
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
. Output only the next line. | self.mgr.remove(rule.id) |
Predict the next line after this snippet: <|code_start|>
class AutoexecThread(Thread):
aexec_rules = []
enabled = True
interval = 1
exec_py_code = False
mgr = AutoexecRulesManager()
def stop(self):
self.print("Stopping AutoExec thread...")
self.enabled = False
bot_header.AUTO_EXEC_THREAD_INSTANCE = None
def print(self, text):
<|code_end|>
using the current file's imports:
from threading import Thread
from time import sleep
from utils import time_utils
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from autoexec.autoexec import AutoexecRule
from autoexec.autoexec_action_type import AutoexecActionType
from console import bot_console
import bot_header
and any relevant context from other files:
# Path: utils/time_utils.py
# def parse_time(time):
#
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
. Output only the next line. | print("[::AEXEC] %s" % text) |
Given the code snippet: <|code_start|>
class AutoexecThread(Thread):
aexec_rules = []
enabled = True
interval = 1
exec_py_code = False
mgr = AutoexecRulesManager()
def stop(self):
self.print("Stopping AutoExec thread...")
self.enabled = False
bot_header.AUTO_EXEC_THREAD_INSTANCE = None
<|code_end|>
, generate the next line using the imports in this file:
from threading import Thread
from time import sleep
from utils import time_utils
from autoexec.autoexec_rules_manager import AutoexecRulesManager
from autoexec.autoexec import AutoexecRule
from autoexec.autoexec_action_type import AutoexecActionType
from console import bot_console
import bot_header
and context (functions, classes, or occasionally code) from other files:
# Path: utils/time_utils.py
# def parse_time(time):
#
# Path: autoexec/autoexec_rules_manager.py
# class AutoexecRulesManager:
#
# def get_all_rules(self):
# result = []
#
# f = utils.config_file.get_field("autoexec")
# if not f:
# return result
#
# json_arr = json.loads(f)
#
# for rule in json_arr:
# result.append(autoexec.autoexec.AutoexecRule.from_json(rule).__dict__)
#
# return result
#
# def add_rule(self, rule):
# if self.get_by_id(rule.id) is not None:
# self.replace(rule.id, rule)
# return 0
#
# if type(rule) is not autoexec.autoexec.AutoexecRule:
# raise TypeError("value must be instance if AutoexecRule")
#
# rules = self.get_all_rules()
# rules.append(rule.__dict__)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def get_by_id(self, id):
# rules = self.get_all_rules()
# for rule in rules:
# if rule['id'] == id:
# return rule
#
# def remove(self, id):
# rule = self.get_by_id(id)
# if rule is None:
# raise Exception("No such rule")
# rules = self.get_all_rules()
# rules.remove(rule)
# _json = json.dumps(rules)
# utils.config_file.set_field(AUTOEXEC, _json)
#
# def replace(self, id, rule):
# self.remove(id)
# self.add_rule(rule)
#
# Path: autoexec/autoexec.py
# class AutoexecRule:
# id = None
# ticks = None
# time_each = None
# time_when = None
# action = None
# action_value = None
#
# def from_json(d):
# s = AutoexecRule(force=True)
# s.__dict__.update(d)
# return s
#
# def __init__(self, time_each=None, time_when=None, action_type=None, force=False):
# if not force:
#
# if not time_each:
# time_each = None
#
# if not time_when:
# time_when = None
#
# print("%s%s" % (time_each, time_when))
#
# if time_each == None and time_when == None:
# raise AttributeError("You must specify time when it action will be go")
#
# if time_each != None and time_when != None:
# raise AttributeError("You can't specify each and when parameters in the same time")
#
# if time_when is not None:
# self.time_when = time_utils.parse_time(time_when)
#
# if time_each is not None:
# self.time_each = time_utils.parse_time(time_each)
#
# pass
#
# Path: autoexec/autoexec_action_type.py
# class AutoexecActionType():
# ACTION_HC_CONSOLE = 1
# ACTION_MESSAGE_SEND = 2
. Output only the next line. | def print(self, text): |
Given the following code snippet before the placeholder: <|code_start|> # INITIALIZE VARIABLES
def __init__(self, username, password, authtype=VKApp.WIN, prevs='audio,wall,friends,messages,status'):
username = username.strip()
password = password.strip()
if not username or not password:
raise AttributeError("Invalid username or password argument (u:'%s', p:'%s')" % (username, password))
self.user_data = UserData()
self.user_data.username = username
self.user_data.password = password
self.auth_type = authtype
self.prevs = prevs
# SET FORCE SMS FLAG
def fsms(self, fsms):
if fsms:
self.force_sms = '1'
else:
self.force_sms = '0'
# VK AUTH EXCEPTION e.g. invalid client or captcha needed
class AuthException(Exception):
error = ''
error_description = ''
def __init__(self, error, error_description):
self.error = error
self.error_description = error_description
# format basic url (__url__)
<|code_end|>
, predict the next line using imports from the current file:
from bot_header import *
from vk_auth.vk_app import VKApp
import vk_auth.vk_2fa_type
and context including class names, function names, and sometimes code from other files:
# Path: vk_auth/vk_app.py
# class VKApp(Enum):
# # subclass describes vk_auth app
# class app:
# cid = ''
# sec = ''
#
# def __init__(self, cid, sec):
# self.cid = cid
# self.sec = sec
#
# APPLE_IPHONE = app("3140623", "VeWdmVclDCtn6ihuP1nt")
# WIN = app("3697615", "AlVXZFMUqyrnABp8ncuU")
# ANDROID = app("2274003", "hHbZxrka2uZ6jB1inYsH")
. Output only the next line. | def __make_request__(self, sms=force_sms): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture()
def workspace():
workspace = Harness("repos/confl_dep")
workspace.initialize("repos/confl_dep?" + str(uuid.uuid4()))
<|code_end|>
, predict the next line using imports from the current file:
from .harness import Harness
import uuid
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | yield workspace |
Based on the snippet: <|code_start|> assert "dependencies" in result
dep_names = {d["attributes"]["name"] for d in result["dependencies"]}
assert dep_names == {
'pytest',
'not_in_sys_path',
'numpy',
'__main__',
'import_tree',
'recurse_class2',
'not_existing',
'psutil',
'rename1',
'local_module',
'objgraph',
'django',
'cpython',
'pylab',
'docopt',
'recurse_class1',
'psycopg2',
'not_existing_nested',
'pygments'
}
def test_absolute_import_definiton():
result = jedi_workspace.definition("/jedi/api/__init__.py", 28, 26)
symbol = {
'symbol': {
'package': {
<|code_end|>
, predict the immediate next line with the help of imports:
from .harness import Harness
import uuid
and context (classes, functions, sometimes code) from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | 'name': 'jedi' |
Given the code snippet: <|code_start|> 'package': {
'name': 'flask'
},
'position': {
'character': 4,
'line': 34
}
}
}
assert symbol in result
def test_cross_module_definition():
result = flask_workspace.definition("/flask/app.py", 220, 12)
symbol = {
'location': {
'range': {
'end': {
'character': 43,
'line': 26
},
'start': {
'character': 28,
'line': 26
}
},
'uri': 'file:///flask/app.py'
},
'symbol': {
'container': 'flask.app',
<|code_end|>
, generate the next line using the imports in this file:
from .harness import Harness
import uuid
and context (functions, classes, or occasionally code) from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | 'file': 'app.py', |
Given the code snippet: <|code_start|>
@pytest.fixture()
def workspace():
workspace = Harness("repos/dep_pkg_module_same_name")
workspace.initialize("repos/dep_pkg_module_same_name" + str(uuid.uuid4()))
yield workspace
<|code_end|>
, generate the next line using the imports in this file:
from .harness import Harness
import uuid
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | workspace.exit() |
Predict the next line after this snippet: <|code_start|> 'line': 138,
'character': 6
}
},
'location': {
'uri': 'file:///graphql/type/definition.py',
'range': {
'start': {
'line': 138,
'character': 6
},
'end': {
'line': 138,
'character': 23
}
}
}
},
{
'symbol': {
'package': {
'name': 'graphql'
},
'name': 'GraphQLObjectType',
'container': 'graphql.type',
'kind': 'class',
'file': '__init__.py',
'position': {
'line': 3,
'character': 4
<|code_end|>
using the current file's imports:
from .harness import Harness
import uuid
import pytest
and any relevant context from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | } |
Continue the code snippet: <|code_start|> },
'location': None
}
# from the import statement at the top of the file
assignment = {
'symbol': {
'package': {
'name': 'fizzbuzz_service'
},
'name': 'Enum',
'container': 'fizzbuzz_service.string_deciders.number_decision',
'kind': 'class',
'file': 'number_decision.py',
'position': {
'line': 0,
'character': 17
},
},
'location': {
'uri': 'file:///fizzbuzz_service/string_deciders/number_decision.py',
'range': {
'start': {
'line': 0,
'character': 17
},
'end': {
'line': 0,
'character': 21
}
<|code_end|>
. Use current file imports:
from .harness import Harness
and context (classes, functions, or code) from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | } |
Using the snippet: <|code_start|>
tensorflow_models_workspace = Harness("repos/tensorflow-models")
tensorflow_models_workspace.initialize(
"git://github.com/tensorflow/models?" + str(uuid.uuid4()))
def test_namespace_package_definition():
result = tensorflow_models_workspace.definition(
"/inception/inception/flowers_eval.py", 23, 22)
symbol = {
'symbol': {
'package': {
'name': 'inception_eval'
},
'name': 'inception_eval',
'container': 'inception_eval',
'kind': 'module',
'file': 'inception_eval.py',
'position': {
'line': 0,
'character': 0
}
},
'location': {
'uri': 'file:///inception/inception/inception_eval.py',
'range': {
'start': {
'line': 0,
'character': 0
<|code_end|>
, determine the next line of code. You have imports:
from .harness import Harness
import uuid
and context (class names, function names, or code) available:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | }, |
Given snippet: <|code_start|>
if __name__ == '__main__':
looper = number_looper.NumberLooper(1, 16)
for number_string in looper.get_number_strings():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .loopers import number_looper
and context:
# Path: test/repos/fizzbuzz_service/fizzbuzz_service/loopers/number_looper.py
# class NumberLooper(object):
# def __init__(self, start, end):
# def get_number_strings(self):
which might include code, classes, or functions. Output only the next line. | print(number_string) |
Next line prediction: <|code_start|>
@pytest.fixture(params=[
# tuples of the repo for the test, along
# with the expected doc_string for the hover
# in that repo
("repos/dep_versioning_fixed", "this is version 0.1"),
("repos/dep_versioning_between", "this is version 0.4"),
("repos/dep_versioning_between_multiple", "this is version 0.4"),
("repos/dep_versioning_none", "this is version 0.6")
])
def test_data(request):
repo_path, expected_doc_string = request.param
workspace = Harness(repo_path)
workspace.initialize(repo_path + str(uuid.uuid4()))
yield (workspace, expected_doc_string)
workspace.exit()
class TestDependencyVersioning:
def test_dep_download_specified_version(self, test_data):
workspace, expected_doc_string = test_data
<|code_end|>
. Use current file imports:
(from .harness import Harness
import uuid
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | uri = "file:///test.py" |
Here is a snippet: <|code_start|>
class Module:
def __init__(self, name, path, is_package=False):
self.name = name
self.path = path
self.is_package = is_package
def __repr__(self):
return "PythonModule({}, {})".format(self.name, self.path)
class DummyFile:
<|code_end|>
. Write the next line using the current file imports:
from os import path as filepath
from typing import List
from .fs import RemoteFileSystem, TestFileSystem
import os
import jedi
import jedi._compatibility
import opentracing
and context from other files:
# Path: langserver/fs.py
# class RemoteFileSystem(FileSystem):
# def __init__(self, conn: JSONRPC2Connection):
# self.conn = conn
#
# def open(self, path, parent_span=None):
# if parent_span is None:
# resp = self.conn.send_request("textDocument/xcontent", {
# "textDocument": {
# "uri": "file://" + path
# }
# })
# if "error" in resp:
# raise FileException(resp["error"])
# return resp["result"]["text"]
#
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.open") as open_span:
# open_span.set_tag("path", path)
# resp = self.conn.send_request("textDocument/xcontent", {
# "textDocument": {
# "uri": "file://" + path
# }
# })
# if "error" in resp:
# raise FileException(resp["error"])
# return resp["result"]["text"]
#
# def listdir(self, path, parent_span=None):
# if parent_span is None:
# return self._listdir(path)
#
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.listdir") as list_span:
# list_span.set_tag("path", path)
# # TODO(keegan) Use workspace/xfiles + cache
# return self._listdir(path)
#
# def _listdir(self, path):
# resp = self.conn.send_request("fs/readDir", path)
# if resp.get("error") is not None:
# raise FileException(resp["error"])
# entries = []
# for e in resp["result"]:
# entries.append(e["name"])
# return entries
#
# def walk(self, path):
# resp = self.conn.send_request("workspace/xfiles",
# {"base": "file://" + path})
# if "error" in resp:
# raise FileException(resp["error"])
# for doc in resp["result"]:
# uri = doc["uri"]
# if uri.startswith("file://"):
# yield uri[7:]
# else:
# yield uri
#
# def batch_open(self, paths, parent_span):
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.batch_open"):
# # We need to read the iterator paths twice, so convert to list
# paths = list(paths)
# responses = self.conn.send_request_batch(("textDocument/xcontent",
# {
# "textDocument": {
# "uri":
# "file://" + path
# }
# }) for path in paths)
# for path, resp in zip(paths, responses):
# if "error" in resp:
# # Consume rest of generator to ensure resources are
# # shutdown
# for _ in responses:
# pass
# raise FileException(resp["error"])
# yield (path, resp["result"]["text"])
#
# class TestFileSystem(FileSystem):
# def __init__(self, local_root_path: str):
# self.root = os.path.abspath(local_root_path)
#
# def open(self, path: str, parent_span=None):
# if os.path.isabs(path):
# path = os.path.join(self.root, os.path.relpath(path, "/"))
# else:
# path = os.path.join(self.root, path)
# with open(path) as open_file:
# return open_file.read()
#
# def batch_open(self, paths, parent_span):
# for path in paths:
# yield (path, self.open(path))
#
# def listdir(self, path: str, parent_span=None):
# path = os.path.abspath(path)
# # need this check for namespace imports, for which we get a relative
# # path
# if not path.startswith(self.root):
# if path.startswith("/"):
# path = path[1:]
# path = os.path.join(self.root, path)
# return [os.path.join(path, p) for p in os.listdir(path)]
#
# def walk(self, top: str):
# yield from (os.path.join("/", p) for p in self._walk(top))
#
# def _walk(self, top: str):
# dir = self.listdir(top)
# files, dirs = [], []
# for e in dir:
# if os.path.isdir(e):
# dirs.append(os.path.relpath(e, self.root))
# else:
# files.append(os.path.relpath(e, self.root))
# yield from files
# for d in dirs:
# yield from self._walk(os.path.join(self.root, d))
, which may include functions, classes, or code. Output only the next line. | def __init__(self, contents): |
Predict the next line after this snippet: <|code_start|>
class Module:
def __init__(self, name, path, is_package=False):
self.name = name
self.path = path
self.is_package = is_package
def __repr__(self):
<|code_end|>
using the current file's imports:
from os import path as filepath
from typing import List
from .fs import RemoteFileSystem, TestFileSystem
import os
import jedi
import jedi._compatibility
import opentracing
and any relevant context from other files:
# Path: langserver/fs.py
# class RemoteFileSystem(FileSystem):
# def __init__(self, conn: JSONRPC2Connection):
# self.conn = conn
#
# def open(self, path, parent_span=None):
# if parent_span is None:
# resp = self.conn.send_request("textDocument/xcontent", {
# "textDocument": {
# "uri": "file://" + path
# }
# })
# if "error" in resp:
# raise FileException(resp["error"])
# return resp["result"]["text"]
#
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.open") as open_span:
# open_span.set_tag("path", path)
# resp = self.conn.send_request("textDocument/xcontent", {
# "textDocument": {
# "uri": "file://" + path
# }
# })
# if "error" in resp:
# raise FileException(resp["error"])
# return resp["result"]["text"]
#
# def listdir(self, path, parent_span=None):
# if parent_span is None:
# return self._listdir(path)
#
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.listdir") as list_span:
# list_span.set_tag("path", path)
# # TODO(keegan) Use workspace/xfiles + cache
# return self._listdir(path)
#
# def _listdir(self, path):
# resp = self.conn.send_request("fs/readDir", path)
# if resp.get("error") is not None:
# raise FileException(resp["error"])
# entries = []
# for e in resp["result"]:
# entries.append(e["name"])
# return entries
#
# def walk(self, path):
# resp = self.conn.send_request("workspace/xfiles",
# {"base": "file://" + path})
# if "error" in resp:
# raise FileException(resp["error"])
# for doc in resp["result"]:
# uri = doc["uri"]
# if uri.startswith("file://"):
# yield uri[7:]
# else:
# yield uri
#
# def batch_open(self, paths, parent_span):
# with opentracing.start_child_span(
# parent_span, "RemoteFileSystem.batch_open"):
# # We need to read the iterator paths twice, so convert to list
# paths = list(paths)
# responses = self.conn.send_request_batch(("textDocument/xcontent",
# {
# "textDocument": {
# "uri":
# "file://" + path
# }
# }) for path in paths)
# for path, resp in zip(paths, responses):
# if "error" in resp:
# # Consume rest of generator to ensure resources are
# # shutdown
# for _ in responses:
# pass
# raise FileException(resp["error"])
# yield (path, resp["result"]["text"])
#
# class TestFileSystem(FileSystem):
# def __init__(self, local_root_path: str):
# self.root = os.path.abspath(local_root_path)
#
# def open(self, path: str, parent_span=None):
# if os.path.isabs(path):
# path = os.path.join(self.root, os.path.relpath(path, "/"))
# else:
# path = os.path.join(self.root, path)
# with open(path) as open_file:
# return open_file.read()
#
# def batch_open(self, paths, parent_span):
# for path in paths:
# yield (path, self.open(path))
#
# def listdir(self, path: str, parent_span=None):
# path = os.path.abspath(path)
# # need this check for namespace imports, for which we get a relative
# # path
# if not path.startswith(self.root):
# if path.startswith("/"):
# path = path[1:]
# path = os.path.join(self.root, path)
# return [os.path.join(path, p) for p in os.listdir(path)]
#
# def walk(self, top: str):
# yield from (os.path.join("/", p) for p in self._walk(top))
#
# def _walk(self, top: str):
# dir = self.listdir(top)
# files, dirs = [], []
# for e in dir:
# if os.path.isdir(e):
# dirs.append(os.path.relpath(e, self.root))
# else:
# files.append(os.path.relpath(e, self.root))
# yield from files
# for d in dirs:
# yield from self._walk(os.path.join(self.root, d))
. Output only the next line. | return "PythonModule({}, {})".format(self.name, self.path) |
Given the code snippet: <|code_start|>
workspace = Harness("repos/global-variables")
workspace.initialize("")
def test_name_definition():
# The __name__ global variable should resolve to a symbol without
# a corresponding location
uri = "file:///name_global.py"
line, col = 0, 4
result = workspace.definition(uri, line, col)
assert result == [
{
'symbol':
{
'package': {
'name': 'name_global'
},
'name': '__name__',
<|code_end|>
, generate the next line using the imports in this file:
from .harness import Harness
and context (functions, classes, or occasionally code) from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | 'container': 'name_global', |
Given the code snippet: <|code_start|> for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
yield from self.visit(item, container)
elif isinstance(value, ast.AST):
yield from self.visit(value, container)
def targeted_symbol(symbol_descriptor, fs, root_path, parent_span):
if "path" in symbol_descriptor:
# exact path
file_filter = "/" + symbol_descriptor["path"]
else:
# just the filename
file_filter = "/" + symbol_descriptor["file"]
paths = (path for path in fs.walk(root_path) if path.endswith(file_filter))
symbols = []
for path in paths:
source = fs.open(path, parent_span)
try:
tree = ast.parse(source, path)
except SyntaxError as e:
log.error("Error parsing Python file %s:%s -- %s: %s",
path, e.lineno, e.msg, e.text)
continue
visitor = TargetedSymbolVisitor(
symbol_descriptor["name"], symbol_descriptor["kind"], path)
for sym in visitor.visit(tree):
sym.file = path
<|code_end|>
, generate the next line using the imports in this file:
from .symbols import SymbolKind, Symbol
import ast
import os
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: langserver/symbols.py
# class SymbolKind(Enum):
# """SymbolKind corresponds to the SymbolKind enum type found in the LSP
# spec."""
# File = 1
# Module = 2
# Namespace = 3
# Package = 4
# Class = 5
# Method = 6
# Property = 7
# Field = 8
# Constructor = 9
# Enum = 10
# Interface = 11
# Function = 12
# Variable = 13
# Constant = 14
# String = 15
# Number = 16
# Boolean = 17
# Array = 18
#
# class Symbol:
# def __init__(self, name, kind, line, col, container=None, file=None):
# self.name = name
# self.kind = kind
# self.line = line
# self.col = col
# self.container = container
# self.file = file
#
# def score(self, query: str) -> int:
# """Score a symbol based on how well it matches a query.
#
# Useful for sorting.
# """
# score = 0
# if self.kind == SymbolKind.Class:
# score += 1
# if self.kind != SymbolKind.Variable:
# score += 1
# if self.container is None:
# score += 1
# if self.file and 'test' not in self.file:
# score += 5
# if query == "":
# return score
# min_score = score
# l_name, l_query = self.name.lower(), query.lower()
# if query == self.name:
# score += 10
# elif l_name == l_query:
# score += 8
# if self.name.startswith(query):
# score += 5
# elif l_name.startswith(l_query):
# score += 4
# if l_query in l_name:
# score += 2
# if self.container:
# if self.container.lower().startswith(l_query):
# score += 2
# if l_query == self.container.lower() + "." + l_name:
# score += 10
# if self.file and self.file.lower().startswith(l_query):
# score += 1
# if score <= min_score:
# score = -1
# return score
#
# def json_object(self):
# d = {
# "name": self.name,
# "kind": self.kind.value,
# "location": {
# "uri": "file://" + self.file,
# "range": {
# "start": {
# "line": self.line - 1,
# "character": self.col,
# },
# "end": {
# "line": self.line - 1,
# "character": self.col + len(self.name),
# }
# }
# },
# }
# if self.container is not None:
# d["containerName"] = self.container
# return d
. Output only the next line. | symbols.append(sym.json_object()) |
Here is a snippet: <|code_start|> SymbolKind.Variable,
node.lineno,
node.col_offset,
container=container
)
break
if n.asname and self.name == n.asname:
yield Symbol(
n.asname,
SymbolKind.Variable,
node.lineno,
node.col_offset,
container=container
)
break
def visit_Import(self, node, container):
for n in node.names:
if n.name and self.name in n.name.split("."):
yield Symbol(
n.name,
SymbolKind.Variable,
node.lineno,
node.col_offset,
container=container
)
if n.asname and self.name == n.asname:
yield Symbol(
n.asname,
SymbolKind.Variable,
<|code_end|>
. Write the next line using the current file imports:
from .symbols import SymbolKind, Symbol
import ast
import os
import logging
and context from other files:
# Path: langserver/symbols.py
# class SymbolKind(Enum):
# """SymbolKind corresponds to the SymbolKind enum type found in the LSP
# spec."""
# File = 1
# Module = 2
# Namespace = 3
# Package = 4
# Class = 5
# Method = 6
# Property = 7
# Field = 8
# Constructor = 9
# Enum = 10
# Interface = 11
# Function = 12
# Variable = 13
# Constant = 14
# String = 15
# Number = 16
# Boolean = 17
# Array = 18
#
# class Symbol:
# def __init__(self, name, kind, line, col, container=None, file=None):
# self.name = name
# self.kind = kind
# self.line = line
# self.col = col
# self.container = container
# self.file = file
#
# def score(self, query: str) -> int:
# """Score a symbol based on how well it matches a query.
#
# Useful for sorting.
# """
# score = 0
# if self.kind == SymbolKind.Class:
# score += 1
# if self.kind != SymbolKind.Variable:
# score += 1
# if self.container is None:
# score += 1
# if self.file and 'test' not in self.file:
# score += 5
# if query == "":
# return score
# min_score = score
# l_name, l_query = self.name.lower(), query.lower()
# if query == self.name:
# score += 10
# elif l_name == l_query:
# score += 8
# if self.name.startswith(query):
# score += 5
# elif l_name.startswith(l_query):
# score += 4
# if l_query in l_name:
# score += 2
# if self.container:
# if self.container.lower().startswith(l_query):
# score += 2
# if l_query == self.container.lower() + "." + l_name:
# score += 10
# if self.file and self.file.lower().startswith(l_query):
# score += 1
# if score <= min_score:
# score = -1
# return score
#
# def json_object(self):
# d = {
# "name": self.name,
# "kind": self.kind.value,
# "location": {
# "uri": "file://" + self.file,
# "range": {
# "start": {
# "line": self.line - 1,
# "character": self.col,
# },
# "end": {
# "line": self.line - 1,
# "character": self.col + len(self.name),
# }
# }
# },
# }
# if self.container is not None:
# d["containerName"] = self.container
# return d
, which may include functions, classes, or code. Output only the next line. | node.lineno, |
Next line prediction: <|code_start|> 'uri': 'file:///thefuck/argument_parser.py',
'range': {
'start': {
'line': 36,
'character': 21
},
'end': {
'line': 36,
'character': 33
}
}
},
{
'uri': 'file:///thefuck/argument_parser.py',
'range': {
'start': {
'line': 40,
'character': 21
},
'end': {
'line': 40,
'character': 33
}
}
},
{
'uri': 'file:///thefuck/argument_parser.py',
'range': {
'start': {
'line': 48,
<|code_end|>
. Use current file imports:
(from .harness import Harness
import uuid)
and context including class names, function names, or small code snippets from other files:
# Path: test/harness.py
# class Harness:
#
# def __init__(self, local_repo_path: str):
# self.langserver = langserver.LangServer(conn=None)
# self.local_repo_path = local_repo_path
# self.langserver.fs = fs.TestFileSystem(local_repo_path)
# self.id = 0
#
# def next_id(self):
# self.id = self.id + 1
# return self.id
#
# def request(self, method: str, params):
# return {
# "jsonrpc": "2.0",
# "id": self.next_id(),
# "method": method,
# "params": params,
# "span": opentracing.tracer.start_span()
# }
#
# @staticmethod
# def text_document_position_params(file: str, line: int, character: int):
# return {
# "textDocument": {
# "uri": file
# },
# "position": {
# "line": line,
# "character": character
# }
# }
#
# def initialize(self, original_root_path: str):
# params = {
# "rootPath": self.local_repo_path,
# "originalRootPath": original_root_path
# }
# request = self.request("initialize", params)
# return self.langserver.test_initialize(
# request, fs.TestFileSystem(self.local_repo_path))
#
# def exit(self):
# self.langserver.serve_exit({})
#
# def x_packages(self):
# request = self.request("workspace/xpackages", {})
# return self.langserver.serve_x_packages(request)
#
# def hover(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/hover", params)
# return self.langserver.serve_hover(request)
#
# def definition(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/definition", params)
# return self.langserver.serve_x_definition(request)
#
# def references(self, file: str, line: int, character: int):
# params = self.text_document_position_params(file, line, character)
# request = self.request("textDocument/references", params)
# return self.langserver.serve_references(request)
#
# def x_references(self, container: str, name: str):
# symbol = {"container": container, "name": name}
# params = {"query": symbol}
# request = self.request("workspace/xreferences", params)
# return self.langserver.serve_x_references(request)
. Output only the next line. | 'character': 14 |
Given snippet: <|code_start|>
class DeleteView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.index')
def post(self, name):
if not may(DELETE):
raise Forbidden()
try:
with current_app.storage.open(name) as item:
if not item.meta[COMPLETE] and not may(ADMIN):
error = 'Upload incomplete. Try again later.'
self.error(item, error)
if item.meta[LOCKED] and not may(ADMIN):
raise Forbidden()
current_app.storage.remove(name)
except OSError as e:
if e.errno == errno.ENOENT:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import errno
from flask import current_app, render_template
from flask.views import MethodView
from werkzeug.exceptions import NotFound, Forbidden
from ..constants import COMPLETE, FILENAME, LOCKED
from ..utils.http import redirect_next_referrer
from ..utils.permissions import ADMIN, DELETE, may
and context:
# Path: src/bepasty/constants.py
# COMPLETE = 'complete'
#
# FILENAME = 'filename'
#
# LOCKED = 'locked'
#
# Path: src/bepasty/utils/http.py
# def redirect_next_referrer(endpoint, **values):
# return redirect(_redirect_target_url(request.form, True, endpoint, **values))
#
# Path: src/bepasty/utils/permissions.py
# ADMIN = 'admin'
#
# DELETE = 'delete'
#
# def may(permission):
# """
# check whether the current user has the permission <permission>
# """
# return permission in flaskg.permissions
which might include code, classes, or functions. Output only the next line. | raise NotFound() |
Here is a snippet: <|code_start|>
class DeleteView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.index')
def post(self, name):
if not may(DELETE):
raise Forbidden()
try:
with current_app.storage.open(name) as item:
if not item.meta[COMPLETE] and not may(ADMIN):
error = 'Upload incomplete. Try again later.'
self.error(item, error)
if item.meta[LOCKED] and not may(ADMIN):
raise Forbidden()
current_app.storage.remove(name)
except OSError as e:
<|code_end|>
. Write the next line using the current file imports:
import errno
from flask import current_app, render_template
from flask.views import MethodView
from werkzeug.exceptions import NotFound, Forbidden
from ..constants import COMPLETE, FILENAME, LOCKED
from ..utils.http import redirect_next_referrer
from ..utils.permissions import ADMIN, DELETE, may
and context from other files:
# Path: src/bepasty/constants.py
# COMPLETE = 'complete'
#
# FILENAME = 'filename'
#
# LOCKED = 'locked'
#
# Path: src/bepasty/utils/http.py
# def redirect_next_referrer(endpoint, **values):
# return redirect(_redirect_target_url(request.form, True, endpoint, **values))
#
# Path: src/bepasty/utils/permissions.py
# ADMIN = 'admin'
#
# DELETE = 'delete'
#
# def may(permission):
# """
# check whether the current user has the permission <permission>
# """
# return permission in flaskg.permissions
, which may include functions, classes, or code. Output only the next line. | if e.errno == errno.ENOENT: |
Based on the snippet: <|code_start|>
class DeleteView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.index')
def post(self, name):
if not may(DELETE):
<|code_end|>
, predict the immediate next line with the help of imports:
import errno
from flask import current_app, render_template
from flask.views import MethodView
from werkzeug.exceptions import NotFound, Forbidden
from ..constants import COMPLETE, FILENAME, LOCKED
from ..utils.http import redirect_next_referrer
from ..utils.permissions import ADMIN, DELETE, may
and context (classes, functions, sometimes code) from other files:
# Path: src/bepasty/constants.py
# COMPLETE = 'complete'
#
# FILENAME = 'filename'
#
# LOCKED = 'locked'
#
# Path: src/bepasty/utils/http.py
# def redirect_next_referrer(endpoint, **values):
# return redirect(_redirect_target_url(request.form, True, endpoint, **values))
#
# Path: src/bepasty/utils/permissions.py
# ADMIN = 'admin'
#
# DELETE = 'delete'
#
# def may(permission):
# """
# check whether the current user has the permission <permission>
# """
# return permission in flaskg.permissions
. Output only the next line. | raise Forbidden() |
Next line prediction: <|code_start|>
class DeleteView(MethodView):
def error(self, item, error):
return render_template('error.html', heading=item.meta[FILENAME], body=error), 409
def response(self, name):
return redirect_next_referrer('bepasty.index')
def post(self, name):
if not may(DELETE):
raise Forbidden()
try:
with current_app.storage.open(name) as item:
if not item.meta[COMPLETE] and not may(ADMIN):
error = 'Upload incomplete. Try again later.'
self.error(item, error)
if item.meta[LOCKED] and not may(ADMIN):
<|code_end|>
. Use current file imports:
(import errno
from flask import current_app, render_template
from flask.views import MethodView
from werkzeug.exceptions import NotFound, Forbidden
from ..constants import COMPLETE, FILENAME, LOCKED
from ..utils.http import redirect_next_referrer
from ..utils.permissions import ADMIN, DELETE, may)
and context including class names, function names, or small code snippets from other files:
# Path: src/bepasty/constants.py
# COMPLETE = 'complete'
#
# FILENAME = 'filename'
#
# LOCKED = 'locked'
#
# Path: src/bepasty/utils/http.py
# def redirect_next_referrer(endpoint, **values):
# return redirect(_redirect_target_url(request.form, True, endpoint, **values))
#
# Path: src/bepasty/utils/permissions.py
# ADMIN = 'admin'
#
# DELETE = 'delete'
#
# def may(permission):
# """
# check whether the current user has the permission <permission>
# """
# return permission in flaskg.permissions
. Output only the next line. | raise Forbidden() |
Predict the next line for this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
<|code_end|>
with the help of current file imports:
import re
import time
import mimetypes
import magic as magic_module
from werkzeug.exceptions import BadRequest, RequestEntityTooLarge
from flask import current_app
from ..constants import (
COMPLETE,
FILENAME,
FOREVER,
HASH,
LOCKED,
SIZE,
TIMESTAMP_DOWNLOAD,
TIMESTAMP_MAX_LIFE,
TIMESTAMP_UPLOAD,
TYPE,
TYPE_HINT,
internal_meta,
)
from .name import ItemName
from .decorators import threaded
from .hashing import compute_hash, hash_new
and context from other files:
# Path: src/bepasty/constants.py
# FILENAME = 'filename'
# TYPE = 'type'
# TYPE_HINT = 'type-hint'
# LOCKED = 'locked'
# SIZE = 'size'
# COMPLETE = 'complete'
# HASH = 'hash'
# TIMESTAMP_UPLOAD = 'timestamp-upload'
# TIMESTAMP_DOWNLOAD = 'timestamp-download'
# TIMESTAMP_MAX_LIFE = 'timestamp-max-life'
# ID = 'id' # storage name
# FOREVER = -1
# TRANSACTION_ID = 'Transaction-ID' # keep in sync with bepasty-cli
#
# Path: src/bepasty/utils/name.py
# class ItemName(str):
# def __new__(cls, uid):
# return str(uid)
#
# @classmethod
# def create(cls, storage, length=ID_LENGTH, max_length=2 * ID_LENGTH, max_tries=10):
# """
# create a unique item name in storage, wanted name length is <length>.
#
# we try at most <max_tries> times to find a unique name of a specific length -
# if we do not succeed, we increase name length and try again.
# if we can't find a unique name even for longer lengths up to max_length,
# we'll raise RuntimeError.
# """
# name = None # avoid false alarm about reference before assignment
# while length <= max_length:
# tries = 0
# while tries < max_tries:
# name = make_id(length)
# if name not in storage:
# break
# tries += 1
# if tries < max_tries:
# # we found a name, break out of outer while also
# break
# length += 1
# if length > max_length:
# raise RuntimeError("no unique names available")
# return cls(name)
#
# Path: src/bepasty/utils/decorators.py
# def threaded(func):
# """
# decorator to run a function asynchronously (in a thread)
#
# be careful: do not access flask threadlocals in f!
# """
# def wrapper(*args, **kwargs):
# t = Thread(target=func, args=args, kwargs=kwargs)
# t.start()
# return wrapper
#
# Path: src/bepasty/utils/hashing.py
# SIZE = 1024 * 1024
# def compute_hash(data, size):
, which may contain function names, class names, or code. Output only the next line. | except ImportError: |
Predict the next line for this snippet: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames. other than that, there is no specific reason we could not
# also take more (or less).
MAX_FILENAME_LENGTH = 250
<|code_end|>
with the help of current file imports:
import re
import time
import mimetypes
import magic as magic_module
from werkzeug.exceptions import BadRequest, RequestEntityTooLarge
from flask import current_app
from ..constants import (
COMPLETE,
FILENAME,
FOREVER,
HASH,
LOCKED,
SIZE,
TIMESTAMP_DOWNLOAD,
TIMESTAMP_MAX_LIFE,
TIMESTAMP_UPLOAD,
TYPE,
TYPE_HINT,
internal_meta,
)
from .name import ItemName
from .decorators import threaded
from .hashing import compute_hash, hash_new
and context from other files:
# Path: src/bepasty/constants.py
# FILENAME = 'filename'
# TYPE = 'type'
# TYPE_HINT = 'type-hint'
# LOCKED = 'locked'
# SIZE = 'size'
# COMPLETE = 'complete'
# HASH = 'hash'
# TIMESTAMP_UPLOAD = 'timestamp-upload'
# TIMESTAMP_DOWNLOAD = 'timestamp-download'
# TIMESTAMP_MAX_LIFE = 'timestamp-max-life'
# ID = 'id' # storage name
# FOREVER = -1
# TRANSACTION_ID = 'Transaction-ID' # keep in sync with bepasty-cli
#
# Path: src/bepasty/utils/name.py
# class ItemName(str):
# def __new__(cls, uid):
# return str(uid)
#
# @classmethod
# def create(cls, storage, length=ID_LENGTH, max_length=2 * ID_LENGTH, max_tries=10):
# """
# create a unique item name in storage, wanted name length is <length>.
#
# we try at most <max_tries> times to find a unique name of a specific length -
# if we do not succeed, we increase name length and try again.
# if we can't find a unique name even for longer lengths up to max_length,
# we'll raise RuntimeError.
# """
# name = None # avoid false alarm about reference before assignment
# while length <= max_length:
# tries = 0
# while tries < max_tries:
# name = make_id(length)
# if name not in storage:
# break
# tries += 1
# if tries < max_tries:
# # we found a name, break out of outer while also
# break
# length += 1
# if length > max_length:
# raise RuntimeError("no unique names available")
# return cls(name)
#
# Path: src/bepasty/utils/decorators.py
# def threaded(func):
# """
# decorator to run a function asynchronously (in a thread)
#
# be careful: do not access flask threadlocals in f!
# """
# def wrapper(*args, **kwargs):
# t = Thread(target=func, args=args, kwargs=kwargs)
# t.start()
# return wrapper
#
# Path: src/bepasty/utils/hashing.py
# SIZE = 1024 * 1024
# def compute_hash(data, size):
, which may contain function names, class names, or code. Output only the next line. | class Upload: |
Next line prediction: <|code_start|>
try:
magic = magic_module.Magic(mime=True)
magic_bufsz = magic.getparam(magic_module.MAGIC_PARAM_BYTES_MAX)
except ImportError:
magic = None
magic_bufsz = None
# we limit to 250 characters as we do not want to accept arbitrarily long
# filenames. other than that, there is no specific reason we could not
# also take more (or less).
<|code_end|>
. Use current file imports:
(import re
import time
import mimetypes
import magic as magic_module
from werkzeug.exceptions import BadRequest, RequestEntityTooLarge
from flask import current_app
from ..constants import (
COMPLETE,
FILENAME,
FOREVER,
HASH,
LOCKED,
SIZE,
TIMESTAMP_DOWNLOAD,
TIMESTAMP_MAX_LIFE,
TIMESTAMP_UPLOAD,
TYPE,
TYPE_HINT,
internal_meta,
)
from .name import ItemName
from .decorators import threaded
from .hashing import compute_hash, hash_new)
and context including class names, function names, or small code snippets from other files:
# Path: src/bepasty/constants.py
# FILENAME = 'filename'
# TYPE = 'type'
# TYPE_HINT = 'type-hint'
# LOCKED = 'locked'
# SIZE = 'size'
# COMPLETE = 'complete'
# HASH = 'hash'
# TIMESTAMP_UPLOAD = 'timestamp-upload'
# TIMESTAMP_DOWNLOAD = 'timestamp-download'
# TIMESTAMP_MAX_LIFE = 'timestamp-max-life'
# ID = 'id' # storage name
# FOREVER = -1
# TRANSACTION_ID = 'Transaction-ID' # keep in sync with bepasty-cli
#
# Path: src/bepasty/utils/name.py
# class ItemName(str):
# def __new__(cls, uid):
# return str(uid)
#
# @classmethod
# def create(cls, storage, length=ID_LENGTH, max_length=2 * ID_LENGTH, max_tries=10):
# """
# create a unique item name in storage, wanted name length is <length>.
#
# we try at most <max_tries> times to find a unique name of a specific length -
# if we do not succeed, we increase name length and try again.
# if we can't find a unique name even for longer lengths up to max_length,
# we'll raise RuntimeError.
# """
# name = None # avoid false alarm about reference before assignment
# while length <= max_length:
# tries = 0
# while tries < max_tries:
# name = make_id(length)
# if name not in storage:
# break
# tries += 1
# if tries < max_tries:
# # we found a name, break out of outer while also
# break
# length += 1
# if length > max_length:
# raise RuntimeError("no unique names available")
# return cls(name)
#
# Path: src/bepasty/utils/decorators.py
# def threaded(func):
# """
# decorator to run a function asynchronously (in a thread)
#
# be careful: do not access flask threadlocals in f!
# """
# def wrapper(*args, **kwargs):
# t = Thread(target=func, args=args, kwargs=kwargs)
# t.start()
# return wrapper
#
# Path: src/bepasty/utils/hashing.py
# SIZE = 1024 * 1024
# def compute_hash(data, size):
. Output only the next line. | MAX_FILENAME_LENGTH = 250 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.