code stringlengths 281 23.7M |
|---|
class OptionPlotoptionsSankeySonificationTracksMappingHighpassResonance(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 Scope(frozenset):
def __new__(cls, *members):
return super().__new__(cls, [str(m) for m in members])
def __repr__(self):
members = (("'" + "', '".join(sorted(self))) + "'")
return f'Scope({members})'
def __str__(self):
return ' '.join(sorted(self))
def __add__(self,... |
class RealtimeEntryRecorded(ModelNormal):
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
_property
def openapi_types():
return {}
_property
def discriminator():
return None
attribute_map = {}
read_only_vars = {}
_compo... |
def cmd_playground():
ensure_node_install()
parser = argparse.ArgumentParser(description='Launches an instance of the LMQL playground.')
parser.add_argument('--live-port', type=int, default=3004, help='port to use to host the LMQL live server')
parser.add_argument('--ui-port', type=int, default=3000, he... |
class GptsMessagesEntity(Model):
__tablename__ = 'gpts_messages'
id = Column(Integer, primary_key=True, comment='autoincrement id')
conv_id = Column(String(255), nullable=False, comment='The unique id of the conversation record')
sender = Column(String(255), nullable=False, comment='Who speaking in the ... |
def get_geth_version_info_string(**geth_kwargs):
if ('suffix_args' in geth_kwargs):
raise TypeError('The `get_geth_version` function cannot be called with the `suffix_args` parameter')
geth_kwargs['suffix_args'] = ['version']
(stdoutdata, stderrdata, command, proc) = geth_wrapper(**geth_kwargs)
... |
class OptionSeriesTreegraphDataDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(... |
def main() -> None:
parser = argparse.ArgumentParser(description='mypy wrapper linter.', fromfile_prefix_chars='')
parser.add_argument('--retries', default=3, type=int, help='times to retry timed out mypy')
parser.add_argument('--config', required=True, help='path to an mypy .ini config file')
parser.ad... |
class TestOptunaInvalidCastChoice():
def test_invalid_cast_choice(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test_hp_cast.yaml'])
optuna_config = OptunaTunerConfig(study_name='Basic Tests', direction='maximize')
... |
class OptionSeriesPolygonMarkerStates(Options):
def hover(self) -> 'OptionSeriesPolygonMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesPolygonMarkerStatesHover)
def normal(self) -> 'OptionSeriesPolygonMarkerStatesNormal':
return self._config_sub_data('normal', OptionSeriesP... |
class Solution(object):
def validPalindrome(self, s):
(st, en) = (0, (len(s) - 1))
while (st < en):
if (s[st] != s[en]):
s1 = (st + 1)
e1 = en
while (s1 < e1):
if (s[s1] != s[e1]):
break
... |
def test_validate_mnt_size(monkeypatch, log_capture):
monkeypatch.setattr(simulation, 'WARN_MONITOR_DATA_SIZE_GB', (1 / (2 ** 30)))
s = SIM.copy(update=dict(monitors=(td.FieldMonitor(name='f', freqs=[.0], size=(1, 1, 1)),)))
s._validate_monitor_size()
assert_log_level(log_capture, 'WARNING')
monkeyp... |
class OptionSeriesGaugeDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, js_ty... |
def test_wf_with_catching_no_return():
def t1() -> typing.Dict:
return {}
def t2(d: typing.Dict):
assert (d == {})
def t3(s: str):
pass
with pytest.raises(AssertionError):
def wf():
d = t1()
x = t2(d=d)
t3(s=x)
wf() |
def aim_at_target(sensitivity, va, angle):
global g_current_tick
global g_previous_tick
y = (va.x - angle.x)
x = (va.y - angle.y)
if (y > 89.0):
y = 89.0
elif (y < (- 89.0)):
y = (- 89.0)
if (x > 180.0):
x -= 360.0
elif (x < (- 180.0)):
x += 360.0
if (... |
class ExtraSettingsFormsTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_form_with_valid_data(self):
form_data = {'name': 'PACKAGE_NAME', 'value_type': Setting.TYPE_BOOL}
form_obj = SettingForm(data=form_data)
self.assertTrue(form_obj.is_val... |
.parametrize('attr_dict', ({}, {'SafeSendLib': 'abc'}, {'SafeSendLib': 123}, {'SafeSendLib': b'abc'}, {'safe-send-lib': '0x4F5B11c860b37b68DE6D14Fb7e7b5f18A9A1bdC0'}, {'SafeSendLib': '0x4F5B11c860b37b68DE6D14Fb7e7b5f18A9A1bdC0', 'Wallet': '0xa66A05D6AB5c1c955F4D2c3FCC166AE6300b452B'}))
def test_contract_factory_invalid... |
class OptionPlotoptionsWordcloudSonificationTracksMappingTime(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):
se... |
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestConcreteWidget(unittest.TestCase, GuiTestAssistant):
def setUp(self):
GuiTestAssistant.setUp(self)
self.widget = ConcreteWidget()
def tearDown(self):
if (self.widget.control is not None):
with self.delete_widget(self.wi... |
class TestExternalPluginSourceSupplier():
def setup_method(self, method):
self.along_es = supplier.ExternalPluginSourceSupplier(plugin=team.PluginDescriptor('some-plugin', core_plugin=False), revision='abc', src_dir='/src', src_config={'plugin.some-plugin.src.subdir': 'elasticsearch-extra/some-plugin', 'plu... |
def extractRosetranslatesWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('my sweet physician wife who calls the shots', 'my sweet physician wife who calls the shots... |
class Cohere(REST):
def credentials(self) -> Dict[(str, str)]:
api_key = os.getenv('CO_API_KEY')
if (api_key is None):
warnings.warn("Could not find the API key to access the Cohere API. Ensure you have an API key set up via then make it available as an environment variable 'CO_API_KEY'... |
def save_to_csv(generator_ad_archives, args, fields, is_verbose=False):
if (len(args) != 1):
raise Exception('save_to_csv action takes 1 argument: output_file')
delimiter = ','
total_count = 0
output = (fields + '\n')
output_file = args[0]
for ad_archives in generator_ad_archives:
... |
def run_example():
bucket_size = 5
epsilon = 1
print('>>>>> in RAPPOR')
rappor = RAPPOR(bucket_size=bucket_size, epsilon=epsilon)
(bucket_list, true_hist) = example.generate_bucket(n=10000, bucket_size=bucket_size, distribution_name='uniform')
print('this is buckets: ', bucket_list)
print('t... |
def test_ld(golden):
ConfigLoad = new_config_ld()
_gemm_config_ld_i8 = ('gemmini_extended3_config_ld({src_stride}, ' + '{scale}[0], 0, 0);\n')
(_gemm_config_ld_i8)
def config_ld_i8(scale: f32, src_stride: stride):
ConfigLoad.scale = scale
ConfigLoad.src_stride = src_stride
_gemm_do_l... |
def convert_to_richtext(apps, schema_editor):
BlogPost = apps.get_model('blog', 'BlogPost')
for post in BlogPost.objects.all():
if (post.body.raw_text is None):
raw_text = ''.join([child.value.source for child in post.body if (child.block_type == 'rich_text')])
post.body = raw_te... |
class Command(BaseCommand):
def handle(self, *args, **kwargs):
today = date.today()
first_of_month = date(today.year, today.month, 1)
num_concessions = NCSOConcession.objects.count()
num_concessions_in_this_month = NCSOConcession.objects.filter(date=first_of_month).count()
un... |
class FieldFile(Field):
name = 'Field Integer'
def __init__(self, page: primitives.PageModel, value, label, placeholder, icon, width, height, html_code, helper, options, profile):
html_input = page.ui.inputs.file(page.inputs.get(html_code, value), width=(None, '%'), placeholder=placeholder, options=opti... |
class flow_lightweight_stats_entry(loxi.OFObject):
def __init__(self, table_id=None, reason=None, priority=None, match=None, stats=None):
if (table_id != None):
self.table_id = table_id
else:
self.table_id = 0
if (reason != None):
self.reason = reason
... |
def run_stage(config: Dict[(str, Any)], instance_id: str, stage: PrivateComputationBaseStageFlow, logger: logging.Logger, server_ips: Optional[List[str]]=None, dry_run: bool=False) -> None:
pc_service = build_private_computation_service(config['private_computation'], config['mpc'], config['pid'], config.get('post_p... |
def downgrade():
with op.batch_alter_table('feed_event', schema=None) as batch_op:
batch_op.alter_column('pour', existing_type=sa.INTEGER(), nullable=False, existing_server_default=sa.text("'0'"))
batch_op.alter_column('full', existing_type=sa.INTEGER(), nullable=False, existing_server_default=sa.te... |
class MsgServicer(object):
def GrantAllowance(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RevokeAllowance(self, request, context):
context.set_code... |
class Permute(Fixed, VolumePreserving):
domain = constraints.real_vector
codomain = constraints.real_vector
def __init__(self, params_fn: Optional[flowtorch.Lazy]=None, *, shape: torch.Size, context_shape: Optional[torch.Size]=None, permutation: Optional[torch.Tensor]=None) -> None:
super().__init__... |
def test_fit_knee():
ap_params = [50, 10, 1]
gauss_params = [10, 0.3, 2, 20, 0.1, 4, 60, 0.3, 1]
nlv = 0.0025
(xs, ys) = sim_power_spectrum([1, 150], ap_params, gauss_params, nlv)
tfm = SpectralModel(aperiodic_mode='knee', verbose=False)
tfm.fit(xs, ys)
assert np.allclose(ap_params, tfm.aper... |
class HighQualityWriter():
def __init__(self, fps=30):
self.fps = fps
self.tmp_dir = None
self.cur_frame = 0
def _initialize_video(self):
self.tmp_dir = tempfile.TemporaryDirectory()
self.cur_frame = 0
def add_frame(self, frame):
if (self.tmp_dir is None):
... |
def user_login(request, username=None):
logger.debug('in user_login')
next_page = None
if ('next' in request.GET):
next_page = request.GET['next']
password = ''
if request.POST:
if (not username):
username = request.POST['username']
if ('password' in request.POST)... |
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--ip', type=str, default='::', help='IP address to bind to')
parser.add_argument('--port', type=int, default=1969, help='port to bind to')
parser.add_argument('--retries', type=int, default=5, help='number of per-packet retries... |
class OCRThread(QThread):
def __init__(self, image_path):
QThread.__init__(self)
self.image_path = image_path
def adjust_ocr(self, ocr_string):
for char in OCR_ADJUST_DICT:
ocr_string = ocr_string.replace(char, OCR_ADJUST_DICT[char])
return ocr_string
def run(self... |
def test_lock(tmp_path, monkeypatch):
with open_storage(tmp_path, mode='w') as storage:
experiment_id = storage.create_experiment()
storage.create_ensemble(experiment_id, name='foo', ensemble_size=42)
monkeypatch.setattr(local.LocalStorageAccessor, 'LOCK_TIMEOUT', 0.1)
with pytest.ra... |
class DirectOutputError(Exception):
Errors = {E_HANDLE: 'Invalid device handle specified.', E_INVALIDARG: "An argument is invalid, and I don't mean it has a poorly leg.", E_OUTOFMEMORY: 'Download more RAM.', E_PAGENOTACTIVE: 'Page not active, stupid page.', E_BUFFERTOOSMALL: 'Buffer used was too small. Use a bigger... |
class CustomEditor(BasicEditorFactory):
klass = Property()
factory = Callable()
args = Tuple()
def __init__(self, *args, **traits):
if (len(args) >= 1):
self.factory = args[0]
self.args = args[1:]
super().__init__(**traits)
def _get_klass(self):
return... |
_checkpoint(dump_params=True, include=['dataset_id'], component=LOG_COMPONENT)
def _get_attribution_dataset_info(client: BoltGraphAPIClient[BoltPAGraphAPICreateInstanceArgs], dataset_id: str, logger: logging.Logger) -> Any:
return json.loads(client.get_attribution_dataset_info(dataset_id, [DATASETS_INFORMATION, TAR... |
def example():
async def move_divider(e: ft.DragUpdateEvent):
if (((e.delta_y > 0) and (c.height < 300)) or ((e.delta_y < 0) and (c.height > 100))):
c.height += e.delta_y
(await c.update_async())
async def show_draggable_cursor(e: ft.HoverEvent):
e.control.mouse_cursor = ft.M... |
class ConnectionCall(invoke.Call):
def __init__(self, *args, **kwargs):
init_kwargs = kwargs.pop('init_kwargs')
super().__init__(*args, **kwargs)
self.init_kwargs = init_kwargs
def clone_kwargs(self):
kwargs = super().clone_kwargs()
kwargs['init_kwargs'] = self.init_kwarg... |
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder):
super(Seq2Seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
def init_weights(self):
for (name, param) in self.named_parameters():
nn.init.uniform_(param.data, (- 0.08), 0.08)
def for... |
.parametrize('testcase', [5, 6])
def test_scalar_convergence(testcase):
mesh = UnitSquareMesh((2 ** 2), (2 ** 2), quadrilateral=True)
mesh = ExtrudedMesh(mesh, (2 ** 2))
fspace = FunctionSpace(mesh, 'S', testcase)
u = TrialFunction(fspace)
v = TestFunction(fspace)
(x, y, z) = SpatialCoordinate(m... |
def ip_prefix_convert(n, is_ipv6=False):
seq = []
cnt = 4
if is_ipv6:
cnt = 16
a = int((n / 8))
b = (n % 8)
for i in range(a):
seq.append(255)
v = 0
for i in range(b):
v |= (1 << (7 - i))
seq.append(v)
if (len(seq) < cnt):
for i in range((cnt - len... |
class ProjectorBase(object, metaclass=abc.ABCMeta):
def __init__(self, source, target, bcs=None, solver_parameters=None, form_compiler_parameters=None, constant_jacobian=True, use_slate_for_inverse=True):
if (solver_parameters is None):
solver_parameters = {}
else:
solver_par... |
def get_cut_text(window, key):
cut_text = ''
new_text = window[key].get()
if (not new_text):
return window.metadata[key]
i = 0
for v in window.metadata[key]:
if ((i >= len(new_text)) or (v != new_text[i])):
cut_text += v
else:
i += 1
return cut_tex... |
(scope='session')
def redshift_test_engine() -> Generator:
connection_config = ConnectionConfig(name='My Redshift Config', key='test_redshift_key', connection_type=ConnectionType.redshift)
host = (integration_config.get('redshift', {}).get('host') or os.environ.get('REDSHIFT_TEST_HOST'))
port = (integration... |
class bad_request_error_msg(error_msg):
version = 3
type = 1
err_type = 1
def __init__(self, xid=None, code=None, data=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (code != None):
self.code = code
else:
s... |
_for(Session, 'after_commit')
def send_messages_after_commit(session):
if ('messages' in session.info):
for m in session.info['messages']:
try:
_publish_with_retry(m)
except fml_exceptions.BaseException:
_log.exception('An error occurred publishing %r ... |
def test_peek_eof():
source = b'Hello, world!\n'
source_stream = io.BytesIO(source)
stream = BufferedReader(source_stream.read, (len(source) - 1))
assert (stream.peek(0) == b'')
assert (stream.peek(1) == b'H')
assert (stream.peek(2) == b'He')
assert (stream.peek(16) == b'Hello, world!')
... |
class TestSkillBehaviour(BaseSkillTestCase):
path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'tac_negotiation')
def setup(cls):
tac_dm_context_kwargs = {'goal_pursuit_readiness': GoalPursuitReadiness(), 'ownership_state': OwnershipState(), 'preferences': Preferences()}
super().se... |
.compilertest
def test_valid_grpc_stats_services():
yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Module\nmetadata:\n name: ambassador\n namespace: default\nspec:\n config:\n grpc_stats:\n services:\n - name: echo.EchoService\n method_names: [Echo]\n'
cache = Cache(logge... |
def test_liveness_of_one_basicblock_a(construct_graph_one_basicblock, variable_x, variable_v, variable_u):
(nodes, cfg) = construct_graph_one_basicblock
liveness_analysis = LivenessAnalysis(cfg)
assert (liveness_analysis.live_in_of(nodes[0]) == {variable_u[0], variable_v[0], variable_x[0]})
assert (live... |
def test___setitem__checks_the_value_ranges_2():
wh = WorkingHours()
with pytest.raises(ValueError) as cm:
wh['sat'] = [[0, 1800]]
assert (str(cm.value) == 'WorkingHours.working_hours value should be a list of lists of two integers between and the range of integers should be 0-1440, not [[0, 1800]]'... |
def test_extruded_periodic_boundary_nodes():
mesh = UnitIntervalMesh(2)
extm = ExtrudedMesh(mesh, layers=2, extrusion_type='uniform', periodic=True)
V = FunctionSpace(extm, 'CG', 2)
assert (V.boundary_nodes(1) == np.array([4, 5, 6, 7])).all()
assert (V.boundary_nodes(2) == np.array([16, 17, 18, 19])... |
def test_arg_botcdm_returns_errors_as_chat(dummy_backend):
dummy_backend.callback_message(makemessage(dummy_backend, '!returns_first_name_last_name --invalid-parameter'))
assert ("I couldn't parse the arguments; unrecognized arguments: --invalid-parameter" in dummy_backend.pop_message().body) |
def exposed_fetch(url, debug=True, rss_debug=False, special_case_enabled=True):
specialcase_data = WebMirror.rules.load_special_case_sites()
print(('Debug: %s, rss_debug: %s' % (debug, rss_debug)))
if rss_debug:
print('Debugging RSS')
flags.RSS_DEBUG = True
parsed = urllib.parse.urlparse... |
def make_git(*prefix_args) -> Optional[Callable]:
git_exe = shutil.which('git')
prefix_args = [str(arg) for arg in prefix_args]
if (not git_exe):
click.secho('Unable to find git', err=True, fg='red')
ctx = click.get_current_context(silent=True)
if (ctx is not None):
ctx.e... |
def test_static_memory_check(compiler):
def callee():
pass
def caller():
x: R
if (1 < 2):
y: (R StaticMemory)
for i in seq(0, 8):
callee()
with pytest.raises(MemGenError, match='Cannot generate static memory in non-leaf procs'):
compiler.compi... |
class LiteSATAPHY(Module, AutoCSR):
def __init__(self, device, pads, gen, clk_freq, refclk=None, data_width=16, qpll=None, gt_type='GTY', use_gtgrefclk=True, with_csr=True):
self.pads = pads
self.gen = gen
self.refclk = refclk
self.enable = Signal()
self.ready = Signal()
... |
class NumpyBackend(Backend):
int = numpy.int64
float = numpy.float64
complex = numpy.complex128
asarray = _replace_float(numpy.asarray)
exp = staticmethod(numpy.exp)
sin = staticmethod(numpy.sin)
cos = staticmethod(numpy.cos)
sum = staticmethod(numpy.sum)
max = staticmethod(numpy.max... |
def choose_middlewares(data: DataModel):
(chosen_middlewares_names, chosen_middlewares_ids) = data.get_selected_middleware_lists()
widget = ReorderBullet(_('3. Choose middlewares (optional).'), choices=chosen_middlewares_names, choices_id=chosen_middlewares_ids)
(middlewares_names, middlewares_ids) = data.g... |
class FESpace():
def __init__(self):
pass
def getFESpace(self):
basis = ft.C0_AffineLinearOnSimplexWithNodalBasis
elementQuadrature = ft.SimplexGaussQuadrature(2, 3)
elementBoundaryQuadrature = ft.SimplexGaussQuadrature(1, 3)
return {'basis': basis, 'elementQuadrature': e... |
class Player():
name: str
def create_players(cls, names: Optional[List[str]]=None) -> List[Player]:
if (names is None):
names = ['Player 1', 'Player 2']
assert (len(names) == len(set(names))), 'Player names must be unique'
return [cls(name) for name in names] |
class TestZillizVectorDB():
.dict(os.environ, {'ZILLIZ_CLOUD_URI': 'mocked_uri', 'ZILLIZ_CLOUD_TOKEN': 'mocked_token'})
def mock_config(self, mocker):
return mocker.Mock(spec=ZillizDBConfig())
('embedchain.vectordb.zilliz.MilvusClient', autospec=True)
('embedchain.vectordb.zilliz.connections.con... |
def measure_for_all_england(request, measure):
measure = get_object_or_404(Measure, pk=measure)
entity_type = request.GET.get('entity_type', 'ccg')
measure_options = {'aggregate': True, 'chartTitleUrlTemplate': _url_template('measure_for_all_ccgs'), 'globalMeasuresUrl': _build_global_measures_url(measure_id... |
def _expand_ellipsis(obj, fields):
direct_names = {f.value.name for f in fields if isinstance(f.value, ast.Name)}
for f in fields:
assert isinstance(f, ast.NamedField)
if isinstance(f.value, ast.Ellipsis):
if f.name:
msg = "Cannot use a name for ellipsis (inlining ope... |
def decodezerostr(barr):
result = ''
for b in range(len(barr)):
if (barr[b] == 0):
try:
result = barr[:b].decode('utf-8')
except:
result = str(barr[:b])
break
if (b >= (len(barr) - 1)):
try:
result = barr.decode(... |
def to_jfed(topology, path, testbed='wall1.ilabt.iminds.be', encoding='utf-8', prettyprint=True):
if topology.is_directed():
topology = topology.to_undirected()
topology = nx.convert_node_labels_to_integers(topology)
if ('capacity_unit' in topology.graph):
capacity_norm = (units.capacity_uni... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
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':... |
def _set_logger():
logger = logging.getLogger('TfPoseEstimator')
logger.setLevel(logging.DEBUG)
logging_stream_handler = logging.StreamHandler()
logging_stream_handler.setLevel(logging.DEBUG)
logging_formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')
logging_st... |
def extractDragomirCM(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ((not postfix) and (':' in item['title'])):
postfix = item['title'].split(':')[(- 1)]
if ('Magic Academ... |
def is_comment(extension, string):
if ((__comment_begining__.get(extension, None) != None) and string.strip().startswith(__comment_begining__[extension])):
return True
if ((__comment_end__.get(extension, None) != None) and string.strip().endswith(__comment_end__[extension])):
return True
if ... |
def get_db_engine(*, config: (FidesConfig | None)=None, database_uri: ((str | URL) | None)=None, pool_size: int=50, max_overflow: int=50) -> Engine:
if ((not config) and (not database_uri)):
raise ValueError('Either a config or database_uri is required')
if ((not database_uri) and config):
if co... |
def test_gc_closes_socket(unused_tcp_port):
custom_range = range(unused_tcp_port, (unused_tcp_port + 1))
(_, port, orig_sock) = port_handler.find_available_port(custom_range=custom_range, custom_host='127.0.0.1')
assert (port == unused_tcp_port)
assert (orig_sock is not None)
assert (orig_sock.filen... |
class TestCliGenerateCommand():
def test_should_exit_zero_when_invoked_with_help(self, monkeypatch, fake_project_with_generators, cli_runner):
monkeypatch.chdir(fake_project_with_generators['root'])
result = cli_runner.invoke(get_generate_cmd(), ['--help'])
assert (result.exit_code == 0)
... |
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 DirectorBackendAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'backend_name': (str,), 'di... |
class FaceCollection():
def __init__(self, api_key: str, domain: str, port: str, options: AllOptionsDict={}):
self.available_services = []
self.api_key = api_key
self.options = options
self.add_example: AddExampleOfSubject = AddExampleOfSubject(domain=domain, port=port, api_key=api_k... |
def read_version_from_file(filename: str) -> Optional[str]:
with open(filename, 'r') as file:
version_content = file.read()
version_match = re.search('version=(\\d+\\.\\d+\\.\\d+)', version_content)
if version_match:
version = version_match.group(1)
else:
vers... |
class EmbeddingEngingOperator(MapOperator[(ChatContext, ChatContext)]):
def __init__(self, **kwargs):
super().__init__(**kwargs)
async def map(self, input_value: ChatContext) -> ChatContext:
from dbgpt.configs.model_config import EMBEDDING_MODEL_CONFIG
from dbgpt.rag.embedding_engine.emb... |
class HTTPProxyGETTestCase(HTTPProxyTestCase):
def setUp(self):
super().setUp()
self.method = 'GET'
.object( 'resolve')
_run_loop
async def test_get_valid_request(self, resolve):
resolve.return_value = echo_dns_q(self.dnsq)
params = utils.build_query_params(self.dnsq.to_w... |
class testNetAsciiReader(unittest.TestCase):
def testNetAsciiReader(self):
tests = [('foo\nbar\nand another\none', bytearray(b'foo\r\nbar\r\nand another\r\none')), ('foo\r\nbar\r\nand another\r\none', bytearray(b'foo\r\x00\r\nbar\r\x00\r\nand another\r\x00\r\none'))]
for (input_content, expected) in... |
class DictMeta(Meta):
def __getitem__(self, types):
(type_keys, type_values) = types
if isinstance(type_keys, str):
type_keys = str2type(type_keys)
if isinstance(type_values, str):
type_values = str2type(type_values)
return type('DictBis', (Dict,), {'type_keys... |
class LTImage(LTComponent):
def __init__(self, name, stream, bbox):
LTComponent.__init__(self, bbox)
self.name = name
self.stream = stream
self.srcsize = (stream.get_any(('W', 'Width')), stream.get_any(('H', 'Height')))
self.imagemask = stream.get_any(('IM', 'ImageMask'))
... |
_blueprint.route('/project/<project_name>')
_blueprint.route('/project/<project_name>/')
def project_name(project_name):
page = flask.request.args.get('page', 1)
try:
page = int(page)
except ValueError:
page = 1
projects = models.Project.search(Session, pattern=project_name, page=page)
... |
class OptionPlotoptionsWaterfallSonificationDefaultinstrumentoptionsMappingNoteduration(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(se... |
def hass_announce_sensor_input(sens_conf: ConfigType, mqtt_conf: ConfigType, mqtt_options: MQTTClientOptions) -> MQTTMessageSend:
disco_conf: ConfigType = mqtt_conf['ha_discovery']
name: str = sens_conf['name']
prefix: str = mqtt_conf['topic_prefix']
disco_prefix: str = disco_conf['prefix']
sensor_c... |
class ScrollBar():
def __init__(self, printer: ColorPrinter, lines: Dict[(int, LineBase)], screen_control: 'Controller'):
self.printer = printer
self.screen_control = screen_control
self.num_lines = len(lines)
self.box_start_fraction = 0.0
self.box_stop_fraction = 0.0
... |
class ReqStatus(ReqTagGeneric):
def __init__(self, config):
ReqTagGeneric.__init__(self, config, 'Status', set([InputModuleTypes.reqtag]))
def rewrite(self, rid, req):
self.check_mandatory_tag(rid, req, 16)
tag = req[self.get_tag()].get_content()
val = create_requirement_status(s... |
def convert_to_data_url(view: sublime.View, edit: sublime.Edit, region: sublime.Region):
max_size = emmet.get_settings('max_data_url', 0)
src = view.substr(region)
abs_file = None
if utils.is_url(src):
abs_file = src
elif view.file_name():
abs_file = utils.locate_file(view.file_name(... |
class SQLConnector(BaseConnector[Engine]):
secrets_schema: Type[ConnectionConfigSecretsSchema]
def __init__(self, configuration: ConnectionConfig):
super().__init__(configuration)
if (not self.secrets_schema):
raise NotImplementedError('SQL Connectors must define their secrets schema... |
def call_multi_core(pInteractionFilesList, pArgs, pViewpointObj, pBackground, pFilePath, pResolution):
significant_data_list = ([None] * pArgs.threads)
significant_key_list = ([None] * pArgs.threads)
target_data_list = ([None] * pArgs.threads)
target_key_list = ([None] * pArgs.threads)
reference_poi... |
class OptionPlotoptionsVariwideSonificationTracksMappingTremoloSpeed(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 TransactionFPDSSerializer(LimitableSerializer):
prefetchable = False
class Meta():
model = TransactionFPDS
fields = '__all__'
default_fields = ['piid', 'parent_award_piid', 'type', 'type_description', 'cost_or_pricing_data', 'type_of_contract_pricing', 'type_of_contract_pricing_des... |
def filter_string(invs: (str | None), domains: (str | None), otype: (str | None), target: (str | None), *, delimiter: str=':') -> str:
str_items = []
for item in (invs, domains, otype, target):
if (item is None):
str_items.append('*')
elif (delimiter in item):
str_items.a... |
def upgrade():
op.create_table('service', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name'))
op.add_column(u'permissions', sa.Column('can_create', sa.Boolean(), nullable=False))
op.add_column(u'permission... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.