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
4974c69fcf4e09e6da618ae6
train
function
def c_compiler_path(): """ Get path to the gdb """ return os.environ.get("YA_CC")
def c_compiler_path():
""" Get path to the gdb """ return os.environ.get("YA_CC")
build root relating to build_root/project path """ return _join_path(os.path.join(build_path(), context.project_path), path) def gdb_path(): """ Get path to the gdb """ return _get_ya_plugin_instance().gdb_path def c_compiler_path():
64
64
27
6
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
c_compiler_path
c_compiler_path
203
207
203
203
8d8f914355c0ab76eafbbc1338a77560a445f113
bigcode/the-stack
train
e284e8f7fe61d0a0b4eeddc0
train
function
@not_test def test_source_path(path=None): return _join_path(os.path.join(source_path(), context.project_path), path)
@not_test def test_source_path(path=None):
return _join_path(os.path.join(source_path(), context.project_path), path)
= core_path if bt_path: log_entry['{} backtrace{}'.format(name, count_str)] = bt_path if pbt_path: log_entry['{} backtrace html{}'.format(name, count_str)] = pbt_path @not_test def test_source_path(path=None):
64
64
28
11
52
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
test_source_path
test_source_path
242
244
242
243
d8c224ec6256bc481fc7449ef680a881ed6358f9
bigcode/the-stack
train
a7468d58f02613455f684e30
train
function
def get_param(key, default=None): """ Get arbitrary parameter passed via command line :param key: key :param default: default value :return: parameter value or the default """ return _get_ya_plugin_instance().get_param(key, default)
def get_param(key, default=None):
""" Get arbitrary parameter passed via command line :param key: key :param default: default value :return: parameter value or the default """ return _get_ya_plugin_instance().get_param(key, default)
""" return _get_ya_plugin_instance().python_path def valgrind_path(): """ Get path to valgrind :return: absolute path to valgrind """ return _get_ya_plugin_instance().valgrind_path def get_param(key, default=None):
64
64
61
8
55
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
get_param
get_param
158
165
158
158
6a107e92aa57af714b4f0eb15b146e15f89e7eca
bigcode/the-stack
train
629f5b09c60a07dc10a34bea
train
function
def java_path(): """ Get path to java :return: absolute path to java """ import runtime_java return runtime_java.get_java_path(binary_path(os.path.join('contrib', 'tools', 'jdk')))
def java_path():
""" Get path to java :return: absolute path to java """ import runtime_java return runtime_java.get_java_path(binary_path(os.path.join('contrib', 'tools', 'jdk')))
inside build directory :param path: path relative to the build directory, e.g. yatest.common.build_path('devtools/ya/bin') :return: absolute path inside build directory """ return _join_path(_get_ya_plugin_instance().build_root, path) def java_path():
64
64
50
4
60
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
java_path
java_path
76
82
76
76
8268f9666e63123652124c727dcf1b2c2051e2fd
bigcode/the-stack
train
438c48bffabeb632a53636d4
train
function
def global_resources(): try: return json.loads(os.environ.get("YA_GLOBAL_RESOURCES")) except (TypeError, ValueError): return {}
def global_resources():
try: return json.loads(os.environ.get("YA_GLOBAL_RESOURCES")) except (TypeError, ValueError): return {}
gdb_path def c_compiler_path(): """ Get path to the gdb """ return os.environ.get("YA_CC") def cxx_compiler_path(): """ Get path to the gdb """ return os.environ.get("YA_CXX") def global_resources():
64
64
32
4
60
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
global_resources
global_resources
217
221
217
217
9b460da856829bd895cd79e98a585a54b1b9393e
bigcode/the-stack
train
5ed6e6b007d1895481f64030
train
function
def _norm_path(path): if path is None: return None assert isinstance(path, six.string_types) if "\\" in path: raise AssertionError("path {} contains Windows seprators \\ - replace them with '/'".format(path)) return os.path.normpath(path)
def _norm_path(path):
if path is None: return None assert isinstance(path, six.string_types) if "\\" in path: raise AssertionError("path {} contains Windows seprators \\ - replace them with '/'".format(path)) return os.path.normpath(path)
.ya: return library.python.testing.recipe except (ImportError, AttributeError): pass raise NotImplementedError("yatest.common.* is only available from the testing runtime") def _get_ya_plugin_instance(): return _get_ya_config().ya def _norm_path(path):
64
64
61
6
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
_norm_path
_norm_path
30
36
30
30
29549ab6486c9e350d3276c3f99ff6f6c543c808
bigcode/the-stack
train
2c46223e46a1353c07e6a4b4
train
function
def _join_path(main_path, path): if not path: return main_path return os.path.join(main_path, _norm_path(path))
def _join_path(main_path, path):
if not path: return main_path return os.path.join(main_path, _norm_path(path))
if path is None: return None assert isinstance(path, six.string_types) if "\\" in path: raise AssertionError("path {} contains Windows seprators \\ - replace them with '/'".format(path)) return os.path.normpath(path) def _join_path(main_path, path):
64
64
32
9
55
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
_join_path
_join_path
39
42
39
39
be98dd179d4a63c4bdb3bc1618845ef96b70ccde
bigcode/the-stack
train
1b3cafc88c446ce99272135e
train
function
def work_path(path=None): """ Get path inside the current test suite working directory. Creating files in the work directory does not guarantee that files will be accessible after the test suite execution :param path: path relative to the test suite working dir :return: absolute path inside the test...
def work_path(path=None):
""" Get path inside the current test suite working directory. Creating files in the work directory does not guarantee that files will be accessible after the test suite execution :param path: path relative to the test suite working dir :return: absolute path inside the test suite working dir """...
the binary relative to the build directory e.g. yatest.common.binary_path('devtools/ya/bin/ya-bin') :return: absolute path to the binary """ path = _norm_path(path) return _get_ya_plugin_instance().get_binary(path) def work_path(path=None):
64
64
89
6
58
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
work_path
work_path
132
139
132
132
9ad5d52303c44cf988c3f22d6784506e7fccdcc4
bigcode/the-stack
train
15183afb7688653176fc7c5b
train
function
def _get_ya_plugin_instance(): return _get_ya_config().ya
def _get_ya_plugin_instance():
return _get_ya_config().ya
try: import library.python.testing.recipe if library.python.testing.recipe.ya: return library.python.testing.recipe except (ImportError, AttributeError): pass raise NotImplementedError("yatest.common.* is only available from the testing runtime...
64
64
18
8
56
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
_get_ya_plugin_instance
_get_ya_plugin_instance
26
27
26
26
cbdc0f90656eb1cc94da15aa4405ea2e8a9f1ce3
bigcode/the-stack
train
d009b20acd167bdfa9f74558
train
function
def valgrind_path(): """ Get path to valgrind :return: absolute path to valgrind """ return _get_ya_plugin_instance().valgrind_path
def valgrind_path():
""" Get path to valgrind :return: absolute path to valgrind """ return _get_ya_plugin_instance().valgrind_path
""" return _join_path(os.environ.get("TEST_WORK_PATH") or os.getcwd(), path) def python_path(): """ Get path to the arcadia python :return: absolute path to python """ return _get_ya_plugin_instance().python_path def valgrind_path():
64
64
43
6
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
valgrind_path
valgrind_path
150
155
150
150
2e55aaaa62c0969052db51caca3e79ee9ea15520
bigcode/the-stack
train
ed7c00801dd5fd414edbfc44
train
function
def cxx_compiler_path(): """ Get path to the gdb """ return os.environ.get("YA_CXX")
def cxx_compiler_path():
""" Get path to the gdb """ return os.environ.get("YA_CXX")
def gdb_path(): """ Get path to the gdb """ return _get_ya_plugin_instance().gdb_path def c_compiler_path(): """ Get path to the gdb """ return os.environ.get("YA_CC") def cxx_compiler_path():
64
64
29
7
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
cxx_compiler_path
cxx_compiler_path
210
214
210
210
9ac4202385685870ddcd0ff48010089ac3b27bde
bigcode/the-stack
train
b639bfb4be5e4d960863f50e
train
function
def ram_drive_path(path=None): """ :param path: path relative to the ram drive. :return: absolute path inside the ram drive directory or None if no ram drive was provided by environment. """ if 'YA_TEST_RAM_DRIVE_PATH' in os.environ: return _join_path(os.environ['YA_TEST_RAM_DRIVE_PATH'], pa...
def ram_drive_path(path=None):
""" :param path: path relative to the ram drive. :return: absolute path inside the ram drive directory or None if no ram drive was provided by environment. """ if 'YA_TEST_RAM_DRIVE_PATH' in os.environ: return _join_path(os.environ['YA_TEST_RAM_DRIVE_PATH'], path)
that files will be accessible after the test suite execution. :param path: path relative to the test suite output dir :return: absolute path inside the test suite output dir """ return _join_path(_get_ya_plugin_instance().output_dir, path) def ram_drive_path(path=None):
64
64
76
7
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
ram_drive_path
ram_drive_path
104
110
104
104
f10e7c4d52f4626fc335801f90dad0c3a34a664a
bigcode/the-stack
train
3e2a1307daf010011119e0d1
train
class
class Context(object): """ Runtime context """ @property def build_type(self): return _get_ya_plugin_instance().get_context("build_type") @property def project_path(self): return _get_ya_plugin_instance().get_context("project_path") @property def test_stderr(self):...
class Context(object):
""" Runtime context """ @property def build_type(self): return _get_ya_plugin_instance().get_context("build_type") @property def project_path(self): return _get_ya_plugin_instance().get_context("project_path") @property def test_stderr(self): return _get_ya...
, count_str)] = core_path if bt_path: log_entry['{} backtrace{}'.format(name, count_str)] = bt_path if pbt_path: log_entry['{} backtrace html{}'.format(name, count_str)] = pbt_path @not_test def test_source_path(path=None): return _join_path(os.path.join(source_path(), context.project_path...
89
89
299
4
85
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
Context
Context
247
296
247
247
5cb391cc972fa84d094763989b437dc2eb1dcfb5
bigcode/the-stack
train
657f5a197927782af053daff
train
function
@not_test def test_output_path(path=None): """ Get dir in the suite output_path for the current test case """ import pytest test_out_dir = os.path.splitext(pytest.config.current_test_log_path)[0] if not os.path.exists(test_out_dir): os.makedirs(test_out_dir) return _join_path(test_ou...
@not_test def test_output_path(path=None):
""" Get dir in the suite output_path for the current test case """ import pytest test_out_dir = os.path.splitext(pytest.config.current_test_log_path)[0] if not os.path.exists(test_out_dir): os.makedirs(test_out_dir) return _join_path(test_out_dir, path)
_param_dict_copy(): """ Return copy of dictionary with all parameters. Changes to this dictionary do *not* change parameters. :return: copy of dictionary with all parameters """ return _get_ya_plugin_instance().get_param_dict_copy() @not_test def test_output_path(path=None):
64
64
79
11
53
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
test_output_path
test_output_path
177
186
177
178
0c2cc21e14bba17b3d69bbb62cb1f402e6c69422
bigcode/the-stack
train
393a8a90d994946c5405ce92
train
function
def not_test(func): """ Mark any function as not a test for py.test :param func: :return: """ @functools.wraps(func) def wrapper(*args, **kwds): return func(*args, **kwds) setattr(wrapper, '__test__', False) return wrapper
def not_test(func):
""" Mark any function as not a test for py.test :param func: :return: """ @functools.wraps(func) def wrapper(*args, **kwds): return func(*args, **kwds) setattr(wrapper, '__test__', False) return wrapper
Error("path {} contains Windows seprators \\ - replace them with '/'".format(path)) return os.path.normpath(path) def _join_path(main_path, path): if not path: return main_path return os.path.join(main_path, _norm_path(path)) def not_test(func):
64
64
73
5
59
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
not_test
not_test
45
55
45
45
cada425d9e1995f4f929f216f1133c48f3021d2d
bigcode/the-stack
train
3eb1a8b4d2b5d41c45b439d0
train
function
def data_path(path=None): """ Get path inside arcadia_tests_data directory :param path: path relative to the arcadia_tests_data directory, e.g. yatest.common.data_path("pers/rerank_service") :return: absolute path inside arcadia_tests_data """ return _join_path(_get_ya_plugin_instance().data_roo...
def data_path(path=None):
""" Get path inside arcadia_tests_data directory :param path: path relative to the arcadia_tests_data directory, e.g. yatest.common.data_path("pers/rerank_service") :return: absolute path inside arcadia_tests_data """ return _join_path(_get_ya_plugin_instance().data_root, path)
_instance().build_root, path) def java_path(): """ Get path to java :return: absolute path to java """ import runtime_java return runtime_java.get_java_path(binary_path(os.path.join('contrib', 'tools', 'jdk'))) def data_path(path=None):
63
64
79
6
57
PallHaraldsson/catboost
library/python/testing/yatest_common/yatest/common/runtime.py
Python
data_path
data_path
85
91
85
85
65643fb61ffcc8623f748efd9129b74fa18e0a69
bigcode/the-stack
train
53f72e51726f89bf559a4186
train
class
class Config(BaseModel): class Config: validate_assignment = True arbitrary_types_allowed = (TextIOBase,) @validator("aliases", "extra_template_data", pre=True) def validate_file(cls, value: Any) -> Optional[TextIOBase]: if value is None or isinstance(value, TextIOBase): ...
class Config(BaseModel):
class Config: validate_assignment = True arbitrary_types_allowed = (TextIOBase,) @validator("aliases", "extra_template_data", pre=True) def validate_file(cls, value: Any) -> Optional[TextIOBase]: if value is None or isinstance(value, TextIOBase): return value ret...
'--class-name', help='Set class name of root model', default=None, ) arg_parser.add_argument( '--custom-template-dir', help='Custom template directory', type=str ) arg_parser.add_argument( '--extra-template-data', help='Extra template data', type=FileType('rt') ) arg_parser.add_argument('--aliases', help='Ali...
230
230
767
5
225
shnups/datamodel-code-generator
datamodel_code_generator/__main__.py
Python
Config
Config
244
323
244
244
6131746428edefb0ef86c16a1aa8dd521396d30c
bigcode/the-stack
train
6691ca2a685f6d40d08fdca9
train
class
class Exit(IntEnum): """Exit reasons.""" OK = 0 ERROR = 1 KeyboardInterrupt = 2
class Exit(IntEnum):
"""Exit reasons.""" OK = 0 ERROR = 1 KeyboardInterrupt = 2
InvalidClassNameError, enable_debug_message, generate, ) from datamodel_code_generator.format import PythonVersion, is_supported_in_black from datamodel_code_generator.parser import LiteralType from datamodel_code_generator.reference import is_url from datamodel_code_generator.types import StrictTypes class Ex...
64
64
29
5
58
shnups/datamodel-code-generator
datamodel_code_generator/__main__.py
Python
Exit
Exit
38
43
38
38
14935b56e5e63a734a852ae6cf38c66ef4935bf0
bigcode/the-stack
train
94a981c8e3ddd3c4c50e917a
train
function
def main(args: Optional[Sequence[str]] = None) -> Exit: """Main function.""" # add cli completion support argcomplete.autocomplete(arg_parser) if args is None: args = sys.argv[1:] namespace: Namespace = arg_parser.parse_args(args) if namespace.version: # pragma: no cover fro...
def main(args: Optional[Sequence[str]] = None) -> Exit:
"""Main function.""" # add cli completion support argcomplete.autocomplete(arg_parser) if args is None: args = sys.argv[1:] namespace: Namespace = arg_parser.parse_args(args) if namespace.version: # pragma: no cover from datamodel_code_generator.version import version ...
_name: bool = False use_default: bool = False force_optional: bool = False class_name: Optional[str] = None use_standard_collections: bool = False use_schema_description: bool = False reuse_model: bool = False encoding: str = 'utf-8' enum_field_as_literal: Optional[LiteralType] = None ...
256
256
958
15
241
shnups/datamodel-code-generator
datamodel_code_generator/__main__.py
Python
main
main
326
451
326
326
c99fa47c906731e5adedc99b2a0e9c0f0ce445af
bigcode/the-stack
train
440ae9a66998765d9111a1a2
train
function
def sig_int_handler(_: int, __: Any) -> None: # pragma: no cover exit(Exit.OK)
def sig_int_handler(_: int, __: Any) -> None: # pragma: no cover
exit(Exit.OK)
import is_url from datamodel_code_generator.types import StrictTypes class Exit(IntEnum): """Exit reasons.""" OK = 0 ERROR = 1 KeyboardInterrupt = 2 def sig_int_handler(_: int, __: Any) -> None: # pragma: no cover
64
64
27
21
42
shnups/datamodel-code-generator
datamodel_code_generator/__main__.py
Python
sig_int_handler
sig_int_handler
46
47
46
46
5bf73874958e470ebed7384485ac22746d469150
bigcode/the-stack
train
c70b26e1bf3824f4c493b632
train
class
class GpuSkiaGoldProperties(skia_gold_properties.SkiaGoldProperties): @staticmethod def _GetGitOriginMasterHeadSha1(): try: return subprocess.check_output(['git', 'rev-parse', 'origin/master'], shell=_IsWin(), cwd=path_util.GetChrom...
class GpuSkiaGoldProperties(skia_gold_properties.SkiaGoldProperties): @staticmethod
def _GetGitOriginMasterHeadSha1(): try: return subprocess.check_output(['git', 'rev-parse', 'origin/master'], shell=_IsWin(), cwd=path_util.GetChromiumSrcDir()).strip() except subprocess.CalledProcessError: return None
.""" import subprocess import sys from gpu_tests import path_util path_util.AddDirToPathIfNeeded(path_util.GetChromiumSrcDir(), 'build') from skia_gold_common import skia_gold_properties class GpuSkiaGoldProperties(skia_gold_properties.SkiaGoldProperties): @staticmethod
64
64
82
20
43
mghgroup/Glide-Browser
content/test/gpu/gpu_tests/skia_gold/gpu_skia_gold_properties.py
Python
GpuSkiaGoldProperties
GpuSkiaGoldProperties
14
22
14
15
0a0833840daa619dba8df8c152d9a8c059a11295
bigcode/the-stack
train
a19d6304d49e451545db8e6a
train
function
def _IsWin(): return sys.platform == 'win32'
def _IsWin():
return sys.platform == 'win32'
GetGitOriginMasterHeadSha1(): try: return subprocess.check_output(['git', 'rev-parse', 'origin/master'], shell=_IsWin(), cwd=path_util.GetChromiumSrcDir()).strip() except subprocess.CalledProcessError: return None def _IsWin()...
64
64
14
5
58
mghgroup/Glide-Browser
content/test/gpu/gpu_tests/skia_gold/gpu_skia_gold_properties.py
Python
_IsWin
_IsWin
25
26
25
25
1c1b7e8d186be7de1b107bcc9724509539d6e1f4
bigcode/the-stack
train
a729ab954759b44c0f10a428
train
class
class TestSupports(unittest.TestCase): """ Test that support generation happens properly. """ def test_remove_dead_examples(self): """Tests that examples with zero weight are removed.""" n_samples = 100 n_features = 3 n_tasks = 1 # Generate dummy dataset np.random.seed(123) p = .05...
class TestSupports(unittest.TestCase):
""" Test that support generation happens properly. """ def test_remove_dead_examples(self): """Tests that examples with zero weight are removed.""" n_samples = 100 n_features = 3 n_tasks = 1 # Generate dummy dataset np.random.seed(123) p = .05 ids = np.arange(n_samples) X =...
""" Simple Tests for Support Generation """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals __author__ = "Han Altae-Tran and Bharath Ramsundar" __copyright__ = "Copyright 2016, Stanford University" __license__ = "MIT" import numpy as np import unittest im...
94
256
3,253
7
86
ozgurozkan123/deepchem
deepchem/data/tests/test_support_generator.py
Python
TestSupports
TestSupports
18
384
18
18
ea56352879577a39468fe0749c718f3439988646
bigcode/the-stack
train
822fb7e45fb7b28f81820418
train
class
class SourceFacebookPages(AbstractSource): def check_connection(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> Tuple[bool, Any]: ok = False error_msg = None try: access_token, page_id = config["access_token"], config["page_id"] access_token = self.generat...
class SourceFacebookPages(AbstractSource):
def check_connection(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> Tuple[bool, Any]: ok = False error_msg = None try: access_token, page_id = config["access_token"], config["page_id"] access_token = self.generate_page_access_token(page_id, access_token) ...
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # from typing import Any, List, Mapping, Tuple import requests from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import SyncMode from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from .streams i...
97
119
397
7
89
OTRI-Unipd/OTRI-airbyte
airbyte-integrations/connectors/source-facebook-pages/source_facebook_pages/source.py
Python
SourceFacebookPages
SourceFacebookPages
17
57
17
17
fed7d78f7b4e518bc5950200a8fb8f261eb413b8
bigcode/the-stack
train
f1b5690571014479ecb29d0a
train
class
class SimulatedAnneling(_BaseMetaHeuristic): """ Implementation of Simulated Anneling Algorithm for Feature Selection The temperature range is [initial_temp, 0]. So, the decay of the temperature each generation is given by ``temp_init/number_gen``. The total number of evaluated solution...
class SimulatedAnneling(_BaseMetaHeuristic):
""" Implementation of Simulated Anneling Algorithm for Feature Selection The temperature range is [initial_temp, 0]. So, the decay of the temperature each generation is given by ``temp_init/number_gen``. The total number of evaluated solutions are: ``number_gen * repetition_schedule`` ...
from __future__ import print_function import random from timeit import time import numpy as np from deap import base from deap import tools import copy from .meta_base import _BaseMetaHeuristic from .meta_base import BaseMask from .meta_base import * from sklearn.utils import check_random_state class SimulatedAnnel...
82
256
1,379
12
69
gonzalesMK/MetaHeuristic
feature_selection/simulated_anneling.py
Python
SimulatedAnneling
SimulatedAnneling
18
200
18
18
7bb5fbbc3799f23cd2219cf4a831dbfc73925d60
bigcode/the-stack
train
a5b49f974d7cc944c545d00a
train
function
def _test_metropolis( now, before, temp): return np.exp( (now - before)/ temp * 100)
def _test_metropolis( now, before, temp):
return np.exp( (now - before)/ temp * 100)
_solution, temp): prob = np.exp(100 * (sum(solution.fitness.wvalues) - sum(prev_solution.fitness.wvalues))/(temp)) if random.random() < prob: return solution else: return prev_solution def _test_metropolis( now, before, temp):
64
64
27
12
51
gonzalesMK/MetaHeuristic
feature_selection/simulated_anneling.py
Python
_test_metropolis
_test_metropolis
203
204
203
203
b09f291fc2a78eedbb8952e5f9715de776e0e0de
bigcode/the-stack
train
65515042cc0eddf223776849
train
function
def factor(name, log_factor): """ Factor statement to add arbitrary log probability factor to a probabilisitic model. :param str name: Name of the trivial sample :param torch.Tensor log_factor: A possibly batched log probability factor. """ unit_dist = dist.Unit(log_factor) unit_value =...
def factor(name, log_factor):
""" Factor statement to add arbitrary log probability factor to a probabilisitic model. :param str name: Name of the trivial sample :param torch.Tensor log_factor: A possibly batched log probability factor. """ unit_dist = dist.Unit(log_factor) unit_value = unit_dist.sample() sample...
None } # handle observation if obs is not None: msg["value"] = obs msg["is_observed"] = True # apply the stack and return its return value apply_stack(msg) return msg["value"] def factor(name, log_factor):
63
64
86
7
56
jrmcornish/pyro
pyro/primitives.py
Python
factor
factor
114
124
114
114
c3475a8eb48588a6f9175717a91aeffc3640ac45
bigcode/the-stack
train
b14110cb139a489212dc9e28
train
function
def sample(name, fn, *args, **kwargs): """ Calls the stochastic function `fn` with additional side-effects depending on `name` and the enclosing context (e.g. an inference algorithm). See `Intro I <http://pyro.ai/examples/intro_part_i.html>`_ and `Intro II <http://pyro.ai/examples/intro_part_ii.html...
def sample(name, fn, *args, **kwargs):
""" Calls the stochastic function `fn` with additional side-effects depending on `name` and the enclosing context (e.g. an inference algorithm). See `Intro I <http://pyro.ai/examples/intro_part_i.html>`_ and `Intro II <http://pyro.ai/examples/intro_part_ii.html>`_ for a discussion. :param name:...
param int event_dim: (optional) number of rightmost dimensions unrelated to baching. Dimension to the left of this will be considered batch dimensions; if the param statement is inside a subsampled plate, then corresponding batch dimensions of the parameter will be correspondingly subsam...
130
130
434
12
118
jrmcornish/pyro
pyro/primitives.py
Python
sample
sample
61
111
61
61
ddba1afdc28ba5002b206e76cfad0982acc753c2
bigcode/the-stack
train
177331039ec35b396ee3a37a
train
function
@contextmanager def validation_enabled(is_validate=True): """ Context manager that is useful when temporarily enabling/disabling validation checks. :param bool is_validate: (optional; defaults to True) temporary validation check override. """ infer_validation_status = infer.is_validatio...
@contextmanager def validation_enabled(is_validate=True):
""" Context manager that is useful when temporarily enabling/disabling validation checks. :param bool is_validate: (optional; defaults to True) temporary validation check override. """ infer_validation_status = infer.is_validation_enabled() distribution_validation_status = dist.is_v...
this off for mature models. :param bool is_validate: (optional; defaults to True) whether to enable validation checks. """ dist.enable_validation(is_validate) infer.enable_validation(is_validate) poutine.enable_validation(is_validate) @contextmanager def validation_enabled(is_validate=T...
64
64
127
11
53
jrmcornish/pyro
pyro/primitives.py
Python
validation_enabled
validation_enabled
376
394
376
377
516756ab56537abcb6ad0a51d9130228f73cd5ad
bigcode/the-stack
train
2b0f2339d1c7d00255517aad
train
class
class plate(PlateMessenger): """ Construct for conditionally independent sequences of variables. ``plate`` can be used either sequentially as a generator or in parallel as a context manager (formerly ``irange`` and ``iarange``, respectively). Sequential :class:`plate` is similar to :py:func:`range...
class plate(PlateMessenger):
""" Construct for conditionally independent sequences of variables. ``plate`` can be used either sequentially as a generator or in parallel as a context manager (formerly ``irange`` and ``iarange``, respectively). Sequential :class:`plate` is similar to :py:func:`range` in that it generates a ...
# initialize data structure to pass up/down the stack msg = { "type": "sample", "name": name, "fn": fn, "is_observed": False, "args": args, "kwargs": kwargs, "value": None, "infer": infer, "scale"...
256
256
1,185
6
250
jrmcornish/pyro
pyro/primitives.py
Python
plate
plate
127
231
127
127
9a88a267a9922be359c231cd7744c8fb0cde111a
bigcode/the-stack
train
2704914fd91e529b913e9f9e
train
function
def param(name, *args, **kwargs): """ Saves the variable as a parameter in the param store. To interact with the param store or write to disk, see `Parameters <parameters.html>`_. :param str name: name of parameter :param init_tensor: initial tensor or lazy callable that returns a tensor. ...
def param(name, *args, **kwargs):
""" Saves the variable as a parameter in the param store. To interact with the param store or write to disk, see `Parameters <parameters.html>`_. :param str name: name of parameter :param init_tensor: initial tensor or lazy callable that returns a tensor. For large tensors, it may be ch...
""" Returns the ParamStore """ return _PYRO_PARAM_STORE def clear_param_store(): """ Clears the ParamStore. This is especially useful if you're working in a REPL. """ return _PYRO_PARAM_STORE.clear() _param = effectful(_PYRO_PARAM_STORE.get_param, type="param") def param(name, *args, **...
79
79
266
10
69
jrmcornish/pyro
pyro/primitives.py
Python
param
param
34
58
34
34
4c2c2cfbc2e0c7da899d89c9b903833c9e1760bd
bigcode/the-stack
train
92482aff67b044c69bba2872
train
function
def get_param_store(): """ Returns the ParamStore """ return _PYRO_PARAM_STORE
def get_param_store():
""" Returns the ParamStore """ return _PYRO_PARAM_STORE
pyro.poutine.runtime import _MODULE_NAMESPACE_DIVIDER, _PYRO_PARAM_STORE, am_i_wrapped, apply_stack, effectful from pyro.poutine.subsample_messenger import SubsampleMessenger from pyro.util import deep_getattr, set_rng_seed # noqa: F401 def get_param_store():
64
64
23
5
58
jrmcornish/pyro
pyro/primitives.py
Python
get_param_store
get_param_store
17
21
17
17
9a0951e4f126b726e74a1dc000f1f36c802d6ae3
bigcode/the-stack
train
9fb57e6054dd8d7c8e075793
train
function
def random_module(name, nn_module, prior, *args, **kwargs): r""" .. warning:: The `random_module` primitive is deprecated, and will be removed in a future release. Use :class:`~pyro.nn.PyroModule` instead to to create Bayesian modules from :class:`torch.nn.Module` instances. See ...
def random_module(name, nn_module, prior, *args, **kwargs):
r""" .. warning:: The `random_module` primitive is deprecated, and will be removed in a future release. Use :class:`~pyro.nn.PyroModule` instead to to create Bayesian modules from :class:`torch.nn.Module` instances. See the `Bayesian Regression tutorial <http://pyro.ai/examples/b...
1: mod_name, param_name = name_arr[0], name_arr[1] else: is_param = True mod_name = _name if _name in target_state_dict.keys(): if not is_param: deep_getattr(nn_module, mod_name)._parameters[param_name] = target_...
112
112
375
16
95
jrmcornish/pyro
pyro/primitives.py
Python
random_module
random_module
323
357
323
323
1fde15f15561764daea4e4e76847ac728d1e7a36
bigcode/the-stack
train
4d5f64a9ff048e9c2978cb43
train
function
@contextmanager def plate_stack(prefix, sizes, rightmost_dim=-1): """ Create a contiguous stack of :class:`plate` s with dimensions:: rightmost_dim - len(sizes), ..., rightmost_dim :param str prefix: Name prefix for plates. :param iterable sizes: An iterable of plate sizes. :param int righ...
@contextmanager def plate_stack(prefix, sizes, rightmost_dim=-1):
""" Create a contiguous stack of :class:`plate` s with dimensions:: rightmost_dim - len(sizes), ..., rightmost_dim :param str prefix: Name prefix for plates. :param iterable sizes: An iterable of plate sizes. :param int rightmost_dim: The rightmost dim, counting from the right. """ ...
__init__(self, *args, **kwargs): warnings.warn("pyro.irange is deprecated; use pyro.plate instead", DeprecationWarning) super(irange, self).__init__(*args, **kwargs) @contextmanager def plate_stack(prefix, sizes, rightmost_dim=-1):
64
64
154
17
47
jrmcornish/pyro
pyro/primitives.py
Python
plate_stack
plate_stack
246
262
246
247
0c8a825eeddedce44e271d247dce7a523ac355ee
bigcode/the-stack
train
6632f05c813a51d0367c4d8c
train
function
def module(name, nn_module, update_module_params=False): """ Takes a torch.nn.Module and registers its parameters with the ParamStore. In conjunction with the ParamStore save() and load() functionality, this allows the user to save and load modules. :param name: name of module :type name: str ...
def module(name, nn_module, update_module_params=False):
""" Takes a torch.nn.Module and registers its parameters with the ParamStore. In conjunction with the ParamStore save() and load() functionality, this allows the user to save and load modules. :param name: name of module :type name: str :param nn_module: the module to be registered with Pyr...
, rightmost_dim=-1): """ Create a contiguous stack of :class:`plate` s with dimensions:: rightmost_dim - len(sizes), ..., rightmost_dim :param str prefix: Name prefix for plates. :param iterable sizes: An iterable of plate sizes. :param int rightmost_dim: The rightmost dim, counting from t...
156
156
520
12
143
jrmcornish/pyro
pyro/primitives.py
Python
module
module
265
320
265
265
ddf632a29dbae87ea2e629078ad4ad8295a9b5c2
bigcode/the-stack
train
3e714c784b0cace14bf950ce
train
class
class irange(SubsampleMessenger): def __init__(self, *args, **kwargs): warnings.warn("pyro.irange is deprecated; use pyro.plate instead", DeprecationWarning) super(irange, self).__init__(*args, **kwargs)
class irange(SubsampleMessenger):
def __init__(self, *args, **kwargs): warnings.warn("pyro.irange is deprecated; use pyro.plate instead", DeprecationWarning) super(irange, self).__init__(*args, **kwargs)
class iarange(plate): def __init__(self, *args, **kwargs): warnings.warn("pyro.iarange is deprecated; use pyro.plate instead", DeprecationWarning) super(iarange, self).__init__(*args, **kwargs) class irange(SubsampleMessenger):
64
64
56
7
57
jrmcornish/pyro
pyro/primitives.py
Python
irange
irange
240
243
240
240
3ffabc450644405414a206e3ed3ec1f83f9726fe
bigcode/the-stack
train
04f7d3ce8d6c7d225f3ce194
train
class
class iarange(plate): def __init__(self, *args, **kwargs): warnings.warn("pyro.iarange is deprecated; use pyro.plate instead", DeprecationWarning) super(iarange, self).__init__(*args, **kwargs)
class iarange(plate):
def __init__(self, *args, **kwargs): warnings.warn("pyro.iarange is deprecated; use pyro.plate instead", DeprecationWarning) super(iarange, self).__init__(*args, **kwargs)
("xy_noise", dist.Normal(loc, scale)) ... assert xy_noise.shape == (200, 320) See `SVI Part II <http://pyro.ai/examples/svi_part_ii.html>`_ for an extended discussion. """ pass class iarange(plate):
64
64
57
6
57
jrmcornish/pyro
pyro/primitives.py
Python
iarange
iarange
234
237
234
234
2e166e6d6a99489325bc52f0d5a91aaf9937b470
bigcode/the-stack
train
93f12d4c4417ab083a71272e
train
function
def enable_validation(is_validate=True): """ Enable or disable validation checks in Pyro. Validation checks provide useful warnings and errors, e.g. NaN checks, validating distribution arguments and support values, etc. which is useful for debugging. Since some of these checks may be expensive, we r...
def enable_validation(is_validate=True):
""" Enable or disable validation checks in Pyro. Validation checks provide useful warnings and errors, e.g. NaN checks, validating distribution arguments and support values, etc. which is useful for debugging. Since some of these checks may be expensive, we recommend turning this off for mature ...
def _fn(): nn_copy = copy.deepcopy(nn_module) # update_module_params must be True or the lifted module will not update local params return lifted_fn(name, nn_copy, update_module_params=True, *args, **kwargs) return _fn def enable_validation(is_validate=True):
64
64
120
7
56
jrmcornish/pyro
pyro/primitives.py
Python
enable_validation
enable_validation
360
373
360
360
08b58b6a8ef96ad17e8eb787276194d27d1ce533
bigcode/the-stack
train
43a30a0cd35d6551a48a05a7
train
function
def clear_param_store(): """ Clears the ParamStore. This is especially useful if you're working in a REPL. """ return _PYRO_PARAM_STORE.clear()
def clear_param_store():
""" Clears the ParamStore. This is especially useful if you're working in a REPL. """ return _PYRO_PARAM_STORE.clear()
_stack, effectful from pyro.poutine.subsample_messenger import SubsampleMessenger from pyro.util import deep_getattr, set_rng_seed # noqa: F401 def get_param_store(): """ Returns the ParamStore """ return _PYRO_PARAM_STORE def clear_param_store():
64
64
36
5
58
jrmcornish/pyro
pyro/primitives.py
Python
clear_param_store
clear_param_store
24
28
24
24
7c8b6129540b975ae263bd339a3de9d0645d5541
bigcode/the-stack
train
af8e3b7b79b355d3f50e73c2
train
function
def simplifiedChessEngine(whites, blacks, moves): # # Write your code here. # from functools import lru_cache n = 4 d = ( (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1), (2, 1), (1, 2), ...
def simplifiedChessEngine(whites, blacks, moves): # # Write your code here. #
from functools import lru_cache n = 4 d = ( (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1), (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2...
#!/bin/python3 import os # # Complete the simplifiedChessEngine function below. # def simplifiedChessEngine(whites, blacks, moves): # # Write your code here. #
42
173
578
23
19
ATrain951/01.python-com_Qproject
hackerrank/Algorithms/Simplified Chess Engine/solution.py
Python
simplifiedChessEngine
simplifiedChessEngine
9
81
9
12
b876799548dd25169dca9c331f049426ec65540c
bigcode/the-stack
train
a6b0219d5b53f8684b911d65
train
class
@six.add_metaclass(abc.ABCMeta) class ManagedObject(object): """Base class to represent all managed objects.""" def __init__(self, name=None, created=None, id=None): """Managed Object :param name: the name of the managed object. :param created: the time a managed object was created. ...
@six.add_metaclass(abc.ABCMeta) class ManagedObject(object):
"""Base class to represent all managed objects.""" def __init__(self, name=None, created=None, id=None): """Managed Object :param name: the name of the managed object. :param created: the time a managed object was created. :param id: the ID of the object, generated after storin...
2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # un...
129
129
432
16
112
vakwetu/castellan
castellan/common/objects/managed_object.py
Python
ManagedObject
ManagedObject
27
95
27
28
7822b0905cfd318a8be193a78d86328254b0c359
bigcode/the-stack
train
5fd7a551f55f94f8d8157661
train
function
@register.tag('block') def do_block(parser, token): """ Define a block that can be overridden by child templates. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxErro...
@register.tag('block') def do_block(parser, token):
""" Define a block that can be overridden by child templates. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) ...
rendered as an empty string." % (template_name, e.__class__.__name__), RemovedInDjango21Warning, ) logger.warning( "Exception raised while rendering {%% include %%} for " "template '%s'. Empty string rendered instead.", ...
85
86
287
13
72
prybintsev/django
django/template/loader_tags.py
Python
do_block
do_block
211
237
211
212
f4a5f13dc68ff49db04f2df6a53420d23248c8bd
bigcode/the-stack
train
cfa8fea52b2cec9710f37d47
train
class
class ExtendsNode(Node): must_be_first = True context_key = 'extends_context' def __init__(self, nodelist, parent_name, template_dirs=None): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs self.blocks = {n.name: n for n in nodelist....
class ExtendsNode(Node):
must_be_first = True context_key = 'extends_context' def __init__(self, nodelist, parent_name, template_dirs=None): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNo...
store context without thread-safety issues. block = type(self)(block.name, block.nodelist) block.context = context context['block'] = block result = block.nodelist.render(context) if push is not None: block_context.push...
176
177
593
6
170
prybintsev/django
django/template/loader_tags.py
Python
ExtendsNode
ExtendsNode
85
154
85
85
d9882324c62375284d597330567278c8b077c840
bigcode/the-stack
train
16e28ce5d0ac9b096fcd40b9
train
class
class BlockContext: def __init__(self): # Dictionary of FIFO queues. self.blocks = defaultdict(list) def add_blocks(self, blocks): for name, block in blocks.items(): self.blocks[name].insert(0, block) def pop(self, name): try: return self.blocks[name...
class BlockContext:
def __init__(self): # Dictionary of FIFO queues. self.blocks = defaultdict(list) def add_blocks(self, blocks): for name, block in blocks.items(): self.blocks[name].insert(0, block) def pop(self, name): try: return self.blocks[name].pop() exce...
django.utils.safestring import mark_safe from .base import ( Node, Template, TemplateSyntaxError, TextNode, Variable, token_kwargs, ) from .library import Library register = Library() BLOCK_CONTEXT_KEY = 'block_context' logger = logging.getLogger('django.template') class BlockContext:
64
64
125
4
60
prybintsev/django
django/template/loader_tags.py
Python
BlockContext
BlockContext
21
43
21
21
539ebb0bac8ba3c0215df3d67e85fe001d54cd88
bigcode/the-stack
train
1018f1524219850a186683ed
train
class
class BlockNode(Node): def __init__(self, name, nodelist, parent=None): self.name, self.nodelist, self.parent = name, nodelist, parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = context.render_...
class BlockNode(Node):
def __init__(self, name, nodelist, parent=None): self.name, self.nodelist, self.parent = name, nodelist, parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = context.render_context.get(BLOCK_CONTE...
for name, block in blocks.items(): self.blocks[name].insert(0, block) def pop(self, name): try: return self.blocks[name].pop() except IndexError: return None def push(self, name, block): self.blocks[name].append(block) def get_block(self...
97
97
325
5
91
prybintsev/django
django/template/loader_tags.py
Python
BlockNode
BlockNode
46
82
46
46
1ec66ca272236bcfeb6f2b3add910008cbe78f73
bigcode/the-stack
train
8ff441c85543d9abb31adee3
train
function
@register.tag('extends') def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses th...
@register.tag('extends') def do_extends(parser, token):
""" Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the pa...
_name: raise TemplateSyntaxError( "The relative path '%s' was translated to template name '%s', the " "same template in which the tag appears." % (relative_name, current_template_name) ) return '"%s"' % new_name @register.tag('extends') def do_extends(parser, toke...
72
72
243
14
57
prybintsev/django
django/template/loader_tags.py
Python
do_extends
do_extends
270
289
270
271
ffa1889346a85a2b58e2a72a5a1c443462496353
bigcode/the-stack
train
6e8858892b96cd39accfff56
train
class
class IncludeNode(Node): context_key = '__include_context' def __init__(self, template, *args, extra_context=None, isolated_context=False, **kwargs): self.template = template self.extra_context = extra_context or {} self.isolated_context = isolated_context super().__init__(*args...
class IncludeNode(Node):
context_key = '__include_context' def __init__(self, template, *args, extra_context=None, isolated_context=False, **kwargs): self.template = template self.extra_context = extra_context or {} self.isolated_context = isolated_context super().__init__(*args, **kwargs) def rend...
block nodes also need to be added to the block context. for node in compiled_parent.nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if not isinstance(node, ExtendsNode): blocks = {n.name: n for n in ...
123
123
412
5
118
prybintsev/django
django/template/loader_tags.py
Python
IncludeNode
IncludeNode
157
208
157
157
252dcf91aac23ab09057027bde5979f2d5cd98eb
bigcode/the-stack
train
98a0f978eccf6d8c8479ccf6
train
function
@register.tag('include') def do_include(parser, token): """ Loads a template and renders it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} U...
@register.tag('include') def do_include(parser, token):
""" Loads a template and renders it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to exclude the current context ...
raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) bits[1] = construct_relative_path(parser.origin.template_name, bits[1]) parent_name = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError("'%s' cannot...
118
118
394
13
105
prybintsev/django
django/template/loader_tags.py
Python
do_include
do_include
292
337
292
293
1a1a9d99327ae636475dc049eade06754d34f64c
bigcode/the-stack
train
ed0a5e04a015c004b4d84271
train
function
def construct_relative_path(current_template_name, relative_name): """ Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name. """ if not any(relative_name.startswith(x) for x in ["'./", "'../", '"./', '"../']): # relative_name is a...
def construct_relative_path(current_template_name, relative_name):
""" Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name. """ if not any(relative_name.startswith(x) for x in ["'./", "'../", '"./', '"../']): # relative_name is a variable or a literal that doesn't contain a # relative pa...
block = parser.next_token() acceptable_endblocks = ('endblock', 'endblock %s' % block_name) if endblock.contents not in acceptable_endblocks: parser.invalid_block_tag(endblock, 'endblock', acceptable_endblocks) return BlockNode(block_name, nodelist) def construct_relative_path(current_template_name...
74
74
248
11
63
prybintsev/django
django/template/loader_tags.py
Python
construct_relative_path
construct_relative_path
240
267
240
240
7078dd16ad74c7fc3478101bd4b1e63b60a85d76
bigcode/the-stack
train
53a905e05b39815596c5ecdd
train
class
class TLDetector(object): def __init__(self): rospy.init_node('tl_detector') self.pose = None self.waypoints = None self.waypoints_2d = None self.camera_image = None self.lights = [] sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb) ...
class TLDetector(object):
def __init__(self): rospy.init_node('tl_detector') self.pose = None self.waypoints = None self.waypoints_2d = None self.camera_image = None self.lights = [] sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb) sub2 = rospy.Subscriber('...
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLCla...
103
256
1,211
5
97
DanWang1230/Capstone_Programming_A_Self_Driving_Car
ros/src/tl_detector/tl_detector.py
Python
TLDetector
TLDetector
17
166
17
17
acb28efe53c1c2045f06f0842d84ce4397614acc
bigcode/the-stack
train
8b43da9b272ff06d423d88c4
train
class
class ForestFireBulldozerEnv(CAEnv): metadata = {"render.modes": ["human"]} nrows = CONFIG["grid_shape"]["nrows"] ncols = CONFIG["grid_shape"]["ncols"] @property def MDP(self): return self._MDP @property def initial_state(self): if self._resample_initial: self...
class ForestFireBulldozerEnv(CAEnv):
metadata = {"render.modes": ["human"]} nrows = CONFIG["grid_shape"]["nrows"] ncols = CONFIG["grid_shape"]["ncols"] @property def MDP(self): return self._MDP @property def initial_state(self): if self._resample_initial: self.nrows = CONFIG["grid_shape"]["nrows"...
import numpy as np from gym import spaces from gym_cellular_automata import CAEnv, GridSpace, Operator from gym_cellular_automata.forest_fire.operators import ( Modify, Move, MoveModify, RepeatCA, WindyForestFire, ) from .utils.config import CONFIG from .utils.render import render class ForestFire...
87
256
2,184
12
74
elbecerrasoto/gym-automata
gym_cellular_automata/forest_fire/bulldozer/bulldozer.py
Python
ForestFireBulldozerEnv
ForestFireBulldozerEnv
17
296
17
17
c74d0cfc4520f97dbf2a8fed7fa60a22bcc84111
bigcode/the-stack
train
230288509186a83fd41ea9b5
train
class
class MDP(Operator): grid_dependant = True action_dependant = True context_dependant = True deterministic = False def __init__(self, repeat_ca, move_modify, *args, **kwargs): super().__init__(*args, **kwargs) self.repeat_ca = repeat_ca self.move_modify = move_modify ...
class MDP(Operator):
grid_dependant = True action_dependant = True context_dependant = True deterministic = False def __init__(self, repeat_ca, move_modify, *args, **kwargs): super().__init__(*args, **kwargs) self.repeat_ca = repeat_ca self.move_modify = move_modify self.suboperators...
.action_space, "context_space": spaces.Tuple((self.ca_params_space, self.time_space)), } self.MDP_space = { "grid_space": self.grid_space, "action_space": self.action_space, "context_space": self.context_space, } class MDP(Operator):
64
64
169
6
58
elbecerrasoto/gym-automata
gym_cellular_automata/forest_fire/bulldozer/bulldozer.py
Python
MDP
MDP
299
324
299
300
9c69e0dd210ec98295fb5800b2715bb77830d3ed
bigcode/the-stack
train
749ffc348ab355a8aa4f0c48
train
function
@pytest.mark.django_db def test_event_org_domain_keep_port(env): with override_settings(SITE_URL='http://example.com:8081'): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar:8081/2015/'
@pytest.mark.django_db def test_event_org_domain_keep_port(env):
with override_settings(SITE_URL='http://example.com:8081'): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar:8081/2015/'
=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/' @pytest.mark.django_db def test_event_org_domain_keep_port(env):
63
64
73
15
48
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_keep_port
test_event_org_domain_keep_port
92
96
92
93
4b4142bb3b8319330f8cfce92e32f72aa6ba09ad
bigcode/the-stack
train
b93ef35c5eb82a1f734b148b
train
function
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_org_domain_cache_clear(env): kd = KnownDomain.objects.create(domainname='foobar', organizer=env[0...
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_org_domain_cache_clear(env):
kd = KnownDomain.objects.create(domainname='foobar', organizer=env[0]) env[0].cache.clear() with assert_num_queries(1): eventreverse(env[1], 'presale:event.index') kd.delete() with assert_num_queries(2): ev = Event.objects.get(pk=env[1].pk) assert ev.pk == env[1].pk a...
.index') @pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_org_domain_cache_clear(env):
64
64
175
62
2
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_cache_clear
test_event_org_domain_cache_clear
155
174
155
163
e657fd3b7ceb8062d6b02be53473bd2096b6410a
bigcode/the-stack
train
13e4e5794710f4eaf4b15582
train
function
@pytest.mark.django_db def test_event_org_domain_front_page(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar/2015/' assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/'
@pytest.mark.django_db def test_event_org_domain_front_page(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar/2015/' assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/'
/' @pytest.mark.django_db def test_event_main_domain_kwargs(env): assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == '/mrmcd/2015/checkout/payment/' @pytest.mark.django_db def test_event_org_domain_front_page(env):
63
64
76
15
48
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_front_page
test_event_org_domain_front_page
70
74
70
71
d29b8947239a130746877c0e53454b02f2cad084
bigcode/the-stack
train
3741fe042b8796984dbc1488
train
function
@pytest.mark.django_db def test_event_custom_domain_absolute(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert build_absolute_uri(env[1], 'presale:event.index') == 'http://barfoo/'
@pytest.mark.django_db def test_event_custom_domain_absolute(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert build_absolute_uri(env[1], 'presale:event.index') == 'http://barfoo/'
, 'presale:event.index') @pytest.mark.django_db def test_event_main_domain_absolute(env): assert build_absolute_uri(env[1], 'presale:event.index') == 'http://example.com/mrmcd/2015/' @pytest.mark.django_db def test_event_custom_domain_absolute(env):
63
64
75
14
49
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_domain_absolute
test_event_custom_domain_absolute
205
209
205
206
e29457f257fe7d99be8884ad363851b5c80f4e03
bigcode/the-stack
train
6c17417583f765654582485e
train
function
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_custom_domain_cache_clear(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0])...
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_custom_domain_cache_clear(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) kd = KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) env[0].cache.clear() with assert_num_queries(1): eventreverse(env[1], 'presale:event.index') kd.delete() with assert_num_queries(2): ...
.index') @pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) @scopes_disabled() def test_event_custom_domain_cache_clear(env):
64
64
198
62
2
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_domain_cache_clear
test_event_custom_domain_cache_clear
177
197
177
185
4112855941dc58b00d93e9928e2ab0d32355061d
bigcode/the-stack
train
c002c6b438d0e824d3e6b648
train
function
@pytest.mark.django_db def test_event_custom_domain_kwargs(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://barfoo/chec...
@pytest.mark.django_db def test_event_custom_domain_kwargs(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://barfoo/checkout/payment/'
_front_page(env): assert eventreverse(env[1], 'presale:event.index') == '/mrmcd/2015/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/' @pytest.mark.django_db def test_event_custom_domain_kwargs(env):
63
64
83
14
49
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_domain_kwargs
test_event_custom_domain_kwargs
52
56
52
53
81fcdf864c77aada404a4f2683addeb2728270eb
bigcode/the-stack
train
5f572fbb60b4c64d66bc23b7
train
function
@pytest.mark.django_db def test_event_main_domain_front_page(env): assert eventreverse(env[1], 'presale:event.index') == '/mrmcd/2015/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/'
@pytest.mark.django_db def test_event_main_domain_front_page(env):
assert eventreverse(env[1], 'presale:event.index') == '/mrmcd/2015/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/'
organizer=o, name='MRMCD2015', slug='2015', date_from=now() ) settings.SITE_URL = 'http://example.com' event.get_cache().clear() return o, event @pytest.mark.django_db def test_event_main_domain_front_page(env):
64
64
60
15
48
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_main_domain_front_page
test_event_main_domain_front_page
46
49
46
47
fdaee6d9a0ccec17c4c58e0ebd6fa68b295b23a0
bigcode/the-stack
train
d986b0da20cc3ac4cf600764
train
function
@pytest.mark.django_db def test_event_org_domain_keep_scheme(env): with override_settings(SITE_URL='https://example.com'): settings.SITE_URL = 'https://example.com' KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'https:...
@pytest.mark.django_db def test_event_org_domain_keep_scheme(env):
with override_settings(SITE_URL='https://example.com'): settings.SITE_URL = 'https://example.com' KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'https://foobar/2015/'
example.com:8081'): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar:8081/2015/' @pytest.mark.django_db def test_event_org_domain_keep_scheme(env):
63
64
79
15
48
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_keep_scheme
test_event_org_domain_keep_scheme
99
104
99
100
b3aef434d6fd9fd52bcf7d953c738d38abcb6c0e
bigcode/the-stack
train
e00aef203a609edd26dc1cfe
train
function
@pytest.mark.django_db def test_event_main_domain_absolute(env): assert build_absolute_uri(env[1], 'presale:event.index') == 'http://example.com/mrmcd/2015/'
@pytest.mark.django_db def test_event_main_domain_absolute(env):
assert build_absolute_uri(env[1], 'presale:event.index') == 'http://example.com/mrmcd/2015/'
.objects.get(pk=env[1].pk) assert ev.pk == env[1].pk assert ev.organizer == env[0] with assert_num_queries(1): eventreverse(ev, 'presale:event.index') @pytest.mark.django_db def test_event_main_domain_absolute(env):
64
64
42
14
50
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_main_domain_absolute
test_event_main_domain_absolute
200
202
200
201
a6308fd413ce0b6cf2a7437f9956502a839ceda6
bigcode/the-stack
train
c1c75a79610eb2b101bba617
train
function
@pytest.mark.django_db def test_event_main_domain_kwargs(env): assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == '/mrmcd/2015/checkout/payment/'
@pytest.mark.django_db def test_event_main_domain_kwargs(env):
assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == '/mrmcd/2015/checkout/payment/'
): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://foobar/2015/checkout/payment/' @pytest.mark.django_db def test_event_main_domain_kwargs(env):
63
64
46
14
49
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_main_domain_kwargs
test_event_main_domain_kwargs
65
67
65
66
d2303c9f36300ce91af7971aa393242c7dcaae90
bigcode/the-stack
train
05e8bb7e64ddfc93593896d5
train
function
@pytest.mark.django_db def test_event_org_domain_absolute(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert build_absolute_uri(env[1], 'presale:event.index') == 'http://foobar/2015/'
@pytest.mark.django_db def test_event_org_domain_absolute(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert build_absolute_uri(env[1], 'presale:event.index') == 'http://foobar/2015/'
env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert build_absolute_uri(env[1], 'presale:event.index') == 'http://barfoo/' @pytest.mark.django_db def test_event_org_domain_absolute(env):
63
64
54
14
49
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_absolute
test_event_org_domain_absolute
212
215
212
213
2eb2070129610575293871f5c517763cbac9630c
bigcode/the-stack
train
6d407c1efd86fa6c455e97c2
train
function
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_custom_domain_cache(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects....
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_custom_domain_cache(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) env[0].get_cache().clear() with assert_num_queries(1): eventreverse(env[1], 'presale:event.index') with assert_num_queries(0): eventrevers...
1], 'presale:event.index') @pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_custom_domain_cache(env):
64
64
147
56
8
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_domain_cache
test_event_custom_domain_cache
138
152
138
145
1abe724e69006ea5590f993df8c2e405c5e98d5d
bigcode/the-stack
train
8bcfd4436aadd4e2b340a523
train
function
@pytest.fixture def env(): o = Organizer.objects.create(name='MRMCD', slug='mrmcd') event = Event.objects.create( organizer=o, name='MRMCD2015', slug='2015', date_from=now() ) settings.SITE_URL = 'http://example.com' event.get_cache().clear() return o, event
@pytest.fixture def env():
o = Organizer.objects.create(name='MRMCD', slug='mrmcd') event = Event.objects.create( organizer=o, name='MRMCD2015', slug='2015', date_from=now() ) settings.SITE_URL = 'http://example.com' event.get_cache().clear() return o, event
.utils.timezone import now from django_scopes import scopes_disabled from tests import assert_num_queries from pretix.base.models import Event, Organizer from pretix.multidomain.models import KnownDomain from pretix.multidomain.urlreverse import build_absolute_uri, eventreverse @pytest.fixture def env():
64
64
81
6
57
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
env
env
34
43
34
35
cffb7055ba81a41c422f875876e05a47397eb0cc
bigcode/the-stack
train
3e0e19f1e376165245c0f329
train
function
@pytest.mark.django_db def test_event_org_domain_kwargs(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://foobar/2015/checkout/payment/'
@pytest.mark.django_db def test_event_org_domain_kwargs(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://foobar/2015/checkout/payment/'
.create(domainname='barfoo', organizer=env[0], event=env[1]) assert eventreverse(env[1], 'presale:event.checkout', {'step': 'payment'}) == 'http://barfoo/checkout/payment/' @pytest.mark.django_db def test_event_org_domain_kwargs(env):
63
64
62
14
49
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_kwargs
test_event_org_domain_kwargs
59
62
59
60
3ac08dd9b26041086371970e5837af21e564d9b4
bigcode/the-stack
train
c27ff1a8ff715431741d3d6c
train
function
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_org_domain_cache(env): KnownDomain.objects.create(domainname='foobar', organizer=env[0]) env[0].get_cache().clea...
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_org_domain_cache(env):
KnownDomain.objects.create(domainname='foobar', organizer=env[0]) env[0].get_cache().clear() with assert_num_queries(1): eventreverse(env[1], 'presale:event.index') with assert_num_queries(0): eventreverse(env[1], 'presale:event.index')
1], 'presale:event.index') @pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_org_domain_cache(env):
64
64
124
56
8
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_org_domain_cache
test_event_org_domain_cache
122
135
122
129
1b3c71209a32a4f5f3933cb971480ba9c84dadf0
bigcode/the-stack
train
708069230b16902898e798ab
train
function
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_main_domain_cache(env): env[0].get_cache().clear() with assert_num_queries(1): eventreverse(env[1], 'pre...
@pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_main_domain_cache(env):
env[0].get_cache().clear() with assert_num_queries(1): eventreverse(env[1], 'presale:event.index') with assert_num_queries(0): eventreverse(env[1], 'presale:event.index')
https://foobar/2015/' @pytest.mark.django_db @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }) def test_event_main_domain_cache(env):
63
64
108
56
7
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_main_domain_cache
test_event_main_domain_cache
107
119
107
114
97e871b0ed75ab37543b39bb13927922ddc66452
bigcode/the-stack
train
3958a4b4218aa749972b9e91
train
function
@pytest.mark.django_db def test_event_custom_domain_front_page(env): KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/'
@pytest.mark.django_db def test_event_custom_domain_front_page(env):
KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/'
[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://foobar/2015/' assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/' @pytest.mark.django_db def test_event_custom_domain_front_page(env):
63
64
81
15
48
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_domain_front_page
test_event_custom_domain_front_page
77
81
77
78
340c4ce30d191a3356e86074122f507597e31c05
bigcode/the-stack
train
f387106274b0edcd7e029dde
train
function
@pytest.mark.django_db def test_event_custom_and_org_domain_front_page(env): KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eve...
@pytest.mark.django_db def test_event_custom_and_org_domain_front_page(env):
KnownDomain.objects.create(domainname='barfoo', organizer=env[0], event=env[1]) KnownDomain.objects.create(domainname='foobar', organizer=env[0]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/'
[1]) assert eventreverse(env[1], 'presale:event.index') == 'http://barfoo/' assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/' @pytest.mark.django_db def test_event_custom_and_org_domain_front_page(env):
63
64
99
17
46
hansegucker/pretix
src/tests/multidomain/test_urlreverse.py
Python
test_event_custom_and_org_domain_front_page
test_event_custom_and_org_domain_front_page
84
89
84
85
28d1091f735b1cf565f5465cb30b7a56fce1c249
bigcode/the-stack
train
5190ce6aa5e3d4db392dd57f
train
function
def suite(): testSuite = unittest.TestSuite() if ocl: testSuite.addTest(TestReduction("test_max_min_rnd")) testSuite.addTest(TestReduction("test_max_min")) testSuite.addTest(TestReduction("test_max_min_rnd_big")) testSuite.addTest(TestReduction("test_max_min_serial")) tes...
def suite():
testSuite = unittest.TestSuite() if ocl: testSuite.addTest(TestReduction("test_max_min_rnd")) testSuite.addTest(TestReduction("test_max_min")) testSuite.addTest(TestReduction("test_max_min_rnd_big")) testSuite.addTest(TestReduction("test_max_min_serial")) testSuite.addTes...
s ", nmax, max_res, numpy.where(data == nmax), numpy.where(data.ravel() == nmax)) self.assertEqual(nmin, min_res, "min: numpy vs OpenCL") self.assertEqual(nmax, max_res, "max: numpy vs OpenCL") def suite():
64
64
89
3
61
physwkim/silx
silx/opencl/sift/test/test_reductions.py
Python
suite
suite
221
229
221
221
ea3d0c853af6870e3e5b4743b25ac168c2cbf9b5
bigcode/the-stack
train
2aadb3f367d1a9ace03c1f3e
train
class
@unittest.skipUnless(scipy and ocl, "scipy or ocl missing") class TestReduction(unittest.TestCase): @classmethod def setUpClass(cls): super(TestReduction, cls).setUpClass() if ocl: cls.ctx = ocl.create_context() if logger.getEffectiveLevel() <= logging.INFO: ...
@unittest.skipUnless(scipy and ocl, "scipy or ocl missing") class TestReduction(unittest.TestCase): @classmethod
def setUpClass(cls): super(TestReduction, cls).setUpClass() if ocl: cls.ctx = ocl.create_context() if logger.getEffectiveLevel() <= logging.INFO: cls.PROFILE = True cls.queue = pyopencl.CommandQueue(cls.ctx, properties=pyopencl.command_queue_pr...
. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """ Test suite for all reductionsessing kernels. "...
256
256
2,047
31
225
physwkim/silx
silx/opencl/sift/test/test_reductions.py
Python
TestReduction
TestReduction
63
218
63
66
e06d7513ed4cbfef6cb5d86e93e2d1eb03c0ad39
bigcode/the-stack
train
c80b6a29b11f51651628b9ee
train
class
class Example(PyGARV): def __init__(self): #You can find out what each parameter do #looking at the source code of PyGARV class. super().__init__( popSize = 60, values = 2, mutationRate = 0.1, #10% fullMutation =...
class Example(PyGARV):
def __init__(self): #You can find out what each parameter do #looking at the source code of PyGARV class. super().__init__( popSize = 60, values = 2, mutationRate = 0.1, #10% fullMutation = True, ...
from PyGARV import * """ This class implements a Genetic Algorithm to maximize the following function. The difference from the ExamplePyGARV is that the number of generations is controlled by a while loop. (look at the end of the file) max f = 20x + 60y subject to: 30x + 20y >= 2700 5x + 10y <= 850 x + y >= 95 x, y...
107
162
541
6
101
rvertulo/PyGARV
ExamplePyGARV2.py
Python
Example
Example
17
79
17
18
1a698f8514e90ce2781b1cf09cc96df7864bf485
bigcode/the-stack
train
cd30b1a59259fb7e6f294e01
train
function
def test_angle_axis2quat(): q = nq.angle_axis2quat(0, [1, 0, 0]) assert_array_equal(q, [1, 0, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0]) assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0], True) assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis...
def test_angle_axis2quat():
q = nq.angle_axis2quat(0, [1, 0, 0]) assert_array_equal(q, [1, 0, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0]) assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [1, 0, 0], True) assert_array_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [2, 0, 0], Fals...
= nq.quat2mat(q) qt = nq.mat2quat(M) # Accept positive or negative match posm = np.allclose(q, qt) negm = np.allclose(q, -qt) assert (posm or negm) def test_angle_axis2quat():
64
64
169
7
57
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_angle_axis2quat
test_angle_axis2quat
167
175
167
167
338a3341afeee477c1112d363589b4d80fed785c
bigcode/the-stack
train
aa1a6bb60c59811e178e8de1
train
function
def test_norm(): qi = nq.eye() assert nq.norm(qi) == 1 assert nq.isunit(qi) qi[1] = 0.2 assert not nq.isunit(qi)
def test_norm():
qi = nq.eye() assert nq.norm(qi) == 1 assert nq.isunit(qi) qi[1] = 0.2 assert not nq.isunit(qi)
iqM) def test_eye(): qi = nq.eye() assert qi.dtype.kind == 'f' assert np.all([1, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3)) def test_norm():
64
64
49
4
60
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_norm
test_norm
117
122
117
117
d4e0b24c2101fd5f9bbcf3f21e48e91e8dc23d5c
bigcode/the-stack
train
287082d9c05f34d4d1c0d593
train
function
@pytest.mark.parametrize("q", unit_quats) def test_quaternion_reconstruction(q): # Test reconstruction of arbitrary unit quaternions M = nq.quat2mat(q) qt = nq.mat2quat(M) # Accept positive or negative match posm = np.allclose(q, qt) negm = np.allclose(q, -qt) assert (posm or negm)
@pytest.mark.parametrize("q", unit_quats) def test_quaternion_reconstruction(q): # Test reconstruction of arbitrary unit quaternions
M = nq.quat2mat(q) qt = nq.mat2quat(M) # Accept positive or negative match posm = np.allclose(q, qt) negm = np.allclose(q, -qt) assert (posm or negm)
q): vdash = nq.rotate_vector(vec, q) vM = np.dot(M, vec) assert_array_almost_equal(vdash, vM) @pytest.mark.parametrize("q", unit_quats) def test_quaternion_reconstruction(q): # Test reconstruction of arbitrary unit quaternions
64
64
88
29
35
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_quaternion_reconstruction
test_quaternion_reconstruction
156
164
156
158
94ef29cf68fe8dd2013a03f16c6bfb6018a9e5ff
bigcode/the-stack
train
19035915d6805dca49d96cb8
train
function
def test_eye(): qi = nq.eye() assert np.all([1, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3))
def test_eye():
qi = nq.eye() assert np.all([1, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3))
(q21) @pytest.mark.parametrize("M, q", eg_pairs) def test_inverse(M, q): iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM) def test_eye():
64
64
48
4
60
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_eye
test_eye
142
145
142
142
c2dbc2750ac8d0a717f2150a7449b7a14fc71b69
bigcode/the-stack
train
532f468a10ea2b2d3a349ee1
train
function
def test_conjugate(): # Takes sequence cq = nq.conjugate((1, 0, 0, 0)) # Returns float type assert cq.dtype.kind == 'f'
def test_conjugate(): # Takes sequence
cq = nq.conjugate((1, 0, 0, 0)) # Returns float type assert cq.dtype.kind == 'f'
nq.fillpositive([1.0] * 3) # Test corner case where w is near zero wxyz = nq.fillpositive([1, 0, 0]) assert wxyz[0] == 0.0 def test_conjugate(): # Takes sequence
64
64
45
11
52
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_conjugate
test_conjugate
74
78
74
75
746fa4cf2e7cae3f8deb8c1cfbf5c29c67726312
bigcode/the-stack
train
1c84bfa5c898dc98c477be9d
train
function
@pytest.mark.parametrize("M, q", eg_pairs) def test_inverse(M, q): iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM)
@pytest.mark.parametrize("M, q", eg_pairs) def test_inverse(M, q):
iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM)
): # Test that quaternion * same as matrix * q21 = nq.mult(q2, q1) assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21) @pytest.mark.parametrize("M, q", eg_pairs) def test_inverse(M, q):
64
64
57
18
46
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_inverse
test_inverse
134
139
134
135
029ee8873fff9a73b1a3cd45c9f0f9282b7e6159
bigcode/the-stack
train
ddff44b42f3a38366b8b6117
train
function
def test_inverse_0(): # Takes sequence iq = nq.inverse((1, 0, 0, 0)) # Returns float type assert iq.dtype.kind == 'f'
def test_inverse_0(): # Takes sequence
iq = nq.inverse((1, 0, 0, 0)) # Returns float type assert iq.dtype.kind == 'f'
_array_almost_equal, M, np.diag([1, -1, -1]) M = nq.quat2mat([0, 0, 0, 0]) assert_array_almost_equal, M, np.eye(3) def test_inverse_0(): # Takes sequence
64
64
43
11
53
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_inverse_0
test_inverse_0
95
99
95
96
1997ead5121c5f075887a090e435de9f14bce28a
bigcode/the-stack
train
386400909e6515b2572b017d
train
function
def test_eye(): qi = nq.eye() assert qi.dtype.kind == 'f' assert np.all([1, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3))
def test_eye():
qi = nq.eye() assert qi.dtype.kind == 'f' assert np.all([1, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3))
' @pytest.mark.parametrize("M, q", eg_pairs) def test_inverse_1(M, q): iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM) def test_eye():
64
64
57
4
60
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_eye
test_eye
110
114
110
110
3241e765bf619bded9b82bd9a20a04fcb85a6c62
bigcode/the-stack
train
885234b27955551acd8f0af5
train
function
@pytest.mark.parametrize("M, q", eg_pairs) def test_inverse_1(M, q): iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM)
@pytest.mark.parametrize("M, q", eg_pairs) def test_inverse_1(M, q):
iq = nq.inverse(q) iqM = nq.quat2mat(iq) iM = np.linalg.inv(M) assert np.allclose(iM, iqM)
) def test_inverse_0(): # Takes sequence iq = nq.inverse((1, 0, 0, 0)) # Returns float type assert iq.dtype.kind == 'f' @pytest.mark.parametrize("M, q", eg_pairs) def test_inverse_1(M, q):
64
64
59
20
44
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_inverse_1
test_inverse_1
102
107
102
103
77e1041892b39745d2449cc8e3ae013f93660cb5
bigcode/the-stack
train
e4ffb32e907f8bbfc8857dab
train
function
def test_fillpos(): # Takes np array xyz = np.zeros((3,)) w, x, y, z = nq.fillpositive(xyz) assert w == 1 # Or lists xyz = [0] * 3 w, x, y, z = nq.fillpositive(xyz) assert w == 1 # Errors with wrong number of values with pytest.raises(ValueError): nq.fillpositive([0, 0]) ...
def test_fillpos(): # Takes np array
xyz = np.zeros((3,)) w, x, y, z = nq.fillpositive(xyz) assert w == 1 # Or lists xyz = [0] * 3 w, x, y, z = nq.fillpositive(xyz) assert w == 1 # Errors with wrong number of values with pytest.raises(ValueError): nq.fillpositive([0, 0]) with pytest.raises(ValueError): ...
q = (w, x, y, z) Nq = np.sqrt(np.dot(q, q)) if not Nq == 0: q = tuple([e / Nq for e in q]) unit_quats.add(q) def test_fillpos(): # Takes np array
64
64
190
11
53
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_fillpos
test_fillpos
52
71
52
53
e83718b8e0a9c11f38a9d2d2688d9ff1c252ac80
bigcode/the-stack
train
264bc365ba85870597914960
train
function
def test_angle_axis(): for M, q in eg_pairs: theta, vec = nq.quat2angle_axis(q) q2 = nq.angle_axis2quat(theta, vec) nq.nearly_equivalent(q, q2) aa_mat = nq.angle_axis2mat(theta, vec) assert_array_almost_equal(aa_mat, M) unit_vec = vec / np.sqrt(vec.dot(vec)) a...
def test_angle_axis():
for M, q in eg_pairs: theta, vec = nq.quat2angle_axis(q) q2 = nq.angle_axis2quat(theta, vec) nq.nearly_equivalent(q, q2) aa_mat = nq.angle_axis2mat(theta, vec) assert_array_almost_equal(aa_mat, M) unit_vec = vec / np.sqrt(vec.dot(vec)) aa_mat2 = nq.angle_axis2...
_almost_equal(q, [0, 1, 0, 0]) q = nq.angle_axis2quat(np.pi, [2, 0, 0], False) assert_array_almost_equal(q, [0, 1, 0, 0]) def test_angle_axis():
64
64
121
5
59
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_angle_axis
test_angle_axis
178
187
178
178
fc7d4cda6a0b80c9e282dc406c98e6f5dfc88651
bigcode/the-stack
train
321a2fdd11e066b10e59e819
train
function
@pytest.mark.parametrize("vec", np.eye(3)) @pytest.mark.parametrize("M, q", eg_pairs) def test_qrotate(vec, M, q): vdash = nq.rotate_vector(vec, q) vM = np.dot(M, vec) assert_array_almost_equal(vdash, vM)
@pytest.mark.parametrize("vec", np.eye(3)) @pytest.mark.parametrize("M, q", eg_pairs) def test_qrotate(vec, M, q):
vdash = nq.rotate_vector(vec, q) vM = np.dot(M, vec) assert_array_almost_equal(vdash, vM)
, 0, 0, 0] == qi) assert np.allclose(nq.quat2mat(qi), np.eye(3)) @pytest.mark.parametrize("vec", np.eye(3)) @pytest.mark.parametrize("M, q", eg_pairs) def test_qrotate(vec, M, q):
64
64
65
32
32
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_qrotate
test_qrotate
148
153
148
150
b7fb996621cfc6940d18fcbffc7ac988e8f9c713
bigcode/the-stack
train
3781530c8fd4b0ac104b7218
train
function
def test_quat2mat(): # also tested in roundtrip case below M = nq.quat2mat([1, 0, 0, 0]) assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([3, 0, 0, 0]) assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([0, 1, 0, 0]) assert_array_almost_equal, M, np.diag([1, -1, -1]) M = nq.q...
def test_quat2mat(): # also tested in roundtrip case below
M = nq.quat2mat([1, 0, 0, 0]) assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([3, 0, 0, 0]) assert_array_almost_equal, M, np.eye(3) M = nq.quat2mat([0, 1, 0, 0]) assert_array_almost_equal, M, np.diag([1, -1, -1]) M = nq.quat2mat([0, 2, 0, 0]) assert_array_almost_equal, M, np.diag...
0 def test_conjugate(): # Takes sequence cq = nq.conjugate((1, 0, 0, 0)) # Returns float type assert cq.dtype.kind == 'f' def test_quat2mat(): # also tested in roundtrip case below
64
64
201
17
47
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_quat2mat
test_quat2mat
81
92
81
82
e7ea4ea464cd624845dbbcb32a9e25ad1d2018ad
bigcode/the-stack
train
4fc72ecd754766402a9c1a5a
train
function
@dec.slow @pytest.mark.parametrize("M1, q1", eg_pairs[0::4]) @pytest.mark.parametrize("M2, q2", eg_pairs[1::4]) def test_mult(M1, q1, M2, q2): # Test that quaternion * same as matrix * q21 = nq.mult(q2, q1) assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21)
@dec.slow @pytest.mark.parametrize("M1, q1", eg_pairs[0::4]) @pytest.mark.parametrize("M2, q2", eg_pairs[1::4]) def test_mult(M1, q1, M2, q2): # Test that quaternion * same as matrix *
q21 = nq.mult(q2, q1) assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21)
@dec.slow @pytest.mark.parametrize("M1, q1", eg_pairs[0::4]) @pytest.mark.parametrize("M2, q2", eg_pairs[1::4]) def test_mult(M1, q1, M2, q2): # Test that quaternion * same as matrix *
64
64
99
64
0
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_quaternions.py
Python
test_mult
test_mult
125
131
125
129
991761f2ad383b6ab00185dd12e814068839689a
bigcode/the-stack
train
163000c86f47ee2040d754ee
train
function
@app.route("/sparql/", methods=["GET"]) def _sparql_proxy(*args, **kwargs): parsed_url = urlparse(request.url) queries = parse_qs(parsed_url.query) #print (queries) url=request.url.replace("/sparql", "").replace( request.host_url, SPARQL_ENDPOINT) #print (url) resp = requests.request...
@app.route("/sparql/", methods=["GET"]) def _sparql_proxy(*args, **kwargs):
parsed_url = urlparse(request.url) queries = parse_qs(parsed_url.query) #print (queries) url=request.url.replace("/sparql", "").replace( request.host_url, SPARQL_ENDPOINT) #print (url) resp = requests.request( method=request.method, url=request.url.replace("/sparql", ...
queries["search"][0]) else: res_dict = {} return Response(json.dumps(res_dict).encode('utf-8'), 200, MOCK_HEADERS) else: raise NotImplementedError @app.route("/sparql/", methods=["GET"]) def _sparql_proxy(*args, **kwargs):
64
64
168
21
42
mtang724/sqid
flask/app.py
Python
_sparql_proxy
_sparql_proxy
105
123
105
106
5f612c88d5c72eb73893821960cd5e53b7b4c8b6
bigcode/the-stack
train
08919e6542b1b4db948666fe
train
function
@app.route("/", methods=["GET"]) def home_page(): return "<h1>Homepage</h1>"
@app.route("/", methods=["GET"]) def home_page():
return "<h1>Homepage</h1>"
') log.setLevel(logging.ERROR) print("# Begin Loading Property File Info") for file in PROPERTY_FILES: print (file) MOCK_CLASSIFICATION.update(build_classifications(file)) print("# Done Loading Property File Info") es = Elasticsearch(ELASTICSEARCH_HOST) @app.route("/", methods=["GET"]) def home_page():
64
64
22
11
53
mtang724/sqid
flask/app.py
Python
home_page
home_page
25
27
25
26
318078a08f60b467fd80364180975402e47c5b15
bigcode/the-stack
train
a71fa98e35e23fba6d6f99a6
train
function
@app.route("/entity/", methods=["GET"]) def _wiki_proxy(*args, **kwargs): parsed_url = urlparse(request.url) #print (parsed_url) queries = parse_qs(parsed_url.query) #print (queries) action = queries["action"][0] if action == "wbgetentities": keys = queries["ids"][0].split("|") r...
@app.route("/entity/", methods=["GET"]) def _wiki_proxy(*args, **kwargs):
parsed_url = urlparse(request.url) #print (parsed_url) queries = parse_qs(parsed_url.query) #print (queries) action = queries["action"][0] if action == "wbgetentities": keys = queries["ids"][0].split("|") res_dict = build_mediawiki_dicts_es(es, keys) return Response(json....
_url) # if parsed_url[2] == '/data/statistics.json': # content = json.dumps(build_mock_stats_dict()) # return Response(content.encode('utf-8'), 200, MOCK_HEADERS) @app.route("/entity/", methods=["GET"]) def _wiki_proxy(*args, **kwargs):
64
64
188
19
45
mtang724/sqid
flask/app.py
Python
_wiki_proxy
_wiki_proxy
84
102
84
85
452dd73ed92e96241449336dc5544e66ac13ce56
bigcode/the-stack
train
63da476a2532b1cfd3839530
train
function
@app.route("/data/<path:data_path>", methods=["GET"]) def _data_proxy(*args, **kwargs): parsed_url = urlparse(request.url) queries = parse_qs(parsed_url.query) if parsed_url[2] == '/data/properties/usage.json': content = json.dumps(MOCK_CLASSIFICATION) elif parsed_url[2] == "/data/properties/cla...
@app.route("/data/<path:data_path>", methods=["GET"]) def _data_proxy(*args, **kwargs):
parsed_url = urlparse(request.url) queries = parse_qs(parsed_url.query) if parsed_url[2] == '/data/properties/usage.json': content = json.dumps(MOCK_CLASSIFICATION) elif parsed_url[2] == "/data/properties/classification.json": content = json.dumps(MOCK_CLASSIFICATION) elif parsed_url...
)) print("# Done Loading Property File Info") es = Elasticsearch(ELASTICSEARCH_HOST) @app.route("/", methods=["GET"]) def home_page(): return "<h1>Homepage</h1>" @app.route("/data/<path:data_path>", methods=["GET"]) def _data_proxy(*args, **kwargs):
63
64
198
23
40
mtang724/sqid
flask/app.py
Python
_data_proxy
_data_proxy
29
45
29
30
221aeef5ca9b5475e9407d5788a82252978a128c
bigcode/the-stack
train
daa226fb45a71be9733b7459
train
function
def pctBetweenKeyframes(frameIndex, keyframes): frameSpan = keyframes[1]['frameIndex'] - keyframes[0]['frameIndex'] if frameSpan == 0: frameSpan = 1 framesIntoKeyframe = frameIndex - keyframes[0]['frameIndex'] pctComplete = framesIntoKeyframe / frameSpan return pctComplete
def pctBetweenKeyframes(frameIndex, keyframes):
frameSpan = keyframes[1]['frameIndex'] - keyframes[0]['frameIndex'] if frameSpan == 0: frameSpan = 1 framesIntoKeyframe = frameIndex - keyframes[0]['frameIndex'] pctComplete = framesIntoKeyframe / frameSpan return pctComplete
, b, c, d): t /= d/2 if t < 1: return c/2*t*t + b t-=1 return -c/2 * (t*(t-2) - 1) + b def pctBetweenKeyframes(frameIndex, keyframes):
64
64
81
11
52
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
pctBetweenKeyframes
pctBetweenKeyframes
226
232
226
226
c83a039a3395a7509c99aef60ea88f4f983b0c1d
bigcode/the-stack
train
f5742d1f98a4700873618d23
train
function
def drawHelper(textBlock): # draws helper bg if displayHelpers: strokeWidth(0) fill(255, 255, 0) rect(0, textBlock['yPos'], docWidth, textBlock['height']) strokeWidth(1) stroke(255,0,0) yMiddle = textBlock['yPos'] + (textBlock['height'] / 2) ...
def drawHelper(textBlock): # draws helper bg
if displayHelpers: strokeWidth(0) fill(255, 255, 0) rect(0, textBlock['yPos'], docWidth, textBlock['height']) strokeWidth(1) stroke(255,0,0) yMiddle = textBlock['yPos'] + (textBlock['height'] / 2) line((0, yMiddle), (docWidth, yMiddle)) ...
- totalHeight) / 2) + textBoxVerticalOffset for textBlock in textBlocks: textBlock['yPos'] = top - textBlock['height'] top = top - textBlock['height'] - spaceBetweenBlocks def drawHelper(textBlock): # draws helper bg
64
64
112
12
51
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
drawHelper
drawHelper
256
269
256
257
87a854ef5d545b71fcfda643ced3304cff885a07
bigcode/the-stack
train
5d71fff4847903d1cda780c9
train
function
def main(): setup() drawFrames() if saveEnabled: saveImage(exportPath)
def main():
setup() drawFrames() if saveEnabled: saveImage(exportPath)
line, so it can be spaced evenly vertically. When displayHelpers are visible, the yellow box should extend from the baseline to the top of the main mass of your letterforms. heightOffsetPct = 0.8 # show this to help set theHeight offset. displayHelpers = False def main():
64
64
23
3
60
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
main
main
127
132
127
127
396c808fda7538475d5b6e4ad04580b3529463bd
bigcode/the-stack
train
75ce084e0273626e78503a19
train
function
def setMainText(textBlock, xPos, yPos, axes): c = defaultTextColor txt = FormattedString() for axis in axes: txt.fontVariations(**axis) txt.font(fontPath) txt.append(textBlock['text'], fontSize=textBlock['textSize'], lineHeight=textBlock['textSize'], fi...
def setMainText(textBlock, xPos, yPos, axes):
c = defaultTextColor txt = FormattedString() for axis in axes: txt.fontVariations(**axis) txt.font(fontPath) txt.append(textBlock['text'], fontSize=textBlock['textSize'], lineHeight=textBlock['textSize'], fill=(c)) text(txt, (xPos,yPos), align="cent...
line((0, yMiddle), (docWidth, yMiddle)) strokeWidth(0) def variableFontInfo(): for axis, data in listFontVariations(fontPath).items(): print((axis, data)) def setMainText(textBlock, xPos, yPos, axes):
63
64
99
15
48
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
setMainText
setMainText
275
289
275
275
7b9440b2eb2d454cf50000674f0f53199f4bb95f
bigcode/the-stack
train
3055d72b0cabc1250d0adc9f
train
function
def addBackground(): fill(*docColor) rect(0,0, docWidth, docHeight)
def addBackground():
fill(*docColor) rect(0,0, docWidth, docHeight)
0 for keyframe in textBlock['keyframes']: keyframe['pct'] = i / (len(textBlock['keyframes']) - 1) i += 1 def drawFrames(): for frameIndex in range(numFrames): drawFrame(frameIndex) def addBackground():
64
64
23
4
60
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
addBackground
addBackground
168
170
168
168
653bdb25d49b657ada76879bb73476a32aee4302
bigcode/the-stack
train
668afb28a98b450ebd8f4f36
train
function
def drawFrame(frameIndex): newPage(docWidth, docHeight) addBackground() frameDuration(defaultFrameDuration) i = 1 for textBlock in textBlocks: drawHelper(textBlock) axesVals = frameAxesVals(frameIndex, textBlock) setMainText(textBlock, docWidth/2, textBlock['yPos'], axe...
def drawFrame(frameIndex):
newPage(docWidth, docHeight) addBackground() frameDuration(defaultFrameDuration) i = 1 for textBlock in textBlocks: drawHelper(textBlock) axesVals = frameAxesVals(frameIndex, textBlock) setMainText(textBlock, docWidth/2, textBlock['yPos'], axesVals) i += 1
Block['keyframes']) - 1) i += 1 def drawFrames(): for frameIndex in range(numFrames): drawFrame(frameIndex) def addBackground(): fill(*docColor) rect(0,0, docWidth, docHeight) def drawFrame(frameIndex):
63
64
87
6
57
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
drawFrame
drawFrame
172
183
172
172
368aa70c1eff7cea4c2b26ca4dc6abf02b188ba9
bigcode/the-stack
train
579945bbefa422b88f9c5107
train
function
def variableFontInfo(): for axis, data in listFontVariations(fontPath).items(): print((axis, data))
def variableFontInfo():
for axis, data in listFontVariations(fontPath).items(): print((axis, data))
strokeWidth(1) stroke(255,0,0) yMiddle = textBlock['yPos'] + (textBlock['height'] / 2) line((0, yMiddle), (docWidth, yMiddle)) strokeWidth(0) def variableFontInfo():
63
64
27
5
58
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
variableFontInfo
variableFontInfo
271
273
271
271
a7529ce6b951c314ddeb56043f1dfbc93a4402fa
bigcode/the-stack
train
1adf1559089592a1f503f1f8
train
function
def axisValsAtPct(pct, keyframes): axes = [] for axis in keyframes[0]['axes']: a = {} minVal = keyframes[0]['axes'][axis] maxVal = keyframes[1]['axes'][axis] axes.append({axis: float((maxVal - minVal) * pct + minVal) }) return axes
def axisValsAtPct(pct, keyframes):
axes = [] for axis in keyframes[0]['axes']: a = {} minVal = keyframes[0]['axes'][axis] maxVal = keyframes[1]['axes'][axis] axes.append({axis: float((maxVal - minVal) * pct + minVal) }) return axes
is the beginning value of the property. # c is the change between the beginning and destination value of the property. # d is the total time of the tween. axes = axisValsAtPct(easedPct, keyframes) return axes def axisValsAtPct(pct, keyframes):
64
64
82
11
52
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
axisValsAtPct
axisValsAtPct
198
206
198
198
555d0365e38d3b339973e485141cf8212d5f8e78
bigcode/the-stack
train
34928f2528d65f64b0dc1dc0
train
function
def frameAxesVals(frameIndex, textBlock): keyframes = relevantKeyframes(frameIndex, textBlock) pct = pctBetweenKeyframes(frameIndex, keyframes) easedPct = easeInOutQuad(pct, 0, 1, 1) # t is the current time (or position) of the tween. # b is the beginning value of the property. # c is the change...
def frameAxesVals(frameIndex, textBlock):
keyframes = relevantKeyframes(frameIndex, textBlock) pct = pctBetweenKeyframes(frameIndex, keyframes) easedPct = easeInOutQuad(pct, 0, 1, 1) # t is the current time (or position) of the tween. # b is the beginning value of the property. # c is the change between the beginning and destination val...
for textBlock in textBlocks: drawHelper(textBlock) axesVals = frameAxesVals(frameIndex, textBlock) setMainText(textBlock, docWidth/2, textBlock['yPos'], axesVals) i += 1 def frameAxesVals(frameIndex, textBlock):
63
64
127
10
52
futurefonts/type-animations
variable-fonts-blog-post/tweak-dance.py
Python
frameAxesVals
frameAxesVals
186
196
186
186
720385380d28770ab0515a8b851852e08d896593
bigcode/the-stack
train