Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>
card_list = soup.cockatrice_carddatabase.cards.find_all('card')
cnt = 0
fout = open("data/all_set_cards.py", "w")
fout.write("from MTG import card\n"
"from MTG import gameobject\n"
"from MTG import cardtype\n"
"from MTG import static_abil... | if len(_type) > 1 and _type[0].upper() in cardtype.SuperType._member_names_: |
Given snippet: <|code_start|> types = []
try:
ID = 'c' + re.search('(?<=multiverseid=)[0-9]+', card.set['picURL']).group(0)
name = card.find('name').text
characteristics = {'name': name}
characteristics['text'] = card.find('text').text
character... | for ability in static_abilities.StaticAbilities._member_names_: |
Here is a snippet: <|code_start|>"""
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.... | fix_path() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.... | fix_path() |
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 ... | SECRET_KEY = get_app_config().secret_key |
Based on the snippet: <|code_start|>
class TestSeasonRange(TestCase):
def test_instantiation(self):
start_season = Season.season_2015
end_season = Season.season_2016
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from nba_data.data.season im... | self.assertIsNotNone(SeasonRange(start=start_season, end=end_season)) |
Continue the code snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoreadvance... | self.assertEqual(nicolas_batum_box_score.player.status.type, PlayerStatusType.active) |
Predict the next line after this snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/... | self.assertEqual(nicolas_batum_box_score.player.team, Team.charlotte_hornets) |
Here is a snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
<|code_end|>
. Write the next line using the current file imports:
import json
imp... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoreadvanced.json')) as data_file: |
Using the snippet: <|code_start|>
class TestSeasonPlayersDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(SeasonPlayersDeserializer())
def test_deserialize(self):
<|code_end|>
, determine the next line of code. You have imports:
import json
import os
from unittest import Te... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/players.json')) as data_file: |
Here is a snippet: <|code_start|>
if len(row_set) < 1:
raise ValueError('Unable to parse row set from %s', data)
return row_set[CommonPlayerInfoDeserializer.row_set_index]
@staticmethod
def deserialize(data):
result = CommonPlayerInfoDeserializer.parse_result(data=data)
... | return DetailedPlayer(id=id, name=name, team=team, birth_date=birth_date, height=height, weight=weight, |
Based on the snippet: <|code_start|>
row_set = result_set[CommonPlayerInfoDeserializer.row_set_field_name]
if len(row_set) < 1:
raise ValueError('Unable to parse row set from %s', data)
return row_set[CommonPlayerInfoDeserializer.row_set_index]
@staticmethod
def deserializ... | position = Position.get_position_from_name(name=str(result[CommonPlayerInfoDeserializer.position_name_index])) |
Predict the next line for this snippet: <|code_start|> if CommonPlayerInfoDeserializer.row_set_field_name not in result_set:
raise ValueError('Unable to parse results from %s', data)
row_set = result_set[CommonPlayerInfoDeserializer.row_set_field_name]
if len(row_set) < 1:
... | team = Team.get_team_by_id(team_id=int(result[CommonPlayerInfoDeserializer.team_id_index])) |
Here is a snippet: <|code_start|>
class CalendarDeserializer:
internal_field_name = "_internal"
start_date_field_name = "startDate"
end_date_field_name = "endDate"
start_date_current_season_field_name = "startDateCurrentSeason"
fields_to_ignore = { internal_field_name, start_date_field_name, end_d... | def deserialize(calendar_json, date_range=DateRange(), ignore_dates_without_games=True): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class TestRotoWirePlayerNewsItemsDeserializer(TestCase):
def test_instantiation(self):
deserializer = RotoWirePlayerNewsItemsDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/rotowire_player_news.json')) as data_file: |
Next line prediction: <|code_start|>
@staticmethod
def generate_common_player_info_uri():
return UriGenerator.stats_base_uri + UriGenerator.common_player_info_path
@staticmethod
def generate_advanced_box_score_uri():
return UriGenerator.stats_base_uri + UriGenerator.advanced_box_score_p... | assert isinstance(season, Season) |
Predict the next line after this snippet: <|code_start|>
class TestDateRange(TestCase):
start = date(year=2015, month=1, day=1)
end = date(year=2015, month=1, day=2)
def test_instantiation(self):
<|code_end|>
using the current file's imports:
from datetime import date, timedelta
from unittest import Te... | self.assertIsNotNone(DateRange(start=TestDateRange.start, end=TestDateRange.end)) |
Given snippet: <|code_start|>
# TODO: @jbradley in future make test more robust
class TestScoreboardDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(ScoreboardDeserializer())
def test_deserialize(self):
<|code_end|>
, continue by predicting the next line. Consider current ... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/scoreboard.json')) as data_file: |
Continue the code snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxsco... | self.assertIsInstance(box_score, GameBoxScore) |
Given the following code snippet before the placeholder: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_... | self.assertIsInstance(box_score.player_box_scores[0], TraditionalPlayerBoxScore) |
Predict the next line after this snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tes... | self.assertIsInstance(box_score.team_box_scores[0], TraditionalTeamBoxScore) |
Based on the snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
<|code_end|>
, predict the immediate next line with the help of imports... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoretraditional.json')) as data_file: |
Next line prediction: <|code_start|>
class TestSeasonType(TestCase):
def test_get_query_parameter_name(self):
self.assertEqual(SeasonType.get_query_parameter_name(), "SeasonType")
def test_get_season_typea(self):
self.assertEqual(SeasonType.get_season_type("Regular Season"), SeasonType.regula... | self.assertEqual(season_type_name_map, |
Given the code snippet: <|code_start|>
class TestOutcome(TestCase):
def test_get_outcome_from_abbreviation(self):
self.assertEqual(Outcome.get_outcome_from_abbreviation("w"), Outcome.win)
self.assertEqual(Outcome.get_outcome_from_abbreviation("W"), Outcome.win)
self.assertRaises(ValueError... | self.assertEqual(outcome_abbreviation_to_outcome_map, |
Next line prediction: <|code_start|>
class CommonAllPlayersDeserializer:
name_index = 2
team_id_index = 7
id_index = 0
result_sets_field_name = 'resultSets'
row_set_field_name = 'rowSet'
results_index = 0
def __init__(self):
pass
@staticmethod
def deserialize(data):
... | return CommonAllPlayer(name=result[CommonAllPlayersDeserializer.name_index], |
Predict the next line after this snippet: <|code_start|>
class CommonAllPlayersDeserializer:
name_index = 2
team_id_index = 7
id_index = 0
result_sets_field_name = 'resultSets'
row_set_field_name = 'rowSet'
results_index = 0
def __init__(self):
pass
@staticmethod
def deser... | team=Team.get_team_by_id(team_id=result[CommonAllPlayersDeserializer.team_id_index]), |
Next line prediction: <|code_start|>
class TestPosition(TestCase):
def test_get_position_from_abbreviation(self):
guard = Position.get_position_from_abbreviation("g")
self.assertEqual(guard, Position.guard)
another_guard = Position.get_position_from_abbreviation("G")
self.assertEq... | self.assertEqual(abbreviation_to_position_map, |
Given the code snippet: <|code_start|>
class TestPosition(TestCase):
def test_get_position_from_abbreviation(self):
guard = Position.get_position_from_abbreviation("g")
self.assertEqual(guard, Position.guard)
another_guard = Position.get_position_from_abbreviation("G")
self.assertEq... | self.assertEqual(name_to_position_map, |
Here is a snippet: <|code_start|>
class TestCalendarDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(CalendarDeserializer())
def test_deserialize(self):
start = date(year=2016, month=12, day=1)
end = date(year=2017, month=2, day=15)
<|code_end|>
. Write the n... | date_range = DateRange(start=start, end=end) |
Predict the next line for this snippet: <|code_start|>
class TestCalendarDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(CalendarDeserializer())
def test_deserialize(self):
start = date(year=2016, month=12, day=1)
end = date(year=2017, month=2, day=15)
... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/calendar.json')) as data_file: |
Next line prediction: <|code_start|>
class TestCommonAllPlayersDeserializer(TestCase):
def test_instantiation(self):
deserializer = CommonAllPlayersDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):
with open(os.path.join(ROOT_DI... | self.assertEqual(quincy_acy.team, Team.sacramento_kings) |
Here is a snippet: <|code_start|>
class TestCommonAllPlayersDeserializer(TestCase):
def test_instantiation(self):
deserializer = CommonAllPlayersDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):
<|code_end|>
. Write the next line using ... | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/commonallplayers.json')) as data_file: |
Given the code snippet: <|code_start|>
class RotoWirePlayerNewsItemsDeserializer:
def __init__(self):
pass
list_items_field_name = 'ListItems'
@staticmethod
def deserialize(data):
return [
<|code_end|>
, generate the next line using the imports in this file:
from nba_data.deserialize... | RotoWirePlayerNewsItemDeserializer.deserialize(data=player_news_item) |
Next line prediction: <|code_start|>
class TestTeamSeasonRange(TestCase):
def test_instantiation(self):
team = Team.atlanta_hawks
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from nba_data.data.season import Season
from nba_data.data.season_range import SeasonRange
from nba_dat... | start_season = Season.season_2015 |
Here is a snippet: <|code_start|>
class CourseModelTest(TestCase):
def test_course_can_be_created_with_only_no(self):
Course.objects.create(no='12345QAQ 010101')
self.assertEqual(1, Course.objects.count())
class FlatPrerequisiteModelTest(TestCase):
def test_update_html_creates_object(self... | FlatPrerequisite.update_html('<3') |
Here is a snippet: <|code_start|>
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
... | crawl_course(ACIXSTORE, auth_num, cou_codes, ys) |
Given snippet: <|code_start|> else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
print('Please provide valid ACIXSTORE and auth_num from')
print(url)
ACIXSTORE = input('ACIXSTORE: ')
auth_num = input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCo... | crawl_dept(ACIXSTORE, auth_num, cou_codes, ys) |
Here is a snippet: <|code_start|>
try:
except ImportError:
Entrance = None
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha no... | cou_codes = get_cou_codes() |
Given snippet: <|code_start|> return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in... | Course.objects.all().delete() |
Here is a snippet: <|code_start|>
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in [get_config('crawler', 'se... | Department.objects.all().delete() |
Here is a snippet: <|code_start|>
try:
except ImportError:
Entrance = None
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha no... | for ys in [get_config('crawler', 'semester')]: |
Based on the snippet: <|code_start|>
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
url(r'^', include('index.urls')),
url(r'^', include('table.urls')),
]
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls... | handler404 = error404 |
Predict the next line for this snippet: <|code_start|>
def prerequisite(request):
return render(
request,
'table/prerequisites.html',
<|code_end|>
with the help of current file imports:
from django.shortcuts import render
from data_center.models import FlatPrerequisite
and context from other fi... | {'data': FlatPrerequisite.objects.get()} |
Continue the code snippet: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import search, syllabus, hit, autocomplete
and context (classes, functions, or code) from other files:
# Path: sea... | syllabus, name='syllabus'), |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
syllabus, name='syllabus'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from .views import search, syllabus, hit, autocomplete
and c... | url(r'^hit/(?P<no>.+)/$', hit, name='hit'), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
syllabus, name='syllabus'),
url(r'^hit/(?P<no>.+)/$', hit, name='hit'),
<|code_end|>
, predict the next line using imports from the current file:
from django.co... | url(r'^autocomplete/$', autocomplete, name='autocomplete'), |
Continue the code snippet: <|code_start|>
class CourseIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.NgramField(document=True, use_template=True)
no = indexes.CharField(model_attr='no')
code = indexes.CharField(model_attr='code')
eng_title = indexes.CharField(model_attr='eng_title')
... | return Course |
Next line prediction: <|code_start|># Name: mapper_occci_online.py
# Purpose: Nansat mapping for OC CCI data, stored online in THREDDS
# Author: Anton Korosov
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, ... | srcDSProjection = NSR().wkt |
Using the snippet: <|code_start|> 'sourceBand': 1,
'ScaleRatio': subScaleRatio,
'ScaleOffset': subScaleOffset},
'dst': {'wkv': subWKV}}
# append band metadata to metaDict
m... | self.dataset.SetProjection(NSR().wkt) |
Here is a snippet: <|code_start|># Name: mapper_pathfinder52
# Purpose: Mapping for NOAA AVHRR PATHFINDER52 DATA
# Authors: Anton Korosov, Dmitry Petrenko
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# ... | raise WrongMapperError(filename) |
Based on the snippet: <|code_start|># ------------------------------------------------------------------------------
# Name: nansat_test_base.py
# Purpose: Basic class for Nansat tests
#
# Author: Anton Korosov
#
# Created: 20.03.2018
# Copyright: (c) NERSC
# Licence: This file is part o... | self.test_file_gcps = os.path.join(ntd.test_data_path, 'gcps.tif') |
Here is a snippet: <|code_start|># Name: mapper_occci_online.py
# Purpose: Nansat mapping for OC CCI data, stored online in THREDDS
# Author: Anton Korosov
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3... | srcDSProjection = NSR().wkt |
Here is a snippet: <|code_start|># http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/conc/2016/04/ice_conc_sh_polstere-100_multi_201604261200.nc ice_conc
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/drift_lr/merged/2016/04/ice_drift_nh_polstere-625_multi-oi_201604151200-201604171200.nc dX dY
# http://thr... | ds = Dataset(filename) |
Here is a snippet: <|code_start|> AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.0174532925199433,
AUTHORITY["EPSG","9108"]],
AUTHORITY["EPSG","4326"]]'
"""
def __init__(self, srs=0)... | raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs) |
Given snippet: <|code_start|> palette = None
pilImg = None
pilImgLegend = None
extensionList = ['png', 'PNG', 'tif', 'TIF', 'bmp',
'BMP', 'jpg', 'JPG', 'jpeg', 'JPEG']
_cmapName = 'jet'
# instance attributes
array = None
def __init__(self, nparray, **kwargs):
... | self.logger = add_logger('Nansat') |
Predict the next line for this snippet: <|code_start|> dataset : gdal.Dataset
input dataset to copy Geolocation metadata from
"""
self = cls.__new__(cls) # empty object
self.x_vrt = None
self.y_vrt = None
self.data = dataset.GetMetadata('GEOLOCATION')
r... | lon_dataset = gdal.Open(self.data['X_DATASET']) |
Here is a snippet: <|code_start|> line_offset=0, line_step=1,
pixel_offset=0, pixel_step=1):
"""Init data of Geolocation object from input parameters
Parameters
-----------
x_filename : str
... | srs = NSR().wkt |
Predict the next line after this snippet: <|code_start|>
class MyWaveOpenDAPTests(unittest.TestCase):
def setUp(self):
self.src = 'http://thredds.met.no/thredds/dodsC/fou-hi/mywavewam4archive' \
'/2017/10/29/MyWave_wam4_WAVE_20171029T18Z.nc'
def test_get_date(self):
<|code_end|>
u... | res = Mapper.get_date(self.src) |
Based on the snippet: <|code_start|> self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_proj4_unicode(self):
nsr = NSR(u'+proj=longlat')
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
... | ss = osr.SpatialReference() |
Predict the next line for this snippet: <|code_start|> self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_proj4_unicode(self):
nsr = NSR(u'+proj=longlat')
self.assertEqual(type(nsr), NSR)
... | self.assertRaises(NansatProjectionError, NSR, -10) |
Using the snippet: <|code_start|> assert isinstance(num_workers, int), \
'num workers must be an int: %r' % (num_workers)
# check existing workers and issue a warning if it exceeds max
num_existing = len(self._workers) if self._workers else 0
num_expected = num_workers + num_... | task = Task(future, fn, args, kwargs) |
Given the code snippet: <|code_start|> self._name = None
self.name = thread_name_prefix
self.start()
def start(self):
with self._lock:
self._running = True
# NOTE : This unconditionally adds more workers (can go over max).
self._create_workers()
... | spawn_worker(self, name=generate_id(self._thread_name_prefix)) |
Using the snippet: <|code_start|> self._name = None
self.name = thread_name_prefix
self.start()
def start(self):
with self._lock:
self._running = True
# NOTE : This unconditionally adds more workers (can go over max).
self._create_workers()
... | spawn_worker(self, name=generate_id(self._thread_name_prefix)) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/task/pool.py
Task pool abstraction. Replacement for `concurrent.futures`.
Defines a task pool class that can be used to run tasks asynchronously.
Most of this logic was taken from pythonfutures:
https://github.com/agronholm/pythonfutures
https://git.io/... | max_workers = (get_cpu_count() or 1) * 5 |
Predict the next line for this snippet: <|code_start|>
class TestMergeDictionaries(unittest.TestCase):
'''
Unit tests for the dictionary merge algorithm. This should recursively
merge the structure of dictionaries, overwriting leaf nodes instead of
branches whenever possible.
'''
@log_function... | result = merge_dicts(base, *rest) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/dict.py
Tests for dictionary utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
class TestMergeDictionaries(unittest.TestCase):
'''
Unit tests for the dictionary merge algorithm. This should recursively
m... | @log_function('[merge : shallow]') |
Based on the snippet: <|code_start|> return False
return True
def map_test_function(test_instance, test_function, test_cases):
assert isinstance(test_instance, unittest.TestCase), \
'test instance must be a unittest.TestCase: %r' % (test_instance)
assert callable(test_function), \
... | wrapped_test_function = log_function( |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/fs.py
Tests for file-system utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
if os.name == 'posix':
FS_ROOT = '/'
elif os.name == 'nt':
FS_ROOT = 'C:\\'
else:
logger.error('unknown os type, test data mig... | result = get_common_ancestor([]) |
Given snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/fs.py
Tests for file-system utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
if os.name == 'posix':
FS_ROOT = '/'
elif os.name == 'nt':
FS_ROOT = 'C:\\'
else:
logger.error('unknown os type, test data might b... | @log_function('[ancestor : empty]') |
Predict the next line for this snippet: <|code_start|> '''
@log_function('[ancestor : empty]')
def test_gca_empty(self):
''' Ensures that `None` is returned for an empty path list. '''
result = get_common_ancestor([])
self.assertEqual(None, result,
'common anc... | map_test_function( |
Given the following code snippet before the placeholder: <|code_start|> This is calculated by first generating the HMAC for each item in
`content` separately, then concatenating them, and finally running another
HMAC on the concatenated intermediate result. Finally, the result of that
is base-64 encoded,... | hmac_digest_str = bytes_to_str(hmac_digest_bytes) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
'''
lib/util/hmac.py
Contains HMAC utility functions. The ycmd server expects an HMAC header with
all requests to verify the client's identity. The ycmd server also includes an
HMAC header in all responses to allow the client... | hmac_secret = str_to_bytes(hmac_secret) |
Given the code snippet: <|code_start|> Calculates the HMAC for the given `content` using the `hmac_secret`.
This is calculated by first generating the HMAC for each item in
`content` separately, then concatenating them, and finally running another
HMAC on the concatenated intermediate result. Finally, th... | hmac_digest_bytes = base64_encode(hmac_digest_binary) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/util/format.py
Data formatting functions. Includes base64 encode/decode functions as well as
json parse/serialize functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def base64_encode(data):
'''
Encodes the given `da... | encoded = bytes_to_str(encoded) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
'''
lib/util/format.py
Data formatting functions. Includes base64 encode/decode functions as well as
json parse/serialize functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def base64_encode(data):
... | data = str_to_bytes(data) |
Based on the snippet: <|code_start|> logger.warning(
'ycmd settings template is missing the '
'filetype_whitelist placeholder'
)
ycmd_settings['filetype_whitelist'] = {}
ycmd_settings['filetype_whitelist']['*'] = 1
# BLACKLIST
# Disable for nothing. This plugin wi... | hmac_secret_encoded = base64_encode(hmac_secret_binary) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/ycmd/settings.py
Utility functions for ycmd settings.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file... | if not is_directory(ycmd_root_directory): |
Given the following code snippet before the placeholder: <|code_start|>Utility functions for ycmd settings.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file from the ycmd module.
The `... | if not is_file(ycmd_settings_path): |
Next line prediction: <|code_start|>logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file from the ycmd module.
The `ycmd_root_directory` should refer to the path to the repository.
'''
if... | ycmd_settings = load_json_file(ycmd_settings_path) |
Next line prediction: <|code_start|> 'ycmd settings template is missing the '
'filetype_whitelist placeholder'
)
ycmd_settings['filetype_whitelist'] = {}
ycmd_settings['filetype_whitelist']['*'] = 1
# BLACKLIST
# Disable for nothing. This plugin will decide what to ignore... | hmac_secret_str = bytes_to_str(hmac_secret_encoded) |
Given the following code snippet before the placeholder: <|code_start|>"""plot_expressions.py - make cluster gene expression plots"""
def normalize_js(value):
if math.isnan(value) or math.isinf(value):
return 0.0
else:
return value
def generate_plots(session, result_dir, output_dir):
<|code_... | ratios = read_ratios(result_dir) |
Given snippet: <|code_start|> cm_string += '<span class="gaggle-species">' + species + '</span>\n'
cm_string += '<div class="gaggle-namelist"><ol>\n'
cluster_conds = [c.column_name.name for c in session.query(cm2db.ColumnMember).filter(
and_(cm2db.ColumnMember.cluster == cluster, cm2... | ratios = read_ratios(result_dir) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
def model_getter(cls):
def f(x):
if isinstance(x, str) and x.isdigit() or isinstance(x, Number):
return cls.objects.get(pk=x)
<|code_end|>
with the help of current file imports:
from numbers im... | elif isinstance(cls, m.IdentifiedBySlug): |
Here is a snippet: <|code_start|>sys.path += ["."]
os.environ['DJANGO_SETTINGS_MODULE']='solalim.settings'
django.setup()
months={
"janvier": 1,
"février": 2,
"fevrier": 2,
"mars": 3,
"avril": 4,
"mai": 5,
"juin": 6,
"juillet": 7,
"août": 8,
"aout": 8,
"septembre": 9,
"... | for dv in m.Delivery.objects.filter(name__iregex=iregex): |
Using the snippet: <|code_start|> subkey = x.pk
dump.__dict__.setdefault(key, {})[subkey] = val
return dump
# In [12]: for k, v in dump.__dict__.items():
# ...: first_val = list(v.values())[0]
# ...: subkeys = list(first_val.__dict__.keys())
# ...: print(f"{k}: {', '.join(su... | u_db, _ = m.User.objects.get_or_create( |
Predict the next line for this snippet: <|code_start|> if granted[k] == wishes[k]:
n_unsatisfied -= 1 # He's satisfied now!
# 2nd stage: give the remaining units, one by one, to biggest unsatisfied buyers
got_leftover = sorted(wishes.keys(), key=lambda k: granted[k]-wish... | purchases = m.Purchase.objects.filter(product=pd)
|
Using the snippet: <|code_start|>def unit_multiple(unit, n=None):
if unit[0].isdigit():
return "×"+unit
else:
return " "+m.plural(unit, n)
@register.filter
def articulate(name, n=None):
return m.articulate(name, n)
@register.filter
def subgroup_state(sg, dv):
x = dv.subgroupstatefordel... | return francais.plural(singular, 2) |
Based on the snippet: <|code_start|>@register.filter
def several(x):
return len(x) > 1
@register.filter
def forced_sign(f):
return "%+g" % f
@register.filter
def price(f):
return "%.02f€" % f
@register.filter
def price_nocurrency(f):
return "%.02f" % f
@register.filter
def weight(w):
if w>=1: re... | return " "+m.plural(unit, n) |
Based on the snippet: <|code_start|> dump.__dict__.setdefault(key, {})[subkey] = val
return dump
# In [12]: for k, v in dump.__dict__.items():
# ...: first_val = list(v.values())[0]
# ...: subkeys = list(first_val.__dict__.keys())
# ...: print(f"{k}: {', '.join(subkeys)}")
def par... | u_db, _ = m.User.objects.get_or_create( |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def render_text(template_name, ctx):
t = get_template(template_name)
text_unicode = t.render(ctx)
return text_unicode
def non_html_response(name_bits, name_extension, content):
"""Common helper to serve PDF and Excel content."""
mime_t... | deliveries = m.Delivery.objects.filter(network_id=network, state=m.Delivery.FROZEN) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def render_text(template_name, ctx):
t = get_template(template_name)
text_unicode = t.render(ctx)
return text_unicode
def non_html_response(name_bits, name_extension, content):
"""Common helper to serve PDF and Excel content."""
mime_type... | nw = get_network(network) |
Given the code snippet: <|code_start|># Generated by Django 3.2.6 on 2021-08-26 16:32
def load_villes(apps, schema_editor):
fixtures = Path(__file__).parent / 'villes.json.gz'
print(" Populating database...")
<|code_end|>
, generate the next line using the imports in this file:
from pathlib import Path
fr... | Ville.objects.all().delete() # In case of partially loaded or corrupted data |
Using the snippet: <|code_start|># import logging
# logger = logging.getLogger("nextion").getChild(__name__)
class EventType(IntEnum):
TOUCH = 0x65 # Touch event
TOUCH_COORDINATE = 0x67 # Touch coordinate
TOUCH_IN_SLEEP = 0x68 # Touch event in sleep mode
AUTO_SLEEP = 0x86 # Device automatically ... | class NextionProtocol(BasicProtocol): |
Continue the code snippet: <|code_start|># hash_to_ipv4 - Return IP associated with <Hash> #
# hash_to_score - Return Score to given <Hash> #
#################################################################
class Ibmxforce(object):
def __init__(self):
# lists of values th... | if config.ibmxforce_token: |
Next line prediction: <|code_start|># Author: 10TOHH #
# #
# Tunes: #
# domain_to_ipv4 - Resolves IP to <Domain> #
# domain_to_hash ... | self.api = helpers.Common() |
Predict the next line for this snippet: <|code_start|> self.ma = Mcafee()
# Check IPv4 in blacklist tunes
def ipv4_blacklist_check(self, ip_address):
if self.a.ipv4_to_blacklist(ip_address):
return True
elif self.f.ipv4_to_blacklist(ip_address):
return True
... | self.api = helpers.Common() |
Given the following code snippet before the placeholder: <|code_start|># #
# Tunes: #
# domain_to_hash - Return Hash to <Domain> #
# ... | self.api = helpers.Common() |
Predict the next line after this snippet: <|code_start|># mutex_to_hash - Return Hash associated with <Mutex> #
#################################################################
class Totalhash(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
... | if config.totalhash_api_key: |
Continue the code snippet: <|code_start|># Tunes: #
# domain_to_hash - Return Hash to <Domain> #
# domain_to_url - Return URL to report for given <Domain> #
# #
# ipv4_to_has... | self.api = helpers.Common() |
Given the following code snippet before the placeholder: <|code_start|>#################################################################
class Cymon(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
self.domain_list = []
self.hash_list = []
... | if config.cymon_api_key: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.