language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 1949,
"end": 2103
} | class ____(_SimpleAutomotiveTestMixin):
"""Test ar_BH automotive provider methods"""
license_plate_pattern: Pattern = re.compile(r"\d{6}")
| TestArBh |
python | mlflow__mlflow | mlflow/gateway/providers/mlflow.py | {
"start": 2065,
"end": 8694
} | class ____(BaseProvider):
NAME = "MLflow Model Serving"
CONFIG_TYPE = MlflowModelServingConfig
def __init__(self, config: EndpointConfig) -> None:
super().__init__(config)
if config.model.config is None or not isinstance(
config.model.config, MlflowModelServingConfig
):
raise TypeError(f"Invalid config type {config.model.config}")
self.mlflow_config: MlflowModelServingConfig = config.model.config
self.headers = {"Content-Type": "application/json"}
@staticmethod
def _extract_mlflow_response_key(response):
if MLFLOW_SERVING_RESPONSE_KEY not in response:
raise AIGatewayException(
status_code=502,
detail=f"The response is missing the required key: {MLFLOW_SERVING_RESPONSE_KEY}.",
)
return response[MLFLOW_SERVING_RESPONSE_KEY]
@staticmethod
def _process_payload(payload, key):
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
input_data = payload.pop(key, None)
request_payload = {"inputs": input_data if isinstance(input_data, list) else [input_data]}
if payload:
request_payload["params"] = payload
return request_payload
@staticmethod
def _process_completions_response_for_mlflow_serving(response):
try:
validated_response = ServingTextResponse(**response)
inference_data = validated_response.predictions
except ValidationError as e:
raise AIGatewayException(status_code=502, detail=str(e))
return [
completions.Choice(index=idx, text=entry, finish_reason=None)
for idx, entry in enumerate(inference_data)
]
async def completions(self, payload: completions.RequestPayload) -> completions.ResponsePayload:
# Example request to MLflow REST API server for completions:
# {
# "inputs": ["hi", "hello", "bye"],
# "params": {
# "temperature": 0.5,
# "top_k": 3,
# }
# }
resp = await send_request(
headers=self.headers,
base_url=self.mlflow_config.model_server_url,
path="invocations",
payload=self._process_payload(payload, "prompt"),
)
# Example response:
# {"predictions": ["hello", "hi", "goodbye"]}
return completions.ResponsePayload(
created=int(time.time()),
object="text_completion",
model=self.config.model.name,
choices=self._process_completions_response_for_mlflow_serving(resp),
usage=completions.CompletionsUsage(
prompt_tokens=None,
completion_tokens=None,
total_tokens=None,
),
)
def _process_chat_response_for_mlflow_serving(self, response):
try:
validated_response = ServingTextResponse(**response)
inference_data = validated_response.predictions
except ValidationError as e:
raise AIGatewayException(status_code=502, detail=str(e))
return [
{"message": {"role": "assistant", "content": entry}, "metadata": {}}
for entry in inference_data
]
async def chat(self, payload: chat.RequestPayload) -> chat.ResponsePayload:
# Example request to MLflow REST API for chat:
# {
# "inputs": ["question"],
# "params": ["temperature": 0.2],
# }
payload = self._process_payload(payload, "messages")
query_count = len(payload["inputs"])
if query_count > 1:
raise AIGatewayException(
status_code=422,
detail="MLflow chat models are only capable of processing a single query at a "
f"time. The request submitted consists of {query_count} queries.",
)
payload["inputs"] = [payload["inputs"][0]["content"]]
resp = await send_request(
headers=self.headers,
base_url=self.mlflow_config.model_server_url,
path="invocations",
payload=payload,
)
# Example response:
# {"predictions": ["answer"]}
return chat.ResponsePayload(
created=int(time.time()),
model=self.config.model.name,
choices=[
chat.Choice(
index=idx,
message=chat.ResponseMessage(
role=c["message"]["role"], content=c["message"]["content"]
),
finish_reason=None,
)
for idx, c in enumerate(self._process_chat_response_for_mlflow_serving(resp))
],
usage=chat.ChatUsage(
prompt_tokens=None,
completion_tokens=None,
total_tokens=None,
),
)
def _process_embeddings_response_for_mlflow_serving(self, response):
try:
validated_response = EmbeddingsResponse(**response)
inference_data = validated_response.predictions
except ValidationError as e:
raise AIGatewayException(status_code=502, detail=str(e))
return inference_data
async def embeddings(self, payload: embeddings.RequestPayload) -> embeddings.ResponsePayload:
# Example request to MLflow REST API server for embeddings:
# {
# "inputs": ["a sentence", "another sentence"],
# "params": {
# "output_value": "token_embeddings",
# }
# }
resp = await send_request(
headers=self.headers,
base_url=self.mlflow_config.model_server_url,
path="invocations",
payload=self._process_payload(payload, "input"),
)
# Example response:
# {"predictions": [[0.100, -0.234, 0.002, ...], [0.222, -0.111, 0.134, ...]]}
return embeddings.ResponsePayload(
data=[
embeddings.EmbeddingObject(
embedding=embedding,
index=idx,
)
for idx, embedding in enumerate(
self._process_embeddings_response_for_mlflow_serving(resp)
)
],
model=self.config.model.name,
usage=embeddings.EmbeddingsUsage(
prompt_tokens=None,
total_tokens=None,
),
)
| MlflowModelServingProvider |
python | ahupp__python-magic | test/libmagic_test.py | {
"start": 298,
"end": 1732
} | class ____(unittest.TestCase):
filename = os.path.join(TESTDATA_DIR, "test.pdf")
expected_mime_type = "application/pdf"
expected_encoding = "us-ascii"
expected_name = (
"PDF document, version 1.2",
"PDF document, version 1.2, 2 pages",
"PDF document, version 1.2, 2 page(s)",
)
def assert_result(self, result):
self.assertEqual(result.mime_type, self.expected_mime_type)
self.assertEqual(result.encoding, self.expected_encoding)
self.assertIn(result.name, self.expected_name)
def test_detect_from_filename(self):
result = magic.detect_from_filename(self.filename)
self.assert_result(result)
def test_detect_from_fobj(self):
if SKIP_FROM_DESCRIPTOR:
self.skipTest("magic_descriptor is broken in this version of libmagic")
with open(self.filename) as fobj:
result = magic.detect_from_fobj(fobj)
self.assert_result(result)
def test_detect_from_content(self):
# differ from upstream by opening file in binary mode,
# this avoids hitting a bug in python3+libfile bindings
# see https://github.com/ahupp/python-magic/issues/152
# for a similar issue
with open(self.filename, "rb") as fobj:
result = magic.detect_from_content(fobj.read(4096))
self.assert_result(result)
if __name__ == "__main__":
unittest.main()
| MagicTestCase |
python | django__django | tests/migrations2/test_migrations_2/0001_initial.py | {
"start": 43,
"end": 559
} | class ____(migrations.Migration):
dependencies = [("migrations", "0002_second")]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
("age", models.IntegerField(default=0)),
("silly_field", models.BooleanField(default=False)),
],
),
]
| Migration |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/workspace.py | {
"start": 12398,
"end": 19625
} | class ____:
def __init__(
self,
uri,
workspace,
source=None,
version=None,
local=True,
extra_sys_path=None,
rope_project_builder=None,
) -> None:
self.uri = uri
self.version = version
self.path = uris.to_fs_path(uri)
self.dot_path = _utils.path_to_dot_name(self.path)
self.filename = os.path.basename(self.path)
self.shared_data = {}
self._config = workspace._config
self._workspace = workspace
self._local = local
self._source = source
self._extra_sys_path = extra_sys_path or []
self._rope_project_builder = rope_project_builder
self._lock = RLock()
def __str__(self):
return str(self.uri)
def _rope_resource(self, rope_config):
from rope.base import libutils
return libutils.path_to_resource(
self._rope_project_builder(rope_config), self.path
)
@property
@lock
def lines(self):
return self.source.splitlines(True)
@property
@lock
def source(self):
if self._source is None:
with open(self.path, encoding="utf-8") as f:
return f.read()
return self._source
def update_config(self, settings) -> None:
self._config.update((settings or {}).get("pylsp", {}))
@lock
def apply_change(self, change):
"""Apply a change to the document."""
text = change["text"]
change_range = change.get("range")
if not change_range:
# The whole file has changed
self._source = text
return
start_line = change_range["start"]["line"]
start_col = change_range["start"]["character"]
end_line = change_range["end"]["line"]
end_col = change_range["end"]["character"]
# Check for an edit occuring at the very end of the file
lines = self.lines
if start_line == len(lines):
self._source = self.source + text
return
new = io.StringIO()
# Iterate over the existing document until we hit the edit range,
# at which point we write the new text, then loop until we hit
# the end of the range and continue writing.
for i, line in enumerate(lines):
if i < start_line:
new.write(line)
continue
if i > end_line:
new.write(line)
continue
if i == start_line:
new.write(line[:start_col])
new.write(text)
if i == end_line:
new.write(line[end_col:])
self._source = new.getvalue()
def offset_at_position(self, position):
"""Return the byte-offset pointed at by the given position."""
return position["character"] + len("".join(self.lines[: position["line"]]))
def word_at_position(self, position):
"""Get the word under the cursor returning the start and end positions."""
lines = self.lines
if position["line"] >= len(lines):
return ""
line = lines[position["line"]]
i = position["character"]
# Split word in two
start = line[:i]
end = line[i:]
# Take end of start and start of end to find word
# These are guaranteed to match, even if they match the empty string
m_start = RE_START_WORD.findall(start)
m_end = RE_END_WORD.findall(end)
return m_start[0] + m_end[-1]
@lock
def jedi_names(self, all_scopes=False, definitions=True, references=False):
script = self.jedi_script()
return script.get_names(
all_scopes=all_scopes, definitions=definitions, references=references
)
@lock
def jedi_script(self, position=None, use_document_path=False):
extra_paths = []
environment_path = None
env_vars = None
prioritize_extra_paths = False
if self._config:
jedi_settings = self._config.plugin_settings(
"jedi", document_path=self.path
)
jedi.settings.auto_import_modules = jedi_settings.get(
"auto_import_modules", DEFAULT_AUTO_IMPORT_MODULES
)
environment_path = jedi_settings.get("environment")
# Jedi itself cannot deal with homedir-relative paths.
# On systems, where it is expected, expand the home directory.
if environment_path and os.name != "nt":
environment_path = os.path.expanduser(environment_path)
extra_paths = jedi_settings.get("extra_paths") or []
env_vars = jedi_settings.get("env_vars")
prioritize_extra_paths = jedi_settings.get("prioritize_extra_paths")
# Drop PYTHONPATH from env_vars before creating the environment to
# ensure that Jedi can startup properly without module name collision.
if env_vars is None:
env_vars = os.environ.copy()
env_vars.pop("PYTHONPATH", None)
environment = self.get_enviroment(environment_path, env_vars=env_vars)
sys_path = self.sys_path(
environment_path, env_vars, prioritize_extra_paths, extra_paths
)
project_path = self._workspace.root_path
# Extend sys_path with document's path if requested
if use_document_path:
sys_path += [os.path.normpath(os.path.dirname(self.path))]
kwargs = {
"code": self.source,
"path": self.path,
"environment": environment if environment_path else None,
"project": jedi.Project(path=project_path, sys_path=sys_path),
}
if position:
# Deprecated by Jedi to use in Script() constructor
kwargs += _utils.position_to_jedi_linecolumn(self, position)
return jedi.Script(**kwargs)
def get_enviroment(self, environment_path=None, env_vars=None):
# TODO(gatesn): #339 - make better use of jedi environments, they seem pretty powerful
if environment_path is None:
environment = jedi.api.environment.get_cached_default_environment()
else:
if environment_path in self._workspace._environments:
environment = self._workspace._environments[environment_path]
else:
environment = jedi.api.environment.create_environment(
path=environment_path, safe=False, env_vars=env_vars
)
self._workspace._environments[environment_path] = environment
return environment
def sys_path(
self,
environment_path=None,
env_vars=None,
prioritize_extra_paths=False,
extra_paths=[],
):
# Copy our extra sys path
path = list(self._extra_sys_path)
environment = self.get_enviroment(
environment_path=environment_path, env_vars=env_vars
)
path.extend(environment.get_sys_path())
if prioritize_extra_paths:
path = extra_paths + path
else:
path = path + extra_paths
return path
| Document |
python | SmileyChris__easy-thumbnails | easy_thumbnails/files.py | {
"start": 27511,
"end": 28589
} | class ____(ImageFieldFile, ThumbnailerFieldFile):
"""
A field file which provides some methods for generating (and returning)
thumbnail images.
"""
def save(self, name, content, *args, **kwargs):
"""
Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field.
"""
options = getattr(self.field, 'resize_source', None)
if options:
if 'quality' not in options:
options['quality'] = self.thumbnail_quality
content = Thumbnailer(content, name).generate_thumbnail(options)
# If the generated extension differs from the original, use it
# instead.
orig_name, ext = os.path.splitext(name)
generated_ext = os.path.splitext(content.name)[1]
if generated_ext.lower() != ext.lower():
name = orig_name + generated_ext
super().save(name, content, *args, **kwargs)
| ThumbnailerImageFieldFile |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 101790,
"end": 102284
} | class ____(fixtures.TestBase):
"""Test of test things"""
@testing.variation("foo", ["foo", "bar", "baz"])
def test_variations(self, foo):
match foo:
case "foo":
is_true(foo.foo)
is_false(foo.bar)
case "bar":
is_true(foo.bar)
is_false(foo.foo)
case "baz":
is_true(foo.baz)
is_false(foo.foo)
case _:
foo.fail()
| TestTest |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/cache.py | {
"start": 941,
"end": 4864
} | class ____:
"""A static class to manage the global secret cache."""
__manager: multiprocessing.managers.SyncManager | None = None
_cache: dict[str, _CacheValue] | None = None
_ttl: datetime.timedelta
class NotPresentException(Exception):
"""Raised when a key is not present in the cache."""
class _CacheValue:
def __init__(self, value: str | None) -> None:
self.value = value
self.date = timezone.utcnow()
def is_expired(self, ttl: datetime.timedelta) -> bool:
return timezone.utcnow() - self.date > ttl
_VARIABLE_PREFIX = "__v_"
_CONNECTION_PREFIX = "__c_"
@classmethod
def init(cls):
"""
Initialize the cache, provided the configuration allows it.
Safe to call several times.
"""
if cls._cache is not None:
return
use_cache = conf.getboolean(section="secrets", key="use_cache", fallback=False)
if not use_cache:
return
if cls.__manager is None:
# it is not really necessary to save the manager, but doing so allows to reuse it between tests,
# making them run a lot faster because this operation takes ~300ms each time
cls.__manager = multiprocessing.Manager()
cls._cache = cls.__manager.dict()
ttl_seconds = conf.getint(section="secrets", key="cache_ttl_seconds", fallback=15 * 60)
cls._ttl = datetime.timedelta(seconds=ttl_seconds)
@classmethod
def reset(cls):
"""Use for test purposes only."""
cls._cache = None
@classmethod
def get_variable(cls, key: str) -> str | None:
"""
Try to get the value associated with the key from the cache.
:return: The saved value (which can be None) if present in cache and not expired,
a NotPresent exception otherwise.
"""
return cls._get(key, cls._VARIABLE_PREFIX)
@classmethod
def get_connection_uri(cls, conn_id: str) -> str:
"""
Try to get the uri associated with the conn_id from the cache.
:return: The saved uri if present in cache and not expired,
a NotPresent exception otherwise.
"""
val = cls._get(conn_id, cls._CONNECTION_PREFIX)
if val: # there shouldn't be any empty entries in the connections cache, but we enforce it here.
return val
raise cls.NotPresentException
@classmethod
def _get(cls, key: str, prefix: str) -> str | None:
if cls._cache is None:
# using an exception for misses allow to meaningfully cache None values
raise cls.NotPresentException
val = cls._cache.get(f"{prefix}{key}")
if val and not val.is_expired(cls._ttl):
return val.value
raise cls.NotPresentException
@classmethod
def save_variable(cls, key: str, value: str | None):
"""Save the value for that key in the cache, if initialized."""
cls._save(key, value, cls._VARIABLE_PREFIX)
@classmethod
def save_connection_uri(cls, conn_id: str, uri: str):
"""Save the uri representation for that connection in the cache, if initialized."""
if uri is None:
# connections raise exceptions if not present, so we shouldn't have any None value to save.
return
cls._save(conn_id, uri, cls._CONNECTION_PREFIX)
@classmethod
def _save(cls, key: str, value: str | None, prefix: str):
if cls._cache is not None:
cls._cache[f"{prefix}{key}"] = cls._CacheValue(value)
@classmethod
def invalidate_variable(cls, key: str):
"""Invalidate (actually removes) the value stored in the cache for that Variable."""
if cls._cache is not None:
# second arg ensures no exception if key is absent
cls._cache.pop(f"{cls._VARIABLE_PREFIX}{key}", None)
| SecretCache |
python | great-expectations__great_expectations | tests/integration/data_sources_and_expectations/expectations/test_expect_column_values_to_not_match_like_pattern.py | {
"start": 4394,
"end": 5659
} | class ____:
@pytest.mark.parametrize(
"expectation",
[
pytest.param(
gxe.ExpectColumnValuesToNotMatchLikePattern(column=COL_A, like_pattern="a[xzy]"),
id="bracket_notation",
),
],
)
@parameterize_batch_for_data_sources(
data_source_configs=[MSSQLDatasourceTestConfig()], data=DATA
)
def test_success(
self,
batch_for_datasource: Batch,
expectation: gxe.ExpectColumnValuesToNotMatchLikePattern,
) -> None:
result = batch_for_datasource.validate(expectation)
assert result.success
@pytest.mark.parametrize(
"expectation",
[
pytest.param(
gxe.ExpectColumnValuesToNotMatchLikePattern(column=COL_A, like_pattern="a[abc]"),
id="bracket_notation_fail",
),
],
)
@parameterize_batch_for_data_sources(
data_source_configs=[MSSQLDatasourceTestConfig()], data=DATA
)
def test_failure(
self,
batch_for_datasource: Batch,
expectation: gxe.ExpectColumnValuesToNotMatchLikePattern,
) -> None:
result = batch_for_datasource.validate(expectation)
assert not result.success
| TestMSSQL |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmc_theano.py | {
"start": 764,
"end": 6490
} | class ____:
def __init__(self, M, K):
self.M = M # number of hidden states
self.K = K # number of Gaussians
def fit(self, X, learning_rate=1e-2, max_iter=10):
# train the HMM model using gradient descent
N = len(X)
D = X[0].shape[1] # assume each x is organized (T, D)
pi0 = np.ones(self.M) / self.M # initial state distribution
A0 = random_normalized(self.M, self.M) # state transition matrix
R0 = np.ones((self.M, self.K)) / self.K # mixture proportions
mu0 = np.zeros((self.M, self.K, D))
for i in range(self.M):
for k in range(self.K):
random_idx = np.random.choice(N)
x = X[random_idx]
random_time_idx = np.random.choice(len(x))
mu0[i,k] = x[random_time_idx]
sigma0 = np.zeros((self.M, self.K, D, D))
for j in range(self.M):
for k in range(self.K):
sigma0[j,k] = np.eye(D)
thx, cost = self.set(pi0, A0, R0, mu0, sigma0)
pi_update = self.pi - learning_rate*T.grad(cost, self.pi)
pi_update = pi_update / pi_update.sum()
A_update = self.A - learning_rate*T.grad(cost, self.A)
A_update = A_update / A_update.sum(axis=1).dimshuffle(0, 'x')
R_update = self.R - learning_rate*T.grad(cost, self.R)
R_update = R_update / R_update.sum(axis=1).dimshuffle(0, 'x')
updates = [
(self.pi, pi_update),
(self.A, A_update),
(self.R, R_update),
(self.mu, self.mu - learning_rate*T.grad(cost, self.mu)),
(self.sigma, self.sigma - learning_rate*T.grad(cost, self.sigma)),
]
train_op = theano.function(
inputs=[thx],
updates=updates,
)
costs = []
for it in range(max_iter):
print("it:", it)
for n in range(N):
c = self.log_likelihood_multi(X).sum()
print("c:", c)
costs.append(c)
train_op(X[n])
print("A:", self.A.get_value())
print("mu:", self.mu.get_value())
print("sigma:", self.sigma.get_value())
print("R:", self.R.get_value())
print("pi:", self.pi.get_value())
plt.plot(costs)
plt.show()
def set(self, pi, A, R, mu, sigma):
self.pi = theano.shared(pi)
self.A = theano.shared(A)
self.R = theano.shared(R)
self.mu = theano.shared(mu)
self.sigma = theano.shared(sigma)
M, K = R.shape
self.M = M
self.K = K
D = self.mu.shape[2]
twopiD = (2*np.pi)**D
# set up theano variables and functions
thx = T.matrix('X') # represents a TxD matrix of sequential observations
def mvn_pdf(x, mu, sigma):
k = 1 / T.sqrt(twopiD * T.nlinalg.det(sigma))
e = T.exp(-0.5*(x - mu).T.dot(T.nlinalg.matrix_inverse(sigma).dot(x - mu)))
return k*e
def gmm_pdf(x):
def state_pdfs(xt):
def component_pdf(j, xt):
Bj_t = 0
for k in range(self.K):
Bj_t += self.R[j,k] * mvn_pdf(xt, self.mu[j,k], self.sigma[j,k])
return Bj_t
Bt, _ = theano.scan(
fn=component_pdf,
sequences=T.arange(self.M),
n_steps=self.M,
outputs_info=None,
non_sequences=[xt],
)
return Bt
B, _ = theano.scan(
fn=state_pdfs,
sequences=x,
n_steps=x.shape[0],
outputs_info=None,
)
return B.T
B = gmm_pdf(thx)
# scale = T.zeros((thx.shape[0], 1), dtype=theano.config.floatX)
# scale[0] = (self.pi*B[:,0]).sum()
def recurrence(t, old_a, B):
a = old_a.dot(self.A) * B[:, t]
s = a.sum()
return (a / s), s
[alpha, scale], _ = theano.scan(
fn=recurrence,
sequences=T.arange(1, thx.shape[0]),
outputs_info=[self.pi*B[:,0], None],
n_steps=thx.shape[0]-1,
non_sequences=[B],
)
cost = -T.log(scale).sum()
self.cost_op = theano.function(
inputs=[thx],
outputs=cost,
)
return thx, cost
def log_likelihood_multi(self, X):
return np.array([self.cost_op(x) for x in X])
def real_signal():
spf = wave.open('helloworld.wav', 'r')
#Extract Raw Audio from Wav File
# If you right-click on the file and go to "Get Info", you can see:
# sampling rate = 16000 Hz
# bits per sample = 16
# The first is quantization in time
# The second is quantization in amplitude
# We also do this for images!
# 2^16 = 65536 is how many different sound levels we have
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
T = len(signal)
signal = (signal - signal.mean()) / signal.std()
hmm = HMM(5, 3)
# signal needs to be of shape N x T(n) x D
hmm.fit(signal.reshape(1, T, 1), learning_rate=1e-5, max_iter=20)
def fake_signal():
signals = get_signals()
hmm = HMM(5, 3)
hmm.fit(signals)
L = hmm.log_likelihood_multi(signals).sum()
print("LL for fitted params:", L)
# test in actual params
_, _, _, pi, A, R, mu, sigma = big_init()
hmm.set(pi, A, R, mu, sigma)
L = hmm.log_likelihood_multi(signals).sum()
print("LL for actual params:", L)
if __name__ == '__main__':
# real_signal()
fake_signal()
| HMM |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 1863,
"end": 1990
} | class ____(Protocol[_A, _B]): ...
# This should generate an error because Protocol must
# include all of the TypeVars.
| ProtoBase1 |
python | RaRe-Technologies__gensim | gensim/models/ldamulticore.py | {
"start": 4050,
"end": 17462
} | class ____(LdaModel):
"""An optimized implementation of the LDA algorithm, able to harness the power of multicore CPUs.
Follows the similar API as the parent class :class:`~gensim.models.ldamodel.LdaModel`.
"""
def __init__(self, corpus=None, num_topics=100, id2word=None, workers=None,
chunksize=2000, passes=1, batch=False, alpha='symmetric',
eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50,
gamma_threshold=0.001, random_state=None, minimum_probability=0.01,
minimum_phi_value=0.01, per_word_topics=False, dtype=np.float32):
"""
Parameters
----------
corpus : {iterable of list of (int, float), scipy.sparse.csc}, optional
Stream of document vectors or sparse matrix of shape (`num_documents`, `num_terms`).
If not given, the model is left untrained (presumably because you want to call
:meth:`~gensim.models.ldamodel.LdaModel.update` manually).
num_topics : int, optional
The number of requested latent topics to be extracted from the training corpus.
id2word : {dict of (int, str), :class:`gensim.corpora.dictionary.Dictionary`}
Mapping from word IDs to words. It is used to determine the vocabulary size, as well as for
debugging and topic printing.
workers : int, optional
Number of workers processes to be used for parallelization. If None all available cores
(as estimated by `workers=cpu_count()-1` will be used. **Note** however that for
hyper-threaded CPUs, this estimation returns a too high number -- set `workers`
directly to the number of your **real** cores (not hyperthreads) minus one, for optimal performance.
chunksize : int, optional
Number of documents to be used in each training chunk.
passes : int, optional
Number of passes through the corpus during training.
alpha : {float, numpy.ndarray of float, list of float, str}, optional
A-priori belief on document-topic distribution, this can be:
* scalar for a symmetric prior over document-topic distribution,
* 1D array of length equal to num_topics to denote an asymmetric user defined prior for each topic.
Alternatively default prior selecting strategies can be employed by supplying a string:
* 'symmetric': (default) Uses a fixed symmetric prior of `1.0 / num_topics`,
* 'asymmetric': Uses a fixed normalized asymmetric prior of `1.0 / (topic_index + sqrt(num_topics))`.
eta : {float, numpy.ndarray of float, list of float, str}, optional
A-priori belief on topic-word distribution, this can be:
* scalar for a symmetric prior over topic-word distribution,
* 1D array of length equal to num_words to denote an asymmetric user defined prior for each word,
* matrix of shape (num_topics, num_words) to assign a probability for each word-topic combination.
Alternatively default prior selecting strategies can be employed by supplying a string:
* 'symmetric': (default) Uses a fixed symmetric prior of `1.0 / num_topics`,
* 'auto': Learns an asymmetric prior from the corpus.
decay : float, optional
A number between (0.5, 1] to weight what percentage of the previous lambda value is forgotten
when each new document is examined. Corresponds to :math:`\\kappa` from
`'Online Learning for LDA' by Hoffman et al.`_
offset : float, optional
Hyper-parameter that controls how much we will slow down the first steps the first few iterations.
Corresponds to :math:`\\tau_0` from `'Online Learning for LDA' by Hoffman et al.`_
eval_every : int, optional
Log perplexity is estimated every that many updates. Setting this to one slows down training by ~2x.
iterations : int, optional
Maximum number of iterations through the corpus when inferring the topic distribution of a corpus.
gamma_threshold : float, optional
Minimum change in the value of the gamma parameters to continue iterating.
minimum_probability : float, optional
Topics with a probability lower than this threshold will be filtered out.
random_state : {np.random.RandomState, int}, optional
Either a randomState object or a seed to generate one. Useful for reproducibility.
Note that results can still vary due to non-determinism in OS scheduling of the worker processes.
minimum_phi_value : float, optional
if `per_word_topics` is True, this represents a lower bound on the term probabilities.
per_word_topics : bool
If True, the model also computes a list of topics, sorted in descending order of most likely topics for
each word, along with their phi values multiplied by the feature length (i.e. word count).
dtype : {numpy.float16, numpy.float32, numpy.float64}, optional
Data-type to use during calculations inside model. All inputs are also converted.
"""
self.workers = max(1, cpu_count() - 1) if workers is None else workers
self.batch = batch
if isinstance(alpha, str) and alpha == 'auto':
raise NotImplementedError("auto-tuning alpha not implemented in LdaMulticore; use plain LdaModel.")
super(LdaMulticore, self).__init__(
corpus=corpus, num_topics=num_topics,
id2word=id2word, chunksize=chunksize, passes=passes, alpha=alpha, eta=eta,
decay=decay, offset=offset, eval_every=eval_every, iterations=iterations,
gamma_threshold=gamma_threshold, random_state=random_state, minimum_probability=minimum_probability,
minimum_phi_value=minimum_phi_value, per_word_topics=per_word_topics, dtype=dtype,
)
def update(self, corpus, chunks_as_numpy=False):
"""Train the model with new documents, by EM-iterating over `corpus` until the topics converge
(or until the maximum number of allowed iterations is reached).
Train the model with new documents, by EM-iterating over the corpus until the topics converge, or until
the maximum number of allowed iterations is reached. `corpus` must be an iterable. The E step is distributed
into the several processes.
Notes
-----
This update also supports updating an already trained model (`self`) with new documents from `corpus`;
the two models are then merged in proportion to the number of old vs. new documents.
This feature is still experimental for non-stationary input streams.
For stationary input (no topic drift in new documents), on the other hand,
this equals the online update of `'Online Learning for LDA' by Hoffman et al.`_
and is guaranteed to converge for any `decay` in (0.5, 1].
Parameters
----------
corpus : {iterable of list of (int, float), scipy.sparse.csc}, optional
Stream of document vectors or sparse matrix of shape (`num_documents`, `num_terms`) used to update the
model.
chunks_as_numpy : bool
Whether each chunk passed to the inference step should be a np.ndarray or not. Numpy can in some settings
turn the term IDs into floats, these will be converted back into integers in inference, which incurs a
performance hit. For distributed computing it may be desirable to keep the chunks as `numpy.ndarray`.
"""
try:
lencorpus = len(corpus)
except TypeError:
logger.warning("input corpus stream has no len(); counting documents")
lencorpus = sum(1 for _ in corpus)
if lencorpus == 0:
logger.warning("LdaMulticore.update() called with an empty corpus")
return
self.state.numdocs += lencorpus
if self.batch:
updatetype = "batch"
updateafter = lencorpus
else:
updatetype = "online"
updateafter = self.chunksize * self.workers
eval_every = self.eval_every or 0
evalafter = min(lencorpus, eval_every * updateafter)
updates_per_pass = max(1, lencorpus / updateafter)
logger.info(
"running %s LDA training, %s topics, %i passes over the supplied corpus of %i documents, "
"updating every %i documents, evaluating every ~%i documents, "
"iterating %ix with a convergence threshold of %f",
updatetype, self.num_topics, self.passes, lencorpus, updateafter,
evalafter, self.iterations, self.gamma_threshold
)
if updates_per_pass * self.passes < 10:
logger.warning(
"too few updates, training might not converge; "
"consider increasing the number of passes or iterations to improve accuracy"
)
job_queue = Queue(maxsize=2 * self.workers)
result_queue = Queue()
# rho is the "speed" of updating; TODO try other fncs
# pass_ + num_updates handles increasing the starting t for each pass,
# while allowing it to "reset" on the first pass of each update
def rho():
return pow(self.offset + pass_ + (self.num_updates / self.chunksize), -self.decay)
def process_result_queue(force=False):
"""
Clear the result queue, merging all intermediate results, and update the
LDA model if necessary.
"""
merged_new = False
while not result_queue.empty():
other.merge(result_queue.get())
queue_size[0] -= 1
merged_new = True
if (force and merged_new and queue_size[0] == 0) or (other.numdocs >= updateafter):
self.do_mstep(rho(), other, pass_ > 0)
other.reset()
if eval_every > 0 and (force or (self.num_updates / updateafter) % eval_every == 0):
self.log_perplexity(chunk, total_docs=lencorpus)
logger.info("training LDA model using %i processes", self.workers)
pool = Pool(self.workers, worker_e_step, (job_queue, result_queue, self))
for pass_ in range(self.passes):
queue_size, reallen = [0], 0
other = LdaState(self.eta, self.state.sstats.shape)
chunk_stream = utils.grouper(corpus, self.chunksize, as_numpy=chunks_as_numpy)
for chunk_no, chunk in enumerate(chunk_stream):
reallen += len(chunk) # keep track of how many documents we've processed so far
# put the chunk into the workers' input job queue
while True:
try:
job_queue.put((chunk_no, chunk, self.state), block=False)
queue_size[0] += 1
logger.info(
"PROGRESS: pass %i, dispatched chunk #%i = documents up to #%i/%i, "
"outstanding queue size %i",
pass_, chunk_no, chunk_no * self.chunksize + len(chunk), lencorpus, queue_size[0]
)
break
except queue.Full:
# in case the input job queue is full, keep clearing the
# result queue, to make sure we don't deadlock
process_result_queue()
process_result_queue()
# endfor single corpus pass
# wait for all outstanding jobs to finish
while queue_size[0] > 0:
process_result_queue(force=True)
if reallen != lencorpus:
raise RuntimeError("input corpus size changed during training (don't use generators as input)")
# endfor entire update
pool.terminate()
def worker_e_step(input_queue, result_queue, worker_lda):
"""Perform E-step for each job.
Parameters
----------
input_queue : queue of (int, list of (int, float), :class:`~gensim.models.lda_worker.Worker`)
Each element is a job characterized by its ID, the corpus chunk to be processed in BOW format and the worker
responsible for processing it.
result_queue : queue of :class:`~gensim.models.ldamodel.LdaState`
After the worker finished the job, the state of the resulting (trained) worker model is appended to this queue.
worker_lda : :class:`~gensim.models.ldamulticore.LdaMulticore`
LDA instance which performed e step
"""
logger.debug("worker process entering E-step loop")
while True:
logger.debug("getting a new job")
chunk_no, chunk, w_state = input_queue.get()
logger.debug("processing chunk #%i of %i documents", chunk_no, len(chunk))
worker_lda.state = w_state
worker_lda.sync_state()
worker_lda.state.reset()
worker_lda.do_estep(chunk) # TODO: auto-tune alpha?
del chunk
logger.debug("processed chunk, queuing the result")
result_queue.put(worker_lda.state)
worker_lda.state = None
logger.debug("result put")
| LdaMulticore |
python | huggingface__transformers | tests/models/dinov2/test_modeling_dinov2.py | {
"start": 7486,
"end": 10819
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as Dinov2 does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
test_torch_exportable = True
all_model_classes = (
(
Dinov2Model,
Dinov2ForImageClassification,
Dinov2Backbone,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{"image-feature-extraction": Dinov2Model, "image-classification": Dinov2ForImageClassification}
if is_torch_available()
else {}
)
test_resize_embeddings = False
def setUp(self):
self.model_tester = Dinov2ModelTester(self)
self.config_tester = ConfigTester(self, config_class=Dinov2Config, has_text_modality=False, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(reason="Dinov2 does not use inputs_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
def test_model_get_set_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_backbone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*config_and_inputs)
def test_for_image_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
@unittest.skip(reason="Dinov2 does not support feedforward chunking yet")
def test_feed_forward_chunking(self):
pass
@slow
def test_model_from_pretrained(self):
model_name = "facebook/dinov2-base"
model = Dinov2Model.from_pretrained(model_name)
self.assertIsNotNone(model)
# We will verify our results on an image of cute cats
def prepare_img():
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
return image
@require_torch
@require_vision
| Dinov2ModelTest |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/fail_defaults.py | {
"start": 40,
"end": 813
} | class ____(BaseModel):
# Required
undefined_default_no_args: int = Field()
undefined_default: int = Field(description='my desc')
positional_ellipsis_default: int = Field(...)
named_ellipsis_default: int = Field(default=...)
# Not required
positional_default: int = Field(1)
named_default: int = Field(default=2)
named_default_factory: int = Field(default_factory=lambda: 3)
Model()
# MYPY: error: Missing named argument "undefined_default_no_args" for "Model" [call-arg]
# MYPY: error: Missing named argument "undefined_default" for "Model" [call-arg]
# MYPY: error: Missing named argument "positional_ellipsis_default" for "Model" [call-arg]
# MYPY: error: Missing named argument "named_ellipsis_default" for "Model" [call-arg]
| Model |
python | django__django | tests/fixtures_regress/models.py | {
"start": 1981,
"end": 2091
} | class ____(models.Manager):
def get_by_natural_key(self, key):
return self.get(name=key)
| TestManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 2506,
"end": 4445
} | class ____(RecordTransformation):
"""
Implements a custom transformation which adds the legacy field equivalent of v2 fields for streams which contain Deals and Contacts entities.
This custom implmentation was developed in lieu of the AddFields component due to the dynamic-nature of the record properties for the HubSpot source. Each
For example:
hs_v2_date_exited_{stage_id} -> hs_date_exited_{stage_id} where {stage_id} is a user-generated value
"""
field_mapping: Mapping[str, str]
def transform(
self,
record_or_schema: Dict[str, Any],
config: Optional[Config] = None,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
) -> None:
"""
Transform a record in place by adding fields directly to the record by manipulating the injected fields into a legacy field to avoid breaking syncs.
:param record_or_schema: The input record or schema to be transformed.
"""
is_record = record_or_schema.get("properties") is not None
for field, value in list(record_or_schema.get("properties", record_or_schema).items()):
for legacy_field, new_field in self.field_mapping.items():
if new_field in field:
transformed_field = field.replace(new_field, legacy_field)
if legacy_field == "hs_lifecyclestage_" and not transformed_field.endswith("_date"):
transformed_field += "_date"
if is_record:
if record_or_schema["properties"].get(transformed_field) is None:
record_or_schema["properties"][transformed_field] = value
else:
if record_or_schema.get(transformed_field) is None:
record_or_schema[transformed_field] = value
| NewtoLegacyFieldTransformation |
python | gevent__gevent | src/gevent/tests/test__close_backend_fd.py | {
"start": 523,
"end": 3865
} | class ____(unittest.TestCase):
# NOTE that we extend unittest.TestCase, not greentest.TestCase
# Extending the later causes the wrong hub to get used.
BACKENDS_THAT_SUCCEED_WHEN_FD_CLOSED = (
'kqueue',
'epoll',
'linux_aio',
'linux_iouring',
)
BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME = (
# This fails on the Fedora Rawhide 33 image. It's not clear
# why; needs investigated.
'linux_iouring',
) if not sysinfo.libev_supports_linux_iouring() else (
# Even on systems that ought to support it, according to the
# version number, it often fails to actually work. See the
# manylinux_2_28_x86_64 image as-of 2024-10-03; it seems that
# 6.8.0-1014-azure, as used in the Ubuntu 22.04 Github Actions
# runner works fine, though. So it's not clear what we can do
# other than skip it. It's possible this has to do with
# running the manylinux images in docker? " Docker also
# consequently disabled io_uring from their default seccomp
# profile."
)
BACKENDS_TO_SKIP = (
'linux_iouring',
)
BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME += (
# This can be compiled on any (?) version of
# linux, but there's a runtime check that you're
# running at least kernel 4.19, so we can fail to create
# the hub. When we updated to libev 4.31 from 4.25, Travis Ci
# was still on kernel 1.15 (Ubuntu 16.04).
'linux_aio',
) if not sysinfo.libev_supports_linux_aio() else (
)
def _check_backend(self, backend):
hub = Hub(backend, default=False)
try:
self.assertEqual(hub.loop.backend, backend)
gevent.sleep(0.001)
fileno = hub.loop.fileno()
if fileno is None:
return # nothing to close, test implicitly passes.
os.close(fileno)
if backend in self.BACKENDS_THAT_SUCCEED_WHEN_FD_CLOSED:
gevent.sleep(0.001)
else:
with self.assertRaisesRegex(SystemError, "(libev)"):
gevent.sleep(0.001)
hub.destroy()
self.assertIn('destroyed', repr(hub))
finally:
if hub.loop is not None:
hub.destroy()
@classmethod
def _make_test(cls, count, backend): # pylint:disable=no-self-argument
if backend in cls.BACKENDS_TO_SKIP:
def test(self):
self.skipTest('Expecting %s to fail' % (backend, ))
elif backend in cls.BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME:
def test(self):
with self.assertRaisesRegex(SystemError, 'ev_loop_new'):
Hub(backend, default=False)
else:
def test(self):
self._check_backend(backend)
test.__name__ = 'test_' + backend + '_' + str(count)
return test.__name__, test
@classmethod
def _make_tests(cls):
count = backend = None
for count in range(2):
for backend in core.supported_backends():
name, func = cls._make_test(count, backend)
setattr(cls, name, func)
name = func = None
Test._make_tests()
if __name__ == '__main__':
unittest.main()
| Test |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/_execution.py | {
"start": 9592,
"end": 14202
} | class ____(BaseExecutionPolicy):
"""Run the shell inside a dedicated Docker container.
Choose this policy when commands originate from untrusted users or you require
strong isolation between sessions. By default the workspace is bind-mounted only
when it refers to an existing non-temporary directory; ephemeral sessions run
without a mount to minimise host exposure. The container's network namespace is
disabled by default (`--network none`) and you can enable further hardening via
`read_only_rootfs` and `user`.
The security guarantees depend on your Docker daemon configuration. Run the agent on
a host where Docker is locked down (rootless mode, AppArmor/SELinux, etc.) and
review any additional volumes or capabilities passed through ``extra_run_args``. The
default image is `python:3.12-alpine3.19`; supply a custom image if you need
preinstalled tooling.
"""
binary: str = "docker"
image: str = "python:3.12-alpine3.19"
remove_container_on_exit: bool = True
network_enabled: bool = False
extra_run_args: Sequence[str] | None = None
memory_bytes: int | None = None
cpu_time_seconds: typing.Any | None = None
cpus: str | None = None
read_only_rootfs: bool = False
user: str | None = None
def __post_init__(self) -> None:
super().__post_init__()
if self.memory_bytes is not None and self.memory_bytes <= 0:
msg = "memory_bytes must be positive if provided."
raise ValueError(msg)
if self.cpu_time_seconds is not None:
msg = (
"DockerExecutionPolicy does not support cpu_time_seconds; configure CPU limits "
"using Docker run options such as '--cpus'."
)
raise RuntimeError(msg)
if self.cpus is not None and not self.cpus.strip():
msg = "cpus must be a non-empty string when provided."
raise ValueError(msg)
if self.user is not None and not self.user.strip():
msg = "user must be a non-empty string when provided."
raise ValueError(msg)
self.extra_run_args = tuple(self.extra_run_args or ())
def spawn(
self,
*,
workspace: Path,
env: Mapping[str, str],
command: Sequence[str],
) -> subprocess.Popen[str]:
full_command = self._build_command(workspace, env, command)
host_env = os.environ.copy()
return _launch_subprocess(
full_command,
env=host_env,
cwd=workspace,
preexec_fn=None,
start_new_session=False,
)
def _build_command(
self,
workspace: Path,
env: Mapping[str, str],
command: Sequence[str],
) -> list[str]:
binary = self._resolve_binary()
full_command: list[str] = [binary, "run", "-i"]
if self.remove_container_on_exit:
full_command.append("--rm")
if not self.network_enabled:
full_command.extend(["--network", "none"])
if self.memory_bytes is not None:
full_command.extend(["--memory", str(self.memory_bytes)])
if self._should_mount_workspace(workspace):
host_path = str(workspace)
full_command.extend(["-v", f"{host_path}:{host_path}"])
full_command.extend(["-w", host_path])
else:
full_command.extend(["-w", "/"])
if self.read_only_rootfs:
full_command.append("--read-only")
for key, value in env.items():
full_command.extend(["-e", f"{key}={value}"])
if self.cpus is not None:
full_command.extend(["--cpus", self.cpus])
if self.user is not None:
full_command.extend(["--user", self.user])
if self.extra_run_args:
full_command.extend(self.extra_run_args)
full_command.append(self.image)
full_command.extend(command)
return full_command
@staticmethod
def _should_mount_workspace(workspace: Path) -> bool:
return not workspace.name.startswith(SHELL_TEMP_PREFIX)
def _resolve_binary(self) -> str:
path = shutil.which(self.binary)
if path is None:
msg = (
"Docker execution policy requires the '%s' CLI to be installed"
" and available on PATH."
)
raise RuntimeError(msg % self.binary)
return path
__all__ = [
"BaseExecutionPolicy",
"CodexSandboxExecutionPolicy",
"DockerExecutionPolicy",
"HostExecutionPolicy",
]
| DockerExecutionPolicy |
python | scipy__scipy | scipy/stats/_multicomp.py | {
"start": 579,
"end": 16917
} | class ____:
"""Result object returned by `scipy.stats.dunnett`.
Attributes
----------
statistic : float ndarray
The computed statistic of the test for each comparison. The element
at index ``i`` is the statistic for the comparison between
groups ``i`` and the control.
pvalue : float ndarray
The computed p-value of the test for each comparison. The element
at index ``i`` is the p-value for the comparison between
group ``i`` and the control.
"""
statistic: np.ndarray
pvalue: np.ndarray
_alternative: Literal['two-sided', 'less', 'greater'] = field(repr=False)
_rho: np.ndarray = field(repr=False)
_df: int = field(repr=False)
_std: float = field(repr=False)
_mean_samples: np.ndarray = field(repr=False)
_mean_control: np.ndarray = field(repr=False)
_n_samples: np.ndarray = field(repr=False)
_n_control: int = field(repr=False)
_rng: SeedType = field(repr=False)
_ci: ConfidenceInterval | None = field(default=None, repr=False)
_ci_cl: DecimalNumber | None = field(default=None, repr=False)
def __str__(self):
# Note: `__str__` prints the confidence intervals from the most
# recent call to `confidence_interval`. If it has not been called,
# it will be called with the default CL of .95.
if self._ci is None:
self.confidence_interval(confidence_level=.95)
s = (
"Dunnett's test"
f" ({self._ci_cl*100:.1f}% Confidence Interval)\n"
"Comparison Statistic p-value Lower CI Upper CI\n"
)
for i in range(self.pvalue.size):
s += (f" (Sample {i} - Control) {self.statistic[i]:>10.3f}"
f"{self.pvalue[i]:>10.3f}"
f"{self._ci.low[i]:>10.3f}"
f"{self._ci.high[i]:>10.3f}\n")
return s
def _allowance(
self, confidence_level: DecimalNumber = 0.95, tol: DecimalNumber = 1e-3
) -> float:
"""Allowance.
It is the quantity to add/subtract from the observed difference
between the means of observed groups and the mean of the control
group. The result gives confidence limits.
Parameters
----------
confidence_level : float, optional
Confidence level for the computed confidence interval.
Default is .95.
tol : float, optional
A tolerance for numerical optimization: the allowance will produce
a confidence within ``10*tol*(1 - confidence_level)`` of the
specified level, or a warning will be emitted. Tight tolerances
may be impractical due to noisy evaluation of the objective.
Default is 1e-3.
Returns
-------
allowance : float
Allowance around the mean.
"""
alpha = 1 - confidence_level
def pvalue_from_stat(statistic):
statistic = np.array(statistic)
sf = _pvalue_dunnett(
rho=self._rho, df=self._df,
statistic=statistic, alternative=self._alternative,
rng=self._rng
)
return abs(sf - alpha)/alpha
# Evaluation of `pvalue_from_stat` is noisy due to the use of RQMC to
# evaluate `multivariate_t.cdf`. `minimize_scalar` is not designed
# to tolerate a noisy objective function and may fail to find the
# minimum accurately. We mitigate this possibility with the validation
# step below, but implementation of a noise-tolerant root finder or
# minimizer would be a welcome enhancement. See gh-18150.
res = minimize_scalar(pvalue_from_stat, method='brent', tol=tol)
critical_value = res.x
# validation
# tol*10 because tol=1e-3 means we tolerate a 1% change at most
if res.success is False or res.fun >= tol*10:
warnings.warn(
"Computation of the confidence interval did not converge to "
"the desired level. The confidence level corresponding with "
f"the returned interval is approximately {alpha*(1+res.fun)}.",
stacklevel=3
)
# From [1] p. 1101 between (1) and (3)
allowance = critical_value*self._std*np.sqrt(
1/self._n_samples + 1/self._n_control
)
return abs(allowance)
def confidence_interval(
self, confidence_level: DecimalNumber = 0.95
) -> ConfidenceInterval:
"""Compute the confidence interval for the specified confidence level.
Parameters
----------
confidence_level : float, optional
Confidence level for the computed confidence interval.
Default is .95.
Returns
-------
ci : ``ConfidenceInterval`` object
The object has attributes ``low`` and ``high`` that hold the
lower and upper bounds of the confidence intervals for each
comparison. The high and low values are accessible for each
comparison at index ``i`` for each group ``i``.
"""
# check to see if the supplied confidence level matches that of the
# previously computed CI.
if (self._ci is not None) and (confidence_level == self._ci_cl):
return self._ci
if not (0 < confidence_level < 1):
raise ValueError("Confidence level must be between 0 and 1.")
allowance = self._allowance(confidence_level=confidence_level)
diff_means = self._mean_samples - self._mean_control
low = diff_means-allowance
high = diff_means+allowance
if self._alternative == 'greater':
high = [np.inf] * len(diff_means)
elif self._alternative == 'less':
low = [-np.inf] * len(diff_means)
self._ci_cl = confidence_level
self._ci = ConfidenceInterval(
low=low,
high=high
)
return self._ci
@xp_capabilities(np_only=True)
@_transition_to_rng('random_state', replace_doc=False)
def dunnett(
*samples: "npt.ArrayLike", # noqa: D417
control: "npt.ArrayLike",
alternative: Literal['two-sided', 'less', 'greater'] = "two-sided",
rng: SeedType = None
) -> DunnettResult:
"""Dunnett's test: multiple comparisons of means against a control group.
This is an implementation of Dunnett's original, single-step test as
described in [1]_.
Parameters
----------
sample1, sample2, ... : 1D array_like
The sample measurements for each experimental group.
control : 1D array_like
The sample measurements for the control group.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The null hypothesis is that the means of the distributions underlying
the samples and control are equal. The following alternative
hypotheses are available (default is 'two-sided'):
* 'two-sided': the means of the distributions underlying the samples
and control are unequal.
* 'less': the means of the distributions underlying the samples
are less than the mean of the distribution underlying the control.
* 'greater': the means of the distributions underlying the
samples are greater than the mean of the distribution underlying
the control.
rng : `numpy.random.Generator`, optional
Pseudorandom number generator state. When `rng` is None, a new
`numpy.random.Generator` is created using entropy from the
operating system. Types other than `numpy.random.Generator` are
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
.. versionchanged:: 1.15.0
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
transition from use of `numpy.random.RandomState` to
`numpy.random.Generator`, this keyword was changed from `random_state` to
`rng`. For an interim period, both keywords will continue to work, although
only one may be specified at a time. After the interim period, function
calls using the `random_state` keyword will emit warnings. Following a
deprecation period, the `random_state` keyword will be removed.
Returns
-------
res : `~scipy.stats._result_classes.DunnettResult`
An object containing attributes:
statistic : float ndarray
The computed statistic of the test for each comparison. The element
at index ``i`` is the statistic for the comparison between
groups ``i`` and the control.
pvalue : float ndarray
The computed p-value of the test for each comparison. The element
at index ``i`` is the p-value for the comparison between
group ``i`` and the control.
And the following method:
confidence_interval(confidence_level=0.95) :
Compute the difference in means of the groups
with the control +- the allowance.
See Also
--------
tukey_hsd : performs pairwise comparison of means.
:ref:`hypothesis_dunnett` : Extended example
Notes
-----
Like the independent-sample t-test, Dunnett's test [1]_ is used to make
inferences about the means of distributions from which samples were drawn.
However, when multiple t-tests are performed at a fixed significance level,
the "family-wise error rate" - the probability of incorrectly rejecting the
null hypothesis in at least one test - will exceed the significance level.
Dunnett's test is designed to perform multiple comparisons while
controlling the family-wise error rate.
Dunnett's test compares the means of multiple experimental groups
against a single control group. Tukey's Honestly Significant Difference Test
is another multiple-comparison test that controls the family-wise error
rate, but `tukey_hsd` performs *all* pairwise comparisons between groups.
When pairwise comparisons between experimental groups are not needed,
Dunnett's test is preferable due to its higher power.
The use of this test relies on several assumptions.
1. The observations are independent within and among groups.
2. The observations within each group are normally distributed.
3. The distributions from which the samples are drawn have the same finite
variance.
References
----------
.. [1] Dunnett, Charles W. (1955) "A Multiple Comparison Procedure for
Comparing Several Treatments with a Control." Journal of the American
Statistical Association, 50:272, 1096-1121,
:doi:`10.1080/01621459.1955.10501294`
.. [2] Thomson, M. L., & Short, M. D. (1969). Mucociliary function in
health, chronic obstructive airway disease, and asbestosis. Journal
of applied physiology, 26(5), 535-539.
:doi:`10.1152/jappl.1969.26.5.535`
Examples
--------
We'll use data from [2]_, Table 1. The null hypothesis is that the means of
the distributions underlying the samples and control are equal.
First, we test that the means of the distributions underlying the samples
and control are unequal (``alternative='two-sided'``, the default).
>>> import numpy as np
>>> from scipy.stats import dunnett
>>> samples = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]
>>> control = [2.9, 3.0, 2.5, 2.6, 3.2]
>>> res = dunnett(*samples, control=control)
>>> res.statistic
array([ 0.90874545, -0.05007117])
>>> res.pvalue
array([0.58325114, 0.99819341])
Now, we test that the means of the distributions underlying the samples are
greater than the mean of the distribution underlying the control.
>>> res = dunnett(*samples, control=control, alternative='greater')
>>> res.statistic
array([ 0.90874545, -0.05007117])
>>> res.pvalue
array([0.30230596, 0.69115597])
For a more detailed example, see :ref:`hypothesis_dunnett`.
"""
samples_, control_, rng = _iv_dunnett(
samples=samples, control=control,
alternative=alternative, rng=rng
)
rho, df, n_group, n_samples, n_control = _params_dunnett(
samples=samples_, control=control_
)
statistic, std, mean_control, mean_samples = _statistic_dunnett(
samples_, control_, df, n_samples, n_control
)
pvalue = _pvalue_dunnett(
rho=rho, df=df, statistic=statistic, alternative=alternative, rng=rng
)
return DunnettResult(
statistic=statistic, pvalue=pvalue,
_alternative=alternative,
_rho=rho, _df=df, _std=std,
_mean_samples=mean_samples,
_mean_control=mean_control,
_n_samples=n_samples,
_n_control=n_control,
_rng=rng
)
def _iv_dunnett(
samples: Sequence["npt.ArrayLike"],
control: "npt.ArrayLike",
alternative: Literal['two-sided', 'less', 'greater'],
rng: SeedType
) -> tuple[list[np.ndarray], np.ndarray, SeedType]:
"""Input validation for Dunnett's test."""
rng = check_random_state(rng)
if alternative not in {'two-sided', 'less', 'greater'}:
raise ValueError(
"alternative must be 'less', 'greater' or 'two-sided'"
)
ndim_msg = "Control and samples groups must be 1D arrays"
n_obs_msg = "Control and samples groups must have at least 1 observation"
control = np.asarray(control)
samples_ = [np.asarray(sample) for sample in samples]
# samples checks
samples_control: list[np.ndarray] = samples_ + [control]
for sample in samples_control:
if sample.ndim > 1:
raise ValueError(ndim_msg)
if sample.size < 1:
raise ValueError(n_obs_msg)
return samples_, control, rng
def _params_dunnett(
samples: list[np.ndarray], control: np.ndarray
) -> tuple[np.ndarray, int, int, np.ndarray, int]:
"""Specific parameters for Dunnett's test.
Degree of freedom is the number of observations minus the number of groups
including the control.
"""
n_samples = np.array([sample.size for sample in samples])
# From [1] p. 1100 d.f. = (sum N)-(p+1)
n_sample = n_samples.sum()
n_control = control.size
n = n_sample + n_control
n_groups = len(samples)
df = n - n_groups - 1
# From [1] p. 1103 rho_ij = 1/sqrt((N0/Ni+1)(N0/Nj+1))
rho = n_control/n_samples + 1
rho = 1/np.sqrt(rho[:, None] * rho[None, :])
np.fill_diagonal(rho, 1)
return rho, df, n_groups, n_samples, n_control
def _statistic_dunnett(
samples: list[np.ndarray], control: np.ndarray, df: int,
n_samples: np.ndarray, n_control: int
) -> tuple[np.ndarray, float, np.ndarray, np.ndarray]:
"""Statistic of Dunnett's test.
Computation based on the original single-step test from [1].
"""
mean_control = np.mean(control)
mean_samples = np.array([np.mean(sample) for sample in samples])
all_samples = [control] + samples
all_means = np.concatenate([[mean_control], mean_samples])
# Variance estimate s^2 from [1] Eq. 1
s2 = np.sum([_var(sample, mean=mean)*sample.size
for sample, mean in zip(all_samples, all_means)]) / df
std = np.sqrt(s2)
# z score inferred from [1] unlabeled equation after Eq. 1
z = (mean_samples - mean_control) / np.sqrt(1/n_samples + 1/n_control)
return z / std, std, mean_control, mean_samples
def _pvalue_dunnett(
rho: np.ndarray, df: int, statistic: np.ndarray,
alternative: Literal['two-sided', 'less', 'greater'],
rng: SeedType = None
) -> np.ndarray:
"""pvalue from the multivariate t-distribution.
Critical values come from the multivariate student-t distribution.
"""
statistic = statistic.reshape(-1, 1)
mvt = stats.multivariate_t(shape=rho, df=df, seed=rng)
if alternative == "two-sided":
statistic = abs(statistic)
pvalue = 1 - mvt.cdf(statistic, lower_limit=-statistic)
elif alternative == "greater":
pvalue = 1 - mvt.cdf(statistic, lower_limit=-np.inf)
else:
pvalue = 1 - mvt.cdf(np.inf, lower_limit=statistic)
return np.atleast_1d(pvalue)
| DunnettResult |
python | tornadoweb__tornado | tornado/test/gen_test.py | {
"start": 8002,
"end": 17433
} | class ____(AsyncTestCase):
def setUp(self):
# Stray StopIteration exceptions can lead to tests exiting prematurely,
# so we need explicit checks here to make sure the tests run all
# the way through.
self.finished = False
super().setUp()
def tearDown(self):
super().tearDown()
assert self.finished
def test_attributes(self):
self.finished = True
def f():
yield gen.moment
coro = gen.coroutine(f)
self.assertEqual(coro.__name__, f.__name__)
self.assertEqual(coro.__module__, f.__module__)
self.assertIs(coro.__wrapped__, f) # type: ignore
def test_is_coroutine_function(self):
self.finished = True
def f():
yield gen.moment
coro = gen.coroutine(f)
self.assertFalse(gen.is_coroutine_function(f))
self.assertTrue(gen.is_coroutine_function(coro))
self.assertFalse(gen.is_coroutine_function(coro()))
@gen_test
def test_sync_gen_return(self):
@gen.coroutine
def f():
raise gen.Return(42)
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_gen_return(self):
@gen.coroutine
def f():
yield gen.moment
raise gen.Return(42)
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_sync_return(self):
@gen.coroutine
def f():
return 42
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_return(self):
@gen.coroutine
def f():
yield gen.moment
return 42
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_early_return(self):
# A yield statement exists but is not executed, which means
# this function "returns" via an exception. This exception
# doesn't happen before the exception handling is set up.
@gen.coroutine
def f():
if True:
return 42
yield gen.Task(self.io_loop.add_callback)
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_await(self):
@gen.coroutine
def f1():
yield gen.moment
raise gen.Return(42)
# This test verifies that an async function can await a
# yield-based gen.coroutine, and that a gen.coroutine
# (the test method itself) can yield an async function.
async def f2():
result = await f1()
return result
result = yield f2()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_asyncio_sleep_zero(self):
# asyncio.sleep(0) turns into a special case (equivalent to
# `yield None`)
async def f():
import asyncio
await asyncio.sleep(0)
return 42
result = yield f()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_async_await_mixed_multi_native_future(self):
@gen.coroutine
def f1():
yield gen.moment
async def f2():
await f1()
return 42
@gen.coroutine
def f3():
yield gen.moment
raise gen.Return(43)
results = yield [f2(), f3()]
self.assertEqual(results, [42, 43])
self.finished = True
@gen_test
def test_async_with_timeout(self):
async def f1():
return 42
result = yield gen.with_timeout(datetime.timedelta(hours=1), f1())
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_sync_return_no_value(self):
@gen.coroutine
def f():
return
result = yield f()
self.assertIsNone(result)
self.finished = True
@gen_test
def test_async_return_no_value(self):
@gen.coroutine
def f():
yield gen.moment
return
result = yield f()
self.assertIsNone(result)
self.finished = True
@gen_test
def test_sync_raise(self):
@gen.coroutine
def f():
1 / 0
# The exception is raised when the future is yielded
# (or equivalently when its result method is called),
# not when the function itself is called).
future = f()
with self.assertRaises(ZeroDivisionError):
yield future
self.finished = True
@gen_test
def test_async_raise(self):
@gen.coroutine
def f():
yield gen.moment
1 / 0
future = f()
with self.assertRaises(ZeroDivisionError):
yield future
self.finished = True
@gen_test
def test_replace_yieldpoint_exception(self):
# Test exception handling: a coroutine can catch one exception
# raised by a yield point and raise a different one.
@gen.coroutine
def f1():
1 / 0
@gen.coroutine
def f2():
try:
yield f1()
except ZeroDivisionError:
raise KeyError()
future = f2()
with self.assertRaises(KeyError):
yield future
self.finished = True
@gen_test
def test_swallow_yieldpoint_exception(self):
# Test exception handling: a coroutine can catch an exception
# raised by a yield point and not raise a different one.
@gen.coroutine
def f1():
1 / 0
@gen.coroutine
def f2():
try:
yield f1()
except ZeroDivisionError:
raise gen.Return(42)
result = yield f2()
self.assertEqual(result, 42)
self.finished = True
@gen_test
def test_moment(self):
calls = []
@gen.coroutine
def f(name, yieldable):
for i in range(5):
calls.append(name)
yield yieldable
# First, confirm the behavior without moment: each coroutine
# monopolizes the event loop until it finishes.
immediate = Future() # type: Future[None]
immediate.set_result(None)
yield [f("a", immediate), f("b", immediate)]
self.assertEqual("".join(calls), "aaaaabbbbb")
# With moment, they take turns.
calls = []
yield [f("a", gen.moment), f("b", gen.moment)]
self.assertEqual("".join(calls), "ababababab")
self.finished = True
calls = []
yield [f("a", gen.moment), f("b", immediate)]
self.assertEqual("".join(calls), "abbbbbaaaa")
@gen_test
def test_sleep(self):
yield gen.sleep(0.01)
self.finished = True
@gen_test
def test_py3_leak_exception_context(self):
class LeakedException(Exception):
pass
@gen.coroutine
def inner(iteration):
raise LeakedException(iteration)
try:
yield inner(1)
except LeakedException as e:
self.assertEqual(str(e), "1")
self.assertIsNone(e.__context__)
try:
yield inner(2)
except LeakedException as e:
self.assertEqual(str(e), "2")
self.assertIsNone(e.__context__)
self.finished = True
@skipNotCPython
def test_coroutine_refcounting(self):
# On CPython, tasks and their arguments should be released immediately
# without waiting for garbage collection.
@gen.coroutine
def inner():
class Foo:
pass
local_var = Foo()
self.local_ref = weakref.ref(local_var)
def dummy():
pass
yield gen.coroutine(dummy)()
raise ValueError("Some error")
@gen.coroutine
def inner2():
try:
yield inner()
except ValueError:
pass
self.io_loop.run_sync(inner2, timeout=3)
self.assertIsNone(self.local_ref())
self.finished = True
def test_asyncio_future_debug_info(self):
self.finished = True
# Enable debug mode
asyncio_loop = asyncio.get_event_loop()
self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug())
asyncio_loop.set_debug(True)
def f():
yield gen.moment
coro = gen.coroutine(f)()
self.assertIsInstance(coro, asyncio.Future)
# We expect the coroutine repr() to show the place where
# it was instantiated
expected = "created at %s:%d" % (__file__, f.__code__.co_firstlineno + 3)
actual = repr(coro)
self.assertIn(expected, actual)
@gen_test
def test_asyncio_gather(self):
# This demonstrates that tornado coroutines can be understood
# by asyncio (This failed prior to Tornado 5.0).
@gen.coroutine
def f():
yield gen.moment
raise gen.Return(1)
ret = yield asyncio.gather(f(), f())
self.assertEqual(ret, [1, 1])
self.finished = True
| GenCoroutineTest |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-openai/tests/test_openai.py | {
"start": 606,
"end": 19367
} | class ____:
"""
Saves the users' OpenAI API key and OpenAI API type either in
the environment variable or set to the library itself.
This allows us to run tests by setting it without plowing over
the local environment.
"""
def __init__(
self,
set_env_key_to: Optional[str] = "",
set_library_key_to: Optional[str] = None,
set_fake_key: bool = False,
set_env_type_to: Optional[str] = "",
set_library_type_to: str = "open_ai", # default value in openai package
):
self.set_env_key_to = set_env_key_to
self.set_library_key_to = set_library_key_to
self.set_fake_key = set_fake_key
self.set_env_type_to = set_env_type_to
self.set_library_type_to = set_library_type_to
def __enter__(self) -> None:
self.api_env_variable_was = os.environ.get("OPENAI_API_KEY", "")
self.api_env_type_was = os.environ.get("OPENAI_API_TYPE", "")
self.openai_api_key_was = openai.api_key
self.openai_api_type_was = openai.api_type
os.environ["OPENAI_API_KEY"] = str(self.set_env_key_to)
os.environ["OPENAI_API_TYPE"] = str(self.set_env_type_to)
if self.set_fake_key:
os.environ["OPENAI_API_KEY"] = "sk-" + "a" * 48
# No matter what, set the environment variable back to what it was
def __exit__(self, *exc: object) -> None:
os.environ["OPENAI_API_KEY"] = str(self.api_env_variable_was)
os.environ["OPENAI_API_TYPE"] = str(self.api_env_type_was)
openai.api_key = self.openai_api_key_was
openai.api_type = self.openai_api_type_was
def mock_completion(*args: Any, **kwargs: Any) -> dict:
# Example taken from https://platform.openai.com/docs/api-reference/completions/create
return {
"id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
"object": "text_completion",
"created": 1589478378,
"model": "text-davinci-003",
"choices": [
{
"text": "\n\nThis is indeed a test",
"index": 0,
"logprobs": None,
"finish_reason": "length",
}
],
"usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},
}
def mock_completion_v1(*args: Any, **kwargs: Any) -> Completion:
return Completion(
id="cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
object="text_completion",
created=1589478378,
model="text-davinci-003",
choices=[
CompletionChoice(
text="\n\nThis is indeed a test",
index=0,
logprobs=None,
finish_reason="length",
)
],
usage=CompletionUsage(prompt_tokens=5, completion_tokens=7, total_tokens=12),
)
async def mock_async_completion(*args: Any, **kwargs: Any) -> dict:
return mock_completion(*args, **kwargs)
async def mock_async_completion_v1(*args: Any, **kwargs: Any) -> Completion:
return mock_completion_v1(*args, **kwargs)
def mock_chat_completion(*args: Any, **kwargs: Any) -> dict:
# Example taken from https://platform.openai.com/docs/api-reference/chat/create
return {
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "gpt-3.5-turbo-0301",
"usage": {"prompt_tokens": 13, "completion_tokens": 7, "total_tokens": 20},
"choices": [
{
"message": {"role": "assistant", "content": "\n\nThis is a test!"},
"finish_reason": "stop",
"index": 0,
}
],
}
def mock_chat_completion_v1(*args: Any, **kwargs: Any) -> ChatCompletion:
return ChatCompletion(
id="chatcmpl-abc123",
object="chat.completion",
created=1677858242,
model="gpt-3.5-turbo-0301",
usage=CompletionUsage(prompt_tokens=13, completion_tokens=7, total_tokens=20),
choices=[
Choice(
message=ChatCompletionMessage(
role="assistant", content="\n\nThis is a test!"
),
finish_reason="stop",
index=0,
)
],
)
def mock_completion_stream(*args: Any, **kwargs: Any) -> Generator[dict, None, None]:
# Example taken from https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb
responses = [
{
"choices": [
{
"text": "1",
}
],
},
{
"choices": [
{
"text": "2",
}
],
},
]
yield from responses
def mock_completion_stream_v1(
*args: Any, **kwargs: Any
) -> Generator[Completion, None, None]:
responses = [
Completion(
id="cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
object="text_completion",
created=1589478378,
model="text-davinci-003",
choices=[CompletionChoice(text="1", finish_reason="stop", index=0)],
),
Completion(
id="cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
object="text_completion",
created=1589478378,
model="text-davinci-003",
choices=[CompletionChoice(text="2", finish_reason="stop", index=0)],
),
]
yield from responses
async def mock_async_completion_stream(
*args: Any, **kwargs: Any
) -> AsyncGenerator[dict, None]:
async def gen() -> AsyncGenerator[dict, None]:
for response in mock_completion_stream(*args, **kwargs):
yield response
return gen()
async def mock_async_completion_stream_v1(
*args: Any, **kwargs: Any
) -> AsyncGenerator[Completion, None]:
async def gen() -> AsyncGenerator[Completion, None]:
for response in mock_completion_stream_v1(*args, **kwargs):
yield response
return gen()
def mock_chat_completion_stream(
*args: Any, **kwargs: Any
) -> Generator[dict, None, None]:
# Example taken from: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb
responses = [
{
"choices": [
{"delta": {"role": "assistant"}, "finish_reason": None, "index": 0}
],
"created": 1677825464,
"id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion.chunk",
},
{
"choices": [
{"delta": {"content": "\n\n"}, "finish_reason": None, "index": 0}
],
"created": 1677825464,
"id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion.chunk",
},
{
"choices": [{"delta": {"content": "2"}, "finish_reason": None, "index": 0}],
"created": 1677825464,
"id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion.chunk",
},
{
"choices": [{"delta": {}, "finish_reason": "stop", "index": 0}],
"created": 1677825464,
"id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion.chunk",
},
]
yield from responses
def mock_chat_completion_stream_v1(
*args: Any, **kwargs: Any
) -> Generator[ChatCompletionChunk, None, None]:
responses = [
ChatCompletionChunk(
id="chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
object="chat.completion.chunk",
created=1677825464,
model="gpt-3.5-turbo-0301",
choices=[
ChunkChoice(
delta=ChoiceDelta(role="assistant"), finish_reason=None, index=0
)
],
),
ChatCompletionChunk(
id="chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
object="chat.completion.chunk",
created=1677825464,
model="gpt-3.5-turbo-0301",
choices=[
ChunkChoice(
delta=ChoiceDelta(content="\n\n"), finish_reason=None, index=0
)
],
),
ChatCompletionChunk(
id="chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
object="chat.completion.chunk",
created=1677825464,
model="gpt-3.5-turbo-0301",
choices=[
ChunkChoice(delta=ChoiceDelta(content="2"), finish_reason=None, index=0)
],
),
ChatCompletionChunk(
id="chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
object="chat.completion.chunk",
created=1677825464,
model="gpt-3.5-turbo-0301",
choices=[ChunkChoice(delta=ChoiceDelta(), finish_reason="stop", index=0)],
),
]
yield from responses
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_completion_model_basic(MockSyncOpenAI: MagicMock) -> None:
with CachedOpenAIApiKeys(set_fake_key=True):
mock_instance = MockSyncOpenAI.return_value
mock_instance.completions.create.return_value = mock_completion_v1()
llm = OpenAI(model="text-davinci-003")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response = llm.complete(prompt)
assert response.text == "\n\nThis is indeed a test"
assert response.additional_kwargs["total_tokens"] == 12
chat_response = llm.chat([message])
assert chat_response.message.content == "\n\nThis is indeed a test"
assert chat_response.message.additional_kwargs["total_tokens"] == 12
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_chat_model_basic(MockSyncOpenAI: MagicMock) -> None:
with CachedOpenAIApiKeys(set_fake_key=True):
mock_instance = MockSyncOpenAI.return_value
mock_instance.chat.completions.create.return_value = mock_chat_completion_v1()
llm = OpenAI(model="gpt-3.5-turbo")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response = llm.complete(prompt)
assert response.text == "\n\nThis is a test!"
chat_response = llm.chat([message])
assert chat_response.message.content == "\n\nThis is a test!"
assert chat_response.additional_kwargs["total_tokens"] == 20
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_completion_model_streaming(MockSyncOpenAI: MagicMock) -> None:
with CachedOpenAIApiKeys(set_fake_key=True):
mock_instance = MockSyncOpenAI.return_value
mock_instance.completions.create.return_value = mock_completion_stream_v1()
llm = OpenAI(model="text-davinci-003")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response_gen = llm.stream_complete(prompt)
responses = list(response_gen)
assert responses[-1].text == "12"
mock_instance.completions.create.return_value = mock_completion_stream_v1()
chat_response_gen = llm.stream_chat([message])
chat_responses = list(chat_response_gen)
assert chat_responses[-1].message.content == "12"
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_chat_model_streaming(MockSyncOpenAI: MagicMock) -> None:
with CachedOpenAIApiKeys(set_fake_key=True):
mock_instance = MockSyncOpenAI.return_value
mock_instance.chat.completions.create.return_value = (
mock_chat_completion_stream_v1()
)
llm = OpenAI(model="gpt-3.5-turbo")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response_gen = llm.stream_complete(prompt)
responses = list(response_gen)
assert responses[-1].text == "\n\n2"
mock_instance.chat.completions.create.return_value = (
mock_chat_completion_stream_v1()
)
chat_response_gen = llm.stream_chat([message])
chat_responses = list(chat_response_gen)
assert chat_responses[-1].message.blocks[-1].text == "\n\n2"
assert chat_responses[-1].message.role == "assistant"
@pytest.mark.asyncio()
@patch("llama_index.llms.openai.base.AsyncOpenAI")
async def test_completion_model_async(MockAsyncOpenAI: MagicMock) -> None:
mock_instance = MockAsyncOpenAI.return_value
create_fn = AsyncMock()
create_fn.side_effect = mock_async_completion_v1
mock_instance.completions.create = create_fn
llm = OpenAI(model="text-davinci-003")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response = await llm.acomplete(prompt)
assert response.text == "\n\nThis is indeed a test"
chat_response = await llm.achat([message])
assert chat_response.message.content == "\n\nThis is indeed a test"
@pytest.mark.asyncio()
@patch("llama_index.llms.openai.base.AsyncOpenAI")
async def test_completion_model_async_streaming(MockAsyncOpenAI: MagicMock) -> None:
mock_instance = MockAsyncOpenAI.return_value
create_fn = AsyncMock()
create_fn.side_effect = mock_async_completion_stream_v1
mock_instance.completions.create = create_fn
llm = OpenAI(model="text-davinci-003")
prompt = "test prompt"
message = ChatMessage(role="user", content="test message")
response_gen = await llm.astream_complete(prompt)
responses = [item async for item in response_gen]
assert responses[-1].text == "12"
chat_response_gen = await llm.astream_chat([message])
chat_responses = [item async for item in chat_response_gen]
assert chat_responses[-1].message.content == "12"
def test_validates_api_key_is_present() -> None:
with CachedOpenAIApiKeys():
os.environ["OPENAI_API_KEY"] = "sk-" + ("a" * 48)
# We can create a new LLM when the env variable is set
assert OpenAI()
os.environ["OPENAI_API_KEY"] = ""
# We can create a new LLM when the api_key is set on the
# class directly
assert OpenAI(api_key="sk-" + ("a" * 48))
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_completion_model_with_retry(MockSyncOpenAI: MagicMock) -> None:
mock_instance = MockSyncOpenAI.return_value
mock_instance.completions.create.side_effect = openai.APITimeoutError(None)
llm = OpenAI(model="text-davinci-003", max_retries=3)
prompt = "test prompt"
with pytest.raises(openai.APITimeoutError) as exc:
llm.complete(prompt)
assert exc.value.message == "Request timed out."
# The actual retry count is max_retries - 1
# see https://github.com/jd/tenacity/issues/459
assert mock_instance.completions.create.call_count == 3
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_ensure_chat_message_is_serializable(MockSyncOpenAI: MagicMock) -> None:
with CachedOpenAIApiKeys(set_fake_key=True):
mock_instance = MockSyncOpenAI.return_value
mock_instance.chat.completions.create.return_value = mock_chat_completion_v1()
llm = OpenAI(model="gpt-3.5-turbo")
message = ChatMessage(role="user", content="test message")
response = llm.chat([message])
response.message.additional_kwargs["test"] = ChatCompletionChunk(
id="chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
object="chat.completion.chunk",
created=1677825464,
model="gpt-3.5-turbo-0301",
choices=[
ChunkChoice(
delta=ChoiceDelta(role="assistant", content="test"),
finish_reason=None,
index=0,
)
],
)
data = response.message.dict()
assert isinstance(data, dict)
assert isinstance(data["additional_kwargs"], dict)
assert isinstance(data["additional_kwargs"]["test"]["choices"], list)
assert (
data["additional_kwargs"]["test"]["choices"][0]["delta"]["content"]
== "test"
)
@patch("llama_index.llms.openai.base.SyncOpenAI")
def test_structured_chat_simple(MockSyncOpenAI: MagicMock):
"""Simple test for structured output using as_structured_llm."""
from pydantic import BaseModel, Field
from llama_index.core.base.llms.types import ChatMessage
class Person(BaseModel):
name: str = Field(description="The person's name")
age: int = Field(description="The person's age")
# Mock OpenAI response structure
mock_choice = MagicMock()
mock_choice.message.role = "assistant"
mock_choice.message.content = '{"name": "Alice", "age": 25}'
mock_response = MagicMock()
mock_response.choices = [mock_choice]
# Mock OpenAI client
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_response
MockSyncOpenAI.return_value = mock_client
llm = OpenAI(model="gpt-4o", api_key="test-key")
structured_llm = llm.as_structured_llm(Person)
messages = [
ChatMessage(role="user", content="Create a person named Alice who is 25")
]
result = structured_llm.chat(messages)
# Verify the result has the expected structure
assert isinstance(result.raw, Person)
@pytest.mark.asyncio()
@patch("llama_index.llms.openai.base.AsyncOpenAI")
async def test_structured_chat_simple_async(MockAsyncOpenAI: MagicMock):
"""Simple async test for structured output using as_structured_llm."""
from pydantic import BaseModel, Field
from llama_index.core.base.llms.types import ChatMessage
class Person(BaseModel):
name: str = Field(description="The person's name")
age: int = Field(description="The person's age")
# Mock OpenAI response structure
mock_choice = MagicMock()
mock_choice.message.role = "assistant"
mock_choice.message.content = '{"name": "Bob", "age": 30}'
mock_response = MagicMock()
mock_response.choices = [mock_choice]
# Mock async OpenAI client
mock_client = MagicMock()
create_fn = AsyncMock()
create_fn.return_value = mock_response
mock_client.chat.completions.create = create_fn
MockAsyncOpenAI.return_value = mock_client
# Instantiate OpenAI class
llm = OpenAI(model="gpt-4o", api_key="test-key")
structured_llm = llm.as_structured_llm(Person)
messages = [ChatMessage(role="user", content="Create a person named Bob who is 30")]
result = await structured_llm.achat(messages)
# Verify the result has the expected structure
assert isinstance(result.raw, Person)
| CachedOpenAIApiKeys |
python | pallets__werkzeug | src/werkzeug/serving.py | {
"start": 31259,
"end": 39826
} | class ____(ForkingMixIn, BaseWSGIServer):
"""A WSGI server that handles concurrent requests in separate forked
processes.
Use :func:`make_server` to create a server instance.
"""
multiprocess = True
def __init__(
self,
host: str,
port: int,
app: WSGIApplication,
processes: int = 40,
handler: type[WSGIRequestHandler] | None = None,
passthrough_errors: bool = False,
ssl_context: _TSSLContextArg | None = None,
fd: int | None = None,
) -> None:
if not can_fork:
raise ValueError("Your platform does not support forking.")
super().__init__(host, port, app, handler, passthrough_errors, ssl_context, fd)
self.max_children = processes
def make_server(
host: str,
port: int,
app: WSGIApplication,
threaded: bool = False,
processes: int = 1,
request_handler: type[WSGIRequestHandler] | None = None,
passthrough_errors: bool = False,
ssl_context: _TSSLContextArg | None = None,
fd: int | None = None,
) -> BaseWSGIServer:
"""Create an appropriate WSGI server instance based on the value of
``threaded`` and ``processes``.
This is called from :func:`run_simple`, but can be used separately
to have access to the server object, such as to run it in a separate
thread.
See :func:`run_simple` for parameter docs.
"""
if threaded and processes > 1:
raise ValueError("Cannot have a multi-thread and multi-process server.")
if threaded:
return ThreadedWSGIServer(
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
)
if processes > 1:
return ForkingWSGIServer(
host,
port,
app,
processes,
request_handler,
passthrough_errors,
ssl_context,
fd=fd,
)
return BaseWSGIServer(
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
)
def is_running_from_reloader() -> bool:
"""Check if the server is running as a subprocess within the
Werkzeug reloader.
.. versionadded:: 0.10
"""
return os.environ.get("WERKZEUG_RUN_MAIN") == "true"
def run_simple(
hostname: str,
port: int,
application: WSGIApplication,
use_reloader: bool = False,
use_debugger: bool = False,
use_evalex: bool = True,
extra_files: t.Iterable[str] | None = None,
exclude_patterns: t.Iterable[str] | None = None,
reloader_interval: int = 1,
reloader_type: str = "auto",
threaded: bool = False,
processes: int = 1,
request_handler: type[WSGIRequestHandler] | None = None,
static_files: dict[str, str | tuple[str, str]] | None = None,
passthrough_errors: bool = False,
ssl_context: _TSSLContextArg | None = None,
) -> None:
"""Start a development server for a WSGI application. Various
optional features can be enabled.
.. warning::
Do not use the development server when deploying to production.
It is intended for use only during local development. It is not
designed to be particularly efficient, stable, or secure.
:param hostname: The host to bind to, for example ``'localhost'``.
Can be a domain, IPv4 or IPv6 address, or file path starting
with ``unix://`` for a Unix socket.
:param port: The port to bind to, for example ``8080``. Using ``0``
tells the OS to pick a random free port.
:param application: The WSGI application to run.
:param use_reloader: Use a reloader process to restart the server
process when files are changed.
:param use_debugger: Use Werkzeug's debugger, which will show
formatted tracebacks on unhandled exceptions.
:param use_evalex: Make the debugger interactive. A Python terminal
can be opened for any frame in the traceback. Some protection is
provided by requiring a PIN, but this should never be enabled
on a publicly visible server.
:param extra_files: The reloader will watch these files for changes
in addition to Python modules. For example, watch a
configuration file.
:param exclude_patterns: The reloader will ignore changes to any
files matching these :mod:`fnmatch` patterns. For example,
ignore cache files.
:param reloader_interval: How often the reloader tries to check for
changes.
:param reloader_type: The reloader to use. The ``'stat'`` reloader
is built in, but may require significant CPU to watch files. The
``'watchdog'`` reloader is much more efficient but requires
installing the ``watchdog`` package first.
:param threaded: Handle concurrent requests using threads. Cannot be
used with ``processes``.
:param processes: Handle concurrent requests using up to this number
of processes. Cannot be used with ``threaded``.
:param request_handler: Use a different
:class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass to
handle requests.
:param static_files: A dict mapping URL prefixes to directories to
serve static files from using
:class:`~werkzeug.middleware.SharedDataMiddleware`.
:param passthrough_errors: Don't catch unhandled exceptions at the
server level, let the server crash instead. If ``use_debugger``
is enabled, the debugger will still catch such errors.
:param ssl_context: Configure TLS to serve over HTTPS. Can be an
:class:`ssl.SSLContext` object, a ``(cert_file, key_file)``
tuple to create a typical context, or the string ``'adhoc'`` to
generate a temporary self-signed certificate.
.. versionchanged:: 2.1
Instructions are shown for dealing with an "address already in
use" error.
.. versionchanged:: 2.1
Running on ``0.0.0.0`` or ``::`` shows the loopback IP in
addition to a real IP.
.. versionchanged:: 2.1
The command-line interface was removed.
.. versionchanged:: 2.0
Running on ``0.0.0.0`` or ``::`` shows a real IP address that
was bound as well as a warning not to run the development server
in production.
.. versionchanged:: 2.0
The ``exclude_patterns`` parameter was added.
.. versionchanged:: 0.15
Bind to a Unix socket by passing a ``hostname`` that starts with
``unix://``.
.. versionchanged:: 0.10
Improved the reloader and added support for changing the backend
through the ``reloader_type`` parameter.
.. versionchanged:: 0.9
A command-line interface was added.
.. versionchanged:: 0.8
``ssl_context`` can be a tuple of paths to the certificate and
private key files.
.. versionchanged:: 0.6
The ``ssl_context`` parameter was added.
.. versionchanged:: 0.5
The ``static_files`` and ``passthrough_errors`` parameters were
added.
"""
if not isinstance(port, int):
raise TypeError("port must be an integer")
if static_files:
from .middleware.shared_data import SharedDataMiddleware
application = SharedDataMiddleware(application, static_files)
if use_debugger:
from .debug import DebuggedApplication
application = DebuggedApplication(application, evalex=use_evalex)
# Allow the specified hostname to use the debugger, in addition to
# localhost domains.
application.trusted_hosts.append(hostname)
if not is_running_from_reloader():
fd = None
else:
fd = int(os.environ["WERKZEUG_SERVER_FD"])
srv = make_server(
hostname,
port,
application,
threaded,
processes,
request_handler,
passthrough_errors,
ssl_context,
fd=fd,
)
srv.socket.set_inheritable(True)
os.environ["WERKZEUG_SERVER_FD"] = str(srv.fileno())
if not is_running_from_reloader():
srv.log_startup()
_log("info", _ansi_style("Press CTRL+C to quit", "yellow"))
if use_reloader:
from ._reloader import run_with_reloader
try:
run_with_reloader(
srv.serve_forever,
extra_files=extra_files,
exclude_patterns=exclude_patterns,
interval=reloader_interval,
reloader_type=reloader_type,
)
finally:
srv.server_close()
else:
srv.serve_forever()
| ForkingWSGIServer |
python | RaRe-Technologies__gensim | gensim/test/test_fasttext.py | {
"start": 74089,
"end": 75197
} | class ____(unittest.TestCase):
def test_add_vector(self):
wv = FastTextKeyedVectors(vector_size=2, min_n=3, max_n=6, bucket=2000000)
wv.add_vector("test_key", np.array([0, 0]))
self.assertEqual(wv.key_to_index["test_key"], 0)
self.assertEqual(wv.index_to_key[0], "test_key")
self.assertTrue(np.all(wv.vectors[0] == np.array([0, 0])))
def test_add_vectors(self):
wv = FastTextKeyedVectors(vector_size=2, min_n=3, max_n=6, bucket=2000000)
wv.add_vectors(["test_key1", "test_key2"], np.array([[0, 0], [1, 1]]))
self.assertEqual(wv.key_to_index["test_key1"], 0)
self.assertEqual(wv.index_to_key[0], "test_key1")
self.assertTrue(np.all(wv.vectors[0] == np.array([0, 0])))
self.assertEqual(wv.key_to_index["test_key2"], 1)
self.assertEqual(wv.index_to_key[1], "test_key2")
self.assertTrue(np.all(wv.vectors[1] == np.array([1, 1])))
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| FastTextKeyedVectorsTest |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 63871,
"end": 67559
} | class ____(_UnsupportedGroupCVMixin, _RepeatedSplits):
"""Repeated class-wise stratified K-Fold cross validator.
Repeats Stratified K-Fold n times with different randomization in each
repetition.
Read more in the :ref:`User Guide <repeated_k_fold>`.
.. note::
Stratification on the class label solves an engineering problem rather
than a statistical one. See :ref:`stratification` for more details.
Parameters
----------
n_splits : int, default=5
Number of folds. Must be at least 2.
n_repeats : int, default=10
Number of times cross-validator needs to be repeated.
random_state : int, RandomState instance or None, default=None
Controls the generation of the random states for each repetition.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Examples
--------
>>> import numpy as np
>>> from sklearn.model_selection import RepeatedStratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2,
... random_state=36851234)
>>> rskf.get_n_splits()
4
>>> print(rskf)
RepeatedStratifiedKFold(n_repeats=2, n_splits=2, random_state=36851234)
>>> for i, (train_index, test_index) in enumerate(rskf.split(X, y)):
... print(f"Fold {i}:")
... print(f" Train: index={train_index}")
... print(f" Test: index={test_index}")
...
Fold 0:
Train: index=[1 2]
Test: index=[0 3]
Fold 1:
Train: index=[0 3]
Test: index=[1 2]
Fold 2:
Train: index=[1 3]
Test: index=[0 2]
Fold 3:
Train: index=[0 2]
Test: index=[1 3]
Notes
-----
Randomized CV splitters may return different results for each call of
split. You can make the results identical by setting `random_state`
to an integer.
See Also
--------
RepeatedKFold : Repeats K-Fold n times.
"""
def __init__(self, *, n_splits=5, n_repeats=10, random_state=None):
super().__init__(
StratifiedKFold,
n_repeats=n_repeats,
random_state=random_state,
n_splits=n_splits,
)
def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Note that providing ``y`` is sufficient to generate the splits and
hence ``np.zeros(n_samples)`` may be used as a placeholder for
``X`` instead of actual training data.
y : array-like of shape (n_samples,)
The target variable for supervised learning problems.
Stratification is done based on the y labels.
groups : array-like of shape (n_samples,), default=None
Always ignored, exists for API compatibility.
Yields
------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
Notes
-----
Randomized CV splitters may return different results for each call of
split. You can make the results identical by setting `random_state`
to an integer.
"""
y = check_array(y, input_name="y", ensure_2d=False, dtype=None)
return super().split(X, y, groups=groups)
| RepeatedStratifiedKFold |
python | django__django | tests/update_only_fields/models.py | {
"start": 94,
"end": 367
} | class ____(models.Model):
GENDER_CHOICES = (
("M", "Male"),
("F", "Female"),
)
name = models.CharField(max_length=20)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
pid = models.IntegerField(null=True, default=None)
| Person |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 650714,
"end": 651540
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for EnterpriseServerInstallation."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseServerInstallationMembershipEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseServerInstallation"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| EnterpriseServerInstallationMembershipConnection |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_loops.py | {
"start": 1790,
"end": 25315
} | class ____(Exception):
pass
def test_loop_restore():
class Simple(_Loop):
def __init__(self, trainer, dataset: Iterator):
super().__init__(trainer)
self.iteration_count = 0
self.dataset = dataset
def run(self):
self.reset()
while not self.iteration_count > len(self.dataset):
try:
self.advance()
self.iteration_count += 1
self._restarting = False
except StopIteration:
break
self._restarting = False
def reset(self) -> None:
self.iter_dataset = iter(self.dataset)
if self.restarting:
for _ in range(self.iteration_count):
next(self.iter_dataset)
self.iteration_count += 1
else:
self.outputs = []
def advance(self) -> None:
value = next(self.iter_dataset)
if self.iteration_count == 5:
raise CustomException
self.outputs.append(value)
def state_dict(self) -> dict:
return {"iteration_count": self.iteration_count, "outputs": self.outputs}
def load_state_dict(self, state_dict: dict) -> None:
self.iteration_count = state_dict["iteration_count"]
self.outputs = state_dict["outputs"]
trainer = Trainer()
data = range(10)
loop = Simple(trainer, data)
try:
loop.run()
state_dict = {}
except CustomException:
state_dict = loop.state_dict()
loop = Simple(trainer, data)
loop.load_state_dict(state_dict)
loop.restarting = True
loop.run()
assert not loop.restarting
assert loop.outputs == list(range(10))
def test_loop_hierarchy():
@dataclass
class SimpleProgress(_BaseProgress):
increment: int = 0
class Simple(_Loop):
def __init__(self, trainer, a):
super().__init__(trainer)
self.a = a
self.progress = SimpleProgress()
def run(self):
while not self.progress.increment > 0:
try:
self.advance()
self.progress.increment += 1
self._restarting = False
except StopIteration:
break
self._restarting = False
def advance(self) -> None:
loop = getattr(self, "loop_child", None)
if not loop:
return
loop.run()
def on_save_checkpoint(self) -> dict:
return {"a": self.a}
def on_load_checkpoint(self, state_dict: dict) -> None:
self.a = state_dict["a"]
trainer = Trainer()
loop_parent = Simple(trainer, 1)
loop_child = Simple(trainer, 2)
loop_parent.loop_child = loop_child
state_dict = loop_parent.state_dict()
assert state_dict == {
"state_dict": {"a": 1},
"progress": {"increment": 0},
"loop_child.state_dict": {"a": 2},
"loop_child.progress": {"increment": 0},
}
state_dict["loop_child.state_dict"]["a"] = 3
# check restarting after `load_state_dict`
loop_parent.load_state_dict(state_dict)
assert loop_parent.restarting
loop_parent.run()
# check the new state after `run`
state_dict = loop_parent.state_dict()
assert state_dict == {
"state_dict": {"a": 1},
"progress": {"increment": 1},
"loop_child.state_dict": {"a": 3},
"loop_child.progress": {"increment": 1},
}
loop_parent_copy = deepcopy(loop_parent)
assert loop_parent_copy.state_dict() == loop_parent.state_dict()
assert loop_parent_copy.on_save_checkpoint() == state_dict["state_dict"]
assert loop_parent_copy.loop_child.on_save_checkpoint() == state_dict["loop_child.state_dict"]
loop_parent = Simple(trainer, 1)
loop_child = Simple(trainer, 2)
loop_parent.loop_child = loop_child
loop_parent.load_state_dict(state_dict)
assert loop_parent.progress.increment == 1
assert loop_parent.loop_child.progress.increment == 1
del loop_parent.loop_child
state_dict = loop_parent.state_dict()
assert state_dict == {"state_dict": {"a": 1}, "progress": {"increment": 1}}
@pytest.mark.parametrize("stop_epoch", [1, 2])
@pytest.mark.parametrize("stop_batch", [1, 2])
@pytest.mark.parametrize(("n_dataloaders", "stop_dataloader"), [(2, 0), (2, 1), (3, 2)])
def test_loop_restart_progress_multiple_dataloaders(tmp_path, n_dataloaders, stop_dataloader, stop_epoch, stop_batch):
n_batches = 5
n_epochs = 3
class ValidationModel(BoringModel):
def __init__(self):
super().__init__()
def validation_step(self, batch, batch_idx, dataloader_idx):
if self.current_epoch == stop_epoch and batch_idx == stop_batch and dataloader_idx == stop_dataloader:
raise CustomException
return super().validation_step(batch, batch_idx)
def val_dataloader(self):
return [super(ValidationModel, self).val_dataloader() for _ in range(n_dataloaders)]
model = ValidationModel()
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=n_epochs,
limit_train_batches=1,
limit_val_batches=n_batches,
callbacks=OnExceptionCheckpoint(tmp_path),
)
# simulate a failure
with pytest.raises(CustomException):
trainer.fit(model)
ckpt_path = str(tmp_path / "on_exception.ckpt")
checkpoint = torch.load(ckpt_path, weights_only=True)["loops"]["fit_loop"]
trainer.fit_loop.load_state_dict(checkpoint)
# `nbe_`: non-breaking epoch, as in, no exception will be raised. `be_`: breaking epoch
# the fit-validation total batch progress is reset per epoch so it's not counted for the total value.
nbe_total_val_batch = 0 # stop_epoch * n_dataloaders * n_batches
be_total_val_batch = stop_dataloader * n_batches + stop_batch
total_val_batch = nbe_total_val_batch + be_total_val_batch
expected = {
"total": {
"ready": total_val_batch + 1,
"started": total_val_batch + 1,
"processed": total_val_batch,
"completed": total_val_batch,
},
"current": {
"ready": total_val_batch + 1,
"started": total_val_batch + 1,
"processed": total_val_batch,
"completed": total_val_batch,
},
"is_last_batch": False,
}
assert trainer.fit_loop.epoch_loop.val_loop.batch_progress.state_dict() == expected
@pytest.mark.parametrize("accumulate_grad_batches", [1, 2, 3])
@pytest.mark.parametrize("stop_epoch", [1, 2])
@pytest.mark.parametrize("stop_batch", [1, 2])
def test_loop_state_on_exception(accumulate_grad_batches, stop_epoch, stop_batch, tmp_path):
n_epochs = 3
n_batches = 3
class TestModel(BoringModel):
def training_step(self, batch, batch_idx):
if self.trainer.current_epoch == stop_epoch and batch_idx == stop_batch:
raise CustomException
return super().training_step(batch, batch_idx)
model = TestModel()
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=n_epochs,
limit_train_batches=n_batches,
limit_val_batches=0,
accumulate_grad_batches=accumulate_grad_batches,
enable_progress_bar=False,
logger=False,
callbacks=OnExceptionCheckpoint(tmp_path),
)
# simulate a failure
with pytest.raises(CustomException):
trainer.fit(model)
ckpt_path = str(tmp_path / "on_exception.ckpt")
assert os.path.exists(ckpt_path)
checkpoint = torch.load(ckpt_path, weights_only=True)
optim_progress = trainer.fit_loop.epoch_loop.automatic_optimization.optim_progress
sch_progress = trainer.fit_loop.epoch_loop.scheduler_progress
# `nbe_`: non-breaking epoch, as in, no exception will be raised. `be_`: breaking epoch
nbe_batches_completed = stop_epoch * n_batches
be_batches_completed = stop_batch
# lightning applies leftover accumulated gradients when the epoch ends
has_leftover_accumulation_batches = n_batches % accumulate_grad_batches != 0
# number of batches that will call `optimizer.step()` during non-breaking and breaking epochs
nbe_stepping_batches = nbe_batches_completed // accumulate_grad_batches
be_stepping_batches = be_batches_completed // accumulate_grad_batches
nbe_total_opt_steps = nbe_stepping_batches + has_leftover_accumulation_batches
be_total_opt_steps = be_stepping_batches
assert optim_progress.optimizer_steps == nbe_total_opt_steps + be_total_opt_steps
assert optim_progress.optimizer.step.current.completed == be_total_opt_steps
has_opt_stepped_in_be = stop_batch + 1 >= accumulate_grad_batches
nbe_total_zero_grad = nbe_stepping_batches + has_leftover_accumulation_batches
# `max` because the first batch always zero-grads
be_total_zero_grad = max(1, be_stepping_batches)
assert optim_progress.optimizer.zero_grad.total.completed == nbe_total_zero_grad + be_total_zero_grad
assert optim_progress.optimizer.zero_grad.current.completed == be_total_zero_grad
nbe_sch_steps = stop_epoch
be_sch_steps = 0 # the current epoch did not complete
assert sch_progress.total.completed == nbe_sch_steps + be_sch_steps
assert sch_progress.current.completed == be_sch_steps
expected = {
"state_dict": ANY,
"epoch_progress": {
"total": {
"ready": stop_epoch + 1,
"started": stop_epoch + 1,
"processed": stop_epoch,
"completed": stop_epoch,
},
"current": {
"ready": stop_epoch + 1,
"started": stop_epoch + 1,
"processed": stop_epoch,
"completed": stop_epoch,
},
},
"epoch_loop.state_dict": ANY,
"epoch_loop.batch_progress": {
"total": {
"ready": nbe_batches_completed + be_batches_completed + 1,
"started": nbe_batches_completed + be_batches_completed + 1,
"processed": nbe_batches_completed + be_batches_completed,
"completed": nbe_batches_completed + be_batches_completed,
},
"current": {
"ready": stop_batch + 1,
"started": stop_batch + 1,
"processed": stop_batch,
"completed": stop_batch,
},
"is_last_batch": (stop_batch + 1) == n_batches,
},
"epoch_loop.scheduler_progress": {
"total": {"ready": nbe_sch_steps + be_sch_steps, "completed": nbe_sch_steps + be_sch_steps},
"current": {"ready": be_sch_steps, "completed": be_sch_steps},
},
"epoch_loop.manual_optimization.state_dict": ANY,
"epoch_loop.manual_optimization.optim_step_progress": {
"total": {"ready": 0, "completed": 0},
"current": {"ready": 0, "completed": 0},
},
"epoch_loop.automatic_optimization.state_dict": {},
"epoch_loop.automatic_optimization.optim_progress": {
"optimizer": {
"step": {
"total": {
"ready": nbe_total_opt_steps + be_total_opt_steps + has_opt_stepped_in_be,
"completed": nbe_total_opt_steps + be_total_opt_steps,
},
"current": {"ready": be_total_opt_steps + has_opt_stepped_in_be, "completed": be_total_opt_steps},
},
"zero_grad": {
"total": {
"ready": nbe_total_zero_grad + be_total_zero_grad,
"started": nbe_total_zero_grad + be_total_zero_grad,
"completed": nbe_total_zero_grad + be_total_zero_grad,
},
"current": {
"ready": be_total_zero_grad,
"started": be_total_zero_grad,
"completed": be_total_zero_grad,
},
},
},
},
"epoch_loop.val_loop.state_dict": ANY,
"epoch_loop.val_loop.batch_progress": ANY,
}
assert checkpoint["loops"]["fit_loop"] == expected
trainer.fit_loop.load_state_dict(checkpoint["loops"]["fit_loop"])
state_dict = trainer.fit_loop.state_dict()
# need to remove these elements for comparison; comparing with `fit_loop.state_dict()` would require the
# fit loop to have an iterator, which is only available during training
state_dict["epoch_loop.state_dict"]["dataloader_state_dict"] = ANY
checkpoint["loops"]["fit_loop"]["epoch_loop.state_dict"]["dataloader_state_dict"] = ANY
assert state_dict == checkpoint["loops"]["fit_loop"]
trainer.fit_loop.load_state_dict(checkpoint["loops"]["fit_loop"])
# test resetting manually, we expect the `ready` counter for batch to be reset to `completed`
# but the `ready` counter for epoch to not be reset, since we are still mid epoch
trainer.fit_loop.reset()
trainer.fit_loop.epoch_loop.reset()
epoch_progress = trainer.fit_loop.epoch_progress
assert epoch_progress.current.ready == stop_epoch + 1
assert epoch_progress.current.completed == stop_epoch
batch_progress = trainer.fit_loop.epoch_loop.batch_progress
assert batch_progress.current.ready == be_batches_completed
assert batch_progress.current.completed == be_batches_completed
optim_progress = trainer.fit_loop.epoch_loop.automatic_optimization.optim_progress
assert optim_progress.optimizer.step.current.ready == be_total_opt_steps
assert optim_progress.optimizer.step.current.completed == be_total_opt_steps
assert optim_progress.optimizer.zero_grad.current.ready == be_total_zero_grad
assert optim_progress.optimizer.zero_grad.current.completed == be_total_zero_grad
state_dict = trainer.fit_loop.state_dict()
assert state_dict != checkpoint["loops"]["fit_loop"]
assert state_dict["epoch_progress"]["total"]["started"] == stop_epoch + 1
assert state_dict["epoch_progress"]["current"]["started"] == stop_epoch + 1
def test_loop_state_on_complete_run(tmp_path):
n_epochs = 3
n_batches = 3
accumulate_grad_batches = 1
class TestModel(BoringModel):
def train_dataloader(self):
# override to test the `is_last_batch` value
return DataLoader(RandomDataset(32, n_batches))
model = TestModel()
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=n_epochs,
limit_val_batches=0,
accumulate_grad_batches=accumulate_grad_batches,
enable_progress_bar=False,
logger=False,
)
trainer.fit(model)
assert trainer.num_training_batches == n_batches
ckpt_path = trainer.checkpoint_callback.best_model_path
assert os.path.exists(ckpt_path)
checkpoint = torch.load(ckpt_path, weights_only=True)
n_sch_steps_total = n_epochs
n_sch_steps_current = 1
expected = {
"state_dict": ANY,
"epoch_progress": {
"total": {
"ready": n_epochs,
"started": n_epochs,
"processed": n_epochs,
"completed": n_epochs - 1,
},
"current": {
"ready": n_epochs,
"started": n_epochs,
"processed": n_epochs,
"completed": n_epochs - 1,
},
},
"epoch_loop.state_dict": ANY,
"epoch_loop.batch_progress": {
"total": {
"ready": n_epochs * n_batches,
"started": n_epochs * n_batches,
"processed": n_epochs * n_batches,
"completed": n_epochs * n_batches,
},
"current": {
"ready": n_batches,
"started": n_batches,
"processed": n_batches,
"completed": n_batches,
},
"is_last_batch": True,
},
"epoch_loop.scheduler_progress": {
"total": {"ready": n_sch_steps_total, "completed": n_sch_steps_total},
"current": {"ready": n_sch_steps_current, "completed": n_sch_steps_current},
},
"epoch_loop.manual_optimization.state_dict": ANY,
"epoch_loop.manual_optimization.optim_step_progress": {
"total": {"ready": 0, "completed": 0},
"current": {"ready": 0, "completed": 0},
},
"epoch_loop.automatic_optimization.state_dict": {},
"epoch_loop.automatic_optimization.optim_progress": {
"optimizer": {
"step": {
"total": {
"ready": n_epochs * n_batches,
"completed": n_epochs * n_batches,
},
"current": {
"ready": n_batches,
"completed": n_batches,
},
},
"zero_grad": {
"total": {
"ready": n_epochs * n_batches,
"started": n_epochs * n_batches,
"completed": n_epochs * n_batches,
},
"current": {
"ready": n_batches,
"started": n_batches,
"completed": n_batches,
},
},
},
},
"epoch_loop.val_loop.state_dict": ANY,
"epoch_loop.val_loop.batch_progress": ANY,
}
assert checkpoint["loops"]["fit_loop"] == expected
def test_fit_loop_reset(tmp_path):
"""Test that the reset logic in fit- and epoch loop is aware of whether the loop is restarting from a completed
loop or from a mid-epoch checkpoint."""
# generate checkpoints at end of epoch and mid-epoch
model = BoringModel()
checkpoint_callback = ModelCheckpoint(
dirpath=tmp_path,
every_n_train_steps=2,
save_top_k=-1,
)
trainer = Trainer(
default_root_dir=tmp_path,
limit_train_batches=4,
max_epochs=2,
callbacks=[checkpoint_callback],
logger=False,
enable_model_summary=False,
)
trainer.fit(model)
# reset state loaded from a checkpoint from mid-epoch
mid_epoch_ckpt = torch.load(str(tmp_path / "epoch=0-step=2.ckpt"), weights_only=True)
fit_loop = trainer.fit_loop
epoch_loop = fit_loop.epoch_loop
optimizer_loop = epoch_loop.automatic_optimization
assert not fit_loop.restarting
assert not epoch_loop.restarting
assert not optimizer_loop.restarting
# we load exactly what was saved - no reset yet
fit_loop.load_state_dict(mid_epoch_ckpt["loops"]["fit_loop"])
assert fit_loop.restarting
assert fit_loop.epoch_progress.total.ready == 1
assert fit_loop.epoch_progress.total.completed == 0 # the checkpoint was saved mid epoch
assert fit_loop.epoch_progress.current.ready == 1
assert fit_loop.epoch_progress.current.completed == 0
assert epoch_loop.batch_progress.total.ready == 2
assert epoch_loop.batch_progress.total.processed == 2
assert epoch_loop.batch_progress.total.completed == 1 # the checkpoint was saved on train_batch_end
assert epoch_loop.batch_progress.current.ready == 2 # currents get set to the completed value
assert epoch_loop.batch_progress.current.processed == 2
assert epoch_loop.batch_progress.current.completed == 1
fit_loop.reset()
epoch_loop.reset()
# resetting from a mid-of-epoch checkpoint SHOULD NOT reset the current counters to 0
assert fit_loop.restarting
assert fit_loop.epoch_progress.total.ready == 1
assert fit_loop.epoch_progress.total.completed == 0 # the checkpoint was saved mid epoch
assert fit_loop.epoch_progress.current.ready == 1
assert fit_loop.epoch_progress.current.completed == 0
# however it should increment completed batch progress, since it was saved immediately prior
assert epoch_loop.restarting
assert epoch_loop.batch_progress.total.ready == 2
assert epoch_loop.batch_progress.total.processed == 2
assert epoch_loop.batch_progress.total.completed == 2
assert epoch_loop.batch_progress.current.ready == 2
assert epoch_loop.batch_progress.current.processed == 2
assert epoch_loop.batch_progress.current.completed == 2
assert optimizer_loop.restarting
# reset state loaded from a checkpoint from the end of an epoch
end_of_epoch_ckpt = torch.load(str(tmp_path / "epoch=0-step=4.ckpt"), weights_only=True)
fit_loop = trainer.fit_loop
epoch_loop = fit_loop.epoch_loop
fit_loop.restarting = False
epoch_loop.restarting = False
optimizer_loop.restarting = False
# we load exactly what was saved - no reset yet
fit_loop.load_state_dict(end_of_epoch_ckpt["loops"]["fit_loop"])
assert fit_loop.restarting
assert fit_loop.epoch_progress.total.ready == 1
assert fit_loop.epoch_progress.total.completed == 0
assert fit_loop.epoch_progress.current.ready == 1
assert fit_loop.epoch_progress.current.completed == 0
# resetting from a end-of-epoch checkpoint SHOULD reset the current counters to 0
fit_loop.reset()
epoch_loop.reset()
# resetting from a mid-of-epoch checkpoint SHOULD NOT reset the current counters to 0
# since we are restarting at the end of epoch, we need to see `completed` being updated after reset
assert fit_loop.restarting
assert fit_loop.epoch_progress.total.ready == 1
assert fit_loop.epoch_progress.total.completed == 1
assert fit_loop.epoch_progress.current.ready == 1
assert fit_loop.epoch_progress.current.completed == 1
# however it should increment completed batch progress, since it was saved immediately prior
assert epoch_loop.restarting
assert epoch_loop.batch_progress.total.ready == 4
assert epoch_loop.batch_progress.total.processed == 4
assert epoch_loop.batch_progress.total.completed == 4
assert epoch_loop.batch_progress.current.ready == 0
assert epoch_loop.batch_progress.current.processed == 0
assert epoch_loop.batch_progress.current.completed == 0
def compare_state_dicts(dict1, dict2):
def compare_leaves(d1, d2):
result = {}
all_keys = set(d1.keys()).union(d2.keys())
for key in all_keys:
val1 = d1.get(key, None)
val2 = d2.get(key, None)
if isinstance(val1, dict) and isinstance(val2, dict):
res = compare_leaves(val1, val2)
if res:
result[key] = res
elif isinstance(val1, dict) or isinstance(val2, dict):
raise ValueError("dicts have different leaves")
elif isinstance(val1, torch.Tensor) and isinstance(val2, torch.Tensor):
diff = torch.norm(val1 - val2)
if diff > 1e-8:
result[key] = f"{diff} > 1e-8"
elif isinstance(val1, float) and isinstance(val2, float):
if abs(val1 - val2) > 1e-8:
result[key] = f"{val1} != {val2}"
elif val1 != val2:
result[key] = f"{val1} != {val2}"
return result
return compare_leaves(dict1, dict2)
| CustomException |
python | numba__numba | numba/cuda/cudadrv/devicearray.py | {
"start": 26643,
"end": 31123
} | class ____(DeviceNDArrayBase, np.ndarray):
"""
A host array that uses CUDA managed memory.
"""
def device_setup(self, gpu_data, stream=0):
self.gpu_data = gpu_data
self.stream = stream
def from_array_like(ary, stream=0, gpu_data=None):
"Create a DeviceNDArray object that is like ary."
return DeviceNDArray(ary.shape, ary.strides, ary.dtype, stream=stream,
gpu_data=gpu_data)
def from_record_like(rec, stream=0, gpu_data=None):
"Create a DeviceRecord object that is like rec."
return DeviceRecord(rec.dtype, stream=stream, gpu_data=gpu_data)
def array_core(ary):
"""
Extract the repeated core of a broadcast array.
Broadcast arrays are by definition non-contiguous due to repeated
dimensions, i.e., dimensions with stride 0. In order to ascertain memory
contiguity and copy the underlying data from such arrays, we must create
a view without the repeated dimensions.
"""
if not ary.strides or not ary.size:
return ary
core_index = []
for stride in ary.strides:
core_index.append(0 if stride == 0 else slice(None))
return ary[tuple(core_index)]
def is_contiguous(ary):
"""
Returns True iff `ary` is C-style contiguous while ignoring
broadcasted and 1-sized dimensions.
As opposed to array_core(), it does not call require_context(),
which can be quite expensive.
"""
size = ary.dtype.itemsize
for shape, stride in zip(reversed(ary.shape), reversed(ary.strides)):
if shape > 1 and stride != 0:
if size != stride:
return False
size *= shape
return True
errmsg_contiguous_buffer = ("Array contains non-contiguous buffer and cannot "
"be transferred as a single memory region. Please "
"ensure contiguous buffer with numpy "
".ascontiguousarray()")
def sentry_contiguous(ary):
core = array_core(ary)
if not core.flags['C_CONTIGUOUS'] and not core.flags['F_CONTIGUOUS']:
raise ValueError(errmsg_contiguous_buffer)
def auto_device(obj, stream=0, copy=True, user_explicit=False):
"""
Create a DeviceRecord or DeviceArray like obj and optionally copy data from
host to device. If obj already represents device memory, it is returned and
no copy is made.
"""
if _driver.is_device_memory(obj):
return obj, False
elif hasattr(obj, '__cuda_array_interface__'):
return numba.cuda.as_cuda_array(obj), False
else:
if isinstance(obj, np.void):
devobj = from_record_like(obj, stream=stream)
else:
# This allows you to pass non-array objects like constants and
# objects implementing the array interface
# https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html
# into this function (with no overhead -- copies -- for `obj`s
# that are already `ndarray`s.
obj = np.array(
obj,
copy=False if numpy_version < (2, 0) else None,
subok=True)
sentry_contiguous(obj)
devobj = from_array_like(obj, stream=stream)
if copy:
if config.CUDA_WARN_ON_IMPLICIT_COPY:
if (
not user_explicit and
(not isinstance(obj, DeviceNDArray)
and isinstance(obj, np.ndarray))
):
msg = ("Host array used in CUDA kernel will incur "
"copy overhead to/from device.")
warn(NumbaPerformanceWarning(msg))
devobj.copy_to_device(obj, stream=stream)
return devobj, True
def check_array_compatibility(ary1, ary2):
ary1sq, ary2sq = ary1.squeeze(), ary2.squeeze()
if ary1.dtype != ary2.dtype:
raise TypeError('incompatible dtype: %s vs. %s' %
(ary1.dtype, ary2.dtype))
if ary1sq.shape != ary2sq.shape:
raise ValueError('incompatible shape: %s vs. %s' %
(ary1.shape, ary2.shape))
# We check strides only if the size is nonzero, because strides are
# irrelevant (and can differ) for zero-length copies.
if ary1.size and ary1sq.strides != ary2sq.strides:
raise ValueError('incompatible strides: %s vs. %s' %
(ary1.strides, ary2.strides))
| ManagedNDArray |
python | langchain-ai__langchain | libs/core/tests/unit_tests/language_models/chat_models/test_base.py | {
"start": 16278,
"end": 30162
} | class ____(FakeTracer):
def __init__(self) -> None:
super().__init__()
self.messages: list = []
def on_chat_model_start(self, *args: Any, **kwargs: Any) -> Run:
_, messages = args
self.messages.append(messages)
return super().on_chat_model_start(
*args,
**kwargs,
)
def test_trace_images_in_openai_format() -> None:
"""Test that images are traced in OpenAI Chat Completions format."""
llm = ParrotFakeChatModel()
messages = [
{
"role": "user",
# v0 format
"content": [
{
"type": "image",
"source_type": "url",
"url": "https://example.com/image.png",
}
],
}
]
tracer = FakeChatModelStartTracer()
llm.invoke(messages, config={"callbacks": [tracer]})
assert tracer.messages == [
[
[
HumanMessage(
content=[
{
"type": "image_url",
"image_url": {"url": "https://example.com/image.png"},
}
]
)
]
]
]
def test_trace_pdfs() -> None:
# For backward compat
llm = ParrotFakeChatModel()
messages = [
{
"role": "user",
"content": [
{
"type": "file",
"mime_type": "application/pdf",
"base64": "<base64 string>",
}
],
}
]
tracer = FakeChatModelStartTracer()
with warnings.catch_warnings():
warnings.simplefilter("error")
llm.invoke(messages, config={"callbacks": [tracer]})
assert tracer.messages == [
[
[
HumanMessage(
content=[
{
"type": "file",
"mime_type": "application/pdf",
"source_type": "base64",
"data": "<base64 string>",
}
]
)
]
]
]
def test_content_block_transformation_v0_to_v1_image() -> None:
"""Test that v0 format image content blocks are transformed to v1 format."""
# Create a message with v0 format image content
image_message = AIMessage(
content=[
{
"type": "image",
"source_type": "url",
"url": "https://example.com/image.png",
}
]
)
llm = GenericFakeChatModel(messages=iter([image_message]), output_version="v1")
response = llm.invoke("test")
# With v1 output_version, .content should be transformed
# Check structure, ignoring auto-generated IDs
assert len(response.content) == 1
content_block = response.content[0]
if isinstance(content_block, dict) and "id" in content_block:
# Remove auto-generated id for comparison
content_without_id = {k: v for k, v in content_block.items() if k != "id"}
expected_content = {
"type": "image",
"url": "https://example.com/image.png",
}
assert content_without_id == expected_content
else:
assert content_block == {
"type": "image",
"url": "https://example.com/image.png",
}
@pytest.mark.parametrize("output_version", ["v0", "v1"])
def test_trace_content_blocks_with_no_type_key(output_version: str) -> None:
"""Test behavior of content blocks that don't have a `type` key.
Only for blocks with one key, in which case, the name of the key is used as `type`.
"""
llm = ParrotFakeChatModel(output_version=output_version)
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Hello",
},
{
"cachePoint": {"type": "default"},
},
],
}
]
tracer = FakeChatModelStartTracer()
response = llm.invoke(messages, config={"callbacks": [tracer]})
assert tracer.messages == [
[
[
HumanMessage(
[
{
"type": "text",
"text": "Hello",
},
{
"type": "cachePoint",
"cachePoint": {"type": "default"},
},
]
)
]
]
]
if output_version == "v0":
assert response.content == [
{
"type": "text",
"text": "Hello",
},
{
"cachePoint": {"type": "default"},
},
]
else:
assert response.content == [
{
"type": "text",
"text": "Hello",
},
{
"type": "non_standard",
"value": {
"cachePoint": {"type": "default"},
},
},
]
assert response.content_blocks == [
{
"type": "text",
"text": "Hello",
},
{
"type": "non_standard",
"value": {
"cachePoint": {"type": "default"},
},
},
]
def test_extend_support_to_openai_multimodal_formats() -> None:
"""Test normalizing OpenAI audio, image, and file inputs to v1."""
# Audio and file only (chat model default)
messages = HumanMessage(
content=[
{"type": "text", "text": "Hello"},
{ # audio-base64
"type": "input_audio",
"input_audio": {
"format": "wav",
"data": "<base64 string>",
},
},
{ # file-base64
"type": "file",
"file": {
"filename": "draconomicon.pdf",
"file_data": "data:application/pdf;base64,<base64 string>",
},
},
{ # file-id
"type": "file",
"file": {"file_id": "<file id>"},
},
]
)
expected_content_messages = HumanMessage(
content=[
{"type": "text", "text": "Hello"}, # TextContentBlock
{ # AudioContentBlock
"type": "audio",
"base64": "<base64 string>",
"mime_type": "audio/wav",
},
{ # FileContentBlock
"type": "file",
"base64": "<base64 string>",
"mime_type": "application/pdf",
"extras": {"filename": "draconomicon.pdf"},
},
{ # ...
"type": "file",
"file_id": "<file id>",
},
]
)
normalized_content = _normalize_messages([messages])
# Check structure, ignoring auto-generated IDs
assert len(normalized_content) == 1
normalized_message = normalized_content[0]
assert len(normalized_message.content) == len(expected_content_messages.content)
assert _content_blocks_equal_ignore_id(
normalized_message.content, expected_content_messages.content
)
messages = HumanMessage(
content=[
{"type": "text", "text": "Hello"},
{ # image-url
"type": "image_url",
"image_url": {"url": "https://example.com/image.png"},
},
{ # image-base64
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."},
},
{ # audio-base64
"type": "input_audio",
"input_audio": {
"format": "wav",
"data": "<base64 string>",
},
},
{ # file-base64
"type": "file",
"file": {
"filename": "draconomicon.pdf",
"file_data": "data:application/pdf;base64,<base64 string>",
},
},
{ # file-id
"type": "file",
"file": {"file_id": "<file id>"},
},
]
)
expected_content_messages = HumanMessage(
content=[
{"type": "text", "text": "Hello"}, # TextContentBlock
{ # image-url passes through
"type": "image_url",
"image_url": {"url": "https://example.com/image.png"},
},
{ # image-url passes through with inline data
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."},
},
{ # AudioContentBlock
"type": "audio",
"base64": "<base64 string>",
"mime_type": "audio/wav",
},
{ # FileContentBlock
"type": "file",
"base64": "<base64 string>",
"mime_type": "application/pdf",
"extras": {"filename": "draconomicon.pdf"},
},
{ # ...
"type": "file",
"file_id": "<file id>",
},
]
)
normalized_content = _normalize_messages([messages])
# Check structure, ignoring auto-generated IDs
assert len(normalized_content) == 1
normalized_message = normalized_content[0]
assert len(normalized_message.content) == len(expected_content_messages.content)
assert _content_blocks_equal_ignore_id(
normalized_message.content, expected_content_messages.content
)
def test_normalize_messages_edge_cases() -> None:
# Test behavior of malformed/unrecognized content blocks
messages = [
HumanMessage(
content=[
{
"type": "input_image", # Responses API type; not handled
"image_url": "uri",
},
{
# Standard OpenAI Chat Completions type but malformed structure
"type": "input_audio",
"input_audio": "uri", # Should be nested in `audio`
},
{
"type": "file",
"file": "uri", # `file` should be a dict for Chat Completions
},
{
"type": "input_file", # Responses API type; not handled
"file_data": "uri",
"filename": "file-name",
},
]
)
]
assert messages == _normalize_messages(messages)
def test_normalize_messages_v1_content_blocks_unchanged() -> None:
"""Test passing v1 content blocks to `_normalize_messages()` leaves unchanged."""
input_messages = [
HumanMessage(
content=[
{
"type": "text",
"text": "Hello world",
},
{
"type": "image",
"url": "https://example.com/image.png",
"mime_type": "image/png",
},
{
"type": "audio",
"base64": "base64encodedaudiodata",
"mime_type": "audio/wav",
},
{
"type": "file",
"id": "file_123",
},
{
"type": "reasoning",
"reasoning": "Let me think about this...",
},
]
)
]
result = _normalize_messages(input_messages)
# Verify the result is identical to the input (message should not be copied)
assert len(result) == 1
assert result[0] is input_messages[0]
assert result[0].content == input_messages[0].content
def test_output_version_invoke(monkeypatch: Any) -> None:
messages = [AIMessage("hello")]
llm = GenericFakeChatModel(messages=iter(messages), output_version="v1")
response = llm.invoke("hello")
assert response.content == [{"type": "text", "text": "hello"}]
assert response.response_metadata["output_version"] == "v1"
llm = GenericFakeChatModel(messages=iter(messages))
response = llm.invoke("hello")
assert response.content == "hello"
monkeypatch.setenv("LC_OUTPUT_VERSION", "v1")
llm = GenericFakeChatModel(messages=iter(messages))
response = llm.invoke("hello")
assert response.content == [{"type": "text", "text": "hello"}]
assert response.response_metadata["output_version"] == "v1"
# -- v1 output version tests --
async def test_output_version_ainvoke(monkeypatch: Any) -> None:
messages = [AIMessage("hello")]
# v0
llm = GenericFakeChatModel(messages=iter(messages))
response = await llm.ainvoke("hello")
assert response.content == "hello"
# v1
llm = GenericFakeChatModel(messages=iter(messages), output_version="v1")
response = await llm.ainvoke("hello")
assert response.content == [{"type": "text", "text": "hello"}]
assert response.response_metadata["output_version"] == "v1"
# v1 from env var
monkeypatch.setenv("LC_OUTPUT_VERSION", "v1")
llm = GenericFakeChatModel(messages=iter(messages))
response = await llm.ainvoke("hello")
assert response.content == [{"type": "text", "text": "hello"}]
assert response.response_metadata["output_version"] == "v1"
| FakeChatModelStartTracer |
python | huggingface__transformers | src/transformers/models/beit/configuration_beit.py | {
"start": 847,
"end": 10980
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the BEiT
[microsoft/beit-base-patch16-224-pt22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k) architecture.
Args:
vocab_size (`int`, *optional*, defaults to 8192):
Vocabulary size of the BEiT model. Defines the number of different image tokens that can be used during
pre-training.
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
use_mask_token (`bool`, *optional*, defaults to `False`):
Whether to use a mask token for masked image modeling.
use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
Whether to use BERT-style absolute position embeddings.
use_relative_position_bias (`bool`, *optional*, defaults to `False`):
Whether to use T5-style relative position embeddings in the self-attention layers.
use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
layer_scale_init_value (`float`, *optional*, defaults to 0.1):
Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
drop_path_rate (`float`, *optional*, defaults to 0.1):
Stochastic depth rate per sample (when applied in the main path of residual layers).
use_mean_pooling (`bool`, *optional*, defaults to `True`):
Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
CLS token, before applying the classification head.
pool_scales (`tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
Pooling scales used in Pooling Pyramid Module applied on the last feature map.
use_auxiliary_head (`bool`, *optional*, defaults to `True`):
Whether to use an auxiliary head during training.
auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
Weight of the cross-entropy loss of the auxiliary head.
auxiliary_channels (`int`, *optional*, defaults to 256):
Number of channels to use in the auxiliary head.
auxiliary_num_convs (`int`, *optional*, defaults to 1):
Number of convolutional layers to use in the auxiliary head.
auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
Whether to concatenate the output of the auxiliary head with the input before the classification layer.
semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
The index that is ignored by the loss function of the semantic segmentation model.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
add_fpn (`bool`, *optional*, defaults to `False`):
Whether to add a FPN as part of the backbone. Only relevant for [`BeitBackbone`].
reshape_hidden_states (`bool`, *optional*, defaults to `True`):
Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
seq_len, hidden_size)`. Only relevant for [`BeitBackbone`].
Example:
```python
>>> from transformers import BeitConfig, BeitModel
>>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration
>>> configuration = BeitConfig()
>>> # Initializing a model (with random weights) from the beit-base-patch16-224-pt22k style configuration
>>> model = BeitModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "beit"
def __init__(
self,
vocab_size=8192,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
image_size=224,
patch_size=16,
num_channels=3,
use_mask_token=False,
use_absolute_position_embeddings=False,
use_relative_position_bias=False,
use_shared_relative_position_bias=False,
layer_scale_init_value=0.1,
drop_path_rate=0.1,
use_mean_pooling=True,
pool_scales=[1, 2, 3, 6],
use_auxiliary_head=True,
auxiliary_loss_weight=0.4,
auxiliary_channels=256,
auxiliary_num_convs=1,
auxiliary_concat_input=False,
semantic_loss_ignore_index=255,
out_features=None,
out_indices=None,
add_fpn=False,
reshape_hidden_states=True,
**kwargs,
):
super().__init__(**kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.use_mask_token = use_mask_token
self.use_absolute_position_embeddings = use_absolute_position_embeddings
self.use_relative_position_bias = use_relative_position_bias
self.use_shared_relative_position_bias = use_shared_relative_position_bias
self.layer_scale_init_value = layer_scale_init_value
self.drop_path_rate = drop_path_rate
self.use_mean_pooling = use_mean_pooling
# decode head attributes (semantic segmentation)
self.pool_scales = pool_scales
# auxiliary head attributes (semantic segmentation)
self.use_auxiliary_head = use_auxiliary_head
self.auxiliary_loss_weight = auxiliary_loss_weight
self.auxiliary_channels = auxiliary_channels
self.auxiliary_num_convs = auxiliary_num_convs
self.auxiliary_concat_input = auxiliary_concat_input
self.semantic_loss_ignore_index = semantic_loss_ignore_index
# handle backwards compatibility
if "segmentation_indices" in kwargs:
warnings.warn(
"The `segmentation_indices` argument is deprecated and will be removed in a future version, use `out_indices` instead.",
FutureWarning,
)
out_indices = kwargs.pop("segmentation_indices")
# backbone attributes
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
self.add_fpn = add_fpn
self.reshape_hidden_states = reshape_hidden_states
__all__ = ["BeitConfig"]
| BeitConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 156994,
"end": 157767
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ClearProjectV2ItemFieldValue"""
__schema__ = github_schema
__field_names__ = ("project_id", "item_id", "field_id", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
"""The ID of the Project."""
item_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="itemId")
"""The ID of the item to be cleared."""
field_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="fieldId")
"""The ID of the field to be cleared."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| ClearProjectV2ItemFieldValueInput |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 28696,
"end": 30522
} | class ____(TestCase):
"""
Tests for auth backend that supports object level permissions
"""
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user("test", "test@example.com", "test")
cls.user2 = User.objects.create_user("test2", "test2@example.com", "test")
cls.user3 = User.objects.create_user("test3", "test3@example.com", "test")
def tearDown(self):
# The get_group_permissions test messes with ContentTypes, which will
# be cached; flush the cache to ensure there are no side effects
# Refs #14975, #14925
ContentType.objects.clear_cache()
def test_has_perm(self):
self.assertIs(self.user1.has_perm("perm", TestObj()), False)
self.assertIs(self.user2.has_perm("perm", TestObj()), True)
self.assertIs(self.user2.has_perm("perm"), False)
self.assertIs(self.user2.has_perms(["simple", "advanced"], TestObj()), True)
self.assertIs(self.user3.has_perm("perm", TestObj()), False)
self.assertIs(self.user3.has_perm("anon", TestObj()), False)
self.assertIs(self.user3.has_perms(["simple", "advanced"], TestObj()), False)
def test_get_all_permissions(self):
self.assertEqual(self.user1.get_all_permissions(TestObj()), {"simple"})
self.assertEqual(
self.user2.get_all_permissions(TestObj()), {"simple", "advanced"}
)
self.assertEqual(self.user2.get_all_permissions(), set())
def test_get_group_permissions(self):
group = Group.objects.create(name="test_group")
self.user3.groups.add(group)
self.assertEqual(self.user3.get_group_permissions(TestObj()), {"group_perm"})
@override_settings(
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"],
)
| RowlevelBackendTest |
python | charliermarsh__ruff | crates/ruff_python_ast/generate.py | {
"start": 6600,
"end": 34440
} | class ____:
rule: str
name: str
inner: str
seq: bool = False
optional: bool = False
slice_: bool = False
def __init__(self, rule: str) -> None:
self.rule = rule
self.name = ""
self.inner = extract_type_argument(rule)
# The following cases are the limitations of this parser(and not used in the ast.toml):
# * Rules that involve declaring a sequence with optional items e.g. Vec<Option<...>>
last_pos = len(rule) - 1
for i, ch in enumerate(rule):
if ch == "?":
if i == last_pos:
self.optional = True
else:
raise ValueError(f"`?` must be at the end: {rule}")
elif ch == "*":
if self.slice_: # The * after & is a slice
continue
if i == last_pos:
self.seq = True
else:
raise ValueError(f"`*` must be at the end: {rule}")
elif ch == "&":
if i == 0 and rule.endswith("*"):
self.slice_ = True
else:
raise ValueError(
f"`&` must be at the start and end with `*`: {rule}"
)
else:
self.name += ch
if self.optional and (self.seq or self.slice_):
raise ValueError(f"optional field cannot be sequence or slice: {rule}")
# ------------------------------------------------------------------------------
# Preamble
def write_preamble(out: list[str]) -> None:
out.append("""
// This is a generated file. Don't modify it by hand!
// Run `crates/ruff_python_ast/generate.py` to re-generate the file.
use crate::name::Name;
use crate::visitor::source_order::SourceOrderVisitor;
""")
# ------------------------------------------------------------------------------
# Owned enum
def write_owned_enum(out: list[str], ast: Ast) -> None:
"""
Create an enum for each group that contains an owned copy of a syntax node.
```rust
pub enum TypeParam {
TypeVar(TypeParamTypeVar),
TypeVarTuple(TypeParamTypeVarTuple),
...
}
```
Also creates:
- `impl Ranged for TypeParam`
- `impl HasNodeIndex for TypeParam`
- `TypeParam::visit_source_order`
- `impl From<TypeParamTypeVar> for TypeParam`
- `impl Ranged for TypeParamTypeVar`
- `impl HasNodeIndex for TypeParamTypeVar`
- `fn TypeParam::is_type_var() -> bool`
If the `add_suffix_to_is_methods` group option is true, then the
`is_type_var` method will be named `is_type_var_type_param`.
"""
for group in ast.groups:
out.append("")
if group.doc is not None:
write_rustdoc(out, group.doc)
out.append("#[derive(Clone, Debug, PartialEq)]")
out.append('#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]')
out.append(f"pub enum {group.owned_enum_ty} {{")
for node in group.nodes:
out.append(f"{node.variant}({node.ty}),")
out.append("}")
for node in group.nodes:
out.append(f"""
impl From<{node.ty}> for {group.owned_enum_ty} {{
fn from(node: {node.ty}) -> Self {{
Self::{node.variant}(node)
}}
}}
""")
out.append(f"""
impl ruff_text_size::Ranged for {group.owned_enum_ty} {{
fn range(&self) -> ruff_text_size::TextRange {{
match self {{
""")
for node in group.nodes:
out.append(f"Self::{node.variant}(node) => node.range(),")
out.append("""
}
}
}
""")
out.append(f"""
impl crate::HasNodeIndex for {group.owned_enum_ty} {{
fn node_index(&self) -> &crate::AtomicNodeIndex {{
match self {{
""")
for node in group.nodes:
out.append(f"Self::{node.variant}(node) => node.node_index(),")
out.append("""
}
}
}
""")
out.append(
"#[allow(dead_code, clippy::match_wildcard_for_single_variants)]"
) # Not all is_methods are used
out.append(f"impl {group.name} {{")
for node in group.nodes:
is_name = to_snake_case(node.variant)
variant_name = node.variant
match_arm = f"Self::{variant_name}"
if group.add_suffix_to_is_methods:
is_name = to_snake_case(node.variant + group.name)
if len(group.nodes) > 1:
out.append(f"""
#[inline]
pub const fn is_{is_name}(&self) -> bool {{
matches!(self, {match_arm}(_))
}}
#[inline]
pub fn {is_name}(self) -> Option<{node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
_ => None,
}}
}}
#[inline]
pub fn expect_{is_name}(self) -> {node.ty} {{
match self {{
{match_arm}(val) => val,
_ => panic!("called expect on {{self:?}}"),
}}
}}
#[inline]
pub fn as_{is_name}_mut(&mut self) -> Option<&mut {node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
_ => None,
}}
}}
#[inline]
pub fn as_{is_name}(&self) -> Option<&{node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
_ => None,
}}
}}
""")
elif len(group.nodes) == 1:
out.append(f"""
#[inline]
pub const fn is_{is_name}(&self) -> bool {{
matches!(self, {match_arm}(_))
}}
#[inline]
pub fn {is_name}(self) -> Option<{node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
}}
}}
#[inline]
pub fn expect_{is_name}(self) -> {node.ty} {{
match self {{
{match_arm}(val) => val,
}}
}}
#[inline]
pub fn as_{is_name}_mut(&mut self) -> Option<&mut {node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
}}
}}
#[inline]
pub fn as_{is_name}(&self) -> Option<&{node.ty}> {{
match self {{
{match_arm}(val) => Some(val),
}}
}}
""")
out.append("}")
for node in ast.all_nodes:
out.append(f"""
impl ruff_text_size::Ranged for {node.ty} {{
fn range(&self) -> ruff_text_size::TextRange {{
self.range
}}
}}
""")
for node in ast.all_nodes:
out.append(f"""
impl crate::HasNodeIndex for {node.ty} {{
fn node_index(&self) -> &crate::AtomicNodeIndex {{
&self.node_index
}}
}}
""")
for group in ast.groups:
out.append(f"""
impl {group.owned_enum_ty} {{
#[allow(unused)]
pub(crate) fn visit_source_order<'a, V>(&'a self, visitor: &mut V)
where
V: crate::visitor::source_order::SourceOrderVisitor<'a> + ?Sized,
{{
match self {{
""")
for node in group.nodes:
out.append(
f"{group.owned_enum_ty}::{node.variant}(node) => node.visit_source_order(visitor),"
)
out.append("""
}
}
}
""")
# ------------------------------------------------------------------------------
# Ref enum
def write_ref_enum(out: list[str], ast: Ast) -> None:
"""
Create an enum for each group that contains a reference to a syntax node.
```rust
pub enum TypeParamRef<'a> {
TypeVar(&'a TypeParamTypeVar),
TypeVarTuple(&'a TypeParamTypeVarTuple),
...
}
```
Also creates:
- `impl<'a> From<&'a TypeParam> for TypeParamRef<'a>`
- `impl<'a> From<&'a TypeParamTypeVar> for TypeParamRef<'a>`
- `impl Ranged for TypeParamRef<'_>`
- `impl HasNodeIndex for TypeParamRef<'_>`
- `fn TypeParamRef::is_type_var() -> bool`
The name of each variant can be customized via the `variant` node option. If
the `add_suffix_to_is_methods` group option is true, then the `is_type_var`
method will be named `is_type_var_type_param`.
"""
for group in ast.groups:
out.append("")
if group.doc is not None:
write_rustdoc(out, group.doc)
out.append("""#[derive(Clone, Copy, Debug, PartialEq, is_macro::Is)]""")
out.append('#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]')
out.append(f"""pub enum {group.ref_enum_ty}<'a> {{""")
for node in group.nodes:
if group.add_suffix_to_is_methods:
is_name = to_snake_case(node.variant + group.name)
out.append(f'#[is(name = "{is_name}")]')
out.append(f"""{node.variant}(&'a {node.ty}),""")
out.append("}")
out.append(f"""
impl<'a> From<&'a {group.owned_enum_ty}> for {group.ref_enum_ty}<'a> {{
fn from(node: &'a {group.owned_enum_ty}) -> Self {{
match node {{
""")
for node in group.nodes:
out.append(
f"{group.owned_enum_ty}::{node.variant}(node) => {group.ref_enum_ty}::{node.variant}(node),"
)
out.append("""
}
}
}
""")
for node in group.nodes:
out.append(f"""
impl<'a> From<&'a {node.ty}> for {group.ref_enum_ty}<'a> {{
fn from(node: &'a {node.ty}) -> Self {{
Self::{node.variant}(node)
}}
}}
""")
out.append(f"""
impl ruff_text_size::Ranged for {group.ref_enum_ty}<'_> {{
fn range(&self) -> ruff_text_size::TextRange {{
match self {{
""")
for node in group.nodes:
out.append(f"Self::{node.variant}(node) => node.range(),")
out.append("""
}
}
}
""")
out.append(f"""
impl crate::HasNodeIndex for {group.ref_enum_ty}<'_> {{
fn node_index(&self) -> &crate::AtomicNodeIndex {{
match self {{
""")
for node in group.nodes:
out.append(f"Self::{node.variant}(node) => node.node_index(),")
out.append("""
}
}
}
""")
# ------------------------------------------------------------------------------
# AnyNodeRef
def write_anynoderef(out: list[str], ast: Ast) -> None:
"""
Create the AnyNodeRef type.
```rust
pub enum AnyNodeRef<'a> {
...
TypeParamTypeVar(&'a TypeParamTypeVar),
TypeParamTypeVarTuple(&'a TypeParamTypeVarTuple),
...
}
```
Also creates:
- `impl<'a> From<&'a TypeParam> for AnyNodeRef<'a>`
- `impl<'a> From<TypeParamRef<'a>> for AnyNodeRef<'a>`
- `impl<'a> From<&'a TypeParamTypeVarTuple> for AnyNodeRef<'a>`
- `impl Ranged for AnyNodeRef<'_>`
- `impl HasNodeIndex for AnyNodeRef<'_>`
- `fn AnyNodeRef::as_ptr(&self) -> std::ptr::NonNull<()>`
- `fn AnyNodeRef::visit_source_order(self, visitor &mut impl SourceOrderVisitor)`
"""
out.append("""
/// A flattened enumeration of all AST nodes.
#[derive(Copy, Clone, Debug, is_macro::Is, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub enum AnyNodeRef<'a> {
""")
for node in ast.all_nodes:
out.append(f"""{node.name}(&'a {node.ty}),""")
out.append("""
}
""")
for group in ast.groups:
out.append(f"""
impl<'a> From<&'a {group.owned_enum_ty}> for AnyNodeRef<'a> {{
fn from(node: &'a {group.owned_enum_ty}) -> AnyNodeRef<'a> {{
match node {{
""")
for node in group.nodes:
out.append(
f"{group.owned_enum_ty}::{node.variant}(node) => AnyNodeRef::{node.name}(node),"
)
out.append("""
}
}
}
""")
out.append(f"""
impl<'a> From<{group.ref_enum_ty}<'a>> for AnyNodeRef<'a> {{
fn from(node: {group.ref_enum_ty}<'a>) -> AnyNodeRef<'a> {{
match node {{
""")
for node in group.nodes:
out.append(
f"{group.ref_enum_ty}::{node.variant}(node) => AnyNodeRef::{node.name}(node),"
)
out.append("""
}
}
}
""")
# `as_*` methods to convert from `AnyNodeRef` to e.g. `ExprRef`
out.append(f"""
impl<'a> AnyNodeRef<'a> {{
pub fn as_{to_snake_case(group.ref_enum_ty)}(self) -> Option<{group.ref_enum_ty}<'a>> {{
match self {{
""")
for node in group.nodes:
out.append(
f"Self::{node.name}(node) => Some({group.ref_enum_ty}::{node.variant}(node)),"
)
out.append("""
_ => None,
}
}
}
""")
for node in ast.all_nodes:
out.append(f"""
impl<'a> From<&'a {node.ty}> for AnyNodeRef<'a> {{
fn from(node: &'a {node.ty}) -> AnyNodeRef<'a> {{
AnyNodeRef::{node.name}(node)
}}
}}
""")
out.append("""
impl ruff_text_size::Ranged for AnyNodeRef<'_> {
fn range(&self) -> ruff_text_size::TextRange {
match self {
""")
for node in ast.all_nodes:
out.append(f"""AnyNodeRef::{node.name}(node) => node.range(),""")
out.append("""
}
}
}
""")
out.append("""
impl crate::HasNodeIndex for AnyNodeRef<'_> {
fn node_index(&self) -> &crate::AtomicNodeIndex {
match self {
""")
for node in ast.all_nodes:
out.append(f"""AnyNodeRef::{node.name}(node) => node.node_index(),""")
out.append("""
}
}
}
""")
out.append("""
impl AnyNodeRef<'_> {
pub fn as_ptr(&self) -> std::ptr::NonNull<()> {
match self {
""")
for node in ast.all_nodes:
out.append(
f"AnyNodeRef::{node.name}(node) => std::ptr::NonNull::from(*node).cast(),"
)
out.append("""
}
}
}
""")
out.append("""
impl<'a> AnyNodeRef<'a> {
pub fn visit_source_order<'b, V>(self, visitor: &mut V)
where
V: crate::visitor::source_order::SourceOrderVisitor<'b> + ?Sized,
'a: 'b,
{
match self {
""")
for node in ast.all_nodes:
out.append(
f"AnyNodeRef::{node.name}(node) => node.visit_source_order(visitor),"
)
out.append("""
}
}
}
""")
for group in ast.groups:
out.append(f"""
impl AnyNodeRef<'_> {{
pub const fn is_{group.anynode_is_label}(self) -> bool {{
matches!(self,
""")
for i, node in enumerate(group.nodes):
if i > 0:
out.append("|")
out.append(f"""AnyNodeRef::{node.name}(_)""")
out.append("""
)
}
}
""")
# ------------------------------------------------------------------------------
# AnyRootNodeRef
def write_root_anynoderef(out: list[str], ast: Ast) -> None:
"""
Create the AnyRootNodeRef type.
```rust
pub enum AnyRootNodeRef<'a> {
...
TypeParam(&'a TypeParam),
...
}
```
Also creates:
- `impl<'a> From<&'a TypeParam> for AnyRootNodeRef<'a>`
- `impl<'a> TryFrom<AnyRootNodeRef<'a>> for &'a TypeParam`
- `impl<'a> TryFrom<AnyRootNodeRef<'a>> for &'a TypeParamVarTuple`
- `impl Ranged for AnyRootNodeRef<'_>`
- `impl HasNodeIndex for AnyRootNodeRef<'_>`
- `fn AnyRootNodeRef::visit_source_order(self, visitor &mut impl SourceOrderVisitor)`
"""
out.append("""
/// An enumeration of all AST nodes.
///
/// Unlike `AnyNodeRef`, this type does not flatten nested enums, so its variants only
/// consist of the "root" AST node types. This is useful as it exposes references to the
/// original enums, not just references to their inner values.
///
/// For example, `AnyRootNodeRef::Mod` contains a reference to the `Mod` enum, while
/// `AnyNodeRef` has top-level `AnyNodeRef::ModModule` and `AnyNodeRef::ModExpression`
/// variants.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub enum AnyRootNodeRef<'a> {
""")
for group in ast.groups:
out.append(f"""{group.name}(&'a {group.owned_enum_ty}),""")
for node in ast.ungrouped_nodes:
out.append(f"""{node.name}(&'a {node.ty}),""")
out.append("""
}
""")
for group in ast.groups:
out.append(f"""
impl<'a> From<&'a {group.owned_enum_ty}> for AnyRootNodeRef<'a> {{
fn from(node: &'a {group.owned_enum_ty}) -> AnyRootNodeRef<'a> {{
AnyRootNodeRef::{group.name}(node)
}}
}}
""")
out.append(f"""
impl<'a> TryFrom<AnyRootNodeRef<'a>> for &'a {group.owned_enum_ty} {{
type Error = ();
fn try_from(node: AnyRootNodeRef<'a>) -> Result<&'a {group.owned_enum_ty}, ()> {{
match node {{
AnyRootNodeRef::{group.name}(node) => Ok(node),
_ => Err(())
}}
}}
}}
""")
for node in group.nodes:
out.append(f"""
impl<'a> TryFrom<AnyRootNodeRef<'a>> for &'a {node.ty} {{
type Error = ();
fn try_from(node: AnyRootNodeRef<'a>) -> Result<&'a {node.ty}, ()> {{
match node {{
AnyRootNodeRef::{group.name}({group.owned_enum_ty}::{node.variant}(node)) => Ok(node),
_ => Err(())
}}
}}
}}
""")
for node in ast.ungrouped_nodes:
out.append(f"""
impl<'a> From<&'a {node.ty}> for AnyRootNodeRef<'a> {{
fn from(node: &'a {node.ty}) -> AnyRootNodeRef<'a> {{
AnyRootNodeRef::{node.name}(node)
}}
}}
""")
out.append(f"""
impl<'a> TryFrom<AnyRootNodeRef<'a>> for &'a {node.ty} {{
type Error = ();
fn try_from(node: AnyRootNodeRef<'a>) -> Result<&'a {node.ty}, ()> {{
match node {{
AnyRootNodeRef::{node.name}(node) => Ok(node),
_ => Err(())
}}
}}
}}
""")
out.append("""
impl ruff_text_size::Ranged for AnyRootNodeRef<'_> {
fn range(&self) -> ruff_text_size::TextRange {
match self {
""")
for group in ast.groups:
out.append(f"""AnyRootNodeRef::{group.name}(node) => node.range(),""")
for node in ast.ungrouped_nodes:
out.append(f"""AnyRootNodeRef::{node.name}(node) => node.range(),""")
out.append("""
}
}
}
""")
out.append("""
impl crate::HasNodeIndex for AnyRootNodeRef<'_> {
fn node_index(&self) -> &crate::AtomicNodeIndex {
match self {
""")
for group in ast.groups:
out.append(f"""AnyRootNodeRef::{group.name}(node) => node.node_index(),""")
for node in ast.ungrouped_nodes:
out.append(f"""AnyRootNodeRef::{node.name}(node) => node.node_index(),""")
out.append("""
}
}
}
""")
out.append("""
impl<'a> AnyRootNodeRef<'a> {
pub fn visit_source_order<'b, V>(self, visitor: &mut V)
where
V: crate::visitor::source_order::SourceOrderVisitor<'b> + ?Sized,
'a: 'b,
{
match self {
""")
for group in ast.groups:
out.append(
f"""AnyRootNodeRef::{group.name}(node) => node.visit_source_order(visitor),"""
)
for node in ast.ungrouped_nodes:
out.append(
f"""AnyRootNodeRef::{node.name}(node) => node.visit_source_order(visitor),"""
)
out.append("""
}
}
}
""")
# ------------------------------------------------------------------------------
# NodeKind
def write_nodekind(out: list[str], ast: Ast) -> None:
"""
Create the NodeKind type.
```rust
pub enum NodeKind {
...
TypeParamTypeVar,
TypeParamTypeVarTuple,
...
}
Also creates:
- `fn AnyNodeRef::kind(self) -> NodeKind`
```
"""
out.append("""
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum NodeKind {
""")
for node in ast.all_nodes:
out.append(f"""{node.name},""")
out.append("""
}
""")
out.append("""
impl AnyNodeRef<'_> {
pub const fn kind(self) -> NodeKind {
match self {
""")
for node in ast.all_nodes:
out.append(f"""AnyNodeRef::{node.name}(_) => NodeKind::{node.name},""")
out.append("""
}
}
}
""")
# ------------------------------------------------------------------------------
# Node structs
def write_node(out: list[str], ast: Ast) -> None:
group_names = [group.name for group in ast.groups]
for group in ast.groups:
for node in group.nodes:
if node.fields is None:
continue
if node.doc is not None:
write_rustdoc(out, node.doc)
out.append(
"#[derive(Clone, Debug, PartialEq"
+ "".join(f", {derive}" for derive in node.derives)
+ ")]"
)
out.append('#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]')
name = node.name
out.append(f"pub struct {name} {{")
out.append("pub node_index: crate::AtomicNodeIndex,")
out.append("pub range: ruff_text_size::TextRange,")
for field in node.fields:
field_str = f"pub {field.name}: "
ty = field.parsed_ty
rust_ty = f"{field.parsed_ty.name}"
if ty.name in types_requiring_crate_prefix:
rust_ty = f"crate::{rust_ty}"
if ty.slice_:
rust_ty = f"[{rust_ty}]"
if (ty.name in group_names or ty.slice_) and ty.seq is False:
rust_ty = f"Box<{rust_ty}>"
if ty.seq:
rust_ty = f"Vec<{rust_ty}>"
elif ty.optional:
rust_ty = f"Option<{rust_ty}>"
field_str += rust_ty + ","
out.append(field_str)
out.append("}")
out.append("")
# ------------------------------------------------------------------------------
# Source order visitor
def write_source_order(out: list[str], ast: Ast) -> None:
for group in ast.groups:
for node in group.nodes:
if node.fields is None or node.custom_source_order:
continue
name = node.name
fields_list = ""
body = ""
for field in node.fields:
if field.skip_source_order():
fields_list += f"{field.name}: _,\n"
else:
fields_list += f"{field.name},\n"
fields_list += "range: _,\n"
fields_list += "node_index: _,\n"
for field in node.fields_in_source_order():
visitor_name = (
type_to_visitor_function.get(
field.parsed_ty.inner, VisitorInfo("")
).name
or f"visit_{to_snake_case(field.parsed_ty.inner)}"
)
visits_sequence = type_to_visitor_function.get(
field.parsed_ty.inner, VisitorInfo("")
).accepts_sequence
if field.is_annotation:
visitor_name = "visit_annotation"
if field.parsed_ty.optional:
body += f"""
if let Some({field.name}) = {field.name} {{
visitor.{visitor_name}({field.name});
}}\n
"""
elif not visits_sequence and field.parsed_ty.seq:
body += f"""
for elm in {field.name} {{
visitor.{visitor_name}(elm);
}}
"""
else:
body += f"visitor.{visitor_name}({field.name});\n"
visitor_arg_name = "visitor"
if len(node.fields_in_source_order()) == 0:
visitor_arg_name = "_"
out.append(f"""
impl {name} {{
pub(crate) fn visit_source_order<'a, V>(&'a self, {visitor_arg_name}: &mut V)
where
V: SourceOrderVisitor<'a> + ?Sized,
{{
let {name} {{
{fields_list}
}} = self;
{body}
}}
}}
""")
# ------------------------------------------------------------------------------
# Format and write output
def generate(ast: Ast) -> list[str]:
out = []
write_preamble(out)
write_owned_enum(out, ast)
write_ref_enum(out, ast)
write_anynoderef(out, ast)
write_root_anynoderef(out, ast)
write_nodekind(out, ast)
write_node(out, ast)
write_source_order(out, ast)
return out
def write_output(root: Path, out: list[str]) -> None:
out_path = root.joinpath("crates", "ruff_python_ast", "src", "generated.rs")
out_path.write_text(rustfmt("\n".join(out)))
# ------------------------------------------------------------------------------
# Main
def main() -> None:
root = Path(
check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip()
)
ast = load_ast(root)
out = generate(ast)
write_output(root, out)
if __name__ == "__main__":
main()
| FieldType |
python | huggingface__transformers | tests/models/dinov3_convnext/test_modeling_dinov3_convnext.py | {
"start": 5456,
"end": 9071
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as ConvNext does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (DINOv3ConvNextModel,) if is_torch_available() else ()
pipeline_model_mapping = {"image-feature-extraction": DINOv3ConvNextModel} if is_torch_available() else {}
test_resize_embeddings = False
has_attentions = False
test_torch_exportable = True
def setUp(self):
self.model_tester = DINOv3ConvNextModelTester(self)
self.config_tester = ConfigTester(
self,
config_class=DINOv3ConvNextConfig,
has_text_modality=False,
hidden_size=37,
common_properties=["num_channels", "hidden_sizes"],
)
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(reason="DINOv3ConvNext does not use inputs_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="DINOv3ConvNext does not support input and output embeddings")
def test_model_get_set_embeddings(self):
pass
@unittest.skip(reason="DINOv3ConvNext does not use feedforward chunking")
def test_feed_forward_chunking(self):
pass
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_backbone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*config_and_inputs)
def test_hidden_states_output(self):
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
self.assertEqual(len(hidden_states), 5)
# DINOv3ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[1].shape[-2:]),
[self.model_tester.image_size // 4, self.model_tester.image_size // 4],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
check_hidden_states_output(inputs_dict, config, model_class)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
check_hidden_states_output(inputs_dict, config, model_class)
@slow
def test_model_from_pretrained(self):
model_name = "facebook/dinov3-convnext-tiny-pretrain-lvd1689m"
model = DINOv3ConvNextModel.from_pretrained(model_name)
self.assertIsNotNone(model)
@unittest.skip(reason="DINOv3ConvNext does not retain grads for first hidden state (original pixel_values)")
def test_retain_grad_hidden_states_attentions(self):
pass
# We will verify our results on an image of cute cats
def prepare_img():
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
return image
@require_torch
@require_vision
| DINOv3ConvNextModelTest |
python | walkccc__LeetCode | solutions/1822. Sign of the Product of an Array/1822.py | {
"start": 0,
"end": 190
} | class ____:
def arraySign(self, nums: list[int]) -> int:
sign = 1
for num in nums:
if num == 0:
return 0
if num < 0:
sign = -sign
return sign
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 572365,
"end": 572956
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("ReactorEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.types.list_of("Reactor"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| ReactorConnection |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 5369,
"end": 5512
} | class ____:
"""Class for minimal repo."""
columns = []
@classmethod
def cls_method(cls) -> None:
pass
# end
# E301
| Class |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/asset_execution_context.py | {
"start": 3526,
"end": 22405
} | class ____:
def __init__(self, op_execution_context: OpExecutionContext) -> None:
self._op_execution_context = check.inst_param(
op_execution_context, "op_execution_context", OpExecutionContext
)
self._step_execution_context = self._op_execution_context._step_execution_context # noqa: SLF001
@staticmethod
def get() -> "AssetExecutionContext":
from dagster._core.execution.context.asset_check_execution_context import (
AssetCheckExecutionContext,
)
from dagster._core.execution.context.compute import current_execution_context
ctx = current_execution_context.get()
if ctx is None:
raise DagsterInvariantViolationError("No current AssetExecutionContext in scope.")
if isinstance(ctx, AssetCheckExecutionContext):
raise DagsterInvariantViolationError(
"Can't use AssetExecutionContext.get() in the context of an "
"AssetCheckExecutionContext. Use AssetCheckExecutionContext.get() instead."
)
return ctx
@property
def op_execution_context(self) -> OpExecutionContext:
return self._op_execution_context
####### Top-level properties/methods on AssetExecutionContext
@public
@property
def log(self) -> DagsterLogManager:
"""The log manager available in the execution context. Logs will be viewable in the Dagster UI.
Returns: DagsterLogManager.
Example:
.. code-block:: python
@asset
def logger(context):
context.log.info("Info level message")
"""
return self.op_execution_context.log
@public
@property
def pdb(self) -> ForkedPdb:
"""Gives access to pdb debugging from within the asset. Materializing the asset via the
Dagster UI or CLI will enter the pdb debugging context in the process used to launch the UI or
run the CLI.
Returns: dagster.utils.forked_pdb.ForkedPdb
Example:
.. code-block:: python
@asset
def debug(context):
context.pdb.set_trace()
"""
return self.op_execution_context.pdb
@property
def run(self) -> DagsterRun:
"""The DagsterRun object corresponding to the execution. Information like run_id,
run configuration, and the assets selected for materialization can be found on the DagsterRun.
"""
return self.op_execution_context.run
@public
@property
def job_def(self) -> JobDefinition:
"""The definition for the currently executing job. Information like the job name, and job tags
can be found on the JobDefinition.
Returns: JobDefinition.
"""
return self.op_execution_context.job_def
@property
def repository_def(self) -> RepositoryDefinition:
"""RepositoryDefinition: The Dagster repository for the currently executing job."""
return self.op_execution_context.repository_def
######## Deprecated methods
@deprecated(**_get_deprecation_kwargs("dagster_run"))
@property
@_copy_docs_from_op_execution_context
def dagster_run(self) -> DagsterRun:
return self.op_execution_context.dagster_run
@deprecated(**_get_deprecation_kwargs("run_id"))
@property
@_copy_docs_from_op_execution_context
def run_id(self) -> str:
return self.op_execution_context.run_id
@deprecated(**_get_deprecation_kwargs("run_config"))
@property
@_copy_docs_from_op_execution_context
def run_config(self) -> Mapping[str, object]:
return self.op_execution_context.run_config
@deprecated(**_get_deprecation_kwargs("run_tags"))
@property
@_copy_docs_from_op_execution_context
def run_tags(self) -> Mapping[str, str]:
return self.op_execution_context.run_tags
@deprecated(**_get_deprecation_kwargs("has_tag"))
@public
@_copy_docs_from_op_execution_context
def has_tag(self, key: str) -> bool:
return self.op_execution_context.has_tag(key)
@deprecated(**_get_deprecation_kwargs("get_tag"))
@public
@_copy_docs_from_op_execution_context
def get_tag(self, key: str) -> Optional[str]:
return self.op_execution_context.get_tag(key)
@deprecated(**_get_deprecation_kwargs("get_op_execution_context"))
def get_op_execution_context(self) -> "OpExecutionContext":
return self.op_execution_context
@deprecated(**_get_deprecation_kwargs("asset_partition_key_for_output"))
@public
@_copy_docs_from_op_execution_context
def asset_partition_key_for_output(self, output_name: str = "result") -> str:
return self.op_execution_context.asset_partition_key_for_output(output_name=output_name)
@deprecated(**_get_deprecation_kwargs("asset_partitions_time_window_for_output"))
@public
@_copy_docs_from_op_execution_context
def asset_partitions_time_window_for_output(self, output_name: str = "result") -> TimeWindow:
return self.op_execution_context.asset_partitions_time_window_for_output(output_name)
@deprecated(**_get_deprecation_kwargs("asset_partition_key_range_for_output"))
@public
@_copy_docs_from_op_execution_context
def asset_partition_key_range_for_output(
self, output_name: str = "result"
) -> PartitionKeyRange:
return self.op_execution_context.asset_partition_key_range_for_output(output_name)
@deprecated(**_get_deprecation_kwargs("asset_partitions_def_for_output"))
@public
@_copy_docs_from_op_execution_context
def asset_partitions_def_for_output(self, output_name: str = "result") -> PartitionsDefinition:
return self.op_execution_context.asset_partitions_def_for_output(output_name=output_name)
@deprecated(**_get_deprecation_kwargs("asset_partition_keys_for_output"))
@public
@_copy_docs_from_op_execution_context
def asset_partition_keys_for_output(self, output_name: str = "result") -> Sequence[str]:
return self.op_execution_context.asset_partition_keys_for_output(output_name=output_name)
@deprecated(**_get_deprecation_kwargs("op_config"))
@public
@property
@_copy_docs_from_op_execution_context
def op_config(self) -> Any:
return self.op_execution_context.op_config
@deprecated(**_get_deprecation_kwargs("node_handle"))
@property
@_copy_docs_from_op_execution_context
def node_handle(self) -> NodeHandle:
return self.op_execution_context.node_handle
@deprecated(**_get_deprecation_kwargs("op_handle"))
@property
@_copy_docs_from_op_execution_context
def op_handle(self) -> NodeHandle:
return self.op_execution_context.op_handle
@deprecated(**_get_deprecation_kwargs("op"))
@property
@_copy_docs_from_op_execution_context
def op(self) -> Node:
return self.op_execution_context.op
@deprecated(**_get_deprecation_kwargs("get_mapping_key"))
@public
@_copy_docs_from_op_execution_context
def get_mapping_key(self) -> Optional[str]:
return self.op_execution_context.get_mapping_key()
@deprecated(**_get_deprecation_kwargs("selected_output_names"))
@public
@property
@_copy_docs_from_op_execution_context
def selected_output_names(self) -> AbstractSet[str]:
return self.op_execution_context.selected_output_names
########## pass-through to op context
#### op related
@property
@_copy_docs_from_op_execution_context
def retry_number(self):
return self.op_execution_context.retry_number
@_copy_docs_from_op_execution_context
def describe_op(self) -> str:
return self.op_execution_context.describe_op()
@public
@property
@_copy_docs_from_op_execution_context
def op_def(self) -> OpDefinition:
return self.op_execution_context.op_def
#### job related
@public
@property
@_copy_docs_from_op_execution_context
def job_name(self) -> str:
return self.op_execution_context.job_name
#### asset related
@public
@property
@_copy_docs_from_op_execution_context
def asset_key(self) -> AssetKey:
return self.op_execution_context.asset_key
@public
@property
@_copy_docs_from_op_execution_context
def has_assets_def(self) -> bool:
return self.op_execution_context.has_assets_def
@public
@property
@_copy_docs_from_op_execution_context
def assets_def(self) -> AssetsDefinition:
return self.op_execution_context.assets_def
@public
@_copy_docs_from_op_execution_context
def asset_key_for_output(self, output_name: str = "result") -> AssetKey:
return self.op_execution_context.asset_key_for_output(output_name=output_name)
@public
@_copy_docs_from_op_execution_context
def output_for_asset_key(self, asset_key: AssetKey) -> str:
return self.op_execution_context.output_for_asset_key(asset_key=asset_key)
@public
@_copy_docs_from_op_execution_context
def asset_key_for_input(self, input_name: str) -> AssetKey:
return self.op_execution_context.asset_key_for_input(input_name=input_name)
@public
@property
@_copy_docs_from_op_execution_context
def selected_asset_keys(self) -> AbstractSet[AssetKey]:
return self.op_execution_context.selected_asset_keys
#### execution related
@public
@property
@_copy_docs_from_op_execution_context
def instance(self) -> DagsterInstance:
return self.op_execution_context.instance
@property
@_copy_docs_from_op_execution_context
def step_launcher(self) -> Optional[StepLauncher]:
return self.op_execution_context.step_launcher
@_copy_docs_from_op_execution_context
def get_step_execution_context(self) -> StepExecutionContext:
return self.op_execution_context.get_step_execution_context()
#### partition_related
@public
@property
@_copy_docs_from_op_execution_context
def has_partition_key(self) -> bool:
return self.op_execution_context.has_partition_key
@public
@property
@_copy_docs_from_op_execution_context
def partition_key(self) -> str:
return self.op_execution_context.partition_key
@public
@property
@_copy_docs_from_op_execution_context
def partition_keys(self) -> Sequence[str]:
return self.op_execution_context.partition_keys
@public
@property
@_copy_docs_from_op_execution_context
def has_partition_key_range(self) -> bool:
return self.op_execution_context.has_partition_key_range
@deprecated(breaking_version="2.0", additional_warn_text="Use `partition_key_range` instead.")
@public
@property
@_copy_docs_from_op_execution_context
def asset_partition_key_range(self) -> PartitionKeyRange:
return self.op_execution_context.asset_partition_key_range
@public
@property
@_copy_docs_from_op_execution_context
def partition_key_range(self) -> PartitionKeyRange:
return self.op_execution_context.partition_key_range
@public
@property
@_copy_docs_from_op_execution_context
def partition_time_window(self) -> TimeWindow:
return self.op_execution_context.partition_time_window
@public
@_copy_docs_from_op_execution_context
def asset_partition_key_range_for_input(self, input_name: str) -> PartitionKeyRange:
return self.op_execution_context.asset_partition_key_range_for_input(input_name)
@public
@_copy_docs_from_op_execution_context
def asset_partition_key_for_input(self, input_name: str) -> str:
return self.op_execution_context.asset_partition_key_for_input(input_name)
@public
@_copy_docs_from_op_execution_context
def asset_partitions_def_for_input(self, input_name: str) -> PartitionsDefinition:
return self.op_execution_context.asset_partitions_def_for_input(input_name=input_name)
@public
@_copy_docs_from_op_execution_context
def asset_partition_keys_for_input(self, input_name: str) -> Sequence[str]:
return self.op_execution_context.asset_partition_keys_for_input(input_name=input_name)
@public
@_copy_docs_from_op_execution_context
def asset_partitions_time_window_for_input(self, input_name: str = "result") -> TimeWindow:
return self.op_execution_context.asset_partitions_time_window_for_input(input_name)
#### Event log related
@_copy_docs_from_op_execution_context
def has_events(self) -> bool:
return self.op_execution_context.has_events()
@_copy_docs_from_op_execution_context
def consume_events(self) -> Iterator[DagsterEvent]:
yield from self.op_execution_context.consume_events()
@public
@_copy_docs_from_op_execution_context
def log_event(self, event: UserEvent) -> None:
return self.op_execution_context.log_event(event)
#### metadata related
@public
@_copy_docs_from_op_execution_context
def add_output_metadata(
self,
metadata: Mapping[str, Any],
output_name: Optional[str] = None,
mapping_key: Optional[str] = None,
) -> None:
return self.op_execution_context.add_output_metadata(
metadata=metadata,
output_name=output_name,
mapping_key=mapping_key,
)
@public
def add_asset_metadata(
self,
metadata: Mapping[str, Any],
asset_key: Optional[CoercibleToAssetKey] = None,
partition_key: Optional[str] = None,
) -> None:
"""Add metadata to an asset materialization event. This metadata will be
available in the Dagster UI.
Args:
metadata (Mapping[str, Any]): The metadata to add to the asset
materialization event.
asset_key (Optional[CoercibleToAssetKey]): The asset key to add metadata to.
Does not need to be provided if only one asset is currently being
materialized.
partition_key (Optional[str]): The partition key to add metadata to, if
applicable. Should not be provided on non-partitioned assets. If not
provided on a partitioned asset, the metadata will be added to all
partitions of the asset currently being materialized.
Examples:
Adding metadata to the asset materialization event for a single asset:
.. code-block:: python
import dagster as dg
@dg.asset
def my_asset(context):
# Add metadata
context.add_asset_metadata({"key": "value"})
Adding metadata to the asset materialization event for a particular partition of a partitioned asset:
.. code-block:: python
import dagster as dg
@dg.asset(partitions_def=dg.StaticPartitionsDefinition(["a", "b"]))
def my_asset(context):
# Adds metadata to all partitions currently being materialized, since no
# partition is specified.
context.add_asset_metadata({"key": "value"})
for partition_key in context.partition_keys:
# Add metadata only to the event for partition "a"
if partition_key == "a":
context.add_asset_metadata({"key": "value"}, partition_key=partition_key)
Adding metadata to the asset materialization event for a particular asset in a multi-asset.
.. code-block:: python
import dagster as dg
@dg.multi_asset(specs=[dg.AssetSpec("asset1"), dg.AssetSpec("asset2")])
def my_multi_asset(context):
# Add metadata to the materialization event for "asset1"
context.add_asset_metadata({"key": "value"}, asset_key="asset1")
# THIS line will fail since asset key is not specified:
context.add_asset_metadata({"key": "value"})
"""
self._step_execution_context.add_asset_metadata(
metadata=metadata,
asset_key=asset_key,
partition_key=partition_key,
)
@_copy_docs_from_op_execution_context
def get_output_metadata(
self,
output_name: str,
mapping_key: Optional[str] = None,
) -> Optional[Mapping[str, Any]]:
return self.op_execution_context.get_output_metadata(
output_name=output_name,
mapping_key=mapping_key,
)
#### asset check related
@public
@property
@_copy_docs_from_op_execution_context
def selected_asset_check_keys(self) -> AbstractSet[AssetCheckKey]:
return self.op_execution_context.selected_asset_check_keys
#### data lineage related
@public
@_copy_docs_from_op_execution_context
def get_asset_provenance(self, asset_key: AssetKey) -> Optional[DataProvenance]:
return self.op_execution_context.get_asset_provenance(asset_key=asset_key)
@_copy_docs_from_op_execution_context
def set_data_version(self, asset_key: AssetKey, data_version: DataVersion) -> None:
return self.op_execution_context.set_data_version(
asset_key=asset_key, data_version=data_version
)
# misc
@public
@property
@_copy_docs_from_op_execution_context
def resources(self) -> Any:
return self.op_execution_context.resources
@property
@_copy_docs_from_op_execution_context
def is_subset(self):
return self.op_execution_context.is_subset
# In this mode no conversion is done on returned values and missing but expected outputs are not
# allowed.
@property
@_copy_docs_from_op_execution_context
def requires_typed_event_stream(self) -> bool:
return self.op_execution_context.requires_typed_event_stream
@property
@_copy_docs_from_op_execution_context
def typed_event_stream_error_message(self) -> Optional[str]:
return self.op_execution_context.typed_event_stream_error_message
@_copy_docs_from_op_execution_context
def set_requires_typed_event_stream(self, *, error_message: Optional[str] = None) -> None:
self.op_execution_context.set_requires_typed_event_stream(error_message=error_message)
@_copy_docs_from_op_execution_context
def load_asset_value(
self,
asset_key: AssetKey,
*,
python_type: Optional[type] = None,
partition_key: Optional[str] = None,
) -> Any:
return self.op_execution_context.load_asset_value(
asset_key=asset_key,
python_type=python_type,
partition_key=partition_key,
)
| AssetExecutionContext |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 85408,
"end": 87294
} | class ____(type_spec.BatchableTypeSpec):
def __init__(self, mass, velocity):
self.shape = array_ops.broadcast_static_shape(
mass.shape, velocity.shape)
self.mass = mass
self.velocity = velocity
def _serialize(self):
return (self.mass, self.velocity)
@property
def value_type(self):
return Particle
@property
def _component_specs(self):
return (self.mass, self.velocity)
def _to_components(self, value):
return (value.mass, value.velocity)
def _from_components(self, components):
return Particle(*components)
def _pad_shape_to_full_rank(self, s):
"""Pad component shapes with 1's so all components have the same rank."""
return tensor_shape.TensorShape(
[1] * (self.shape.ndims - s.ndims)).concatenate(s)
def _batch(self, batch_size):
return ParticleSpec(
mass=tensor_spec.TensorSpec(
dtype=self.mass.dtype,
shape=tensor_shape.TensorShape([batch_size]).concatenate(
self._pad_shape_to_full_rank(self.mass.shape))),
velocity=tensor_spec.TensorSpec(
dtype=self.velocity.dtype,
shape=tensor_shape.TensorShape([batch_size]).concatenate(
self._pad_shape_to_full_rank(self.velocity.shape))))
def _unbatch(self):
return ParticleSpec(
tensor_spec.TensorSpec(dtype=self.mass.dtype,
shape=self.mass.shape[1:]),
tensor_spec.TensorSpec(dtype=self.velocity.dtype,
shape=self.velocity.shape[1:]))
def _to_tensor_list(self, value):
return [array_ops.reshape(
value.mass,
self._pad_shape_to_full_rank(value.mass.shape)),
array_ops.reshape(
value.velocity,
self._pad_shape_to_full_rank(value.velocity.shape))]
| ParticleSpec |
python | fluentpython__example-code-2e | 24-class-metaprog/tinyenums/nanoenum.py | {
"start": 830,
"end": 879
} | class ____(metaclass=NanoEnumMeta):
pass
| NanoEnum |
python | fluentpython__example-code | 06-dp-1class-func/classic_strategy.py | {
"start": 2054,
"end": 2228
} | class ____(ABC): # the Strategy: an Abstract Base Class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
| Promotion |
python | doocs__leetcode | solution/0400-0499/0459.Repeated Substring Pattern/Solution.py | {
"start": 0,
"end": 116
} | class ____:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).index(s, 1) < len(s)
| Solution |
python | jazzband__django-pipeline | pipeline/finders.py | {
"start": 1455,
"end": 1863
} | class ____(BaseFinder):
def find(self, path, **kwargs):
"""
Work out the uncached name of the file and look that up instead
"""
try:
start, _, extn = path.rsplit(".", 2)
except ValueError:
return []
path = ".".join((start, extn))
return find(path, **kwargs) or []
def list(self, *args):
return []
| CachedFileFinder |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_mcp_tool_param.py | {
"start": 550,
"end": 1051
} | class ____(TypedDict, total=False):
read_only: bool
"""Indicates whether or not a tool modifies data or is read-only.
If an MCP server is
[annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),
it will match this filter.
"""
tool_names: SequenceNotStr[str]
"""List of allowed tool names."""
AllowedTools: TypeAlias = Union[SequenceNotStr[str], AllowedToolsMcpToolFilter]
| AllowedToolsMcpToolFilter |
python | django__django | tests/custom_migration_operations/operations.py | {
"start": 1767,
"end": 1951
} | class ____(ArgsKwargsOperation):
def __init__(self, arg1, arg2, *, kwarg1, kwarg2):
super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2)
| ArgsAndKeywordOnlyArgsOperation |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_google.py | {
"start": 365,
"end": 1456
} | class ____(TestCase):
factory = RequestFactory()
google_dummy_requests = [
factory.get("/extensions/google/setup/"),
# Unsure how these requests are getting generated, but they shouldn't fail in the middleware
factory.get("/extensions/google/setup/null/"),
factory.get("/extensions/google/setup/null/api/0/organizations/"),
]
def get_response(self, request: HttpRequest) -> HttpResponse:
return HttpResponse(status=200, content="passthrough")
@responses.activate
def test_routing_all_to_control(self) -> None:
for request in self.google_dummy_requests:
parser = GoogleRequestParser(request=request, response_handler=self.get_response)
assert parser.get_integration_from_request() is None
response = parser.get_response()
assert isinstance(response, HttpResponse)
assert response.status_code == 200
assert response.content == b"passthrough"
assert len(responses.calls) == 0
assert_no_webhook_payloads()
| GoogleRequestParserTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/schedule_tests/test_business_logic.py | {
"start": 13374,
"end": 19850
} | class ____:
"""Test processing of schedule data structures.
This class tests pure functions and domain model functionality
without requiring external dependencies.
"""
def test_schedule_creation_with_all_fields(self, snapshot):
"""Test creating schedule with all possible fields."""
schedule = DgApiSchedule(
id="complete-schedule-xyz",
name="comprehensive_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 0 * * *",
pipeline_name="comprehensive_pipeline",
description="Comprehensive test schedule with all fields",
execution_timezone="America/Los_Angeles",
code_location_origin="test_location@test_repo",
next_tick_timestamp=1705311000.0,
)
# Test JSON serialization works correctly
result = schedule.model_dump_json(indent=2)
parsed = json.loads(result)
snapshot.assert_match(parsed)
def test_schedule_status_enum_values(self):
"""Test that all expected ScheduleStatus enum values are available."""
expected_statuses = ["RUNNING", "STOPPED"]
actual_statuses = [status.value for status in DgApiScheduleStatus]
assert set(actual_statuses) == set(expected_statuses)
def test_schedule_with_missing_optional_fields(self):
"""Test schedule creation with None values for optional fields."""
schedule = DgApiSchedule(
id="sparse-schedule-123",
name="sparse_schedule",
status=DgApiScheduleStatus.STOPPED,
cron_schedule="0 12 * * *",
pipeline_name="sparse_pipeline",
description=None,
execution_timezone=None,
code_location_origin=None,
next_tick_timestamp=None,
)
assert schedule.id == "sparse-schedule-123"
assert schedule.name == "sparse_schedule"
assert schedule.status == DgApiScheduleStatus.STOPPED
assert schedule.cron_schedule == "0 12 * * *"
assert schedule.pipeline_name == "sparse_pipeline"
assert schedule.description is None
assert schedule.execution_timezone is None
assert schedule.code_location_origin is None
assert schedule.next_tick_timestamp is None
def test_schedule_list_creation(self):
"""Test ScheduleList creation and basic functionality."""
schedules = [
DgApiSchedule(
id="schedule1",
name="first_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 0 * * *",
pipeline_name="first_pipeline",
),
DgApiSchedule(
id="schedule2",
name="second_schedule",
status=DgApiScheduleStatus.STOPPED,
cron_schedule="0 6 * * *",
pipeline_name="second_pipeline",
),
]
schedule_list = DgApiScheduleList(items=schedules, total=len(schedules))
assert len(schedule_list.items) == 2
assert schedule_list.total == 2
assert schedule_list.items[0].name == "first_schedule"
assert schedule_list.items[1].name == "second_schedule"
def test_schedule_timestamp_handling(self, snapshot):
"""Test schedule with various timestamp values."""
test_cases = [
# Normal timestamp
DgApiSchedule(
id="schedule1",
name="normal_timestamp",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 0 * * *",
pipeline_name="normal_pipeline",
next_tick_timestamp=1705311000.0,
),
# No timestamp
DgApiSchedule(
id="schedule2",
name="no_timestamp",
status=DgApiScheduleStatus.STOPPED,
cron_schedule="0 12 * * *",
pipeline_name="no_pipeline",
next_tick_timestamp=None,
),
# Future timestamp
DgApiSchedule(
id="schedule3",
name="future_timestamp",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 18 * * *",
pipeline_name="future_pipeline",
next_tick_timestamp=2000000000.0, # Far future
),
]
results = []
for schedule in test_cases:
# Test serialization
serialized = json.loads(schedule.model_dump_json())
results.append(serialized)
snapshot.assert_match(results)
def test_schedule_cron_patterns(self, snapshot):
"""Test schedules with various cron patterns."""
test_cases = [
# Daily at midnight
DgApiSchedule(
id="daily",
name="daily_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 0 * * *",
pipeline_name="daily_pipeline",
),
# Hourly
DgApiSchedule(
id="hourly",
name="hourly_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 * * * *",
pipeline_name="hourly_pipeline",
),
# Every 15 minutes
DgApiSchedule(
id="frequent",
name="frequent_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="*/15 * * * *",
pipeline_name="frequent_pipeline",
),
# Weekly on Monday at 9am
DgApiSchedule(
id="weekly",
name="weekly_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 9 * * 1",
pipeline_name="weekly_pipeline",
),
# Monthly on 1st at midnight
DgApiSchedule(
id="monthly",
name="monthly_schedule",
status=DgApiScheduleStatus.RUNNING,
cron_schedule="0 0 1 * *",
pipeline_name="monthly_pipeline",
),
]
results = []
for schedule in test_cases:
serialized = json.loads(schedule.model_dump_json())
results.append(serialized)
snapshot.assert_match(results)
| TestScheduleDataProcessing |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/project_preprod_artifact_install_details.py | {
"start": 1020,
"end": 4414
} | class ____(PreprodArtifactEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self,
request: Request,
project: Project,
head_artifact_id: int,
head_artifact: PreprodArtifact,
) -> HttpResponseBase:
try:
analytics.record(
PreprodArtifactApiInstallDetailsEvent(
organization_id=project.organization_id,
project_id=project.id,
user_id=request.user.id,
artifact_id=str(head_artifact_id),
)
)
except Exception as e:
sentry_sdk.capture_exception(e)
# For iOS apps (XCARCHIVE), check code signature validity
if head_artifact.artifact_type == PreprodArtifact.ArtifactType.XCARCHIVE:
if (
not head_artifact.extras
or head_artifact.extras.get("is_code_signature_valid") is not True
):
return JsonResponse(
{
"is_code_signature_valid": False,
"code_signature_errors": (
head_artifact.extras.get("code_signature_errors", [])
if head_artifact.extras
else []
),
"platform": platform_from_artifact_type(head_artifact.artifact_type),
}
)
if not head_artifact.installable_app_file_id:
return Response({"error": "Installable file not available"}, status=404)
installable_url = get_download_url_for_artifact(head_artifact)
# Calculate total download count from all InstallablePreprodArtifact instances
total_download_count = (
InstallablePreprodArtifact.objects.filter(preprod_artifact=head_artifact).aggregate(
total_downloads=Sum("download_count")
)["total_downloads"]
or 0
)
# Build response based on artifact type
response_data: dict[str, Any] = {
"install_url": installable_url,
"platform": platform_from_artifact_type(head_artifact.artifact_type),
"download_count": total_download_count,
"release_notes": (
head_artifact.extras.get("release_notes") if head_artifact.extras else None
),
}
# Only include iOS-specific fields for iOS apps
if head_artifact.artifact_type == PreprodArtifact.ArtifactType.XCARCHIVE:
response_data.update(
{
"is_code_signature_valid": True,
"profile_name": (
head_artifact.extras["profile_name"]
if head_artifact.extras and "profile_name" in head_artifact.extras
else "unknown"
),
"codesigning_type": (
head_artifact.extras["codesigning_type"]
if head_artifact.extras and "codesigning_type" in head_artifact.extras
else "unknown"
),
}
)
response = JsonResponse(response_data)
return response
| ProjectPreprodInstallDetailsEndpoint |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 68676,
"end": 69100
} | class ____(BiffRecord):
"""
This record is part of the Calculation Settings Block.
It stores if iterations are allowed while calculating recursive formulas.
Record ITERATION, BIFF2-BIFF8:
Offset Size Contents
0 2 0 = Iterations off; 1 = Iterations on
"""
_REC_ID = 0x011
def __init__(self, iterations_on):
self._rec_data = pack('<H', iterations_on)
| IterationRecord |
python | bokeh__bokeh | src/bokeh/models/widgets/sliders.py | {
"start": 10379,
"end": 12179
} | class ____(NumericalSlider):
""" Slider-based datetime range selection widget. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@property
def value_as_datetime(self) -> tuple[datetime, datetime] | None:
''' Convenience property to retrieve the value tuple as a tuple of
datetime objects.
'''
if self.value is None:
return None
v1, v2 = self.value
if isinstance(v1, numbers.Number):
d1 = datetime.fromtimestamp(v1 / 1000, tz=timezone.utc)
else:
d1 = v1
if isinstance(v2, numbers.Number):
d2 = datetime.fromtimestamp(v2 / 1000, tz=timezone.utc)
else:
d2 = v2
return d1, d2
value = Required(Tuple(Datetime, Datetime), help="""
Initial or selected range.
""")
value_throttled = Readonly(Required(Tuple(Datetime, Datetime)), help="""
Initial or selected value, throttled to report only on mouseup.
""")
start = Required(Datetime, help="""
The minimum allowable value.
""")
end = Required(Datetime, help="""
The maximum allowable value.
""")
step = Int(default=3_600_000, help="""
The step between consecutive values, in units of milliseconds.
Default is one hour.
""")
format = Override(default="%d %b %Y %H:%M:%S")
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| DatetimeRangeSlider |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 40664,
"end": 45086
} | class ____(Response):
"""
Response of queues.get_all endpoint.
:param queues: Queues list
:type queues: Sequence[Queue]
"""
_service = "queues"
_action = "get_all"
_version = "2.13"
_schema = {
"definitions": {
"entry": {
"properties": {
"added": {
"description": "Time this entry was added to the queue",
"format": "date-time",
"type": ["string", "null"],
},
"task": {
"description": "Queued task ID",
"type": ["string", "null"],
},
},
"type": "object",
},
"metadata": {
"items": {
"properties": {
"key": {
"description": "The key uniquely identifying the metadata item inside the given entity",
"type": "string",
},
"type": {
"description": "The type of the metadata item",
"type": "string",
},
"value": {
"description": "The value stored in the metadata item",
"type": "string",
},
},
"type": "object",
},
"type": "array",
},
"queue": {
"properties": {
"company": {
"description": "Company id",
"type": ["string", "null"],
},
"created": {
"description": "Queue creation time",
"format": "date-time",
"type": ["string", "null"],
},
"entries": {
"description": "List of ordered queue entries",
"items": {"$ref": "#/definitions/entry"},
"type": ["array", "null"],
},
"id": {"description": "Queue id", "type": ["string", "null"]},
"metadata": {
"description": "Queue metadata",
"oneOf": [{"$ref": "#/definitions/metadata"}, {"type": "null"}],
},
"name": {"description": "Queue name", "type": ["string", "null"]},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"user": {
"description": "Associated user id",
"type": ["string", "null"],
},
},
"type": "object",
},
},
"properties": {
"queues": {
"description": "Queues list",
"items": {"$ref": "#/definitions/queue"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, queues: Optional[List[Any]] = None, **kwargs: Any) -> None:
super(GetAllResponse, self).__init__(**kwargs)
self.queues = queues
@schema_property("queues")
def queues(self) -> Optional[List[Any]]:
return self._property_queues
@queues.setter
def queues(self, value: Optional[List[Any]]) -> None:
if value is None:
self._property_queues = None
return
self.assert_isinstance(value, "queues", (list, tuple))
if any((isinstance(v, dict) for v in value)):
value = [Queue.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "queues", Queue, is_array=True)
self._property_queues = value
| GetAllResponse |
python | joke2k__faker | faker/providers/date_time/hr_HR/__init__.py | {
"start": 46,
"end": 881
} | class ____(DateTimeProvider):
def day_of_week(self) -> str:
day = self.date("%w")
DAY_NAMES = {
"0": "Nedjelja",
"1": "Ponedjeljak",
"2": "Utorak",
"3": "Srijeda",
"4": "Četvrtak",
"5": "Petak",
"6": "Subota",
}
return DAY_NAMES[day]
def month_name(self) -> str:
month = self.month()
MONTH_NAMES = {
"01": "Siječanj",
"02": "Veljača",
"03": "Ožujak",
"04": "Travanj",
"05": "Svibanj",
"06": "Lipanj",
"07": "Srpanj",
"08": "Kolovoz",
"09": "Rujan",
"10": "Listopad",
"11": "Studeni",
"12": "Prosinac",
}
return MONTH_NAMES[month]
| Provider |
python | sympy__sympy | sympy/stats/drv_types.py | {
"start": 6579,
"end": 8709
} | class ____(SingleDiscreteDistribution):
_argnames = ('a1', 'a2')
set = S.Naturals0
@staticmethod
def check(a1, a2):
_value_check(a1.is_nonnegative, 'Parameter a1 must be >= 0.')
_value_check(a2.is_nonnegative, 'Parameter a2 must be >= 0.')
def pdf(self, k):
a1, a2 = self.a1, self.a2
term1 = exp(-(a1 + a2))
j = Dummy("j", integer=True)
num = a1**(k - 2*j) * a2**j
den = factorial(k - 2*j) * factorial(j)
return term1 * Sum(num/den, (j, 0, k//2)).doit()
def _moment_generating_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(t) - 1)
term2 = a2 * (exp(2*t) - 1)
return exp(term1 + term2)
def _characteristic_function(self, t):
a1, a2 = self.a1, self.a2
term1 = a1 * (exp(I*t) - 1)
term2 = a2 * (exp(2*I*t) - 1)
return exp(term1 + term2)
def Hermite(name, a1, a2):
r"""
Create a discrete random variable with a Hermite distribution.
Explanation
===========
The density of the Hermite distribution is given by
.. math::
f(x):= e^{-a_1 -a_2}\sum_{j=0}^{\left \lfloor x/2 \right \rfloor}
\frac{a_{1}^{x-2j}a_{2}^{j}}{(x-2j)!j!}
Parameters
==========
a1 : A Positive number greater than equal to 0.
a2 : A Positive number greater than equal to 0.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Hermite, density, E, variance
>>> from sympy import Symbol
>>> a1 = Symbol("a1", positive=True)
>>> a2 = Symbol("a2", positive=True)
>>> x = Symbol("x")
>>> H = Hermite("H", a1=5, a2=4)
>>> density(H)(2)
33*exp(-9)/2
>>> E(H)
13
>>> variance(H)
21
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermite_distribution
"""
return rv(name, HermiteDistribution, a1, a2)
#-------------------------------------------------------------------------------
# Logarithmic distribution ------------------------------------------------------------
| HermiteDistribution |
python | run-llama__llama_index | llama-index-integrations/storage/index_store/llama-index-storage-index-store-couchbase/llama_index/storage/index_store/couchbase/base.py | {
"start": 184,
"end": 1519
} | class ____(KVIndexStore):
"""Couchbase Index store."""
def __init__(
self,
couchbase_kvstore: CouchbaseKVStore,
namespace: Optional[str] = None,
collection_suffix: Optional[str] = None,
) -> None:
"""
Initialize a CouchbaseIndexStore.
Args:
couchbase_kvstore (CouchbaseKVStore): Couchbase key-value store
namespace (str): namespace for the index store
collection_suffix (str): suffix for the collection name
"""
super().__init__(
couchbase_kvstore,
namespace=namespace,
collection_suffix=collection_suffix,
)
@classmethod
def from_couchbase_client(
cls,
client: Any,
bucket_name: str,
scope_name: str,
namespace: Optional[str] = None,
collection_suffix: Optional[str] = None,
async_client: Optional[Any] = None,
) -> "CouchbaseIndexStore":
"""Initialize a CouchbaseIndexStore from a Couchbase client."""
couchbase_kvstore = CouchbaseKVStore.from_couchbase_client(
client=client,
bucket_name=bucket_name,
scope_name=scope_name,
async_client=async_client,
)
return cls(couchbase_kvstore, namespace, collection_suffix)
| CouchbaseIndexStore |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 74294,
"end": 79504
} | class ____:
"""Settings for cuda backend, today this consists of cutlass"""
# CUDA arch to use for CUDA template kernel compilation.
# e.g. "70", "75", "80", "90", etc.
# When arch is None, Inductor uses torch.cuda.get_device_capability(0).
arch: Optional[str] = None
# CUDA version to use for CUDA template kernel compilation.
# e.g. "11.4", "12.1", etc.
# When version is None, Inductor uses torch.version.cuda.
version: Optional[str] = None
# Optimization level for the host compiler.
compile_opt_level: Literal["-O0", "-O1", "-O2", "-O3", "-OS"] = "-O1"
# Whether to enable device LTO (link-time-optimization).
enable_cuda_lto = False
# Whether to keep intermediate files dring compilation.
enable_ptxas_info = False
# Whether to enable debug info, e.g. line number, cutlass debug info.
enable_debug_info = False
# Whether to use fast math.
use_fast_math = False
# Path to the CUTLASS repo root directory.
# The default path only works under PyTorch local development environment.
cutlass_dir = os.path.realpath(
os.environ.get(
"TORCHINDUCTOR_CUTLASS_DIR",
os.path.join(os.path.dirname(torch.__file__), "../third_party/cutlass/"),
)
)
# Configures the maximum number of CUTLASS configs to profile in max_autotune.
# By default it's None, so that all CUTLASS configs are tuned.
# This is mainly used to reduce test time in CI.
cutlass_max_profiling_configs: Optional[int] = None
# The L2 swizzle values to consider when profiling CUTLASS configs in max_autotune.
cutlass_max_profiling_swizzle_options: list[int] = [1, 2, 4, 8]
# Whether to use CUTLASS EVT for epilogue fusion
cutlass_epilogue_fusion_enabled = (
os.environ.get("CUTLASS_EPILOGUE_FUSION", "0") == "1"
)
# Whether to only use TMA-compatible kernels in CUTLASS
cutlass_tma_only = False
# Path to CUDA NVCC.
# NVCC search order:
# 1) cuda_cxx set in this config
# 2) CUDACXX environment variable
# 3) CUDA_HOME environment variable
# 4) default system search PATH.
cuda_cxx: Optional[str] = None
# Minimum value of M*N*K to consider the CUTLASS backend for GEMM ops.
cutlass_backend_min_gemm_size: int = 1
# enable generation of inline standalone runner in CUDA CPP generated code
# which allows to compile the generated code into a standalone executable.
generate_test_runner: bool = (
os.environ.get("INDUCTOR_CUDA_BACKEND_GENERATE_TEST_RUNNER_CODE", "0") == "1"
)
# Keep only Cutlass op configs which contain this regular expression pattern
# Set this to "warpspecialized_cooperative_epi_tma" to enable only SM90 TMA Cutlass Kernels for large GEMMs
cutlass_op_allowlist_regex: Optional[str] = os.environ.get(
"TORCHINDUCTOR_CUTLASS_ALLOWLIST"
)
# Note: Names of Cutlass ops names can be obtained by calling
# op.configuration_name() on a Cutlass op instance, for example those
# returned from cutlass_utils.gen_ops() or the op argument passed to
# CUTLASSGemmTemplate.render(...)
# Filter Cutlass configs which contain this regular expression pattern
# Set this to "pingpong" to avoid numerical issues
# caused by the op ordering of the "pingpong" memory access
# pattern used by some Cutlass Kernels.
cutlass_op_denylist_regex: Optional[str] = os.environ.get(
"TORCHINDUCTOR_CUTLASS_DENYLIST"
)
# Non-negative integer which determines how many kernels are instantiated.
# 0 = 0000 generates the fewest kernels, 9999 generates all possible combinations.
# increasing first digit reduces schedule / mixed type pruning,
# increasing second digit generates more cluster sizes,
# increasing third digit generates more MMA multipliers,
# increasing fourth digit generates more instruction shapes.
cutlass_instantiation_level: str = os.environ.get(
"TORCHINDUCTOR_CUTLASS_INSTANTIATION_LEVEL", "0"
)
# use compile command to create kernel .cu and .so name
cutlass_hash_with_compile_cmd: bool = (
os.environ.get("TORCHINDUCTOR_CUTLASS_HASH_WITH_COMPILE_CMD", "0") == "1"
)
# Experimental. Prescreen top x configs before tuning on swizzle.
cutlass_prescreening: bool = (
os.environ.get("TORCHINDUCTOR_CUTLASS_PRESCREENING", "1") == "1"
)
# Specify which operations should use CUTLASS backend
# Comma-separated list like "mm,addmm,bmm", "all" for all operations, and "" for none.
# Acceptable operations: mm, int_mm, addmm, sparse_semi_structured_mm, bmm, scaled_mm
cutlass_enabled_ops: str = os.environ.get(
"TORCHINDUCTOR_CUTLASS_ENABLED_OPS", "all"
)
# Whether to consult the binary remote cache
use_binary_remote_cache: bool = True
# Whether to upload compiled kernels to remote cache
upload_to_binary_remote_cache: bool = False
# Whether to force upload if the key already exists
# Use this to overwrite and handle cache pollution
binary_remote_cache_force_write: bool = False
# Enable caching codegen of cuda templates.
enable_caching_codegen: bool = True
| cuda |
python | run-llama__llama_index | llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/extractor.py | {
"start": 571,
"end": 2378
} | class ____(Exception):
pass
@contextmanager
def time_limit(seconds: int) -> Any:
"""
Time limit context manager.
NOTE: copied from https://github.com/HazyResearch/evaporate.
"""
def signal_handler(signum: Any, frame: Any) -> Any:
raise TimeoutException("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
def get_function_field_from_attribute(attribute: str) -> str:
"""
Get function field from attribute.
NOTE: copied from https://github.com/HazyResearch/evaporate.
"""
return re.sub(r"[^A-Za-z0-9]", "_", attribute)
def extract_field_dicts(result: str, text_chunk: str) -> Set:
"""Extract field dictionaries."""
existing_fields = set()
result = result.split("---")[0].strip("\n")
results = result.split("\n")
results = [r.strip("-").strip() for r in results]
results = [r[2:].strip() if len(r) > 2 and r[1] == "." else r for r in results]
for result in results:
try:
field = result.split(": ")[0].strip(":")
value = ": ".join(result.split(": ")[1:])
except Exception:
print(f"Skipped: {result}")
continue
field_versions = [
field,
field.replace(" ", ""),
field.replace("-", ""),
field.replace("_", ""),
]
if not any(f.lower() in text_chunk.lower() for f in field_versions):
continue
if not value:
continue
field = field.lower().strip("-").strip("_").strip(" ").strip(":")
if field in existing_fields:
continue
existing_fields.add(field)
return existing_fields
# since we define globals below
| TimeoutException |
python | kamyu104__LeetCode-Solutions | Python/stone-game-v.py | {
"start": 33,
"end": 1286
} | class ____(object):
def stoneGameV(self, stoneValue):
"""
:type stoneValue: List[int]
:rtype: int
"""
n = len(stoneValue)
prefix = [0]
for v in stoneValue:
prefix.append(prefix[-1] + v)
mid = range(n)
dp = [[0]*n for _ in xrange(n)]
for i in xrange(n):
dp[i][i] = stoneValue[i]
max_score = 0
for l in xrange(2, n+1):
for i in xrange(n-l+1):
j = i+l-1
while prefix[mid[i]]-prefix[i] < prefix[j+1]-prefix[mid[i]]:
mid[i] += 1 # Time: O(n^2) in total
p = mid[i]
max_score = 0
if prefix[p]-prefix[i] == prefix[j+1]-prefix[p]:
max_score = max(dp[i][p-1], dp[j][p])
else:
if i <= p-2:
max_score = max(max_score, dp[i][p-2])
if p <= j:
max_score = max(max_score, dp[j][p])
dp[i][j] = max(dp[i][j-1], (prefix[j+1]-prefix[i]) + max_score)
dp[j][i] = max(dp[j][i+1], (prefix[j+1]-prefix[i]) + max_score)
return max_score
# Time: O(n^2)
# Space: O(n^2)
| Solution |
python | walkccc__LeetCode | solutions/1573. Number of Ways to Split a String/1573.py | {
"start": 0,
"end": 722
} | class ____:
def numWays(self, s: str) -> int:
MOD = 1_000_000_007
ones = s.count('1')
if ones % 3 != 0:
return 0
if ones == 0:
n = len(s)
return (n - 1) * (n - 2) // 2 % MOD
s1End = -1
s2Start = -1
s2End = -1
s3Start = -1
onesSoFar = 0
for i, c in enumerate(s):
if c == '1':
onesSoFar += 1
if s1End == -1 and onesSoFar == ones // 3:
s1End = i
elif s2Start == -1 and onesSoFar == ones // 3 + 1:
s2Start = i
if s2End == -1 and onesSoFar == ones // 3 * 2:
s2End = i
elif s3Start == -1 and onesSoFar == ones // 3 * 2 + 1:
s3Start = i
return (s2Start - s1End) * (s3Start - s2End) % MOD
| Solution |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 23088,
"end": 23876
} | class ____(TestRefererMiddleware):
settings = {"REFERRER_POLICY": CustomPythonOrgPolicy}
scenarii = [
("https://example.com/", "https://scrapy.org/", b"https://python.org/"),
("http://example.com/", "http://scrapy.org/", b"http://python.org/"),
("http://example.com/", "https://scrapy.org/", b"https://python.org/"),
("https://example.com/", "http://scrapy.org/", b"http://python.org/"),
(
"file:///home/path/to/somefile.html",
"https://scrapy.org/",
b"https://python.org/",
),
(
"file:///home/path/to/somefile.html",
"http://scrapy.org/",
b"http://python.org/",
),
]
# --- Tests using Request meta dict to set policy
| TestSettingsCustomPolicy |
python | kamyu104__LeetCode-Solutions | Python/finding-3-digit-even-numbers.py | {
"start": 1600,
"end": 3135
} | class ____(object):
def findEvenNumbers(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
k = 3
def backtracking(curr, dummy, result):
if len(curr) == k:
result.append(reduce(lambda x, y: x*10+y, curr))
return
node = dummy.right
while node:
if (not curr and node.val[0] == 0) or (len(curr) == k-1 and node.val[0]%2 != 0):
node = node.right
continue
node.val[1] -= 1
if node.val[1] == 0:
if node.left:
node.left.right = node.right
if node.right:
node.right.left = node.left
curr.append(node.val[0])
backtracking(curr, dummy, result)
curr.pop()
if node.val[1] == 0:
if node.left:
node.left.right = node
if node.right:
node.right.left = node
node.val[1] += 1
node = node.right
prev = dummy = Node()
for digit, cnt in sorted(map(list, collections.Counter(digits).iteritems())):
prev.right = Node(val=[digit, cnt], left=prev)
prev = prev.right
result = []
backtracking([], dummy, result)
return result
# Time: O(1) ~ O(nlogn), n is 10^3
# Space: O(1)
import collections
| Solution3 |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 2990,
"end": 3209
} | class ____(StringEnum):
NO_OWNERSHIP = enum.auto() # readable
USES = enum.auto() # writeable
INITIALIZES = enum.auto() # initializes
# base class for things that are the "result" of analysis
| ModuleOwnership |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-pebblo/llama_index/readers/pebblo/utility.py | {
"start": 1754,
"end": 2369
} | class ____(BaseModel):
"""
This class represents an AI application.
Args:
name (str): Name of the app.
owner (str): Owner of the app.
description (Optional[str]): Description of the app.
load_id (str): Unique load_id of the app instance.
runtime (Runtime): Runtime details of app.
framework (Framework): Framework details of the app
plugin_version (str): Plugin version used for the app.
"""
name: str
owner: str
description: Optional[str]
load_id: str
runtime: Runtime
framework: Framework
plugin_version: str
| App |
python | numba__numba | numba/tests/test_typedlist.py | {
"start": 37898,
"end": 40944
} | class ____(MemoryLeakMixin, TestCase):
def setUp(self):
super(TestListSort, self).setUp()
np.random.seed(0)
def make(self, ctor, data):
lst = ctor()
lst.extend(data)
return lst
def make_both(self, data):
return {
'py': self.make(list, data),
'nb': self.make(List, data),
}
def test_sort_no_args(self):
def udt(lst):
lst.sort()
return lst
for nelem in [13, 29, 127]:
my_lists = self.make_both(np.random.randint(0, nelem, nelem))
self.assertEqual(list(udt(my_lists['nb'])), udt(my_lists['py']))
def test_sort_all_args(self):
def udt(lst, key, reverse):
lst.sort(key=key, reverse=reverse)
return lst
possible_keys = [
lambda x: -x, # negative
lambda x: 1 / (1 + x), # make float
lambda x: (x, -x), # tuple
lambda x: x, # identity
]
possible_reverse = [True, False]
for key, reverse in product(possible_keys, possible_reverse):
my_lists = self.make_both(np.random.randint(0, 100, 23))
msg = "case for key={} reverse={}".format(key, reverse)
self.assertEqual(
list(udt(my_lists['nb'], key=key, reverse=reverse)),
udt(my_lists['py'], key=key, reverse=reverse),
msg=msg,
)
def test_sort_dispatcher_key(self):
def udt(lst, key):
lst.sort(key=key)
return lst
my_lists = self.make_both(np.random.randint(0, 100, 31))
py_key = lambda x: x + 1
nb_key = njit(lambda x: x + 1)
# test typedlist with jitted function
self.assertEqual(
list(udt(my_lists['nb'], key=nb_key)),
udt(my_lists['py'], key=py_key),
)
# test typedlist with and without jitted function
self.assertEqual(
list(udt(my_lists['nb'], key=nb_key)),
list(udt(my_lists['nb'], key=py_key)),
)
def test_sort_in_jit_w_lambda_key(self):
@njit
def udt(lst):
lst.sort(key=lambda x: -x)
return lst
lst = self.make(List, np.random.randint(0, 100, 31))
self.assertEqual(udt(lst), udt.py_func(lst))
def test_sort_in_jit_w_global_key(self):
@njit
def keyfn(x):
return -x
@njit
def udt(lst):
lst.sort(key=keyfn)
return lst
lst = self.make(List, np.random.randint(0, 100, 31))
self.assertEqual(udt(lst), udt.py_func(lst))
def test_sort_on_arrays(self):
@njit
def foo(lst):
lst.sort(key=lambda arr: np.sum(arr))
return lst
arrays = [np.random.random(3) for _ in range(10)]
my_lists = self.make_both(arrays)
self.assertEqual(
list(foo(my_lists['nb'])),
foo.py_func(my_lists['py']),
)
| TestListSort |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 98364,
"end": 98489
} | class ____(PythonPrinter):
def _print_Float(self, expr: sympy.Float) -> str:
return str(float(expr))
| SymExprPrinter |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 40120,
"end": 40389
} | class ____(Operator):
""" Decrement an upper a index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(1 - bi + _x, _x)
def __str__(self):
return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
| MeijerShiftB |
python | getsentry__sentry | src/sentry/deletions/defaults/group.py | {
"start": 6904,
"end": 7141
} | class ____(EventsBaseDeletionTask):
"""
Deletes nodestore data, EventAttachment and UserReports for requested groups.
This class uses the old Snuba deletion method.
"""
dataset = Dataset.Events
| ErrorEventsDeletionTask |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 46122,
"end": 47502
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: VitsConfig):
super().__init__()
self.attention = VitsAttention(config)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.feed_forward = VitsFeedForward(config)
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
padding_mask: torch.FloatTensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
):
residual = hidden_states
hidden_states, attn_weights = self.attention(
hidden_states=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
)
hidden_states = self.dropout(hidden_states)
hidden_states = self.layer_norm(residual + hidden_states)
residual = hidden_states
hidden_states = self.feed_forward(hidden_states, padding_mask)
hidden_states = self.dropout(hidden_states)
hidden_states = self.final_layer_norm(residual + hidden_states)
outputs = (hidden_states,)
if output_attentions:
outputs += (attn_weights,)
return outputs
| VitsEncoderLayer |
python | has2k1__plotnine | plotnine/themes/theme_538.py | {
"start": 140,
"end": 1088
} | class ____(theme_gray):
"""
Theme in the likeness of fivethirtyeight.com plots
Parameters
----------
base_size : int
Base font size. All text sizes are a scaled versions of
the base font size.
base_family : str
Base font family.
"""
def __init__(self, base_size=11, base_family="DejaVu Sans"):
super().__init__(base_size, base_family)
bgcolor = "#F0F0F0"
self += theme(
axis_ticks=element_blank(),
title=element_text(color="#3C3C3C"),
legend_background=element_rect(fill="none"),
panel_background=element_rect(fill=bgcolor),
panel_border=element_blank(),
panel_grid_major=element_line(color="#D5D5D5"),
panel_grid_minor=element_blank(),
plot_background=element_rect(fill=bgcolor, color=bgcolor, size=1),
strip_background=element_rect(size=0),
)
| theme_538 |
python | django__django | tests/custom_managers/models.py | {
"start": 1952,
"end": 2262
} | class ____(models.QuerySet):
# QuerySet with an __init__() method that takes an additional argument.
def __init__(
self, custom_optional_arg=None, model=None, query=None, using=None, hints=None
):
super().__init__(model=model, query=query, using=using, hints=hints)
| CustomInitQuerySet |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_bigtable.py | {
"start": 1341,
"end": 5315
} | class ____:
@pytest.mark.parametrize(
("missing_attribute", "project_id", "instance_id", "table_id"),
[
("instance_id", PROJECT_ID, "", TABLE_ID),
("table_id", PROJECT_ID, INSTANCE_ID, ""),
],
)
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.BigtableHook")
def test_empty_attribute(self, missing_attribute, project_id, instance_id, table_id, mock_hook):
with pytest.raises(AirflowException) as ctx:
BigtableTableReplicationCompletedSensor(
project_id=project_id,
instance_id=instance_id,
table_id=table_id,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
err = ctx.value
assert str(err) == f"Empty parameter: {missing_attribute}"
mock_hook.assert_not_called()
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.BigtableHook")
def test_wait_no_instance(self, mock_hook):
mock_hook.return_value.get_instance.return_value = None
op = BigtableTableReplicationCompletedSensor(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
assert not op.poke(None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.BigtableHook")
def test_wait_no_table(self, mock_hook):
mock_hook.return_value.get_instance.return_value = mock.Mock(Instance)
mock_hook.return_value.get_cluster_states_for_table.side_effect = mock.Mock(
side_effect=google.api_core.exceptions.NotFound("Table not found.")
)
op = BigtableTableReplicationCompletedSensor(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
assert not op.poke(None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.BigtableHook")
def test_wait_not_ready(self, mock_hook):
mock_hook.return_value.get_instance.return_value = mock.Mock(Instance)
mock_hook.return_value.get_cluster_states_for_table.return_value = {"cl-id": ClusterState(0)}
op = BigtableTableReplicationCompletedSensor(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
assert not op.poke(None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.BigtableHook")
def test_wait_ready(self, mock_hook):
mock_hook.return_value.get_instance.return_value = mock.Mock(Instance)
mock_hook.return_value.get_cluster_states_for_table.return_value = {"cl-id": ClusterState(4)}
op = BigtableTableReplicationCompletedSensor(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
assert op.poke(None)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
| BigtableWaitForTableReplicationTest |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 17137,
"end": 21685
} | class ____:
def test_setitem_new_child_node(self) -> None:
john = DataTree(name="john")
mary = DataTree(name="mary")
john["mary"] = mary
grafted_mary = john["mary"]
assert grafted_mary.parent is john
assert grafted_mary.name == "mary"
def test_setitem_unnamed_child_node_becomes_named(self) -> None:
john2 = DataTree(name="john2")
john2["sonny"] = DataTree()
assert john2["sonny"].name == "sonny"
def test_setitem_new_grandchild_node(self) -> None:
john = DataTree.from_dict({"/Mary/Rose": DataTree()})
new_rose = DataTree(dataset=xr.Dataset({"x": 0}))
john["Mary/Rose"] = new_rose
grafted_rose = john["Mary/Rose"]
assert grafted_rose.parent is john["/Mary"]
assert grafted_rose.name == "Rose"
def test_grafted_subtree_retains_name(self) -> None:
subtree = DataTree(name="original_subtree_name")
root = DataTree(name="root")
root["new_subtree_name"] = subtree
assert subtree.name == "original_subtree_name"
def test_setitem_new_empty_node(self) -> None:
john = DataTree(name="john")
john["mary"] = DataTree()
mary = john["mary"]
assert isinstance(mary, DataTree)
assert_identical(mary.to_dataset(), xr.Dataset())
def test_setitem_overwrite_data_in_node_with_none(self) -> None:
john = DataTree.from_dict({"/mary": xr.Dataset()}, name="john")
john["mary"] = DataTree()
assert_identical(john["mary"].to_dataset(), xr.Dataset())
john.dataset = xr.Dataset() # type: ignore[assignment,unused-ignore]
with pytest.raises(ValueError, match="has no name"):
john["."] = DataTree()
@pytest.mark.xfail(reason="assigning Datasets doesn't yet create new nodes")
def test_setitem_dataset_on_this_node(self) -> None:
data = xr.Dataset({"temp": [0, 50]})
results = DataTree(name="results")
results["."] = data
assert_identical(results.to_dataset(), data)
def test_setitem_dataset_as_new_node(self) -> None:
data = xr.Dataset({"temp": [0, 50]})
folder1 = DataTree(name="folder1")
folder1["results"] = data
assert_identical(folder1["results"].to_dataset(), data)
def test_setitem_dataset_as_new_node_requiring_intermediate_nodes(self) -> None:
data = xr.Dataset({"temp": [0, 50]})
folder1 = DataTree(name="folder1")
folder1["results/highres"] = data
assert_identical(folder1["results/highres"].to_dataset(), data)
def test_setitem_named_dataarray(self) -> None:
da = xr.DataArray(name="temp", data=[0, 50])
folder1 = DataTree(name="folder1")
folder1["results"] = da
expected = da.rename("results")
assert_equal(folder1["results"], expected)
def test_setitem_unnamed_dataarray(self) -> None:
data = xr.DataArray([0, 50])
folder1 = DataTree(name="folder1")
folder1["results"] = data
assert_equal(folder1["results"], data)
def test_setitem_variable(self) -> None:
var = xr.Variable(data=[0, 50], dims="x")
folder1 = DataTree(name="folder1")
folder1["results"] = var
assert_equal(folder1["results"], xr.DataArray(var))
def test_setitem_coerce_to_dataarray(self) -> None:
folder1 = DataTree(name="folder1")
folder1["results"] = 0
assert_equal(folder1["results"], xr.DataArray(0))
def test_setitem_add_new_variable_to_empty_node(self) -> None:
results = DataTree(name="results")
results["pressure"] = xr.DataArray(data=[2, 3])
assert "pressure" in results.dataset
results["temp"] = xr.Variable(data=[10, 11], dims=["x"])
assert "temp" in results.dataset
# What if there is a path to traverse first?
results_with_path = DataTree(name="results")
results_with_path["highres/pressure"] = xr.DataArray(data=[2, 3])
assert "pressure" in results_with_path["highres"].dataset
results_with_path["highres/temp"] = xr.Variable(data=[10, 11], dims=["x"])
assert "temp" in results_with_path["highres"].dataset
def test_setitem_dataarray_replace_existing_node(self) -> None:
t = xr.Dataset({"temp": [0, 50]})
results = DataTree(name="results", dataset=t)
p = xr.DataArray(data=[2, 3])
results["pressure"] = p
expected = t.assign(pressure=p)
assert_identical(results.to_dataset(), expected)
| TestSetItem |
python | doocs__leetcode | solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.py | {
"start": 95,
"end": 1295
} | class ____:
def __init__(self, nums):
n = len(nums)
self.nums = nums
self.tr = [Node() for _ in range(4 * n)]
self.build(1, 1, n)
def build(self, u, l, r):
self.tr[u].l = l
self.tr[u].r = r
if l == r:
self.tr[u].v = self.nums[l - 1]
return
mid = (l + r) >> 1
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
self.pushup(u)
def modify(self, u, x, v):
if self.tr[u].l == x and self.tr[u].r == x:
self.tr[u].v = v
return
mid = (self.tr[u].l + self.tr[u].r) >> 1
if x <= mid:
self.modify(u << 1, x, v)
else:
self.modify(u << 1 | 1, x, v)
self.pushup(u)
def query(self, u, l, r):
if self.tr[u].l >= l and self.tr[u].r <= r:
return self.tr[u].v
mid = (self.tr[u].l + self.tr[u].r) >> 1
v = 0
if l <= mid:
v += self.query(u << 1, l, r)
if r > mid:
v += self.query(u << 1 | 1, l, r)
return v
def pushup(self, u):
self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v
| SegmentTree |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 13977,
"end": 14160
} | class ____(_SimpleAutomotiveTestMixin):
"""Test vi_VN automotive provider methods"""
license_plate_pattern: Pattern = re.compile(r"\d{2}[ABCDĐEFGHKLMNPSTUVXYZ]-\d{5}")
| TestViVn |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/value_parsers.py | {
"start": 4400,
"end": 4956
} | class ____(ChoicesParser):
"""Composite argument parser for "{platform}/{version}" formatted choices."""
def __init__(self, choices: list[str]) -> None:
super().__init__(choices, conditions=MatchConditions.CHOICE | MatchConditions.ANY)
def parse(self, state: ParserState) -> t.Any:
"""Parse the input from the given state and return the result."""
value = super().parse(state)
if len(value.split('/')) != 2:
raise ParserError(f'invalid platform format: {value}')
return value
| PlatformParser |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/svd_op_test.py | {
"start": 12134,
"end": 13914
} | class ____(test.TestCase):
pass # Filled in below
def _GetSvdGradGradOpTest(dtype_, shape_, compute_uv_, full_matrices_):
@test_util.run_v1_only("b/120545219")
def Test(self):
np.random.seed(42)
a = np.random.uniform(low=-1.0, high=1.0, size=shape_).astype(dtype_)
if dtype_ in [np.complex64, np.complex128]:
a += 1j * np.random.uniform(
low=-1.0, high=1.0, size=shape_).astype(dtype_)
# Optimal stepsize for central difference is O(epsilon^{1/3}).
# See Equation (21) in:
# http://www.karenkopecky.net/Teaching/eco613614/Notes_NumericalDifferentiation.pdf
# TODO(rmlarsen): Move step size control to gradient checker.
epsilon = np.finfo(dtype_).eps
delta = 0.1 * epsilon**(1.0 / 3.0)
tol = 1e-5
with self.session():
tf_a = constant_op.constant(a)
if compute_uv_:
tf_s, tf_u, tf_v = _NormalizingSvd(tf_a, full_matrices_)
outputs = [tf_s, tf_u, tf_v]
else:
tf_s = linalg_ops.svd(tf_a, compute_uv=False)
outputs = [tf_s]
outputs_sums = [math_ops.reduce_sum(o) for o in outputs]
tf_func_outputs = math_ops.add_n(outputs_sums)
grad = gradients_impl.gradients(tf_func_outputs, tf_a)[0]
x_init = np.random.uniform(low=-1.0, high=1.0, size=shape_).astype(dtype_)
if dtype_ in [np.complex64, np.complex128]:
x_init += 1j * np.random.uniform(
low=-1.0, high=1.0, size=shape_).astype(dtype_)
theoretical, numerical = gradient_checker.compute_gradient(
tf_a,
tf_a.get_shape().as_list(),
grad,
grad.get_shape().as_list(),
x_init_value=x_init,
delta=delta)
self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)
return Test
| SvdGradGradOpTest |
python | apache__airflow | providers/slack/src/airflow/providers/slack/operators/slack.py | {
"start": 3972,
"end": 6123
} | class ____(SlackAPIOperator):
"""
Post messages to a Slack channel.
.. code-block:: python
slack = SlackAPIPostOperator(
task_id="post_hello",
dag=dag,
text="hello there!",
channel="#random",
)
:param channel: channel in which to post message on slack name (#general) or
ID (C12318391). (templated)
:param username: Username that airflow will be posting to Slack as. (templated)
:param text: message to send to slack. (templated)
:param icon_url: URL to icon used for this message
:param blocks: A list of blocks to send with the message. (templated)
See https://api.slack.com/reference/block-kit/blocks
:param attachments: (legacy) A list of attachments to send with the message. (templated)
See https://api.slack.com/docs/attachments
"""
template_fields: Sequence[str] = ("username", "text", "attachments", "blocks", "channel")
ui_color = "#FFBA40"
def __init__(
self,
channel: str = "#general",
username: str = "Airflow",
text: str = (
"No message has been set.\n"
"Here is a cat video instead\n"
"https://www.youtube.com/watch?v=J---aiyznGQ"
),
icon_url: str = (
"https://raw.githubusercontent.com/apache/airflow/main/airflow-core/src/airflow/ui/public/pin_100.png"
),
blocks: list | None = None,
attachments: list | None = None,
**kwargs,
) -> None:
super().__init__(method="chat.postMessage", **kwargs)
self.channel = channel
self.username = username
self.text = text
self.icon_url = icon_url
self.attachments = attachments or []
self.blocks = blocks or []
def construct_api_call_params(self) -> Any:
self.api_params = {
"channel": self.channel,
"username": self.username,
"text": self.text,
"icon_url": self.icon_url,
"attachments": json.dumps(self.attachments),
"blocks": json.dumps(self.blocks),
}
| SlackAPIPostOperator |
python | kamyu104__LeetCode-Solutions | Python/high-five.py | {
"start": 67,
"end": 510
} | class ____(object):
def highFive(self, items):
"""
:type items: List[List[int]]
:rtype: List[List[int]]
"""
min_heaps = collections.defaultdict(list)
for i, val in items:
heapq.heappush(min_heaps[i], val)
if len(min_heaps[i]) > 5:
heapq.heappop(min_heaps[i])
return [[i, sum(min_heaps[i]) // len(min_heaps[i])] for i in sorted(min_heaps)]
| Solution |
python | facebook__pyre-check | tools/upgrade/tests/upgrade_test.py | {
"start": 299,
"end": 1314
} | class ____(unittest.TestCase):
def test_filter_errors(self) -> None:
error7 = {
"line": 2,
"column": 4,
"path": "local.py",
"code": 7,
"name": "Kind",
"concise_description": "Error",
"ignore_error": False,
"external_to_global_root": False,
}
error0 = {
"line": 2,
"column": 2,
"path": "local.py",
"code": 0,
"name": "Unused ignore",
"concise_description": "Unused ignore",
"ignore_error": False,
"external_to_global_root": False,
}
pyre_errors = [error7, error0]
self.assertEqual(errors._filter_errors(pyre_errors, 44), [])
self.assertEqual(errors._filter_errors(pyre_errors, 7), [error7])
self.assertEqual(errors._filter_errors(pyre_errors, 0), [error0])
self.assertEqual(errors._filter_errors(pyre_errors, None), [error7, error0])
| FilterErrorTest |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/constructor.py | {
"start": 13816,
"end": 28327
} | class ____(BaseConstructor):
def construct_scalar(self, node):
# type: (Any) -> Any
if isinstance(node, MappingNode):
for key_node, value_node in node.value:
if key_node.tag == 'tag:yaml.org,2002:value':
return self.construct_scalar(value_node)
return BaseConstructor.construct_scalar(self, node)
def flatten_mapping(self, node):
# type: (Any) -> Any
"""
This implements the merge key feature http://yaml.org/type/merge.html
by inserting keys from the merge dict/list of dicts if not yet
available in this node
"""
merge = [] # type: List[Any]
index = 0
while index < len(node.value):
key_node, value_node = node.value[index]
if key_node.tag == 'tag:yaml.org,2002:merge':
if merge: # double << key
if self.allow_duplicate_keys:
del node.value[index]
index += 1
continue
args = [
'while constructing a mapping',
node.start_mark,
'found duplicate key "{}"'.format(key_node.value),
key_node.start_mark,
"""
To suppress this check see:
http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
""",
"""\
Duplicate keys will become an error in future releases, and are errors
by default when using the new API.
""",
]
if self.allow_duplicate_keys is None:
warnings.warn(DuplicateKeyFutureWarning(*args))
else:
raise DuplicateKeyError(*args)
del node.value[index]
if isinstance(value_node, MappingNode):
self.flatten_mapping(value_node)
merge.extend(value_node.value)
elif isinstance(value_node, SequenceNode):
submerge = []
for subnode in value_node.value:
if not isinstance(subnode, MappingNode):
raise ConstructorError(
'while constructing a mapping',
node.start_mark,
_F(
'expected a mapping for merging, but found {subnode_id!s}',
subnode_id=subnode.id,
),
subnode.start_mark,
)
self.flatten_mapping(subnode)
submerge.append(subnode.value)
submerge.reverse()
for value in submerge:
merge.extend(value)
else:
raise ConstructorError(
'while constructing a mapping',
node.start_mark,
_F(
'expected a mapping or list of mappings for merging, '
'but found {value_node_id!s}',
value_node_id=value_node.id,
),
value_node.start_mark,
)
elif key_node.tag == 'tag:yaml.org,2002:value':
key_node.tag = 'tag:yaml.org,2002:str'
index += 1
else:
index += 1
if bool(merge):
node.merge = merge # separate merge keys to be able to update without duplicate
node.value = merge + node.value
def construct_mapping(self, node, deep=False):
# type: (Any, bool) -> Any
"""deep is True when creating an object/mapping recursively,
in that case want the underlying elements available during construction
"""
if isinstance(node, MappingNode):
self.flatten_mapping(node)
return BaseConstructor.construct_mapping(self, node, deep=deep)
def construct_yaml_null(self, node):
# type: (Any) -> Any
self.construct_scalar(node)
return None
# YAML 1.2 spec doesn't mention yes/no etc any more, 1.1 does
bool_values = {
'yes': True,
'no': False,
'y': True,
'n': False,
'true': True,
'false': False,
'on': True,
'off': False,
}
def construct_yaml_bool(self, node):
# type: (Any) -> bool
value = self.construct_scalar(node)
return self.bool_values[value.lower()]
def construct_yaml_int(self, node):
# type: (Any) -> int
value_s = self.construct_scalar(node)
value_s = value_s.replace('_', "")
sign = +1
if value_s[0] == '-':
sign = -1
if value_s[0] in '+-':
value_s = value_s[1:]
if value_s == '0':
return 0
elif value_s.startswith('0b'):
return sign * int(value_s[2:], 2)
elif value_s.startswith('0x'):
return sign * int(value_s[2:], 16)
elif value_s.startswith('0o'):
return sign * int(value_s[2:], 8)
elif self.resolver.processing_version == (1, 1) and value_s[0] == '0':
return sign * int(value_s, 8)
elif self.resolver.processing_version == (1, 1) and ':' in value_s:
digits = [int(part) for part in value_s.split(':')]
digits.reverse()
base = 1
value = 0
for digit in digits:
value += digit * base
base *= 60
return sign * value
else:
return sign * int(value_s)
inf_value = 1e300
while inf_value != inf_value * inf_value:
inf_value *= inf_value
nan_value = -inf_value / inf_value # Trying to make a quiet NaN (like C99).
def construct_yaml_float(self, node):
# type: (Any) -> float
value_so = self.construct_scalar(node)
value_s = value_so.replace('_', "").lower()
sign = +1
if value_s[0] == '-':
sign = -1
if value_s[0] in '+-':
value_s = value_s[1:]
if value_s == '.inf':
return sign * self.inf_value
elif value_s == '.nan':
return self.nan_value
elif self.resolver.processing_version != (1, 2) and ':' in value_s:
digits = [float(part) for part in value_s.split(':')]
digits.reverse()
base = 1
value = 0.0
for digit in digits:
value += digit * base
base *= 60
return sign * value
else:
if self.resolver.processing_version != (1, 2) and 'e' in value_s:
# value_s is lower case independent of input
mantissa, exponent = value_s.split('e')
if '.' not in mantissa:
warnings.warn(MantissaNoDotYAML1_1Warning(node, value_so))
return sign * float(value_s)
def construct_yaml_binary(self, node):
# type: (Any) -> Any
try:
value = self.construct_scalar(node).encode('ascii')
except UnicodeEncodeError as exc:
raise ConstructorError(
None,
None,
_F('failed to convert base64 data into ascii: {exc!s}', exc=exc),
node.start_mark,
)
try:
return base64.decodebytes(value)
except binascii.Error as exc:
raise ConstructorError(
None,
None,
_F('failed to decode base64 data: {exc!s}', exc=exc),
node.start_mark,
)
timestamp_regexp = timestamp_regexp # moved to util 0.17.17
def construct_yaml_timestamp(self, node, values=None):
# type: (Any, Any) -> Any
if values is None:
try:
match = self.timestamp_regexp.match(node.value)
except TypeError:
match = None
if match is None:
raise ConstructorError(
None,
None,
'failed to construct timestamp from "{}"'.format(node.value),
node.start_mark,
)
values = match.groupdict()
return create_timestamp(**values)
def construct_yaml_omap(self, node):
# type: (Any) -> Any
# Note: we do now check for duplicate keys
omap = ordereddict()
yield omap
if not isinstance(node, SequenceNode):
raise ConstructorError(
'while constructing an ordered map',
node.start_mark,
_F('expected a sequence, but found {node_id!s}', node_id=node.id),
node.start_mark,
)
for subnode in node.value:
if not isinstance(subnode, MappingNode):
raise ConstructorError(
'while constructing an ordered map',
node.start_mark,
_F(
'expected a mapping of length 1, but found {subnode_id!s}',
subnode_id=subnode.id,
),
subnode.start_mark,
)
if len(subnode.value) != 1:
raise ConstructorError(
'while constructing an ordered map',
node.start_mark,
_F(
'expected a single mapping item, but found {len_subnode_val:d} items',
len_subnode_val=len(subnode.value),
),
subnode.start_mark,
)
key_node, value_node = subnode.value[0]
key = self.construct_object(key_node)
assert key not in omap
value = self.construct_object(value_node)
omap[key] = value
def construct_yaml_pairs(self, node):
# type: (Any) -> Any
# Note: the same code as `construct_yaml_omap`.
pairs = [] # type: List[Any]
yield pairs
if not isinstance(node, SequenceNode):
raise ConstructorError(
'while constructing pairs',
node.start_mark,
_F('expected a sequence, but found {node_id!s}', node_id=node.id),
node.start_mark,
)
for subnode in node.value:
if not isinstance(subnode, MappingNode):
raise ConstructorError(
'while constructing pairs',
node.start_mark,
_F(
'expected a mapping of length 1, but found {subnode_id!s}',
subnode_id=subnode.id,
),
subnode.start_mark,
)
if len(subnode.value) != 1:
raise ConstructorError(
'while constructing pairs',
node.start_mark,
_F(
'expected a single mapping item, but found {len_subnode_val:d} items',
len_subnode_val=len(subnode.value),
),
subnode.start_mark,
)
key_node, value_node = subnode.value[0]
key = self.construct_object(key_node)
value = self.construct_object(value_node)
pairs.append((key, value))
def construct_yaml_set(self, node):
# type: (Any) -> Any
data = set() # type: Set[Any]
yield data
value = self.construct_mapping(node)
data.update(value)
def construct_yaml_str(self, node):
# type: (Any) -> Any
value = self.construct_scalar(node)
return value
def construct_yaml_seq(self, node):
# type: (Any) -> Any
data = self.yaml_base_list_type() # type: List[Any]
yield data
data.extend(self.construct_sequence(node))
def construct_yaml_map(self, node):
# type: (Any) -> Any
data = self.yaml_base_dict_type() # type: Dict[Any, Any]
yield data
value = self.construct_mapping(node)
data.update(value)
def construct_yaml_object(self, node, cls):
# type: (Any, Any) -> Any
data = cls.__new__(cls)
yield data
if hasattr(data, '__setstate__'):
state = self.construct_mapping(node, deep=True)
data.__setstate__(state)
else:
state = self.construct_mapping(node)
data.__dict__.update(state)
def construct_undefined(self, node):
# type: (Any) -> None
raise ConstructorError(
None,
None,
_F(
'could not determine a constructor for the tag {node_tag!r}', node_tag=node.tag
),
node.start_mark,
)
SafeConstructor.add_constructor('tag:yaml.org,2002:null', SafeConstructor.construct_yaml_null)
SafeConstructor.add_constructor('tag:yaml.org,2002:bool', SafeConstructor.construct_yaml_bool)
SafeConstructor.add_constructor('tag:yaml.org,2002:int', SafeConstructor.construct_yaml_int)
SafeConstructor.add_constructor(
'tag:yaml.org,2002:float', SafeConstructor.construct_yaml_float
)
SafeConstructor.add_constructor(
'tag:yaml.org,2002:binary', SafeConstructor.construct_yaml_binary
)
SafeConstructor.add_constructor(
'tag:yaml.org,2002:timestamp', SafeConstructor.construct_yaml_timestamp
)
SafeConstructor.add_constructor('tag:yaml.org,2002:omap', SafeConstructor.construct_yaml_omap)
SafeConstructor.add_constructor(
'tag:yaml.org,2002:pairs', SafeConstructor.construct_yaml_pairs
)
SafeConstructor.add_constructor('tag:yaml.org,2002:set', SafeConstructor.construct_yaml_set)
SafeConstructor.add_constructor('tag:yaml.org,2002:str', SafeConstructor.construct_yaml_str)
SafeConstructor.add_constructor('tag:yaml.org,2002:seq', SafeConstructor.construct_yaml_seq)
SafeConstructor.add_constructor('tag:yaml.org,2002:map', SafeConstructor.construct_yaml_map)
SafeConstructor.add_constructor(None, SafeConstructor.construct_undefined)
| SafeConstructor |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 22785,
"end": 24893
} | class ____(ImageBase):
''' Render images given as scalar data together with a color mapper.
In addition to the defined model properties, ``Image`` also can accept
a keyword argument ``palette`` in place of an explicit ``color_mapper``.
The value should be a list of colors, or the name of one of the built-in
palettes in ``bokeh.palettes``. This palette will be used to automatically
construct a ``ColorMapper`` model for the ``color_mapper`` property.
If both ``palette`` and ``color_mapper`` are passed, a ``ValueError``
exception will be raised. If neither is passed, then the ``Greys9``
palette will be used as a default.
'''
def __init__(self, *args, **kwargs) -> None:
if 'palette' in kwargs and 'color_mapper' in kwargs:
raise ValueError("only one of 'palette' and 'color_mapper' may be specified")
elif 'color_mapper' not in kwargs:
# Use a palette (given or default)
palette = kwargs.pop('palette', 'Greys9')
mapper = LinearColorMapper(palette)
kwargs['color_mapper'] = mapper
super().__init__(*args, **kwargs)
_args = ('image', 'x', 'y', 'dw', 'dh', 'dilate')
# a hook to specify any additional kwargs handled by an initializer
_extra_kws = {
'palette': (
'str or list[color value]',
'a palette to construct a value for the color mapper property from',
),
}
image = NumberSpec(default=field("image"), help="""
The arrays of scalar data for the images to be colormapped.
""")
color_mapper = Instance(ColorMapper, default=InstanceDefault(LinearColorMapper, palette="Greys9"), help="""
A ``ColorMapper`` to use to map the scalar data from ``image``
into RGBA values for display.
The name of a palette from ``bokeh.palettes`` may also be set, in which
case a ``LinearColorMapper`` configured with the named palette will be used.
.. note::
The color mapping step happens on the client.
""").accepts(Enum(Palette), lambda pal: LinearColorMapper(palette=pal))
| Image |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 2901,
"end": 3024
} | class ____(IsTrainingCheck):
def __init__(self) -> None:
super().__init__()
self.train(False)
| IsEvalCheck |
python | oauthlib__oauthlib | tests/oauth1/rfc5849/test_client.py | {
"start": 9985,
"end": 12907
} | class ____(TestCase):
def test_case_insensitive_headers(self):
client = Client('client_key')
# Uppercase
_, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
self.assertEqual(h['Content-Type'], 'application/x-www-form-urlencoded')
# Lowercase
_, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
headers={'content-type': 'application/x-www-form-urlencoded'})
self.assertEqual(h['content-type'], 'application/x-www-form-urlencoded')
# Capitalized
_, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
headers={'Content-type': 'application/x-www-form-urlencoded'})
self.assertEqual(h['Content-type'], 'application/x-www-form-urlencoded')
# Random
_, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
headers={'conTent-tYpe': 'application/x-www-form-urlencoded'})
self.assertEqual(h['conTent-tYpe'], 'application/x-www-form-urlencoded')
def test_sign_no_body(self):
client = Client('client_key', decoding='utf-8')
self.assertRaises(ValueError, client.sign, 'http://i.b/path',
http_method='POST', body=None,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
def test_sign_body(self):
client = Client('client_key')
_, h, b = client.sign('http://i.b/path', http_method='POST', body='',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
self.assertEqual(h['Content-Type'], 'application/x-www-form-urlencoded')
def test_sign_get_with_body(self):
client = Client('client_key')
for method in ('GET', 'HEAD'):
self.assertRaises(ValueError, client.sign, 'http://a.b/path?query',
http_method=method, body='a=b',
headers={
'Content-Type': 'application/x-www-form-urlencoded'
})
def test_sign_unicode(self):
client = Client('client_key', nonce='abc', timestamp='abc')
_, h, b = client.sign('http://i.b/path', http_method='POST',
body='status=%E5%95%A6%E5%95%A6',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
self.assertEqual(b, 'status=%E5%95%A6%E5%95%A6')
self.assertIn('oauth_signature="yrtSqp88m%2Fc5UDaucI8BXK4oEtk%3D"', h['Authorization'])
_, h, b = client.sign('http://i.b/path', http_method='POST',
body='status=%C3%A6%C3%A5%C3%B8',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
self.assertEqual(b, 'status=%C3%A6%C3%A5%C3%B8')
self.assertIn('oauth_signature="oG5t3Eg%2FXO5FfQgUUlTtUeeZzvk%3D"', h['Authorization'])
| SigningTest |
python | kamyu104__LeetCode-Solutions | Python/strings-differ-by-one-character.py | {
"start": 54,
"end": 928
} | class ____(object):
def differByOne(self, dict):
"""
:type dict: List[str]
:rtype: bool
"""
MOD, P = 10**9+7, 113
hashes = [0]*len(dict)
for i, word in enumerate(dict):
for c in word:
hashes[i] = (P*hashes[i] + (ord(c)-ord('a'))) % MOD
base = 1
for p in reversed(xrange(len(dict[0]))):
lookup = collections.defaultdict(list)
for i, word in enumerate(dict):
new_hash = (hashes[i] - base*(ord(word[p])-ord('a'))) % MOD
if new_hash in lookup:
for j in lookup[new_hash]:
if dict[j][:p]+dict[j][p+1:] == word[:p]+word[p+1:]:
return True
lookup[new_hash].append(i)
base = P*base % MOD
return False
| Solution |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 28252,
"end": 29889
} | class ____(Structure):
_fields_ = (
("ilocalsym", p_uint32),
("nlocalsym", p_uint32),
("iextdefsym", p_uint32),
("nextdefsym", p_uint32),
("iundefsym", p_uint32),
("nundefsym", p_uint32),
("tocoff", p_uint32),
("ntoc", p_uint32),
("modtaboff", p_uint32),
("nmodtab", p_uint32),
("extrefsymoff", p_uint32),
("nextrefsyms", p_uint32),
("indirectsymoff", p_uint32),
("nindirectsyms", p_uint32),
("extreloff", p_uint32),
("nextrel", p_uint32),
("locreloff", p_uint32),
("nlocrel", p_uint32),
)
def describe(self):
dys = {}
dys["ilocalsym"] = int(self.ilocalsym)
dys["nlocalsym"] = int(self.nlocalsym)
dys["iextdefsym"] = int(self.iextdefsym)
dys["nextdefsym"] = int(self.nextdefsym)
dys["iundefsym"] = int(self.iundefsym)
dys["nundefsym"] = int(self.nundefsym)
dys["tocoff"] = int(self.tocoff)
dys["ntoc"] = int(self.ntoc)
dys["modtaboff"] = int(self.modtaboff)
dys["nmodtab"] = int(self.nmodtab)
dys["extrefsymoff"] = int(self.extrefsymoff)
dys["nextrefsyms"] = int(self.nextrefsyms)
dys["indirectsymoff"] = int(self.indirectsymoff)
dys["nindirectsyms"] = int(self.nindirectsyms)
dys["extreloff"] = int(self.extreloff)
dys["nextrel"] = int(self.nextrel)
dys["locreloff"] = int(self.locreloff)
dys["nlocrel"] = int(self.nlocrel)
return dys
INDIRECT_SYMBOL_LOCAL = 0x80000000
INDIRECT_SYMBOL_ABS = 0x40000000
| dysymtab_command |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 3530,
"end": 5399
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: EdgeTamVideoConfig):
super().__init__()
self.depthwise_conv = nn.Conv2d(
config.memory_fuser_embed_dim,
config.memory_fuser_embed_dim,
kernel_size=config.memory_fuser_kernel_size,
padding=config.memory_fuser_padding,
groups=config.memory_fuser_embed_dim,
) # depthwise conv
self.layer_norm = EdgeTamVideoLayerNorm(config.memory_fuser_embed_dim, eps=1e-6, data_format="channels_first")
self.activation = ACT2FN[config.memory_fuser_hidden_act]
self.pointwise_conv1 = nn.Linear(
config.memory_fuser_embed_dim, config.memory_fuser_intermediate_dim
) # pointwise/1x1 convs, implemented with linear layers
self.pointwise_conv2 = nn.Linear(config.memory_fuser_intermediate_dim, config.memory_fuser_embed_dim)
self.scale = nn.Parameter(
config.memory_fuser_layer_scale_init_value * torch.ones(config.memory_fuser_embed_dim),
requires_grad=True,
)
def forward(self, hidden_states):
input = hidden_states
hidden_states = self.depthwise_conv(hidden_states)
hidden_states = self.layer_norm(hidden_states)
hidden_states = hidden_states.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
hidden_states = self.pointwise_conv1(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.pointwise_conv2(hidden_states)
hidden_states = self.scale * hidden_states
hidden_states = hidden_states.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
hidden_states = input + hidden_states
return hidden_states
@dataclass
@auto_docstring(custom_intro="Base class for the vision encoder's outputs.")
| EdgeTamVideoMemoryFuserCXBlock |
python | pytorch__pytorch | test/dynamo/test_pgo.py | {
"start": 501,
"end": 15786
} | class ____(torch._dynamo.test_case.TestCase):
def setUp(self):
super().setUp()
self._test_stack = contextlib.ExitStack()
self._test_stack.enter_context(torch.compiler.config.patch(job_id=self.id()))
self._test_stack.enter_context(
torch._dynamo.config.patch(automatic_dynamic_local_pgo=True)
)
if os.environ.get("INDUCTOR_TEST_DISABLE_FRESH_CACHE") != "1":
self._test_stack.enter_context(fresh_cache())
mock_cache.PatchCaches.setUp()
def tearDown(self):
super().tearDown()
torch._dynamo.reset()
self._test_stack.close()
mock_cache.PatchCaches.tearDown()
def reset(self):
torch._dynamo.reset()
clear_caches()
def test_basic(self):
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
def f(x):
return x * 2
f(torch.randn(2, 3))
f(torch.randn(2, 4))
self.assertEqual(cnts.frame_count, 2)
self.reset()
cnts.clear()
f(torch.randn(2, 5))
f(torch.randn(2, 6))
self.assertEqual(cnts.frame_count, 1)
@torch._dynamo.config.patch(
force_parameter_static_shapes=False,
force_nn_module_property_static_shapes=False,
)
def test_whitelist_suggestion(self):
from torch._dynamo.pgo import (
_collect_dynamic_sources,
_collect_missing_sources,
get_code_state,
render_code_state,
)
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
class Foo(torch.nn.Module):
def __init__(self):
super().__init__()
self.lin = torch.nn.Linear(4, 4)
self.attr = torch.randn(4)
def forward(self, x, y):
return self.lin(x) + self.attr + y
sources = [
"L['x']",
"L['self']._modules['lin']._parameters['weight']",
"L['self']._modules['lin']._parameters['bias']",
"L['self'].attr",
"L['y']",
]
def check_whitelist(sources_):
state = render_code_state(get_code_state())
whitelist = re.search(r'TORCH_COMPILE_DYNAMIC_SOURCES="(.*)"', state).group(
1
)
for src in sources_:
self.assertTrue(src in whitelist)
def check_num_missing_whitelist(expected):
frame_state = next(iter(get_code_state().values()))
all_dynamic_sources = _collect_dynamic_sources(frame_state)
missing_whitelist = _collect_missing_sources(all_dynamic_sources)
self.assertEqual(len(missing_whitelist), expected)
# check growing whitelist
f = Foo()
f(torch.randn(2, 4), torch.randn(4))
# only x
f(torch.randn(4, 4), torch.randn(4))
check_whitelist(sources[:1])
# x, lin.weight
f.lin = torch.nn.Linear(8, 4)
f(torch.randn(8, 8), torch.randn(4))
check_whitelist(sources[:2])
# x, y, lin.weight, lin.bias, attr
f.lin = torch.nn.Linear(8, 8)
f.attr = torch.randn(8)
f(torch.randn(8, 8), torch.randn(8))
check_whitelist(sources)
check_num_missing_whitelist(5)
# now use suggested whitelist
self.reset()
cnts.clear()
code_state = get_code_state()
state = render_code_state(code_state)
whitelist = re.search(r'TORCH_COMPILE_DYNAMIC_SOURCES="(.*)"', state).group(1)
with torch.compiler.config.patch(dynamic_sources=whitelist):
f = Foo()
f(torch.randn(2, 4), torch.randn(4))
f(torch.randn(4, 4), torch.randn(4))
f.lin = torch.nn.Linear(8, 8)
f.attr = torch.randn(8)
f(torch.randn(8, 8), torch.randn(8))
self.assertEqual(cnts.frame_count, 1)
check_num_missing_whitelist(0)
def test_no_empty_graph_allowlist(self):
@torch._dynamo.disable
def g(x):
return x * 2 + x
@torch.compile(backend="eager")
def f(x):
return g(x)
self.reset()
f(torch.randn(4))
f(torch.randn(8))
self.assertEqual(torch._dynamo.pgo._LOGGED_DYNAMIC_ALLOWLIST, False)
@torch.compile(backend="eager")
def f1(x):
return g(x + 2) + 2
self.reset()
f1(torch.randn(4))
f1(torch.randn(8))
self.assertEqual(torch._dynamo.pgo._LOGGED_DYNAMIC_ALLOWLIST, True)
def test_pgo_dynamic_false(self):
@torch.compile(backend="eager", dynamic=False)
class Foo(torch.nn.Module):
def forward(self, x, y):
x += 2
y += 2
torch._dynamo.graph_break()
x -= 2
y *= 2
return x, y
self.reset()
f = Foo()
f(torch.randn(2, 4), torch.randn(2, 4))
f(torch.randn(4, 4), torch.randn(6, 8))
# check PGO code state is overwritten with static value, both before/after graph break
for code_state in torch._dynamo.pgo.get_code_state().values():
self.assertEqual(code_state.automatic_dynamic["L['x']"].size, (4, 4))
self.assertEqual(code_state.automatic_dynamic["L['y']"].size, (6, 8))
def test_whitelist_ints_floats(self):
@torch.compile(backend="eager", fullgraph=True)
class Bar(torch.nn.Module):
def __init__(self, c, d):
super().__init__()
self.c = c
self.d = d
def forward(self, x, y, z):
if self.d == 2:
x += 1
if self.c == 1.0:
return x + y + torch.tensor([z])
f = Bar(1.0, 2)
f(2, 1.0, 2.0)
f.d = 3
f(3, 1.2, 2.0)
state = torch._dynamo.pgo.render_code_state(torch._dynamo.pgo.get_code_state())
whitelist = re.search(r'TORCH_COMPILE_DYNAMIC_SOURCES="(.*)"', state).group(1)
self.assertTrue("L['x']" in whitelist)
self.assertTrue("L['y']" in whitelist)
self.assertTrue(
"___as_tensor(L['y'])" not in whitelist
) # ephemeral FloatTensor source
self.assertTrue("L['z']" not in whitelist) # static float
self.assertTrue("L['self'].c" not in whitelist) # static float property
self.assertTrue("L['self'].d" in whitelist) # dynamic int property
def test_pgo_dynamic_params(self):
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
class Foo(torch.nn.Module):
def __init__(self):
super().__init__()
self.lin = None
def forward(self, x):
return self.lin(x)
f = Foo()
def run():
self.reset()
cnts.clear()
f.lin = torch.nn.Linear(4, 4)
f(torch.randn(2, 4))
f(torch.randn(4, 4))
f.lin = torch.nn.Linear(8, 8)
f(torch.randn(8, 8))
# recompile each run
run()
self.assertEqual(cnts.frame_count, 3)
# parameter static shapes are forced static, so we recompile once
with torch._dynamo.config.patch(
force_parameter_static_shapes=False,
force_nn_module_property_static_shapes=False,
):
run()
self.assertEqual(cnts.frame_count, 2)
# because flags were flipped, params were included in PGO
run()
self.assertEqual(cnts.frame_count, 1)
def test_njt(self):
cnts = CompileCounter()
# NB: PGO doesn't do anything here, the point is to catch pickle
# problem with nested int
@torch.compile(backend=cnts, fullgraph=True)
def f(x):
return x * 2
x = torch.nested.nested_tensor_from_jagged(
torch.randn(10, 3), torch.tensor([0, 3, 7, 10]), torch.tensor([1, 2, 3])
)
y = torch.nested.nested_tensor_from_jagged(
torch.randn(13, 3), torch.tensor([0, 3, 7, 13]), torch.tensor([1, 2, 6])
)
f(x)
f(y)
self.assertEqual(cnts.frame_count, 1)
self.reset()
cnts.clear()
a = torch.nested.nested_tensor_from_jagged(
torch.randn(14, 3), torch.tensor([0, 3, 7, 14]), torch.tensor([1, 2, 7])
)
b = torch.nested.nested_tensor_from_jagged(
torch.randn(15, 3), torch.tensor([0, 3, 7, 15]), torch.tensor([1, 2, 8])
)
f(a)
f(b)
self.assertEqual(cnts.frame_count, 1)
def test_distinct_compile_id(self):
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
def f(x):
return x * 2
with torch.compiler.config.patch(job_id="foo"):
f(torch.randn(2, 3))
f(torch.randn(2, 4))
self.assertEqual(cnts.frame_count, 2)
self.reset()
cnts.clear()
with torch.compiler.config.patch(job_id="bar"):
f(torch.randn(2, 5))
f(torch.randn(2, 6))
self.assertEqual(cnts.frame_count, 2)
torch._dynamo.reset()
clear_caches()
cnts.clear()
with torch.compiler.config.patch(job_id="foo"):
f(torch.randn(2, 7))
f(torch.randn(2, 8))
self.assertEqual(cnts.frame_count, 1)
# TODO: to test local need to ensure the local filesystem gets cleared out
@torch._dynamo.config.patch(
automatic_dynamic_remote_pgo=True, automatic_dynamic_local_pgo=False
)
def test_remote_basic(self):
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
def f(x):
return x * 2
with mock_cache.PatchCaches():
f(torch.randn(2, 3))
f(torch.randn(2, 4))
self.assertEqual(cnts.frame_count, 2)
self.assertEqual(
mock_cache.global_stats.dynamo_pgo, mock_cache.Stats(2, 0, 1)
)
self.reset()
cnts.clear()
f(torch.randn(2, 5))
f(torch.randn(2, 6))
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(
mock_cache.global_stats.dynamo_pgo, mock_cache.Stats(2, 1, 1)
)
self.reset()
cnts.clear()
with torch.compiler.config.patch({"cache_key_tag": "test"}):
f(torch.randn(2, 7))
f(torch.randn(2, 8))
self.assertEqual(cnts.frame_count, 2)
self.assertEqual(
mock_cache.global_stats.dynamo_pgo, mock_cache.Stats(4, 1, 2)
)
# Test that if the same file appears in two different paths for two different compilations PGO still works.
def test_different_file_paths_local_pgo(self):
content = """
import torch
def run(cnt):
@torch.compile(backend=cnt, fullgraph=True)
def func(x):
return x*10
func(torch.rand(10))
func(torch.rand(20))
func(torch.rand(30))
"""
temp_dir1 = tempfile.TemporaryDirectory()
temp_dir2 = tempfile.TemporaryDirectory()
# We need normalize_path_separator for Windows file path.
path1 = normalize_path_separator(os.path.join(temp_dir1.name, "example.py"))
path2 = normalize_path_separator(os.path.join(temp_dir2.name, "example.py"))
cnts = CompileCounter()
assert path1 != path2
def write_load_and_run(path):
with open(path, "w") as file:
file.write(content)
spec = importlib.util.spec_from_file_location("example", path1)
assert spec is not None
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
module.run(cnts)
write_load_and_run(path1)
self.assertEqual(cnts.frame_count, 2)
state = torch._dynamo.pgo.render_code_state(torch._dynamo.pgo.get_code_state())
# Windows can't create unification temp path:
# hash(a18a3259)C:/Users/Xuhan/AppData/Local/Temp/tmpx3hfkuqa/example.py
# Skip hash check
self.assertTrue("hash" if IS_WINDOWS else "hash(390fe689)" in state)
self.assertTrue("/example.py:4:func:" in state)
self.assertTrue(" L['x']: tensor size=[?] stride=[1]" in state)
# We should compile this only once due to PGO.
cnts.clear()
write_load_and_run(path2)
self.assertEqual(cnts.frame_count, 1)
@torch._dynamo.config.patch(
automatic_dynamic_remote_pgo=True, automatic_dynamic_local_pgo=False
)
def test_sticky_pgo_read_write(self):
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
def f(x, y):
return x * 2, y * 3
def t(x, y):
return torch.randn(x, y)
with mock_cache.PatchCaches():
# we pretend to disable the default remote cache, by keying different job ids per run
with torch.compiler.config.patch(job_id="a"):
f(t(2, 2), t(2, 2))
f(t(2, 4), t(2, 2))
self.assertEqual(cnts.frame_count, 2)
# first test we're not reading from local/default remote cache;
# we should recompile when x wobbles
self.reset()
cnts.clear()
with torch.compiler.config.patch(
job_id="b", pgo_extra_write_key="sticky_0"
):
f(t(2, 2), t(2, 2))
f(t(2, 4), t(2, 2))
self.assertEqual(cnts.frame_count, 2)
# now with the extra sticky_0 key, we start with dynamic x;
# no recompiles
self.reset()
cnts.clear()
with torch.compiler.config.patch(job_id="c", pgo_extra_read_key="sticky_0"):
f(t(2, 2), t(2, 2))
f(t(2, 4), t(2, 2))
self.assertEqual(cnts.frame_count, 1)
# last test: wobble y and write to sticky_1 key
self.reset()
cnts.clear()
with torch.compiler.config.patch(
job_id="d", pgo_extra_write_key="sticky_1"
):
f(t(2, 2), t(2, 2))
f(t(2, 2), t(2, 4))
f(t(2, 2), t(4, 4))
self.assertEqual(cnts.frame_count, 3)
# start using default remote PGO, create run that wobbles y
self.reset()
cnts.clear()
f(t(2, 2), t(2, 2))
f(t(2, 4), t(2, 2))
f(t(4, 2), t(2, 2))
# with both default remote present, we ignore extra remote.
self.reset()
cnts.clear()
with torch.compiler.config.patch(pgo_extra_read_key="sticky_1"):
f(t(2, 2), t(2, 2))
f(t(6, 8), t(2, 2))
self.assertEqual(cnts.frame_count, 1)
f(t(2, 2), t(2, 4))
self.assertEqual(cnts.frame_count, 2)
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
run_tests()
| PgoTest |
python | crytic__slither | slither/vyper_parsing/variables/structure_variable.py | {
"start": 186,
"end": 672
} | class ____:
def __init__(self, variable: StructureVariable, variable_data: AnnAssign):
self._variable: StructureVariable = variable
self._variable.name = variable_data.target.id
self._elem_to_parse = variable_data.annotation
@property
def underlying_variable(self) -> StructureVariable:
return self._variable
def analyze(self, contract) -> None:
self._variable.type = parse_type(self._elem_to_parse, contract)
| StructureVariableVyper |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 29027,
"end": 30050
} | class ____(StateMachineEvent):
__slots__ = ("key", "compute_duration")
key: Key
compute_duration: float
# {TaskState -> finish: TaskStateState | (finish: TaskStateState, transition *args)}
# Not to be confused with distributed.scheduler.Recs
Recs: TypeAlias = dict[TaskState, TaskStateState | tuple]
Instructions: TypeAlias = list[Instruction]
RecsInstrs: TypeAlias = tuple[Recs, Instructions]
def merge_recs_instructions(*args: RecsInstrs) -> RecsInstrs:
"""Merge multiple (recommendations, instructions) tuples.
Collisions in recommendations are only allowed if identical.
"""
recs: Recs = {}
instr: Instructions = []
for recs_i, instr_i in args:
for ts, finish in recs_i.items():
if ts in recs and recs[ts] != finish:
raise RecommendationsConflict(
f"Mismatched recommendations for {ts.key!r}: {recs[ts]} vs. {finish}"
)
recs[ts] = finish
instr += instr_i
return recs, instr
| SecedeEvent |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 122953,
"end": 128235
} | class ____(Response):
"""
Response of tasks.delete endpoint.
:param deleted: Indicates whether the task was deleted
:type deleted: bool
:param updated_children: Number of child tasks whose parent property was
updated
:type updated_children: int
:param updated_models: Number of models whose task property was updated
:type updated_models: int
:param updated_versions: Number of dataset versions whose task property was
updated
:type updated_versions: int
:param frames: Response from frames.rollback
:type frames: dict
:param events: Response from events.delete_for_task
:type events: dict
"""
_service = "tasks"
_action = "delete"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"deleted": {
"description": "Indicates whether the task was deleted",
"type": ["boolean", "null"],
},
"events": {
"additionalProperties": True,
"description": "Response from events.delete_for_task",
"type": ["object", "null"],
},
"frames": {
"additionalProperties": True,
"description": "Response from frames.rollback",
"type": ["object", "null"],
},
"updated_children": {
"description": "Number of child tasks whose parent property was updated",
"type": ["integer", "null"],
},
"updated_models": {
"description": "Number of models whose task property was updated",
"type": ["integer", "null"],
},
"updated_versions": {
"description": "Number of dataset versions whose task property was updated",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
deleted: Optional[bool] = None,
updated_children: Optional[int] = None,
updated_models: Optional[int] = None,
updated_versions: Optional[int] = None,
frames: Optional[dict] = None,
events: Optional[dict] = None,
**kwargs: Any
) -> None:
super(DeleteResponse, self).__init__(**kwargs)
self.deleted = deleted
self.updated_children = updated_children
self.updated_models = updated_models
self.updated_versions = updated_versions
self.frames = frames
self.events = events
@schema_property("deleted")
def deleted(self) -> Optional[bool]:
return self._property_deleted
@deleted.setter
def deleted(self, value: Optional[bool]) -> None:
if value is None:
self._property_deleted = None
return
self.assert_isinstance(value, "deleted", (bool,))
self._property_deleted = value
@schema_property("updated_children")
def updated_children(self) -> Optional[int]:
return self._property_updated_children
@updated_children.setter
def updated_children(self, value: Optional[int]) -> None:
if value is None:
self._property_updated_children = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated_children", six.integer_types)
self._property_updated_children = value
@schema_property("updated_models")
def updated_models(self) -> Optional[int]:
return self._property_updated_models
@updated_models.setter
def updated_models(self, value: Optional[int]) -> None:
if value is None:
self._property_updated_models = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated_models", six.integer_types)
self._property_updated_models = value
@schema_property("updated_versions")
def updated_versions(self) -> Optional[int]:
return self._property_updated_versions
@updated_versions.setter
def updated_versions(self, value: Optional[int]) -> None:
if value is None:
self._property_updated_versions = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated_versions", six.integer_types)
self._property_updated_versions = value
@schema_property("frames")
def frames(self) -> Optional[dict]:
return self._property_frames
@frames.setter
def frames(self, value: Optional[dict]) -> None:
if value is None:
self._property_frames = None
return
self.assert_isinstance(value, "frames", (dict,))
self._property_frames = value
@schema_property("events")
def events(self) -> Optional[dict]:
return self._property_events
@events.setter
def events(self, value: Optional[dict]) -> None:
if value is None:
self._property_events = None
return
self.assert_isinstance(value, "events", (dict,))
self._property_events = value
| DeleteResponse |
python | skorch-dev__skorch | skorch/callbacks/logging.py | {
"start": 1714,
"end": 9733
} | class ____(Callback):
"""Logs model metadata and training metrics to Neptune.
Neptune is a lightweight experiment-tracking tool.
You can read more about it here: https://neptune.ai
Use this callback to automatically log all interesting values from
your net's history to Neptune.
The best way to log additional information is to log directly to the
run object.
To monitor resource consumption, install psutil:
$ python -m pip install psutil
You can view example experiment logs here:
https://app.neptune.ai/o/common/org/skorch-integration/e/SKOR-32/all
Examples
--------
$ # Install Neptune
$ python -m pip install neptune
>>> # Create a Neptune run
>>> import neptune
>>> from neptune.types import File
>>> # This example uses the API token for anonymous users.
>>> # For your own projects, use the token associated with your neptune.ai account.
>>> run = neptune.init_run(
... api_token=neptune.ANONYMOUS_API_TOKEN,
... project='shared/skorch-integration',
... name='skorch-basic-example',
... source_files=['skorch_example.py'],
... )
>>> # Create a NeptuneLogger callback
>>> neptune_logger = NeptuneLogger(run, close_after_train=False)
>>> # Pass the logger to the net callbacks argument
>>> net = NeuralNetClassifier(
... ClassifierModule,
... max_epochs=20,
... lr=0.01,
... callbacks=[neptune_logger, Checkpoint(dirname="./checkpoints")])
>>> net.fit(X, y)
>>> # Save the checkpoints to Neptune
>>> neptune_logger.run["checkpoints"].upload_files("./checkpoints")
>>> # Log additional metrics after training has finished
>>> from sklearn.metrics import roc_auc_score
>>> y_proba = net.predict_proba(X)
>>> auc = roc_auc_score(y, y_proba[:, 1])
>>> neptune_logger.run["roc_auc_score"].log(auc)
>>> # Log charts, such as an ROC curve
>>> from sklearn.metrics import RocCurveDisplay
>>> roc_plot = RocCurveDisplay.from_estimator(net, X, y)
>>> neptune_logger.run["roc_curve"].upload(File.as_html(roc_plot.figure_))
>>> # Log the net object after training
>>> net.save_params(f_params='basic_model.pkl')
>>> neptune_logger.run["basic_model"].upload(File('basic_model.pkl'))
>>> # Close the run
>>> neptune_logger.run.stop()
Parameters
----------
run : neptune.Run or neptune.handler.Handler
Instantiated ``Run`` or ``Handler`` class.
log_on_batch_end : bool (default=False)
Whether to log loss and other metrics on batch level.
close_after_train : bool (default=True)
Whether to close the ``Run`` object once training
finishes. Set this parameter to False if you want to continue
logging to the same run or if you use it as a context
manager.
keys_ignored : str or list of str (default=None)
Key or list of keys that should not be logged to Neptune. Note that in
addition to the keys provided by the user, keys such as those starting
with ``'event_'`` or ending on ``'_best'`` are ignored by default.
base_namespace: str
Namespace (folder) under which all metadata logged by the ``NeptuneLogger``
will be stored. Defaults to "training".
Attributes
----------
.. _Neptune: https://www.neptune.ai
"""
def __init__(
self,
run,
*,
log_on_batch_end=False,
close_after_train=True,
keys_ignored=None,
base_namespace='training',
):
self.run = run
self.log_on_batch_end = log_on_batch_end
self.close_after_train = close_after_train
self.keys_ignored = keys_ignored
self.base_namespace = base_namespace
def _log_integration_version(self) -> None:
from skorch import __version__
self.run['source_code/integrations/skorch'] = __version__
@property
def _metric_logger(self):
return self.run[self._base_namespace]
@staticmethod
def _get_obj_name(obj):
return type(obj).__name__
def initialize(self):
keys_ignored = self.keys_ignored
if isinstance(keys_ignored, str):
keys_ignored = [keys_ignored]
self.keys_ignored_ = set(keys_ignored or [])
self.keys_ignored_.add('batches')
if self.base_namespace.endswith("/"):
self._base_namespace = self.base_namespace[:-1]
else:
self._base_namespace = self.base_namespace
self._log_integration_version()
return self
def on_train_begin(self, net, X, y, **kwargs):
# TODO: we might want to improve logging of the multi-module net objects, see:
# https://github.com/skorch-dev/skorch/pull/906#discussion_r993514643
self._metric_logger['model/model_type'] = self._get_obj_name(net.module_)
self._metric_logger['model/summary'] = self._model_summary_file(net.module_)
self._metric_logger['config/optimizer'] = self._get_obj_name(net.optimizer_)
self._metric_logger['config/criterion'] = self._get_obj_name(net.criterion_)
self._metric_logger['config/lr'] = net.lr
self._metric_logger['config/epochs'] = net.max_epochs
self._metric_logger['config/batch_size'] = net.batch_size
self._metric_logger['config/device'] = net.device
def on_batch_end(self, net, **kwargs):
if self.log_on_batch_end:
batch_logs = net.history[-1]['batches'][-1]
for key in filter_log_keys(batch_logs.keys(), self.keys_ignored_):
self._log_metric(key, batch_logs, batch=True)
def on_epoch_end(self, net, **kwargs):
"""Automatically log values from the last history step."""
epoch_logs = net.history[-1]
for key in filter_log_keys(epoch_logs.keys(), self.keys_ignored_):
self._log_metric(key, epoch_logs, batch=False)
def on_train_end(self, net, **kwargs):
try:
self._metric_logger['train/epoch/event_lr'].append(net.history[:, 'event_lr'])
except KeyError:
pass
if self.close_after_train:
try: # >1.0 package structure
from neptune.handler import Handler
except ImportError: # <1.0 package structure
from neptune.new.handler import Handler
# Neptune integrations now accept passing Handler object
# to an integration.
# Ref: https://docs.neptune.ai/api/field_types/#handler
# Example of getting an handler from a `Run` object.
# handler = run["foo"]
# handler['bar'] = 1 # Logs to `foo/bar`
# NOTE: Handler provides most of the functionality of `Run`
# for logging, however it doesn't implement a few methods like
# `stop`, `wait`, etc.
root_obj = self.run
if isinstance(self.run, Handler):
root_obj = self.run.get_root_object()
root_obj.stop()
def _log_metric(self, name, logs, batch):
kind, _, key = name.partition('_')
if not key:
key = 'epoch_duration' if kind == 'dur' else kind
self._metric_logger[key].append(logs[name])
else:
if kind == 'valid':
kind = 'validation'
if batch:
granularity = 'batch'
else:
granularity = 'epoch'
# for example: train / epoch / loss
self._metric_logger[kind][granularity][key].append(logs[name])
@staticmethod
def _model_summary_file(model):
try:
# neptune-client>=1.0.0 package structure
from neptune.types import File
except ImportError:
# neptune-client=0.9.0+ package structure
from neptune.new.types import File
return File.from_content(str(model), extension='txt')
| NeptuneLogger |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/sparkdf_data_sampler.py | {
"start": 495,
"end": 6751
} | class ____(DataSampler):
"""Methods for sampling a Spark dataframe."""
def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Sample the first n rows of data.
Args:
df: Spark dataframe.
batch_spec: Should contain key `n` in sampling_kwargs, the number of
values in the sample e.g. sampling_kwargs={"n": 100}.
Returns:
Sampled dataframe
Raises:
SamplerError
"""
self.verify_batch_spec_sampling_kwargs_exists(batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("n", batch_spec)
n: int = batch_spec["sampling_kwargs"]["n"]
return df.limit(n)
def sample_using_random(
self, df: pyspark.DataFrame, batch_spec: BatchSpec
) -> pyspark.DataFrame:
"""Take a random sample of rows, retaining proportion p.
Args:
df: dataframe to sample
batch_spec: Can contain keys `p` (float), `seed` (int) which
default to 0.1 and 1 respectively if not provided.
Returns:
Sampled dataframe
Raises:
SamplerError
"""
p: float = self.get_sampling_kwargs_value_or_default(
batch_spec=batch_spec, sampling_kwargs_key="p", default_value=0.1
)
seed: int = self.get_sampling_kwargs_value_or_default(
batch_spec=batch_spec, sampling_kwargs_key="seed", default_value=1
)
res = df.withColumn("rand", F.rand(seed=seed)).filter(F.col("rand") < p).drop("rand")
return res
def sample_using_mod(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Take the mod of named column, and only keep rows that match the given value.
Args:
df: dataframe to sample
batch_spec: should contain keys `column_name`, `mod` and `value`
Returns:
Sampled dataframe
Raises:
SamplerError
"""
self.verify_batch_spec_sampling_kwargs_exists(batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("column_name", batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("mod", batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("value", batch_spec)
column_name: str = self.get_sampling_kwargs_value_or_default(batch_spec, "column_name")
mod: int = self.get_sampling_kwargs_value_or_default(batch_spec, "mod")
value: int = self.get_sampling_kwargs_value_or_default(batch_spec, "value")
res = (
df.withColumn("mod_temp", (F.col(column_name) % mod).cast(pyspark.types.IntegerType()))
.filter(F.col("mod_temp") == value)
.drop("mod_temp")
)
return res
def sample_using_a_list(
self,
df: pyspark.DataFrame,
batch_spec: BatchSpec,
) -> pyspark.DataFrame:
"""Match the values in the named column against value_list, and only keep the matches.
Args:
df: dataframe to sample
batch_spec: should contain keys `column_name` and `value_list`
Returns:
Sampled dataframe
Raises:
SamplerError
"""
self.verify_batch_spec_sampling_kwargs_exists(batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("column_name", batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("value_list", batch_spec)
column_name: str = self.get_sampling_kwargs_value_or_default(batch_spec, "column_name")
value_list: list = self.get_sampling_kwargs_value_or_default(batch_spec, "value_list")
return df.where(F.col(column_name).isin(value_list))
def sample_using_hash(
self,
df: pyspark.DataFrame,
batch_spec: BatchSpec,
) -> pyspark.DataFrame:
"""Hash the values in the named column, and only keep rows that match the given hash_value.
Args:
df: dataframe to sample
batch_spec: should contain keys `column_name` and optionally `hash_digits`
(default is 1 if not provided), `hash_value` (default is "f" if not provided),
and `hash_function_name` (default is "md5" if not provided)
Returns:
Sampled dataframe
Raises:
SamplerError
"""
self.verify_batch_spec_sampling_kwargs_exists(batch_spec)
self.verify_batch_spec_sampling_kwargs_key_exists("column_name", batch_spec)
column_name: str = self.get_sampling_kwargs_value_or_default(batch_spec, "column_name")
hash_digits: int = self.get_sampling_kwargs_value_or_default(
batch_spec=batch_spec, sampling_kwargs_key="hash_digits", default_value=1
)
hash_value: str = self.get_sampling_kwargs_value_or_default(
batch_spec=batch_spec, sampling_kwargs_key="hash_value", default_value="f"
)
hash_function_name: str = self.get_sampling_kwargs_value_or_default(
batch_spec=batch_spec,
sampling_kwargs_key="hash_function_name",
default_value="md5",
)
try:
getattr(hashlib, str(hash_function_name))
except (TypeError, AttributeError):
raise (
gx_exceptions.ExecutionEngineError( # noqa: TRY003 # FIXME CoP
f"""The sampling method used with SparkDFExecutionEngine has a reference to an invalid hash_function_name.
Reference to {hash_function_name} cannot be found.""" # noqa: E501 # FIXME CoP
)
)
def _encrypt_value(to_encode):
to_encode_str = str(to_encode)
hash_func = getattr(hashlib, hash_function_name)
hashed_value = hash_func(to_encode_str.encode()).hexdigest()[-1 * hash_digits :]
return hashed_value
encrypt_udf = F.udf(_encrypt_value, pyspark.types.StringType())
res = (
df.withColumn("encrypted_value", encrypt_udf(column_name))
.filter(F.col("encrypted_value") == hash_value)
.drop("encrypted_value")
)
return res
| SparkDataSampler |
python | getsentry__sentry | src/sentry/backup/findings.py | {
"start": 6652,
"end": 7224
} | class ____:
"""A wrapper type for a list of 'ComparatorFinding' which enables pretty-printing in asserts."""
def __init__(self, findings: list[ComparatorFinding]):
self.findings = findings
def append(self, finding: ComparatorFinding) -> None:
self.findings.append(finding)
def empty(self) -> bool:
return not self.findings
def extend(self, findings: list[ComparatorFinding]) -> None:
self.findings += findings
def pretty(self) -> str:
return "\n".join(f.pretty() for f in self.findings)
| ComparatorFindings |
python | django__django | django/core/exceptions.py | {
"start": 731,
"end": 849
} | class ____(SuspiciousOperation):
"""Suspect MIME request in multipart form data"""
pass
| SuspiciousMultipartForm |
python | sqlalchemy__sqlalchemy | test/orm/test_utils.py | {
"start": 32989,
"end": 41896
} | class ____(_poly_fixtures._Polymorphic):
run_setup_mappers = "once"
run_inserts = None
run_deletes = None
def test_plain(self):
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
pmapper = inspect(Person)
emapper = inspect(Engineer)
p1 = PathRegistry.coerce((pmapper, emapper.attrs.machines))
# given a mapper and an attribute on a subclass,
# the path converts what you get to be against that subclass
eq_(p1.path, (emapper, emapper.attrs.machines))
def test_plain_compound(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
cmapper = inspect(Company)
pmapper = inspect(Person)
emapper = inspect(Engineer)
p1 = PathRegistry.coerce(
(cmapper, cmapper.attrs.employees, pmapper, emapper.attrs.machines)
)
# given a mapper and an attribute on a subclass,
# the path converts what you get to be against that subclass
eq_(
p1.path,
(
cmapper,
cmapper.attrs.employees,
emapper,
emapper.attrs.machines,
),
)
def test_plain_aliased(self):
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
emapper = inspect(Engineer)
p_alias = aliased(Person)
p_alias = inspect(p_alias)
p1 = PathRegistry.coerce((p_alias, emapper.attrs.machines))
# plain AliasedClass - the path keeps that AliasedClass directly
# as is in the path
eq_(p1.path, (p_alias, emapper.attrs.machines))
def test_plain_aliased_compound(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
cmapper = inspect(Company)
emapper = inspect(Engineer)
c_alias = aliased(Company)
p_alias = aliased(Person)
c_alias = inspect(c_alias)
p_alias = inspect(p_alias)
p1 = PathRegistry.coerce(
(c_alias, cmapper.attrs.employees, p_alias, emapper.attrs.machines)
)
# plain AliasedClass - the path keeps that AliasedClass directly
# as is in the path
eq_(
p1.path,
(
c_alias,
cmapper.attrs.employees,
p_alias,
emapper.attrs.machines,
),
)
def test_with_poly_sub(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
emapper = inspect(Engineer)
cmapper = inspect(Company)
p_poly = with_polymorphic(Person, [Engineer])
e_poly_insp = inspect(p_poly.Engineer) # noqa - used by comment below
p_poly_insp = inspect(p_poly)
p1 = PathRegistry.coerce((p_poly_insp, emapper.attrs.machines))
# changes as of #5082: when a with_polymorphic is in the middle
# of a path, the natural path makes sure it uses the base mappers,
# however when it's at the root, the with_polymorphic stays in
# the natural path
# this behavior is the same as pre #5082, it was temporarily changed
# but this proved to be incorrect. The path starts on a
# with_polymorphic(), so a Query will "naturally" construct a path
# that comes from that wp.
eq_(p1.path, (e_poly_insp, emapper.attrs.machines))
eq_(p1.natural_path, (e_poly_insp, emapper.attrs.machines))
# this behavior is new as of the final version of #5082.
# the path starts on a normal entity and has a with_polymorphic
# in the middle, for this to match what Query will generate it needs
# to use the non aliased mappers in the natural path.
p2 = PathRegistry.coerce(
(
cmapper,
cmapper.attrs.employees,
p_poly_insp,
emapper.attrs.machines,
)
)
eq_(
p2.path,
(
cmapper,
cmapper.attrs.employees,
e_poly_insp,
emapper.attrs.machines,
),
)
eq_(
p2.natural_path,
(
cmapper,
cmapper.attrs.employees,
emapper,
emapper.attrs.machines,
),
)
def test_with_poly_base_two(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
cmapper = inspect(Company)
pmapper = inspect(Person)
p_poly = with_polymorphic(Person, [Engineer])
e_poly_insp = inspect(p_poly.Engineer) # noqa - used by comment below
p_poly_insp = inspect(p_poly)
p1 = PathRegistry.coerce(
(
cmapper,
cmapper.attrs.employees,
p_poly_insp,
pmapper.attrs.paperwork,
)
)
eq_(
p1.path,
(
cmapper,
cmapper.attrs.employees,
p_poly_insp,
pmapper.attrs.paperwork,
),
)
eq_(
p1.natural_path,
(
cmapper,
cmapper.attrs.employees,
pmapper,
pmapper.attrs.paperwork,
),
)
def test_nonpoly_oftype_aliased_subclass_onroot(self):
Engineer = _poly_fixtures.Engineer
eng_alias = aliased(Engineer)
ea_insp = inspect(eng_alias)
p1 = PathRegistry.coerce((ea_insp, ea_insp.mapper.attrs.paperwork))
eq_(p1.path, (ea_insp, ea_insp.mapper.attrs.paperwork))
eq_(p1.natural_path, (ea_insp, ea_insp.mapper.attrs.paperwork))
def test_nonpoly_oftype_aliased_subclass(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
cmapper = inspect(Company)
pmapper = inspect(Person)
eng_alias = aliased(Engineer)
ea_insp = inspect(eng_alias)
p1 = PathRegistry.coerce(
(
cmapper,
cmapper.attrs.employees,
ea_insp,
ea_insp.mapper.attrs.paperwork,
)
)
eq_(
p1.path,
(
cmapper,
cmapper.attrs.employees,
ea_insp,
ea_insp.mapper.attrs.paperwork,
),
)
eq_(
p1.natural_path,
(
cmapper,
cmapper.attrs.employees,
pmapper,
pmapper.attrs.paperwork,
),
)
def test_nonpoly_oftype_subclass(self):
Company = _poly_fixtures.Company
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
emapper = inspect(Engineer)
cmapper = inspect(Company)
pmapper = inspect(Person)
p1 = PathRegistry.coerce(
(
cmapper,
cmapper.attrs.employees,
emapper,
emapper.attrs.paperwork,
)
)
eq_(
p1.path,
(
cmapper,
cmapper.attrs.employees,
pmapper,
pmapper.attrs.paperwork,
),
)
eq_(
p1.natural_path,
(
cmapper,
cmapper.attrs.employees,
pmapper,
pmapper.attrs.paperwork,
),
)
def test_with_poly_base_one(self):
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
pmapper = inspect(Person)
emapper = inspect(Engineer)
p_poly = with_polymorphic(Person, [Engineer])
p_poly = inspect(p_poly)
# "name" is actually on Person, not Engineer
p1 = PathRegistry.coerce((p_poly, emapper.attrs.name))
# polymorphic AliasedClass - because "name" is on Person,
# we get Person, not Engineer
eq_(p1.path, (p_poly, pmapper.attrs.name))
def test_with_poly_use_mapper(self):
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
emapper = inspect(Engineer)
p_poly = with_polymorphic(Person, [Engineer], _use_mapper_path=True)
p_poly = inspect(p_poly)
p1 = PathRegistry.coerce((p_poly, emapper.attrs.machines))
# polymorphic AliasedClass with the "use_mapper_path" flag -
# the AliasedClass acts just like the base mapper
eq_(p1.path, (emapper, emapper.attrs.machines))
| PathRegistryInhTest |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 2992,
"end": 9716
} | class ____(metaclass=NodeType):
"""Baseclass for all Jinja nodes. There are a number of nodes available
of different types. There are four major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,
or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically.
"""
fields: tuple[str, ...] = ()
attributes: tuple[str, ...] = ("lineno", "environment")
abstract = True
lineno: int
environment: t.Optional["Environment"]
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
if self.abstract:
raise TypeError("abstract nodes are not instantiable")
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
raise TypeError(
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
f" argument{'s' if len(self.fields) != 1 else ''}"
)
for name, arg in zip(self.fields, fields, strict=False):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
def iter_fields(
self,
exclude: t.Container[str] | None = None,
only: t.Container[str] | None = None,
) -> t.Iterator[tuple[str, t.Any]]:
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (
(exclude is None and only is None)
or (exclude is not None and name not in exclude)
or (only is not None and name in only)
):
try:
yield name, getattr(self, name)
except AttributeError:
pass
def iter_child_nodes(
self,
exclude: t.Container[str] | None = None,
only: t.Container[str] | None = None,
) -> t.Iterator["Node"]:
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for _, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
def find(self, node_type: type[_NodeBound]) -> _NodeBound | None:
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
return None
def find_all(
self, node_type: type[_NodeBound] | tuple[type[_NodeBound], ...]
) -> t.Iterator[_NodeBound]:
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child # type: ignore
yield from child.find_all(node_type)
def set_ctx(self, ctx: str) -> "Node":
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if "ctx" in node.fields:
node.ctx = ctx # type: ignore
todo.extend(node.iter_child_nodes())
return self
def set_lineno(self, lineno: int, override: bool = False) -> "Node":
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if "lineno" in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
def set_environment(self, environment: "Environment") -> "Node":
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
def __eq__(self, other: t.Any) -> bool:
if type(self) is not type(other):
return NotImplemented
return tuple(self.iter_fields()) == tuple(other.iter_fields())
__hash__ = object.__hash__
def __repr__(self) -> str:
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
return f"{type(self).__name__}({args_str})"
def dump(self) -> str:
def _dump(node: Node | t.Any) -> None:
if not isinstance(node, Node):
buf.append(repr(node))
return
buf.append(f"nodes.{type(node).__name__}(")
if not node.fields:
buf.append(")")
return
for idx, field in enumerate(node.fields):
if idx:
buf.append(", ")
value = getattr(node, field)
if isinstance(value, list):
buf.append("[")
for idx, item in enumerate(value):
if idx:
buf.append(", ")
_dump(item)
buf.append("]")
else:
_dump(value)
buf.append(")")
buf: list[str] = []
_dump(self)
return "".join(buf)
| Node |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 1291,
"end": 1633
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.StandardModel
sqlalchemy_get_or_create = ('foo',)
sqlalchemy_session = models.session
sqlalchemy_session_persistence = 'commit'
id = factory.Sequence(lambda n: n)
foo = factory.Sequence(lambda n: 'foo%d' % n)
| WithGetOrCreateFieldFactory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/conftest/google_sheets_base_test.py | {
"start": 965,
"end": 7565
} | class ____(TestCase, ABC):
def setUp(self) -> None:
self._config = deepcopy(_CONFIG)
self._service_config = deepcopy(_SERVICE_CONFIG)
@staticmethod
def _check(config: Dict[str, Any], expecting_exception: bool = True) -> EntrypointOutput:
return check_helper(config, stream_name=_STREAM_NAME, expecting_exception=expecting_exception)
@staticmethod
def _discover(config: Dict[str, Any], expecting_exception: bool = True) -> EntrypointOutput:
return discover_helper(config, stream_name=_STREAM_NAME, expecting_exception=expecting_exception)
@staticmethod
def _read(config: Dict[str, Any], catalog: ConfiguredAirbyteCatalog, expecting_exception: bool = False) -> EntrypointOutput:
return read_helper(config, catalog, expecting_exception=expecting_exception)
@staticmethod
def authorize(http_mocker: HttpMocker):
# Authorization request with user credentials to "https://oauth2.googleapis.com" to obtain a token
http_mocker.post(
AuthBuilder.get_token_endpoint().with_body(AUTH_BODY).build(),
HttpResponse(json.dumps(find_template("auth_response", __file__)), 200),
)
@staticmethod
def get_spreadsheet_info_and_sheets(
http_mocker: HttpMocker,
streams_response_file: Optional[str] = None,
meta_response_code: Optional[int] = 200,
spreadsheet_id: Optional[str] = _SPREADSHEET_ID,
):
""" "
Mock request to https://sheets.googleapis.com/v4/spreadsheets/<spreed_sheet_id>?includeGridData=false&alt=json in order
to obtain sheets (streams) from the spreed_sheet_id provided.
e.g. from response file
"sheets": [
{
"properties": {
"sheetId": 0,
"title": "<sheet_id>",
"index": 0,
"sheetType": "GRID",
"gridProperties": {
"rowCount": 1,
"columnCount": 1
}
}
}
],
"""
GoogleSheetsBaseTest.authorize(http_mocker)
if streams_response_file:
http_mocker.get(
RequestBuilder().with_spreadsheet_id(spreadsheet_id).with_include_grid_data(False).with_alt("json").build(),
HttpResponse(json.dumps(find_template(streams_response_file, __file__)), meta_response_code),
)
@staticmethod
def get_sheet_first_row(
http_mocker: HttpMocker,
headers_response_file: str,
headers_response_code: int = 200,
stream_name: Optional[str] = _STREAM_NAME,
data_initial_range_response_file: Optional[str] = None,
data_initial_response_code: Optional[int] = 200,
spreadsheet_id: Optional[str] = _SPREADSHEET_ID,
):
""" "
Mock request to 'https://sheets.googleapis.com/v4/spreadsheets/<spreadsheet>?includeGridData=true&ranges=<sheet>!1:1&alt=json'
to obtain headers data (keys) used for stream schema from the spreadsheet + sheet provided.
For this we use range of first row in query.
e.g. from response file
"sheets": [
{
"properties": {
"sheetId": 0,
"title": <sheet_id>,
"index": 0,
"sheetType": "GRID",
"gridProperties": {
"rowCount": 4,
"columnCount": 2
}
},
"data": [
{
"rowData": [
{
"values": [
{
"userEnteredValue": {
"stringValue": "name"
},
"effectiveValue": {
"stringValue": "name"
},
"formattedValue": "name"
},
{
"userEnteredValue": {
"stringValue": "age"
},
"effectiveValue": {
"stringValue": "age"
},
"formattedValue": "age"
}
]}],}]}]
"""
http_mocker.get(
RequestBuilder()
.with_spreadsheet_id(spreadsheet_id)
.with_include_grid_data(True)
.with_ranges(f"{stream_name}!1:1")
.with_alt("json")
.build(),
HttpResponse(json.dumps(find_template(headers_response_file, __file__)), headers_response_code),
)
@staticmethod
def get_stream_data(
http_mocker: HttpMocker,
data_response_file: Optional[str] = None,
response_code: Optional[int] = 200,
stream_name: Optional[str] = _STREAM_NAME,
request_range: Tuple = (2, 202),
spreadsheet_id: Optional[str] = _SPREADSHEET_ID,
responses: Optional[Union[HttpResponse, List[HttpResponse]]] = None,
):
""" "
Mock requests to 'https://sheets.googleapis.com/v4/spreadsheets/<spreadsheet>/values:batchGet?ranges=<sheet>!2:202&majorDimension=ROWS&alt=json'
to obtain value ranges (data) for stream from the spreadsheet + sheet provided.
For this we use range e.g. [2:202(2 + range in config which default is 200)].
We start at 2 as we consider row 1 to contain headers. If we had more data the routine would continue to next ranges.
e.g. from response file
{
"spreadsheetId": "<spreadsheet_id>",
"valueRanges": [
{
"range": "<sheet_id>!A2:B4",
"majorDimension": "ROWS",
"values": [
["name1", "22"],
["name2", "24"],
["name3", "25"]
]
}
]
}
"""
start_range = str(request_range[0])
end_range = str(request_range[1])
batch_request_ranges = f"{stream_name}!{start_range}:{end_range}"
http_mocker.get(
RequestBuilder.get_account_endpoint()
.with_spreadsheet_id(spreadsheet_id)
.with_ranges(batch_request_ranges)
.with_major_dimension("ROWS")
.with_alt("json")
.build(),
HttpResponse(json.dumps(find_template(data_response_file, __file__)), response_code) if data_response_file else responses,
)
| GoogleSheetsBaseTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-tasks-you-can-assign.py | {
"start": 2694,
"end": 3985
} | class ____(object):
def maxTaskAssign(self, tasks, workers, pills, strength):
"""
:type tasks: List[int]
:type workers: List[int]
:type pills: int
:type strength: int
:rtype: int
"""
def check(tasks, workers, pills, strength, x):
t = tasks[:x]
for worker in workers[-x:]: # enumerate from the weakest worker to the strongest worker, greedily assign him to the hardest task which he can do
i = bisect.bisect_right(t, worker)-1
if i != -1:
t.pop(i)
continue
if pills:
i = bisect.bisect_right(t, worker+strength)-1
if i != -1:
t.pop(i)
pills -= 1
continue
return False
return True
tasks.sort()
workers.sort()
left, right = 1, min(len(workers), len(tasks))
while left <= right:
mid = left + (right-left)//2
if not check(tasks, workers, pills, strength, mid):
right = mid-1
else:
left = mid+1
return right
# Time: O(n^2 * logn)
# Space: O(n)
import bisect
| Solution3 |
python | openai__openai-python | src/openai/types/responses/tool_param.py | {
"start": 3257,
"end": 5321
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""A label for this MCP server, used to identify it in tool calls."""
type: Required[Literal["mcp"]]
"""The type of the MCP tool. Always `mcp`."""
allowed_tools: Optional[McpAllowedTools]
"""List of allowed tool names or a filter object."""
authorization: str
"""
An OAuth access token that can be used with a remote MCP server, either with a
custom MCP server URL or a service connector. Your application must handle the
OAuth authorization flow and provide the token here.
"""
connector_id: Literal[
"connector_dropbox",
"connector_gmail",
"connector_googlecalendar",
"connector_googledrive",
"connector_microsoftteams",
"connector_outlookcalendar",
"connector_outlookemail",
"connector_sharepoint",
]
"""Identifier for service connectors, like those available in ChatGPT.
One of `server_url` or `connector_id` must be provided. Learn more about service
connectors
[here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).
Currently supported `connector_id` values are:
- Dropbox: `connector_dropbox`
- Gmail: `connector_gmail`
- Google Calendar: `connector_googlecalendar`
- Google Drive: `connector_googledrive`
- Microsoft Teams: `connector_microsoftteams`
- Outlook Calendar: `connector_outlookcalendar`
- Outlook Email: `connector_outlookemail`
- SharePoint: `connector_sharepoint`
"""
headers: Optional[Dict[str, str]]
"""Optional HTTP headers to send to the MCP server.
Use for authentication or other purposes.
"""
require_approval: Optional[McpRequireApproval]
"""Specify which of the MCP server's tools require approval."""
server_description: str
"""Optional description of the MCP server, used to provide more context."""
server_url: str
"""The URL for the MCP server.
One of `server_url` or `connector_id` must be provided.
"""
| Mcp |
python | sphinx-doc__sphinx | sphinx/transforms/post_transforms/__init__.py | {
"start": 1848,
"end": 11256
} | class ____(SphinxPostTransform):
"""Resolves cross-references on doctrees."""
default_priority = 10
def run(self, **kwargs: Any) -> None:
for node in self.document.findall(addnodes.pending_xref):
content = self.find_pending_xref_condition(node, ('resolved', '*'))
if content:
contnode = cast('Element', content[0].deepcopy())
else:
contnode = cast('Element', node[0].deepcopy())
new_node = self._resolve_pending_xref(node, contnode)
if new_node:
new_nodes: list[Node] = [new_node]
else:
new_nodes = [contnode]
if new_node is None and isinstance(
node[0], addnodes.pending_xref_condition
):
matched = self.find_pending_xref_condition(node, ('*',))
if matched:
new_nodes = matched
else:
msg = __(
'Could not determine the fallback text for the '
'cross-reference. Might be a bug.'
)
logger.warning(msg, location=node)
node.replace_self(new_nodes)
def _resolve_pending_xref(
self, node: addnodes.pending_xref, contnode: Element
) -> nodes.reference | None:
new_node: nodes.reference | None
typ = node['reftype']
target = node['reftarget']
ref_doc = node.setdefault('refdoc', self.env.current_document.docname)
ref_domain = node.get('refdomain', '')
domain: Domain | None
if ref_domain:
try:
domain = self.env.domains[ref_domain]
except KeyError:
return None
else:
domain = None
try:
new_node = self._resolve_pending_xref_in_domain(
domain=domain,
node=node,
contnode=contnode,
ref_doc=ref_doc,
typ=typ,
target=target,
)
except NoUri:
return None
if new_node is not None:
return new_node
try:
# no new node found? try the missing-reference event
new_node = self.env.events.emit_firstresult(
'missing-reference',
self.env,
node,
contnode,
allowed_exceptions=(NoUri,),
)
except NoUri:
return None
if new_node is not None:
return new_node
# Is this a self-referential intersphinx reference?
if 'intersphinx_self_referential' in node:
del node.attributes['intersphinx_self_referential']
try:
new_node = self._resolve_pending_xref_in_domain(
domain=domain,
node=node,
contnode=contnode,
ref_doc=ref_doc,
typ=typ,
target=node['reftarget'],
)
except NoUri:
return None
if new_node is not None:
return new_node
# Still not found? Emit a warning if we are in nitpicky mode
# or if the node wishes to be warned about.
self.warn_missing_reference(ref_doc, typ, target, node, domain)
return None
def _resolve_pending_xref_in_domain(
self,
*,
domain: Domain | None,
node: addnodes.pending_xref,
contnode: Element,
ref_doc: str,
typ: str,
target: str,
) -> nodes.reference | None:
builder = self.env._app.builder
# let the domain try to resolve the reference
if domain is not None:
return domain.resolve_xref(
self.env, ref_doc, builder, typ, target, node, contnode
)
# really hardwired reference types
if typ == 'any':
return self._resolve_pending_any_xref(
node=node, contnode=contnode, ref_doc=ref_doc, target=target
)
return None
def _resolve_pending_any_xref(
self,
*,
node: addnodes.pending_xref,
contnode: Element,
ref_doc: str,
target: str,
) -> nodes.reference | None:
"""Resolve reference generated by the "any" role."""
env = self.env
builder = self.env._app.builder
domains = env.domains
results: list[tuple[str, nodes.reference]] = []
# first, try resolving as :doc:
doc_ref = domains.standard_domain.resolve_xref(
env, ref_doc, builder, 'doc', target, node, contnode
)
if doc_ref:
results.append(('doc', doc_ref))
# next, do the standard domain (makes this a priority)
results += domains.standard_domain.resolve_any_xref(
env, ref_doc, builder, target, node, contnode
)
for domain in domains.sorted():
if domain.name == 'std':
continue # we did this one already
try:
results += domain.resolve_any_xref(
env, ref_doc, builder, target, node, contnode
)
except NotImplementedError:
# the domain doesn't yet support the new interface
# we have to manually collect possible references (SLOW)
for role in domain.roles:
res = domain.resolve_xref(
env, ref_doc, builder, role, target, node, contnode
)
if res and len(res) > 0 and isinstance(res[0], nodes.Element):
results.append((f'{domain.name}:{role}', res))
# now, see how many matches we got...
if not results:
return None
if len(results) > 1:
candidates = ' or '.join(starmap(self._stringify, results))
msg = __(
"more than one target found for 'any' cross-reference %r: could be %s"
)
logger.warning(
msg, target, candidates, location=node, type='ref', subtype='any'
)
res_role, new_node = results[0]
# Override "any" class with the actual role type to get the styling
# approximately correct.
res_domain = res_role.partition(':')[0]
if (
len(new_node) > 0
and isinstance(new_node[0], nodes.Element)
and new_node[0].get('classes')
):
new_node[0]['classes'].extend((res_domain, res_role.replace(':', '-')))
return new_node
@staticmethod
def _stringify(name: str, node: Element) -> str:
reftitle = node.get('reftitle', node.astext())
return f':{name}:`{reftitle}`'
def warn_missing_reference(
self,
refdoc: str,
typ: str,
target: str,
node: pending_xref,
domain: Domain | None,
) -> None:
warn = node.get('refwarn')
if self.config.nitpicky:
warn = True
dtype = f'{domain.name}:{typ}' if domain else typ
if self.config.nitpick_ignore:
if (dtype, target) in self.config.nitpick_ignore:
warn = False
# for "std" types also try without domain name
if (
(not domain or domain.name == 'std')
and (typ, target) in self.config.nitpick_ignore
): # fmt: skip
warn = False
if self.config.nitpick_ignore_regex:
if _matches_ignore(self.config.nitpick_ignore_regex, dtype, target):
warn = False
# for "std" types also try without domain name
if not domain or domain.name == 'std':
if _matches_ignore(self.config.nitpick_ignore_regex, typ, target):
warn = False
if not warn:
return
if self.env.events.emit_firstresult('warn-missing-reference', domain, node):
return
elif domain and typ in domain.dangling_warnings:
msg = domain.dangling_warnings[typ] % {'target': target}
elif node.get('refdomain', 'std') not in {'', 'std'}:
msg = __('%s:%s reference target not found: %s') % (
node['refdomain'],
typ,
target,
)
else:
msg = __('%r reference target not found: %s') % (typ, target)
logger.warning(msg, location=node, type='ref', subtype=typ)
def find_pending_xref_condition(
self,
node: pending_xref,
conditions: Sequence[str],
) -> list[Node] | None:
for condition in conditions:
matched = find_pending_xref_condition(node, condition)
if matched:
return matched.children
return None
def _matches_ignore(
ignore_patterns: Sequence[tuple[str, str]], entry_type: str, entry_target: str
) -> bool:
return any(
(
re.fullmatch(ignore_type, entry_type)
and re.fullmatch(ignore_target, entry_target)
)
for ignore_type, ignore_target in ignore_patterns
)
| ReferencesResolver |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.