code stringlengths 281 23.7M |
|---|
class CollisionLinks(object):
swagger_types = {'_self': 'Link', 'trip': 'Link', 'vehicle': 'Link'}
attribute_map = {'_self': 'self', 'trip': 'trip', 'vehicle': 'vehicle'}
def __init__(self, _self=None, trip=None, vehicle=None):
self.__self = None
self._trip = None
self._vehicle = Non... |
class Model(SkillComponent, ABC):
def __init__(self, name: str, skill_context: SkillContext, configuration: Optional[SkillComponentConfiguration]=None, keep_terminal_state_dialogues: Optional[bool]=None, **kwargs: Any) -> None:
super().__init__(name, skill_context, configuration=configuration, **kwargs)
... |
class ExperienceReplay():
def __init__(self, model, max_memory=1000, discount=0.95):
self.model = model
self.discount = discount
self.memory = list()
self.max_memory = max_memory
def remember(self, transition):
self.memory.append(transition)
if (len(self.memory) >... |
def filter_data_categories(access_request_results: Dict[(str, List[Dict[(str, Optional[Any])]])], target_categories: Set[str], data_category_fields: Dict[(CollectionAddress, Dict[(FidesKey, List[FieldPath])])], rule_key: str='', fides_connector_datasets: Optional[Set[str]]=None) -> Dict[(str, List[Dict[(str, Optional[A... |
def _wrap_gen_lifespan_context(lifespan_context: typing.Callable[([typing.Any], typing.Generator[(typing.Any, typing.Any, typing.Any)])]) -> typing.Callable[([typing.Any], typing.AsyncContextManager[typing.Any])]:
cmgr = contextlib.contextmanager(lifespan_context)
(cmgr)
def wrapper(app: typing.Any) -> _Asy... |
class TestIlluminaDataForCasava(BaseTestIlluminaData):
def setUp(self):
self.top_dir = tempfile.mkdtemp()
def tearDown(self):
try:
os.rmdir(self.top_dir)
except Exception:
pass
def makeMockIlluminaData(self, paired_end=False, multiple_projects=False, multiplex... |
class Interpolate():
def __init__(self, points: Sequence[VectorLike], callback: Callable[(..., float)], length: int, linear: bool=False) -> None:
self.length = length
self.num_coords = len(points[0])
self.points = list(zip(*points))
self.callback = callback
self.linear = line... |
def _run_in_venv_handler(env_dir: str, fn: Callable, queue: multiprocessing.Queue, *args: Any) -> None:
result = None
try:
make_venv(env_dir, set_env=True)
result = fn(*args)
except Exception as e:
print(f'''Exception in venv runner at {datetime.datetime.now()} for {fn}:
{format_exc(... |
_frequency(timedelta(days=2))
def fetch_exchange_forecast(zone_key1: str='NO-NO4', zone_key2: str='SE', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]:
return fetch_data(zone_key1=zone_key1, zone_key2=zone_key2, session=session, target_date... |
class ADH_metfile(object):
from proteus.cSubsurfaceTransportCoefficients import piecewiseLinearTableLookup
allowed_time_units = ['day', 'hour', 'sec']
def __init__(self, fileprefix, directory='.'):
self.fileprefix = fileprefix
self.directory = directory
import os, numpy
filen... |
class TestSelectTasks(TestCase):
('app.database.db', new=tasks)
def test_select_tasks_deve_retornar_somente_tasks_de_acordar(self):
results = select_tasks('Acordar', '')
for result in results:
with self.subTest(f'Acordar in {result}'):
self.assertEqual('Acordar', resu... |
def evaluate_supersampled(field_generator, grid, oversampling, statistic='mean', make_sparse=True):
import scipy.sparse
from ..mode_basis import ModeBasis
if isinstance(field_generator, (list, tuple)):
modes = []
for fg in field_generator:
field = evaluate_supersampled(fg, grid, ... |
class MDataWrapper(HasStrictTraits):
def has_format(self, format):
return (format.mimetype in self.mimetypes())
def get_format(self, format):
return format.deserialize(self.get_mimedata(format.mimetype))
def set_format(self, format, data):
self.set_mimedata(format.mimetype, format.se... |
class NodeItem(QStandardItem):
ITEM_TYPE = (QStandardItem.UserType + 35)
NAME_ROLE = (Qt.UserRole + 1)
COL_CFG = 1
STATE_OFF = 0
STATE_RUN = 1
STATE_WARNING = 2
STATE_GHOST = 3
STATE_DUPLICATE = 4
STATE_PARTS = 5
def __init__(self, node_info):
QStandardItem.__init__(self,... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
class ExpandTestCase(unittest.TestCase):
def test_expand_fails_mismatched_ndim(self):
x = Tensor(shape=[5, IntVar([1, 10]), 5])
expand_shape = [5, (- 1)]
self.assertRaises(ValueError, ops.expand().__call__, x, expand_shape)
d... |
class BaseFixedDecoder(Fixed32ByteSizeDecoder):
frac_places = None
is_big_endian = True
def validate(self):
super().validate()
if (self.frac_places is None):
raise ValueError('must specify `frac_places`')
if ((self.frac_places <= 0) or (self.frac_places > 80)):
... |
def normalizeLinkText(url: str) -> str:
parsed = mdurl.parse(url, slashes_denote_host=True)
if (parsed.hostname and ((not parsed.protocol) or (parsed.protocol in RECODE_HOSTNAME_FOR))):
with suppress(Exception):
parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname))
ret... |
def _parse_value(value: Union[(int, str, float, dict)], name: str, parent_name: str=None) -> dict:
if (name is not None):
assert isinstance(name, str), 'name can only be `str` type, not {}.'.format(name)
_dict = {}
if (isinstance(value, (int, float, str, bool)) or (value is None)):
if (name ... |
def test_globals():
base_args = ['python', 'decompile.py']
args1 = (base_args + ['tests/samples/bin/systemtests/64/2/condmap', 'main'])
args2 = (base_args + ['tests/samples/bin/systemtests/32/0/test_goto', 'test2'])
output1 = str(subprocess.run(args1, check=True, capture_output=True).stdout)
output2... |
class Chart():
def __init__(self, date, pos, **kwargs):
hsys = kwargs.get('hsys', const.HOUSES_DEFAULT)
IDs = kwargs.get('IDs', const.LIST_OBJECTS_TRADITIONAL)
self.date = date
self.pos = pos
self.hsys = hsys
self.objects = ephem.getObjectList(IDs, date, pos)
... |
class CommandStreamer(PacketStreamer):
def __init__(self):
self.source = stream.Endpoint(command_tx_description(32))
self.packets = []
self.packet = CommandTXPacket()
self.packet.done = True
def send(self, packet):
packet = deepcopy(packet)
self.packets.append(pac... |
class LastSboxes():
def __new__(cls, guesses=_np.arange(64, dtype='uint8'), words=None, ciphertext_tag='ciphertext', key_tag='key'):
return _decorated_selection_function(_AttackSelectionFunctionWrapped, _sboxes, expected_key_function=_last_key, words=words, guesses=guesses, target_tag=ciphertext_tag, key_ta... |
class MiscellaneousRoutes(ComponentBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.stats_updater = StatsUpdater(stats_db=self.db.stats_updater)
_required
_accepted(*PRIVILEGES['status'])
('/', GET)
def show_home(self):
latest_count = config.... |
class VRRPRouter(app_manager.RyuApp):
_EVENTS = [vrrp_event.EventVRRPStateChanged]
_CONSTRUCTORS = {}
_STATE_MAP = {}
def register(version):
def _register(cls):
VRRPRouter._CONSTRUCTORS[version] = cls
return cls
return _register
def factory(name, monitor_name,... |
('bodhi.server.security.get_current_registry', mock.MagicMock(return_value=FakeRegistry()))
class TestCorsOrigins():
def test___contains___initialized(self):
co = security.CorsOrigins('cors_origins_ro')
co.initialize()
with mock.patch('bodhi.server.security.get_current_registry', side_effect... |
class TestPredictionCountEvaluation(unittest.TestCase):
def setUp(self):
self.evaluator = PredictionCountEvaluator()
image_size = (224, 224)
self.mock_outputs = [{'instances': Instances(image_size, scores=torch.Tensor([0.9, 0.8, 0.7]))}, {'instances': Instances(image_size, scores=torch.Tenso... |
def manage_context(args, daccess):
path = args['context']
name = args.get('name')
options = get_options(args, CONTEXT_MUTATORS)
exists = True
if ((len(options) == 0) and (name is None)):
return todo(args, daccess)
else:
if (name is not None):
renamed = data_access.ren... |
def convert_schemas(d, definitions=None):
if (definitions is None):
definitions = {}
definitions.update(d.get('definitions', {}))
new = {}
for (k, v) in d.items():
if isinstance(v, dict):
v = convert_schemas(v, definitions)
if isinstance(v, (list, tuple)):
... |
def mfa_reset_secret(username):
secret = pyotp.random_base32()
conn = sqlite3.connect('db_users.sqlite')
conn.set_trace_callback(print)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('UPDATE users SET mfa_secret = ? WHERE username = ?', (secret, username))
conn.commit()
retur... |
class TestUndoItem(UnittestTools, unittest.TestCase):
def test_undo(self):
example = SimpleExample(value=11)
undo_item = UndoItem(object=example, name='value', old_value=10, new_value=11)
with self.assertTraitChanges(example, 'value', count=1):
undo_item.undo()
self.asser... |
class OptionSeriesWindbarbSonificationDefaultinstrumentoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, n... |
def unfreeze_last_n_stages(stages: List[nn.Module], n: int):
if (n == (- 1)):
return
num_stages = len(stages)
num_stages_to_freeze = (num_stages - n)
for (i, stage) in enumerate(stages):
if (i >= num_stages_to_freeze):
break
for param in stage.parameters():
... |
def _run_is_compiling_tests(dtype_name, backend):
dtype = to_backend_dtype(dtype_name, like=backend)
x = anp.array([[0.0, 1.0], [1.0, 2.0]], dtype=dtype, like=backend)
assert (not _is_compiling(x)), f'_is_compiling has a false positive with backend {backend}'
def check_compiling(x):
assert _is_c... |
def test_local_error(tmp_path: Path) -> None:
def failing_job() -> None:
raise RuntimeError('Failed on purpose')
executor = local.LocalExecutor(tmp_path)
job = executor.submit(failing_job)
exception = job.exception()
assert isinstance(exception, utils.FailedJobError)
traceback = exceptio... |
('ecs_deploy.cli.get_client')
def test_run_task_with_environment_var(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.run, (CLUSTER_NAME, 'test-task', '2', '-e', 'application', 'foo', 'bar'))
assert (not result.exception)
assert (result.e... |
(ITreeNode)
class AdderNode(TreeNode):
label = Str('Base AdderNode')
tooltip = Str('Add an item')
object = Any
scene = Property
view = View(Group(label='AdderNode'))
def dialog_view(self):
view = self.trait_view()
view.buttons = []
view.title = self.label
view.ico... |
class PolygonPlot(BaseXYPlot):
edge_color = black_color_trait(requires_redraw=True)
edge_width = Float(1.0, requires_redraw=True)
edge_style = LineStyle(requires_redraw=True)
face_color = transparent_color_trait(requires_redraw=True)
hittest_type = Enum('poly', 'point', 'line')
effective_edge_co... |
class TestMisc(unittest.TestCase):
def setUp(self):
datasets = [tvtk.ImageData(), tvtk.StructuredPoints(), tvtk.RectilinearGrid(), tvtk.StructuredGrid(), tvtk.PolyData(), tvtk.UnstructuredGrid()]
exts = ['.vti', '.vti', '.vtr', '.vts', '.vtp', '.vtu']
self.datasets = datasets
self.ex... |
class OcrNumbersTest(unittest.TestCase):
def test_recognizes_0(self):
self.assertEqual(convert([' _ ', '| |', '|_|', ' ']), '0')
def test_recognizes_1(self):
self.assertEqual(convert([' ', ' |', ' |', ' ']), '1')
def test_unreadable_but_correctly_sized_inputs_return(self):
se... |
def LocationEditContent(request, location_slug):
location = get_object_or_404(Location, slug=location_slug)
if (request.method == 'POST'):
form = LocationContentForm(request.POST, request.FILES, instance=location)
if form.is_valid():
form.save()
messages.add_message(reque... |
class ModelLoader():
_instance: Optional[object] = None
def __new__(cls):
if (cls._instance is None):
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self) -> None:
self.model_path: Text = 'models/model.joblib'
self.model: Optional[Callable]... |
def _get_code_object(obj):
kind = _get_kind(obj)
if (kind == 'code'):
return obj
try:
return obj.__code__
except AttributeError:
pass
if (kind == 'function'):
raise NotImplementedError
elif (kind in ('class', 'module')):
(filename, text) = _get_source(obj,... |
def test_validate_bloch_with_symmetry():
with pytest.raises(pydantic.ValidationError):
td.Simulation(size=(1, 1, 1), run_time=1e-12, boundary_spec=td.BoundarySpec(x=td.Boundary.bloch(bloch_vec=1.0), y=td.Boundary.bloch(bloch_vec=1.0), z=td.Boundary.bloch(bloch_vec=1.0)), symmetry=(1, 1, 1), grid_spec=td.Gri... |
def print_table(term: Terminal, players: Dict[(str, AsciiPlayer)], public_cards: AsciiCardCollection, n_table_rotations: int, n_spaces_between_cards: int=4, n_chips_in_pot: int=0):
left_player = players['left']
middle_player = players['middle']
right_player = players['right']
for line in public_cards.li... |
def get_item_names(is_jp: bool) -> list[str]:
item_names = game_data_getter.get_file_latest('resLocal', 'GatyaitemName.csv', is_jp)
if (item_names is None):
helper.error_text('Failed to get item names')
return []
item_names = csv_handler.parse_csv(item_names.decode('utf-8'), delimeter=helper... |
class EvalLearner(Learner):
__subtype__ = EvalSubLearner
def __init__(self, estimator, preprocess, name, attr, scorer, error_score=None, verbose=False, **kwargs):
super(EvalLearner, self).__init__(estimator=estimator, preprocess=preprocess, name=name, attr=attr, scorer=scorer, verbose=verbose, **kwargs)... |
def log_deploy():
current_commit = run('git rev-parse --verify HEAD')
url = (' % (env.previous_commit, current_commit))
log_line = json.dumps({'started_at': str(env.started_at), 'ended_at': str(datetime.utcnow()), 'changes_url': url})
run(("echo '%s' >> deploy-log.json" % log_line))
with prefix('sou... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
class GribIndexingDirectoryParserIterator():
def __init__(self, directory, db_path, relative_paths, extensions=['.grib', '.grib1', '.grib2'], followlinks=True, verbose=False, with_statistics=True):
self.db_path = db_path
self.extensions = set(extensions)
self.directory = directory
se... |
class CTrait(ctraits.cTrait):
def __call__(self, *args, **metadata):
from .trait_type import TraitType
from .traits import Trait
handler = self.handler
if isinstance(handler, TraitType):
dict = (self.__dict__ or {}).copy()
dict.update(metadata)
ret... |
_type(ofproto.OFPTFPT_NEXT_TABLES)
_type(ofproto.OFPTFPT_NEXT_TABLES_MISS)
class OFPTableFeaturePropNextTables(OFPTableFeatureProp):
_TABLE_ID_PACK_STR = '!B'
def __init__(self, type_=None, length=None, table_ids=None):
table_ids = (table_ids if table_ids else [])
super(OFPTableFeaturePropNextTa... |
class TripLinks(object):
swagger_types = {'alerts': 'Link', '_self': 'Link', 'vehicle': 'Link', 'waypoints': 'Link'}
attribute_map = {'alerts': 'alerts', '_self': 'self', 'vehicle': 'vehicle', 'waypoints': 'waypoints'}
def __init__(self, alerts=None, _self=None, vehicle=None, waypoints=None):
self._... |
def validate_attributed_ast(test: unittest.TestCase, source_unit: ast.SourceUnit):
grammar = get_solidity_grammar_instance()
stmts = []
ids_to_vars = {}
def regsiter_variables(a, _, __):
if isinstance(a, Statement):
stmts.append(a)
if isinstance(a, VariableDeclaration):
... |
class Commands():
def __init__(self) -> None:
self.by_version: typing.Dict[(typing.Sequence[int], CommandProtocol)] = {}
def register(self, version: typing.Sequence[int]) -> typing.Callable[([CommandProtocol], CommandProtocol)]:
if (version in self.by_version):
raise Exception(f'Vers... |
def test_branch(converter):
assert (str(converter.convert(Branch(Condition(OperationType.equal, [var_x.copy(), const_1.copy()])))) == str((BitVec('x', 32) == BitVecVal(1, 32))))
assert (str(converter.convert(Branch(Condition(OperationType.not_equal, [var_x.copy(), const_1.copy()])))) == str((BitVec('x', 32) != ... |
class RemotableModelPool(remote.Remotable, Launchable):
def __init__(self, model: RemotableModel, capacity: int=0, seed: Optional[int]=None, identifier: Optional[str]=None) -> None:
super().__init__(identifier)
self._model = model
self._capacity = capacity
self._seed = seed
i... |
def extractAnathema(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
return buildReleaseMessageWithType(item, 'Anathema', vol, chp, frag=frag, postfix=postfix, tl_type='oel') |
def test_appending_records_null_schema_works(tmpdir):
'
schema = {'type': 'record', 'name': 'test_appending_records_different_schema_fails', 'fields': [{'name': 'field', 'type': 'string'}]}
test_file = str(tmpdir.join('test.avro'))
with open(test_file, 'wb') as new_file:
fastavro.writer(new_file... |
class OptionPlotoptionsPackedbubbleSonificationDefaultspeechoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(se... |
class FSDPShampoo(torch.optim.Optimizer):
def __init__(self, params, param_metadata: Dict[(torch.nn.Parameter, Tuple)], lr: float=0.01, betas: Tuple[(float, float)]=(0.9, 1.0), epsilon: float=1e-12, momentum: float=0.0, weight_decay: float=0.0, max_preconditioner_dim: int=1024, precondition_frequency: int=1, start_... |
def test_make_config_positional_args_complex():
_registry.cats('catsie.v890')
def catsie_890(*args: Optional[Union[(StrictBool, PositiveInt)]]):
assert (args[0] == 123)
return args[0]
cfg = {'config': {'': 'catsie.v890', '*': [123, True, 1, False]}}
assert (my_registry.resolve(cfg)['conf... |
def fetch_exchange(zone_key1: str, zone_key2: str, session: Session=Session(), target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)):
if (target_datetime is not None):
raise ParserException('HN.py', 'This parser is not yet able to parse past dates')
(CSV_data, EXCHANGE_MAP) = get_... |
def convert_not_equal(name, operator, version_id):
if version_id.endswith('.*'):
version_id = version_id[:(- 2)]
version = RpmVersion(version_id)
if version.is_legacy():
return 'Invalid version'
version_gt = RpmVersion(version_id).increment()
version_gt_operator =... |
class Generator(lg.Node):
OUTPUT = lg.Topic(RandomMessage)
config: GeneratorConfig
(OUTPUT)
async def generate_noise(self) -> lg.AsyncPublisher:
while True:
(yield (self.OUTPUT, RandomMessage(sources=np.random.random(1), detectors=np.random.random(8))))
(await asyncio.sle... |
class OptionSeriesPyramid3dSonificationTracksMappingLowpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class TestDumpManifest(unittest.TestCase):
tmpdir: TemporaryDirectory
def setUp(self):
self.tmpdir = TemporaryDirectory()
def tearDown(self):
self.tmpdir.cleanup()
def test_editorconfig(self):
for (i, _style) in enumerate(EDITORCONFIG_STYLES):
(econfig, expected_data)... |
class VirtualKeyboard(QWidget):
def __init__(self, pw_edit):
super().__init__(pw_edit)
self.pw_edit = pw_edit
self.page = pages[0]
self.pages = pages.copy()
self.refresh_button = vkb_button(self._refresh)
self.refresh_button.setIcon(read_QIcon('refresh_win10_16.png'))... |
def read_font(font: str) -> dict:
fonts_dir = (__file__.replace('__init__.py', '') + 'fonts')
if ('/' in font):
font_filename = os.path.realpath(str(font))
else:
font_filename = (((fonts_dir.rstrip('/') + '/') + font.replace('.aff', '')) + '.aff')
file_line = 0
try:
fontfile ... |
class BaseTest(object):
def assign(self, value):
self.obj.value = value
def coerce(self, value):
return value
def test_assignment(self):
obj = self.obj
value = self._default_value
self.assertEqual(obj.value, value)
for (i, value) in enumerate(self._good_values... |
def test():
assert Token.has_extension('is_country'), "As-tu declare l'extension du token ?"
ext = Token.get_extension('is_country')
assert (ext[0] == False), 'As-tu defini correctement la valeur par defaut ?'
country_values = [False, False, False, True, False]
assert ([t._.is_country for t in doc] ... |
.django_db
def test_show_collaborators_tab_when_all_checks_are_false_should_return_false(user1, event1, mocker):
mock_can_register_as_collaborator = mocker.patch('manager.templatetags.filters.can_register_as_collaborator')
mock_can_register_as_collaborator.return_value = False
mock_can_register_as_installer... |
def test_valid_document(tmpdir):
schema = os.path.join(tmpdir, 'schema.json')
with open(schema, 'w') as schema_file:
schema_file.write(json.dumps({'openapi': '3.0.0', 'info': {'title': '', 'version': ''}, 'paths': {}}))
runner = CliRunner()
result = runner.invoke(cli, ['validate', '--path', sche... |
.asyncio
.workspace_host
class TestUserOAuthAccounts():
async def test_unauthorized(self, unauthorized_dashboard_assertions: HTTPXResponseAssertion, test_client_dashboard: test_data: TestData):
response = (await test_client_dashboard.get(f"/users/{test_data['users']['regular'].id}/oauth-accounts"))
... |
class PhysicalFile(tuple):
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
for f in self:
f.close()
def __repr__(self):
return 'PhysicalFile(logical files: {})'.format(len(self))
def describe(self,... |
class VirtualMachineError(Exception):
def __init__(self, exc: ValueError) -> None:
self.txid: str = ''
self.source: str = ''
self.revert_type: str = ''
self.pc: Optional[int] = None
self.revert_msg: Optional[str] = None
self.dev_revert_msg: Optional[str] = None
... |
class CartesianGrid(Grid):
_coordinate_system = 'cartesian'
def x(self):
return self.coords[0]
def y(self):
return self.coords[1]
def z(self):
return self.coords[2]
def w(self):
return self.coords[3]
def scale(self, scale):
if np.isscalar(scale):
... |
class vtk(testing.TestCase):
def setUp(self):
super().setUp()
if (self.ndims == 1):
self.x = numpy.array([[0], [1], [2], [3]], dtype=self.xtype)
self.tri = numpy.array([[0, 1], [1, 2], [2, 3]])
elif (self.ndims == 2):
self.x = numpy.array([[0, 0], [0, 1], ... |
def visit_fields_with_memo(fields: Dict[(str, FieldEntry)], func: Callable[([FieldEntry, Field], None)], memo: Optional[Dict[(str, Field)]]=None) -> None:
for (name, details) in fields.items():
if ('field_details' in details):
func(details, memo)
if ('fields' in details):
vis... |
class StacktraceProfiler(threading.Thread):
def __init__(self, thread_to_monitor, endpoint, ip, group_by, outlier_profiler=None):
threading.Thread.__init__(self)
self._keeprunning = True
self._thread_to_monitor = thread_to_monitor
self._endpoint = endpoint
self._ip = ip
... |
_blueprint.route('/projects/search')
_blueprint.route('/projects/search/')
_blueprint.route('/projects/search/<pattern>')
def projects_search(pattern=None):
pattern = (flask.request.args.get('pattern', pattern) or '*')
page = flask.request.args.get('page', 1)
exact = flask.request.args.get('exact', 0)
t... |
class OptionPlotoptionsLineSonificationDefaultspeechoptionsMapping(Options):
def pitch(self) -> 'OptionPlotoptionsLineSonificationDefaultspeechoptionsMappingPitch':
return self._config_sub_data('pitch', OptionPlotoptionsLineSonificationDefaultspeechoptionsMappingPitch)
def playDelay(self) -> 'OptionPlot... |
class PageModel():
def __init__(self):
self.id: int = None
self.title: str = None
self.link_name: str = None
self.type: str = None
self.order: int = None
self.content: str = None
def copy(self):
m = PageModel()
m.id = self.id
m.title = self... |
class OptionSonificationGlobalcontexttracksMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
s... |
class PageCallToAction(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isPageCallToAction = True
super(PageCallToAction, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
android_app = 'android_app'
android_deeplink = 'and... |
def copy_solution_files(exercise: ExerciseInfo, workdir: Path, exercise_config: ExerciseConfig=None):
if (exercise_config is not None):
solution_files = exercise_config.files.solution
exemplar_files = exercise_config.files.exemplar
helper_files = exercise_config.files.editor
else:
... |
class PageTriggerBase(UrlTrigger):
pluginName = 'Page Triggers'
loggerPath = 'PageTriggers'
def pages(self):
pass
def get_urls(self):
return [tmp for tmp in self.pages]
def retriggerPages(self):
self.retriggerUrlList(self.pages, ignoreignore=True, retrigger_complete=True)
... |
.standalone
def contour():
mayavi.new_scene()
r = VTKFileReader()
filename = join(mayavi2.get_data_dir(dirname(abspath(__file__))), 'heart.vtk')
r.initialize(filename)
mayavi.add_source(r)
o = Outline()
mayavi.add_module(o)
gp = GridPlane()
mayavi.add_module(gp)
gp = GridPlane()
... |
def update_event_info(event_slug, render_dict=None, event=None):
event = get_object_or_404(Event, event_slug=event_slug)
contacts = Contact.objects.filter(event=event)
render_dict = (render_dict or {})
render_dict.update({'event_slug': event_slug, 'event': event, 'contacts': contacts})
return render... |
class encrypt(crypto_base):
def __get_tcp_wrap(self, _list: list):
byte_data = b''.join(_list)
size = len(byte_data)
header = struct.pack('!IH', zlib.crc32(byte_data), size)
return b''.join([header, byte_data])
def wrap(self, user_id: bytes, byte_data: bytes):
size = len(... |
def query_photos(url, key, nsid, page):
params = {'per_page': 100, 'page': page, 'extras': 'media,url_sq,url_q,url_t,url_s,url_n,url_w,url_m,url_z,url_c,url_l,url_h,url_k,url_3k,url_4k,url_f,url_5k,url_6k,url_o', 'api_key': key, 'format': 'json', 'nojsoncallback': 1}
match = re.search('/(?:sets|albums)/([^/]+)'... |
class LoopIR_Dependencies(LoopIR_Do):
def __init__(self, buf_sym, stmts):
self._buf_sym = buf_sym
self._lhs = None
self._depends = defaultdict(set)
self._alias = dict()
self._lhs = None
self._context = set()
self._control = False
self.do_stmts(stmts)
... |
class Function_Definition(Definition):
def __init__(self, t_fun, n_sig, l_validation, n_body, l_nested):
super().__init__()
assert isinstance(t_fun, MATLAB_Token)
assert ((t_fun.kind == 'KEYWORD') and (t_fun.value == 'function'))
assert isinstance(n_sig, Function_Signature)
a... |
class OptionPlotoptionsTimelineSonificationDefaultspeechoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, ... |
class MainDialog(QtWidgets.QDialog, AnimaDialogBase):
shot_child_task_defaults = {'Animation': {'schedule_timing': 1, 'schedule_unit': 'd'}, 'Camera': {'schedule_timing': 10, 'schedule_unit': 'min', 'schedule_model': 'duration'}, 'Comp': {'schedule_timing': 1, 'schedule_unit': 'h'}, 'Lighting': {'schedule_timing': ... |
class OptionSeriesPyramidSonificationTracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
s... |
.parametrize('type_str, expected_type', (('uint', BasicType('uint', 256)), ('uint256[]', BasicType('uint', 256, ((),))), ('function', BasicType('bytes', 24)), ('fixed', BasicType('fixed', (128, 18))), ('ufixed', BasicType('ufixed', (128, 18)))))
def test_normalizing_and_parsing_works(type_str, expected_type):
asser... |
class Candidate():
def __init__(self, source_contig, source_start, source_end, members, score, std_span, std_pos, support_fraction='.', genotype='./.', ref_reads=None, alt_reads=None):
self.source_contig = source_contig
self.source_start = source_start
self.source_end = source_end
se... |
class OptionPlotoptionsTreemapStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsTreemapStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsTreemapStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
class BrownieMiddlewareABC(ABC):
def __init__(self, w3: Web3) -> None:
self.w3 = w3
def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]:
raise NotImplementedError
def __call__(self, make_request: Callable, w3: Web3) -> Callable:
return functools.partial(self.process_requ... |
class MongoClientModel(Document):
id = SequenceField(primary_key=True)
namespace = StringField()
sender = StringField()
create_time = LongField()
is_deleted = BooleanField(default=False)
def __repr__(self):
return '<Document Client ({}, {}, {}, {})>'.format(self.id, self.namespace, self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.