uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7db49a6a75d1819cf99f86aa | train | function | def default():
return '''THE SHIPYARD COMMAND
The base shipyard command supports options that determine cross-CLI behaviors.
FORMAT
shipyard [--context-marker=<uuid>] [--os_{various}=<value>]
[--debug/--no-debug] [--output-format] <subcommands>
Please Note: --os_auth_url is required for every command except s... | def default():
| return '''THE SHIPYARD COMMAND
The base shipyard command supports options that determine cross-CLI behaviors.
FORMAT
shipyard [--context-marker=<uuid>] [--os_{various}=<value>]
[--debug/--no-debug] [--output-format] <subcommands>
Please Note: --os_auth_url is required for every command except shipyard help
... | # 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
# limitations under the License.
def ... | 64 | 64 | 113 | 3 | 61 | att-comdev/shipyard | src/bin/shipyard_client/shipyard_client/cli/help/output.py | Python | default | default | 16 | 30 | 16 | 16 | 90088177c2801a89cc5027361fe247a0b778c743 | bigcode/the-stack | train |
44ca5e73253d24ffd409bc20 | train | function | def actions():
return '''ACTIONS
The workflow actions that may be invoked using Shipyard
deploy_site: Triggers the initial deployment of a site using the latest
committed configuration documents.
update_site: Triggers the initial deployment of a site, using the latest
committed configura... | def actions():
| return '''ACTIONS
The workflow actions that may be invoked using Shipyard
deploy_site: Triggers the initial deployment of a site using the latest
committed configuration documents.
update_site: Triggers the initial deployment of a site, using the latest
committed configuration documents.... | /--no-debug] [--output-format] <subcommands>
Please Note: --os_auth_url is required for every command except shipyard help
<topic>.
TOPICS
For information of the following topics, run shipyard help <topic>
actions
configdocs'''
def actions():
| 63 | 64 | 93 | 3 | 60 | att-comdev/shipyard | src/bin/shipyard_client/shipyard_client/cli/help/output.py | Python | actions | actions | 33 | 46 | 33 | 33 | e5441ca5df960774859017f741937562b3eff1e8 | bigcode/the-stack | train |
ef96b5118ecdb089b00752ca | train | class | class TestWriteXdrcol(unittest.TestCase):
"""
Test the Drawing _write_col() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_col(self):
"""Test the _write_col() method"""
self.d... | class TestWriteXdrcol(unittest.TestCase):
| """
Test the Drawing _write_col() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_col(self):
"""Test the _write_col() method"""
self.drawing._write_col(4)
exp = """<xd... | Writer.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
import unittest
from io import StringIO
from ...drawing import Drawing
class TestWriteXdrcol(unittest.TestCase):
| 64 | 64 | 120 | 10 | 53 | hugovk/XlsxWriter | xlsxwriter/test/drawing/test_write_col.py | Python | TestWriteXdrcol | TestWriteXdrcol | 14 | 33 | 14 | 14 | bcd489a90b572a9040851e75f739c6f2a882b144 | bigcode/the-stack | train |
845bb8139c7ed09590796945 | train | function | def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
cities_temperature = pd.read_csv(file... | def load_data(filename: str) -> pd.DataFrame:
| """
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
cities_temperature = pd.read_csv(filename, parse_dates=["Date"]).dropna().drop_dupl... |
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
def load_data(filename: str) -> pd.DataFrame:
| 71 | 71 | 237 | 12 | 59 | talazulay27/IML.HUJI | exercises/city_temperature_prediction.py | Python | load_data | load_data | 19 | 43 | 19 | 19 | a1dcf66cb0e1c87413f8edf7733fa8f8e9d1eb96 | bigcode/the-stack | train |
66c27fa0f2e0e4b32432eb4b | train | function | def iter_source_code(paths: Iterable[str], config: Config, skipped: List[str]) -> Iterator[str]:
"""Iterate over all Python source files defined in paths."""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path, topdown=True, followlinks=True):
... | def iter_source_code(paths: Iterable[str], config: Config, skipped: List[str]) -> Iterator[str]:
| """Iterate over all Python source files defined in paths."""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path, topdown=True, followlinks=True):
base_path = Path(dirpath)
for dirname in list(dirnames):
... | return SortAttempt(result.incorrectly_sorted, result.skipped)
except OSError as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
def iter_source_code(paths: Iterable[str], config: Config, skipped: List[str]) -> Iterator[str]:
| 64 | 64 | 160 | 22 | 41 | tegkhanna/isort | isort/main.py | Python | iter_source_code | iter_source_code | 81 | 99 | 81 | 81 | 57d4b4399b4c512088e3eab5fcfee0ca136cf73f | bigcode/the-stack | train |
74b3449e81b33978d3ebe29b | train | function | def is_python_file(path: str) -> bool:
_root, ext = os.path.splitext(path)
if ext in SUPPORTED_EXTENSIONS:
return True
if ext in (".pex",):
return False
# Skip editor backup files.
if path.endswith("~"):
return False
try:
if stat.S_ISFIFO(os.stat(path).st_mode):... | def is_python_file(path: str) -> bool:
| _root, ext = os.path.splitext(path)
if ext in SUPPORTED_EXTENSIONS:
return True
if ext in (".pex",):
return False
# Skip editor backup files.
if path.endswith("~"):
return False
try:
if stat.S_ISFIFO(os.stat(path).st_mode):
return False
except OS... | if imports are correctly sorted within this project.
`isort --help` - In-depth information about isort's available command-line options.
Visit https://timothycrosley.github.io/isort/ for complete information about how to use isort.
"""
def is_python_file(path: str) -> bool:
| 64 | 64 | 138 | 11 | 53 | tegkhanna/isort | isort/main.py | Python | is_python_file | is_python_file | 40 | 63 | 40 | 40 | 3a6e4a1e66fb83c600ceea627c74f8851f412355 | bigcode/the-stack | train |
bf0340aa31d638128c60e967 | train | class | class SortAttempt:
def __init__(self, incorrectly_sorted: bool, skipped: bool) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
| class SortAttempt:
| def __init__(self, incorrectly_sorted: bool, skipped: bool) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
| ).st_mode):
return False
except OSError:
pass
try:
with open(path, "rb") as fp:
line = fp.readline(100)
except OSError:
return False
else:
return bool(shebang_re.match(line))
class SortAttempt:
| 64 | 64 | 40 | 4 | 60 | tegkhanna/isort | isort/main.py | Python | SortAttempt | SortAttempt | 66 | 69 | 66 | 66 | 991c7070823d2ca95cd1131ee3b5a015ace43f46 | bigcode/the-stack | train |
377f557ece071f3caab23a37 | train | function | def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]:
parser = argparse.ArgumentParser(
description="Sort Python import definitions alphabetically "
"within logical sections. Run with no arguments to run "
"interactively. Run with `-` as the first argument to read from "
... | def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]:
| parser = argparse.ArgumentParser(
description="Sort Python import definitions alphabetically "
"within logical sections. Run with no arguments to run "
"interactively. Run with `-` as the first argument to read from "
"stdin. Otherwise provide a list of files to sort."
)
inli... |
def sort_imports(file_name: str, **arguments: Any) -> Optional[SortAttempt]:
try:
result = SortImports(file_name, **arguments)
return SortAttempt(result.incorrectly_sorted, result.skipped)
except OSError as error:
warn(f"Unable to parse file {file_name} due to {error}")
return... | 256 | 256 | 3,004 | 19 | 236 | tegkhanna/isort | isort/main.py | Python | parse_args | parse_args | 102 | 526 | 102 | 102 | 2a23cfd2adcc550481824d3d88e37ee9054527a6 | bigcode/the-stack | train |
bc63060d925cb8dfa7c559eb | train | function | def main(argv: Optional[Sequence[str]] = None) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
sp = arguments["settings_path"]
argume... | def main(argv: Optional[Sequence[str]] = None) -> None:
| arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
sp = arguments["settings_path"]
arguments["settings_path"] = (
os.path.abspath(sp)... | }) will be used.",
)
parser.add_argument(
"--profile",
dest="profile",
choices=list(profiles.keys()),
type=str,
help="Base profile type to use for configuration.",
)
parser.add_argument(
"--interactive",
dest="ask_to_apply",
action="store_t... | 249 | 249 | 833 | 15 | 233 | tegkhanna/isort | isort/main.py | Python | main | main | 529 | 641 | 529 | 529 | c4c88a8000989df603fb83a0ece268133c6ea6b5 | bigcode/the-stack | train |
efeaeb6131e205ec6badb160 | train | function | def sort_imports(file_name: str, **arguments: Any) -> Optional[SortAttempt]:
try:
result = SortImports(file_name, **arguments)
return SortAttempt(result.incorrectly_sorted, result.skipped)
except OSError as error:
warn(f"Unable to parse file {file_name} due to {error}")
return No... | def sort_imports(file_name: str, **arguments: Any) -> Optional[SortAttempt]:
| try:
result = SortImports(file_name, **arguments)
return SortAttempt(result.incorrectly_sorted, result.skipped)
except OSError as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
| _re.match(line))
class SortAttempt:
def __init__(self, incorrectly_sorted: bool, skipped: bool) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
def sort_imports(file_name: str, **arguments: Any) -> Optional[SortAttempt]:
| 64 | 64 | 76 | 20 | 43 | tegkhanna/isort | isort/main.py | Python | sort_imports | sort_imports | 72 | 78 | 72 | 72 | e202c187b333fa0e323f33832d9805d324fe3e31 | bigcode/the-stack | train |
9ce0fa5d22b526f9482f112b | train | class | class GEOSCoordSeq(GEOSBase):
"The internal representation of a list of coordinates inside a Geometry."
ptr_type = CS_PTR
def __init__(self, ptr, z=False):
"Initializes from a GEOS pointer."
if not isinstance(ptr, CS_PTR):
raise TypeError('Coordinate sequence should initialize ... | class GEOSCoordSeq(GEOSBase):
| "The internal representation of a list of coordinates inside a Geometry."
ptr_type = CS_PTR
def __init__(self, ptr, z=False):
"Initializes from a GEOS pointer."
if not isinstance(ptr, CS_PTR):
raise TypeError('Coordinate sequence should initialize with a CS_PTR.')
self.... | """
This module houses the GEOSCoordSeq object, which is used internally
by GEOSGeometry to house the actual coordinates of the Point,
LineString, and LinearRing geometries.
"""
from ctypes import byref, c_double, c_uint
from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.base import... | 129 | 256 | 1,170 | 9 | 119 | ecrespo/django_kanban-agile | kanban/lib/python2.7/site-packages/django/contrib/gis/geos/coordseq.py | Python | GEOSCoordSeq | GEOSCoordSeq | 15 | 163 | 15 | 15 | cab160aaeb254d4f4582c12b49356a1c100ce49b | bigcode/the-stack | train |
dce3337686ae0bfe5bdc0a79 | train | function | def maior(*num):
cont = maior = 0
print('-=' * 30)
print('Analisando os valores passados...')
for valor in num:
print(f'{valor} ', end='')
sleep(0.5)
if cont == 0:
maior = valor
else:
if valor > maior:
maior = valor
cont += ... | def maior(*num):
| cont = maior = 0
print('-=' * 30)
print('Analisando os valores passados...')
for valor in num:
print(f'{valor} ', end='')
sleep(0.5)
if cont == 0:
maior = valor
else:
if valor > maior:
maior = valor
cont += 1
print(f'For... | # Faça um programa que tenha uma função chamada maior(), que
# receba varios parametros com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o maior.
from time import sleep
def maior(*num):
| 50 | 64 | 114 | 5 | 44 | EduardoMachadoCostaOliveira/Python | CEV/ex099.py | Python | maior | maior | 7 | 21 | 7 | 7 | 9b49ffa4a73f92009770c3f9464bb522f9c004c0 | bigcode/the-stack | train |
08d89056a62b5f0e25c84d6e | train | function | def test_json_data_to_pdtable():
""" ensure dict-obj to pdtable conversion
compare to target created w. make_table(List[List]])
"""
# Make a table using the cell grid parser
lines_target = [
["**farm_types1"],
["your_farm my_farm farms_galore"],
["species", "num", "flt", ... | def test_json_data_to_pdtable():
| """ ensure dict-obj to pdtable conversion
compare to target created w. make_table(List[List]])
"""
# Make a table using the cell grid parser
lines_target = [
["**farm_types1"],
["your_farm my_farm farms_galore"],
["species", "num", "flt", "log"],
["text", "-", "kg... | None, 2.0]},
"flt": {"unit": "kg",
"values": [3.0, 39.0, None, None, 200.0, 9.0]},
"log": {"unit": "onoff",
"values": [True, False, True, False, True, False]}
},
"destinations": {"your_farm": None, "my_farm": None, "farms_galore": None}
}
# fmt: o... | 148 | 148 | 496 | 8 | 140 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_json_data_to_pdtable | test_json_data_to_pdtable | 76 | 121 | 76 | 76 | 1c127f269b7bb60996d99baab5047ba1e3acda0c | bigcode/the-stack | train |
61f2395bcf68148986b1dc96 | train | class | class custom_test_fixer(ParseFixer):
def __init__(self):
ParseFixer.__init__(self)
self.stop_on_errors = False
self._called_from_test = True
| class custom_test_fixer(ParseFixer):
| def __init__(self):
ParseFixer.__init__(self)
self.stop_on_errors = False
self._called_from_test = True
| ParseFixer
from pdtable.io import json_data_to_table, table_to_json_data
from pdtable.io._json import to_json_serializable
from pdtable.io.parsers import parse_blocks
from pdtable.io.parsers.blocks import make_table, make_table_json_data
class custom_test_fixer(ParseFixer):
| 64 | 64 | 42 | 9 | 54 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | custom_test_fixer | custom_test_fixer | 16 | 20 | 16 | 16 | fe53fe1284430c054a5b05921bd55ff38cbf816e | bigcode/the-stack | train |
a9c92f8f9e1634c46a3684e6 | train | function | def input_dir() -> Path:
return Path(__file__).parent / "input/with_errors"
| def input_dir() -> Path:
| return Path(__file__).parent / "input/with_errors"
| from pdtable.io.parsers.blocks import make_table, make_table_json_data
class custom_test_fixer(ParseFixer):
def __init__(self):
ParseFixer.__init__(self)
self.stop_on_errors = False
self._called_from_test = True
def input_dir() -> Path:
| 64 | 64 | 21 | 7 | 56 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | input_dir | input_dir | 23 | 24 | 23 | 23 | da17315f3dc84d3188b70513382a8c6b143df810 | bigcode/the-stack | train |
b144ce2506ab313e8b36101a | train | function | def test_json_pdtable():
""" ensure dict-obj to pdtable conversion
compare to target created w. read_stream_csv
"""
cell_rows = [
line.split(";")
for line in dedent(
"""\
**farm_types1;;;
your_farm my_farm farms_galore;;;
species; num; flt; lo... | def test_json_pdtable():
| """ ensure dict-obj to pdtable conversion
compare to target created w. read_stream_csv
"""
cell_rows = [
line.split(";")
for line in dedent(
"""\
**farm_types1;;;
your_farm my_farm farms_galore;;;
species; num; flt; log;
text; -;... |
from textwrap import dedent
import numpy as np
import pandas as pd
from pdtable import BlockType, ParseFixer
from pdtable.io import json_data_to_table, table_to_json_data
from pdtable.io._json import to_json_serializable
from pdtable.io.parsers import parse_blocks
from pdtable.io.parsers.blocks import make_table, ma... | 149 | 149 | 498 | 6 | 143 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_json_pdtable | test_json_pdtable | 27 | 73 | 27 | 27 | d62e0b075d1e8944c2ca8085a5a01df2301b3ed1 | bigcode/the-stack | train |
67ae7263000820af011d4fe7 | train | function | def test_make_table_json_data__empty_table():
""" tests reading in an empty table (ie no rows) to a jsondata object
and creating a table via that json using json_data_to_table
"""
lines_target = [
["**farm_types1"],
["your_farm my_farm farms_galore"],
["species", "num", "flt", "l... | def test_make_table_json_data__empty_table():
| """ tests reading in an empty table (ie no rows) to a jsondata object
and creating a table via that json using json_data_to_table
"""
lines_target = [
["**farm_types1"],
["your_farm my_farm farms_galore"],
["species", "num", "flt", "log"],
["text", "-", "kg", "onoff"]
... | [1][1] == 1
assert pdtab.df.iloc[2][4] == 4
assert pandas_pdtab.equals(pdtab)
# now verify from json-string
jstr = json.dumps(js_obj)
js_obj_from_json = json.loads(jstr)
pdtab_from_json = json_data_to_table(js_obj_from_json)
assert pandas_pdtab.equals(pdtab_from_json)
def test_make_table_j... | 97 | 97 | 325 | 10 | 87 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_make_table_json_data__empty_table | test_make_table_json_data__empty_table | 228 | 261 | 228 | 228 | b95248cbd413fa28d5b8b08c74a208e65ebf179b | bigcode/the-stack | train |
b16296affd9244ef2029c2b0 | train | function | def test_to_json_serializable():
""" Unit test pure_json_obj / json_esc
"""
obj = {
"k1": r'k1 w. \"quotes"',
"nix": None,
"no-flt": np.nan,
"no-date": pd.NaT,
"flt": 1.23,
"int": 123,
}
js_obj = to_json_serializable(obj)
# verify that js_obj is d... | def test_to_json_serializable():
| """ Unit test pure_json_obj / json_esc
"""
obj = {
"k1": r'k1 w. \"quotes"',
"nix": None,
"no-flt": np.nan,
"no-date": pd.NaT,
"flt": 1.23,
"int": 123,
}
js_obj = to_json_serializable(obj)
# verify that js_obj is directly json serializable
jst... | :
if tp == BlockType.TABLE:
""" compare generic object
i.e. containing None instead of pd.NaT, np.nan &c.
"""
count += 1
assert tt == all_json[fn]
assert count == all_files
def test_to_json_ser... | 64 | 64 | 208 | 7 | 56 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_to_json_serializable | test_to_json_serializable | 167 | 189 | 167 | 167 | 03de3c4c109ebfc88fad7a78bed5419d8e3440e3 | bigcode/the-stack | train |
c68e280251d9a9fb776fe9b6 | train | function | def test_fat():
""" Factory Acceptance Test
Read input files as dictionary objects.
Compare objects to stored target objects (input_dir() / all.json)
"""
all_files = 0
for fn in os.listdir(input_dir()):
path = input_dir() / fn
if not os.path.isfile(path):
co... | def test_fat():
| """ Factory Acceptance Test
Read input files as dictionary objects.
Compare objects to stored target objects (input_dir() / all.json)
"""
all_files = 0
for fn in os.listdir(input_dir()):
path = input_dir() / fn
if not os.path.isfile(path):
continue
i... | fmt: on
table_from_json = json_data_to_table(table_json_data, fixer=custom_test_fixer)
assert table_from_cell_grid.equals(table_from_json)
# Round trip
table_json_data_back = table_to_json_data(table_from_json)
table_from_json_round_trip = json_data_to_table(table_json_data_back, fixer=custom_tes... | 95 | 95 | 319 | 5 | 90 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_fat | test_fat | 124 | 164 | 124 | 124 | 174ddf5b592eac6664d50f442587c2bc1d171fd0 | bigcode/the-stack | train |
30054a7a234e425f1fae1990 | train | function | def test_preserve_column_order():
""" Unit test
Verify that column order is preserved when translating btw. jsondata
and pdtable.Table
"""
# fmt: off
lines_target = [
["**col_order"],
["dst2 dst2 dst2"],
["species" , "a3" , "a2" , "a1" , "a4" ],
["text... | def test_preserve_column_order():
| """ Unit test
Verify that column order is preserved when translating btw. jsondata
and pdtable.Table
"""
# fmt: off
lines_target = [
["**col_order"],
["dst2 dst2 dst2"],
["species" , "a3" , "a2" , "a1" , "a4" ],
["text" , "-" , "-" , "-" , "-"... | directly json serializable
jstr = json.dumps(js_obj)
js_obj_from_json = json.loads(jstr)
assert js_obj_from_json["k1"] == obj["k1"]
assert js_obj_from_json["nix"] is None
assert js_obj_from_json["no-flt"] is None
assert js_obj_from_json["no-date"] is None
assert js_obj_from_json["flt"] == ... | 116 | 117 | 392 | 7 | 109 | vegatheil/pdtable | pdtable/test/io/test_read_csv_json.py | Python | test_preserve_column_order | test_preserve_column_order | 192 | 225 | 192 | 192 | 9dc3cc817eac78fbe9f2d20dba2ec77d4f7dc924 | bigcode/the-stack | train |
ca966103e856ba188140325c | train | class | class MabFileFolderProtectedItem(ProtectedItem):
"""MAB workload-specific backup item.
All required parameters must be populated in order to send to Azure.
:param backup_management_type: Type of backup managemenent for the backed
up item. Possible values include: 'Invalid', 'AzureIaasVM', 'MAB', 'DPM... | class MabFileFolderProtectedItem(ProtectedItem):
| """MAB workload-specific backup item.
All required parameters must be populated in order to send to Azure.
:param backup_management_type: Type of backup managemenent for the backed
up item. Possible values include: 'Invalid', 'AzureIaasVM', 'MAB', 'DPM',
'AzureBackupServer', 'AzureSql', 'AzureSt... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 94 | 256 | 1,174 | 10 | 83 | JonathanGailliez/azure-sdk-for-python | azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/mab_file_folder_protected_item.py | Python | MabFileFolderProtectedItem | MabFileFolderProtectedItem | 15 | 103 | 15 | 15 | b4a1a70ab611965bedb9d68b7cb36c733ba8dc21 | bigcode/the-stack | train |
61dff830dfbcf673b127e03c | train | class | class Command(BaseCommand):
help = 'Remove expire Candidates'
def handle(self, *args, **options):
now = datetime.datetime.now()
# now = timezone.now()
CandidateUserModel.objects.filter(expire_at__lt=now).delete()
| class Command(BaseCommand):
| help = 'Remove expire Candidates'
def handle(self, *args, **options):
now = datetime.datetime.now()
# now = timezone.now()
CandidateUserModel.objects.filter(expire_at__lt=now).delete()
| import datetime
# from django.utils import timezone
from django.core.management.base import BaseCommand
from users.models import CandidateUserModel
class Command(BaseCommand):
| 32 | 64 | 54 | 5 | 26 | OlexandrTopuzov/Data_converter | data_ocean/management/commands/clear_candidate.py | Python | Command | Command | 7 | 13 | 7 | 7 | 24c209adc7e4f1df1ac9b73719f3c3a9e62f2dff | bigcode/the-stack | train |
136c23282f6eba12916a5113 | train | class | class NodesNodeQemuVmidAgentGetTimezoneGetTimezoneAction(ProxmoxAction):
"""
Execute get-timezone.
"""
def run(self, node, vmid, profile_name=None):
super().run(profile_name)
# Only include non None arguments to pass through to proxmox api.
proxmox_kwargs = {}
for api_a... | class NodesNodeQemuVmidAgentGetTimezoneGetTimezoneAction(ProxmoxAction):
| """
Execute get-timezone.
"""
def run(self, node, vmid, profile_name=None):
super().run(profile_name)
# Only include non None arguments to pass through to proxmox api.
proxmox_kwargs = {}
for api_arg in [
["node", node, "string"],
["vmid", vmid, ... | import json
from packlib.base import ProxmoxAction
class NodesNodeQemuVmidAgentGetTimezoneGetTimezoneAction(ProxmoxAction):
| 31 | 72 | 242 | 18 | 12 | nzlosh/stackstorm-proxmox | actions/nodes_node_qemu_vmid_agent_get_timezone.py | Python | NodesNodeQemuVmidAgentGetTimezoneGetTimezoneAction | NodesNodeQemuVmidAgentGetTimezoneGetTimezoneAction | 5 | 30 | 5 | 5 | d56f0f39a397c47081a0830c388d406480ca2ae6 | bigcode/the-stack | train |
fdc3cd54e206400e16e752ca | train | class | class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
| class StagingConfig(Config):
| DEVELOPMENT = True
DEBUG = True
| ):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
| 64 | 64 | 16 | 6 | 57 | pskfry/wowrecruitapi | config.py | Python | StagingConfig | StagingConfig | 14 | 16 | 14 | 14 | 46c04b00aa47cc21f479b49c8bf17173e50a1c75 | bigcode/the-stack | train |
8c4038e049c9efb64a6d82a7 | train | class | class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
| class Config(object):
| DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
| import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
| 19 | 64 | 51 | 4 | 15 | pskfry/wowrecruitapi | config.py | Python | Config | Config | 4 | 9 | 4 | 4 | 0ab125e30cfad8a89dfe35e1f92f340089cd1eb3 | bigcode/the-stack | train |
ffc5fc5e6689a1b3de2c1fec | train | class | class ProductionConfig(Config):
DEBUG = False
| class ProductionConfig(Config):
| DEBUG = False
| .abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
| 64 | 64 | 10 | 5 | 59 | pskfry/wowrecruitapi | config.py | Python | ProductionConfig | ProductionConfig | 11 | 12 | 11 | 11 | 99f1347bd586d6ecfe7232a19d7a9e6fa7047326 | bigcode/the-stack | train |
3114e67b5499cc0cacce46ac | train | class | class TestingConfig(Config):
TESTING = True
| class TestingConfig(Config):
| TESTING = True
| -be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
class TestingConfig(Config):
| 64 | 64 | 11 | 5 | 58 | pskfry/wowrecruitapi | config.py | Python | TestingConfig | TestingConfig | 22 | 23 | 22 | 22 | 833229da3b53177f3aab1e60589191fdf16a0998 | bigcode/the-stack | train |
91bf2fe0c2cc5b02fd8bf444 | train | class | class DevelopmentConfig(Config):
DEVELOPMENT = True
DEBUG = True
| class DevelopmentConfig(Config):
| DEVELOPMENT = True
DEBUG = True
| _ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class ProductionConfig(Config):
DEBUG = False
class StagingConfig(Config):
DEVELOPMENT = True
DEBUG = True
class DevelopmentConfig(Config):
| 64 | 64 | 15 | 5 | 58 | pskfry/wowrecruitapi | config.py | Python | DevelopmentConfig | DevelopmentConfig | 18 | 20 | 18 | 18 | 4b8498e295929f30196aa8b364cc3bddc58a49c0 | bigcode/the-stack | train |
d534735eb552dda5047ffe1d | train | class | class OrthogonalTest(unittest.TestCase):
def __init__(self, *args):
super().__init__(*args)
self.batch_size = 256
self.tol = 1e-4
torch.manual_seed(0)
def test_inverse(self):
return
x = torch.randn(self.batch_size, inp_size)
y = test_net(x)
x_r... | class OrthogonalTest(unittest.TestCase):
| def __init__(self, *args):
super().__init__(*args)
self.batch_size = 256
self.tol = 1e-4
torch.manual_seed(0)
def test_inverse(self):
return
x = torch.randn(self.batch_size, inp_size)
y = test_net(x)
x_re = test_net(y, rev=True)
if torc... | = Node([orthog_layer.out0], PermuteRandom, {'seed':0})
permute_2 = Node([permute_1.out0], HouseholderPerm, {'n_reflections':10})
outp= OutputNode([permute_2.out0], name='output')
test_net = GraphINN([inp, orthog_layer, permute_1, permute_2, outp])
optim = torch.optim.SGD(test_net.parameters(), lr=5e-1)
#for name, p... | 134 | 134 | 448 | 8 | 126 | RussellALA/FrEIA | tests/test_orthogonal_layer.py | Python | OrthogonalTest | OrthogonalTest | 27 | 89 | 27 | 28 | 8eaf05fa803a8fd28ffe2098e9621330b758ca50 | bigcode/the-stack | train |
dd9214451d6684b49c9195d4 | train | function | def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops):
"""
reduces expression by combining powers with similar bases and exponents.
Explanation
===========
If ``deep`` is ``True`` then powsimp() will also simplify arguments of
functions. By default ``deep`` is set to ``F... | def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops):
| """
reduces expression by combining powers with similar bases and exponents.
Explanation
===========
If ``deep`` is ``True`` then powsimp() will also simplify arguments of
functions. By default ``deep`` is set to ``False``.
If ``force`` is ``True`` then bases will be combined without chec... | from collections import defaultdict
from functools import reduce
from sympy.core.function import expand_log, count_ops
from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms
from sympy.core.compatibility import ordered, default_sort_key
from sympy.core.numbers import Integer, Rational... | 158 | 256 | 4,575 | 20 | 137 | gurpartap0306/sympy | sympy/simplify/powsimp.py | Python | powsimp | powsimp | 16 | 485 | 16 | 16 | a4db8b9b790c659fd5e9044d50ab5ce878696921 | bigcode/the-stack | train |
f05e66aa840a76171895a795 | train | function | def _denest_pow(eq):
"""
Denest powers.
This is a helper function for powdenest that performs the actual
transformation.
"""
from sympy.simplify.simplify import logcombine
b, e = eq.as_base_exp()
if b.is_Pow or isinstance(b.func, exp) and e != 1:
new = b._eval_power(e)
... | def _denest_pow(eq):
| """
Denest powers.
This is a helper function for powdenest that performs the actual
transformation.
"""
from sympy.simplify.simplify import logcombine
b, e = eq.as_base_exp()
if b.is_Pow or isinstance(b.func, exp) and e != 1:
new = b._eval_power(e)
if new is not None:
... | )
(n**i)**x
"""
from sympy.simplify.simplify import posify
if force:
def _denest(b, e):
if not isinstance(b, (Pow, exp)):
return b.is_positive, Pow(b, e, evaluate=False)
return _denest(b.base, b.exp*e)
reps = []
for p in eq.atoms(Pow, exp... | 256 | 256 | 1,054 | 7 | 249 | gurpartap0306/sympy | sympy/simplify/powsimp.py | Python | _denest_pow | _denest_pow | 608 | 709 | 608 | 608 | f403a1f54556d6064c500435c121ac159fe2782f | bigcode/the-stack | train |
08e0c5ed6575c4d60d707a23 | train | function | def powdenest(eq, force=False, polar=False):
r"""
Collect exponents on powers as assumptions allow.
Explanation
===========
Given ``(bb**be)**e``, this can be simplified as follows:
* if ``bb`` is positive, or
* ``e`` is an integer, or
* ``|be| < 1`` then this simplifies to... | def powdenest(eq, force=False, polar=False):
| r"""
Collect exponents on powers as assumptions allow.
Explanation
===========
Given ``(bb**be)**e``, this can be simplified as follows:
* if ``bb`` is positive, or
* ``e`` is an integer, or
* ``|be| < 1`` then this simplifies to ``bb**(be*e)``
Given a product of power... | )
# here is a new joined base
new_base = expr.func(*(nonneg + neg))
# if there are positive parts they will just get separated
# again unless some change is made
def _terms(e):
# return the number of terms of this expre... | 256 | 256 | 1,124 | 12 | 244 | gurpartap0306/sympy | sympy/simplify/powsimp.py | Python | powdenest | powdenest | 488 | 603 | 488 | 488 | 4df061fdcfb9211402b1e4730f68252576076020 | bigcode/the-stack | train |
bb3f3a74bb8f2296e2b8169c | train | class | @skipIf(NO_MOCK, NO_MOCK_REASON)
class MacPkgutilTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
return {mac_pkgutil: {}}
def test_install(self):
# Given
source = '/foo/bar/fubar.pkg'
package_id = 'com.foo.fubar.pkg'
# When
with patch... | @skipIf(NO_MOCK, NO_MOCK_REASON)
class MacPkgutilTestCase(TestCase, LoaderModuleMockMixin):
| def setup_loader_modules(self):
return {mac_pkgutil: {}}
def test_install(self):
# Given
source = '/foo/bar/fubar.pkg'
package_id = 'com.foo.fubar.pkg'
# When
with patch('salt.modules.mac_pkgutil.is_installed',
return_value=False):
... | as mac_pkgutil
# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import NO_MOCK, NO_MOCK_REASON, patch
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MacPkgutilTestCase(TestCase, LoaderModuleMockMixin):
| 75 | 75 | 253 | 26 | 48 | byteskeptical/salt | tests/unit/modules/test_mac_pkgutil.py | Python | MacPkgutilTestCase | MacPkgutilTestCase | 15 | 49 | 15 | 17 | c1840a440af8a1e4ec77d29643234824d214613d | bigcode/the-stack | train |
c65ca9fb13b85ece353ffb3e | train | function | def line_intersect(p0, q0, p1, q1):
'''
Intersect two lines: (p0, q0) and (p1, q1). Each should be a 2D
point.
Adapted from http://stackoverflow.com/a/26416320/893113
'''
dy = q0[1] - p0[1]
dx = q0[0] - p0[0]
lhs0 = [-dy, dx]
rhs0 = p0[1] * dx - dy * p0[0]
dy = q1[1] - p1[1]
... | def line_intersect(p0, q0, p1, q1):
| '''
Intersect two lines: (p0, q0) and (p1, q1). Each should be a 2D
point.
Adapted from http://stackoverflow.com/a/26416320/893113
'''
dy = q0[1] - p0[1]
dx = q0[0] - p0[0]
lhs0 = [-dy, dx]
rhs0 = p0[1] * dx - dy * p0[0]
dy = q1[1] - p1[1]
dx = q1[0] - p1[0]
lhs1 = [-d... | - p2)
unit_direction = (p2 - p1) / dist
partition_width = dist / partition_size
domain = partition_width * np.arange(1, partition_size)
return p1 + unit_direction * domain[:, np.newaxis]
def line_intersect(p0, q0, p1, q1):
| 71 | 71 | 239 | 16 | 55 | metabolize/blmath | blmath/geometry/segment.py | Python | line_intersect | line_intersect | 99 | 126 | 99 | 99 | 513bc877101a39f728ddaf0cf65b47ebf8aadc5b | bigcode/the-stack | train |
cfd1fe59f98a5aaa0b540d7b | train | function | def partition_segment(p1, p2, n_samples, endpoint=True):
'''
For two points in n-space, return an np.ndarray of equidistant partition
points along the segment determined by p1 & p2.
The total number of points returned will be n_samples. When n_samples is
2, returns the original points.
When en... | def partition_segment(p1, p2, n_samples, endpoint=True):
| '''
For two points in n-space, return an np.ndarray of equidistant partition
points along the segment determined by p1 & p2.
The total number of points returned will be n_samples. When n_samples is
2, returns the original points.
When endpoint is True, p2 is the last point. When false, p2 is e... | .repeat(v[:-1], partition_size, axis=0)
unitds = np.repeat(unitds, partition_size, axis=0)
filled = points + (unitds * domain)
return np.vstack((filled, v[-1]))
def partition_segment(p1, p2, n_samples, endpoint=True):
| 65 | 65 | 219 | 15 | 50 | metabolize/blmath | blmath/geometry/segment.py | Python | partition_segment | partition_segment | 39 | 64 | 39 | 39 | c92faf04711e85d674e097dfbf2cc503a9dc47e3 | bigcode/the-stack | train |
c4d6563dae45ec29c29ac85a | train | function | def line_intersect3(p0, q0, p1, q1):
'''
Intersect two lines in 3d: (p0, q0) and (p1, q1). Each should be a 3D
point.
See this for a diagram: http://math.stackexchange.com/questions/270767/find-intersection-of-two-3d-lines
'''
e = p0 - q0 # direction of line 0
f = p1 - q1 # direction of line... | def line_intersect3(p0, q0, p1, q1):
| '''
Intersect two lines in 3d: (p0, q0) and (p1, q1). Each should be a 3D
point.
See this for a diagram: http://math.stackexchange.com/questions/270767/find-intersection-of-two-3d-lines
'''
e = p0 - q0 # direction of line 0
f = p1 - q1 # direction of line 1
# Check for special case where... | lhs1 = [-dy, dx]
rhs1 = p1[1] * dx - dy * p1[0]
a = np.array([lhs0,
lhs1])
b = np.array([rhs0,
rhs1])
try:
return np.linalg.solve(a, b)
except np.linalg.LinAlgError:
return np.array([np.nan, np.nan])
def line_intersect3(p0, q0, p1, q1):
| 102 | 102 | 342 | 17 | 85 | metabolize/blmath | blmath/geometry/segment.py | Python | line_intersect3 | line_intersect3 | 128 | 153 | 128 | 128 | c091dd5849c3aa3b1204959240c5c928e4196816 | bigcode/the-stack | train |
70f48677b3237901d56deb7d | train | function | def partition_segment_old(p1, p2, partition_size=5):
'''
Deprecated. Please use partition_segment.
For two points in n-space, return an np.ndarray of partition points at equal widths
determined by 'partition_size' on the interior of the segment determined by p1 & p2.
Accomplished by partitioning t... | def partition_segment_old(p1, p2, partition_size=5):
| '''
Deprecated. Please use partition_segment.
For two points in n-space, return an np.ndarray of partition points at equal widths
determined by 'partition_size' on the interior of the segment determined by p1 & p2.
Accomplished by partitioning the segment into 'partition_size' sub-intervals.
... | elif n_samples < 2:
raise ValueError('partition_size should be bigger than 1.')
return (p2 - p1) * np.linspace(0, 1, num=n_samples, endpoint=endpoint)[:, np.newaxis] + p1
def partition_segment_old(p1, p2, partition_size=5):
| 71 | 71 | 237 | 15 | 55 | metabolize/blmath | blmath/geometry/segment.py | Python | partition_segment_old | partition_segment_old | 66 | 97 | 66 | 66 | ff62e523593f984e0d8c863a6ba175616fe7e10b | bigcode/the-stack | train |
ff339def5281dbef1827cf3d | train | function | def partition(v, partition_size=5):
'''
params:
v:
V x N np.array of points in N-space
partition_size:
how many partitions intervals for each segment?
Fill in the line segments determined by v with equally
spaced points - the space for each segment is determine... | def partition(v, partition_size=5):
| '''
params:
v:
V x N np.array of points in N-space
partition_size:
how many partitions intervals for each segment?
Fill in the line segments determined by v with equally
spaced points - the space for each segment is determined
by the length of the segment a... | import numpy as np
def partition(v, partition_size=5):
| 14 | 73 | 244 | 9 | 4 | metabolize/blmath | blmath/geometry/segment.py | Python | partition | partition | 3 | 37 | 3 | 3 | f786eaa227ddc16c5737c111230c8b5d7bb0ff59 | bigcode/the-stack | train |
08732e7946aeaaa393725a26 | train | function | def generalised_adder(*args):
return sum(args)
| def generalised_adder(*args):
| return sum(args)
| """this is a module doc"""
'''
any python file is a module
convention: file name in lower case
'''
#set values to expose as interface
__all__ = ['generalised_adder']
def adder(x, y):
return x + y
def generalised_adder(*args):
| 64 | 64 | 13 | 8 | 55 | praisetompane/3_programming | 1_languages/python/src/modules/combine/functions/number_funcs.py | Python | generalised_adder | generalised_adder | 14 | 15 | 14 | 14 | a8feb7f1cce913b1f66f2f7f205f94fe86bb1788 | bigcode/the-stack | train |
2f814386b6183dfde178de86 | train | function | def adder(x, y):
return x + y
| def adder(x, y):
| return x + y
| """this is a module doc"""
'''
any python file is a module
convention: file name in lower case
'''
#set values to expose as interface
__all__ = ['generalised_adder']
def adder(x, y):
| 50 | 64 | 13 | 7 | 43 | praisetompane/3_programming | 1_languages/python/src/modules/combine/functions/number_funcs.py | Python | adder | adder | 11 | 12 | 11 | 11 | e87738e27b443a077266dff31d2cced27b684d57 | bigcode/the-stack | train |
b282e878533a5ad082ec782a | train | class | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return head
even_head = head.next
odd, even = head, head.next
while even and even.next:
odd.next, odd = even.next, even.next
even.next, even = odd.next, odd.next
... | class Solution:
| def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return head
even_head = head.next
odd, even = head, head.next
while even and even.next:
odd.next, odd = even.next, even.next
even.next, even = odd.next, odd.next
odd.next = eve... | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
| 28 | 64 | 87 | 3 | 24 | VVKot/leetcode-solutions | leetcode/python/328_odd_even_linked_list.py | Python | Solution | Solution | 8 | 19 | 8 | 9 | 770b15ade05fe09fa74a66ea53eb795a3f8d342a | bigcode/the-stack | train |
c2dcb5b7184b8e90f1616b5d | train | class | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
| class ListNode:
| def __init__(self, x):
self.val = x
self.next = None
| class ListNode:
| 4 | 64 | 25 | 4 | 0 | VVKot/leetcode-solutions | leetcode/python/328_odd_even_linked_list.py | Python | ListNode | ListNode | 1 | 5 | 1 | 2 | 90f5dabfc6b4fc217b017f0d406ace5f7a3cc765 | bigcode/the-stack | train |
60b045dbdd032110b540dd2a | train | class | class BaseGame:
pause = False
frameRate = 60
screen = None
font = None
def __init__(self, width, height, *args, **kwargs):
pygame.init() #pylint: disable=E1101
pygame.display.set_caption('Snake')
pygame.font.init()
self.size = self.width, self.height = width, height
... | class BaseGame:
| pause = False
frameRate = 60
screen = None
font = None
def __init__(self, width, height, *args, **kwargs):
pygame.init() #pylint: disable=E1101
pygame.display.set_caption('Snake')
pygame.font.init()
self.size = self.width, self.height = width, height
self.scr... | import pygame
from core.errors import LoadSceneError
class BaseGame:
| 15 | 99 | 332 | 4 | 10 | kuronosu/ajedrez | core/game.py | Python | BaseGame | BaseGame | 4 | 46 | 4 | 4 | ad0fe017d77b939f615eed930ceccbf7e9fe8e90 | bigcode/the-stack | train |
28770d50e676890bdc02493d | train | class | class BaseScene:
def __init__(self, game, *args, **kwargs):
self.gameObjects = {}
self.game = game
self.screen = game.screen
def start(self): pass
def update(self, events, keys): pass
def draw(self):
for key, value in self.gameObjects.items():
value.draw(... | class BaseScene:
| def __init__(self, game, *args, **kwargs):
self.gameObjects = {}
self.game = game
self.screen = game.screen
def start(self): pass
def update(self, events, keys): pass
def draw(self):
for key, value in self.gameObjects.items():
value.draw()
def ge... | break
self.scene.update(events, pygame.key.get_pressed())
self.scene.draw()
pygame.display.update()
self.clock.tick(self.frameRate)
def quitGame(self):
pygame.quit() #pylint: disable=E1101
self.quitStatus = True
cla... | 64 | 64 | 112 | 4 | 59 | kuronosu/ajedrez | core/game.py | Python | BaseScene | BaseScene | 48 | 63 | 48 | 48 | 002b4c44b741cd8f66c976cc4b569ce3d4e54146 | bigcode/the-stack | train |
f587e8b59db0c8e77b738a62 | train | function | def hash_path(path):
sha256 = subprocess.check_output(["nix", "hash-path", "--base32", "--type", "sha256", path]).strip()
if re.match(r'[0-9a-z]{52}', sha256) == None:
raise ValueError('bad hash %s' % sha256)
return sha256
| def hash_path(path):
| sha256 = subprocess.check_output(["nix", "hash-path", "--base32", "--type", "sha256", path]).strip()
if re.match(r'[0-9a-z]{52}', sha256) == None:
raise ValueError('bad hash %s' % sha256)
return sha256
| above
from __future__ import print_function
import argparse
import json
import os
import re
import shutil
import string
import subprocess
import sys
BASEDIR = "/mnt/cache/chromium"
SKIP_DEPS = [ "src/tools/luci-go" ]
def hash_path(path):
| 64 | 64 | 74 | 5 | 59 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | hash_path | hash_path | 20 | 24 | 20 | 20 | 3a4f299f21005ebeebdeb8fc364d43a2406a781d | bigcode/the-stack | train |
c69356c26cfb65a85228c305 | train | function | def checkout_cipd(package, version, path):
os.makedirs(path)
subprocess.check_call(["cipd", "init", path])
subprocess.check_call(["cipd", "install", "-root", path, package, version])
return hash_path(path)
| def checkout_cipd(package, version, path):
| os.makedirs(path)
subprocess.check_call(["cipd", "init", path])
subprocess.check_call(["cipd", "install", "-root", path, package, version])
return hash_path(path)
| , rev, path):
subprocess.check_call([
"nix-prefetch-git",
"--builder",
"--url", url,
"--out", path,
"--rev", rev,
"--fetch-submodules"])
return hash_path(path)
def checkout_cipd(package, version, path):
| 64 | 64 | 55 | 11 | 53 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | checkout_cipd | checkout_cipd | 36 | 40 | 36 | 36 | 60183a375d3e70e3ed6eb762b27ce54222302791 | bigcode/the-stack | train |
b25bbdda027d0bc74472c8be | train | function | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--target-os', type=str, default=["unix"], action='append')
parser.add_argument('version', nargs='+')
args = parser.parse_args()
for chromium_version in args.version:
make_vendor_file(chromium_version, args.target_os)
| def main():
| parser = argparse.ArgumentParser()
parser.add_argument('--target-os', type=str, default=["unix"], action='append')
parser.add_argument('version', nargs='+')
args = parser.parse_args()
for chromium_version in args.version:
make_vendor_file(chromium_version, args.target_os)
| ${fetchurl {
url = "%(url)s";
sha256 = "%(sha256)s";
}} -C $out
'';
''' % { "path": path, "url": url, "sha256": sha256 })
vendor_nix.write("}\n")
def main():
| 64 | 64 | 67 | 3 | 61 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | main | main | 276 | 283 | 276 | 276 | 360ee0a86a3d5f72e874ccd291c05d8441ee07b5 | bigcode/the-stack | train |
ae14bf8461fea416d0a8a096 | train | function | def nix_str_cipd(path, dep):
def _fetchcipd_str(p):
return 'fetchcipd { package = "%(package)s"; version = "%(version)s"; sha256 = "%(sha256)s"; }' % p
if len(dep['packages']) == 1:
src_str = _fetchcipd_str(dep['packages'][0])
else:
nix_paths = ' \n'.join([ "(%s)" % (_fetchcipd_s... | def nix_str_cipd(path, dep):
| def _fetchcipd_str(p):
return 'fetchcipd { package = "%(package)s"; version = "%(version)s"; sha256 = "%(sha256)s"; }' % p
if len(dep['packages']) == 1:
src_str = _fetchcipd_str(dep['packages'][0])
else:
nix_paths = ' \n'.join([ "(%s)" % (_fetchcipd_str(p),) for p in dep['package... | (sha256)s"; };\n''' % {
"path": '"' + path + '"',
"url": '"' + dep["url"] + '"',
"rev": dep["rev"],
"sha256": dep["sha256"],
}
def nix_str_cipd(path, dep):
| 64 | 64 | 174 | 10 | 54 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | nix_str_cipd | nix_str_cipd | 50 | 64 | 50 | 50 | 01e447a57ad786b9f451097c5150b0f3e0bac6b4 | bigcode/the-stack | train |
dc6152afbc11515462255fb5 | train | function | def checkout_git(url, rev, path):
subprocess.check_call([
"nix-prefetch-git",
"--builder",
"--url", url,
"--out", path,
"--rev", rev,
"--fetch-submodules"])
return hash_path(path)
| def checkout_git(url, rev, path):
| subprocess.check_call([
"nix-prefetch-git",
"--builder",
"--url", url,
"--out", path,
"--rev", rev,
"--fetch-submodules"])
return hash_path(path)
| ", "--base32", "--type", "sha256", path]).strip()
if re.match(r'[0-9a-z]{52}', sha256) == None:
raise ValueError('bad hash %s' % sha256)
return sha256
def checkout_git(url, rev, path):
| 64 | 64 | 57 | 9 | 54 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | checkout_git | checkout_git | 26 | 34 | 26 | 26 | db9bca6eb8f18e0530cc1a9f358533202aaeaf22 | bigcode/the-stack | train |
9438d94d5c6d28dff5c6aac3 | train | function | def nix_str_git(path, dep):
return ''' %(path)-90s = fetchgit { url = %(url)-128s; rev = "%(rev)s"; sha256 = "%(sha256)s"; };\n''' % {
"path": '"' + path + '"',
"url": '"' + dep["url"] + '"',
"rev": dep["rev"],
"sha256": dep["sha256"],
}
| def nix_str_git(path, dep):
| return ''' %(path)-90s = fetchgit { url = %(url)-128s; rev = "%(rev)s"; sha256 = "%(sha256)s"; };\n''' % {
"path": '"' + path + '"',
"url": '"' + dep["url"] + '"',
"rev": dep["rev"],
"sha256": dep["sha256"],
}
| )
def checkout_cipd(package, version, path):
os.makedirs(path)
subprocess.check_call(["cipd", "init", path])
subprocess.check_call(["cipd", "install", "-root", path, package, version])
return hash_path(path)
def nix_str_git(path, dep):
| 64 | 64 | 94 | 8 | 56 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | nix_str_git | nix_str_git | 42 | 48 | 42 | 42 | 304fed7958e261d2ad0c124f2c8e458f9e007c93 | bigcode/the-stack | train |
28c36aef1875df01c5d808a0 | train | function | def make_vendor_file(chromium_version, target_os):
topdir = os.path.join(BASEDIR, chromium_version)
if not os.path.isdir(topdir):
os.makedirs(topdir)
# first checkout depot_tools for gclient.py which will help to produce list of deps
if not os.path.isdir(os.path.join(topdir, "depot_tools")):
... | def make_vendor_file(chromium_version, target_os):
| topdir = os.path.join(BASEDIR, chromium_version)
if not os.path.isdir(topdir):
os.makedirs(topdir)
# first checkout depot_tools for gclient.py which will help to produce list of deps
if not os.path.isdir(os.path.join(topdir, "depot_tools")):
checkout_git("https://chromium.googlesource.c... | url)-128s; rev = "%(rev)s"; sha256 = "%(sha256)s"; };\n''' % {
"path": '"' + path + '"',
"url": '"' + dep["url"] + '"',
"rev": dep["rev"],
"sha256": dep["sha256"],
}
def nix_str_cipd(path, dep):
def _fetchcipd_str(p):
return 'fetchcipd { package = "%(package)s"; version ... | 256 | 256 | 2,391 | 12 | 244 | samuelgrf/robotnix | apks/chromium/mk-vendor-file.py | Python | make_vendor_file | make_vendor_file | 66 | 274 | 66 | 66 | d007a03021e6580ee6972da192975512a3266d06 | bigcode/the-stack | train |
73f646d51d3b9a9789a70ae4 | train | class | class Migration(migrations.Migration):
dependencies = [
('Blog', '0007_auto_20180413_1250'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='content',
field=markdownx.models.MarkdownxField(),
),
migrations.AlterField(
... | class Migration(migrations.Migration):
| dependencies = [
('Blog', '0007_auto_20180413_1250'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='content',
field=markdownx.models.MarkdownxField(),
),
migrations.AlterField(
model_name='post',
... | # Generated by Django 2.0.3 on 2018-05-28 07:28
from django.db import migrations
import markdownx.models
class Migration(migrations.Migration):
| 41 | 64 | 93 | 7 | 33 | stevenpi/Link.Python.Django.DiyBlog | Blog/migrations/0008_auto_20180528_0728.py | Python | Migration | Migration | 7 | 24 | 7 | 8 | 830bafbb595e61de11e44ff88ca9522d45b58d84 | bigcode/the-stack | train |
d9c279029055f400103b9944 | train | function | def appendShaders( menuDefinition, prefix="/RenderMan/Shader", matchExpression = "*" ) :
searchPaths = GafferRenderMan.RenderManShader.shaderLoader().searchPath.paths
# the 3delight installer adds "." to the shader path, but we skip it
# since it can lead to us traversing into arbitrarily deep hierarchies
# rooted... | def appendShaders( menuDefinition, prefix="/RenderMan/Shader", matchExpression = "*" ) :
| searchPaths = GafferRenderMan.RenderManShader.shaderLoader().searchPath.paths
# the 3delight installer adds "." to the shader path, but we skip it
# since it can lead to us traversing into arbitrarily deep hierarchies
# rooted in the current directory.
searchPaths = [ p for p in searchPaths if p != "." ]
GafferS... | ##########################################################################
import GafferSceneUI
import GafferRenderMan
## Appends menu items for the creation of all renderman shaders found on the searchpath, optionally
# filtered by filename based on matchExpression.
def appendShaders( menuDefinition, prefix="/Rende... | 64 | 64 | 136 | 20 | 44 | Kthulhu/gaffer | python/GafferRenderManUI/ShaderMenu.py | Python | appendShaders | appendShaders | 43 | 53 | 43 | 44 | 84ef8e82bf37035829112c6797557fce76230d7f | bigcode/the-stack | train |
df5b6d3a3e68bbd6632c56c6 | train | function | def __nodeCreator( nodeName, shaderName ) :
shader = GafferRenderMan.RenderManShader.shaderLoader().read( shaderName + ".sdl" )
if shader.type == "light" :
node = GafferRenderMan.RenderManLight( nodeName )
else :
node = GafferRenderMan.RenderManShader( nodeName )
node.loadShader( shaderName )
return node
| def __nodeCreator( nodeName, shaderName ) :
| shader = GafferRenderMan.RenderManShader.shaderLoader().read( shaderName + ".sdl" )
if shader.type == "light" :
node = GafferRenderMan.RenderManLight( nodeName )
else :
node = GafferRenderMan.RenderManShader( nodeName )
node.loadShader( shaderName )
return node
| Paths = [ p for p in searchPaths if p != "." ]
GafferSceneUI.ShaderUI.appendShaders(
menuDefinition, prefix, searchPaths, [ "slo", "sdl" ], __nodeCreator, matchExpression
)
def __nodeCreator( nodeName, shaderName ) :
| 64 | 64 | 83 | 12 | 52 | Kthulhu/gaffer | python/GafferRenderManUI/ShaderMenu.py | Python | __nodeCreator | __nodeCreator | 55 | 65 | 55 | 56 | 61ae04d8a893244c95e038e8818f59541bc2b80e | bigcode/the-stack | train |
d6876f94d52e48797067f18b | train | class | class TestIPv4IfAddrRoute(VppTestCase):
""" IPv4 Interface Addr Route Test Case """
@classmethod
def setUpClass(cls):
super(TestIPv4IfAddrRoute, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPv4IfAddrRoute, cls).tearDownClass()
def setUp(self):
supe... | class TestIPv4IfAddrRoute(VppTestCase):
| """ IPv4 Interface Addr Route Test Case """
@classmethod
def setUpClass(cls):
super(TestIPv4IfAddrRoute, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPv4IfAddrRoute, cls).tearDownClass()
def setUp(self):
super(TestIPv4IfAddrRoute, self).setUp()
... | (self):
# Verify we find the host route
prefix = "1.1.1.1/32"
result = self.route_lookup(prefix, True)
assert (prefix == str(result.route.prefix))
# Verify we find a middle prefix route
prefix = "1.1.1.0/24"
result = self.route_lookup(prefix, True)
assert... | 256 | 256 | 1,455 | 12 | 244 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4IfAddrRoute | TestIPv4IfAddrRoute | 293 | 432 | 293 | 293 | 4832ada18a4c507cc47e8cb3c1f572df56a687fc | bigcode/the-stack | train |
2adc96a95d405d9a79459818 | train | class | class TestIP4Replace(VppTestCase):
""" IPv4 Interface Address Replace """
@classmethod
def setUpClass(cls):
super(TestIP4Replace, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIP4Replace, cls).tearDownClass()
def setUp(self):
super(TestIP4Replace, se... | class TestIP4Replace(VppTestCase):
| """ IPv4 Interface Address Replace """
@classmethod
def setUpClass(cls):
super(TestIP4Replace, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIP4Replace, cls).tearDownClass()
def setUp(self):
super(TestIP4Replace, self).setUp()
self.create_pg... | (self, lo, "127.0.0.1", 32).add_vpp_config()
# add a neighbour that matches the loopback's /32
nbr = VppNeighbor(self,
lo.sw_if_index,
lo.remote_mac,
"127.0.0.1").add_vpp_config()
# add the default route which will b... | 256 | 256 | 1,331 | 10 | 246 | xerothermic/vpp | test/test_ip4.py | Python | TestIP4Replace | TestIP4Replace | 2,408 | 2,566 | 2,408 | 2,408 | 29a1a5f33bf83737f7826c4e58b9def099a3192e | bigcode/the-stack | train |
494b03609087d2ce5386fe32 | train | class | class TestIPv4FibCrud(VppTestCase):
""" FIB - add/update/delete - ip4 routes
Test scenario:
- add 1k,
- del 100,
- add new 1k,
- del 1.5k
..note:: Python API is too slow to add many routes, needs replacement.
"""
def config_fib_many_to_one(self, start_dest_addr, ne... | class TestIPv4FibCrud(VppTestCase):
| """ FIB - add/update/delete - ip4 routes
Test scenario:
- add 1k,
- del 100,
- add new 1k,
- del 1.5k
..note:: Python API is too slow to add many routes, needs replacement.
"""
def config_fib_many_to_one(self, start_dest_addr, next_hop_addr,
... | p_echo_request = (Ether(src=self.pg0.remote_mac,
dst=self.pg0.local_mac) /
IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
ICMP(id=icmp_id, seq=icmp_seq) /
Raw(load=icmp_load))
self.pg0.a... | 256 | 256 | 2,077 | 11 | 245 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4FibCrud | TestIPv4FibCrud | 503 | 740 | 503 | 503 | 05782c4a537d13ef9a801b6ed079ca1085d97acc | bigcode/the-stack | train |
502571d072220534ea360808 | train | class | class TestIPPunt(IPPuntSetup, VppTestCase):
""" IPv4 Punt Police/Redirect """
def setUp(self):
super().setUp()
super().punt_setup()
def tearDown(self):
super().punt_teardown()
super().tearDown()
def test_ip_punt_api_validation(self):
""" IP punt API parameter v... | class TestIPPunt(IPPuntSetup, VppTestCase):
| """ IPv4 Punt Police/Redirect """
def setUp(self):
super().setUp()
super().punt_setup()
def tearDown(self):
super().punt_teardown()
super().tearDown()
def test_ip_punt_api_validation(self):
""" IP punt API parameter validation """
nh_addr = self.pg1.re... | that have a port we need to explicitly
# register to get punted.
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
punt_udp = {
'type': pt_l4,
'p... | 256 | 256 | 1,112 | 14 | 242 | xerothermic/vpp | test/test_ip4.py | Python | TestIPPunt | TestIPPunt | 1,475 | 1,604 | 1,475 | 1,475 | 9e75f826d9adffd3f5e440e827c446e010d88387 | bigcode/the-stack | train |
37b9d845f9cd348c4865b4ee | train | class | class TestIPDirectedBroadcast(VppTestCase):
""" IPv4 Directed Broadcast """
@classmethod
def setUpClass(cls):
super(TestIPDirectedBroadcast, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDirectedBroadcast, cls).tearDownClass()
def setUp(self):
supe... | class TestIPDirectedBroadcast(VppTestCase):
| """ IPv4 Directed Broadcast """
@classmethod
def setUpClass(cls):
super(TestIPDirectedBroadcast, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDirectedBroadcast, cls).tearDownClass()
def setUp(self):
super(TestIPDirectedBroadcast, self).setUp()
... | dst=self.pg0.local_mac) /
IP(src="0.0.0.0",
dst=self.pg0.local_ip4) /
ICMP(id=4, seq=4) /
Raw(load=b'\x0a' * 18))
rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17)
p_s0 = (Ether(src=self.pg0.remote_mac,
... | 178 | 178 | 596 | 10 | 168 | xerothermic/vpp | test/test_ip4.py | Python | TestIPDirectedBroadcast | TestIPDirectedBroadcast | 2,010 | 2,083 | 2,010 | 2,010 | d5014dbbab4f1d3d0cb40ffdf527df42fb300044 | bigcode/the-stack | train |
525ff12c2697822122b17a1d | train | class | class TestICMPEcho(VppTestCase):
""" ICMP Echo Test Case """
@classmethod
def setUpClass(cls):
super(TestICMPEcho, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestICMPEcho, cls).tearDownClass()
def setUp(self):
super(TestICMPEcho, self).setUp()
... | class TestICMPEcho(VppTestCase):
| """ ICMP Echo Test Case """
@classmethod
def setUpClass(cls):
super(TestICMPEcho, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestICMPEcho, cls).tearDownClass()
def setUp(self):
super(TestICMPEcho, self).setUp()
# create 1 pg interface
... | (0)
self.assertTrue(lo_if.is_ip4_entry_in_fib_dump(fib4_dump))
def test_ipv4_ifaddr_del(self):
""" Delete an interface address that does not exist """
loopbacks = self.create_loopback_interfaces(1)
lo = self.lo_interfaces[0]
lo.config_ip4()
lo.admin_up()
#... | 149 | 149 | 498 | 11 | 138 | xerothermic/vpp | test/test_ip4.py | Python | TestICMPEcho | TestICMPEcho | 435 | 500 | 435 | 435 | d7fd8f82772001ea0e4fe4174f651e922fdcf262 | bigcode/the-stack | train |
e2a643ecefaacf6c064a9629 | train | class | class TestIPv4PathMTU(VppTestCase):
""" IPv4 Path MTU """
@classmethod
def setUpClass(cls):
super(TestIPv4PathMTU, cls).setUpClass()
cls.create_pg_interfaces(range(2))
# setup all interfaces
for i in cls.pg_interfaces:
i.admin_up()
i.config_ip4()
... | class TestIPv4PathMTU(VppTestCase):
| """ IPv4 Path MTU """
@classmethod
def setUpClass(cls):
super(TestIPv4PathMTU, cls).setUpClass()
cls.create_pg_interfaces(range(2))
# setup all interfaces
for i in cls.pg_interfaces:
i.admin_up()
i.config_ip4()
i.resolve_arp()
@clas... | generate a 'duplicate address' warning. but in
# this case, since what is newly downloaded is sane, it's ok
#
for intf in self.pg_interfaces:
# 172.18.x.1/24
addr = "172.18.%d.1" % intf.sw_if_index
VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config()
... | 256 | 256 | 1,708 | 12 | 244 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4PathMTU | TestIPv4PathMTU | 2,569 | 2,734 | 2,569 | 2,569 | 83338742028ba5759fbb22a786859acc18091541 | bigcode/the-stack | train |
139d07f67729981096e2e93f | train | class | class TestIPCover(VppTestCase):
""" IPv4 Table Cover """
@classmethod
def setUpClass(cls):
super(TestIPCover, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPCover, cls).tearDownClass()
def setUp(self):
super(TestIPCover, self).setUp()
self.... | class TestIPCover(VppTestCase):
| """ IPv4 Table Cover """
@classmethod
def setUpClass(cls):
super(TestIPCover, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPCover, cls).tearDownClass()
def setUp(self):
super(TestIPCover, self).setUp()
self.create_pg_interfaces(range(4))
... | _vpp_config()
r['multi'].add_vpp_config()
# all the routes are still there
for ii, t in enumerate(self.tables):
dump = t.dump()
mdump = t.mdump()
for r in routes[ii]:
self.assertTrue(find_route_in_dump(dump,... | 146 | 146 | 487 | 9 | 137 | xerothermic/vpp | test/test_ip4.py | Python | TestIPCover | TestIPCover | 2,340 | 2,405 | 2,340 | 2,340 | 177f98c346e1bdd66645d530d69682eea90e5eaf | bigcode/the-stack | train |
0be6ee28b50ca2bfe3e8bb8f | train | class | class TestIPv4ItfRebind(VppTestCase):
""" IPv4 Interface Bind w/ attached routes """
def setUp(self):
super(TestIPv4ItfRebind, self).setUp()
self.create_pg_interfaces(range(3))
def tearDown(self):
super(TestIPv4ItfRebind, self).tearDown()
def test_rebind(self):
""" Im... | class TestIPv4ItfRebind(VppTestCase):
| """ IPv4 Interface Bind w/ attached routes """
def setUp(self):
super(TestIPv4ItfRebind, self).setUp()
self.create_pg_interfaces(range(3))
def tearDown(self):
super(TestIPv4ItfRebind, self).tearDown()
def test_rebind(self):
""" Import to no import """
TABLE_I... | for many peers
#
N_HOSTS = 16
self.pg1.generate_remote_hosts(16)
self.pg1.configure_ipv4_neighbors()
for h in range(N_HOSTS):
pmtu = VppIpPathMtu(self, self.pg1.remote_hosts[h].ip4, 900)
pmtu.add_vpp_config()
self.assertTrue(pmtu.query_vpp_co... | 256 | 256 | 1,151 | 13 | 243 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4ItfRebind | TestIPv4ItfRebind | 2,737 | 2,869 | 2,737 | 2,737 | b8b92033615d263072fbd456dc7cbbca86cdb978 | bigcode/the-stack | train |
3e4354aa3dde8e22f5c2970b | train | class | class TestIPv4RouteLookup(VppTestCase):
""" IPv4 Route Lookup Test Case """
routes = []
def route_lookup(self, prefix, exact):
return self.vapi.api(self.vapi.papi.ip_route_lookup,
{
'table_id': 0,
'exact'... | class TestIPv4RouteLookup(VppTestCase):
| """ IPv4 Route Lookup Test Case """
routes = []
def route_lookup(self, prefix, exact):
return self.vapi.api(self.vapi.papi.ip_route_lookup,
{
'table_id': 0,
'exact': exact,
... | ):
""" IPv4 FIB test
Test scenario:
- Create IPv4 stream for pg0 interface
- Create IPv4 tagged streams for pg1's and pg2's sub-interface.
- Send and verify received packets on each interface.
"""
pkts = self.create_stream(self.pg0)
self.pg0... | 172 | 172 | 574 | 11 | 161 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4RouteLookup | TestIPv4RouteLookup | 219 | 288 | 219 | 219 | 599d0ff12c499cacc3f698f8a94f8fe9ac52f3a3 | bigcode/the-stack | train |
99bd4cb82b90ecff8cb472e0 | train | class | class TestIPLPM(VppTestCase):
""" IPv4 longest Prefix Match """
@classmethod
def setUpClass(cls):
super(TestIPLPM, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPLPM, cls).tearDownClass()
def setUp(self):
super(TestIPLPM, self).setUp()
self... | class TestIPLPM(VppTestCase):
| """ IPv4 longest Prefix Match """
@classmethod
def setUpClass(cls):
super(TestIPLPM, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPLPM, cls).tearDownClass()
def setUp(self):
super(TestIPLPM, self).setUp()
self.create_pg_interfaces(range(4)... | ,
"directed broadcast disabled")
#
# toggle directed broadcast on pg0
#
self.vapi.sw_interface_set_ip_directed_broadcast(
self.pg0.sw_if_index, 0)
self.send_and_assert_no_replies(self.pg1, p0 * NUM_PKTS,
... | 144 | 144 | 482 | 9 | 135 | xerothermic/vpp | test/test_ip4.py | Python | TestIPLPM | TestIPLPM | 2,086 | 2,140 | 2,086 | 2,086 | 2fd19300fcbb5ccec06404fc77702041853fb61c | bigcode/the-stack | train |
ac07510c26b7e2c2197b73ee | train | class | class TestIPv4(VppTestCase):
""" IPv4 Test Case """
@classmethod
def setUpClass(cls):
super(TestIPv4, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPv4, cls).tearDownClass()
def setUp(self):
"""
Perform test setup before test case.
... | class TestIPv4(VppTestCase):
| """ IPv4 Test Case """
@classmethod
def setUpClass(cls):
super(TestIPv4, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPv4, cls).tearDownClass()
def setUp(self):
"""
Perform test setup before test case.
**Config:**
- cre... | codes
from scapy.layers.l2 import Ether, Dot1Q, ARP
from scapy.packet import Raw
from six import moves
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from util import ppp
from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \
VppMRoutePath, VppMplsIpBind, \
... | 256 | 256 | 1,581 | 9 | 246 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4 | TestIPv4 | 31 | 216 | 31 | 31 | 171f2735ccf471e2c2db6db2898ee04ad7bc29a7 | bigcode/the-stack | train |
e8756160bae050cfec316930 | train | class | class IPPuntSetup(object):
""" Setup for IPv4 Punt Police/Redirect """
def punt_setup(self):
self.create_pg_interfaces(range(4))
for i in self.pg_interfaces:
i.admin_up()
i.config_ip4()
i.resolve_arp()
# use UDP packet that have a port we need to ex... | class IPPuntSetup(object):
| """ Setup for IPv4 Punt Police/Redirect """
def punt_setup(self):
self.create_pg_interfaces(range(4))
for i in self.pg_interfaces:
i.admin_up()
i.config_ip4()
i.resolve_arp()
# use UDP packet that have a port we need to explicitly
# register... | _ip4,
src=self.pg0.remote_ip4) /
UDP(sport=1234, dport=1234) /
Raw(b'\xa5' * 100)) * NUM_PKTS
#
# Expect that packets sent on VLAN-0 are forwarded on the
# main interface.
#
self.send_and_expect(self.pg0, pkts, self.pg1)
class I... | 91 | 91 | 305 | 7 | 84 | xerothermic/vpp | test/test_ip4.py | Python | IPPuntSetup | IPPuntSetup | 1,434 | 1,472 | 1,434 | 1,434 | 12006eaae0709d2da7c636c0f33852a54b44d0a2 | bigcode/the-stack | train |
4f2ad7e2a24fc54bc2cfadae | train | class | class TestIPDisabled(VppTestCase):
""" IPv4 disabled """
@classmethod
def setUpClass(cls):
super(TestIPDisabled, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDisabled, cls).tearDownClass()
def setUp(self):
super(TestIPDisabled, self).setUp()
... | class TestIPDisabled(VppTestCase):
| """ IPv4 disabled """
@classmethod
def setUpClass(cls):
super(TestIPDisabled, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDisabled, cls).tearDownClass()
def setUp(self):
super(TestIPDisabled, self).setUp()
# create 2 pg interfaces
... | 4) /
Raw(b'\xa5' * 100))
r1 = VppIpRoute(self, "1.1.1.0", 24,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index)])
r1.add_vpp_config()
rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
#
... | 222 | 222 | 740 | 9 | 213 | xerothermic/vpp | test/test_ip4.py | Python | TestIPDisabled | TestIPDisabled | 867 | 963 | 867 | 867 | d7dc1cfefb0943ae2660594bf5a6e511307436a3 | bigcode/the-stack | train |
65255288b0ae805b916e6ca1 | train | class | class TestIPLoadBalance(VppTestCase):
""" IPv4 Load-Balancing """
@classmethod
def setUpClass(cls):
super(TestIPLoadBalance, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPLoadBalance, cls).tearDownClass()
def setUp(self):
super(TestIPLoadBalance, s... | class TestIPLoadBalance(VppTestCase):
| """ IPv4 Load-Balancing """
@classmethod
def setUpClass(cls):
super(TestIPLoadBalance, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPLoadBalance, cls).tearDownClass()
def setUp(self):
super(TestIPLoadBalance, self).setUp()
self.create_pg_i... | .inet_pton(socket.AF_INET, "10.10.10.10")
self.vapi.sw_interface_add_del_address(
sw_if_index=self.pg0.sw_if_index,
prefix="10.10.10.10/31")
pn = (Ether(src=self.pg1.remote_mac,
dst=self.pg1.local_mac) /
IP(dst="10.10.10.11", src=self.pg0.local... | 256 | 256 | 2,756 | 10 | 246 | xerothermic/vpp | test/test_ip4.py | Python | TestIPLoadBalance | TestIPLoadBalance | 1,090 | 1,382 | 1,090 | 1,090 | fefa53eb02f9f4f2af3c8d50ff20cd346fcea2ab | bigcode/the-stack | train |
1af82dfa388f24d176bd6a8b | train | class | class TestIPInput(VppTestCase):
""" IPv4 Input Exceptions """
@classmethod
def setUpClass(cls):
super(TestIPInput, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPInput, cls).tearDownClass()
def setUp(self):
super(TestIPInput, self).setUp()
... | class TestIPInput(VppTestCase):
| """ IPv4 Input Exceptions """
@classmethod
def setUpClass(cls):
super(TestIPInput, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPInput, cls).tearDownClass()
def setUp(self):
super(TestIPInput, self).setUp()
self.create_pg_interfaces(range(... | forward via pg2
#
route_in_src = VppIpRoute(self, "2.2.2.2", 32,
[VppRoutePath(self.pg2.remote_ip4,
self.pg2.sw_if_index)],
table_id=2)
route_in_src.add_vpp_config()
self.... | 256 | 256 | 1,478 | 9 | 247 | xerothermic/vpp | test/test_ip4.py | Python | TestIPInput | TestIPInput | 1,837 | 2,007 | 1,837 | 1,837 | a746424169a3418f44a094394de2923509ce9beb | bigcode/the-stack | train |
3ddd98d99f971790a5cbeb91 | train | class | @tag_fixme_vpp_workers
class TestIPv4Frag(VppTestCase):
""" IPv4 fragmentation """
@classmethod
def setUpClass(cls):
super(TestIPv4Frag, cls).setUpClass()
cls.create_pg_interfaces([0, 1])
cls.src_if = cls.pg0
cls.dst_if = cls.pg1
# setup all interfaces
for ... | @tag_fixme_vpp_workers
class TestIPv4Frag(VppTestCase):
| """ IPv4 fragmentation """
@classmethod
def setUpClass(cls):
super(TestIPv4Frag, cls).setUpClass()
cls.create_pg_interfaces([0, 1])
cls.src_if = cls.pg0
cls.dst_if = cls.pg1
# setup all interfaces
for i in cls.pg_interfaces:
i.admin_up()
... | (Ether(src=self.pg0.remote_mac,
dst=self.pg0.local_mac) /
IP(src="1.1.1.1",
dst="10.1.2.1") /
UDP(sport=1234, dport=1234) /
Raw(b'\xa5' * 2000))
self.logger.info(self.vapi.cli("sh ip fib mtrie"))
rx = self.send_an... | 149 | 149 | 498 | 18 | 131 | xerothermic/vpp | test/test_ip4.py | Python | TestIPv4Frag | TestIPv4Frag | 2,143 | 2,205 | 2,143 | 2,144 | 4a3a5a49f89f79df6a9b609ecb803d554e8f3b2e | bigcode/the-stack | train |
e427f5ea5a88685492defd9e | train | class | class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
""" IPv4 Punt Policer thread handoff """
vpp_worker_count = 2
def setUp(self):
super(TestIPPuntHandoff, self).setUp()
super(TestIPPuntHandoff, self).punt_setup()
def tearDown(self):
super(TestIPPuntHandoff, self).punt_teardown(... | class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
| """ IPv4 Punt Policer thread handoff """
vpp_worker_count = 2
def setUp(self):
super(TestIPPuntHandoff, self).setUp()
super(TestIPPuntHandoff, self).punt_setup()
def tearDown(self):
super(TestIPPuntHandoff, self).punt_teardown()
super(TestIPPuntHandoff, self).tearDown()... | _index,
self.pg3.sw_if_index, nh_address)
ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index,
self.pg3.sw_if_index, "0.0.0.0")
ipr_03.add_vpp_config()
ipr_13.add_vpp_config()
ipr_23.add_vpp_config()
#
... | 256 | 256 | 1,053 | 16 | 240 | xerothermic/vpp | test/test_ip4.py | Python | TestIPPuntHandoff | TestIPPuntHandoff | 1,607 | 1,715 | 1,607 | 1,607 | f5c3ee1af765ed5de6e1fac219757688431a091a | bigcode/the-stack | train |
8a060c6319d79a9f0513b99d | train | class | class TestIPNull(VppTestCase):
""" IPv4 routes via NULL """
@classmethod
def setUpClass(cls):
super(TestIPNull, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPNull, cls).tearDownClass()
def setUp(self):
super(TestIPNull, self).setUp()
# cre... | class TestIPNull(VppTestCase):
| """ IPv4 routes via NULL """
@classmethod
def setUpClass(cls):
super(TestIPNull, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPNull, cls).tearDownClass()
def setUp(self):
super(TestIPNull, self).setUp()
# create 2 pg interfaces
sel... | _4 = self.create_stream(
self.pg2, self.pg0, self.deleted_routes, 100)
self.pg1.add_stream(self.stream_1 + self.stream_3)
self.pg2.add_stream(self.stream_2 + self.stream_4)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
pkts = self.pg0.get_capture(len(se... | 256 | 256 | 1,034 | 9 | 247 | xerothermic/vpp | test/test_ip4.py | Python | TestIPNull | TestIPNull | 743 | 864 | 743 | 743 | e6a24a0afd6f176f8e5468559fed7118a02527a4 | bigcode/the-stack | train |
577f72613a24f3d8740c3fef | train | class | class TestIPDeag(VppTestCase):
""" IPv4 Deaggregate Routes """
@classmethod
def setUpClass(cls):
super(TestIPDeag, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDeag, cls).tearDownClass()
def setUp(self):
super(TestIPDeag, self).setUp()
se... | class TestIPDeag(VppTestCase):
| """ IPv4 Deaggregate Routes """
@classmethod
def setUpClass(cls):
super(TestIPDeag, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPDeag, cls).tearDownClass()
def setUp(self):
super(TestIPDeag, self).setUp()
self.create_pg_interfaces(range(3... | .assertEqual(stats0['violate_packets'] + stats1['violate_packets'],
stats['violate_packets'])
# Unbind the policer and repeat
policer.bind_vpp_config(1, False)
for worker in [0, 1]:
self.send_and_expect(self.pg0, pkts, self.pg1, worker=worker)
se... | 256 | 256 | 1,005 | 10 | 246 | xerothermic/vpp | test/test_ip4.py | Python | TestIPDeag | TestIPDeag | 1,718 | 1,834 | 1,718 | 1,718 | 394bf7befdb46d37c022e70a7cef108c9bc80fb4 | bigcode/the-stack | train |
4f9db0b472fc20c1f0478456 | train | class | class TestIPSubNets(VppTestCase):
""" IPv4 Subnets """
@classmethod
def setUpClass(cls):
super(TestIPSubNets, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPSubNets, cls).tearDownClass()
def setUp(self):
super(TestIPSubNets, self).setUp()
#... | class TestIPSubNets(VppTestCase):
| """ IPv4 Subnets """
@classmethod
def setUpClass(cls):
super(TestIPSubNets, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPSubNets, cls).tearDownClass()
def setUp(self):
super(TestIPSubNets, self).setUp()
# create a 2 pg interfaces
... | ") /
UDP(sport=1234, dport=1234) /
Raw(b'\xa5' * 100))
#
# PG1 does not forward IP traffic
#
self.send_and_assert_no_replies(self.pg1, pu, "IP disabled")
self.send_and_assert_no_replies(self.pg1, pm, "IP disabled")
#
# IP enable PG1
... | 256 | 256 | 1,033 | 11 | 245 | xerothermic/vpp | test/test_ip4.py | Python | TestIPSubNets | TestIPSubNets | 966 | 1,087 | 966 | 966 | 00ececab3b377d7ea6575f4965457cf3b3b041ec | bigcode/the-stack | train |
56029613c0898d8edcea8c62 | train | class | class TestIPVlan0(VppTestCase):
""" IPv4 VLAN-0 """
@classmethod
def setUpClass(cls):
super(TestIPVlan0, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPVlan0, cls).tearDownClass()
def setUp(self):
super(TestIPVlan0, self).setUp()
self.creat... | class TestIPVlan0(VppTestCase):
| """ IPv4 VLAN-0 """
@classmethod
def setUpClass(cls):
super(TestIPVlan0, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPVlan0, cls).tearDownClass()
def setUp(self):
super(TestIPVlan0, self).setUp()
self.create_pg_interfaces(range(2))
... | ii) /
Raw(b'\xa5' * 100))
self.send_and_expect_only(self.pg0, port_pkts, self.pg4)
# bring the link back up
self.pg3.link_up()
rx = self.send_and_expect_load_balancing(self.pg0, port_pkts,
[self.pg3, self.p... | 100 | 100 | 336 | 11 | 89 | xerothermic/vpp | test/test_ip4.py | Python | TestIPVlan0 | TestIPVlan0 | 1,385 | 1,431 | 1,385 | 1,385 | 93412a7186388f127812b605a861788a4c90bb80 | bigcode/the-stack | train |
8417fe3f919e4a47df13bb37 | train | class | class TestIPReplace(VppTestCase):
""" IPv4 Table Replace """
@classmethod
def setUpClass(cls):
super(TestIPReplace, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPReplace, cls).tearDownClass()
def setUp(self):
super(TestIPReplace, self).setUp()
... | class TestIPReplace(VppTestCase):
| """ IPv4 Table Replace """
@classmethod
def setUpClass(cls):
super(TestIPReplace, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestIPReplace, cls).tearDownClass()
def setUp(self):
super(TestIPReplace, self).setUp()
self.create_pg_interfaces(ran... | .sw_if_index,
self.dst_if.remote_mac,
self.dst_if.remote_ip4).add_vpp_config()
# Force fragmentation by setting MTU of output interface
# lower than packet size
self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index,
... | 256 | 256 | 1,112 | 9 | 247 | xerothermic/vpp | test/test_ip4.py | Python | TestIPReplace | TestIPReplace | 2,208 | 2,337 | 2,208 | 2,208 | 0dd4eca2e53644a0fe6fbe1dde764f48da177bcb | bigcode/the-stack | train |
4676a22c035831d5a9728ac9 | train | function | def test():
assert level05.unique("123")
assert not level05.unique((1, 1))
| def test():
| assert level05.unique("123")
assert not level05.unique((1, 1))
| from homeworks.aleksey_gukov.hw05 import level05
def test():
| 18 | 64 | 23 | 3 | 14 | tgrx/Z22 | homeworks/aleksey_gukov/hw05/test_lvl5.py | Python | test | test | 4 | 7 | 4 | 5 | de7a39c33fe4175a201c0480f4e00b121d7cbc9e | bigcode/the-stack | train |
c4d8f01affe43ef1980fe53c | train | function | @pytest.fixture
def list_test2():
linked2 = LinkedList()
linked2.append("5")
linked2.append("9")
linked2.append(4)
return linked2 | @pytest.fixture
def list_test2():
| linked2 = LinkedList()
linked2.append("5")
linked2.append("9")
linked2.append(4)
return linked2 | -> { 2 } -> NULL"
assert excpected == actual
@pytest.fixture
def list_test1():
linked1 = LinkedList()
linked1.append(1)
linked1.append(3)
linked1.append(2)
return linked1
@pytest.fixture
def list_test2():
| 64 | 64 | 40 | 8 | 55 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | list_test2 | list_test2 | 34 | 40 | 34 | 35 | 55b96ddf1dcaa380cc34358129b323ce46b52725 | bigcode/the-stack | train |
4a6104078ac041e973a1780b | train | function | def test_zipList_unbalance1(list_test1,list_test2):
list_test1.append(4)
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> { 4 } -> NULL"
assert excpected == actual
| def test_zipList_unbalance1(list_test1,list_test2):
| list_test1.append(4)
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> { 4 } -> NULL"
assert excpected == actual
| (list_test1,list_test2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
def test_zipList_unbalance1(list_test1,list_test2):
| 64 | 64 | 82 | 14 | 49 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | test_zipList_unbalance1 | test_zipList_unbalance1 | 11 | 15 | 11 | 11 | 99fa11191a8bb5559bcb1a1f8c6d223c1d003a58 | bigcode/the-stack | train |
c590623ae3a7cf63b4652669 | train | function | def test_zipList(list_test1,list_test2):
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
| def test_zipList(list_test1,list_test2):
| actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
| from datastructures.ll_zip.ll_zip import zipLists
from datastructures.linked_list.linked_list import LinkedList
# from datastructures.linked_list.linked_list import LinkedList
import pytest
def test_zipList(list_test1,list_test2):
| 55 | 64 | 66 | 11 | 43 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | test_zipList | test_zipList | 7 | 10 | 7 | 7 | c58f328b6f3ff99df997ec9a6ee05c7cd8d89ff2 | bigcode/the-stack | train |
541910f8d37bd11a4aa177f6 | train | function | def test_zipList_None(list_test1):
list_test2 = LinkedList()
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 3 } -> { 2 } -> NULL"
assert excpected == actual
| def test_zipList_None(list_test1):
| list_test2 = LinkedList()
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 3 } -> { 2 } -> NULL"
assert excpected == actual
| (list_test1,list_test2)
excpected = "{ 5 } -> { 1 } -> { 9 } -> { 3 } -> { 4 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
def test_zipList_None(list_test1):
| 64 | 64 | 57 | 9 | 54 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | test_zipList_None | test_zipList_None | 21 | 25 | 21 | 21 | 6ecef51db5ff3036b3ca8b5daaf1b82e69cc8b4f | bigcode/the-stack | train |
78947324c5fb837e4984dfe8 | train | function | @pytest.fixture
def list_test1():
linked1 = LinkedList()
linked1.append(1)
linked1.append(3)
linked1.append(2)
return linked1
| @pytest.fixture
def list_test1():
| linked1 = LinkedList()
linked1.append(1)
linked1.append(3)
linked1.append(2)
return linked1
| test_zipList_None(list_test1):
list_test2 = LinkedList()
actual = zipLists(list_test1,list_test2)
excpected = "{ 1 } -> { 3 } -> { 2 } -> NULL"
assert excpected == actual
@pytest.fixture
def list_test1():
| 64 | 64 | 41 | 8 | 55 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | list_test1 | list_test1 | 27 | 33 | 27 | 28 | 42bbd8f8a715c6e1f85950f79ef6cc409ed07493 | bigcode/the-stack | train |
0aa8def99b95d7b4c0d9b2fc | train | function | def test_zipList_unbalance2(list_test1,list_test2):
list_test2.append(4)
actual = zipLists(list_test1,list_test2)
excpected = "{ 5 } -> { 1 } -> { 9 } -> { 3 } -> { 4 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
| def test_zipList_unbalance2(list_test1,list_test2):
| list_test2.append(4)
actual = zipLists(list_test1,list_test2)
excpected = "{ 5 } -> { 1 } -> { 9 } -> { 3 } -> { 4 } -> { 2 } -> { 4 } -> NULL"
assert excpected == actual
| 2)
excpected = "{ 1 } -> { 5 } -> { 3 } -> { 9 } -> { 2 } -> { 4 } -> { 4 } -> NULL"
assert excpected == actual
def test_zipList_unbalance2(list_test1,list_test2):
| 64 | 64 | 82 | 14 | 49 | RaneemAbdulazez/data-structures-and-algorithms | python/tests/test_ll-zip-test.py | Python | test_zipList_unbalance2 | test_zipList_unbalance2 | 16 | 20 | 16 | 16 | 214f31f1234cec9d33774941aafa317e2dc364c8 | bigcode/the-stack | train |
80cbcc6e6161bbb6a9effee3 | train | function | def main(argv):
ns.core.CommandLine().Parse(argv)
#
# We are interacting with the outside, real, world. This means we have to
# interact in real-time and therefore we have to use the real-time simulator
# and take the time to calculate checksums.
#
ns.core.GlobalValue.Bind("Simulator... | def main(argv):
| ns.core.CommandLine().Parse(argv)
#
# We are interacting with the outside, real, world. This means we have to
# interact in real-time and therefore we have to use the real-time simulator
# and take the time to calculate checksums.
#
ns.core.GlobalValue.Bind("SimulatorImplementationTyp... | # -*- Mode: Python; -*-
#
# Copyright 2010 University of Washington
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be usefu... | 200 | 236 | 787 | 4 | 195 | usi-systems/cc | ns-allinone-3.35/ns-3.35/src/tap-bridge/examples/tap-wifi-virtual-machine.py | Python | main | main | 27 | 110 | 27 | 28 | f5a60500aa5f9260584db032b401bee4a3fa49dd | bigcode/the-stack | train |
dc71652b8aba96c14ff19d35 | train | function | def main_app(**kwargs):
"""
"""
# build the config and the dataManager from kwargs
url_params = st.experimental_get_query_params()
config, dataManager = build_config(url_params=url_params, **kwargs)
# set page config and debug view
st.set_page_config(page_title='Uncertainty Explorer', layou... | def main_app(**kwargs):
| """
"""
# build the config and the dataManager from kwargs
url_params = st.experimental_get_query_params()
config, dataManager = build_config(url_params=url_params, **kwargs)
# set page config and debug view
st.set_page_config(page_title='Uncertainty Explorer', layout=config.layout)
deb... | """
# TODO: add the story mode stuff here
# explainer
concept_explainer(config)
# show the graph
fig = concept_graph(config)
plot_area = st.empty()
plot_area.plotly_chart(fig, use_container_width=True)
def main_app(**kwargs):
| 64 | 64 | 119 | 6 | 58 | hydrocode-de/RUINSapp | ruins/apps/uncertainty.py | Python | main_app | main_app | 219 | 234 | 219 | 219 | 6bcc9408c099f6de54db5dd3bc53da3633f25dfe | bigcode/the-stack | train |
67125d62e489bc95e60231b4 | train | function | def concept_explainer(config: Config, **kwargs):
"""Show an explanation, if it was not already shown.
"""
# check if we saw the explainer already
if config.has_key('uncertainty_playground_explainer'):
return
# get the container and a translation function
container = kwargs['containe... | def concept_explainer(config: Config, **kwargs):
| """Show an explanation, if it was not already shown.
"""
# check if we saw the explainer already
if config.has_key('uncertainty_playground_explainer'):
return
# get the container and a translation function
container = kwargs['container'] if 'container' in kwargs else st
t = conf... | . Allerdings ist das Ergebnis hier
schlechter als der bessere Ausgang des ersten Erignisses. Wir erkaufen uns die Sicherheit keine sehr schlechten Ergbnisse
zu haben damit, dass wir auch auf sehr positive Ergebnisse verzichten.
Aber lohnt sich das?
"""
)
def concept_explainer(config: Config, **kwargs):
| 64 | 64 | 195 | 12 | 52 | hydrocode-de/RUINSapp | ruins/apps/uncertainty.py | Python | concept_explainer | concept_explainer | 68 | 89 | 68 | 68 | b0caff4dda5a8a1be74ce0c7d891144ef43fe027 | bigcode/the-stack | train |
1088d71f8019c79abc9b0949 | train | function | def concept_graph(config: Config, expander_container=st.sidebar, **kwargs) -> go.Figure:
"""
# TODO: document this
"""
# get the container and translator
container = kwargs['container'] if 'container' in kwargs else st
t = config.translator(de=_TRANSLATE_DE, en=_TRANSLATE_EN)
# ------------... | def concept_graph(config: Config, expander_container=st.sidebar, **kwargs) -> go.Figure:
| """
# TODO: document this
"""
# get the container and translator
container = kwargs['container'] if 'container' in kwargs else st
t = config.translator(de=_TRANSLATE_DE, en=_TRANSLATE_EN)
# ------------------------
# First PDF
if not config.has_key('concept_event_1'):
contai... | ev2 is not None:
mu, std = ev2
y = norm.pdf(x, loc=mu, scale=std)
y_sum = y.sum()
y /= y_sum
# add distribution
fig.add_trace(
go.Scatter(x=x, y=y * 100, mode='lines', line=dict(color='orange', width=2), name='Alternative Event', fill='tozerox')
... | 215 | 215 | 719 | 22 | 192 | hydrocode-de/RUINSapp | ruins/apps/uncertainty.py | Python | concept_graph | concept_graph | 143 | 197 | 143 | 143 | c8b37fe2322f26118096734b59b4eeec5a8220a9 | bigcode/the-stack | train |
a1658468f61731274319a2f7 | train | function | def _helper_plot(ev1: List[Tuple[float, float]], ev2: Tuple[float, float] = None, **kwargs) -> go.Figure:
# create figure
fig = go.Figure()
# build the colorscale with enough colors
cscale = getattr(sequential, kwargs.get('colorscale', 'Greens'))
cmap = n_colors(unlabel_rgb(cscale[-1]), unlabel_rgb... | def _helper_plot(ev1: List[Tuple[float, float]], ev2: Tuple[float, float] = None, **kwargs) -> go.Figure:
# create figure
| fig = go.Figure()
# build the colorscale with enough colors
cscale = getattr(sequential, kwargs.get('colorscale', 'Greens'))
cmap = n_colors(unlabel_rgb(cscale[-1]), unlabel_rgb(cscale[-3]), len(ev1))
# get a common x
x = np.linspace(0, 10, 200)
# iterate over all outcomes
for i,outco... | config.translator(en=_TRANSLATE_EN, de=_TRANSLATE_DE)
# place title and intro
container.title(t('title'))
container.markdown(t('introduction'), unsafe_allow_html=True)
# check if the user wants to continue
accept = container.button('WEITER' if config.lang == 'de' else 'CONTINUE')
if accept:
... | 150 | 150 | 503 | 40 | 110 | hydrocode-de/RUINSapp | ruins/apps/uncertainty.py | Python | _helper_plot | _helper_plot | 92 | 140 | 92 | 93 | 3adccd1423ab5cd53080a4cd939710194fd5bbe3 | bigcode/the-stack | train |
53f10b19e6d70a7366fff9f8 | train | function | def concept_playground(config: Config) -> None:
"""
The concept playground demonstrates how knightian uncertainty
is different from risk and how it influences everyday decisions.
"""
# TODO: add the story mode stuff here
# explainer
concept_explainer(config)
# show the graph
f... | def concept_playground(config: Config) -> None:
| """
The concept playground demonstrates how knightian uncertainty
is different from risk and how it influences everyday decisions.
"""
# TODO: add the story mode stuff here
# explainer
concept_explainer(config)
# show the graph
fig = concept_graph(config)
plot_area = st.em... | comes': ev1_new, 'name': 'Original Event', 'colorscale': 'Greens'}, {'outcomes': [(e2_mu, e2_st)], 'name': 'Alternative Event', 'colorscale': 'Oranges'})
return fig
def concept_playground(config: Config) -> None:
| 64 | 64 | 93 | 11 | 52 | hydrocode-de/RUINSapp | ruins/apps/uncertainty.py | Python | concept_playground | concept_playground | 202 | 216 | 202 | 202 | 36aa27be2a911a5fe963f91670f579fbc7cf1eb1 | bigcode/the-stack | train |
60bd8c23e5fcf86c96597cf2 | train | function | def load_labels(filename):
"""Read in labels, one label per line."""
return [line.rstrip() for line in tf.gfile.GFile(filename)]
| def load_labels(filename):
| """Read in labels, one label per line."""
return [line.rstrip() for line in tf.gfile.GFile(filename)]
| '--input_layer',
type=str,
default='DecodeJpeg/contents:0',
help='Name of the input operation')
def load_image(filename):
"""Read in the image_data to be classified."""
return tf.gfile.FastGFile(filename, 'rb').read()
def load_labels(filename):
| 64 | 64 | 32 | 5 | 59 | shengfuintel/tensorflow | tensorflow/examples/image_retraining/label_image.py | Python | load_labels | load_labels | 85 | 87 | 85 | 85 | eadcbf7d8e1fb14bfdc4568a6b837ad244425c13 | bigcode/the-stack | train |
d964c7c48e326c1ebde0630a | train | function | def main(argv):
"""Runs inference on an image."""
if argv[1:]:
raise ValueError('Unused Command Line Args: %s' % argv[1:])
if not tf.gfile.Exists(FLAGS.image):
tf.logging.fatal('image file does not exist %s', FLAGS.image)
if not tf.gfile.Exists(FLAGS.labels):
tf.logging.fatal('labels file does not... | def main(argv):
| """Runs inference on an image."""
if argv[1:]:
raise ValueError('Unused Command Line Args: %s' % argv[1:])
if not tf.gfile.Exists(FLAGS.image):
tf.logging.fatal('image file does not exist %s', FLAGS.image)
if not tf.gfile.Exists(FLAGS.labels):
tf.logging.fatal('labels file does not exist %s', FLAG... | = predictions.argsort()[-num_top_predictions:][::-1]
for node_id in top_k:
human_string = labels[node_id]
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score))
return 0
def main(argv):
| 64 | 64 | 193 | 4 | 59 | shengfuintel/tensorflow | tensorflow/examples/image_retraining/label_image.py | Python | main | main | 118 | 142 | 118 | 118 | 0ec7ad6e30d5ac3576daeebfbd4f5de263ed91a2 | bigcode/the-stack | train |
c01906a6bf242fe8f88ce3a9 | train | function | def load_image(filename):
"""Read in the image_data to be classified."""
return tf.gfile.FastGFile(filename, 'rb').read()
| def load_image(filename):
| """Read in the image_data to be classified."""
return tf.gfile.FastGFile(filename, 'rb').read()
| '--output_layer',
type=str,
default='final_result:0',
help='Name of the result operation')
parser.add_argument(
'--input_layer',
type=str,
default='DecodeJpeg/contents:0',
help='Name of the input operation')
def load_image(filename):
| 64 | 64 | 31 | 5 | 59 | shengfuintel/tensorflow | tensorflow/examples/image_retraining/label_image.py | Python | load_image | load_image | 80 | 82 | 80 | 80 | de066707934ca7682b1adaf4a107810bf4da308b | bigcode/the-stack | train |
b75c9e4ea95fbc7da1c8c2ac | train | function | def run_graph(image_data, labels, input_layer_name, output_layer_name,
num_top_predictions):
with tf.Session() as sess:
# Feed the image_data as input to the graph.
# predictions will contain a two-dimensional array, where one
# dimension represents the input image count, and the other h... | def run_graph(image_data, labels, input_layer_name, output_layer_name,
num_top_predictions):
| with tf.Session() as sess:
# Feed the image_data as input to the graph.
# predictions will contain a two-dimensional array, where one
# dimension represents the input image count, and the other has
# predictions per class
softmax_tensor = sess.graph.get_tensor_by_name(output_layer_name)
... | with tf.gfile.FastGFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
def run_graph(image_data, labels, input_layer_name, output_layer_name,
num_top_predictions):
| 63 | 64 | 185 | 21 | 43 | shengfuintel/tensorflow | tensorflow/examples/image_retraining/label_image.py | Python | run_graph | run_graph | 98 | 115 | 98 | 99 | 6dd43c7d54a4808db283fb0faf3b2a9fc051812a | bigcode/the-stack | train |
6c771fbbe8231a6ee04a51be | train | function | def load_graph(filename):
"""Unpersists graph from file as default graph."""
with tf.gfile.FastGFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
| def load_graph(filename):
| """Unpersists graph from file as default graph."""
with tf.gfile.FastGFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
| """Read in the image_data to be classified."""
return tf.gfile.FastGFile(filename, 'rb').read()
def load_labels(filename):
"""Read in labels, one label per line."""
return [line.rstrip() for line in tf.gfile.GFile(filename)]
def load_graph(filename):
| 63 | 64 | 60 | 5 | 58 | shengfuintel/tensorflow | tensorflow/examples/image_retraining/label_image.py | Python | load_graph | load_graph | 90 | 95 | 90 | 90 | 42aebc288834e0edc030cd44f689c8944d6a33b6 | bigcode/the-stack | train |
4e0656267206218413dd3a43 | train | class | class Entity:
def __init__(self, anim=None, x=0, y=0, heading=0):
self.anim = anim
self.frame = 0 # index of the current frame of animation
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.heading = heading # in degrees
self.looped = False # true if animation has looped at least ... | class Entity:
| def __init__(self, anim=None, x=0, y=0, heading=0):
self.anim = anim
self.frame = 0 # index of the current frame of animation
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.heading = heading # in degrees
self.looped = False # true if animation has looped at least once
self.a... | import pygame, Global
class Entity:
| 8 | 135 | 453 | 3 | 4 | dmfabritius/Asteroids | Python - pygame/Entity.py | Python | Entity | Entity | 3 | 51 | 3 | 4 | 370559c340b5896692a1f9b5baa3dee4f7342b8d | bigcode/the-stack | train |
c0d33de9b7aadb1183ea827f | train | class | class LoaderNotRegisteredError(LoaderError):
"""Task Holder Loader Not Registered Error."""
| class LoaderNotRegisteredError(LoaderError):
| """Task Holder Loader Not Registered Error."""
| import os
import uuid
from ..TaskHolder import TaskHolder
class LoaderError(Exception):
"""Task Holder Loader Error."""
class LoaderNotRegisteredError(LoaderError):
| 35 | 64 | 18 | 9 | 26 | paulondc/chilopoda | src/lib/kombi/TaskHolder/Loader/Loader.py | Python | LoaderNotRegisteredError | LoaderNotRegisteredError | 8 | 9 | 8 | 8 | d634e0caed62d2ca8746ffca1d33a92c6005000a | bigcode/the-stack | train |
a3c5602f5c7cc29d1f214470 | train | class | class Loader(object):
"""
Abstracted task holders loader.
"""
__registered = {}
def __init__(self):
"""
Create a config loader.
"""
self.__taskHolders = []
def loadFromDirectory(self, directory):
"""
Load the configuration from inside of a direc... | class Loader(object):
| """
Abstracted task holders loader.
"""
__registered = {}
def __init__(self):
"""
Create a config loader.
"""
self.__taskHolders = []
def loadFromDirectory(self, directory):
"""
Load the configuration from inside of a directory by looking for co... | import os
import uuid
from ..TaskHolder import TaskHolder
class LoaderError(Exception):
"""Task Holder Loader Error."""
class LoaderNotRegisteredError(LoaderError):
"""Task Holder Loader Not Registered Error."""
class LoaderInvalidConfigError(LoaderError):
"""Task Holder Loader Invalid Config Error."""
c... | 66 | 245 | 819 | 4 | 62 | paulondc/chilopoda | src/lib/kombi/TaskHolder/Loader/Loader.py | Python | Loader | Loader | 14 | 149 | 14 | 14 | bbcd13a4bf1e9dae556582fc68da77b0dc953f64 | bigcode/the-stack | train |
fa30b0477bc94b8966f79f37 | train | class | class LoaderError(Exception):
"""Task Holder Loader Error."""
| class LoaderError(Exception):
| """Task Holder Loader Error."""
| import os
import uuid
from ..TaskHolder import TaskHolder
class LoaderError(Exception):
| 19 | 64 | 12 | 5 | 13 | paulondc/chilopoda | src/lib/kombi/TaskHolder/Loader/Loader.py | Python | LoaderError | LoaderError | 5 | 6 | 5 | 5 | 74458c5c2bbd17a136d0628129fd0dfde622080b | bigcode/the-stack | train |
5224f9a5e600e5aa57beb14b | train | class | class LoaderInvalidConfigError(LoaderError):
"""Task Holder Loader Invalid Config Error."""
| class LoaderInvalidConfigError(LoaderError):
| """Task Holder Loader Invalid Config Error."""
| import os
import uuid
from ..TaskHolder import TaskHolder
class LoaderError(Exception):
"""Task Holder Loader Error."""
class LoaderNotRegisteredError(LoaderError):
"""Task Holder Loader Not Registered Error."""
class LoaderInvalidConfigError(LoaderError):
| 53 | 64 | 18 | 9 | 44 | paulondc/chilopoda | src/lib/kombi/TaskHolder/Loader/Loader.py | Python | LoaderInvalidConfigError | LoaderInvalidConfigError | 11 | 12 | 11 | 11 | f787cdc0ddc90309eeb85a86c7159791930edca7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.