uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
37be79c95e1df664cf7cfdd5 | train | function | def downgrade_fitter():
pass
| def downgrade_fitter():
| pass
| nullable=True))
### end Alembic commands ###
def downgrade_account():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('customer', 'email_confirmed')
### end Alembic commands ###
def upgrade_fitter():
pass
def downgrade_fitter():
| 64 | 64 | 8 | 5 | 58 | deti/boss | backend/model/migrate/versions/1d6f96d1df_.py | Python | downgrade_fitter | downgrade_fitter | 46 | 47 | 46 | 46 | a9942b46a2e79732019aa4d48cd4e998ad31e5a0 | bigcode/the-stack | train |
bfc2d717bc78ab5f3306340f | train | function | def downgrade_account():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('customer', 'email_confirmed')
| def downgrade_account():
### commands auto generated by Alembic - please adjust! ###
| op.drop_column('customer', 'email_confirmed')
| upgrade_account():
### commands auto generated by Alembic - please adjust! ###
op.add_column('customer', sa.Column('email_confirmed', sa.Boolean(), nullable=True))
### end Alembic commands ###
def downgrade_account():
### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 30 | 18 | 45 | deti/boss | backend/model/migrate/versions/1d6f96d1df_.py | Python | downgrade_account | downgrade_account | 36 | 38 | 36 | 37 | dc7a58901877edc2ebcedd7045a0c91e9461e36e | bigcode/the-stack | train |
94955c305d34647a61d5287c | train | function | def upgrade_fitter():
pass
| def upgrade_fitter():
| pass
| ('email_confirmed', sa.Boolean(), nullable=True))
### end Alembic commands ###
def downgrade_account():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('customer', 'email_confirmed')
### end Alembic commands ###
def upgrade_fitter():
| 63 | 64 | 8 | 5 | 58 | deti/boss | backend/model/migrate/versions/1d6f96d1df_.py | Python | upgrade_fitter | upgrade_fitter | 42 | 43 | 42 | 42 | 15bc5c2960d1efebe22a437ba3a7dd96184098cb | bigcode/the-stack | train |
6e6652bfa34c932b1f100802 | train | class | class ImportTaskMessage(PrimordialModel):
TYPE_INFO = constants.ImportTaskMessageType.INFO.value
TYPE_WARNING = constants.ImportTaskMessageType.WARNING.value
TYPE_SUCCESS = constants.ImportTaskMessageType.SUCCESS.value
# FIXME(cutwater): ERROR and FAILED types seem to be redundant
TYPE_FAILED = cons... | class ImportTaskMessage(PrimordialModel):
| TYPE_INFO = constants.ImportTaskMessageType.INFO.value
TYPE_WARNING = constants.ImportTaskMessageType.WARNING.value
TYPE_SUCCESS = constants.ImportTaskMessageType.SUCCESS.value
# FIXME(cutwater): ERROR and FAILED types seem to be redundant
TYPE_FAILED = constants.ImportTaskMessageType.FAILED.value
... | message_text=message)
self.save()
def finish_failed(self, reason=None):
self.state = ImportTask.STATE_FAILED
self.finished = timezone.now()
if reason:
# FIXME(cutwater): Remove truncating reason to 256 chars.
# Use TruncatingC... | 105 | 105 | 351 | 9 | 96 | dinivas/ansible-galaxy | galaxy/main/models/importing.py | Python | ImportTaskMessage | ImportTaskMessage | 118 | 171 | 118 | 118 | 53bda882c0750d69537ae2cd8d7c6e51dd2eaa9f | bigcode/the-stack | train |
ac3a81f9f756f54e526ff23a | train | class | class ImportTask(PrimordialModel):
class Meta:
ordering = ('-id',)
get_latest_by = 'created'
# TODO(cutwater): Constants left for backward compatibility, to be removed
STATE_PENDING = constants.ImportTaskState.PENDING.value
STATE_RUNNING = constants.ImportTaskState.RUNNING.value
STA... | class ImportTask(PrimordialModel):
| class Meta:
ordering = ('-id',)
get_latest_by = 'created'
# TODO(cutwater): Constants left for backward compatibility, to be removed
STATE_PENDING = constants.ImportTaskState.PENDING.value
STATE_RUNNING = constants.ImportTaskState.RUNNING.value
STATE_FAILED = constants.ImportTaskSta... | from django.conf import settings
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.utils import timezone
from galaxy import constants
from .base import PrimordialModel
class ImportTask(PrimordialModel):
| 52 | 192 | 642 | 8 | 43 | dinivas/ansible-galaxy | galaxy/main/models/importing.py | Python | ImportTask | ImportTask | 10 | 115 | 10 | 10 | 028ee5e3e0748e3ac84c2e0df47cb97a7b48afef | bigcode/the-stack | train |
410b4527c0139213968f2585 | train | function | def As_check():
while True:
As_cal = input("\nВведите площадь требуемую по расчету, см2/1м ")
As_ef = input("\nВведите площадь фактически установленную, см2/1м ")
try:
if L0an != 0 and As_cal != '0' and As_ef != '0':
Lan = float(α1) * L0an * (float(As_... | def As_check():
| while True:
As_cal = input("\nВведите площадь требуемую по расчету, см2/1м ")
As_ef = input("\nВведите площадь фактически установленную, см2/1м ")
try:
if L0an != 0 and As_cal != '0' and As_ef != '0':
Lan = float(α1) * L0an * (float(As_cal) / float(As_e... | , то выводится L0an = n или L0an = 0 (при площади арматуры равной 0)
# если нет, то тогда программа выдает сообщение пользователю о неккоректном вводе и перезапускает цикл для введения корректого значения.
def As_check():
| 63 | 64 | 210 | 4 | 59 | DNA-Atom/Tension_anchorage_length_to_SP63.13330.2018 | Anker.py | Python | As_check | As_check | 10 | 25 | 10 | 10 | 8a950c6cb3c34f0835cce435f001240ebea78e43 | bigcode/the-stack | train |
996db4b441db59f0b6b4632c | train | class | class ZsmoothValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="zsmooth", parent_name="histogram2d", **kwargs):
super(ZsmoothValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_t... | class ZsmoothValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| def __init__(self, plotly_name="zsmooth", parent_name="histogram2d", **kwargs):
super(ZsmoothValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop("values", ["fast", "best", Fa... | import _plotly_utils.basevalidators
class ZsmoothValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| 23 | 64 | 101 | 15 | 7 | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | env/Lib/site-packages/plotly/validators/histogram2d/_zsmooth.py | Python | ZsmoothValidator | ZsmoothValidator | 4 | 12 | 4 | 4 | 2175b721f51b0d801e07952c1048e7b313b99a4e | bigcode/the-stack | train |
cc276d0f82823cae372d0275 | train | function | @app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
return redirect(url_for('bot', name=form.name.data,_external=True))
return render_template('index.html',form = form, name = form.name.data)
| @app.route('/', methods=['GET', 'POST'])
def index():
| form = NameForm()
if form.validate_on_submit():
return redirect(url_for('bot', name=form.name.data,_external=True))
return render_template('index.html',form = form, name = form.name.data)
| ', validators=[NumberRange(min=0, max=10)])
marge=IntegerField('Marge bénéficiaire (%+)', validators=[NumberRange(min=0, max=10)])
submit = SubmitField('Calculer le prix des tshirts')
@app.route('/', methods=['GET', 'POST'])
def index():
| 64 | 64 | 60 | 13 | 51 | louisjkender/francetex_bot | hello.py | Python | index | index | 52 | 57 | 52 | 53 | a9c3b2a6f5cdfab1a74dcbc2b0c3cf024b27da59 | bigcode/the-stack | train |
4359b3081b9dd62d2b0f2750 | train | class | class NameForm(FlaskForm):
name = StringField('Quel est votre nom?', validators=[DataRequired()])
submit = SubmitField('Faire le devis')
| class NameForm(FlaskForm):
| name = StringField('Quel est votre nom?', validators=[DataRequired()])
submit = SubmitField('Faire le devis')
| _KEY'] = 'severine'
quantityfeuille=0
produitparfeuille=0
quantity=50
size=0
color=0
coeur=0
carre=0
big=0
marge=0
lock=True
class NameForm(FlaskForm):
| 64 | 64 | 34 | 8 | 55 | louisjkender/francetex_bot | hello.py | Python | NameForm | NameForm | 34 | 36 | 34 | 34 | ef5d5fcb56601c4243d8091942f5e3bef80d83d4 | bigcode/the-stack | train |
35baec34c6d7e55a5238dadd | train | class | class FormDevis(FlaskForm):
title = SelectField('Produit', [DataRequired()], choices=[('hoodie', 'hoodie'),('casquette', 'casquette'),('t-shirt','t-shirt'),('sweat','sweat')])
quantity = IntegerField('Quantité?', validators=[NumberRange(min=0, max=1000)])
printype=SelectField('Quelle impression ... | class FormDevis(FlaskForm):
| title = SelectField('Produit', [DataRequired()], choices=[('hoodie', 'hoodie'),('casquette', 'casquette'),('t-shirt','t-shirt'),('sweat','sweat')])
quantity = IntegerField('Quantité?', validators=[NumberRange(min=0, max=1000)])
printype=SelectField('Quelle impression souhaitez-vous', [DataRequir... | 0
quantity=50
size=0
color=0
coeur=0
carre=0
big=0
marge=0
lock=True
class NameForm(FlaskForm):
name = StringField('Quel est votre nom?', validators=[DataRequired()])
submit = SubmitField('Faire le devis')
class FormDevis(FlaskForm):
| 79 | 79 | 266 | 9 | 70 | louisjkender/francetex_bot | hello.py | Python | FormDevis | FormDevis | 39 | 49 | 39 | 39 | 612a46c04225b260e411aa49345a729872117bdf | bigcode/the-stack | train |
d09c27cb6256bb24deebf0e6 | train | function | @app.route('/bot/<name>', methods=['GET', 'POST'])
def bot(name):
marge=0
lettragecoeur=0
form = FormDevis()
quantity=form.quantity.data
lettragecoeur=form.lettragecoeur.data
coeur=form.coeur.data
carre=form.carre.data
big=form.big.data
title=form.title.data
color=form.color.da... | @app.route('/bot/<name>', methods=['GET', 'POST'])
def bot(name):
| marge=0
lettragecoeur=0
form = FormDevis()
quantity=form.quantity.data
lettragecoeur=form.lettragecoeur.data
coeur=form.coeur.data
carre=form.carre.data
big=form.big.data
title=form.title.data
color=form.color.data
marge=form.marge.data
if title=="hoodie":
produ... | -vous', [DataRequired()], choices=[('impression', 'impression'),('broderie', 'broderie')])
lettragecoeur = IntegerField('lettrage coeur?', validators=[NumberRange(min=0, max=10)])
coeur = IntegerField('logo coeur?', validators=[NumberRange(min=0, max=10)])
carre = IntegerField('logo carre?', val... | 256 | 256 | 1,997 | 18 | 238 | louisjkender/francetex_bot | hello.py | Python | bot | bot | 59 | 291 | 59 | 61 | aa1094045a5e40640c4b282200e43a874a80e0a8 | bigcode/the-stack | train |
675397e56dd06c6e662a8ddf | train | function | def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
| def from_union(fs, x):
| for f in fs:
try:
return f(x)
except:
pass
assert False
| isinstance(x, str)
return x
def from_int(x: Any) -> int:
assert isinstance(x, int) and not isinstance(x, bool)
return x
def from_none(x: Any) -> Any:
assert x is None
return x
def from_union(fs, x):
| 64 | 64 | 31 | 7 | 56 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | from_union | from_union | 23 | 29 | 23 | 23 | 6e61cc59bbfd9455f8d672909f37791480352617 | bigcode/the-stack | train |
31834e0b1c92e26bdd5407f7 | train | function | def to_float(x: Any) -> float:
assert isinstance(x, float)
return x
| def to_float(x: Any) -> float:
| assert isinstance(x, float)
return x
| f in fs:
try:
return f(x)
except:
pass
assert False
def from_float(x: Any) -> float:
assert isinstance(x, (float, int)) and not isinstance(x, bool)
return float(x)
def to_float(x: Any) -> float:
| 64 | 64 | 21 | 10 | 54 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | to_float | to_float | 37 | 39 | 37 | 37 | b3469562b233aadbb56c4db9e33d7acd2904633f | bigcode/the-stack | train |
00073d047ae52ec93e764db0 | train | class | @dataclass
class Doc:
journal_id: str
rank: int
normalized_name: str
display_name: str
webpage: Optional[str]
paper_count: int
citation_count: int
created_date: str
version: float
issn: Optional[str]
@staticmethod
def from_dict(obj: Any) -> 'Doc':
assert isinstan... | @dataclass
class Doc:
| journal_id: str
rank: int
normalized_name: str
display_name: str
webpage: Optional[str]
paper_count: int
citation_count: int
created_date: str
version: float
issn: Optional[str]
@staticmethod
def from_dict(obj: Any) -> 'Doc':
assert isinstance(obj, dict)
... | int) and not isinstance(x, bool)
return x
def from_none(x: Any) -> Any:
assert x is None
return x
def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
def from_float(x: Any) -> float:
assert isinstance(x, (float, int)) and ... | 123 | 123 | 413 | 6 | 116 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | Doc | Doc | 42 | 82 | 42 | 43 | e27eccaf13c2af750e62b07fb694705c72e9acc3 | bigcode/the-stack | train |
725c1b02ef5112802a829c9c | train | function | def from_float(x: Any) -> float:
assert isinstance(x, (float, int)) and not isinstance(x, bool)
return float(x)
| def from_float(x: Any) -> float:
| assert isinstance(x, (float, int)) and not isinstance(x, bool)
return float(x)
| return x
def from_none(x: Any) -> Any:
assert x is None
return x
def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
def from_float(x: Any) -> float:
| 64 | 64 | 32 | 10 | 53 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | from_float | from_float | 32 | 34 | 32 | 32 | 3aade9dddac02048a8991ef421ed6bd388de27ec | bigcode/the-stack | train |
b1803db97a613105df4c2388 | train | function | def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
| def from_str(x: Any) -> str:
| assert isinstance(x, str)
return x
| from dataclasses import dataclass
from typing import Optional, Any, TypeVar
T = TypeVar("T")
def from_str(x: Any) -> str:
| 34 | 64 | 21 | 10 | 24 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | from_str | from_str | 8 | 10 | 8 | 8 | eafd339f1e2e54ab61f42e7bd9d7d3df073b8224 | bigcode/the-stack | train |
a5ef8e5488cb147bd5c30281 | train | function | def from_none(x: Any) -> Any:
assert x is None
return x
| def from_none(x: Any) -> Any:
| assert x is None
return x
| TypeVar("T")
def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
def from_int(x: Any) -> int:
assert isinstance(x, int) and not isinstance(x, bool)
return x
def from_none(x: Any) -> Any:
| 64 | 64 | 20 | 10 | 53 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | from_none | from_none | 18 | 20 | 18 | 18 | d4ae3138f11a1424c2c57e6a008418fd115cee88 | bigcode/the-stack | train |
47daed5df7e098d4fa66ee6a | train | function | def from_int(x: Any) -> int:
assert isinstance(x, int) and not isinstance(x, bool)
return x
| def from_int(x: Any) -> int:
| assert isinstance(x, int) and not isinstance(x, bool)
return x
| from dataclasses import dataclass
from typing import Optional, Any, TypeVar
T = TypeVar("T")
def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
def from_int(x: Any) -> int:
| 55 | 64 | 28 | 10 | 44 | sonne-academic/solr-utils | data/mag/data_classes/journal_mag.py | Python | from_int | from_int | 13 | 15 | 13 | 13 | 0ad8ac659817de8350688f264a27cf316662f254 | bigcode/the-stack | train |
5b84af455da6104fa33af580 | train | function | def get_ext_modules():
""""
Generate C extensions
1. By default already Cython generated *.c files are used.
2. If *.c files are not present Cython generates them.
3. If the option '--cython' is specified Cython generates new *.c files.
"""
# Check if *.c files are already there
file_l... | def get_ext_modules():
| """"
Generate C extensions
1. By default already Cython generated *.c files are used.
2. If *.c files are not present Cython generates them.
3. If the option '--cython' is specified Cython generates new *.c files.
"""
# Check if *.c files are already there
file_list = ['qmeq/approach/c... | import os
import sys
import numpy as np
from setuptools import setup, Extension
def get_ext_modules():
| 23 | 175 | 586 | 5 | 17 | gedaskir/test-deploy-qmeq | setup.py | Python | get_ext_modules | get_ext_modules | 8 | 71 | 8 | 8 | 6004de96d4a45dcf461c97d8fb32fd0107be80c2 | bigcode/the-stack | train |
86bb370a3524a4367bb66d92 | train | class | class IdentityGate(OneQubitGate):
"""The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('1')
gate_name_latex = u('1')
def get_target_matrix(self, format='sympy'):
ret... | class IdentityGate(OneQubitGate):
| """The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('1')
gate_name_latex = u('1')
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('eye2'... | ._eval_anticommutator(self, other, **hints)
class TwoQubitGate(Gate):
"""A two qubit unitary gate base class."""
nqubits = Integer(2)
#-----------------------------------------------------------------------------
# Single Qubit Gates
#-------------------------------------------------------------------------... | 63 | 64 | 135 | 9 | 54 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | IdentityGate | IdentityGate | 609 | 631 | 609 | 609 | feef68a603954c1b93cfd549e2e1bf05e1f78972 | bigcode/the-stack | train |
d6cfb13d3747847918b31196 | train | function | def _validate_targets_controls(tandc):
tandc = list(tandc)
# Check for integers
for bit in tandc:
if not bit.is_Integer and not bit.is_Symbol:
raise TypeError('Integer expected, got: %r' % tandc[bit])
# Detect duplicates
if len(list(set(tandc))) != len(tandc):
raise Quant... | def _validate_targets_controls(tandc):
| tandc = list(tandc)
# Check for integers
for bit in tandc:
if not bit.is_Integer and not bit.is_Symbol:
raise TypeError('Integer expected, got: %r' % tandc[bit])
# Detect duplicates
if len(list(set(tandc))) != len(tandc):
raise QuantumError(
'Target/control qu... | qrt(2) normalization factor?
When True, the Hadamard gate will have the 1/sqrt(2). When False, the
Hadamard gate will not have this factor.
"""
global _normalized
_normalized = normalize
def _validate_targets_controls(tandc):
| 64 | 64 | 103 | 9 | 54 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | _validate_targets_controls | _validate_targets_controls | 108 | 118 | 108 | 108 | 2170b94c06792933eaa143f3f00ce897010dbf93 | bigcode/the-stack | train |
f8f88cacb32df9b37febd9c2 | train | class | class TGate(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
... | class TGate(OneQubitGate):
| """The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('T')
... | matrix_cache.get_matrix('S', format)
def _eval_commutator_ZGate(self, other, **hints):
return Integer(0)
def _eval_commutator_TGate(self, other, **hints):
return Integer(0)
class TGate(OneQubitGate):
| 64 | 64 | 173 | 9 | 55 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | TGate | TGate | 805 | 830 | 805 | 805 | 406901cf8edc1db057aa857a437a517d422c3344 | bigcode/the-stack | train |
0a7ce34e8c70ae2b91e2dada | train | class | class HadamardGate(HermitianOperator, OneQubitGate):
"""The single qubit Hadamard gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
>>> from sympy import sqrt
>>> from sympy.physics.quantum.qubit import Qubit
>>> from symp... | class HadamardGate(HermitianOperator, OneQubitGate):
| """The single qubit Hadamard gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
>>> from sympy import sqrt
>>> from sympy.physics.quantum.qubit import Qubit
>>> from sympy.physics.quantum.gate import HadamardGate
>>> fr... | ):
"""The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('1')
gate_name_latex = u('1')
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('ey... | 142 | 142 | 476 | 15 | 126 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | HadamardGate | HadamardGate | 634 | 682 | 634 | 634 | e2085050372a6a53a2453616473bd57f269ce4f8 | bigcode/the-stack | train |
129e8f6cdc4391f147fb5eb8 | train | function | def _max(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
| def _max(*args, **kwargs):
| if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
| ',
'Phase',
'normalized',
'gate_sort',
'gate_simp',
'random_circuit',
'CPHASE',
'CGateS',
]
#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------
_normalized = True
... | 64 | 64 | 37 | 9 | 54 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | _max | _max | 79 | 82 | 79 | 79 | 20c0b4bab5b7e3fb2f5696fae93b5410a181e672 | bigcode/the-stack | train |
7f92fd1f858975c1dfbd62c0 | train | function | def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
"""Represent a gate with controls, targets and target_matrix.
This function does the low-level work of representing gates as matrices
in the standard computational basis (ZGate). Currently, we support two
main cases:
... | def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
| """Represent a gate with controls, targets and target_matrix.
This function does the low-level work of representing gates as matrices
in the standard computational basis (ZGate). Currently, we support two
main cases:
1. One target qubit and no control qubits.
2. One target qubits and multiple ... | op00 = matrix_cache.get_matrix('op00', format)
eye2 = matrix_cache.get_matrix('eye2', format)
result = None
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
product = nqubits*[eye2]
product[nqubits - min_target - 1] = i
product[nqubits -... | 208 | 209 | 697 | 21 | 187 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | represent_zbasis | represent_zbasis | 1,039 | 1,116 | 1,039 | 1,039 | db0d2619c9ed23786b3428fc37a852a33466722c | bigcode/the-stack | train |
56a69a70fbe1a6e24daacd97 | train | function | def normalized(normalize):
"""Set flag controlling normalization of Hadamard gates by 1/sqrt(2).
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate.
Parameters
----------
normalize : bool
Shou... | def normalized(normalize):
| """Set flag controlling normalization of Hadamard gates by 1/sqrt(2).
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate.
Parameters
----------
normalize : bool
Should the Hadamard gate includ... | in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
def _min(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
def normalized(normalize):
| 64 | 64 | 140 | 5 | 59 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | normalized | normalized | 91 | 105 | 91 | 91 | 4457217a96d00a68999d291c1af23440c375d481 | bigcode/the-stack | train |
871b6be2069215d0fa8e1d4b | train | function | def zy_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to Y basis."""
return matrix_cache.get_matrix('ZY', format)
| def zy_basis_transform(self, format='sympy'):
| """Transformation matrix from Z to Y basis."""
return matrix_cache.get_matrix('ZY', format)
| bit_space)
g = g(qubit)
result.append(g)
return Mul(*result)
def zx_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
def zy_basis_transform(self, format='sympy'):
| 64 | 64 | 32 | 11 | 53 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | zy_basis_transform | zy_basis_transform | 1,288 | 1,290 | 1,288 | 1,288 | 3e67a24fc3448719f29ad16c63ac319ffe785c1e | bigcode/the-stack | train |
fc4b1eba88a65bdb3042c79e | train | function | def gate_simp(circuit):
"""Simplifies gates symbolically
It first sorts gates using gate_sort. It then applies basic
simplification rules to the circuit, e.g., XGate**2 = Identity
"""
# Bubble sort out gates that commute.
circuit = gate_sort(circuit)
# Do simplifications by subing a simpl... | def gate_simp(circuit):
| """Simplifies gates symbolically
It first sorts gates using gate_sort. It then applies basic
simplification rules to the circuit, e.g., XGate**2 = Identity
"""
# Bubble sort out gates that commute.
circuit = gate_sort(circuit)
# Do simplifications by subing a simplification into the first... | return matrix_tensor_product(*product)
# Single target, multiple controls.
elif len(targets) == 1 and len(controls) >= 1:
target = targets[0]
# Build the non-trivial part.
product2 = []
for i in range(nqubits):
product2.append(matrix_eye(2, format=format))
... | 197 | 198 | 663 | 7 | 190 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | gate_simp | gate_simp | 1,124 | 1,190 | 1,124 | 1,124 | 7ca56e862903240bd3ef194f7a06b1443cb52b4c | bigcode/the-stack | train |
3696ba192e5d66531ceaf996 | train | class | class TwoQubitGate(Gate):
"""A two qubit unitary gate base class."""
nqubits = Integer(2)
| class TwoQubitGate(Gate):
| """A two qubit unitary gate base class."""
nqubits = Integer(2)
| if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return Integer(2)*self*other
return Operator._eval_anticommutator(self, other, **hints)
class TwoQubitGate(Gate):
| 64 | 64 | 29 | 8 | 56 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | TwoQubitGate | TwoQubitGate | 599 | 602 | 599 | 599 | 5ccfc730fdafa93c36d23eb3b68a4c1c6fe35137 | bigcode/the-stack | train |
d8830715122b935fc84b3ea6 | train | function | def CPHASE(a,b): return CGateS((a,),Z(b))
| def CPHASE(a,b): | return CGateS((a,),Z(b))
| new_result = matrix_tensor_product(*product)
if result is None:
result = new_result
else:
result = result + new_result
return result
# Aliases for gate names.
CNOT = CNotGate
SWAP = SwapGate
def CPHASE(a,b): | 64 | 64 | 17 | 8 | 55 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | CPHASE | CPHASE | 1,031 | 1,031 | 1,031 | 1,031 | 9210f5ad2717b8f1a2618fd781f01f73bb054ddb | bigcode/the-stack | train |
00b98e3878a4212f9d9247e2 | train | class | class CGate(Gate):
"""A general unitary gate with control qubits.
A general control gate applies a target gate to a set of targets if all
of the control qubits have a particular values (set by
``CGate.control_value``).
Parameters
----------
label : tuple
The label in this case has ... | class CGate(Gate):
| """A general unitary gate with control qubits.
A general control gate applies a target gate to a set of targets if all
of the control qubits have a particular values (set by
``CGate.control_value``).
Parameters
----------
label : tuple
The label in this case has the form (controls,... | % nqubits
)
target_matrix = self.get_target_matrix(format)
targets = self.targets
if isinstance(self, CGate):
controls = self.controls
else:
controls = []
m = represent_zbasis(
controls, targets, target_matrix, nqubits, format
... | 255 | 256 | 1,363 | 6 | 249 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | CGate | CGate | 303 | 483 | 303 | 303 | 74ad1f741ddde82fc1e3f60f92c7dd0dfce2659b | bigcode/the-stack | train |
a48bae17fe1b19f72d4e8d2a | train | function | def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
"""Return a random circuit of ngates and nqubits.
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
gates.
Parameters
----------
ngates : int
The number of gates in the circuit.
nqu... | def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
| """Return a random circuit of ngates and nqubits.
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
gates.
Parameters
----------
ngates : int
The number of gates in the circuit.
nqubits : int
The number of qubits in the circuit.
gate_space : tuple
... | first_exp*second_exp)
circuit = sign*Mul(*new_args)
circ_array = circuit.args
changes = True
break
return circuit
#-----------------------------------------------------------------------------
# Utility functions
#----... | 76 | 77 | 257 | 33 | 43 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | random_circuit | random_circuit | 1,252 | 1,280 | 1,252 | 1,252 | 1fdcbd1dba4a7d5a2fe2a8858289f4cc9810ea7b | bigcode/the-stack | train |
ab78c32b1655026a64fa1836 | train | class | class PhaseGate(OneQubitGate):
"""The single qubit phase, or S, gate.
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
------... | class PhaseGate(OneQubitGate):
| """The single qubit phase, or S, gate.
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('... | _eval_commutator_XGate(self, other, **hints):
return Integer(2)*I*YGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(0)
class PhaseGate(OneQubitGate):
| 64 | 64 | 174 | 9 | 55 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | PhaseGate | PhaseGate | 777 | 802 | 777 | 777 | ab55d17563e4b48dd8ad921060b82bbab4964554 | bigcode/the-stack | train |
4ab04685c44cab8ed65f3c80 | train | class | class ZGate(HermitianOperator, OneQubitGate):
"""The single qubit Z gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('Z')
gate_name_latex = u('Z')
def get_target_matrix(self, format='sympy'):
... | class ZGate(HermitianOperator, OneQubitGate):
| """The single qubit Z gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('Z')
gate_name_latex = u('Z')
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Z', format)
... | ommutator_YGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_ZGate(self, other, **hints):
return Integer(0)
class ZGate(HermitianOperator, OneQubitGate):
| 64 | 64 | 149 | 13 | 51 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | ZGate | ZGate | 752 | 774 | 752 | 752 | 7f54b1133335f4a88d0d7bd22f1abbe1f9d12084 | bigcode/the-stack | train |
1145022199b556178369af28 | train | class | class YGate(HermitianOperator, OneQubitGate):
"""The single qubit Y gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('Y')
gate_name_latex = u('Y')
def get_target_matrix(self, format='sympy'):
... | class YGate(HermitianOperator, OneQubitGate):
| """The single qubit Y gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('Y')
gate_name_latex = u('Y')
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Y', format)
... | ])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(0)
def _eval_anticommutator_ZGate(self, other, **hints):
return Integer(0)
class YGate(HermitianOperator, OneQubitGate):
| 64 | 64 | 181 | 13 | 51 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | YGate | YGate | 724 | 749 | 724 | 724 | 15989a5a202ea13af58c06698a2c7c07e20122d6 | bigcode/the-stack | train |
efa294241483810b84c7ef6e | train | class | class XGate(HermitianOperator, OneQubitGate):
"""The single qubit X, or NOT, gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('X')
gate_name_latex = u('X')
def get_target_matrix(self, format='sympy'... | class XGate(HermitianOperator, OneQubitGate):
| """The single qubit X, or NOT, gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
--------
"""
gate_name = u('X')
gate_name_latex = u('X')
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('X',... | (2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(0)
def _eval_anticommutator_ZGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
class XGate(HermitianOperator, OneQubitGate):
| 80 | 80 | 268 | 13 | 67 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | XGate | XGate | 685 | 721 | 685 | 685 | a4edc9d34fdea80785eb3ec68029d0dbc094dbc5 | bigcode/the-stack | train |
eae8e6294ff587434e166c3d | train | class | class CGateS(CGate):
"""Version of CGate that allows gate simplifications.
I.e. cnot looks like an oplus, cphase has dots, etc.
"""
simplify_cgate=True
| class CGateS(CGate):
| """Version of CGate that allows gate simplifications.
I.e. cnot looks like an oplus, cphase has dots, etc.
"""
simplify_cgate=True
| exp == -1:
return Gate._eval_power(self, exp)
elif abs(exp) % 2 == 0:
return self*(Gate._eval_inverse(self))
else:
return self
else:
return Gate._eval_power(self, exp)
class CGateS(CGate):
| 64 | 64 | 46 | 7 | 57 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | CGateS | CGateS | 485 | 489 | 485 | 485 | 7f60c59c97e6a4f3b02a7ab11b969c78d5ca69d9 | bigcode/the-stack | train |
129e8eeceb3c28e46a258c15 | train | class | class OneQubitGate(Gate):
"""A single qubit unitary gate base class."""
nqubits = Integer(1)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
def _eval_commutator(self, other, **hints):
... | class OneQubitGate(Gate):
| """A single qubit unitary gate base class."""
nqubits = Integer(1)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
def _eval_commutator(self, other, **hints):
if isinstance(other, ... | '%s_{%s}' % (self.gate_name_latex, targets)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
class OneQubitGate(Gate):
| 64 | 64 | 206 | 8 | 56 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | OneQubitGate | OneQubitGate | 575 | 596 | 575 | 575 | 120220bb6839928622344f749cf675e84e419b6a | bigcode/the-stack | train |
385f8af82344c333e02afab1 | train | class | class SwapGate(TwoQubitGate):
"""Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
--------
"""
gate_name = 'SWAP'
gate_name_latex = u('SWAP')
def get_target_matr... | class SwapGate(TwoQubitGate):
| """Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
--------
"""
gate_name = 'SWAP'
gate_name_latex = u('SWAP')
def get_target_matrix(self, format='sympy'):
... | return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_XGate(self, other, **hints):
"""[CNOT(i, j), X(j)] == 0."""
if self.targets[0] == other.targets[0]:
return Integer(0)
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
... | 173 | 173 | 577 | 9 | 164 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | SwapGate | SwapGate | 961 | 1,025 | 961 | 961 | 4b42c43bed014e9e2e7d94dc9718e6bc41838fb4 | bigcode/the-stack | train |
9987531653330648055cabb1 | train | function | def gate_sort(circuit):
"""Sorts the gates while keeping track of commutation relations
This function uses a bubble sort to rearrange the order of gate
application. Keeps track of Quantum computations special commutation
relations (e.g. things that apply to the same Qubit do not commute with
each o... | def gate_sort(circuit):
| """Sorts the gates while keeping track of commutation relations
This function uses a bubble sort to rearrange the order of gate
application. Keeps track of Quantum computations special commutation
relations (e.g. things that apply to the same Qubit do not commute with
each other)
circuit is th... | break
elif isinstance(circuit_args[i].base, TGate):
# Build a new circuit taking all the old elements.
newargs = circuit_args[:i]
# Put an Phasegate in place of any TGate**2.
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
... | 156 | 156 | 521 | 6 | 149 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | gate_sort | gate_sort | 1,193 | 1,244 | 1,193 | 1,193 | 30d99d43dde073bc18467e7bdfae85b39ad879c3 | bigcode/the-stack | train |
8d9ceae18a88b293d602e9d5 | train | class | class CNotGate(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
-------... | class CNotGate(HermitianOperator, CGate, TwoQubitGate):
| """Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
--------
>>> from sympy.physics.quantum.gate import CNOT
... | other, **hints):
return Integer(0)
class TGate(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will ... | 254 | 255 | 852 | 17 | 237 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | CNotGate | CNotGate | 847 | 958 | 847 | 847 | c750f106dbccb97a55d9783b68f17c9f4b261755 | bigcode/the-stack | train |
bd478e90d1b5e3acd312b083 | train | function | def zx_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
| def zx_basis_transform(self, format='sympy'):
| """Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
| :
qubits = random.sample(qubit_space, 2)
g = g(*qubits)
else:
qubit = random.choice(qubit_space)
g = g(qubit)
result.append(g)
return Mul(*result)
def zx_basis_transform(self, format='sympy'):
| 64 | 64 | 32 | 11 | 53 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | zx_basis_transform | zx_basis_transform | 1,283 | 1,285 | 1,283 | 1,283 | 52d2b80872eb93933599af6226cd24cba2eec3fa | bigcode/the-stack | train |
13a831baaa133fd3beef828d | train | class | class Gate(UnitaryOperator):
"""Non-controlled unitary gate operator that acts on qubits.
This is a general abstract gate that needs to be subclassed to do anything
useful.
Parameters
----------
label : tuple, int
A list of the target qubits (as ints) that the gate will apply to.
... | class Gate(UnitaryOperator):
| """Non-controlled unitary gate operator that acts on qubits.
This is a general abstract gate that needs to be subclassed to do anything
useful.
Parameters
----------
label : tuple, int
A list of the target qubits (as ints) that the gate will apply to.
Examples
--------
"... | min(*args, **kwargs)
def normalized(normalize):
"""Set flag controlling normalization of Hadamard gates by 1/sqrt(2).
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate.
Parameters
----------
norma... | 256 | 256 | 1,280 | 6 | 250 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | Gate | Gate | 121 | 300 | 121 | 121 | 3a953f14a71eb11ccf41a10e39e14cf93ce9a0a6 | bigcode/the-stack | train |
14a969f0a8dbed38a113d489 | train | function | def _min(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
| def _min(*args, **kwargs):
| if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
| ',
]
#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------
_normalized = True
def _max(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*a... | 64 | 64 | 37 | 9 | 55 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | _min | _min | 85 | 88 | 85 | 85 | b8652694e0ae503733711af5198cbc6898584647 | bigcode/the-stack | train |
39ac2a4f1c55ac73262db2f8 | train | class | class UGate(Gate):
"""General gate specified by a set of targets and a target matrix.
Parameters
----------
label : tuple
A tuple of the form (targets, U), where targets is a tuple of the
target qubits and U is a unitary matrix with dimension of
len(targets).
"""
gate_na... | class UGate(Gate):
| """General gate specified by a set of targets and a target matrix.
Parameters
----------
label : tuple
A tuple of the form (targets, U), where targets is a tuple of the
target qubits and U is a unitary matrix with dimension of
len(targets).
"""
gate_name = u('U')
gat... | )
def _eval_inverse(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self.gate, HermitianOperator):
if exp == -1:
return Gate._eval_power(s... | 165 | 165 | 552 | 6 | 158 | nishithshah2211/sympy | sympy/physics/quantum/gate.py | Python | UGate | UGate | 492 | 572 | 492 | 492 | 17b4e71d489d216de5fda44406cd4b5bbd6a4f19 | bigcode/the-stack | train |
247b678c9cde2daa4a39862b | train | function | def random_hsv_in_yiq(
image: TensorLike,
max_delta_hue: Number = 0,
lower_saturation: Number = 1,
upper_saturation: Number = 1,
lower_value: Number = 1,
upper_value: Number = 1,
seed: Optional[int] = None,
name: Optional[str] = None,
) -> tf.Tensor:
"""Adjust hue, saturation, value ... | def random_hsv_in_yiq(
image: TensorLike,
max_delta_hue: Number = 0,
lower_saturation: Number = 1,
upper_saturation: Number = 1,
lower_value: Number = 1,
upper_value: Number = 1,
seed: Optional[int] = None,
name: Optional[str] = None,
) -> tf.Tensor:
| """Adjust hue, saturation, value of an RGB image randomly in YIQ color space.
Equivalent to `adjust_yiq_hsv()` but uses a `delta_h` randomly
picked in the interval `[-max_delta_hue, max_delta_hue]`, a
`scale_saturation` randomly picked in the interval
`[lower_saturation, upper_saturation]`, and a `... | 2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License... | 214 | 214 | 714 | 86 | 128 | leandro-gracia-gil/addons | tensorflow_addons/image/distort_image_ops.py | Python | random_hsv_in_yiq | random_hsv_in_yiq | 26 | 99 | 26 | 35 | 3dfbbf0086e94c1617e562e7f63408b9669bc1e2 | bigcode/the-stack | train |
5556c5cf16575032919304fc | train | function | def adjust_hsv_in_yiq(
image: TensorLike,
delta_hue: Number = 0,
scale_saturation: Number = 1,
scale_value: Number = 1,
name: Optional[str] = None,
) -> tf.Tensor:
"""Adjust hue, saturation, value of an RGB image in YIQ color space.
This is a convenience method that converts an RGB image to... | def adjust_hsv_in_yiq(
image: TensorLike,
delta_hue: Number = 0,
scale_saturation: Number = 1,
scale_value: Number = 1,
name: Optional[str] = None,
) -> tf.Tensor:
| """Adjust hue, saturation, value of an RGB image in YIQ color space.
This is a convenience method that converts an RGB image to float
representation, converts it to YIQ, rotates the color around the
Y channel by delta_hue in radians, scales the chrominance channels
(I, Q) by scale_saturation, scale... | [], lower_saturation, upper_saturation, seed=seed
)
if lower_value == upper_value:
scale_value = lower_value
else:
scale_value = tf.random.uniform([], lower_value, upper_value, seed=seed)
return adjust_hsv_in_yiq(
image, delta_hue, ... | 138 | 138 | 463 | 57 | 81 | leandro-gracia-gil/addons | tensorflow_addons/image/distort_image_ops.py | Python | adjust_hsv_in_yiq | adjust_hsv_in_yiq | 102 | 144 | 102 | 108 | 44077fba4ee095de8cfc3ad4f8bddeda56b362c9 | bigcode/the-stack | train |
c8374358ababe0f8ba36869a | train | class | class ImportTodoListTemplateFromSpreadsheetForm(forms.Form):
spreadsheet_url = forms.URLField(
label='Spreadsheet URL')
| class ImportTodoListTemplateFromSpreadsheetForm(forms.Form):
| spreadsheet_url = forms.URLField(
label='Spreadsheet URL')
| from django import forms
class ImportTodoListTemplateFromSpreadsheetForm(forms.Form):
| 16 | 64 | 25 | 11 | 4 | code-review-doctor/orchestra | orchestra/todos/forms.py | Python | ImportTodoListTemplateFromSpreadsheetForm | ImportTodoListTemplateFromSpreadsheetForm | 4 | 6 | 4 | 4 | 5a9c2d27600fd44f8223028caa43852c047c22ee | bigcode/the-stack | train |
b57c506e66ac73f5680b55ac | train | class | class GistTestCase(NBViewerTestCase):
@skip_unless_github_auth
def test_gist(self):
url = self.url("2352771")
r = requests.get(url)
self.assertEqual(r.status_code, 200)
@skip_unless_github_auth
def test_gist_not_nb(self):
url = self.url("6689377")
r = requests.ge... | class GistTestCase(NBViewerTestCase):
@skip_unless_github_auth
| def test_gist(self):
url = self.url("2352771")
r = requests.get(url)
self.assertEqual(r.status_code, 200)
@skip_unless_github_auth
def test_gist_not_nb(self):
url = self.url("6689377")
r = requests.get(url)
self.assertEqual(r.status_code, 400)
@skip_unle... | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (C) Jupyter Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
# ------------------------------------... | 111 | 154 | 515 | 20 | 90 | AI-Collaboratory/nbviewer | nbviewer/providers/gist/tests/test_gist.py | Python | GistTestCase | GistTestCase | 15 | 73 | 15 | 16 | 77316068b4b2e0e6b05dee4fc7cfa08f2b4efad6 | bigcode/the-stack | train |
d8f19802fb872b558cb42299 | train | class | class FormatHTMLGistTestCase(GistTestCase, FormatHTMLMixin):
pass
| class FormatHTMLGistTestCase(GistTestCase, FormatHTMLMixin):
| pass
| (url)
self.assertEqual(r.status_code, 200)
html = r.text
self.assertNotIn("paramétrica", html)
self.assertIn("paramétrica", html)
class FormatHTMLGistTestCase(GistTestCase, FormatHTMLMixin):
| 64 | 64 | 19 | 16 | 48 | AI-Collaboratory/nbviewer | nbviewer/providers/gist/tests/test_gist.py | Python | FormatHTMLGistTestCase | FormatHTMLGistTestCase | 76 | 77 | 76 | 76 | 73e04f32c75b9de8d705fb4495bea4a57a6ab9e4 | bigcode/the-stack | train |
0bbdddeeaff4150660140e88 | train | class | class NT(NamedTuple):
x: int
y: int
| class NT(NamedTuple):
| x: int
y: int
| , arg: str) -> int:
...
class Concrete(Proto):
pass
class Other:
attr: int = 1
def meth(self, arg: str) -> int:
if arg == 'this':
return 1
return 0
class NT(NamedTuple):
| 64 | 64 | 16 | 6 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | NT | NT | 815 | 817 | 815 | 815 | 674bd3114c8c0a073214a0392736687196bba849 | bigcode/the-stack | train |
fc74fd04aad0330eb04733db | train | class | class TypedDictTests(BaseTestCase):
def test_basics_functional_syntax(self):
Emp = TypedDict('Emp', {'name': str, 'id': int})
self.assertIsSubclass(Emp, dict)
self.assertIsSubclass(Emp, typing.MutableMapping)
self.assertNotIsSubclass(Emp, collections.abc.Sequence)
jim = Emp(n... | class TypedDictTests(BaseTestCase):
| def test_basics_functional_syntax(self):
Emp = TypedDict('Emp', {'name': str, 'id': int})
self.assertIsSubclass(Emp, dict)
self.assertIsSubclass(Emp, typing.MutableMapping)
self.assertNotIsSubclass(Emp, collections.abc.Sequence)
jim = Emp(name='Jim', id=1)
self.assert... | Error):
NamedTuple('Emp', [('_name', str)])
with self.assertRaises(TypeError):
NamedTuple(typename='Emp', name=str, id=int)
with self.assertRaises(TypeError):
NamedTuple('Emp', fields=[('name', str), ('id', int)])
def test_copy_and_pickle(self):
global Em... | 256 | 256 | 1,750 | 8 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | TypedDictTests | TypedDictTests | 4,127 | 4,295 | 4,127 | 4,127 | 3db311038400ee0c299532c0fafb768d43f779d2 | bigcode/the-stack | train |
6c550e30d73a04f6c1803a4f | train | class | class CoolEmployeeWithDefault(NamedTuple):
name: str
cool: int = 0
| class CoolEmployeeWithDefault(NamedTuple):
| name: str
cool: int = 0
| lst: ClassVar[List[T]] = []
class Loop:
attr: Final['Loop']
class NoneAndForward:
parent: 'NoneAndForward'
meaning: None
class CoolEmployee(NamedTuple):
name: str
cool: int
class CoolEmployeeWithDefault(NamedTuple):
| 64 | 64 | 22 | 9 | 54 | Visva92/cpython | Lib/test/test_typing.py | Python | CoolEmployeeWithDefault | CoolEmployeeWithDefault | 2,993 | 2,995 | 2,993 | 2,993 | dd626894696cbdffdae6fd633f82eabf73adf3c3 | bigcode/the-stack | train |
04a9ed5c82dec67722b0f818 | train | class | class CollectionsAbcTests(BaseTestCase):
def test_hashable(self):
self.assertIsInstance(42, typing.Hashable)
self.assertNotIsInstance([], typing.Hashable)
def test_iterable(self):
self.assertIsInstance([], typing.Iterable)
# Due to ABC caching, the second time takes a separate ... | class CollectionsAbcTests(BaseTestCase):
| def test_hashable(self):
self.assertIsInstance(42, typing.Hashable)
self.assertNotIsInstance([], typing.Hashable)
def test_iterable(self):
self.assertIsInstance([], typing.Iterable)
# Due to ABC caching, the second time takes a separate code
# path and could fail. So ca... | (get_args(Tuple[()]), ((),))
self.assertEqual(get_args(Annotated[T, 'one', 2, ['three']]), (T, 'one', 2, ['three']))
self.assertEqual(get_args(List), ())
self.assertEqual(get_args(Tuple), ())
self.assertEqual(get_args(Callable), ())
self.assertEqual(get_args(list[int]), (int,))
... | 256 | 256 | 3,677 | 9 | 247 | Visva92/cpython | Lib/test/test_typing.py | Python | CollectionsAbcTests | CollectionsAbcTests | 3,333 | 3,807 | 3,333 | 3,334 | 8777e62bf8b2c920cab64641616862044552f90b | bigcode/the-stack | train |
3b50044b6b90882f291e3fc9 | train | class | class Manager(Employee):
pass
| class Manager(Employee):
| pass
| r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
pass
class Manager(Employee):
| 64 | 64 | 7 | 4 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | Manager | Manager | 70 | 71 | 70 | 70 | 0532384cca480d062d133a5a18eb3ef798cd5997 | bigcode/the-stack | train |
cc31b51fe4590e82189010c3 | train | class | class AnyTests(BaseTestCase):
def test_any_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, Any)
def test_any_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, Any)
with self.assertRaises(TypeError):
... | class AnyTests(BaseTestCase):
| def test_any_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, Any)
def test_any_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, Any)
with self.assertRaises(TypeError):
issubclass(Any, Empl... | message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
pass
class Manager(Employee):
pass
class Founder(Employee):
pass
class ManagingFounder(Manager, Founder):
pass... | 75 | 75 | 250 | 7 | 67 | Visva92/cpython | Lib/test/test_typing.py | Python | AnyTests | AnyTests | 82 | 121 | 82 | 83 | 81310e2abf9be6a599f692886a7add27de618e1e | bigcode/the-stack | train |
94eebbc323851dc9d2cf52a5 | train | class | class ParamSpecTests(BaseTestCase):
def test_basic_plain(self):
P = ParamSpec('P')
self.assertEqual(P, P)
self.assertIsInstance(P, ParamSpec)
def test_valid_uses(self):
P = ParamSpec('P')
T = TypeVar('T')
C1 = Callable[P, int]
self.assertEqual(C1.__args_... | class ParamSpecTests(BaseTestCase):
| def test_basic_plain(self):
P = ParamSpec('P')
self.assertEqual(P, P)
self.assertIsInstance(P, ParamSpec)
def test_valid_uses(self):
P = ParamSpec('P')
T = TypeVar('T')
C1 = Callable[P, int]
self.assertEqual(C1.__args__, (P, int))
self.assertEqual... | [Annotated[T, 5]]
self.assertEqual(X[int], List[Annotated[int, 5]])
class TypeAliasTests(BaseTestCase):
def test_canonical_usage_with_variable_annotation(self):
Alias: TypeAlias = Employee
def test_canonical_usage_with_type_comment(self):
Alias = Employee # type: TypeAlias
def t... | 256 | 256 | 1,269 | 8 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | ParamSpecTests | ParamSpecTests | 4,611 | 4,742 | 4,611 | 4,612 | 53b7eba82541251db7a3a8e39a598d51815a0e26 | bigcode/the-stack | train |
69cd7ffcd923a736037c5add | train | class | class TypeGuardTests(BaseTestCase):
def test_basics(self):
TypeGuard[int] # OK
def foo(arg) -> TypeGuard[int]: ...
self.assertEqual(gth(foo), {'return': TypeGuard[int]})
def test_repr(self):
self.assertEqual(repr(TypeGuard), 'typing.TypeGuard')
cv = TypeGuard[int]
... | class TypeGuardTests(BaseTestCase):
| def test_basics(self):
TypeGuard[int] # OK
def foo(arg) -> TypeGuard[int]: ...
self.assertEqual(gth(foo), {'return': TypeGuard[int]})
def test_repr(self):
self.assertEqual(repr(TypeGuard), 'typing.TypeGuard')
cv = TypeGuard[int]
self.assertEqual(repr(cv), 'typi... | args__, (Concatenate[int, P], int))
self.assertEqual(C3.__parameters__, (P,))
C4 = collections.abc.Callable[Concatenate[int, T, P], T]
self.assertEqual(C4.__args__, (Concatenate[int, T, P], T))
self.assertEqual(C4.__parameters__, (T, P))
class TypeGuardTests(BaseTestCase):
| 85 | 85 | 285 | 8 | 77 | Visva92/cpython | Lib/test/test_typing.py | Python | TypeGuardTests | TypeGuardTests | 4,771 | 4,807 | 4,771 | 4,771 | 07fce3d88f7a9e1773be138331b87c3f5ef663f9 | bigcode/the-stack | train |
402b46b548b2b7bbb8cf12b8 | train | class | class G(Generic[T]):
lst: ClassVar[List[T]] = []
| class G(Generic[T]):
| lst: ClassVar[List[T]] = []
| from typing import AsyncContextManager
class A:
y: float
class B(A):
x: ClassVar[Optional['B']] = None
y: int
b: int
class CSub(B):
z: ClassVar['CSub'] = B()
class G(Generic[T]):
| 64 | 64 | 15 | 5 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | G | G | 2,979 | 2,980 | 2,979 | 2,979 | 2d4cb03fb20d6571ee533b04aa7469f4e94b9758 | bigcode/the-stack | train |
bd97dde048a5eebe4fcb998b | train | class | class HasForeignBaseClass(mod_generics_cache.A):
some_xrepr: 'XRepr'
other_a: 'mod_generics_cache.A'
| class HasForeignBaseClass(mod_generics_cache.A):
| some_xrepr: 'XRepr'
other_a: 'mod_generics_cache.A'
| : int
class Bar(_typed_dict_helper.Foo, total=False):
b: int
class LabelPoint2D(Point2D, Label): ...
class Options(TypedDict, total=False):
log_level: int
log_path: str
class HasForeignBaseClass(mod_generics_cache.A):
| 64 | 64 | 32 | 11 | 52 | Visva92/cpython | Lib/test/test_typing.py | Python | HasForeignBaseClass | HasForeignBaseClass | 3,025 | 3,027 | 3,025 | 3,025 | 8ccd07e574a9ba16819919c7c53357ebf76d1484 | bigcode/the-stack | train |
da147d29c8b115517f2625bd | train | class | class AllTests(BaseTestCase):
"""Tests for __all__."""
def test_all(self):
from typing import __all__ as a
# Just spot-check the first and last of every category.
self.assertIn('AbstractSet', a)
self.assertIn('ValuesView', a)
self.assertIn('cast', a)
self.assertI... | class AllTests(BaseTestCase):
| """Tests for __all__."""
def test_all(self):
from typing import __all__ as a
# Just spot-check the first and last of every category.
self.assertIn('AbstractSet', a)
self.assertIn('ValuesView', a)
self.assertIn('cast', a)
self.assertIn('overload', a)
if ha... | loaded)
self.assertEqual(SpecialAttrsP.__name__, 'SpecialAttrsP')
self.assertFalse(hasattr(SpecialAttrsP, '__qualname__'))
self.assertEqual(SpecialAttrsP.__module__, 'test.test_typing')
# Module-level ParamSpecs are picklable.
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
... | 114 | 114 | 380 | 7 | 107 | Visva92/cpython | Lib/test/test_typing.py | Python | AllTests | AllTests | 4,989 | 5,031 | 4,989 | 4,989 | c983262fc39ae07c1e40a47cb1a22d0cb545d506 | bigcode/the-stack | train |
461431242762e602ef8da192 | train | class | @runtime_checkable
class HasCallProtocol(Protocol):
__call__: typing.Callable
| @runtime_checkable
class HasCallProtocol(Protocol):
| __call__: typing.Callable
| attr: int = 1
def meth(self, arg: str) -> int:
if arg == 'this':
return 1
return 0
class NT(NamedTuple):
x: int
y: int
@runtime_checkable
class HasCallProtocol(Protocol):
| 64 | 64 | 20 | 12 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | HasCallProtocol | HasCallProtocol | 819 | 821 | 819 | 820 | e7f0e44530e08ce93adfdafa5444ed215f0bc2ce | bigcode/the-stack | train |
1ee38d0334f1d6badd702e12 | train | class | class Coordinate(Protocol):
x: int
y: int
| class Coordinate(Protocol):
| x: int
y: int
| ):
return self.store[key]
def __setitem__(self, key: str, value):
self.store[key] = value
def get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
return default
class Coordinate(Protocol):
| 64 | 64 | 15 | 5 | 58 | Visva92/cpython | Lib/test/test_typing.py | Python | Coordinate | Coordinate | 776 | 778 | 776 | 776 | 67371138d487ebcf8408585bac1d3cbd8844ee22 | bigcode/the-stack | train |
5a95e68321394371ae1b4dd5 | train | function | async def g_with(am: AsyncContextManager[int]):
x: int
async with am as x:
return x
| async def g_with(am: AsyncContextManager[int]):
| x: int
async with am as x:
return x
| class Options(TypedDict, total=False):
log_level: int
log_path: str
class HasForeignBaseClass(mod_generics_cache.A):
some_xrepr: 'XRepr'
other_a: 'mod_generics_cache.A'
async def g_with(am: AsyncContextManager[int]):
| 64 | 64 | 27 | 11 | 53 | Visva92/cpython | Lib/test/test_typing.py | Python | g_with | g_with | 3,029 | 3,032 | 3,029 | 3,029 | 9a91017eecabf3628ca6e06266621b19f9bac24f | bigcode/the-stack | train |
0bbe1be45a07142fa41c8c73 | train | class | class XMeth(NamedTuple):
x: int
def double(self):
return 2 * self.x
| class XMeth(NamedTuple):
| x: int
def double(self):
return 2 * self.x
| class NoneAndForward:
parent: 'NoneAndForward'
meaning: None
class CoolEmployee(NamedTuple):
name: str
cool: int
class CoolEmployeeWithDefault(NamedTuple):
name: str
cool: int = 0
class XMeth(NamedTuple):
| 64 | 64 | 25 | 7 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | XMeth | XMeth | 2,997 | 3,000 | 2,997 | 2,997 | fcc7bb7a68ec73c4bf3cf567bb19e9268ce5df42 | bigcode/the-stack | train |
56337d8ff870333450a8ac28 | train | class | class Concrete(Proto):
pass
| class Concrete(Proto):
| pass
|
class YAxis(Protocol):
y: int
@runtime_checkable
class Position(XAxis, YAxis, Protocol):
pass
@runtime_checkable
class Proto(Protocol):
attr: int
def meth(self, arg: str) -> int:
...
class Concrete(Proto):
| 64 | 64 | 8 | 5 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | Concrete | Concrete | 805 | 806 | 805 | 805 | 8550c862fdddb2d771d58f4aa411077259fc94c2 | bigcode/the-stack | train |
aa88cace345bd0d69c4428d4 | train | class | class CSub(B):
z: ClassVar['CSub'] = B()
| class CSub(B):
| z: ClassVar['CSub'] = B()
| .6
from test import ann_module, ann_module2, ann_module3
from typing import AsyncContextManager
class A:
y: float
class B(A):
x: ClassVar[Optional['B']] = None
y: int
b: int
class CSub(B):
| 64 | 64 | 17 | 5 | 58 | Visva92/cpython | Lib/test/test_typing.py | Python | CSub | CSub | 2,977 | 2,978 | 2,977 | 2,977 | 694e04b01b37f06725e0bf7052f611fe5d7a701d | bigcode/the-stack | train |
dde2a188c9d7277890edabc4 | train | class | class XRepr(NamedTuple):
x: int
y: int = 1
def __str__(self):
return f'{self.x} -> {self.y}'
def __add__(self, other):
return 0
| class XRepr(NamedTuple):
| x: int
y: int = 1
def __str__(self):
return f'{self.x} -> {self.y}'
def __add__(self, other):
return 0
| name: str
cool: int
class CoolEmployeeWithDefault(NamedTuple):
name: str
cool: int = 0
class XMeth(NamedTuple):
x: int
def double(self):
return 2 * self.x
class XRepr(NamedTuple):
| 64 | 64 | 54 | 8 | 55 | Visva92/cpython | Lib/test/test_typing.py | Python | XRepr | XRepr | 3,002 | 3,008 | 3,002 | 3,002 | ed13c358bfa12ad5ab0d8ed1a31085d07e6d4a1b | bigcode/the-stack | train |
a820ffc263c91913f7b83af5 | train | class | class CoolEmployee(NamedTuple):
name: str
cool: int
| class CoolEmployee(NamedTuple):
| name: str
cool: int
| (B):
z: ClassVar['CSub'] = B()
class G(Generic[T]):
lst: ClassVar[List[T]] = []
class Loop:
attr: Final['Loop']
class NoneAndForward:
parent: 'NoneAndForward'
meaning: None
class CoolEmployee(NamedTuple):
| 64 | 64 | 17 | 7 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | CoolEmployee | CoolEmployee | 2,989 | 2,991 | 2,989 | 2,989 | 0c13edfe9fee6099935406697c6b36e937ede432 | bigcode/the-stack | train |
d353ceff0e70b34a70acbe5a | train | class | class MyPoint:
x: int
y: int
label: str
| class MyPoint:
| x: int
y: int
label: str
| get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
return default
class Coordinate(Protocol):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
label: str
class MyPoint:
| 64 | 64 | 19 | 4 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | MyPoint | MyPoint | 784 | 787 | 784 | 784 | bad2e4a3484f228ae93d9c79ffefa8d5100d856a | bigcode/the-stack | train |
5353e794f5f99a573fb23642 | train | class | class OverloadTests(BaseTestCase):
def test_overload_fails(self):
from typing import overload
with self.assertRaises(RuntimeError):
@overload
def blah():
pass
blah()
def test_overload_succeeds(self):
from typing import overload
... | class OverloadTests(BaseTestCase):
| def test_overload_fails(self):
from typing import overload
with self.assertRaises(RuntimeError):
@overload
def blah():
pass
blah()
def test_overload_succeeds(self):
from typing import overload
@overload
def blah():
... | _ref(self):
self.assertEqual(gth(Loop, globals())['attr'], Final[Loop])
self.assertNotEqual(gth(Loop, globals())['attr'], Final[int])
self.assertNotEqual(gth(Loop, globals())['attr'], Final)
class OverloadTests(BaseTestCase):
| 64 | 64 | 84 | 8 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | OverloadTests | OverloadTests | 2,897 | 2,920 | 2,897 | 2,898 | 5ce2f1c84a40607cf0011752897461ab5bdade25 | bigcode/the-stack | train |
0b3bc9cf0d103781945a3a2f | train | class | class Employee:
pass
| class Employee:
| pass
| '%r is a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
| 64 | 64 | 6 | 3 | 61 | Visva92/cpython | Lib/test/test_typing.py | Python | Employee | Employee | 66 | 67 | 66 | 66 | 198f971d3bac7bb603bb72b4ae0f5a168fc4450e | bigcode/the-stack | train |
4deafe5e013513bb010e0b90 | train | class | class ManagingFounder(Manager, Founder):
pass
| class ManagingFounder(Manager, Founder):
| pass
| message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
pass
class Manager(Employee):
pass
class Founder(Employee):
pass
class ManagingFounder(Manager, Founder):
| 64 | 64 | 11 | 8 | 55 | Visva92/cpython | Lib/test/test_typing.py | Python | ManagingFounder | ManagingFounder | 78 | 79 | 78 | 78 | 347c48d3928c26b1697edaa2428a35c274cb1fe5 | bigcode/the-stack | train |
271ebcb76a3b257beff49f18 | train | class | class FinalTests(BaseTestCase):
def test_basics(self):
Final[int] # OK
with self.assertRaises(TypeError):
Final[1]
with self.assertRaises(TypeError):
Final[int, str]
with self.assertRaises(TypeError):
Final[int][str]
with self.assertRaise... | class FinalTests(BaseTestCase):
| def test_basics(self):
Final[int] # OK
with self.assertRaises(TypeError):
Final[1]
with self.assertRaises(TypeError):
Final[int, str]
with self.assertRaises(TypeError):
Final[int][str]
with self.assertRaises(TypeError):
Optiona... | _cannot_init(self):
with self.assertRaises(TypeError):
ClassVar()
with self.assertRaises(TypeError):
type(ClassVar)()
with self.assertRaises(TypeError):
type(ClassVar[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError... | 97 | 97 | 324 | 7 | 90 | Visva92/cpython | Lib/test/test_typing.py | Python | FinalTests | FinalTests | 2,483 | 2,529 | 2,483 | 2,484 | 41003eb64f59353b3ac3c90d14eff70dc043a7b0 | bigcode/the-stack | train |
49f24fccf467d81e61172a5b | train | class | class TypingCallableTests(BaseCallableTests, BaseTestCase):
Callable = typing.Callable
def test_consistency(self):
# bpo-42195
# Testing collections.abc.Callable's consistency with typing.Callable
c1 = typing.Callable[[int, str], dict]
c2 = collections.abc.Callable[[int, str], d... | class TypingCallableTests(BaseCallableTests, BaseTestCase):
| Callable = typing.Callable
def test_consistency(self):
# bpo-42195
# Testing collections.abc.Callable's consistency with typing.Callable
c1 = typing.Callable[[int, str], dict]
c2 = collections.abc.Callable[[int, str], dict]
self.assertEqual(c1.__args__, c2.__args__)
... | C1 = Callable[P, T]
with self.assertRaisesRegex(TypeError, "many arguments for"):
C1[int, str, str]
with self.assertRaisesRegex(TypeError, "few arguments for"):
C1[int]
class TypingCallableTests(BaseCallableTests, BaseTestCase):
| 64 | 64 | 110 | 13 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | TypingCallableTests | TypingCallableTests | 634 | 643 | 634 | 634 | 8cee75228377d6f31bb1d5f091e174e1c43d33dc | bigcode/the-stack | train |
43d4742c0e8b5cfc98cf1e9f | train | class | class NewTypePythonTests(NewTypeTests, BaseTestCase):
module = py_typing
| class NewTypePythonTests(NewTypeTests, BaseTestCase):
| module = py_typing
| icklingError):
pickle.dumps(UserAge, proto)
def test_missing__name__(self):
code = ("import typing\n"
"NT = typing.NewType('NT', int)\n"
)
exec(code, {})
class NewTypePythonTests(NewTypeTests, BaseTestCase):
| 63 | 64 | 20 | 13 | 50 | Visva92/cpython | Lib/test/test_typing.py | Python | NewTypePythonTests | NewTypePythonTests | 3,975 | 3,976 | 3,975 | 3,975 | d8c907e114f1a6bee3869480561e66e02fb05a67 | bigcode/the-stack | train |
7892dbd11517ac3e0e1ce06a | train | class | class B(A):
x: ClassVar[Optional['B']] = None
y: int
b: int
| class B(A):
| x: ClassVar[Optional['B']] = None
y: int
b: int
| # multithreading is not enabled
else:
ASYNCIO = True
# Definitions needed for features introduced in Python 3.6
from test import ann_module, ann_module2, ann_module3
from typing import AsyncContextManager
class A:
y: float
class B(A):
| 64 | 64 | 27 | 4 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | B | B | 2,973 | 2,976 | 2,973 | 2,973 | bdeb3fb03b9249bb68402177fbaf1a82ced899dd | bigcode/the-stack | train |
32166fe8a41d9cd2559bff64 | train | class | class GetUtilitiesTestCase(TestCase):
def test_get_origin(self):
T = TypeVar('T')
P = ParamSpec('P')
class C(Generic[T]): pass
self.assertIs(get_origin(C[int]), C)
self.assertIs(get_origin(C[T]), C)
self.assertIs(get_origin(int), None)
self.assertIs(get_origin... | class GetUtilitiesTestCase(TestCase):
| def test_get_origin(self):
T = TypeVar('T')
P = ParamSpec('P')
class C(Generic[T]): pass
self.assertIs(get_origin(C[int]), C)
self.assertIs(get_origin(C[T]), C)
self.assertIs(get_origin(int), None)
self.assertIs(get_origin(ClassVar[int]), ClassVar)
sel... | Set[T]}
)
def test_get_type_hints_classes_str_annotations(self):
class Foo:
y = str
x: 'y'
# This previously raised an error under PEP 563.
self.assertEqual(get_type_hints(Foo), {'x': str})
def test_get_type_hints_bad_module(self):
# bpo-41515
... | 237 | 237 | 793 | 8 | 229 | Visva92/cpython | Lib/test/test_typing.py | Python | GetUtilitiesTestCase | GetUtilitiesTestCase | 3,270 | 3,330 | 3,270 | 3,270 | 343223130406255e8fced21d0fe46855c9fd2629 | bigcode/the-stack | train |
0007841ec5b1e9aa97c4db09 | train | class | class UnionTests(BaseTestCase):
def test_basics(self):
u = Union[int, float]
self.assertNotEqual(u, Union)
def test_subclass_error(self):
with self.assertRaises(TypeError):
issubclass(int, Union)
with self.assertRaises(TypeError):
issubclass(Union, int)
... | class UnionTests(BaseTestCase):
| def test_basics(self):
u = Union[int, float]
self.assertNotEqual(u, Union)
def test_subclass_error(self):
with self.assertRaises(TypeError):
issubclass(int, Union)
with self.assertRaises(TypeError):
issubclass(Union, int)
with self.assertRaises(Ty... | ):
self.assertNotEqual(TypeVar('T'), TypeVar('T'))
self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
def test_cannot_subclass_vars(self):
with self.assertRaises(TypeError):
class V(TypeVar('T')):
pass
def test_cannot_subclass_var_itself(sel... | 256 | 256 | 1,123 | 7 | 249 | Visva92/cpython | Lib/test/test_typing.py | Python | UnionTests | UnionTests | 257 | 397 | 257 | 258 | 42d2d0260162c197fd30b32374caba4fe0e1c9e0 | bigcode/the-stack | train |
53c260fb08358b2485bb7223 | train | class | class ForwardRefTests(BaseTestCase):
def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self,
left: 'Optional[Node[T]]',
... | class ForwardRefTests(BaseTestCase):
| def test_basics(self):
class Node(Generic[T]):
def __init__(self, label: T):
self.label = label
self.left = self.right = None
def add_both(self,
left: 'Optional[Node[T]]',
right: 'Node[T]' = None,
... | )()
with self.assertRaises(TypeError):
type(Final[Optional[int]])()
def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, Final[int])
with self.assertRaises(TypeError):
issubclass(int, Final)
def test_final_unmodified(self):
... | 256 | 256 | 2,513 | 8 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | ForwardRefTests | ForwardRefTests | 2,550 | 2,894 | 2,550 | 2,551 | 5d6748afd88d6eb9b5d4251f19e77195a4302845 | bigcode/the-stack | train |
292c9884b46e82a3d464b93e | train | class | class AnnotatedTests(BaseTestCase):
def test_repr(self):
self.assertEqual(
repr(Annotated[int, 4, 5]),
"typing.Annotated[int, 4, 5]"
)
self.assertEqual(
repr(Annotated[List[int], 4, 5]),
"typing.Annotated[typing.List[int], 4, 5]"
)
... | class AnnotatedTests(BaseTestCase):
| def test_repr(self):
self.assertEqual(
repr(Annotated[int, 4, 5]),
"typing.Annotated[int, 4, 5]"
)
self.assertEqual(
repr(Annotated[List[int], 4, 5]),
"typing.Annotated[typing.List[int], 4, 5]"
)
def test_flatten(self):
A =... | self.assertEqual(repr(Pattern), 'typing.Pattern')
self.assertEqual(repr(Pattern[str]), 'typing.Pattern[str]')
self.assertEqual(repr(Pattern[bytes]), 'typing.Pattern[bytes]')
self.assertEqual(repr(Match), 'typing.Match')
self.assertEqual(repr(Match[str]), 'typing.Match[str]')
... | 256 | 256 | 1,508 | 8 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | AnnotatedTests | AnnotatedTests | 4,399 | 4,569 | 4,399 | 4,400 | 95488f902b5afad6a3ad9554e3eb4f8ffbac4af1 | bigcode/the-stack | train |
c59ef8616b955548a82d5740 | train | class | class IOTests(BaseTestCase):
def test_io(self):
def stuff(a: IO) -> AnyStr:
return a.readline()
a = stuff.__annotations__['a']
self.assertEqual(a.__parameters__, (AnyStr,))
def test_textio(self):
def stuff(a: TextIO) -> str:
return a.readline()
... | class IOTests(BaseTestCase):
| def test_io(self):
def stuff(a: IO) -> AnyStr:
return a.readline()
a = stuff.__annotations__['a']
self.assertEqual(a.__parameters__, (AnyStr,))
def test_textio(self):
def stuff(a: TextIO) -> str:
return a.readline()
a = stuff.__annotations__['... | assert is_typeddict(Union[str, int]) is False
# classes, not instances
assert is_typeddict(Point2D()) is False
def test_get_type_hints(self):
self.assertEqual(
get_type_hints(Bar),
{'a': typing.Optional[int], 'b': int}
)
class IOTests(BaseTestCase):
| 78 | 78 | 263 | 7 | 71 | Visva92/cpython | Lib/test/test_typing.py | Python | IOTests | IOTests | 4,298 | 4,333 | 4,298 | 4,299 | ebc9c60f00463c1650520d8db2db0e0991e08c76 | bigcode/the-stack | train |
fe3da27d372dd7481af31e54 | train | class | class CastTests(BaseTestCase):
def test_basics(self):
self.assertEqual(cast(int, 42), 42)
self.assertEqual(cast(float, 42), 42)
self.assertIs(type(cast(float, 42)), int)
self.assertEqual(cast(Any, 42), 42)
self.assertEqual(cast(list, 42), 42)
self.assertEqual(cast(Un... | class CastTests(BaseTestCase):
| def test_basics(self):
self.assertEqual(cast(int, 42), 42)
self.assertEqual(cast(float, 42), 42)
self.assertIs(type(cast(float, 42)), int)
self.assertEqual(cast(Any, 42), 42)
self.assertEqual(cast(list, 42), 42)
self.assertEqual(cast(Union[str, float], 42), 42)
... | (self):
with self.assertRaises(TypeError):
isinstance(1, Final[int])
with self.assertRaises(TypeError):
issubclass(int, Final)
def test_final_unmodified(self):
def func(x): ...
self.assertIs(func, final(func))
class CastTests(BaseTestCase):
| 64 | 64 | 166 | 7 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | CastTests | CastTests | 2,532 | 2,547 | 2,532 | 2,533 | 440e8e9ef3666f4b48bd6dfcb055995c05384eab | bigcode/the-stack | train |
0046191e1fc02838a59a5402 | train | class | class TestModules(TestCase):
func_names = ['_idfunc']
def test_py_functions(self):
for fname in self.func_names:
self.assertEqual(getattr(py_typing, fname).__module__, 'typing')
@skipUnless(c_typing, 'requires _typing')
def test_c_functions(self):
for fname in self.func_nam... | class TestModules(TestCase):
| func_names = ['_idfunc']
def test_py_functions(self):
for fname in self.func_names:
self.assertEqual(getattr(py_typing, fname).__module__, 'typing')
@skipUnless(c_typing, 'requires _typing')
def test_c_functions(self):
for fname in self.func_names:
self.assertEq... | A = Optional[Type[BaseException]]
def foo(a: A) -> Optional[BaseException]:
if a is None:
return None
else:
return a()
assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt)
assert foo(None) is None
class TestModules(TestCase):
| 64 | 64 | 92 | 6 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | TestModules | TestModules | 3,879 | 3,889 | 3,879 | 3,879 | 2d3e86e7dfc2d2c2e38ed7e396eb76473b3df08f | bigcode/the-stack | train |
8188ef8fd862c107e058a11c | train | class | class LiteralTests(BaseTestCase):
def test_basics(self):
# All of these are allowed.
Literal[1]
Literal[1, 2, 3]
Literal["x", "y", "z"]
Literal[None]
Literal[True]
Literal[1, "2", False]
Literal[Literal[1, 2], Literal[4, 5]]
Literal[b"foo", u"b... | class LiteralTests(BaseTestCase):
| def test_basics(self):
# All of these are allowed.
Literal[1]
Literal[1, 2, 3]
Literal["x", "y", "z"]
Literal[None]
Literal[True]
Literal[1, "2", False]
Literal[Literal[1, 2], Literal[4, 5]]
Literal[b"foo", u"bar"]
def test_illegal_paramet... | fullname}[typing.Concatenate[int, ~P], int]")
def test_errors(self):
Callable = self.Callable
alias = Callable[[int, str], float]
with self.assertRaisesRegex(TypeError, "is not a generic class"):
alias[int]
P = ParamSpec('P')
C1 = Callable[P, T]
with self... | 256 | 256 | 981 | 7 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | LiteralTests | LiteralTests | 650 | 739 | 650 | 650 | c9394660646b90268f68fb93e58095e793d264cc | bigcode/the-stack | train |
0e010026acd984aa4047786f | train | class | class BaseCallableTests:
def test_self_subclass(self):
Callable = self.Callable
with self.assertRaises(TypeError):
issubclass(types.FunctionType, Callable[[int], int])
self.assertIsSubclass(types.FunctionType, Callable)
def test_eq_hash(self):
Callable = self.Callab... | class BaseCallableTests:
| def test_self_subclass(self):
Callable = self.Callable
with self.assertRaises(TypeError):
issubclass(types.FunctionType, Callable[[int], int])
self.assertIsSubclass(types.FunctionType, Callable)
def test_eq_hash(self):
Callable = self.Callable
C = Callable[[i... | ], Tuple[int])
self.assertEqual(Tuple[int, ...], Tuple[int, ...])
self.assertNotEqual(Tuple[int], Tuple[int, int])
self.assertNotEqual(Tuple[int], Tuple[int, ...])
def test_tuple_subclass(self):
class MyTuple(tuple):
pass
self.assertIsSubclass(MyTuple, Tuple)
... | 256 | 256 | 1,819 | 5 | 251 | Visva92/cpython | Lib/test/test_typing.py | Python | BaseCallableTests | BaseCallableTests | 442 | 632 | 442 | 443 | 33f9017a3d43c96df370ad2db01e4fcc09119e1d | bigcode/the-stack | train |
de17fdf174a5daa836ce33b2 | train | class | class TupleTests(BaseTestCase):
def test_basics(self):
with self.assertRaises(TypeError):
issubclass(Tuple, Tuple[int, str])
with self.assertRaises(TypeError):
issubclass(tuple, Tuple[int, str])
class TP(tuple): ...
self.assertIsSubclass(tuple, Tuple)
... | class TupleTests(BaseTestCase):
| def test_basics(self):
with self.assertRaises(TypeError):
issubclass(Tuple, Tuple[int, str])
with self.assertRaises(TypeError):
issubclass(tuple, Tuple[int, str])
class TP(tuple): ...
self.assertIsSubclass(tuple, Tuple)
self.assertIsSubclass(TP, Tuple... | /issue25390
A = Union[str, Pattern]
A
def test_etree(self):
# See https://github.com/python/typing/issues/229
# (Only relevant for Python 2.)
from xml.etree.ElementTree import Element
Union[Element, str] # Shouldn't crash
def Elem(*args):
retur... | 102 | 102 | 343 | 7 | 94 | Visva92/cpython | Lib/test/test_typing.py | Python | TupleTests | TupleTests | 400 | 439 | 400 | 401 | 3437de0077029430f29a3221e869b3acc7809c2c | bigcode/the-stack | train |
7700790edf9f7eb4df1cc4a7 | train | class | class Point2D(TypedDict):
x: int
y: int
| class Point2D(TypedDict):
| x: int
y: int
| : int
y: int = 1
def __str__(self):
return f'{self.x} -> {self.y}'
def __add__(self, other):
return 0
Label = TypedDict('Label', [('label', str)])
class Point2D(TypedDict):
| 64 | 64 | 18 | 8 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | Point2D | Point2D | 3,012 | 3,014 | 3,012 | 3,012 | c7ae7a55371c0c1185933e5dc0cb26db61d7599a | bigcode/the-stack | train |
2ec379c9217781bf279e814f | train | class | class SimpleMapping(Generic[XK, XV]):
def __getitem__(self, key: XK) -> XV:
...
def __setitem__(self, key: XK, value: XV):
...
def get(self, key: XK, default: XV = None) -> XV:
...
| class SimpleMapping(Generic[XK, XV]):
| def __getitem__(self, key: XK) -> XV:
...
def __setitem__(self, key: XK, value: XV):
...
def get(self, key: XK, default: XV = None) -> XV:
...
| :
self.assertEqual(l, Literal[1, 2, 3])
self.assertEqual(l.__args__, (1, 2, 3))
XK = TypeVar('XK', str, bytes)
XV = TypeVar('XV')
class SimpleMapping(Generic[XK, XV]):
| 64 | 64 | 64 | 10 | 54 | Visva92/cpython | Lib/test/test_typing.py | Python | SimpleMapping | SimpleMapping | 746 | 755 | 746 | 747 | 7e1c69f0194c0dfb6b748d8307745c206c139e93 | bigcode/the-stack | train |
b3e159fd691eb634eff94eb4 | train | class | class ProtocolTests(BaseTestCase):
def test_basic_protocol(self):
@runtime_checkable
class P(Protocol):
def meth(self):
pass
class C: pass
class D:
def meth(self):
pass
def f():
pass
self.assertIs... | class ProtocolTests(BaseTestCase):
| def test_basic_protocol(self):
@runtime_checkable
class P(Protocol):
def meth(self):
pass
class C: pass
class D:
def meth(self):
pass
def f():
pass
self.assertIsSubclass(D, P)
self.assertI... | , key: str, value):
self.store[key] = value
def get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
return default
class Coordinate(Protocol):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
label: str
c... | 256 | 256 | 4,735 | 7 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | ProtocolTests | ProtocolTests | 824 | 1,611 | 824 | 824 | 7a300ae669608bfe57ae4264c3659b939118eb8a | bigcode/the-stack | train |
7364df7b22211123bd756a38 | train | class | class NoneAndForward:
parent: 'NoneAndForward'
meaning: None
| class NoneAndForward:
| parent: 'NoneAndForward'
meaning: None
| Optional['B']] = None
y: int
b: int
class CSub(B):
z: ClassVar['CSub'] = B()
class G(Generic[T]):
lst: ClassVar[List[T]] = []
class Loop:
attr: Final['Loop']
class NoneAndForward:
| 64 | 64 | 18 | 5 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | NoneAndForward | NoneAndForward | 2,985 | 2,987 | 2,985 | 2,985 | 2e3011c0d8d16213a1f24800f8957300ad870876 | bigcode/the-stack | train |
05ed10ddd36628f748f5ee8a | train | class | class NoReturnTests(BaseTestCase):
def test_noreturn_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, NoReturn)
def test_noreturn_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, NoReturn)
with self.a... | class NoReturnTests(BaseTestCase):
| def test_noreturn_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, NoReturn)
def test_noreturn_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, NoReturn)
with self.assertRaises(TypeError):
... | .assertRaises(TypeError):
Any()
with self.assertRaises(TypeError):
type(Any)()
def test_any_works_with_alias(self):
# These expressions must simply not fail.
typing.Match[Any]
typing.Pattern[Any]
typing.IO[Any]
class NoReturnTests(BaseTestCase):
| 64 | 64 | 201 | 8 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | NoReturnTests | NoReturnTests | 124 | 155 | 124 | 125 | ec568ca8574dc7777714e064e4a7103a3c943f28 | bigcode/the-stack | train |
6c89d1e8a9a15f75fffec34b | train | class | class XAxis(Protocol):
x: int
| class XAxis(Protocol):
| x: int
| KeyError:
return default
class Coordinate(Protocol):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
label: str
class MyPoint:
x: int
y: int
label: str
class XAxis(Protocol):
| 64 | 64 | 11 | 6 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | XAxis | XAxis | 789 | 790 | 789 | 789 | cf6b573e403b90954b43ecf515a23e5cdfe79483 | bigcode/the-stack | train |
bb13c9360876560f53d8ff1d | train | class | class Founder(Employee):
pass
| class Founder(Employee):
| pass
| _or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
pass
class Manager(Employee):
pass
class Founder(Employee):
| 64 | 64 | 7 | 4 | 59 | Visva92/cpython | Lib/test/test_typing.py | Python | Founder | Founder | 74 | 75 | 74 | 74 | a98b94a0d852a8eda0ffa9d6b025fa5299d511cc | bigcode/the-stack | train |
82f149148a4f4fa3fe4b6925 | train | class | class MySimpleMapping(SimpleMapping[XK, XV]):
def __init__(self):
self.store = {}
def __getitem__(self, key: str):
return self.store[key]
def __setitem__(self, key: str, value):
self.store[key] = value
def get(self, key: str, default=None):
try:
return sel... | class MySimpleMapping(SimpleMapping[XK, XV]):
| def __init__(self):
self.store = {}
def __getitem__(self, key: str):
return self.store[key]
def __setitem__(self, key: str, value):
self.store[key] = value
def get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
... | __getitem__(self, key: XK) -> XV:
...
def __setitem__(self, key: XK, value: XV):
...
def get(self, key: XK, default: XV = None) -> XV:
...
class MySimpleMapping(SimpleMapping[XK, XV]):
| 64 | 64 | 93 | 12 | 52 | Visva92/cpython | Lib/test/test_typing.py | Python | MySimpleMapping | MySimpleMapping | 758 | 773 | 758 | 759 | edd943a9f4d62e6beea318aedcf82530d169135e | bigcode/the-stack | train |
c3338b35e119f9674d756f38 | train | class | class CollectionsCallableTests(BaseCallableTests, BaseTestCase):
Callable = collections.abc.Callable
| class CollectionsCallableTests(BaseCallableTests, BaseTestCase):
| Callable = collections.abc.Callable
| , str], dict]
c2 = collections.abc.Callable[[int, str], dict]
self.assertEqual(c1.__args__, c2.__args__)
self.assertEqual(hash(c1.__args__), hash(c2.__args__))
class CollectionsCallableTests(BaseCallableTests, BaseTestCase):
| 63 | 64 | 21 | 12 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | CollectionsCallableTests | CollectionsCallableTests | 646 | 647 | 646 | 646 | 4d97e6523fc57e1a8bad5496226045f070962754 | bigcode/the-stack | train |
5a9c5f7802fbe069da4584f0 | train | class | class TypeVarTests(BaseTestCase):
def test_basic_plain(self):
T = TypeVar('T')
# T equals itself.
self.assertEqual(T, T)
# T is an instance of TypeVar
self.assertIsInstance(T, TypeVar)
def test_typevar_instance_type_error(self):
T = TypeVar('T')
with sel... | class TypeVarTests(BaseTestCase):
| def test_basic_plain(self):
T = TypeVar('T')
# T equals itself.
self.assertEqual(T, T)
# T is an instance of TypeVar
self.assertIsInstance(T, TypeVar)
def test_typevar_instance_type_error(self):
T = TypeVar('T')
with self.assertRaises(TypeError):
... | type(Any)()
def test_any_works_with_alias(self):
# These expressions must simply not fail.
typing.Match[Any]
typing.Pattern[Any]
typing.IO[Any]
class NoReturnTests(BaseTestCase):
def test_noreturn_instance_type_error(self):
with self.assertRaises(TypeError... | 249 | 249 | 832 | 8 | 241 | Visva92/cpython | Lib/test/test_typing.py | Python | TypeVarTests | TypeVarTests | 158 | 254 | 158 | 159 | ac89f916ebd95b7cc4b05eb4978972cb8853fb11 | bigcode/the-stack | train |
b3e70a0bf81592925cf257e2 | train | class | class SpecialAttrsTests(BaseTestCase):
def test_special_attrs(self):
cls_to_check = {
# ABC classes
typing.AbstractSet: 'AbstractSet',
typing.AsyncContextManager: 'AsyncContextManager',
typing.AsyncGenerator: 'AsyncGenerator',
typing.AsyncIterable... | class SpecialAttrsTests(BaseTestCase):
| def test_special_attrs(self):
cls_to_check = {
# ABC classes
typing.AbstractSet: 'AbstractSet',
typing.AsyncContextManager: 'AsyncContextManager',
typing.AsyncGenerator: 'AsyncGenerator',
typing.AsyncIterable: 'AsyncIterable',
typing.As... | typing.TypeGuard')
cv = TypeGuard[int]
self.assertEqual(repr(cv), 'typing.TypeGuard[int]')
cv = TypeGuard[Employee]
self.assertEqual(repr(cv), 'typing.TypeGuard[%s.Employee]' % __name__)
cv = TypeGuard[tuple[int]]
self.assertEqual(repr(cv), 'typing.TypeGuard[tuple[int]]')... | 256 | 256 | 1,665 | 8 | 248 | Visva92/cpython | Lib/test/test_typing.py | Python | SpecialAttrsTests | SpecialAttrsTests | 4,814 | 4,987 | 4,814 | 4,815 | b5ee3bb7dfa2aa1df411de8768769e0855002355 | bigcode/the-stack | train |
7336a11f532b726228a629fd | train | class | class NewTypeTests:
def cleanup(self):
for f in self.module._cleanups:
f()
@classmethod
def setUpClass(cls):
sys.modules['typing'] = cls.module
global UserId
UserId = cls.module.NewType('UserId', int)
cls.UserName = cls.module.NewType(cls.__qualname__ + '... | class NewTypeTests:
| def cleanup(self):
for f in self.module._cleanups:
f()
@classmethod
def setUpClass(cls):
sys.modules['typing'] = cls.module
global UserId
UserId = cls.module.NewType('UserId', int)
cls.UserName = cls.module.NewType(cls.__qualname__ + '.UserName', str)
... | TypeVar('U', bound=User)
def new_user(user_class: Type[U]) -> U:
return user_class()
new_user(BasicUser)
def test_type_optional(self):
A = Optional[Type[BaseException]]
def foo(a: A) -> Optional[BaseException]:
if a is None:
return None
... | 198 | 198 | 661 | 5 | 193 | Visva92/cpython | Lib/test/test_typing.py | Python | NewTypeTests | NewTypeTests | 3,892 | 3,972 | 3,892 | 3,892 | 33a5d215d5ad7a8b4b2133b5beac2069620443fe | bigcode/the-stack | train |
a11f1a9d625216b4a6c2808d | train | class | @runtime_checkable
class Position(XAxis, YAxis, Protocol):
pass
| @runtime_checkable
class Position(XAxis, YAxis, Protocol):
| pass
| , Protocol):
label: str
class MyPoint:
x: int
y: int
label: str
class XAxis(Protocol):
x: int
class YAxis(Protocol):
y: int
@runtime_checkable
class Position(XAxis, YAxis, Protocol):
| 64 | 64 | 18 | 15 | 48 | Visva92/cpython | Lib/test/test_typing.py | Python | Position | Position | 795 | 797 | 795 | 796 | d933217b65d23dfe5a9e29d4957662aceb0d3304 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.