Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|># Copyright 2014 OpenStack Foundation
# 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.or... | @utils.memoized_property |
Given the following code snippet before the placeholder: <|code_start|># 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/licens... | base_class=schemas.SchemaBasedModel) |
Using the snippet: <|code_start|> if isinstance(fixture[1], str):
try:
data = json.loads(fixture[1])
except ValueError:
data = io.StringIO(fixture[1])
return FakeResponse(fixture[0], fixture[1]), data
def get(self, *args, **kwargs):
re... | return schemas.Schema(raw_schema) |
Continue the code snippet: <|code_start|>#
# 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 by applicable l... | data = list(progressbar.VerboseIteratorWrapper(requestid_proxy, |
Given snippet: <|code_start|># Copyright 2013 OpenStack Foundation
# 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/L... | iterator_with_len = utils.IterableWithLength(iter('X' * 100), size) |
Predict the next line after this snippet: <|code_start|># Copyright 2013 OpenStack Foundation
# 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:... | sys.stdout = output = test_utils.FakeTTYStdout() |
Predict the next line for this snippet: <|code_start|># Copyright 2021 OpenStack Foundation
# 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://... | if utils.has_version(self.http_client, version): |
Next line prediction: <|code_start|># Copyright 2021 OpenStack Foundation
# 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/lic... | raise exc.HTTPNotImplemented( |
Predict the next line for this snippet: <|code_start|># Copyright 2013 OpenStack Foundation
# 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://... | @utils.memoized_property |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2013 OpenStack Foundation
# 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
#
... | return warlock.model_factory(schema.raw(), schemas.SchemaBasedModel) |
Given the code snippet: <|code_start|> return meta
def get(self, image, **kwargs):
"""Get the metadata for a specific image.
:param image: image object or id to look up
:rtype: :class:`Image`
"""
image_id = base.getid(image)
resp, body = self.client.head('/v1... | body = utils.integrity_iter(body, checksum) |
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... | class Image(base.Resource): |
Using the snippet: <|code_start|> raw_schema = {'name': 'Country', 'properties': {}}
schema = schemas.Schema(raw_schema)
self.assertEqual('Country', schema.name)
self.assertEqual([], schema.properties)
def test_schema_with_property(self):
raw_schema = {'name': 'Country', 'pro... | self.api = utils.FakeAPI(fixtures) |
Continue the code snippet: <|code_start|>
fixtures = {
'/v2/schemas': {
'GET': (
{},
{
'image': '/v2/schemas/image',
'access': '/v2/schemas/image/access',
},
),
},
'/v2/schemas/image': {
'GET': (
{},
... | _SCHEMA = schemas.Schema({ |
Given the following code snippet before the placeholder: <|code_start|>
if kwargs.get('insecure', False) is True:
self.session.verify = False
else:
if kwargs.get('cacert', None) != '':
self.session.verify = kwargs.get('cacert', True)
... | header = '-H \'%s: %s\'' % utils.safe_header(key, value) |
Predict the next line after this snippet: <|code_start|> break
yield chunk
def _set_common_request_kwargs(self, headers, kwargs):
"""Handle the common parameters used to send the request."""
# Default Content-Type is octet-stream
content_type = headers.get('Conte... | raise exc.from_response(resp, resp.content) |
Next line prediction: <|code_start|> {
"status": "CURRENT",
"id": "v2.3",
"links": [
{
"href": "http://10.229.45.145:9292/v2/",
"rel": "self"
... | self.api = utils.FakeAPI(fixtures) |
Based on the snippet: <|code_start|> {
"additionalProperties": True,
"name": {
"type": "string"
},
"created_at": {
"type": "string",
"readOnly": True,
"description":... | self.controller = base.BaseController(self.api, self.schema_api, |
Next line prediction: <|code_start|> "GET": (
{},
{
"additionalProperties": True,
"name": {
"type": "string"
},
"created_at": {
"type": "string",
"readOnly": True,
... | self.api = utils.FakeAPI(data_fixtures) |
Next line prediction: <|code_start|>#
# 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 by applicable law or... | self.assertEqual("106B", utils.make_size_human_readable(106)) |
Here is a snippet: <|code_start|># Copyright 2012 OpenStack Foundation
# 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/licens... | @utils.memoized_property |
Given the code snippet: <|code_start|>
@utils.memoized_property
def unvalidated_model(self):
"""A model which does not validate the image against the v2 schema."""
schema = self.schema_client.get('image')
warlock_model = warlock.model_factory(
schema.raw(), base_class=schemas... | raise exc.HTTPBadRequest(msg) |
Predict the next line after this snippet: <|code_start|># 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 by... | schema.raw(), base_class=schemas.SchemaBasedModel) |
Using the snippet: <|code_start|> username=username,
password=password,
user_domain_id=user_domain_id,
user_domain_name=user_domain_name,
project_id=project_id,
project_name=project_name,
project_domain_id=pro... | _("You must provide a username via" |
Given snippet: <|code_start|>#
# 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 by applicable law or agreed... | parser.set_defaults(os_auth_url=utils.env('OS_AUTH_URL')) |
Predict the next line for this snippet: <|code_start|> return args.os_image_url
else:
return None
def _discover_auth_versions(self, session, auth_url):
# discover the API versions the server is supporting base on the
# given URL
v2_auth_url = None
v3_a... | raise exc.CommandError(msg) |
Using the snippet: <|code_start|> "null"
],
"type": "string"
}
}
},
"type": {
"enum": [
... | self.controller = base.BaseController(self.api, self.schema_api, |
Predict the next line after this snippet: <|code_start|> "object",
"string",
"null"
],
"type": "string"
}
... | self.api = utils.FakeAPI(data_fixtures) |
Next line prediction: <|code_start|> ],
"type": "string"
}
}
},
"type": {
"enum": [
"array",
... | metadefs.PropertyController) |
Predict the next line after this snippet: <|code_start|># Copyright 2013 OpenStack Foundation
# 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:... | @utils.memoized_property |
Continue the code snippet: <|code_start|># Copyright 2013 OpenStack Foundation
# 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.or... | base_class=schemas.SchemaBasedModel) |
Predict the next line after this snippet: <|code_start|>
class UnsupportedVersion(ClientException):
"""User is trying to use an unsupported version of the API."""
pass
class CommandError(ClientException):
"""Error in CLI tool."""
pass
class AuthorizationFailure(ClientException):
"""Cannot author... | _("Authentication failed. Missing options: %s") % |
Continue the code snippet: <|code_start|> json.dumps({
"image": {
"status": "queued",
"deleted": False,
"container_format": "bare",
"min_ram": 0,
"updated_at": "2013-12-20T01:51:45",
... | self.api = utils.FakeAPI(fixtures) |
Here is a snippet: <|code_start|> "image": {
"status": "queued",
"deleted": False,
"container_format": "bare",
"min_ram": 0,
"updated_at": "2013-12-20T01:51:45",
"owner": "foo",
... | self.mgr = images.ImageManager(self.api) |
Continue the code snippet: <|code_start|> 'properties': {'arch': 'x86_64'},
},
]}
def get(self, url, **kwargs):
self.url = url
return utils.FakeResponse({}), ParameterFakeAPI.image_list
class FakeArg(object):
def __init__(self, arg_dict):
self.arg_dict = arg_dic... | shell.do_image_list(self.gc, FakeArg({"is_public": "True"})) |
Continue the code snippet: <|code_start|> {
'image_id': IMAGE,
'member_id': MEMBER,
'status': 'accepted'
}
),
}
}
schema_fixtures = {
'member': {
'GET': (
{},
{
'name': 'member',
... | self.controller = base.BaseController(self.api, self.schema_api, |
Given the code snippet: <|code_start|> 'PUT': (
{},
{
'image_id': IMAGE,
'member_id': MEMBER,
'status': 'accepted'
}
),
}
}
schema_fixtures = {
'member': {
'GET': (
{},
{
... | self.api = utils.FakeAPI(data_fixtures) |
Predict the next line for this snippet: <|code_start|> 'image_id': IMAGE,
'member_id': MEMBER,
'status': 'accepted'
}
),
}
}
schema_fixtures = {
'member': {
'GET': (
{},
{
'name': 'member',
... | image_members.Controller) |
Given snippet: <|code_start|> This decorator checks that required fields are present when image
data has been supplied via command line arguments or via stdin
On error throws CommandError exception with meaningful message.
:param data_fields: Which fields' presence imply image data
:type data_field... | msg = (_("error: Must provide %(req)s when using %(opt)s.") % |
Predict the next line for this snippet: <|code_start|> On error throws CommandError exception with meaningful message.
:param data_fields: Which fields' presence imply image data
:type data_fields: iter
:param required: Required fields
:type required: iter
:return: function decorator
"""
... | raise exc.CommandError(msg) |
Next line prediction: <|code_start|> help='Directory to serve out of.')
return parser
HOME_PAGE = jsontemplate.Template("""\
<h3>latch</h3>
{.repeated section pages}
<a href="{@|htmltag}">{@}</a> <br/>
{.end}
""", default_formatter='html')
LATCH_PATH_RE = re.compile(r'/-/latch/(\S+)$')
# TODO: Rewrite l... | class LatchRequestHandler(httpd.BaseRequestHandler): |
Using the snippet: <|code_start|>#!/usr/bin/python
#
# Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd
"""
publish.py
Implement publishing plugins.
"""
c... | log = util.Logger(util.ANSI_BLUE) |
Here is a snippet: <|code_start|>#!/usr/bin/python
#
# Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd
"""
recv.py
Receive file contents from stdin, write t... | log = util.Logger(util.ANSI_GREEN) |
Predict the next line for this snippet: <|code_start|>"""
wait_server.py
Server that does a hanging get. Doesn't need to be a WSGI app I think.
Override SimpelHttpServer.
Only things like /<roll-name/1/ can hang.
Even index.html should be static?
There is a thread that reads from a Queue. And then some event doe... | log = util.Logger(util.ANSI_BLUE) |
Here is a snippet: <|code_start|>{.repeated section package}
<li>{name} {.if test static} <a href="{name}/static/">static</a> {.end} </li>
{.end}
</ul>
""", default_formatter='html')
# /s//<session>/<partnum>.html
PATH_RE = re.compile(r'/s/(\S+)/(\d+).html$')
def _ListPlugins(root_dir):
"""
Returns a template... | class WaitingRequestHandler(httpd.BaseRequestHandler): |
Based on the snippet: <|code_start|>"Style Guide". Things plugins should do:
- check size of file (whether in bytes, entries, depth, etc.)
- small: just display it inline (and possibly summary)
- large: display summary, then click through to full view
- huge: display summary, and message that says it's too big ... | log = util.Logger(util.ANSI_GREEN) |
Given snippet: <|code_start|>class Resources(object):
def __init__(self, package_dir=None):
self.package_dir = util.GetPackageDir()
self.user_dir = util.GetUserDir()
def GetPluginBin(self, file_type):
# plugins dir is parallel to webpipe python dir.
u = os.path.join(self.user_dir, 'plugins', file_t... | spy_client = spy.GetClientFromConfig() |
Given the following code snippet before the placeholder: <|code_start|> log('received header %r', header)
next_part = header.get('nextPart')
if next_part is not None:
if isinstance(next_part, int):
waiter.SetCounter(next_part)
log('received counter state in header: %d', next_part)
else:
... | s = httpd.ThreadedHTTPServer(('', opts.port), handler_class) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
#
# Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd
"""
webpipe.py
Server that recei... | log = util.Logger(util.ANSI_BLUE) |
Given snippet: <|code_start|> # Write index.html in the session dir.
package_dir = util.GetPackageDir()
path = os.path.join(package_dir, 'webpipe/index.html')
with open(path) as f:
index_html = f.read()
out_path = os.path.join(scroll_path, 'index.html')
with open(out_path, 'w') as f:
... | spy_client = spy.GetClientFromConfig() |
Predict the next line after this snippet: <|code_start|>
def test_load_json_from_url() -> None:
url = "https://raw.githubusercontent.com/statsbomb/open-data/master/data/events/15946.json"
result = _remoteloadjson(url)
assert isinstance(result, list)
assert isinstance(result[0], dict)
def test_load_j... | result = _localloadjson(os.path.join(data_dir, "events", "15946.json")) |
Predict the next line for this snippet: <|code_start|>class StatsBombGameSchema(GameSchema):
"""Definition of a dataframe containing a list of games."""
competition_stage: Series[str]
"""The name of the phase of the competition this game is in."""
home_score: Series[int]
"""The final score of the h... | class StatsBombEventSchema(EventSchema): |
Predict the next line after this snippet: <|code_start|>"""SPADL schema for StatsBomb data."""
class StatsBombCompetitionSchema(CompetitionSchema):
"""Definition of a dataframe containing a list of competitions and seasons."""
country_name: Series[str]
"""The name of the country the competition relates... | class StatsBombGameSchema(GameSchema): |
Here is a snippet: <|code_start|>"""SPADL schema for StatsBomb data."""
class StatsBombCompetitionSchema(CompetitionSchema):
"""Definition of a dataframe containing a list of competitions and seasons."""
country_name: Series[str]
"""The name of the country the competition relates to."""
competition... | class StatsBombPlayerSchema(PlayerSchema): |
Continue the code snippet: <|code_start|> competition_gender: Series[str]
"""The gender of the players competing in the competition."""
class StatsBombGameSchema(GameSchema):
"""Definition of a dataframe containing a list of games."""
competition_stage: Series[str]
"""The name of the phase of the ... | class StatsBombTeamSchema(TeamSchema): |
Next line prediction: <|code_start|>
home_score: Optional[Series[int]]
"""The final score of the home team."""
away_score: Optional[Series[int]]
"""The final score of the away team."""
duration: Optional[Series[int]]
"""The total duration of the game in minutes."""
referee: Optional[Series[s... | class OptaEventSchema(EventSchema): |
Based on the snippet: <|code_start|>"""SPADL schema for Opta data."""
class OptaCompetitionSchema(CompetitionSchema):
"""Definition of a dataframe containing a list of competitions and seasons."""
class OptaGameSchema(GameSchema):
"""Definition of a dataframe containing a list of games."""
home_score... | class OptaPlayerSchema(PlayerSchema): |
Here is a snippet: <|code_start|>
class OptaGameSchema(GameSchema):
"""Definition of a dataframe containing a list of games."""
home_score: Optional[Series[int]]
"""The final score of the home team."""
away_score: Optional[Series[int]]
"""The final score of the away team."""
duration: Optional... | class OptaTeamSchema(TeamSchema): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""Implements the formula of the VAEP framework."""
def _prev(x: pd.Series) -> pd.Series:
prev_x = x.shift(1)
prev_x[:1] = x.values[0]
return prev_x
_samephase_nb: int = 10
def offensive_value(
<|code_end|>
, generate the next line using t... | actions: DataFrame[SPADLSchema], scores: Series[float], concedes: Series[float] |
Continue the code snippet: <|code_start|> # venue=?
# attendance=?
# home_manager=?
# away_manager=?
)
return {game_id: game_dict}
def extract_events(self) -> Dict[Tuple[int, int], Dict[str, Any]]:
"""Return a dictionary with all available even... | end_x = _get_end_x(qualifiers) or start_x |
Continue the code snippet: <|code_start|> # attendance=?
# home_manager=?
# away_manager=?
)
return {game_id: game_dict}
def extract_events(self) -> Dict[Tuple[int, int], Dict[str, Any]]:
"""Return a dictionary with all available events.
Returns
... | end_y = _get_end_y(qualifiers) or start_y |
Predict the next line for this snippet: <|code_start|>"""XML parser for Opta F24 feeds."""
class F24XMLParser(OptaXMLParser):
"""Extract data from a Opta F24 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_doc(self) -> objectify.ObjectifiedElement:... | game_id = int(assertget(attr, 'id')) |
Predict the next line for this snippet: <|code_start|> Parameters
----------
path : str
Path of the data file.
competition_id : int
ID of the competition to which the provided data file belongs. If
None, this information is extracted from a field 'competition_id' in
the JS... | raise MissingDataError( |
Next line prediction: <|code_start|>"""JSON parser for WhoScored feeds."""
def _position_mapping(formation: str, x: float, y: float) -> str:
if x == 0 and y == 5:
return "GK"
return "Unknown"
<|code_end|>
. Use current file imports:
(import json # type: ignore
import re
from datetime import datet... | class WhoScoredParser(OptaParser): |
Next line prediction: <|code_start|> # info.
# age=int(p["age"]),
# height=float(p.get("height", float("NaN"))),
# weight=float(p.get("weight", float("NaN"))),
)
return players
def extract_events(self) -> Dict[Tu... | end_x = attr.get("endX") or _get_end_x(qualifiers) or start_x |
Next line prediction: <|code_start|> # age=int(p["age"]),
# height=float(p.get("height", float("NaN"))),
# weight=float(p.get("weight", float("NaN"))),
)
return players
def extract_events(self) -> Dict[Tuple[int, int], Dict[str, Any... | end_y = attr.get("endY") or _get_end_y(qualifiers) or start_y |
Given snippet: <|code_start|> """Extract data from a JSON data stream scraped from WhoScored.
Parameters
----------
path : str
Path of the data file.
competition_id : int
ID of the competition to which the provided data file belongs. If
None, this information is extracted fro... | competition_id = int(assertget(self.root, "competition_id")) |
Based on the snippet: <|code_start|>"""JSON parser for Stats Perform MA1 feeds."""
class MA1JSONParser(OptaJSONParser):
"""Extract data from a Stats Perform MA1 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_matches(self) -> List[Dict[str, Any]]:
... | raise MissingDataError |
Predict the next line for this snippet: <|code_start|>
class MA1JSONParser(OptaJSONParser):
"""Extract data from a Stats Perform MA1 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_matches(self) -> List[Dict[str, Any]]:
if 'matchInfo' in self.... | return assertget(obj, "name") |
Given snippet: <|code_start|> """
def _get_doc(self) -> objectify.ObjectifiedElement:
optadocument = self.root.find('SoccerDocument')
return optadocument
def _get_stats(self, obj: objectify.ObjectifiedElement) -> Dict[str, Any]:
stats = {}
for stat in obj.find('Stat'):
... | season_id = int(assertget(stats, 'season_id')) |
Here is a snippet: <|code_start|>"""Configuration for pytest."""
def pytest_configure(config: Config) -> None:
"""Pytest configuration hook."""
config.addinivalue_line("markers", "e2e: mark as end-to-end test.")
@pytest.fixture(scope='session')
def spadl_actions() -> DataFrame[SPADLSchema]:
json_file ... | def atomic_spadl_actions() -> DataFrame[AtomicSPADLSchema]: |
Next line prediction: <|code_start|>"""Configuration for pytest."""
def pytest_configure(config: Config) -> None:
"""Pytest configuration hook."""
config.addinivalue_line("markers", "e2e: mark as end-to-end test.")
@pytest.fixture(scope='session')
<|code_end|>
. Use current file imports:
(import os
impor... | def spadl_actions() -> DataFrame[SPADLSchema]: |
Based on the snippet: <|code_start|> a "remote" getter are::
{
'competitions': 'competitions',
'seasons': 'competitions/{season_id}/seasons',
'games': 'seasons/{season_id}/matches',
'events': 'matches/{game_id}/events'
}
... | self.get = _remoteloadjson |
Continue the code snippet: <|code_start|>
@pytest.fixture
def test_goal_df() -> pd.DataFrame:
return pd.DataFrame(
[spadlconfig.actiontypes.index('shot'), spadlconfig.actiontypes.index('goal')],
columns=['type_id'],
)
def test_atomic_goal_from_shot_label(test_goal_df: pd.DataFrame) -> None:
... | model = AtomicVAEP(nb_prev_actions=1) |
Using the snippet: <|code_start|> [spadlconfig.actiontypes.index('shot'), spadlconfig.actiontypes.index('goal')],
columns=['type_id'],
)
def test_atomic_goal_from_shot_label(test_goal_df: pd.DataFrame) -> None:
assert (lab.goal_from_shot(test_goal_df) == pd.DataFrame([[True], [False]], columns=... | expected_features = set(fs.feature_column_names(model.xfns, model.nb_prev_actions)) |
Here is a snippet: <|code_start|>"""JSON parser for Opta F9 feeds."""
class F9JSONParser(OptaJSONParser):
"""Extract data from a Opta F9 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_feed(self) -> Dict[str, Any]:
for node in self.root:
... | raise MissingDataError |
Predict the next line after this snippet: <|code_start|>"""JSON parser for Opta F9 feeds."""
class F9JSONParser(OptaJSONParser):
"""Extract data from a Opta F9 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_feed(self) -> Dict[str, Any]:
for... | data = assertget(f9, "data") |
Given snippet: <|code_start|>"""JSON parser for Opta F1 feeds."""
class F1JSONParser(OptaJSONParser):
"""Extract data from a Opta F1 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_feed(self) -> Dict[str, Any]:
for node in self.root:
... | raise MissingDataError |
Given snippet: <|code_start|>"""JSON parser for Opta F1 feeds."""
class F1JSONParser(OptaJSONParser):
"""Extract data from a Opta F1 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_feed(self) -> Dict[str, Any]:
for node in self.root:
... | data = assertget(f1, 'data') |
Predict the next line for this snippet: <|code_start|> model.save_model(str(p))
model.xT = np.zeros((model.w, model.l))
with pytest.raises(NotFittedError):
model.save_model(str(p))
def test_save_model_file_exists(self, tmp_path: Path) -> None:
"""It should raise an ex... | def test_get_move_actions(spadl_actions: DataFrame[SPADLSchema]) -> None: |
Using the snippet: <|code_start|>
class TestGridCount:
"""Tests for counting the number of actions occuring in each grid cell.
Grid cells ares represented by 2D pitch coordinates. The (0,0) coordinate
corresponds to the bottom left corner of the pitch. The 2D coordinates are
mapped to a flat index. ... | x = Series[float]([0, field_length / 2 - 1, field_length]) |
Given the code snippet: <|code_start|>
class TestGridCount:
"""Tests for counting the number of actions occuring in each grid cell.
Grid cells ares represented by 2D pitch coordinates. The (0,0) coordinate
corresponds to the bottom left corner of the pitch. The 2D coordinates are
mapped to a flat in... | y = Series[float]([0, field_width / 2 + 1, field_width]) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""Implements the formula of the Atomic-VAEP framework."""
def _prev(x: pd.Series) -> pd.Series:
prev_x = x.shift(1)
prev_x[:1] = x.values[0]
return prev_x
def offensive_value(
<|code_end|>
, determine the next line of code. You have ... | actions: DataFrame[AtomicSPADLSchema], scores: Series[float], concedes: Series[float]
|
Continue the code snippet: <|code_start|> """It raises an error upon initialization of a remote loader if statsbombpy is not installed."""
with pytest.raises(ImportError):
sb.StatsBombLoader(getter="remote")
# Test competitions ##########################################################
de... | with pytest.raises(ParseError): |
Predict the next line after this snippet: <|code_start|>
def test_load_local_missing_root() -> None:
"""It raises an error if the root is not provided when loading local data."""
with pytest.raises(ValueError):
sb.StatsBombLoader(getter="local")
class TestWithoutStatsBombPy(unittest.TestCase):
def... | StatsBombCompetitionSchema.validate(df_competitions) |
Next line prediction: <|code_start|> df_players = SBL.players(7584)
assert len(df_players) == 26
StatsBombPlayerSchema.validate(df_players)
def test_no_players(tmpdir: local) -> None:
"""It raises an error when no lineups are available for both teams."""
p = tmpdir.mkdir("lineups").join("7584.json"... | StatsBombEventSchema.validate(df_events) |
Based on the snippet: <|code_start|> assert len(df_competitions) > 0
StatsBombCompetitionSchema.validate(df_competitions)
def test_no_competitions(tmpdir: local) -> None:
"""It returns an empty DataFrame when no competitions are available."""
p = tmpdir.join("competitions.json")
p.write(json.dumps(... | StatsBombGameSchema.validate(df_games) |
Given snippet: <|code_start|> df_teams = SBL.teams(7584)
assert len(df_teams) == 2
StatsBombTeamSchema.validate(df_teams)
def test_no_teams(tmpdir: local) -> None:
"""It raises an error when no lineups are available for each team."""
p = tmpdir.mkdir("lineups").join("7584.json")
p.write(json.du... | StatsBombPlayerSchema.validate(df_players) |
Given the following code snippet before the placeholder: <|code_start|> assert len(df_games) == 64
StatsBombGameSchema.validate(df_games)
def test_no_games(tmpdir: local) -> None:
"""It returns an empty DataFrame when no games are available."""
p = tmpdir.mkdir("matches").mkdir("11").join("1.json")
... | StatsBombTeamSchema.validate(df_teams) |
Based on the snippet: <|code_start|>"""JSON parser for Stats Perform MA3 feeds."""
class MA3JSONParser(OptaJSONParser):
"""Extract data from a Stats Perform MA3 data stream.
Parameters
----------
path : str
Path of the data file.
"""
_position_map = {
1: "Goalkeeper",
... | raise MissingDataError |
Given the following code snippet before the placeholder: <|code_start|> # Fields required by the opta schema
"starting_position": self._position_map.get(
player.starting_position_id, "Unknown"
),
}
return players
... | end_x = _get_end_x(qualifiers) or start_x |
Predict the next line for this snippet: <|code_start|> "starting_position": self._position_map.get(
player.starting_position_id, "Unknown"
),
}
return players
def extract_events(self) -> Dict[Tuple[str, int], Dict[str, Any]]:
... | end_y = _get_end_y(qualifiers) or start_y |
Continue the code snippet: <|code_start|> """
_position_map = {
1: "Goalkeeper",
2: "Defender",
3: "Midfielder",
4: "Forward",
5: "Substitute",
}
def _get_match_info(self) -> Dict[str, Any]:
if "matchInfo" in self.root:
return self.root["match... | season = assertget(match_info, "tournamentCalendar") |
Next line prediction: <|code_start|>"""JSON parser for Opta F24 feeds."""
class F24JSONParser(OptaJSONParser):
"""Extract data from a Opta F24 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_doc(self) -> Dict[str, Any]:
for node in self.root... | raise MissingDataError |
Next line prediction: <|code_start|> return game_dict
def extract_events(self) -> Dict[Tuple[int, int], Dict[str, Any]]:
"""Return a dictionary with all available events.
Returns
-------
dict
A mapping between (game ID, event ID) tuples and the information
... | end_x = _get_end_x(qualifiers) or start_x |
Continue the code snippet: <|code_start|>
def extract_events(self) -> Dict[Tuple[int, int], Dict[str, Any]]:
"""Return a dictionary with all available events.
Returns
-------
dict
A mapping between (game ID, event ID) tuples and the information
available abou... | end_y = _get_end_y(qualifiers) or start_y |
Using the snippet: <|code_start|>"""JSON parser for Opta F24 feeds."""
class F24JSONParser(OptaJSONParser):
"""Extract data from a Opta F24 data stream.
Parameters
----------
path : str
Path of the data file.
"""
def _get_doc(self) -> Dict[str, Any]:
for node in self.root:
... | data = assertget(f24, 'data') |
Predict the next line after this snippet: <|code_start|> x : pd.Series
The x-coordinates of the actions.
y : pd.Series
The y-coordinates of the actions.
l : int
Amount of grid cells in the x-dimension of the grid.
w : int
Amount of grid cells in the y-dimension of the grid... | actions: DataFrame[SPADLSchema], l: int = N, w: int = M |
Next line prediction: <|code_start|>"""SPADL schema for Wyscout data."""
class WyscoutCompetitionSchema(CompetitionSchema):
"""Definition of a dataframe containing a list of competitions and seasons."""
country_name: Series[str]
competition_gender: Series[str]
class WyscoutGameSchema(GameSchema):
... | class WyscoutEventSchema(EventSchema): |
Given snippet: <|code_start|>"""SPADL schema for Wyscout data."""
class WyscoutCompetitionSchema(CompetitionSchema):
"""Definition of a dataframe containing a list of competitions and seasons."""
country_name: Series[str]
competition_gender: Series[str]
<|code_end|>
, continue by predicting the next l... | class WyscoutGameSchema(GameSchema): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.