Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
Parameters
----------
x, y, z : float or array_like of floats
Cartesian coordinates, in metres.
"""
@u.quantity_input
def __init__(self, x: u.m, y: u.m, z: u.m):
self._x = x
self._y = y
self._z = z
@cl... | x, y, z = transform.geodetic_to_cartesian(lat, lon, height, ell=ell) |
Based on the snippet: <|code_start|> uncertainty=1e9,
reference='Jacobson, R. A., Antreasian, P. G., Bordi, J. J., '
'Criddle, K. E., Ionasescu,R., Jones, J. B., Mackenzie, R. A., '
'Pelletier, F. J., Owen Jr., W. M., Roth, D. C., and Stauch, J. R., '
'(2006), The gravity field of the Saturnian syste... | _gm_body = {'moon' : gm_moon, 'sun' : gm_sun, 'mars' : gm_mars, |
Next line prediction: <|code_start|>
def test_lplm_lplm_d_equality():
l_max = 2190
x_test = np.linspace(-1, 1, 10)
for x in x_test:
<|code_end|>
. Use current file imports:
(import numpy as np
from pygeoid.sharm import legendre)
and context including class names, function names, or small code snippets ... | lpmn_1 = legendre.lplm_d1(l_max, x)[0] |
Using the snippet: <|code_start|> 3 * cpsi * np.log(spsi2 + spsi2**2)
@u.quantity_input
def derivative_spherical_distance(self, spherical_distance):
r"""Evaluate Stokes's spherical kernel derivative.
The derivative of the Stokes function is the Vening-Meinesz function.
Para... | return VeningMeineszKernel().kernel( |
Using the snippet: <|code_start|>
def test_bounds():
bounds = (0, 100, 0, 100, 0, 100)
density = 2670
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import numpy as np
from pygeoid.simple import prism
and context (class names, function names, or code) available:
# Path: pyg... | p = prism.Prism(bounds, density=density) |
Given the code snippet: <|code_start|>
Will expand this function later to aid interactivity/updates.
"""
print("Training bot. CTRL-C to stop training.")
bot.train(dataset)
def start_chatting(bot):
"""Talk to bot.
Will re-add teacher mode soon. Old implementation in _decode.py."""
... | config = io_utils.parse_config(flags=FLAGS) |
Using the snippet: <|code_start|> @abstractproperty
def idx_to_word(self):
"""Return dictionary map from int -> str. """
pass
@abstractproperty
def name(self):
"""Returns name of the dataset as a string."""
pass
@abstractproperty
def max_seq_len(self):
""... | id_paths, vocab_path, vocab_size = io_utils.prepare_data( |
Given snippet: <|code_start|>"""ABC for datasets. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import logging
import numpy as np
import tensorflow as tf
f... | DEFAULT_PARAMS = DEFAULT_FULL_CONFIG['dataset_params'] |
Given the code snippet: <|code_start|> lengths: (dict) parsed context feature from protobuf file.
Supports keys in LENGTHS.
sequences: (dict) parsed feature_list from protobuf file.
Supports keys in SEQUENCES.
"""
with tf.variable_scope(name... | return tf.convert_to_tensor([[io_utils.GO_ID]]) |
Predict the next line for this snippet: <|code_start|> graph_def,
input_map=None,
return_elements=None,
op_dict=None,
producer_op_list=None
)
return graph
def unfreeze_bot(frozen_model_path):
"""Restores the frozen graph from file and grabs in... | config = io_utils.parse_config(pretrained_dir=frozen_model_path) |
Given the following code snippet before the placeholder: <|code_start|>
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
TEST_DATA_DIR = os.path.join(TEST_DIR, 'test_data')
TEST_CONFIG_PATH = os.path.join(TEST_DIR, 'test_config.yml')
logging.basicConfig(level=logging.INFO)
_flag_names = ["pretrained_dir",
... | config = io_utils.parse_config(flags=flags) |
Given snippet: <|code_start|>
def create_bot(flags=TEST_FLAGS, return_dataset=False):
"""Chatbot factory: Creates and returns a fresh bot. Nice for
testing specific methods quickly.
"""
# Wipe the graph and update config if needed.
tf.reset_default_graph()
config = io_utils.parse_config(flags=... | for key in DEFAULT_FULL_CONFIG: |
Given the code snippet: <|code_start|> # ================================================
flags = TEST_FLAGS
flags = flags._replace(model_params=dict(
ckpt_dir=os.path.join(TEST_DIR, 'out'),
reset_model=True,
steps_per_ckpt=20,
max_steps=40))
... | config = io_utils.parse_config(flags=flags) |
Next line prediction: <|code_start|>
print("Testing quick chat sesh . . . ")
config = io_utils.parse_config(flags=flags)
dataset_class = pydoc.locate(config['dataset']) \
or getattr(data, config['dataset'])
dataset = dataset_class(config['dataset_params'])
... | frozen_graph = bot_freezer.load_graph(bot.ckpt_dir) |
Using the snippet: <|code_start|> def test_basic(self):
"""Instantiate all supported datasets and check they satisfy basic conditions.
THIS MAY TAKE A LONG TIME TO COMPLETE. Since we are testing that the
supported datasets can be instantiated successfully, it necessarily
me... | config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> Otherwise, a few seconds. :)
"""
if os.getenv('DATA') is None \
and not os.path.exists('/home/brandon/Datasets'):
print('To run this test, please enter the path to your datasets: ')
data_dir = input()
else:
... | for default_key in DEFAULT_FULL_CONFIG['dataset_params']: |
Using the snippet: <|code_start|>
class TestLegacyModels(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
self.seq_len = 20
<|code_end|>
, determine the next line of code. You have imports:
import os
import tensorflow as tf
import unittest
import lo... | self.config = io_utils.parse_config(flags=TEST_FLAGS) |
Using the snippet: <|code_start|>
class TestLegacyModels(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
self.seq_len = 20
<|code_end|>
, determine the next line of code. You have imports:
import os
import tensorflow as tf
import unittest
import lo... | self.config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> time=tf.TensorShape(None),
alignments=tf.TensorShape([None, None]),
alignment_history=())
class BasicRNNCell(RNNCell):
"""Same as tf.contrib.rnn.BasicRNNCell, rewritten for clarity.
For example, many TF implementations have leftover code... | output = tf.tanh(bot_ops.linear_map( |
Predict the next line for this snippet: <|code_start|> config_path=None,
return_config=True,
**kwargs):
"""Update contents of a config file, overwriting any that
match those in kwargs.
Args:
config: (dict) subset of DEFAULT_FULL_CONFIG.
... | for top_level_key in DEFAULT_FULL_CONFIG: |
Predict the next line after this snippet: <|code_start|>"""Used by legacy_models for decoding. Not needed by DynamicBot."""
def decode(bot, dataset, teacher_mode=True):
"""Runs a chat session between the given chatbot and user."""
# We decode one sentence at a time.
bot.batch_size = 1
# Decode from... | sentence = io_utils.get_sentence() |
Here is a snippet: <|code_start|>"""Used by legacy_models for decoding. Not needed by DynamicBot."""
def decode(bot, dataset, teacher_mode=True):
"""Runs a chat session between the given chatbot and user."""
# We decode one sentence at a time.
bot.batch_size = 1
# Decode from standard input.
pr... | token_ids = sentence_to_token_ids(tf.compat.as_bytes(sentence), dataset.word_to_idx) |
Continue the code snippet: <|code_start|>"""Tests for various operations done on config (yaml) dictionaries in project."""
dir = os.path.dirname(os.path.realpath(__file__))
class TestConfig(unittest.TestCase):
"""Test behavior of tf.contrib.rnn after migrating to r1.0."""
def setUp(self):
with open(... | config = io_utils.parse_config(flags=TEST_FLAGS) |
Next line prediction: <|code_start|> def check_input_lengths(self, inputs, expected_lengths):
"""
Raises:
ValueError: if length of encoder_inputs, decoder_inputs, or
target_weights disagrees with bucket size for the specified bucket_id.
"""
for input, length in... | encoder_pad = [io_utils.PAD_ID] * (encoder_size - len(encoder_input)) |
Here is a snippet: <|code_start|> """Useful for e.g. deploying model on website.
Args: directory containing model ckpt files we'd like to freeze.
"""
if not tf.get_collection('freezer'):
self.log.warning('No freezer found. Not saving a frozen model.')
return
... | elif name in DEFAULT_FULL_CONFIG: # Requesting a top-level key. |
Given the following code snippet before the placeholder: <|code_start|> dir_name = kwargs[key]
new_ckpt_dir = os.path.join(new_ckpt_dir, dir_name)
return new_ckpt_dir
class BucketModel(Model):
"""Abstract class. Any classes that extend BucketModel just need to customize their
... | optimizer = OPTIMIZERS[self.optimizer](self.learning_rate) |
Next line prediction: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License ... | numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | fsat = instanciar_funcoes_sat(numero_caixa) |
Based on the snippet: <|code_start|>
class TrocarCodigoDeAtivacao(restful.Resource):
def post(self):
args = parser.parse_args()
numero_caixa = args['numero_caixa']
opcao = args['opcao']
novo_codigo = args['novo_codigo']
novo_codigo_confirmacao = args['novo_codigo_confirmac... | hexdump(retorno))) |
Based on the snippet: <|code_start|> type=opcao_codigo,
required=True,
help=u'Identifica a que se refere o código de ativação usado '
u'para realizar a troca')
parser.add_argument('novo_codigo',
type=str,
required=True,
help=u'Novo código de ativação')
pa... | fsat = instanciar_funcoes_sat(numero_caixa) |
Next line prediction: <|code_start|>
Se o código de ativação original tiver sido perdido, então o código de
ativação de emergência deverá ser escrito no arquivo de configurações e
deverá ser usada a opção ``2`` para que seja reconhecido pelo equipamento
SAT como o código de ativação de emergência.
... | parser = request_parser() |
Continue the code snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('certificado',
type=str,
required=True,
help=u'Conteúdo do certificado digital ICP-Brasil')
class ComunicarCertificadoI... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Next line prediction: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the code snippet: <|code_start|> type=str,
required=True,
help=u'Sequencia contendo CNPJ da AC e do estabelecimento comercial')
parser.add_argument('assinatura_ac',
type=str,
required=True,
help=u'Assinatura da sequencia pela AC codificada em base64')
class Associ... | hexdump(retorno)) |
Continue the code snippet: <|code_start|>#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('sequencia_cnpj',
type=str,
required=True,
help=u'Sequencia contendo CNPJ da AC e do estabelecimento comercial')
parser.add_argument('assinatura_ac',
... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the following code snippet before the placeholder: <|code_start|> Assim, cada caixa terá a sua própria faixa de numeração de sessão, o que
torna impossível conflitos de número de sessão. Além disso, cada caixa
terá um arquivo próprio, onde os números gerados serão persistidos,
garantindo que os últ... | self._arquivo_json = os.path.join(PROJECT_ROOT, |
Next line prediction: <|code_start|>
def _escrever_memoria(self):
with open(self._arquivo_json, 'w') as f:
json.dump(self._memoria, f)
def memoize(fn):
# Implementação de memoize obtida de "Thumbtack Engineering"
# https://www.thumbtack.com/engineering/a-primer-on-python-decorators/
... | funcoes_sat = FuncoesSAT(BibliotecaSAT(conf.caminho_biblioteca, |
Predict the next line after this snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('configuracao',
type=str,
required=True,
help=u'XML contendo as configurações da interface de rede')
cla... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the following code snippet before the placeholder: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda para ... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... | fsat = instanciar_funcoes_sat(numero_caixa) |
Based on the snippet: <|code_start|>
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('chave_cfe',
type=str,
required=True,
help=u'Chave do CF-e a ser cancelado (prefixada "CFe...")')
parser.add_argument('dados_cancelamento',
type=str,
... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Next line prediction: <|code_start|>#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('chave_cfe',
type=str,
required=True,
help=u'Chave do CF-e a ser cancelado (prefixada "CFe...")')
parser.add_argument('dados_cancelamento',
type=str,
... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Licens... | numero_caixa, hexdump(retorno)) |
Predict the next line for this snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | fsat = instanciar_funcoes_sat(numero_caixa) |
Predict the next line for this snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
... | numero_caixa, hexdump(retorno)) |
Given the code snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('numero_sessao',
type=str,
required=True,
help=u'Número da sessão a ser consultada')
class ConsultarNumeroSessao(restful.Resource):
def post(self):
args = p... | numero_caixa, numero_sessao, hexdump(retorno)) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('numero_sessao',
type=str,
required=True,
... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the... | numero_caixa, hexdump(retorno)) |
Continue the code snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | fsat = instanciar_funcoes_sat(numero_caixa) |
Continue the code snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lic... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Using the snippet: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | fsat = instanciar_funcoes_sat(numero_caixa) |
Predict the next line after this snippet: <|code_start|># limitations under the License.
#
logger = logging.getLogger('sathub.resource')
parser = request_parser()
parser.add_argument('dados_venda',
type=str,
required=True,
help=u'XML contendo os dados do CF-e de venda')
class EnviarDado... | '(numero_caixa=%s)\n%s', numero_caixa, hexdump(retorno)) |
Predict the next line after this snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... | fsat = instanciar_funcoes_sat(numero_caixa) |
Given snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the... | numero_caixa, hexdump(retorno)) |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Base4 Sistemas Ltda ME
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/li... | fsat = instanciar_funcoes_sat(numero_caixa) |
Next line prediction: <|code_start|>
:param meta_string: Raw meta-inf content as a string
"""
super(PageMetaInf, self).__init__(meta_string)
self.nav_name = self.title if self.nav_name is None else self.nav_name
def load_page(content_path, page_path):
"""Load the page file and retu... | class Page(NavigationBaseItem): |
Given the following code snippet before the placeholder: <|code_start|>META_INF_REGEX = r'(^```metainf(?P<metainf>.*?)```)?(?P<content>.*)'
class PageMetaInf(MetaInfParser): # pylint: disable=R0903
"""MDWeb Page Meta Information."""
def __init__(self, meta_string):
"""Content page meta-information.
... | raise ContentException('Could not find file for content page "%s"' % |
Next line prediction: <|code_start|>#: A regex to extract the url path from the file path
URL_PATH_REGEX = r'^%s(?P<path>[^\0]*?)(index)?(\.md)'
#: A regex for extracting meta information (and comments).
META_INF_REGEX = r'(^```metainf(?P<metainf>.*?)```)?(?P<content>.*)'
class PageMetaInf(MetaInfParser): # pylint:... | raise PageParseException("Unable to parse page path [%s]" % |
Given snippet: <|code_start|>
Tests to write
* Handle symlinks
* File already open
* Non supported extension (.xls)
* Permissions
Maybe test?
* atime, mtime
* large file
"""
try:
# Python >= 3.3
except ImportError:
# Python < 3.3
class TestPageMeta(fake_filesystem_unittest.TestCase):
"""Pag... | meta_inf = PageMetaInf(file_string) |
Predict the next line after this snippet: <|code_start|> def test_parse_custom_field(self):
"""Multiline fields should parse successfully."""
file_string = u"""Title: MDWeb
Description: The minimalistic markdown NaCMS
Author: Chad Rempp
Summary Image: blah.jpg
"""
meta_inf = PageMetaInf(file... | page = Page(*load_page('/my/content', '/my/content/about/history.md')) |
Based on the snippet: <|code_start|> def test_parse_custom_field(self):
"""Multiline fields should parse successfully."""
file_string = u"""Title: MDWeb
Description: The minimalistic markdown NaCMS
Author: Chad Rempp
Summary Image: blah.jpg
"""
meta_inf = PageMetaInf(file_string)
se... | page = Page(*load_page('/my/content', '/my/content/about/history.md')) |
Using the snippet: <|code_start|> self.setUpPyfakefs()
def test_page_instantiation(self):
"""A page should be instantiated with appropriate attributes."""
file_string = u"This is a page"
self.fs.create_file('/my/content/about/history.md',
contents=file_stri... | self.assertRaises(PageParseException, load_page, '/my/content', |
Next line prediction: <|code_start|> # Not an MD file
self.assertRaises(PageParseException, load_page, '/my/content',
'/my/content/index')
@mock.patch('mdweb.Page.PageMetaInf')
def test_repr(self, mock_page_meta_inf):
"""A Page object should return the proper re... | self.assertRaises(ContentException, load_page, '/my/content', |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""Tests for the Debug Helper."""
class TestDebugHelperOn(TestCase):
"""Debug helper tests.
Can't use pyfakefs for this or partials won't load"""
def create_app(self):
<|code_end|>
. Use current file imports:
(from flask_testing import TestCa... | app = MDTestSiteDebugHelper( |
Given snippet: <|code_start|>
class TestDebugHelperOn(TestCase):
"""Debug helper tests.
Can't use pyfakefs for this or partials won't load"""
def create_app(self):
app = MDTestSiteDebugHelper(
"MDWeb",
app_options={}
)
app.start()
return app
d... | app = MDTestSite( |
Here is a snippet: <|code_start|> def _parse_meta_inf(self, meta_inf_string):
"""Parse given meta information string into a dictionary.
Metainf fields now support multi-line values. New lines must be
indented with at least one whitespace character.
:param meta_inf_st... | raise PageMetaInfFieldException( |
Next line prediction: <|code_start|>"""MDWeb Base Navigation Item.
This is broken out into a separate file to avoid circular imports.
"""
class NavigationBaseItem(object): # pylint: disable=R0903
"""Base object for navigation items such as nav-levels or pages."""
#: Type of navigation item
@property
... | META_FIELDS = MDW_META_FIELDS |
Continue the code snippet: <|code_start|>
class Files(object):
"""
Keeps track of the files TSS uses (currently?).
Keeps references like this /// <reference path="lib/mocha/mocha.d.ts" />
up to date. For this it parses unsaved views after each keystroke.
"""
@max_calls(name='Files.i... | LISTE.add(filename, |
Using the snippet: <|code_start|># coding=utf8
#from .Project import ProjectSettings, ProjectError, errorSetting
# ----------------------------------------- CONSTANT ---------------------------------------- #
SUBLIME_PROJECT = 'sublime_project'
SUBLIME_TS = 'sublime_ts'
NO_PROJECT = 'no_project'
# ---------------... | def get_root(self, view): |
Given the following code snippet before the placeholder: <|code_start|># coding=utf8
class Message(object):
messages =[]
def show(self, message, hide=False, with_panel=True):
self.messages = []
self.messages.append(message)
if with_panel:
window = sublime.active_window()... | debounce(self.hide, 1, 'message' + str(id(MESSAGE))) |
Continue the code snippet: <|code_start|>
# has a global variable in globals.py
def is_plugin_globally_disabled():
return "*global" in plugin_disabled_for_folders
def is_plugin_temporarily_disabled(folder=None):
""" Returns True if the plugin is disabled globally or for folder.
Folder can be a view "... | Debug('project', 'Enable ArcticTypescript for %s' % folder) |
Continue the code snippet: <|code_start|># coding=utf8
try:
except ImportError:
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self... | Debug('error', "Only use Compiler Object once!") |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(sel... | self.kwargs = get_kwargs() |
Given the following code snippet before the placeholder: <|code_start|> Debug('build', '> Cancel Build')
self.cancel_build = True
self.answer_pending.put("")
Debug('build', 'Ask for authoritation of post/pre commands')
sublime.active_window().show_quick_panel(... | tsc_path = default_tsc_path(self.project.get_setting('tsc_path'), |
Predict the next line after this snippet: <|code_start|> else:
Debug('build', '> Cancel Build')
self.cancel_build = True
self.answer_pending.put("")
Debug('build', 'Ask for authoritation of post/pre commands')
sublime.active_window().show_quick_pan... | node_path = default_node_path(self.project.get_setting('node_path')) |
Given the following code snippet before the placeholder: <|code_start|>
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel, triggered_for_file):
self.triggered_for_file = triggered_for_file
... | pre_cmd = expand_variables(str(pre_cmd), self.project, use_cache=True) |
Predict the next line for this snippet: <|code_start|>
# ----------------------------------------- UTILS --------------------------------------- #
# --------------------------------------- COMPILER -------------------------------------- #
class Compiler(Thread):
def __init__(self, project, window_for_panel,... | PANEL.clear(self.window_for_panel) |
Predict the next line for this snippet: <|code_start|># coding=utf8
empty_tsconfig = {
"compilerOptions": {},
}
# ##########################################################################
# ################### MAIN: lints entry point ##########
# #######################################... | Debug('tsconfig', 'tsconfig modified, check') |
Predict the next line after this snippet: <|code_start|># coding=utf8
empty_tsconfig = {
"compilerOptions": {},
}
# ##########################################################################
# ################### MAIN: lints entry point ##########
# #####################################... | @catch_CancelCommand |
Given the code snippet: <|code_start|>
def _add_regions(self):
""" Display all found Errors """
if self.view:
self.view.add_regions('tsconfig-error', self.error_regions,
'invalid', 'dot', sublime.DRAW_NO_FILL)
# ####################################... | raise CancelCommand() |
Based on the snippet: <|code_start|> error_locations = []
error_locations.extend(self.harderrors)
error_locations.extend(self.softerrors)
self.view.settings().set('tsconfig-lints', error_locations)
# ###################################################################... | self.content = read_file(self.file_name) |
Given the code snippet: <|code_start|> """ Stores the errors in view.settings()
Format: [<((a,b), msg)>] """
if self.view:
error_locations = []
error_locations.extend(self.harderrors)
error_locations.extend(self.softerrors)
self.view.settings().... | self.content = get_content(self.view) |
Continue the code snippet: <|code_start|> return
self._soft_error("key '%s' is spelled wrong" % k,
self._lint_key(k))
return key_found
def _check_root_dicts(self):
""" Check Type of root dicts == dict.
Returns True if ... | if option not in allowed_compileroptions: |
Here is a snippet: <|code_start|> def _check_root_dicts(self):
""" Check Type of root dicts == dict.
Returns True if everything is ok. """
# root
if type(self.tsconfig) != dict:
self._hard_error("root structure must be an object: { }",
self... | if option not in allowed_settings: |
Here is a snippet: <|code_start|> return all(valid)
def _check_unknown_keys(self):
""" Check for unknown keys in compilerOptions and ArcticTypescript """
if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
if option not i... | for key, validator in compileroptions_validations.items(): |
Predict the next line for this snippet: <|code_start|> if "compilerOptions" in self.tsconfig:
for option in self.tsconfig["compilerOptions"].keys():
if option not in allowed_compileroptions:
self._soft_error("unknown key '%s' in compilerOptions"
... | for key, validator in settings_validations.items(): |
Given snippet: <|code_start|> if view.settings().has('tsconfig-lints'):
error_locations = view.settings().get('tsconfig-lints', [])
current_errors = []
current_selection = view.sel()[0]
for pos, error in error_locations:
error_region = sublime.Region(pos[0], pos[1])
... | if is_tsglobexpansion_disabled(): |
Continue the code snippet: <|code_start|># coding=utf8
# PACKAGE PATH
package_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
def add_usr_local_bin_to_path_on_osx():
""" OBSOLETE
Adds /usr/local/bin to path on mac osx, because that is
where nodejs lives.
Thi... | if file_exists(os.path.join(rootdir, "tsconfig.json")): |
Given the code snippet: <|code_start|> """ OBSOLETE
Adds /usr/local/bin to path on mac osx, because that is
where nodejs lives.
This function has not worked out its intension. Popen does not
use this PATH as a search base for the executable.
default_node_path() is back to it's... | return replace_variables(path, variables) |
Predict the next line for this snippet: <|code_start|> except FileNotFoundError:
pass
parentdir = os.path.abspath(os.path.join(rootdir, os.pardir))
if parentdir == rootdir:
return None
else:
return find_tsconfigdir(parentdir)
def expand_variables(path, project=None, use_cache=F... | Debug('notify', 'The setting node_path is set to "none". That is depreciated. Remove the setting.') |
Using the snippet: <|code_start|>
# Expanding?
if is_tsglobexpansion_disabled():
return False
if linter is None or not linter or not linter.linted:
return False
if len(linter.harderrors) > 0:
return False
if len(linter.softerrors) != linter.numerrors:
return False... | check_tsconfig(linter.view) |
Based on the snippet: <|code_start|> This operates on the file contents, so the file should have been saved
before.
Returns immediately if not linted or linter is None
Returns True if the filesGlob has been expanded
Returns False if there was a linter error, so no expansion has be... | Debug("tsconfig.json", "fileGlobs expaned") |
Here is a snippet: <|code_start|>
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
Debug("tsconfig.json", "fileGlobs expaned")
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are... | expandglob_path = get_expandglob_path() |
Next line prediction: <|code_start|> if "filesGlob" not in linter.tsconfig:
return True # Should reopen project, so return True here
# Expand!
project_dir = os.path.dirname(linter.view.file_name())
file_list = _expand_globs_with_javascript(project_dir, linter)
Debug("tsconfig.json", "fileGlo... | node_path = default_node_path(node_path) |
Predict the next line after this snippet: <|code_start|>
# reload file
linter.view.run_command("revert")
# lint again, so the soft errors are still displayed
check_tsconfig(linter.view)
return True
def _expand_globs_with_javascript(project_dir, linter):
""" use the nodejs script bin/expandgl... | kwargs = get_kwargs() |
Continue the code snippet: <|code_start|>
# from pathlib import Path # not avalilable in python 3.3 (only 3.4)
# Expanding is now done via javascript expandglob.js
# There are too many differences between the glob implementations, and pathutils
# are not available for now
# Second reason for pure js solution: python... | if is_tsglobexpansion_disabled(): |
Predict the next line after this snippet: <|code_start|># coding=utf8
# CANCEL COMMAND EXCEPTION
class CancelCommand(Exception):
""" Throw this exception in a command. The decorator
catch_CancelCommand will catch it and cancel silently """
pass
# CANCEL COMMAND EXCEPTION CATCHER DECORATOR
def catch_C... | Debug('command', "A COMMAND WAS CANCELED") |
Given the following code snippet before the placeholder: <|code_start|># coding=utf8
# CANCEL COMMAND EXCEPTION
class CancelCommand(Exception):
""" Throw this exception in a command. The decorator
catch_CancelCommand will catch it and cancel silently """
pass
# CANCEL COMMAND EXCEPTION CATCHER DECORA... | if is_plugin_temporarily_disabled(): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.