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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baa33a1ef8a8d2b6ae95e7eb | train | function | def truncate_and_tensor(dataX, dataY, length):
"""crop any longer than length,
return new X and Y tensors"""
# Our dataset is not a sequencial (time series) dataset like in the first paper. So we don't need the code below
new_X = []
new_Y = []
for x in list(range(len(dataX))):
... | def truncate_and_tensor(dataX, dataY, length):
| """crop any longer than length,
return new X and Y tensors"""
# Our dataset is not a sequencial (time series) dataset like in the first paper. So we don't need the code below
new_X = []
new_Y = []
for x in list(range(len(dataX))):
new_X.append(dataX[x][:length])
new_... | Name.split(".")
fileName[0] += "_" + str(count)
fileName = ".".join(fileName)
else:
fileName = originalName + "_" + str(count)
count += 1
return fileName
def truncate_and_tensor(dataX, dataY, length):
| 64 | 64 | 135 | 12 | 51 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | truncate_and_tensor | truncate_and_tensor | 92 | 108 | 92 | 92 | 3dbe5f989f41f1cfdee53da22b3f9054e49b35fc | bigcode/the-stack | train |
d9ddaaad5f6a86e13c2d38bc | train | class | class ResetStatesCallback(callbacks.Callback):
def __init__(self):
self.current_epoch = 0
def on_batch_begin(self, batch, logs={}):
self.model.reset_states()
| class ResetStatesCallback(callbacks.Callback):
| def __init__(self):
self.current_epoch = 0
def on_batch_begin(self, batch, logs={}):
self.model.reset_states()
| """Given two dicts, merge them into a new dict as a shallow copy. Credit: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression"""
z = x.copy()
z.update(y)
return z
class ResetStatesCallback(callbacks.Callback):
| 64 | 64 | 41 | 8 | 55 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | ResetStatesCallback | ResetStatesCallback | 249 | 254 | 249 | 249 | 446a4749c267a90e9be7322dc4d70cf11e289a84 | bigcode/the-stack | train |
d1f65e859fc2dfda36bfce5f | train | function | def sliding_window_data(data_x, chunk_size):
"""return array of data cut into chunks of size chunk_size sliding along array
and array of tuples denoting starting index and end index for chunk"""
big_X = []
data_temp = array_to_list(data_x)
idx_len_tuples = list(range(len(data_temp[0]) - chunk_s... | def sliding_window_data(data_x, chunk_size):
| """return array of data cut into chunks of size chunk_size sliding along array
and array of tuples denoting starting index and end index for chunk"""
big_X = []
data_temp = array_to_list(data_x)
idx_len_tuples = list(range(len(data_temp[0]) - chunk_size + 1)) if ids == [] else ids
for i i... | (data_temp[0]) - chunk_size + 1)):
x = []
for s, sequence in enumerate(data_temp):
x.append(sequence[i:i + chunk_size])
big_X.append(np.array(x))
return big_X, idx_len_tuples
def sliding_window_data(data_x, chunk_size):
| 64 | 64 | 146 | 10 | 53 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | sliding_window_data | sliding_window_data | 211 | 224 | 211 | 211 | 3a93ac6836ebefaf478300d46026b2939703d561 | bigcode/the-stack | train |
e76f66c18e3e35eb693e9bda | train | function | def to_chunks(l, num_chunks):
last_one = 0
chunks = []
n = len(l) // num_chunks
# Most samples spread out
for i in range(0, n * num_chunks, n):
chunks.append(l[i:i + n])
# Extras distributed evenly:
for i in range(n * num_chunks, len(l)):
chunks[last_one].append(l[... | def to_chunks(l, num_chunks):
| last_one = 0
chunks = []
n = len(l) // num_chunks
# Most samples spread out
for i in range(0, n * num_chunks, n):
chunks.append(l[i:i + n])
# Extras distributed evenly:
for i in range(n * num_chunks, len(l)):
chunks[last_one].append(l[i])
last_one = (last_o... | (range(len(data_temp[0]) - chunk_size + 1)):
x = []
for s, sequence in enumerate(data_temp):
x.append(sequence[i:i + chunk_size])
big_X.append(np.array(x))
return big_X, idx_len_tuples
def to_chunks(l, num_chunks):
| 64 | 64 | 107 | 8 | 55 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | to_chunks | to_chunks | 227 | 239 | 227 | 227 | 7f002447ac6d36d218834bb64b056fc75d2b1157 | bigcode/the-stack | train |
d46eb1d64d478955b3e8c460 | train | function | def timestamped_to_vector(data, classification_col=1):
"""Return tuple of inputs and outputs)
Removes timestamp - not desirable if irregular inputs
"""
x = []
y = []
for input_row in data:
keep = np.array([x for x in range(len(input_row)) if x not in [classification_col]])
... | def timestamped_to_vector(data, classification_col=1):
| """Return tuple of inputs and outputs)
Removes timestamp - not desirable if irregular inputs
"""
x = []
y = []
for input_row in data:
keep = np.array([x for x in range(len(input_row)) if x not in [classification_col]])
# print(keep) #[0,1,2,3,4,5,6,7,...,36]
x.a... | (new_idxs[0])))
# return x, y, np.array(new_idxs)
# print(x)
# print(x.shape)
# print(y)
# print(y.shape)
# print(idxs)
# print(np.array(idxs))
#return x, y, idxs
return x, y, np.array(idxs)
def timestamped_to_vector(data, classification_col=1):
| 87 | 87 | 292 | 12 | 75 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | timestamped_to_vector | timestamped_to_vector | 165 | 185 | 165 | 165 | b13d570807c7231bde99f57601ffbe84dd4a2050 | bigcode/the-stack | train |
a6c343788f8aaa1ec9f2ad67 | train | function | def extract_neg(input_data, targets, val_percentage):
change_every = 1 / val_percentage # add to val indicies every 1/percentage
pos = []
neg = []
classes = [pos, neg]
train_long_tensor = []
val_long_tensor = []
for t, target in enumerate(targets):
int_targ = int(target[0])
... | def extract_neg(input_data, targets, val_percentage):
| change_every = 1 / val_percentage # add to val indicies every 1/percentage
pos = []
neg = []
classes = [pos, neg]
train_long_tensor = []
val_long_tensor = []
for t, target in enumerate(targets):
int_targ = int(target[0])
classes[int_targ].append(t)
pos = pos[-... | train_data = input_data[train_long_tensor]
train_targets = targets[train_long_tensor]
val_data = input_data[val_long_tensor]
val_targets = targets[val_long_tensor]
return train_data, train_targets, val_data, val_targets
def extract_neg(input_data, targets, val_percentage):
| 64 | 64 | 148 | 11 | 52 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | extract_neg | extract_neg | 280 | 297 | 280 | 280 | fde7f7987e9758a15edc6bf3fd72bc8ecdfaa620 | bigcode/the-stack | train |
feb9d734b549052fb7426632 | train | function | def remove_short(dataX, dataY, length):
"""Remove any seqences in dataX shorter than length,
crop any longer than length, return new X and Y tensors"""
new_X = []
new_Y = []
for x in list(range(len(dataX))):
#if len(dataX[x]) >= length:
new_X.append(dataX[x][:length])
... | def remove_short(dataX, dataY, length):
| """Remove any seqences in dataX shorter than length,
crop any longer than length, return new X and Y tensors"""
new_X = []
new_Y = []
for x in list(range(len(dataX))):
#if len(dataX[x]) >= length:
new_X.append(dataX[x][:length])
new_Y.append(dataY[x][:length])
... | (dataX[x][:length])
new_Y.append(dataY[x][:length])
x, y = to_numpy_tensors(new_X, new_Y)
#x, y = to_numpy_tensors(dataX, dataY)
return x, y
def remove_short(dataX, dataY, length):
| 64 | 64 | 128 | 11 | 52 | burunkus/Linux-Malware-Prediction-Using-RNN | experiments/useful.py | Python | remove_short | remove_short | 111 | 126 | 111 | 111 | ef51601212ba07518908371dce2d23654be39c04 | bigcode/the-stack | train |
b7fb7794f5eed20841d6df69 | train | class | class StubtestUnit(unittest.TestCase):
@collect_cases
def test_basic_good(self) -> Iterator[Case]:
yield Case(
stub="def f(number: int, text: str) -> None: ...",
runtime="def f(number, text): pass",
error=None,
)
yield Case(
stub="""
... | class StubtestUnit(unittest.TestCase):
@collect_cases
| def test_basic_good(self) -> Iterator[Case]:
yield Case(
stub="def f(number: int, text: str) -> None: ...",
runtime="def f(number, text): pass",
error=None,
)
yield Case(
stub="""
class X:
def f(self, number: int, te... | and make it more like
other mypy tests.
"""
def test(*args: Any, **kwargs: Any) -> None:
cases = list(fn(*args, **kwargs))
expected_errors = set()
for c in cases:
if c.error is None:
continue
expected_error = c.error
if expected_... | 256 | 256 | 6,267 | 13 | 242 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | StubtestUnit | StubtestUnit | 167 | 1,021 | 167 | 168 | 64b56d42a5a74a957462e606a4a46cbf538faab1 | bigcode/the-stack | train |
a5e854f39c07d42596ec79c5 | train | function | def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:
"""run_stubtest used to be slow, so we used this decorator to combine cases.
If you're reading this and bored, feel free to refactor this and make it more like
other mypy tests.
"""
def test(*args: Any, **kwargs: Any) ->... | def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:
| """run_stubtest used to be slow, so we used this decorator to combine cases.
If you're reading this and bored, feel free to refactor this and make it more like
other mypy tests.
"""
def test(*args: Any, **kwargs: Any) -> None:
cases = list(fn(*args, **kwargs))
expected_errors = se... | =True
)
# remove cwd as it's not available from outside
return output.getvalue().replace(tmp_dir + os.sep, "")
class Case:
def __init__(self, stub: str, runtime: str, error: Optional[str]):
self.stub = stub
self.runtime = runtime
self.error = error
def collect_c... | 87 | 87 | 292 | 16 | 70 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | collect_cases | collect_cases | 131 | 164 | 131 | 131 | dc2c498e289f0d9b83a1e4448e4ed1951fab446f | bigcode/the-stack | train |
33a6bffb5ebe7121c48cb2bc | train | function | @contextlib.contextmanager
def use_tmp_dir(mod_name: str) -> Iterator[str]:
current = os.getcwd()
current_syspath = sys.path[:]
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
if sys.path[0] != tmp:
sys.path.insert(0, tmp)
yield tmp
... | @contextlib.contextmanager
def use_tmp_dir(mod_name: str) -> Iterator[str]:
| current = os.getcwd()
current_syspath = sys.path[:]
with tempfile.TemporaryDirectory() as tmp:
try:
os.chdir(tmp)
if sys.path[0] != tmp:
sys.path.insert(0, tmp)
yield tmp
finally:
sys.path = current_syspath[:]
if mod... |
import unittest
from typing import Any, Callable, Iterator, List, Optional
import mypy.stubtest
from mypy.stubtest import parse_options, test_stubs
from mypy.test.data import root_dir
@contextlib.contextmanager
def use_tmp_dir(mod_name: str) -> Iterator[str]:
| 64 | 64 | 108 | 19 | 44 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | use_tmp_dir | use_tmp_dir | 17 | 32 | 17 | 18 | 4725509a46286601e738b4fdfd52e616ed7ee517 | bigcode/the-stack | train |
09f54f4c1280f815000f2d02 | train | function | def remove_color_code(s: str) -> str:
return re.sub("\\x1b.*?m", "", s) # this works!
| def remove_color_code(s: str) -> str:
| return re.sub("\\x1b.*?m", "", s) # this works!
| runtime="""
opt1 = {"a": "3.", "b": 14}
opt2 = {"some": "stuff"} # false negative
opt3 = 0
""",
error="opt3",
)
def remove_color_code(s: str) -> str:
| 64 | 64 | 31 | 11 | 53 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | remove_color_code | remove_color_code | 1,024 | 1,025 | 1,024 | 1,024 | ead53c683d28ea32e6021da144a1d4f2628b9f61 | bigcode/the-stack | train |
2641dde738c9041f2ba0da19 | train | class | class StubtestMiscUnit(unittest.TestCase):
def test_output(self) -> None:
output = run_stubtest(
stub="def bad(number: int, text: str) -> None: ...",
runtime="def bad(num, text): pass",
options=[],
)
expected = (
'error: {0}.bad is inconsistent... | class StubtestMiscUnit(unittest.TestCase):
| def test_output(self) -> None:
output = run_stubtest(
stub="def bad(number: int, text: str) -> None: ...",
runtime="def bad(num, text): pass",
options=[],
)
expected = (
'error: {0}.bad is inconsistent, stub argument "number" differs from runti... | runtime="WRONG_BOOL_2 = True",
error='WRONG_BOOL_2',
)
@collect_cases
def test_special_subtype(self) -> Iterator[Case]:
yield Case(
stub="""
b1: bool
b2: bool
b3: bool
""",
runtime="""
b1... | 256 | 256 | 1,398 | 9 | 247 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | StubtestMiscUnit | StubtestMiscUnit | 1,028 | 1,178 | 1,028 | 1,028 | acfc203d41c75a284b6d04d2e49715ead75b7c70 | bigcode/the-stack | train |
ec7e8e05c6477f08c46af9ab | train | class | class Case:
def __init__(self, stub: str, runtime: str, error: Optional[str]):
self.stub = stub
self.runtime = runtime
self.error = error
| class Case:
| def __init__(self, stub: str, runtime: str, error: Optional[str]):
self.stub = stub
self.runtime = runtime
self.error = error
| with contextlib.redirect_stdout(output):
test_stubs(
parse_options([TEST_MODULE_NAME] + options),
use_builtins_fixtures=True
)
# remove cwd as it's not available from outside
return output.getvalue().replace(tmp_dir + os.sep, "")
class Case:
| 63 | 64 | 41 | 3 | 60 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | Case | Case | 124 | 128 | 124 | 124 | 7b05531335000c1af27430975ede1a34bd37de76 | bigcode/the-stack | train |
10c590195e98902bf23ee6ad | train | function | def run_stubtest(
stub: str, runtime: str, options: List[str], config_file: Optional[str] = None,
) -> str:
with use_tmp_dir(TEST_MODULE_NAME) as tmp_dir:
with open("builtins.pyi", "w") as f:
f.write(stubtest_builtins_stub)
with open("typing.pyi", "w") as f:
f.write(stubt... | def run_stubtest(
stub: str, runtime: str, options: List[str], config_file: Optional[str] = None,
) -> str:
| with use_tmp_dir(TEST_MODULE_NAME) as tmp_dir:
with open("builtins.pyi", "w") as f:
f.write(stubtest_builtins_stub)
with open("typing.pyi", "w") as f:
f.write(stubtest_typing_stub)
with open(f"{TEST_MODULE_NAME}.pyi", "w") as f:
f.write(stub)
with ... | ...
class bytes: ...
class list(Sequence[T]): ...
def property(f: T) -> T: ...
def classmethod(f: T) -> T: ...
def staticmethod(f: T) -> T: ...
"""
def run_stubtest(
stub: str, runtime: str, options: List[str], config_file: Optional[str] = None,
) -> str:
| 77 | 77 | 259 | 32 | 45 | edupyter/EDUPYTER38 | Lib/site-packages/mypy/test/teststubtest.py | Python | run_stubtest | run_stubtest | 98 | 121 | 98 | 100 | 4e71a72f5d7560f033e066a28ee60d1c8ba6b8c2 | bigcode/the-stack | train |
56c9a52d6545e823beed9575 | train | class | class Installer:
def __init__(
self,
io: IO,
env: Env,
package: ProjectPackage,
locker: Locker,
pool: Pool,
config: Config,
installed: Repository | None = None,
executor: Executor | None = None,
):
self._io = io
self._env = ... | class Installer:
| def __init__(
self,
io: IO,
env: Env,
package: ProjectPackage,
locker: Locker,
pool: Pool,
config: Config,
installed: Repository | None = None,
executor: Executor | None = None,
):
self._io = io
self._env = env
self.... | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Iterable
from typing import Sequence
from cleo.io.null_io import NullIO
from poetry.installation.executor import Executor
from poetry.installation.operations import Install
from poetry.installation.operations import Uninstall
from... | 214 | 256 | 3,498 | 3 | 210 | anthonymichaelclark/poetry | src/poetry/installation/installer.py | Python | Installer | Installer | 34 | 548 | 34 | 34 | 917c6b15178c39cac808a104fc9d142f80b93e4f | bigcode/the-stack | train |
8e172f302d216b224b8e53c5 | train | class | class PyHttpbin(PythonPackage):
"""HTTP Request and Response Service"""
homepage = "https://github.com/Runscope/httpbin"
url = "https://pypi.io/packages/source/h/httpbin/httpbin-0.5.0.tar.gz"
version('0.5.0', '923793df99156caa484975ade96ee115')
depends_on('py-setuptools', type='build')
... | class PyHttpbin(PythonPackage):
| """HTTP Request and Response Service"""
homepage = "https://github.com/Runscope/httpbin"
url = "https://pypi.io/packages/source/h/httpbin/httpbin-0.5.0.tar.gz"
version('0.5.0', '923793df99156caa484975ade96ee115')
depends_on('py-setuptools', type='build')
depends_on('py-decorator@3.4.0... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyHttpbin(PythonPackage):
| 62 | 64 | 200 | 8 | 54 | nkianggiss/spack | var/spack/repos/builtin/packages/py-httpbin/package.py | Python | PyHttpbin | PyHttpbin | 9 | 22 | 9 | 9 | b4726e3a8f9bacbd284ecc3167940bf9a1a97f1e | bigcode/the-stack | train |
6f276776a566c3445566313c | train | class | class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Menu02 Demo")
wx.Panel(self)
menu_bar = wx.MenuBar()
# 复选开关菜单项
self.menu = wx.Menu()
self.str1 = self.menu.AppendRadioItem(-1, "aaa")
self.str2 = self.menu.AppendRadioIte... | class MyFrame(wx.Frame):
| def __init__(self):
wx.Frame.__init__(self, None, -1, "Menu02 Demo")
wx.Panel(self)
menu_bar = wx.MenuBar()
# 复选开关菜单项
self.menu = wx.Menu()
self.str1 = self.menu.AppendRadioItem(-1, "aaa")
self.str2 = self.menu.AppendRadioItem(-1, "bbb")
self... | # -*- coding: utf-8 -*-
import wx
class MyFrame(wx.Frame):
| 18 | 162 | 540 | 6 | 11 | anliven/Reading-Code-Learning-Python | Python3-GUI/QuickStart-wxPython/wxPython_13_Menu02.py | Python | MyFrame | MyFrame | 5 | 57 | 5 | 5 | 7497a144ae63b8d09de2aa0d4edc280429c41b3d | bigcode/the-stack | train |
3b5d0822a1750227d3b8f7c7 | train | class | class GetIdentityInfoResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the GetIdentityInfo Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Respon... | class GetIdentityInfoResultSet(ResultSet):
| """
A ResultSet with methods tailored to the values returned by the GetIdentityInfo Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the ... | ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid: Specify json, or xml. Default is set to json.)
"""
super(GetIdentityInfoInputSet, self)._set_input('ResponseFormat', value)
class GetIdentityInfoResultSet(ResultSet):
| 64 | 64 | 122 | 9 | 55 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/NewsletterAPI/Identity/GetIdentityInfo.py | Python | GetIdentityInfoResultSet | GetIdentityInfoResultSet | 80 | 93 | 80 | 80 | 821df006e63146fd8bee634c81c06f02a61ca1a5 | bigcode/the-stack | train |
89f7eec415d1a231d042068d | train | class | class GetIdentityInfoInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the GetIdentityInfo
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the API... | class GetIdentityInfoInputSet(InputSet):
| """
An InputSet with methods appropriate for specifying the inputs to the GetIdentityInfo
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((required, st... | SendGrid/NewsletterAPI/Identity/GetIdentityInfo')
def new_input_set(self):
return GetIdentityInfoInputSet()
def _make_result_set(self, result, path):
return GetIdentityInfoResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return GetIdentityInfoChoreograph... | 88 | 88 | 295 | 9 | 79 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/NewsletterAPI/Identity/GetIdentityInfo.py | Python | GetIdentityInfoInputSet | GetIdentityInfoInputSet | 53 | 77 | 53 | 53 | ec8b7def7cf72f80a4f969be5be036167b0611a7 | bigcode/the-stack | train |
66731806bcbf586188e4cd52 | train | class | class GetIdentityInfoChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return GetIdentityInfoResultSet(response, path)
| class GetIdentityInfoChoreographyExecution(ChoreographyExecution):
| def _make_result_set(self, response, path):
return GetIdentityInfoResultSet(response, path)
| """
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
"""
return self._output.get('Response', None)
class GetIdentityInfoChoreographyExecution(ChoreographyExecution):
| 64 | 64 | 37 | 14 | 50 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/NewsletterAPI/Identity/GetIdentityInfo.py | Python | GetIdentityInfoChoreographyExecution | GetIdentityInfoChoreographyExecution | 95 | 98 | 95 | 96 | d8b14387127e072eabe1964dc10277884c45f3fb | bigcode/the-stack | train |
748e26660c6857f30a738785 | train | class | class GetIdentityInfo(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the GetIdentityInfo Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(GetIdentityInfo, self).__init__(temboo_session,... | class GetIdentityInfo(Choreography):
| def __init__(self, temboo_session):
"""
Create a new instance of the GetIdentityInfo Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(GetIdentityInfo, self).__init__(temboo_session, '/Library/SendGrid/NewsletterAPI/Iden... | .
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetIdentityI... | 64 | 64 | 154 | 9 | 54 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/NewsletterAPI/Identity/GetIdentityInfo.py | Python | GetIdentityInfo | GetIdentityInfo | 34 | 51 | 34 | 35 | 0935108fcc9c1df3dd77f9c51e9d3a8c838e91a7 | bigcode/the-stack | train |
bf3fc4561cd5ed8c2893face | train | class | class VideoClips(object):
"""
Given a list of video files, computes all consecutive subvideos of size
`clip_length_in_frames`, where the distance between each subvideo in the
same video is defined by `frames_between_clips`.
If `frame_rate` is specified, it will also resample all the videos to have
... | class VideoClips(object):
| """
Given a list of video files, computes all consecutive subvideos of size
`clip_length_in_frames`, where the distance between each subvideo in the
same video is defined by `frames_between_clips`.
If `frame_rate` is specified, it will also resample all the videos to have
the same frame rate, an... | similar to tensor.unfold, but with the dilation
and specialized for 1d tensors
Returns all consecutive windows of `size` elements, with
`step` between windows. The distance between each element
in a window is given by `dilation`.
"""
assert tensor.dim() == 1
o_stride = tensor.stride(0)
... | 256 | 256 | 2,371 | 6 | 250 | tengerye/vision | torchvision/datasets/video_utils.py | Python | VideoClips | VideoClips | 61 | 324 | 61 | 61 | 400929e24199ddde7df2c194aef0de3515cff592 | bigcode/the-stack | train |
b59c213d97ed2fb5f4c49437 | train | function | def unfold(tensor, size, step, dilation=1):
"""
similar to tensor.unfold, but with the dilation
and specialized for 1d tensors
Returns all consecutive windows of `size` elements, with
`step` between windows. The distance between each element
in a window is given by `dilation`.
"""
asser... | def unfold(tensor, size, step, dilation=1):
| """
similar to tensor.unfold, but with the dilation
and specialized for 1d tensors
Returns all consecutive windows of `size` elements, with
`step` between windows. The distance between each element
in a window is given by `dilation`.
"""
assert tensor.dim() == 1
o_stride = tensor.st... | base. Fraction
timebase_to: new timebase. Fraction
round_func: rounding function.
"""
new_pts = Fraction(pts, 1) * timebase_from / timebase_to
return round_func(new_pts)
def unfold(tensor, size, step, dilation=1):
| 64 | 64 | 182 | 13 | 51 | tengerye/vision | torchvision/datasets/video_utils.py | Python | unfold | unfold | 27 | 43 | 27 | 27 | 7a774c114d530c9ae6c4d128ac1aa210f697cbb3 | bigcode/the-stack | train |
ef5c40759f0bdbfb28195e9c | train | class | class _DummyDataset(object):
"""
Dummy dataset used for DataLoader in VideoClips.
Defined at top level so it can be pickled when forking.
"""
def __init__(self, x):
self.x = x
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return read_video_timest... | class _DummyDataset(object):
| """
Dummy dataset used for DataLoader in VideoClips.
Defined at top level so it can be pickled when forking.
"""
def __init__(self, x):
self.x = x
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return read_video_timestamps(self.x[idx])
| - (dilation * (size - 1) + 1)) // step + 1, size)
if new_size[0] < 1:
new_size = (0, size)
return torch.as_strided(tensor, new_size, new_stride)
class _DummyDataset(object):
| 64 | 64 | 84 | 6 | 58 | tengerye/vision | torchvision/datasets/video_utils.py | Python | _DummyDataset | _DummyDataset | 46 | 58 | 46 | 46 | d322233eb11e57d0ab6e95c097fb3239db2dc4ec | bigcode/the-stack | train |
7c154317f5b6c802252ecceb | train | function | def pts_convert(pts, timebase_from, timebase_to, round_func=math.floor):
"""convert pts between different time bases
Args:
pts: presentation timestamp, float
timebase_from: original timebase. Fraction
timebase_to: new timebase. Fraction
round_func: rounding function.
"""
... | def pts_convert(pts, timebase_from, timebase_to, round_func=math.floor):
| """convert pts between different time bases
Args:
pts: presentation timestamp, float
timebase_from: original timebase. Fraction
timebase_to: new timebase. Fraction
round_func: rounding function.
"""
new_pts = Fraction(pts, 1) * timebase_from / timebase_to
return round... | import (
_read_video_timestamps_from_file,
_read_video_from_file,
_probe_video_from_file
)
from torchvision.io import read_video_timestamps, read_video
from .utils import tqdm
def pts_convert(pts, timebase_from, timebase_to, round_func=math.floor):
| 64 | 64 | 98 | 20 | 43 | tengerye/vision | torchvision/datasets/video_utils.py | Python | pts_convert | pts_convert | 15 | 24 | 15 | 15 | 252d517fb25f7f345a62270c36b1d17d4363ccbf | bigcode/the-stack | train |
0d8b9473c65ccc723f0fb140 | train | class | class Pin(object):
def __init__(self, left_connections=[], right_connections=[]):
self.left_side_connections = left_connections
self.right_side_connections = right_connections
def paint(self, painter, point):
painter.save()
painter.setBrush(QColor(0, 0, 0, 255))
right_... | class Pin(object):
| def __init__(self, left_connections=[], right_connections=[]):
self.left_side_connections = left_connections
self.right_side_connections = right_connections
def paint(self, painter, point):
painter.save()
painter.setBrush(QColor(0, 0, 0, 255))
right_point = QPoint(poin... | # encoding: utf8
from PySide.QtCore import QPoint
from PySide.QtGui import QColor
PIN_RADIUS = 2
PIN_OFFSET = 1
class Pin(object):
| 38 | 64 | 167 | 4 | 33 | Ingener74/Olive-Moon | SubtleMonkey/Pin.py | Python | Pin | Pin | 10 | 32 | 10 | 10 | 4bcf9538f91572b89e5a92c3e6019ca30cb4b237 | bigcode/the-stack | train |
499afb86b115dac9e4be12f4 | train | function | def gcs_open(req, *args, **kwargs):
"""Open a reader stream to a blob object on GCS
"""
import spack.util.gcs as gcs_util
url = url_util.parse(req.get_full_url())
gcsblob = gcs_util.GCSBlob(url)
if not gcsblob.exists():
raise web_util.SpackWebError('GCS blob {0} does not exist'.format(... | def gcs_open(req, *args, **kwargs):
| """Open a reader stream to a blob object on GCS
"""
import spack.util.gcs as gcs_util
url = url_util.parse(req.get_full_url())
gcsblob = gcs_util.GCSBlob(url)
if not gcsblob.exists():
raise web_util.SpackWebError('GCS blob {0} does not exist'.format(
... | See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import six.moves.urllib.response as urllib_response
import spack.util.url as url_util
import spack.util.web as web_util
def gcs_open(req, *args, **kwargs):
| 64 | 64 | 136 | 12 | 51 | player1537-forks/spack | lib/spack/spack/gcs_handler.py | Python | gcs_open | gcs_open | 12 | 26 | 12 | 12 | 624b5f2870b3dc068ca35c910cda8af1918a4944 | bigcode/the-stack | train |
698e014fe6532fe6aff26867 | train | class | @unittest.skipIf(SkNearestNeighbors is None, 'scikit-learn not installed')
class Test(unittest.TestCase):
def setUp(self) -> None:
self.session = new_session().as_default()
self._old_executor = self.session._sess._executor
self.executor = self.session._sess._executor = \
Executor... | @unittest.skipIf(SkNearestNeighbors is None, 'scikit-learn not installed')
class Test(unittest.TestCase):
| def setUp(self) -> None:
self.session = new_session().as_default()
self._old_executor = self.session._sess._executor
self.executor = self.session._sess._executor = \
ExecutorForTest('numpy', storage=self.session._sess._context)
def tearDown(self) -> None:
self.sessio... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
import scipy.sparse as sps
try:
import faiss
except ImportError: # pragma: no cover
faiss = None
try:
... | 256 | 256 | 3,268 | 26 | 230 | snsnlou/mars | mars/learn/neighbors/tests/test_nearest_neighbors.py | Python | Test | Test | 45 | 431 | 45 | 46 | 55d8da73f14ae052f42a073ed1f8dbd9a8a4b218 | bigcode/the-stack | train |
aae5245aca81482391868fe7 | train | function | def get_input_frame(current_frame):
return (current_frame - 1)*2 + 11 - 2*5
| def get_input_frame(current_frame):
| return (current_frame - 1)*2 + 11 - 2*5
| import numpy as np
import torch
import os
import json
import math
import pdb
import time
import pdb
import argparse
from tqdm import tqdm
def get_input_frame(current_frame):
| 41 | 64 | 25 | 7 | 33 | archiki/ASR-Accent-Analysis | PhoneProbes/data_ready.py | Python | get_input_frame | get_input_frame | 12 | 13 | 12 | 12 | ff3dec89652bfe8a104910fee229a82e8039dd62 | bigcode/the-stack | train |
b75b9e0e533789c0e387b317 | train | function | def data_prepare(csv_path, file_info_path, data_path, rep_type, target_path):
with open(csv_path, 'r') as f:
ids = f.readlines()
ids = [x.strip().split(',') for x in ids]
#self.ids = ids
samp_rate = 16000
spec_stride = 0.01
window_size = 0.02
size = len(ids)
rep_path = os.path.join(data_path, rep_type)... | def data_prepare(csv_path, file_info_path, data_path, rep_type, target_path):
| with open(csv_path, 'r') as f:
ids = f.readlines()
ids = [x.strip().split(',') for x in ids]
#self.ids = ids
samp_rate = 16000
spec_stride = 0.01
window_size = 0.02
size = len(ids)
rep_path = os.path.join(data_path, rep_type)
#self.file_info_path = file_info_path
with open(file_info_path, 'r') as j... | import numpy as np
import torch
import os
import json
import math
import pdb
import time
import pdb
import argparse
from tqdm import tqdm
def get_input_frame(current_frame):
return (current_frame - 1)*2 + 11 - 2*5
def data_prepare(csv_path, file_info_path, data_path, rep_type, target_path):
| 78 | 195 | 653 | 19 | 58 | archiki/ASR-Accent-Analysis | PhoneProbes/data_ready.py | Python | data_prepare | data_prepare | 15 | 75 | 15 | 15 | 3a0d997bcdf1760e221ba739ccad30e5ceab1787 | bigcode/the-stack | train |
1fa55942b3dff7fb1a18dedc | train | class | class ProductionUpdateSerializer(serializers.ModelSerializer):
day_starts_at = serializers.TimeField(required=False, allow_null=True,)
day_finishes_at = serializers.TimeField(required=False, allow_null=True,)
inspection_frequency = serializers.IntegerField(required=True, allow_null=False)
class Meta:
... | class ProductionUpdateSerializer(serializers.ModelSerializer):
| day_starts_at = serializers.TimeField(required=False, allow_null=True,)
day_finishes_at = serializers.TimeField(required=False, allow_null=True,)
inspection_frequency = serializers.IntegerField(required=True, allow_null=False)
class Meta:
model = Production
fields = (
'name'... | django.shortcuts import get_object_or_404
from django.template.loader import render_to_string # HTML / TXT
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions, serializers
from rest_framework.response import Response
from foundation.models i... | 87 | 87 | 290 | 8 | 78 | mikaponics/mikaponics-back | mikaponics/production/serializers/production_update_serializer.py | Python | ProductionUpdateSerializer | ProductionUpdateSerializer | 16 | 56 | 16 | 16 | aff6a001155e8e0ef4222b903f08b84d7e95abec | bigcode/the-stack | train |
aa4db91ec0f1362cc9dada7b | train | class | class ServerCore(object):
def __init__(self, my_port = 50082, core_node_host=None, core_node_port=None):
self.server_state = STATE_INIT
print('Initializing server...')
self.my_ip = self.__get_myip()
print('Server IP address is set to ... ', self.my_ip)
self.my_port = my_port... | class ServerCore(object):
| def __init__(self, my_port = 50082, core_node_host=None, core_node_port=None):
self.server_state = STATE_INIT
print('Initializing server...')
self.my_ip = self.__get_myip()
print('Server IP address is set to ... ', self.my_ip)
self.my_port = my_port
self.cm = Connecti... | import time
import socket, threading, json
from blockchain.blockchain_manager import BlockchainManager
from blockchain.block_builder import BlockBuilder
from transaction.transaction_pool import TransactionPool
from p2p.connection_manager import ConnectionManager
from p2p.my_protocol_message_handler import MyProtocolMe... | 176 | 256 | 956 | 5 | 170 | peaks-cc/cryptocurrency-samplecode | 03/03/core/server_core.py | Python | ServerCore | ServerCore | 27 | 124 | 27 | 28 | 5615bddf0dff69aa644b3b252fafbe5198e5724f | bigcode/the-stack | train |
b4c43361d622ad410c953895 | train | class | class H2OMOJOAlgoSharedParams(Params):
predictionCol = Param(
Params._dummy(),
"predictionCol",
"Prediction column name",
H2OTypeConverters.toString())
detailedPredictionCol = Param(
Params._dummy(),
"detailedPredictionCol",
"Column containing additional ... | class H2OMOJOAlgoSharedParams(Params):
| predictionCol = Param(
Params._dummy(),
"predictionCol",
"Prediction column name",
H2OTypeConverters.toString())
detailedPredictionCol = Param(
Params._dummy(),
"detailedPredictionCol",
"Column containing additional prediction details, its content depends... | may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR C... | 142 | 142 | 476 | 11 | 130 | salliewalecka/sparkling-water | py/src/ai/h2o/sparkling/ml/params/H2OMOJOAlgoSharedParams.py | Python | H2OMOJOAlgoSharedParams | H2OMOJOAlgoSharedParams | 23 | 88 | 23 | 23 | b8080cf04a6d1400ee0265138c81a7f356b350dc | bigcode/the-stack | train |
afd5217e3ebbfabc4ec42dcd | train | function | def generate_flow(epoch=3):
"""读取存储的模型,生成新词"""
corpus = Corpus(train_dir)
config = Config()
config.vocab_size = len(corpus.dictionary)
model = RNNModel(config)
model_file = os.path.join(save_dir, model_name.format(epoch))
assert os.path.exists(model_file), 'File %s does not exist.' % model_... | def generate_flow(epoch=3):
| """读取存储的模型,生成新词"""
corpus = Corpus(train_dir)
config = Config()
config.vocab_size = len(corpus.dictionary)
model = RNNModel(config)
model_file = os.path.join(save_dir, model_name.format(epoch))
assert os.path.exists(model_file), 'File %s does not exist.' % model_file
model.load_state_di... | 一次模型参数
#if epoch % config.save_interval == 0:
torch.save(model.state_dict(), os.path.join(save_dir, model_name.format(epoch)))
logger.info(''.join(generate(model, corpus.dictionary.VocabID_to_vocab, len(corpus.dictionary))))
def generate_flow(epoch=3):
| 63 | 64 | 138 | 7 | 56 | gajanlee/ZeusKnows | language_model/main.py | Python | generate_flow | generate_flow | 194 | 206 | 194 | 194 | 139080bcfd4a13882cd5e2062d40260d2d627c0e | bigcode/the-stack | train |
b16a44600f9b8558b61b4f1d | train | class | class Config(object):
"""RNNLM模型配置项"""
embedding_dim = 200 # 词向量维度
rnn_type = 'LSTM' # 支持RNN/LSTM/GRU
hidden_dim = 200 # 隐藏层维度
num_layers = 2 # RNN 层数
dropout = 0.5 # 丢弃概率
tie_weights = True # 是否绑定参数
batch_size = 10 # 每一批数据量
seq_len = 30 # 序列长度
clip = 0.25 # 用于梯度规范化
... | class Config(object):
| """RNNLM模型配置项"""
embedding_dim = 200 # 词向量维度
rnn_type = 'LSTM' # 支持RNN/LSTM/GRU
hidden_dim = 200 # 隐藏层维度
num_layers = 2 # RNN 层数
dropout = 0.5 # 丢弃概率
tie_weights = True # 是否绑定参数
batch_size = 10 # 每一批数据量
seq_len = 30 # 序列长度
clip = 0.25 # 用于梯度规范化
learning_rate = 20... | train', help='train or gen.')
parser.add_argument('--epoch', type=int, default=3, help='the epoch of parameter to be loaded.')
parser.add_argument("--load", type=int, default=0, help='the epoch of training to be loaded.')
args = parser.parse_args()
class Config(object):
| 64 | 64 | 210 | 4 | 60 | gajanlee/ZeusKnows | language_model/main.py | Python | Config | Config | 37 | 56 | 37 | 37 | 0107bdd8a95e40449abd5bd8c40fd6a6ef0f7860 | bigcode/the-stack | train |
83c107cf9f2ac28829bf3470 | train | function | def repackage_hidden(h):
"""用新的变量重新包装隐藏层,将它们从历史中分离。"""
if type(h) == Variable: # rnn/gru
return Variable(h.data)
else: # lstm
return tuple(repackage_hidden(v) for v in h)
| def repackage_hidden(h):
| """用新的变量重新包装隐藏层,将它们从历史中分离。"""
if type(h) == Variable: # rnn/gru
return Variable(h.data)
else: # lstm
return tuple(repackage_hidden(v) for v in h)
| volatile=evaluation)
target = Variable(source[(i + 1):(i + 1 + seq_len)].view(-1)) # 为训练方便,展平
if use_cuda:
data, target = data.cuda(), target.cuda()
return data, target
def repackage_hidden(h):
| 64 | 64 | 67 | 6 | 57 | gajanlee/ZeusKnows | language_model/main.py | Python | repackage_hidden | repackage_hidden | 81 | 86 | 81 | 81 | 8c49e0c7be311aa8087abbf22edb9aaa2d329b93 | bigcode/the-stack | train |
8c623308a07b7a502c0ebeb1 | train | function | def generate(model, idx2word, vocab_size, word_len=200, temperature=1.0):
"""生成一定数量的文本,temperature结合多项式分布可增添抽样的多样性。"""
model.eval()
hidden = model.init_hidden(1) # batch_size为1
inputs = Variable(torch.rand(1, 1).mul(vocab_size).long(), volatile=True) # 随机选取一个字作为开始
if use_cuda:
inputs = inp... | def generate(model, idx2word, vocab_size, word_len=200, temperature=1.0):
| """生成一定数量的文本,temperature结合多项式分布可增添抽样的多样性。"""
model.eval()
hidden = model.init_hidden(1) # batch_size为1
inputs = Variable(torch.rand(1, 1).mul(vocab_size).long(), volatile=True) # 随机选取一个字作为开始
if use_cuda:
inputs = inputs.cuda()
word_list = []
for i in range(word_len): # 逐字生成
... | : # rnn/gru
return Variable(h.data)
else: # lstm
return tuple(repackage_hidden(v) for v in h)
def get_time_dif(start_time):
"""获取已使用时间"""
end_time = time.time()
time_dif = end_time - start_time
return timedelta(seconds=int(round(time_dif)))
def generate(model, idx2word, vocab_siz... | 100 | 101 | 339 | 22 | 78 | gajanlee/ZeusKnows | language_model/main.py | Python | generate | generate | 96 | 122 | 96 | 96 | f408f7738c64ce10399c660a0d05dd24b5699fbb | bigcode/the-stack | train |
6daa3791c22248642c4a37fa | train | function | def get_time_dif(start_time):
"""获取已使用时间"""
end_time = time.time()
time_dif = end_time - start_time
return timedelta(seconds=int(round(time_dif)))
| def get_time_dif(start_time):
| """获取已使用时间"""
end_time = time.time()
time_dif = end_time - start_time
return timedelta(seconds=int(round(time_dif)))
| 重新包装隐藏层,将它们从历史中分离。"""
if type(h) == Variable: # rnn/gru
return Variable(h.data)
else: # lstm
return tuple(repackage_hidden(v) for v in h)
def get_time_dif(start_time):
| 64 | 64 | 43 | 8 | 56 | gajanlee/ZeusKnows | language_model/main.py | Python | get_time_dif | get_time_dif | 89 | 93 | 89 | 89 | 4bf6da1335ea47089c6e1ef5494593990a0d83a8 | bigcode/the-stack | train |
e17352f6d8d3170dfd54b38f | train | function | def batchify(data, bsz):
"""返回数据维度为(nbatch, batch_size)"""
nbatch = data.size(0) // bsz
data = data.narrow(0, 0, nbatch * bsz) # 去除多余部分
data = data.view(bsz, -1).t().contiguous() # 将数据按照bsz切分
return data
| def batchify(data, bsz):
| """返回数据维度为(nbatch, batch_size)"""
nbatch = data.size(0) // bsz
data = data.narrow(0, 0, nbatch * bsz) # 去除多余部分
data = data.view(bsz, -1).t().contiguous() # 将数据按照bsz切分
return data
| 初始学习率
num_epochs = 50 # 迭代轮次
log_interval = 500 # 每隔多少个批次输出一次状态
save_interval = 3 # 每个多少个轮次保存一次参数
def batchify(data, bsz):
| 64 | 64 | 91 | 8 | 55 | gajanlee/ZeusKnows | language_model/main.py | Python | batchify | batchify | 59 | 64 | 59 | 59 | 345950bb5dc03c2d969a141e721856e0e22e45d5 | bigcode/the-stack | train |
247fd2803786d7c5edc2ddfa | train | function | def train():
# 载入数据与配置模型
logger.info("Loading data...")
corpus = Corpus(train_dir)
logger.info(corpus)
config = Config()
config.vocab_size = len(corpus.dictionary)
train_data = batchify(corpus.train, config.batch_size)
train_len = train_data.size(0)
seq_len = config.seq_len
log... | def train():
# 载入数据与配置模型
| logger.info("Loading data...")
corpus = Corpus(train_dir)
logger.info(corpus)
config = Config()
config.vocab_size = len(corpus.dictionary)
train_data = batchify(corpus.train, config.batch_size)
train_len = train_data.size(0)
seq_len = config.seq_len
logger.info("Configuring model..... | 逐字生成
output, hidden = model(inputs, hidden)
word_weights = output.squeeze().data.div(temperature).exp().cpu()
# 基于词的权重,对其再进行一次抽样,增添其多样性,如果不使用此法,会导致常用字的无限循环
# word_idx = torch.multinomial(word_weights, 1)[0]
word_idx = torch.multinomial(word_weights, 1)
#print(word_idx)
... | 223 | 223 | 744 | 13 | 209 | gajanlee/ZeusKnows | language_model/main.py | Python | train | train | 125 | 191 | 125 | 126 | fa00dda9aa5bdfc01eee4f91cde2eed0f315d55a | bigcode/the-stack | train |
1d70b7b8ceb80d845e046ab5 | train | function | def get_batch(source, i, seq_len, evaluation=False):
"""
获取一个batch
data: (seq_len, batch_size)
target: (seq_len * batch_size)
"""
seq_len = min(seq_len, len(source) - 1 - i)
data = Variable(source[i:(i + seq_len)], volatile=evaluation)
target = Variable(source[(i + 1):(i + 1 + seq_len)].... | def get_batch(source, i, seq_len, evaluation=False):
| """
获取一个batch
data: (seq_len, batch_size)
target: (seq_len * batch_size)
"""
seq_len = min(seq_len, len(source) - 1 - i)
data = Variable(source[i:(i + seq_len)], volatile=evaluation)
target = Variable(source[(i + 1):(i + 1 + seq_len)].view(-1)) # 为训练方便,展平
if use_cuda:
data, ... | arrow(0, 0, nbatch * bsz) # 去除多余部分
data = data.view(bsz, -1).t().contiguous() # 将数据按照bsz切分
return data
def get_batch(source, i, seq_len, evaluation=False):
| 64 | 64 | 129 | 13 | 50 | gajanlee/ZeusKnows | language_model/main.py | Python | get_batch | get_batch | 67 | 78 | 67 | 67 | e550e8067f04f78bdad65f3b24cd0b778100b047 | bigcode/the-stack | train |
a5b6dc294c0a391a0565260b | train | function | @auth_bp.post("/login")
@input(LoginSchema)
def login(data):
user = User.query.filter_by(username=data["username"]).one_or_none()
if user and user.password == data["password"]:
session.clear()
session["user_id"] = user.id
return {'msg': 'logged in'}
else:
abort(403)
| @auth_bp.post("/login")
@input(LoginSchema)
def login(data):
| user = User.query.filter_by(username=data["username"]).one_or_none()
if user and user.password == data["password"]:
session.clear()
session["user_id"] = user.id
return {'msg': 'logged in'}
else:
abort(403)
| .before_app_request
def user_checkout():
user_id = session.get("user_id")
if user_id is None:
g.user =None
else:
g.user = User.query.filter_by(id=user_id).first()
@auth_bp.post("/login")
@input(LoginSchema)
def login(data):
| 64 | 64 | 74 | 16 | 48 | PythonistaMX/py231 | src/estructura-flask/apiflaskdemo/project/auth/blueprints.py | Python | login | login | 17 | 26 | 17 | 19 | 22486cc62dfcbb9e6dfc8a8a273daee927a9c9a3 | bigcode/the-stack | train |
2df23cf0ea21ca4ed085f316 | train | function | @auth_bp.get("/logout")
def logout():
session.clear()
return {"msg": "logged out"} | @auth_bp.get("/logout")
def logout():
| session.clear()
return {"msg": "logged out"} | .query.filter_by(username=data["username"]).one_or_none()
if user and user.password == data["password"]:
session.clear()
session["user_id"] = user.id
return {'msg': 'logged in'}
else:
abort(403)
@auth_bp.get("/logout")
def logout():
| 64 | 64 | 23 | 10 | 54 | PythonistaMX/py231 | src/estructura-flask/apiflaskdemo/project/auth/blueprints.py | Python | logout | logout | 28 | 31 | 28 | 29 | 142ad0e81d65de28ecb23a660a68840cb1c97ce3 | bigcode/the-stack | train |
4b9e60b524ec2b79006b50e5 | train | function | @auth_bp.before_app_request
def user_checkout():
user_id = session.get("user_id")
if user_id is None:
g.user =None
else:
g.user = User.query.filter_by(id=user_id).first()
| @auth_bp.before_app_request
def user_checkout():
| user_id = session.get("user_id")
if user_id is None:
g.user =None
else:
g.user = User.query.filter_by(id=user_id).first()
| from apiflask import APIBlueprint, abort, input, output
from apiflask.fields import String
from apiflaskdemo.project.auth.schemas import LoginSchema
from flask import session, g
auth_bp = APIBlueprint("auth_bp", __name__)
@auth_bp.before_app_request
def user_checkout():
| 64 | 64 | 51 | 11 | 53 | PythonistaMX/py231 | src/estructura-flask/apiflaskdemo/project/auth/blueprints.py | Python | user_checkout | user_checkout | 9 | 15 | 9 | 10 | cac655296e6da0ed97a405a7d8c5e1ae08cbffa2 | bigcode/the-stack | train |
55e1dca309762dee7a74f3e5 | train | class | class AdhocQLearning(Agent):
actions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def __init__(self, id, lrate=0.8, discount=0.95, eps=0.05):
super().__init__(id)
self.eps = eps
self.qtable = defaultdict(lambda: np.zeros(4))
self.lrate = lrate
self.discount = discount
se... | class AdhocQLearning(Agent):
| actions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def __init__(self, id, lrate=0.8, discount=0.95, eps=0.05):
super().__init__(id)
self.eps = eps
self.qtable = defaultdict(lambda: np.zeros(4))
self.lrate = lrate
self.discount = discount
self.dataset = {}
self.... | import random
from collections import defaultdict
import numpy as np
from pursuit.agents.base_agent import Agent
class AdhocQLearning(Agent):
| 30 | 93 | 313 | 8 | 21 | goncalo-rodrigues/thesis | pursuit/agents/ad_hoc/adhoc_qlearning.py | Python | AdhocQLearning | AdhocQLearning | 9 | 39 | 9 | 9 | 0b771718219abe768c5b5e344458653e56423a1c | bigcode/the-stack | train |
4aa264a9c229ffebd03855a6 | train | class | class GetTransactionData(BaseParser):
def setParams(self, market, code, start, count):
if type(code) is six.text_type:
code = code.encode("utf-8")
pkg = bytearray.fromhex(u'0c 17 08 01 01 01 0e 00 0e 00 c5 0f')
pkg.extend(struct.pack("<H6sHH", market, code, start, count))
... | class GetTransactionData(BaseParser):
| def setParams(self, market, code, start, count):
if type(code) is six.text_type:
code = code.encode("utf-8")
pkg = bytearray.fromhex(u'0c 17 08 01 01 01 0e 00 0e 00 c5 0f')
pkg.extend(struct.pack("<H6sHH", market, code, start, count))
self.send_pkg = pkg
def parseRes... | # coding=utf-8
from pytdx.parser.base import BaseParser
from pytdx.helper import get_datetime, get_volume, get_price, get_time
from collections import OrderedDict
import struct
import six
class GetTransactionData(BaseParser):
| 53 | 100 | 335 | 7 | 45 | AtlantixJJ/vnpy | pytdx/parser/get_transaction_data.py | Python | GetTransactionData | GetTransactionData | 9 | 50 | 9 | 10 | 1572dc920114c3381c87e4a829a0011b068c4119 | bigcode/the-stack | train |
e075e2ea9b33170700885fba | train | function | def plot_lightcurve(
df_bran, df_tywin, df_lancel, plot_lumi=True, outpath="bran_tywin_lancel_lumi.pdf"
):
df = df_bran
fig = plt.figure(figsize=(0.8 * FIG_WIDTH, 0.5658 * FIG_WIDTH), dpi=DPI)
filter_wl = utilities.load_info_json("filter_wl")
plt.subplots_adjust(bottom=0.13, top=0.85, left=0.13, ri... | def plot_lightcurve(
df_bran, df_tywin, df_lancel, plot_lumi=True, outpath="bran_tywin_lancel_lumi.pdf"
):
| df = df_bran
fig = plt.figure(figsize=(0.8 * FIG_WIDTH, 0.5658 * FIG_WIDTH), dpi=DPI)
filter_wl = utilities.load_info_json("filter_wl")
plt.subplots_adjust(bottom=0.13, top=0.85, left=0.13, right=0.9)
ax1 = fig.add_subplot(1, 1, 1)
# ax1 = plt.subplot(111)
plt.yscale("log")
colors = ["... | import constants as const
from astropy.table import Table
from astropy import units as u
from astropy.cosmology import Planck15 as cosmo
from modelSED import utilities
nice_fonts = {
"text.usetex": True,
"font.family": "serif",
"font.serif": "Times New Roman",
}
matplotlib.rcParams.update(nice_fonts)
XR... | 256 | 256 | 1,185 | 36 | 219 | simeonreusch/at2019fdr | bran_tywin_lancel.py | Python | plot_lightcurve | plot_lightcurve | 45 | 158 | 45 | 48 | be721c1cd7554d54b5da9fd233ab99eda5896fa2 | bigcode/the-stack | train |
a9bcf87547f2ebbf54971111 | train | function | def angstrom_to_ev(angstrom):
energy = const.h.value * const.c.value / (angstrom * 1e-10)
ev = energy / 1.602e-19
return ev
| def angstrom_to_ev(angstrom):
| energy = const.h.value * const.c.value / (angstrom * 1e-10)
ev = energy / 1.602e-19
return ev
|
SMALL_FONTSIZE = 9
DPI = 400
REDSHIFT_TYWIN = 0.267
REDSHIFT_BRAN = 0.0512
REDSHIFT_LANCEL = 0.0357
def angstrom_to_ev(angstrom):
| 64 | 64 | 45 | 8 | 55 | simeonreusch/at2019fdr | bran_tywin_lancel.py | Python | angstrom_to_ev | angstrom_to_ev | 39 | 42 | 39 | 39 | 09b11326ea3a47e6687b7b8eaeb4d7785265225b | bigcode/the-stack | train |
b9246c5a570cd83aa6cea237 | train | function | def parse_modelkey(key):
_, typename, docid, modelid = decode_utf8(key).split(":")
return typename, docid, modelid
| def parse_modelkey(key):
| _, typename, docid, modelid = decode_utf8(key).split(":")
return typename, docid, modelid
| id)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
def callbackskey(typename, docid, modelid):
return 'bbcallback:%s:%s:%s' % (typename, docid, modelid)
def parse_modelkey(key):
| 64 | 64 | 34 | 6 | 58 | csaid/bokeh | bokeh/server/serverbb.py | Python | parse_modelkey | parse_modelkey | 61 | 63 | 61 | 61 | 16881fd94727845a022ef0f22f0f90c8f53ac151 | bigcode/the-stack | train |
ee7ed2d71a01029ba6755ee9 | train | function | def prune(document, delete=False):
all_models = docs.prune_and_get_valid_models(document, delete=delete)
to_keep = set([x._id for x in all_models])
to_delete = set(document._models.keys()) - to_keep
for k in to_delete:
document.remove(k)
| def prune(document, delete=False):
| all_models = docs.prune_and_get_valid_models(document, delete=delete)
to_keep = set([x._id for x in all_models])
to_delete = set(document._models.keys()) - to_keep
for k in to_delete:
document.remove(k)
| ):
return 'bbcallback:%s:%s:%s' % (typename, docid, modelid)
def parse_modelkey(key):
_, typename, docid, modelid = decode_utf8(key).split(":")
return typename, docid, modelid
def prune(document, delete=False):
| 64 | 64 | 65 | 7 | 56 | csaid/bokeh | bokeh/server/serverbb.py | Python | prune | prune | 65 | 70 | 65 | 65 | cf52afaa53f61240d5ab839a993c1cc2065339b2 | bigcode/the-stack | train |
f28ac8235f1b9869c672af78 | train | function | def modelkey(typename, docid, modelid):
docid = encode_utf8(docid)
modelid = encode_utf8(modelid)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
| def modelkey(typename, docid, modelid):
| docid = encode_utf8(docid)
modelid = encode_utf8(modelid)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
| data):
raise NotImplementedError("abstract method")
def delete(self, key):
raise NotImplementedError("abstract method")
def dockey(docid):
docid = encode_utf8('doc:' + docid)
return docid
def modelkey(typename, docid, modelid):
| 64 | 64 | 54 | 12 | 51 | csaid/bokeh | bokeh/server/serverbb.py | Python | modelkey | modelkey | 53 | 56 | 53 | 53 | 3199ccbdbdabc70b5ec5ec2969fa4c7e30414ae6 | bigcode/the-stack | train |
646b418b35038e2ba8104bb4 | train | function | def dockey(docid):
docid = encode_utf8('doc:' + docid)
return docid
| def dockey(docid):
| docid = encode_utf8('doc:' + docid)
return docid
| ImplementedError("abstract method")
def smembers(self, doc_key):
raise NotImplementedError("abstract method")
def set(self, key, data):
raise NotImplementedError("abstract method")
def delete(self, key):
raise NotImplementedError("abstract method")
def dockey(docid):
| 64 | 64 | 25 | 6 | 58 | csaid/bokeh | bokeh/server/serverbb.py | Python | dockey | dockey | 49 | 51 | 49 | 49 | 6c29ec73da82f4ee5db47383f3731b8ffae29523 | bigcode/the-stack | train |
20bd0eb007a134d4319477f3 | train | function | def callbackskey(typename, docid, modelid):
return 'bbcallback:%s:%s:%s' % (typename, docid, modelid)
| def callbackskey(typename, docid, modelid):
| return 'bbcallback:%s:%s:%s' % (typename, docid, modelid)
| key(typename, docid, modelid):
docid = encode_utf8(docid)
modelid = encode_utf8(modelid)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
def callbackskey(typename, docid, modelid):
| 64 | 64 | 34 | 12 | 52 | csaid/bokeh | bokeh/server/serverbb.py | Python | callbackskey | callbackskey | 58 | 59 | 58 | 58 | c82ae81e77c4fc703873db3d0728c2867fed2af8 | bigcode/the-stack | train |
f6d3c28629e09ee3a8b692b4 | train | class | class RedisBackboneStorage(PersistentBackboneStorage):
"""storage used by the webserver to work with
a user's documents. uses redis directly.
"""
def __init__(self, redis):
self.redis = redis
super(RedisBackboneStorage, self).__init__()
def mget(self, doc_keys):
if not doc_... | class RedisBackboneStorage(PersistentBackboneStorage):
| """storage used by the webserver to work with
a user's documents. uses redis directly.
"""
def __init__(self, redis):
self.redis = redis
super(RedisBackboneStorage, self).__init__()
def mget(self, doc_keys):
if not doc_keys:
return []
vals = self.redis.m... | def store_callbacks(self, to_store):
for callbacks in to_store:
typename = callbacks['type']
_id = callbacks['id']
key = self.callbackskey(typename, self.docid, _id)
data = self.serialize(callbacks)
self.set(key, data)
class RedisBackboneStorage(Persi... | 72 | 72 | 243 | 11 | 61 | csaid/bokeh | bokeh/server/serverbb.py | Python | RedisBackboneStorage | RedisBackboneStorage | 160 | 191 | 160 | 160 | b2a1942451bfbfd49bc445ba5870b951a06a97f7 | bigcode/the-stack | train |
97a0d8542e88fd1dd74018fa | train | class | class StoreAdapter(object):
"""API modeled after Redis that other stores have to adapt to. """
def mget(self, doc_keys):
raise NotImplementedError("abstract method")
def mset(self, data):
raise NotImplementedError("abstract method")
def sadd(self, doc_key, *keys):
raise NotImp... | class StoreAdapter(object):
| """API modeled after Redis that other stores have to adapt to. """
def mget(self, doc_keys):
raise NotImplementedError("abstract method")
def mset(self, data):
raise NotImplementedError("abstract method")
def sadd(self, doc_key, *keys):
raise NotImplementedError("abstract meth... | docs
import numpy as np
logger = logging.getLogger(__name__)
from ..objects import PlotObject, Plot
from ..document import Document
from ..utils import encode_utf8, decode_utf8, dump
from . import server_backends
from .app import bokeh_app
class StoreAdapter(object):
| 64 | 64 | 148 | 5 | 58 | csaid/bokeh | bokeh/server/serverbb.py | Python | StoreAdapter | StoreAdapter | 25 | 47 | 25 | 25 | 23cedd8caa9c5f39f97f512b47084d0af733bc7f | bigcode/the-stack | train |
4bded7a5bcfe39aa92b2a775 | train | class | class PersistentBackboneStorage(object):
"""Base class for `RedisBackboneStorage`, `InMemoryBackboneStorage`, etc. """
def pull(self, docid, typename=None, objid=None):
"""you need to call this with either typename AND objid
or leave out both. leaving them out means retrieve all
... | class PersistentBackboneStorage(object):
| """Base class for `RedisBackboneStorage`, `InMemoryBackboneStorage`, etc. """
def pull(self, docid, typename=None, objid=None):
"""you need to call this with either typename AND objid
or leave out both. leaving them out means retrieve all
otherwise, retrieves a specific object... | dockey(docid):
docid = encode_utf8('doc:' + docid)
return docid
def modelkey(typename, docid, modelid):
docid = encode_utf8(docid)
modelid = encode_utf8(modelid)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
def callbackskey(typename, docid, modelid):
return 'bbcallback:%s:%s:%s' % (... | 218 | 218 | 727 | 7 | 211 | csaid/bokeh | bokeh/server/serverbb.py | Python | PersistentBackboneStorage | PersistentBackboneStorage | 72 | 158 | 72 | 72 | 7f008df6a475846a35d7068a28f54260f5a9fbf3 | bigcode/the-stack | train |
b6c901784227cd367c98291e | train | class | class InMemoryBackboneStorage(PersistentBackboneStorage):
"""storage used by the webserver to work with
a user's documents. uses in memory data store directly.
"""
_inmem_data = {}
_inmem_sets = defaultdict(set)
def mget(self, doc_keys):
return [self._inmem_data.get(key, None) for key... | class InMemoryBackboneStorage(PersistentBackboneStorage):
| """storage used by the webserver to work with
a user's documents. uses in memory data store directly.
"""
_inmem_data = {}
_inmem_sets = defaultdict(set)
def mget(self, doc_keys):
return [self._inmem_data.get(key, None) for key in doc_keys]
def mset(self, data):
self._inm... | _key)
return [None if val is None else val.decode('utf-8') for val in vals]
def set(self, key, data):
self.redis.set(key, data)
def delete(self, mkey):
self.redis.delete(mkey)
class InMemoryBackboneStorage(PersistentBackboneStorage):
| 67 | 67 | 224 | 12 | 55 | csaid/bokeh | bokeh/server/serverbb.py | Python | InMemoryBackboneStorage | InMemoryBackboneStorage | 193 | 222 | 193 | 193 | 203a786944c5de32381d1a53d8ee878b5560c48e | bigcode/the-stack | train |
b3d9f5dfa23b80ee83eb0700 | train | class | class ShelveBackboneStorage(PersistentBackboneStorage):
"""storage used by the webserver to work with
a user's documents. uses shelve data store directly.
"""
@contextlib.contextmanager
def shelve_data(self):
data = shelve.open('bokeh.data')
try:
yield data
fina... | class ShelveBackboneStorage(PersistentBackboneStorage):
| """storage used by the webserver to work with
a user's documents. uses shelve data store directly.
"""
@contextlib.contextmanager
def shelve_data(self):
data = shelve.open('bokeh.data')
try:
yield data
finally:
data.close()
@contextlib.contextma... | (self, doc_key, *keys):
self._inmem_sets[doc_key].update(keys)
def srem(self, doc_key, member_key):
inmem_set = self._inmem_sets[doc_key]
try: inmem_set.remove(member_key)
except KeyError: pass
def smembers(self, doc_key):
return list(self._inmem_sets[doc_key])
def... | 133 | 133 | 444 | 12 | 121 | csaid/bokeh | bokeh/server/serverbb.py | Python | ShelveBackboneStorage | ShelveBackboneStorage | 224 | 277 | 224 | 224 | 92a18e19e3108277cccd14c8805ef51d96fbfffb | bigcode/the-stack | train |
8181937b2f8d42f00abd09b9 | train | class | @path_dec("install_lib")
class CustomInstallCommand(install):
pass
| @path_dec("install_lib")
class CustomInstallCommand(install):
| pass
| orig_run(self)
self.execute(parse, (getattr(self,install_path),),
msg="\nRunning the parameter parsers")
command_subclass.run = modified_run
return command_subclass
return customcmd
@path_dec("install_lib")
class CustomInstallCommand(inst... | 64 | 64 | 17 | 14 | 49 | ajkerr0/kappa | setup.py | Python | CustomInstallCommand | CustomInstallCommand | 41 | 43 | 41 | 42 | a9f69ec3fd756128d1b1cdabba94543cd353d903 | bigcode/the-stack | train |
1d72c4f031b212329e072d79 | train | function | def path_dec(install_path):
def customcmd(command_subclass):
"""A decorator for subclasses of the setuptools commands,
modifying the run() method so that it parses the force parameter
files after installation."""
orig_run = command_subclass.run
def modified... | def path_dec(install_path):
| def customcmd(command_subclass):
"""A decorator for subclasses of the setuptools commands,
modifying the run() method so that it parses the force parameter
files after installation."""
orig_run = command_subclass.run
def modified_run(self):
orig... | path))]
for path in parser_paths:
call([interpreter, "parser.py"],
cwd=os.path.join(dir_, os.path.join(param_dir,path)))
#Peter Lamut: http://blog.niteoweb.com/setuptools-run-custom-code-in-setup-py/
def path_dec(install_path):
| 64 | 64 | 112 | 7 | 57 | ajkerr0/kappa | setup.py | Python | path_dec | path_dec | 24 | 39 | 24 | 24 | 0d67308ae818af0f04afc2a840c0ed2dfef48508 | bigcode/the-stack | train |
f14579435e23df5ef4c6e392 | train | function | def parse(dir_):
from subprocess import call
#get path to interpreter
interpreter = sys.executable
#get param directories
param_dir = 'kappa/param/'
parser_paths = [path for path in os.listdir(param_dir) if os.path.isdir(os.path.join(param_dir, path))]
for path in parser_paths:
call(... | def parse(dir_):
| from subprocess import call
#get path to interpreter
interpreter = sys.executable
#get param directories
param_dir = 'kappa/param/'
parser_paths = [path for path in os.listdir(param_dir) if os.path.isdir(os.path.join(param_dir, path))]
for path in parser_paths:
call([interpreter, "pa... | # -*- coding: utf-8 -*-
"""
Created on Thu May 26 14:19:51 2016
@author: Alex Kerr
"""
import os,sys
from setuptools import find_packages, setup
from setuptools.command.install import install
from setuptools.command.develop import develop
def parse(dir_):
| 64 | 64 | 98 | 5 | 58 | ajkerr0/kappa | setup.py | Python | parse | parse | 12 | 21 | 12 | 12 | c91b4db827e1a03d635a4a515d46270fa7f3d556 | bigcode/the-stack | train |
edff62284a1c6abe53a15896 | train | class | @path_dec("egg_path")
class CustomDevelopCommand(develop):
pass
| @path_dec("egg_path")
class CustomDevelopCommand(develop):
| pass
| ),),
msg="\nRunning the parameter parsers")
command_subclass.run = modified_run
return command_subclass
return customcmd
@path_dec("install_lib")
class CustomInstallCommand(install):
pass
@path_dec("egg_path")
class CustomDevelopCommand(develop):
| 64 | 64 | 17 | 14 | 49 | ajkerr0/kappa | setup.py | Python | CustomDevelopCommand | CustomDevelopCommand | 45 | 47 | 45 | 46 | 0524834e5d416195e4cce2e7bc096d6ba7073094 | bigcode/the-stack | train |
e0505495f7235b915e9b674b | train | function | def _rank_from_shape(x):
"""Returns the rank implied by this shape."""
if not hasattr(x, 'shape'):
return tf.TensorShape(x).rank
else:
# If the input is a Tensor, we can't make a `TensorShape` out of it
# directly:
# - In graph mode, `TensorShape` complains that it can't iterate over a
# Ten... | def _rank_from_shape(x):
| """Returns the rank implied by this shape."""
if not hasattr(x, 'shape'):
return tf.TensorShape(x).rank
else:
# If the input is a Tensor, we can't make a `TensorShape` out of it
# directly:
# - In graph mode, `TensorShape` complains that it can't iterate over a
# Tensor.
# - In eager mod... | .'
if shape_ is not None:
if np.any(shape_ < -1):
raise ValueError(message.format(shape))
elif validate_args:
assertions.append(assert_util.assert_greater(
shape, -2, message=message.format(shape)))
return assertions
def _rank_from_shape(x):
| 64 | 64 | 168 | 7 | 56 | rmothukuru/probability | tensorflow_probability/python/bijectors/reshape.py | Python | _rank_from_shape | _rank_from_shape | 440 | 454 | 440 | 440 | e07c8cc717d3f7069fdcfa25db70ff55a279aa1e | bigcode/the-stack | train |
642a7e24438832d719523b25 | train | function | def _replace_event_shape_in_shape_tensor(
input_shape, event_shape_in, event_shape_out, validate_args):
"""Replaces the rightmost dims in a `Tensor` representing a shape.
Args:
input_shape: a rank-1 `Tensor` of integers
event_shape_in: the event shape expected to be present in rightmost dims
of `... | def _replace_event_shape_in_shape_tensor(
input_shape, event_shape_in, event_shape_out, validate_args):
| """Replaces the rightmost dims in a `Tensor` representing a shape.
Args:
input_shape: a rank-1 `Tensor` of integers
event_shape_in: the event shape expected to be present in rightmost dims
of `shape_in`.
event_shape_out: the event shape with which to replace `event_shape_in` in
the rightmos... | event_shape_out)[0]
def _inverse_event_shape(self, output_shape):
return _replace_event_shape_in_tensorshape(
output_shape,
self._event_shape_out,
self._event_shape_in)[0]
def _forward_event_shape_tensor(self, input_shape):
return _replace_event_shape_in_shape_tensor(
input... | 184 | 184 | 616 | 24 | 160 | rmothukuru/probability | tensorflow_probability/python/bijectors/reshape.py | Python | _replace_event_shape_in_shape_tensor | _replace_event_shape_in_shape_tensor | 268 | 329 | 268 | 269 | 6be687377ab009728c657caf9cc0bf729243b04c | bigcode/the-stack | train |
1651ef6c09b4ebaa0c90f850 | train | function | def _maybe_check_valid_shape(shape, validate_args):
"""Check that a shape Tensor is int-type and otherwise sane."""
if not dtype_util.is_integer(shape.dtype):
raise TypeError('`{}` dtype (`{}`) should be `int`-like.'.format(
shape, dtype_util.name(shape.dtype)))
assertions = []
message = '`{}` ran... | def _maybe_check_valid_shape(shape, validate_args):
| """Check that a shape Tensor is int-type and otherwise sane."""
if not dtype_util.is_integer(shape.dtype):
raise TypeError('`{}` dtype (`{}`) should be `int`-like.'.format(
shape, dtype_util.name(shape.dtype)))
assertions = []
message = '`{}` rank should be <= 1.'
if tensorshape_util.rank(shape.... | event_tensorshape_out = tensorshape_util.constant_value_as_shape(
event_shape_out)
if tensorshape_util.rank(event_tensorshape_out) is None:
output_tensorshape = tf.TensorShape(None)
else:
output_tensorshape = tensorshape_util.concatenate(
input_non_event_tensorshape, event_tensorshape_out)
... | 95 | 95 | 318 | 11 | 83 | rmothukuru/probability | tensorflow_probability/python/bijectors/reshape.py | Python | _maybe_check_valid_shape | _maybe_check_valid_shape | 400 | 437 | 400 | 400 | 7a108ad9850c3842182250b322dadb3a27414bfb | bigcode/the-stack | train |
87a0d1c648df2e649ccfe331 | train | function | def _replace_event_shape_in_tensorshape(
input_tensorshape, event_shape_in, event_shape_out):
"""Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event sha... | def _replace_event_shape_in_tensorshape(
input_tensorshape, event_shape_in, event_shape_out):
| """Replaces the event shape dims of a `TensorShape`.
Args:
input_tensorshape: a `TensorShape` instance in which to attempt replacing
event shape.
event_shape_in: `Tensor` shape representing the event shape expected to
be present in (rightmost dims of) `tensorshape_in`. Must be compatible
... | -1` in
# `event_shape_in`. Note that our validations at construction time ensure
# there is at most one such entry in `event_shape_in`.
mask = event_shape_in >= 0
explicit_input_event_shape = tf.boolean_mask(input_event_shape, mask=mask)
explicit_event_shape_in = tf.boolean_mask(event_shape_in, mask... | 226 | 226 | 756 | 24 | 201 | rmothukuru/probability | tensorflow_probability/python/bijectors/reshape.py | Python | _replace_event_shape_in_tensorshape | _replace_event_shape_in_tensorshape | 332 | 397 | 332 | 333 | 0e1618b86eab1ceb02d795e2d2aaa80e0d406cb0 | bigcode/the-stack | train |
960913ccdc13732a7a170552 | train | class | @auto_composite_tensor.auto_composite_tensor(omit_kwargs=('name',))
class Reshape(bijector.AutoCompositeTensorBijector):
"""Reshapes the `event_shape` of a `Tensor`.
The semantics generally follow that of `tf.reshape()`, with
a few differences:
* The user must provide both the input and output shape, so that
... | @auto_composite_tensor.auto_composite_tensor(omit_kwargs=('name',))
class Reshape(bijector.AutoCompositeTensorBijector):
| """Reshapes the `event_shape` of a `Tensor`.
The semantics generally follow that of `tf.reshape()`, with
a few differences:
* The user must provide both the input and output shape, so that
the transformation can be inverted. If an input shape is not
specified, the default assumes a vector-shaped input... | .
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the ... | 256 | 256 | 2,106 | 28 | 228 | rmothukuru/probability | tensorflow_probability/python/bijectors/reshape.py | Python | Reshape | Reshape | 41 | 265 | 41 | 42 | 549aff23f16fd2f795e99fa4dd00053c3508a7b6 | bigcode/the-stack | train |
d53ae8f8f3f0729dde4ec3f0 | train | class | class DVIEvaluationTest(parameterized.TestCase):
@parameterized.parameters(_DTYPES,)
def test_dvi_sync_converges(self, dtype: np.dtype):
tolerance_places = 6 if dtype is np.float32 else 10
environment = micro.create_mrp1(dtype)
algorithm = dvi.Evaluation(
mrp=environment,
step_size=.5,
... | class DVIEvaluationTest(parameterized.TestCase):
@parameterized.parameters(_DTYPES,)
| def test_dvi_sync_converges(self, dtype: np.dtype):
tolerance_places = 6 if dtype is np.float32 else 10
environment = micro.create_mrp1(dtype)
algorithm = dvi.Evaluation(
mrp=environment,
step_size=.5,
beta=.5,
initial_r_bar=.5,
initial_values=np.zeros(environment.n... | """Tests for basic functioning of DVI algorithms."""
import functools
import itertools
from typing import Callable
import numpy as np
from absl.testing import absltest
from absl.testing import parameterized
from differential_value_iteration.algorithms import dvi
from differential_value_iteration.environments import ga... | 147 | 174 | 581 | 19 | 128 | btanner/differential_value_iteration | src/differential_value_iteration/algorithms/dvi_test.py | Python | DVIEvaluationTest | DVIEvaluationTest | 17 | 88 | 17 | 19 | 0c9642374507050e46b0e6eeb36e0431369b7dd5 | bigcode/the-stack | train |
0e37f4c2cf1b2415f61b27d2 | train | class | class DVIControlTest(parameterized.TestCase):
@parameterized.parameters(itertools.product(
(micro.create_mdp1, _GARET1, _GARET2, _GARET3), _DTYPES)
)
def test_dvi_sync_converges(self,
mdp_constructor: Callable[[np.dtype], structure.MarkovDecisionProcess],
dtype: np.dtype):
tolerance_places ... | class DVIControlTest(parameterized.TestCase):
@parameterized.parameters(itertools.product(
(micro.create_mdp1, _GARET1, _GARET2, _GARET3), _DTYPES)
)
| def test_dvi_sync_converges(self,
mdp_constructor: Callable[[np.dtype], structure.MarkovDecisionProcess],
dtype: np.dtype):
tolerance_places = 10 if dtype == np.float64 else 5
environment = mdp_constructor(dtype=dtype)
algorithm = dvi.Control(
mdp=environment,
step_size=1.,
... | (50):
change_sum = 0.
for _ in range(environment.num_states):
change = algorithm.update()
change_sum += np.abs(change)
with self.subTest('did_not_diverge'):
self.assertFalse(algorithm.diverged())
with self.subTest('maintained_types'):
self.assertTrue(algorithm.types_ok()... | 149 | 149 | 498 | 51 | 98 | btanner/differential_value_iteration | src/differential_value_iteration/algorithms/dvi_test.py | Python | DVIControlTest | DVIControlTest | 91 | 147 | 91 | 95 | 85ed59b69737cde73fea43812a80e8a0c69e7b26 | bigcode/the-stack | train |
857374f78b0bd987296b029f | train | function | @pytest.fixture
def mock_bridge(hass):
"""Mock a Hue bridge."""
bridge = Mock(
hass=hass,
available=True,
authorized=True,
allow_unreachable=False,
allow_groups=False,
api=Mock(),
reset_jobs=[],
spec=hue.HueBridge,
)
bridge.mock_requests = ... | @pytest.fixture
def mock_bridge(hass):
| """Mock a Hue bridge."""
bridge = Mock(
hass=hass,
available=True,
authorized=True,
allow_unreachable=False,
allow_groups=False,
api=Mock(),
reset_jobs=[],
spec=hue.HueBridge,
)
bridge.mock_requests = []
# We're using a deque so we can ... | ",
}
LIGHT_GAMUT = color.GamutType(
color.XYPoint(0.704, 0.296),
color.XYPoint(0.2151, 0.7106),
color.XYPoint(0.138, 0.08),
)
LIGHT_GAMUT_TYPE = "A"
@pytest.fixture
def mock_bridge(hass):
| 78 | 78 | 261 | 9 | 69 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | mock_bridge | mock_bridge | 178 | 217 | 178 | 179 | 6658b4855ee3fac7145534c1a0a87912158a4a56 | bigcode/the-stack | train |
c71ea66951da60e6dd290e39 | train | function | def test_hs_color():
"""Test hs_color property."""
light = hue_light.HueLight(
light=Mock(
state={"colormode": "ct", "hue": 1234, "sat": 123},
raw=LIGHT_RAW,
colorgamuttype=LIGHT_GAMUT_TYPE,
colorgamut=LIGHT_GAMUT,
),
coordinator=Mock(last_... | def test_hs_color():
| """Test hs_color property."""
light = hue_light.HueLight(
light=Mock(
state={"colormode": "ct", "hue": 1234, "sat": 123},
raw=LIGHT_RAW,
colorgamuttype=LIGHT_GAMUT_TYPE,
colorgamut=LIGHT_GAMUT,
),
coordinator=Mock(last_update_success=True),... | ,
)
assert light.available is True
light = hue_light.HueLight(
light=Mock(
state={"reachable": False},
raw=LIGHT_RAW,
colorgamuttype=LIGHT_GAMUT_TYPE,
colorgamut=LIGHT_GAMUT,
),
coordinator=Mock(last_update_success=True),
brid... | 100 | 100 | 336 | 6 | 93 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_hs_color | test_hs_color | 742 | 784 | 742 | 742 | 0bc8daec8b7d9600735fe22bbc3bf3c84b41ddd7 | bigcode/the-stack | train |
8cec1167ce2f4aadd2a3df59 | train | function | async def test_lights(hass, mock_bridge):
"""Test the update_lights function with some lights."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
# 2 lights
assert len(hass.states.async_all()) == 2
lamp... | async def test_lights(hass, mock_bridge):
| """Test the update_lights function with some lights."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
# 2 lights
assert len(hass.states.async_all()) == 2
lamp_1 = hass.states.get("light.hue_lamp_1")
... | mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append({})
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
assert len(hass.states.async_all()) == 0
async def test_lights(hass, mock_bridge):
| 64 | 64 | 182 | 11 | 52 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_lights | test_lights | 259 | 275 | 259 | 259 | 8db4ab73608a0de8642bad107c09b77d2c198250 | bigcode/the-stack | train |
15c6e9d7eb6eb1802c624502 | train | function | async def test_light_turn_off_service(hass, mock_bridge):
"""Test calling the turn on service on a light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
light = hass.states.get("light.hue_lamp_1")
assert light is not None
assert light.state == "o... | async def test_light_turn_off_service(hass, mock_bridge):
| """Test calling the turn on service on a light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
light = hass.states.get("light.hue_lamp_1")
assert light is not None
assert light.state == "on"
updated_light_response = dict(LIGHT_RESPONSE)
... | =True,
)
assert len(mock_bridge.mock_requests) == 5
assert mock_bridge.mock_requests[3]["json"] == {
"on": True,
"xy": (0.138, 0.08),
"alert": "none",
}
async def test_light_turn_off_service(hass, mock_bridge):
| 71 | 71 | 237 | 13 | 58 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_light_turn_off_service | test_light_turn_off_service | 669 | 694 | 669 | 669 | f54b9675eae28199059687ad6e206e152a7ad4b6 | bigcode/the-stack | train |
bdf74cda26e45c54d9eccd11 | train | function | def test_available():
"""Test available property."""
light = hue_light.HueLight(
light=Mock(
state={"reachable": False},
raw=LIGHT_RAW,
colorgamuttype=LIGHT_GAMUT_TYPE,
colorgamut=LIGHT_GAMUT,
),
coordinator=Mock(last_update_success=True),
... | def test_available():
| """Test available property."""
light = hue_light.HueLight(
light=Mock(
state={"reachable": False},
raw=LIGHT_RAW,
colorgamuttype=LIGHT_GAMUT_TYPE,
colorgamut=LIGHT_GAMUT,
),
coordinator=Mock(last_update_success=True),
bridge=Mock(al... | _bridge.mock_requests) == 3
assert mock_bridge.mock_requests[1]["json"] == {"on": False, "alert": "none"}
assert len(hass.states.async_all()) == 2
light = hass.states.get("light.hue_lamp_1")
assert light is not None
assert light.state == "off"
def test_available():
| 78 | 78 | 262 | 4 | 74 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_available | test_available | 697 | 739 | 697 | 697 | 6ab7fde90e38c6a971d1bf7f24a20f2b3792c145 | bigcode/the-stack | train |
b7419f752412538c9db7bd64 | train | function | async def test_other_group_update(hass, mock_bridge):
"""Test changing one group that will impact the state of other light."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
... | async def test_other_group_update(hass, mock_bridge):
| """Test changing one group that will impact the state of other light."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
asser... | a service will trigger the updates to run
await hass.services.async_call(
"light", "turn_on", {"entity_id": "light.hue_lamp_1"}, blocking=True
)
# 2x light update, 1 turn on request
assert len(mock_bridge.mock_requests) == 3
assert len(hass.states.async_all()) == 1
light = hass.states... | 138 | 138 | 461 | 12 | 125 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_other_group_update | test_other_group_update | 487 | 537 | 487 | 487 | 2c9b1f2ce577181bd184ebd3de726c976a718786 | bigcode/the-stack | train |
81cd8507e754338183138389 | train | function | async def test_lights_color_mode(hass, mock_bridge):
"""Test that lights only report appropriate color mode."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
lamp_1 = hass.states.get("light.hue_lamp_1")
assert lamp_1 is not None
assert lamp_1.stat... | async def test_lights_color_mode(hass, mock_bridge):
| """Test that lights only report appropriate color mode."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
lamp_1 = hass.states.get("light.hue_lamp_1")
assert lamp_1 is not None
assert lamp_1.state == "on"
assert lamp_1.attributes["brightness"] ... | 1")
assert lamp_1 is not None
assert lamp_1.state == "on"
assert lamp_1.attributes["brightness"] == 144
assert lamp_1.attributes["hs_color"] == (36.067, 69.804)
lamp_2 = hass.states.get("light.hue_lamp_2")
assert lamp_2 is not None
assert lamp_2.state == "off"
async def test_lights_color_mo... | 104 | 104 | 348 | 13 | 91 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_lights_color_mode | test_lights_color_mode | 278 | 308 | 278 | 278 | d225d5007f1c243258e2d6038295f4440c4dfd4a | bigcode/the-stack | train |
98c5001defd038398659fe03 | train | function | async def setup_bridge(hass, mock_bridge):
"""Load the Hue light platform with the provided bridge."""
hass.config.components.add(hue.DOMAIN)
config_entry = config_entries.ConfigEntry(
1,
hue.DOMAIN,
"Mock Title",
{"host": "mock-host"},
"test",
config_entries.... | async def setup_bridge(hass, mock_bridge):
| """Load the Hue light platform with the provided bridge."""
hass.config.components.add(hue.DOMAIN)
config_entry = config_entries.ConfigEntry(
1,
hue.DOMAIN,
"Mock Title",
{"host": "mock-host"},
"test",
config_entries.CONN_CLASS_LOCAL_POLL,
system_optio... | await task()
bridge.async_request_call = async_request_call
bridge.api.config.apiversion = "9.9.9"
bridge.api.lights = Lights({}, mock_request)
bridge.api.groups = Groups({}, mock_request)
return bridge
async def setup_bridge(hass, mock_bridge):
| 64 | 64 | 148 | 10 | 53 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | setup_bridge | setup_bridge | 220 | 236 | 220 | 220 | beb36bfe8c1da4c4a41716e0ab241aaf5df92aaf | bigcode/the-stack | train |
92cc95427cf0012b40af52ac | train | function | async def test_update_timeout(hass, mock_bridge):
"""Test bridge marked as not available if timeout error during update."""
mock_bridge.api.lights.update = Mock(side_effect=asyncio.TimeoutError)
mock_bridge.api.groups.update = Mock(side_effect=asyncio.TimeoutError)
await setup_bridge(hass, mock_bridge)
... | async def test_update_timeout(hass, mock_bridge):
| """Test bridge marked as not available if timeout error during update."""
mock_bridge.api.lights.update = Mock(side_effect=asyncio.TimeoutError)
mock_bridge.api.groups.update = Mock(side_effect=asyncio.TimeoutError)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 0
... | .hue_lamp_2")
assert lamp_2 is not None
assert lamp_2.name == "Hue Lamp 2 new"
assert lamp_2.state == "on"
assert lamp_2.attributes["brightness"] == 100
async def test_update_timeout(hass, mock_bridge):
| 64 | 64 | 93 | 11 | 52 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_update_timeout | test_update_timeout | 598 | 604 | 598 | 598 | d903f25185c2549e32ec743b95712af931bd9a44 | bigcode/the-stack | train |
c96be943198f060b7739b2b5 | train | function | async def test_light_turn_on_service(hass, mock_bridge):
"""Test calling the turn on service on a light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
light = hass.states.get("light.hue_lamp_2")
assert light is not None
assert light.state == "of... | async def test_light_turn_on_service(hass, mock_bridge):
| """Test calling the turn on service on a light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
light = hass.states.get("light.hue_lamp_2")
assert light is not None
assert light.state == "off"
updated_light_response = dict(LIGHT_RESPONSE)
... | """Test bridge marked as not authorized if unauthorized during update."""
mock_bridge.api.lights.update = Mock(side_effect=aiohue.Unauthorized)
mock_bridge.api.groups.update = Mock(side_effect=aiohue.Unauthorized)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 0
a... | 115 | 115 | 386 | 13 | 101 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_light_turn_on_service | test_light_turn_on_service | 617 | 666 | 617 | 617 | 38417a9b5d81bb791a798599c2f23de1b5e1594c | bigcode/the-stack | train |
ddf38fdc1249b1493e493896 | train | function | async def test_light_removed(hass, mock_bridge):
"""Test if 2nd update has removed light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 2
mock_bridge.mock_light_... | async def test_light_removed(hass, mock_bridge):
| """Test if 2nd update has removed light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 2
mock_bridge.mock_light_responses.clear()
mock_bridge.mock_light_resp... | == 4
assert len(hass.states.async_all()) == 1
group = hass.states.get("light.group_1")
assert group is not None
removed_group = hass.states.get("light.group_2")
assert removed_group is None
async def test_light_removed(hass, mock_bridge):
| 67 | 67 | 226 | 11 | 55 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_light_removed | test_light_removed | 460 | 484 | 460 | 460 | f4bd7ef55f6bc63c75275990003b4c4cb16d0afb | bigcode/the-stack | train |
fb33e070e3d53b8c27dc39e8 | train | function | async def test_other_light_update(hass, mock_bridge):
"""Test changing one light that will impact state of other light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == ... | async def test_other_light_update(hass, mock_bridge):
| """Test changing one light that will impact state of other light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 2
lamp_2 = hass.states.get("light.hue_lamp_2")
... | _responses.append(updated_group_response)
# Calling a service will trigger the updates to run
await hass.services.async_call(
"light", "turn_on", {"entity_id": "light.group_1"}, blocking=True
)
# 2x group update, 1x light update, 1 turn on request
assert len(mock_bridge.mock_requests) == 4
... | 152 | 152 | 509 | 12 | 140 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_other_light_update | test_other_light_update | 540 | 595 | 540 | 540 | dd8f6b7bb10dfd54372c2c9d310c9e99397735e4 | bigcode/the-stack | train |
4acecd9acaf93f02a2009010 | train | function | async def test_new_group_discovered(hass, mock_bridge):
"""Test if 2nd update has a new group."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock... | async def test_new_group_discovered(hass, mock_bridge):
| """Test if 2nd update has a new group."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
assert len(hass.states.async_all()) ... |
assert len(hass.states.async_all()) == 2
lamp_1 = hass.states.get("light.group_1")
assert lamp_1 is not None
assert lamp_1.state == "on"
assert lamp_1.attributes["brightness"] == 254
assert lamp_1.attributes["color_temp"] == 250
lamp_2 = hass.states.get("light.group_2")
assert lamp_2 ... | 120 | 120 | 401 | 13 | 107 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_new_group_discovered | test_new_group_discovered | 333 | 377 | 333 | 333 | 8296844cd1cce705e2d97e31fb0917cc03f59817 | bigcode/the-stack | train |
90c67cf5348319b82022c277 | train | function | async def test_new_light_discovered(hass, mock_bridge):
"""Test if 2nd update has a new light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 2
new_light_response... | async def test_new_light_discovered(hass, mock_bridge):
| """Test if 2nd update has a new light."""
mock_bridge.mock_light_responses.append(LIGHT_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 2
new_light_response = dict(LIGHT_RESPONSE)
new_light_response["3"] = {
... | _id": "light.group_1"}, blocking=True
)
# 2x group update, 1x light update, 1 turn on request
assert len(mock_bridge.mock_requests) == 4
assert len(hass.states.async_all()) == 3
new_group = hass.states.get("light.group_3")
assert new_group is not None
assert new_group.state == "on"
asse... | 126 | 126 | 421 | 13 | 112 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_new_light_discovered | test_new_light_discovered | 380 | 428 | 380 | 380 | 6b09483f6c6d5662e538f5be81f94d7f9ef52d08 | bigcode/the-stack | train |
d3f6f43454c25f3e0f69665e | train | function | async def test_update_unauthorized(hass, mock_bridge):
"""Test bridge marked as not authorized if unauthorized during update."""
mock_bridge.api.lights.update = Mock(side_effect=aiohue.Unauthorized)
mock_bridge.api.groups.update = Mock(side_effect=aiohue.Unauthorized)
await setup_bridge(hass, mock_bridg... | async def test_update_unauthorized(hass, mock_bridge):
| """Test bridge marked as not authorized if unauthorized during update."""
mock_bridge.api.lights.update = Mock(side_effect=aiohue.Unauthorized)
mock_bridge.api.groups.update = Mock(side_effect=aiohue.Unauthorized)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 0
a... | mock_bridge.api.groups.update = Mock(side_effect=asyncio.TimeoutError)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 0
assert len(hass.states.async_all()) == 0
async def test_update_unauthorized(hass, mock_bridge):
| 64 | 64 | 115 | 13 | 50 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_update_unauthorized | test_update_unauthorized | 607 | 614 | 607 | 607 | 6f878c19e02c15337dca6e379f630426f48237b2 | bigcode/the-stack | train |
cbb6b609465b70e3189a5c5f | train | function | async def test_no_lights_or_groups(hass, mock_bridge):
"""Test the update_lights function when no lights are found."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append({})
await setup_bridge(hass, mock_bridge)
assert len(mock_bri... | async def test_no_lights_or_groups(hass, mock_bridge):
| """Test the update_lights function when no lights are found."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append({})
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
assert len(hass.states.asyn... | ponses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 1
assert len(hass.states.async_all()) == 0
async def test_no_lights_or_groups(hass, mock_bridge):
| 64 | 64 | 89 | 14 | 49 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_no_lights_or_groups | test_no_lights_or_groups | 249 | 256 | 249 | 249 | daaac6d303fa2efb5e3fdb6cadf934e9d81fdb71 | bigcode/the-stack | train |
3e9008ffb0319ba0dccb360e | train | function | async def test_group_removed(hass, mock_bridge):
"""Test if 2nd update has removed group."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requ... | async def test_group_removed(hass, mock_bridge):
| """Test if 2nd update has removed group."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
assert len(hass.states.async_all()... | 1 turn on request
assert len(mock_bridge.mock_requests) == 3
assert len(hass.states.async_all()) == 3
light = hass.states.get("light.hue_lamp_3")
assert light is not None
assert light.state == "off"
async def test_group_removed(hass, mock_bridge):
| 71 | 71 | 239 | 11 | 60 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_group_removed | test_group_removed | 431 | 457 | 431 | 431 | 128f4a1d9d268073cb0f585508f85a48980ed401 | bigcode/the-stack | train |
61cba8f5f3c0069f6364ae56 | train | function | async def test_groups(hass, mock_bridge):
"""Test the update_lights function with some lights."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock... | async def test_groups(hass, mock_bridge):
| """Test the update_lights function with some lights."""
mock_bridge.allow_groups = True
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) == 2
# 2 hue group lights
... | is not None
assert lamp_1.state == "on"
assert lamp_1.attributes["brightness"] == 144
assert lamp_1.attributes["color_temp"] == 467
assert "hs_color" not in lamp_1.attributes
async def test_groups(hass, mock_bridge):
| 64 | 64 | 187 | 10 | 53 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_groups | test_groups | 311 | 330 | 311 | 311 | 4ee6b23961a27c4644558bb77880aa619a4dbdcd | bigcode/the-stack | train |
f7e7cf594180d4b3e74f2ba7 | train | function | async def test_not_load_groups_if_old_bridge(hass, mock_bridge):
"""Test that we don't try to load gorups if bridge runs old software."""
mock_bridge.api.config.apiversion = "1.12.0"
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridg... | async def test_not_load_groups_if_old_bridge(hass, mock_bridge):
| """Test that we don't try to load gorups if bridge runs old software."""
mock_bridge.api.config.apiversion = "1.12.0"
mock_bridge.mock_light_responses.append({})
mock_bridge.mock_group_responses.append(GROUP_RESPONSE)
await setup_bridge(hass, mock_bridge)
assert len(mock_bridge.mock_requests) ==... | AIN] = {config_entry.entry_id: mock_bridge}
await hass.config_entries.async_forward_entry_setup(config_entry, "light")
# To flush out the service call to update the group
await hass.async_block_till_done()
async def test_not_load_groups_if_old_bridge(hass, mock_bridge):
| 64 | 64 | 104 | 15 | 49 | Squixx/home-assistant | tests/components/hue/test_light.py | Python | test_not_load_groups_if_old_bridge | test_not_load_groups_if_old_bridge | 239 | 246 | 239 | 239 | 7b159fbc076553c27d15a3f1eb08ce766afee1aa | bigcode/the-stack | train |
0bcae830525cbd5f74f6adb2 | train | class | class TFCausalLanguageModelingLoss:
"""
Loss function suitable for causal language modeling (CLM), that is, the task of guessing the next token.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, lab... | class TFCausalLanguageModelingLoss:
| """
Loss function suitable for causal language modeling (CLM), that is, the task of guessing the next token.
<Tip>
Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
</Tip>
"""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.k... | kwargs)
return cfg
cls.get_config = get_config
cls._keras_serializable = True
if hasattr(tf.keras.utils, "register_keras_serializable"):
cls = tf.keras.utils.register_keras_serializable()(cls)
return cls
class TFCausalLanguageModelingLoss:
| 64 | 64 | 193 | 9 | 54 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFCausalLanguageModelingLoss | TFCausalLanguageModelingLoss | 170 | 189 | 170 | 170 | 589b6137d6a818693e0162c2e19655485fc3f412 | bigcode/the-stack | train |
0c86e900e76b6598af2bcb0b | train | function | def input_processing(func, config, input_ids, **kwargs):
"""
Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input
has to be named accordingly to the parameters name, i.e. `input_ids = tf.keras.Input(shape=(128,), dtype='int32',
name="input_i... | def input_processing(func, config, input_ids, **kwargs):
| """
Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input
has to be named accordingly to the parameters name, i.e. `input_ids = tf.keras.Input(shape=(128,), dtype='int32',
name="input_ids")` otherwise the order of the tensors will not be guar... | _hidden_states"] = (
kwargs["output_hidden_states"]
if kwargs["output_hidden_states"] is not None
else config.output_hidden_states
)
final_booleans["return_dict"] = (
kwargs["return_dict"] if kwargs["return_dict"] is not None else config.return_dict
... | 256 | 256 | 1,328 | 13 | 242 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | input_processing | input_processing | 346 | 491 | 346 | 346 | 316b2bb9a8037c0f24b787771fdd17e78eeacf95 | bigcode/the-stack | train |
b36c64e9dc711a0cbf607933 | train | class | class TFWrappedEmbeddings:
"""
this class wraps a the TFSharedEmbeddingTokens layer into a python 'no-keras-layer' class to avoid problem with
weight restoring. Also it makes sure that the layer is called from the correct scope to avoid problem with
saving/storing the correct weights
"""
def __... | class TFWrappedEmbeddings:
| """
this class wraps a the TFSharedEmbeddingTokens layer into a python 'no-keras-layer' class to avoid problem with
weight restoring. Also it makes sure that the layer is called from the correct scope to avoid problem with
saving/storing the correct weights
"""
def __init__(self, layer, abs_sco... | izers.TruncatedNormal:
"""
Creates a `tf.initializers.TruncatedNormal` with the given range.
Args:
initializer_range (*float*, defaults to 0.02): Standard deviation of the initializer range.
Returns:
`tf.initializers.TruncatedNormal`: The truncated normal initializer.
"""
retur... | 87 | 87 | 293 | 7 | 80 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFWrappedEmbeddings | TFWrappedEmbeddings | 2,061 | 2,088 | 2,061 | 2,061 | e357422a420c4c671f298b58af265560ebe81ad1 | bigcode/the-stack | train |
d9013391475407366b026552 | train | class | class TFModelUtilsMixin:
"""
A few utilities for `tf.keras.Model`, to be used as a mixin.
"""
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get the number of (optionally, trainable) parameters in the model.
Args:
only_trainable (`bool`, *optiona... | class TFModelUtilsMixin:
| """
A few utilities for `tf.keras.Model`, to be used as a mixin.
"""
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get the number of (optionally, trainable) parameters in the model.
Args:
only_trainable (`bool`, *optional*, defaults to `False`):... | List[KerasTensor],
Dict[str, tf.Tensor],
Dict[str, np.ndarray],
Dict[str, KerasTensor],
tf.Tensor,
np.ndarray,
KerasTensor,
]
def dummy_loss(y_true, y_pred):
return tf.reduce_mean(y_pred)
class TFModelUtilsMixin:
| 64 | 64 | 145 | 6 | 58 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFModelUtilsMixin | TFModelUtilsMixin | 83 | 102 | 83 | 83 | 83825c5e2ab47932b752eee246c830528fb4b63b | bigcode/the-stack | train |
f6c302ad636a2c6efde4b6ca | train | class | class TFSequenceSummary(tf.keras.layers.Layer):
"""
Compute a single vector summary of a sequence hidden states.
Args:
config ([`PretrainedConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of yo... | class TFSequenceSummary(tf.keras.layers.Layer):
| """
Compute a single vector summary of a sequence hidden states.
Args:
config ([`PretrainedConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default values it uses):
... | is not valid.
Shared weights logic is adapted from
[here](https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24).
"""
if mode == "embedding":
return self._embedding(inputs)
elif mode == "lin... | 256 | 256 | 1,426 | 9 | 247 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFSequenceSummary | TFSequenceSummary | 1,906 | 2,045 | 1,906 | 1,906 | 6270157babd097375ea8bdc215e64b3fbdc770df | bigcode/the-stack | train |
e08fdc072c139f756ca389ac | train | class | class TFConv1D(tf.keras.layers.Layer):
"""
1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).
Basically works like a linear layer but the weights are transposed.
Args:
nf (`int`):
The number of output features.
nx (`int`):
... | class TFConv1D(tf.keras.layers.Layer):
| """
1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).
Basically works like a linear layer but the weights are transposed.
Args:
nf (`int`):
The number of output features.
nx (`int`):
The number of input features.
... | we need to copy the method, otherwise we change the original docstring.
TFPreTrainedModel.push_to_hub = copy_func(TFPreTrainedModel.push_to_hub)
TFPreTrainedModel.push_to_hub.__doc__ = TFPreTrainedModel.push_to_hub.__doc__.format(
object="model", object_class="TFAutoModel", object_files="model checkpoint"
)
class ... | 95 | 95 | 318 | 10 | 85 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFConv1D | TFConv1D | 1,768 | 1,805 | 1,768 | 1,768 | a35724aeb71dc7d2d3f450b90a1d6ffaf39ba1d5 | bigcode/the-stack | train |
28ec3738a84a11369f95eee1 | train | class | class TFPreTrainedModel(tf.keras.Model, TFModelUtilsMixin, TFGenerationMixin, PushToHubMixin):
r"""
Base class for all TF models.
[`TFPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading,
downloading and saving models as well as a few methods common to... | class TFPreTrainedModel(tf.keras.Model, TFModelUtilsMixin, TFGenerationMixin, PushToHubMixin):
| r"""
Base class for all TF models.
[`TFPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading,
downloading and saving models as well as a few methods common to all models to:
- resize the input embeddings,
- prune heads in the self-atten... | , we extend the current embeddings with a padding until getting new size
# and we create a mask to properly identify the padded values and be replaced by the values of the newly created
# embeddings
current_weights = tf.pad(
old_embeddings.value(), tf.convert_to_tensor([[0, size_diff... | 256 | 256 | 11,043 | 24 | 231 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFPreTrainedModel | TFPreTrainedModel | 645 | 1,758 | 645 | 645 | d968973aec3b8824e51efc11388da7a7362c91f1 | bigcode/the-stack | train |
a52a624d794d30c3963a90a1 | train | class | class TFMultipleChoiceLoss:
"""Loss function suitable for multiple choice tasks."""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
return loss_fn(labels, logits)... | class TFMultipleChoiceLoss:
| """Loss function suitable for multiple choice tasks."""
def hf_compute_loss(self, labels, logits):
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
return loss_fn(labels, logits)
| .losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE)
else:
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
return loss_fn(labels, logits)
class TFMultipleChoiceLoss:
| 64 | 64 | 66 | 6 | 58 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFMultipleChoiceLoss | TFMultipleChoiceLoss | 251 | 258 | 251 | 251 | b1f92ccda588222d16819336371b4fff0558490f | bigcode/the-stack | train |
001730a577ebcc99e5207daf | train | function | def init_copy_embeddings(old_embeddings, new_num_tokens):
r"""
This function aims to reduce the embeddings in case new_num_tokens < old_num_tokens or to pad with -1 in case
new_num_tokens > old_num_tokens. A mask is also computed in order to know which weight in the embeddings should be
kept or not. Exa... | def init_copy_embeddings(old_embeddings, new_num_tokens):
| r"""
This function aims to reduce the embeddings in case new_num_tokens < old_num_tokens or to pad with -1 in case
new_num_tokens > old_num_tokens. A mask is also computed in order to know which weight in the embeddings should be
kept or not. Example:
- if new_num_tokens=5 and old_num_tokens=4 ... | _name, saved_weight_value.shape, K.int_shape(symbolic_weight))
)
continue
else:
raise e
else:
array = saved_weight_value
... | 145 | 145 | 484 | 11 | 133 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | init_copy_embeddings | init_copy_embeddings | 605 | 642 | 605 | 605 | db4f1b944c8d3278980d8d8981f586af1a5e53c4 | bigcode/the-stack | train |
bc53e1111de48eab701bea35 | train | function | def booleans_processing(config, **kwargs):
"""
Process the input booleans of each model in order to be sure they are compliant with the execution mode (eager or
graph)
Args:
config ([`PretrainedConfig`]):
The config of the running model.
**kwargs:
The boolean par... | def booleans_processing(config, **kwargs):
| """
Process the input booleans of each model in order to be sure they are compliant with the execution mode (eager or
graph)
Args:
config ([`PretrainedConfig`]):
The config of the running model.
**kwargs:
The boolean parameters
Returns:
A dictionary ... |
)
# make sure only labels that are not equal to -100
# are taken into account as loss
next_sentence_active_loss = tf.not_equal(tf.reshape(labels, (-1,)), -100)
next_sentence_reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, 2)), next_sentence_active_loss)
next_sen... | 117 | 117 | 390 | 10 | 107 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | booleans_processing | booleans_processing | 297 | 343 | 297 | 297 | 5106421acfcf5e55f7665dd1a7120f277ecdf6dd | bigcode/the-stack | train |
ca13b4d744116bde0db6e9a5 | train | function | def get_initializer(initializer_range: float = 0.02) -> tf.initializers.TruncatedNormal:
"""
Creates a `tf.initializers.TruncatedNormal` with the given range.
Args:
initializer_range (*float*, defaults to 0.02): Standard deviation of the initializer range.
Returns:
`tf.initializers.Tru... | def get_initializer(initializer_range: float = 0.02) -> tf.initializers.TruncatedNormal:
| """
Creates a `tf.initializers.TruncatedNormal` with the given range.
Args:
initializer_range (*float*, defaults to 0.02): Standard deviation of the initializer range.
Returns:
`tf.initializers.TruncatedNormal`: The truncated normal initializer.
"""
return tf.keras.initializers... | transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f"{auto_class} is not a valid auto class.")
cls._auto_class = auto_class
def get_initializer(initializer_range: float = 0.02) -> tf.initializers.TruncatedNormal:
| 64 | 64 | 97 | 22 | 41 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | get_initializer | get_initializer | 2,048 | 2,058 | 2,048 | 2,048 | a8aceccf6eab808f8516df13224dd1386b3d8553 | bigcode/the-stack | train |
ef0eea2fbfcdca062722da96 | train | class | class TFSequenceClassificationLoss:
"""
Loss function suitable for sequence classification.
"""
def hf_compute_loss(self, labels, logits):
if len(shape_list(logits)) == 1 or shape_list(logits)[1] == 1:
loss_fn = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NO... | class TFSequenceClassificationLoss:
| """
Loss function suitable for sequence classification.
"""
def hf_compute_loss(self, labels, logits):
if len(shape_list(logits)) == 1 or shape_list(logits)[1] == 1:
loss_fn = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE)
else:
loss_f... | 1,)) != -100
reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, shape_list(logits)[2])), active_loss)
labels = tf.boolean_mask(tf.reshape(labels, (-1,)), active_loss)
return loss_fn(labels, reduced_logits)
class TFSequenceClassificationLoss:
| 64 | 64 | 116 | 6 | 58 | reynolds9808/transformers_backdoor_attack | src/transformers/modeling_tf_utils.py | Python | TFSequenceClassificationLoss | TFSequenceClassificationLoss | 235 | 248 | 235 | 235 | a5479af91b98942718bda4230939bc73203e052d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.