code stringlengths 281 23.7M |
|---|
def extractAnargyatestingHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type... |
class patch():
def __init__(self, name=None, path=None, preservecase=False):
if ((not (name == None)) and (not (path == None))):
inifile = os.path.join(path, (name + '.ini'))
elif (not (name == None)):
inifile = (name + '.ini')
else:
inifile = None
... |
(name='api.vm.status.tasks.vm_status_event_cb', base=InternalTask, ignore_result=True)
def vm_status_event_cb(result, task_id):
vm_uuid = result['zonename']
state_cache = cache.get(Vm.status_key(vm_uuid))
state = Vm.STATUS_DICT[result['state']]
when = result['when']
change_time = datetime.utcfromtim... |
class queue_desc_stats_request(stats_request):
version = 5
type = 18
stats_type = 15
def __init__(self, xid=None, flags=None, port_no=None, queue_id=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = ... |
class All2Allv_Wait(Function):
def forward(ctx, myreq, *output):
collectiveArgs = myreq.bench.collectiveArgs
backendFuncs = myreq.bench.backendFuncs
myreq.req.wait()
backendFuncs.complete_accel_ops(collectiveArgs)
collectiveArgs.timers['fwd_a2a_end'] = time.monotonic()
... |
def extractOneSecondSpring(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('The Princess Who Cannot Marry' in item['tags']):
return buildReleaseMessageWithType(item, 'The Princ... |
def get_dispatch(parsed_list: js_data) -> dict:
reg_graphql = 'e.{method}\\("{queryId}",'.format(method='({0})'.format('|'.join(get_dispatch_list().keys())), queryId='([a-z_/]*?)')
dispatch_list = search_js_reg(parsed_list, reg_graphql)
dispatch_list_unique: list[js_search_data] = []
for i in dispatch_l... |
class EntityData():
unique_id: str
name: str
state: int
attributes: dict
icon: str
device_name: str
status: str
disabled: bool
binary_sensor_device_class: Optional[BinarySensorDeviceClass]
sensor_device_class: Optional[SensorDeviceClass]
sensor_state_class: Optional[SensorSta... |
class RecordableEnvMixin(ABC):
def get_maze_state(self) -> MazeStateType:
raise NotImplementedError
def get_maze_action(self) -> MazeActionType:
raise NotImplementedError
def get_episode_id(self) -> str:
raise NotImplementedError
def get_renderer(self) -> Renderer:
raise ... |
class EpisodeCallbacks():
def __init__(self) -> None:
self._custom_metrics = {}
def custom_metrics(self) -> Dict[(str, Any)]:
return self._custom_metrics
_metrics.setter
def custom_metrics(self, metrics: Dict[(str, Any)]) -> None:
self._custom_metrics = metrics
def reset(self... |
def remaining():
w_pawn_count = utils.typeCounter('pawn', 'W')
w_rook_count = utils.typeCounter('rook', 'W')
w_knight_count = utils.typeCounter('knight', 'W')
w_bishop_count = utils.typeCounter('bishop', 'W')
w_queen_count = utils.typeCounter('queen', 'W')
w_king_count = utils.typeCounter('king'... |
class ChangeEmailActivateView(View):
def get(request, code):
act = get_object_or_404(Activation, code=code)
user = act.user
user.email = act.email
user.save()
act.delete()
messages.success(request, _('You have successfully changed your email!'))
return redirec... |
.parametrize(('base_mesh_thunk', 'fs', 'degree'), [((lambda : UnitIntervalMesh(10)), 'CG', 1), ((lambda : UnitIntervalMesh(10)), 'CG', 2), ((lambda : UnitIntervalMesh(10)), 'DG', 1), ((lambda : UnitIntervalMesh(10)), 'DG', 2), ((lambda : UnitSquareMesh(10, 10)), 'CG', 1), ((lambda : UnitSquareMesh(10, 10)), 'CG', 2), (... |
def get_device_info() -> Tuple[(str, str, str, int, str)]:
(torch_version, device, device_version, device_count, device_other) = (None, 'cpu', None, 0, '')
try:
import torch
torch_version = torch.__version__
if torch.cuda.is_available():
device = 'cuda'
device_ver... |
class TensorFlowShim(Shim):
gradients: Optional[List['tf.Tensor']]
def __init__(self, model: Any, config=None, optimizer: Any=None):
super().__init__(model, config, optimizer)
self.gradients = None
def __str__(self):
lines: List[str] = []
def accumulate(line: str):
... |
class FirewallCommand():
def __init__(self, quiet=False, verbose=False):
self.quiet = quiet
self.verbose = verbose
self.__use_exception_handler = True
self.fw = None
def set_fw(self, fw):
self.fw = fw
def set_quiet(self, flag):
self.quiet = flag
def get_qu... |
class TestGetGitLog(unittest.TestCase):
path = os.path.dirname(__file__)
('subprocess.check_output')
def test_doesnt_crash_when_git_command_fails(self, mock_proc):
mock_proc.side_effect = CalledProcessError(999, 'Non-zero return value')
log = ciftify.config.get_git_log(self.path)
ass... |
def cli(f, *, argv=None):
import textwrap
(progname, *args) = (argv or sys.argv)
doc = stringly.util.DocString(f)
serializers = {}
booleans = set()
mandatory = set()
for param in inspect.signature(f).parameters.values():
T = param.annotation
if ((T == param.empty) and (param.... |
def translate(text: str, auth_key: str, preserve_formatting: bool=False, target_lang: str='EN-GB') -> str:
translator = deepl.Translator(auth_key)
result = translator.translate_text(text, target_lang=target_lang, preserve_formatting=preserve_formatting)
assert (not isinstance(result, list))
return resul... |
def main(page):
page.title = 'ListTile Examples'
page.add(Card(content=Container(width=500, content=Column([ListTile(title=Text('One-line list tile')), ListTile(title=Text('One-line dense list tile'), dense=True), ListTile(leading=Icon(icons.SETTINGS), title=Text('One-line selected list tile'), selected=True), ... |
def test_query_sobj_row_with_blob():
testutil.add_response('login_response_200')
testutil.add_response('api_version_response_200')
testutil.add_response('query_attachments_before_blob_200')
testutil.add_response('query_attachments_blob_200')
client = testutil.get_client()
query_result = client.s... |
def get_user_chroots_map(chroots, email_filter):
user_chroot_map = {}
for chroot in chroots:
for admin in coprs_logic.CoprPermissionsLogic.get_admins_for_copr(chroot.copr):
if (email_filter and (admin.mail not in email_filter)):
continue
if (admin not in user_chro... |
def convert_rnn_inputs(model: Model, Xp: Padded, is_train: bool):
shim = cast(PyTorchShim, model.shims[0])
size_at_t = Xp.size_at_t
lengths = Xp.lengths
indices = Xp.indices
def convert_from_torch_backward(d_inputs: ArgsKwargs) -> Padded:
dX = torch2xp(d_inputs.args[0])
return Padded... |
def ui_path(*path, **kwargs):
relto = kwargs.pop('relto', None)
if len(kwargs):
raise ValueError("Only 'relto' is allowed as a keyword argument")
if (relto is None):
return xdg.get_data_path(*path)
else:
return os.path.abspath(os.path.join(os.path.dirname(relto), *path)) |
def chain_without_block_validation(base_db, genesis_state):
klass = MiningChain.configure(__name__='TestChainWithoutBlockValidation', vm_configuration=ConsensusApplier(NoProofConsensus).amend_vm_configuration(((eth_constants.GENESIS_BLOCK_NUMBER, SpuriousDragonVM),)), chain_id=1337)
genesis_params = {'block_num... |
def subscriptgroup_handle(tokens):
internal_assert((0 < len(tokens) <= 3), 'invalid slice args', tokens)
args = []
for arg in tokens:
if (not arg):
arg = 'None'
args.append(arg)
if (len(args) == 1):
return args[0]
else:
return (('_coconut.slice(' + ', '.jo... |
class TestFetchRunnerFunction(unittest.TestCase):
def test_fetch_simple_job_runner(self):
runner = fetch_runner('SimpleJobRunner')
self.assertTrue(isinstance(runner, SimpleJobRunner))
self.assertEqual(runner.nslots, 1)
def test_fetch_simple_job_runner_with_nslots(self):
runner = ... |
def as_geojson_stream(dicts, geometry_field='geometry', srid=4326):
to_geojson = GeoJSONConvertor(srid)
header = {'type': 'FeatureCollection', 'crs': {'type': 'name', 'properties': {'name': 'EPSG:{}'.format(srid)}}}
(yield json.dumps(header)[:(- 1)])
(yield ', "features": [')
for (n, dictionary) in ... |
class Plot2dPane(TraitsTaskPane):
id = 'example.attractors.plot_2d_pane'
name = 'Plot 2D Pane'
active_model = Instance(IPlottable2d)
models = List(IPlottable2d)
plot_type = Property(Str, observe='active_model.plot_type')
title = Property(Str, observe='active_model.name')
x_data = Property(ob... |
class PluginManagerTestCase(unittest.TestCase):
def test_get_plugin(self):
simple_plugin = SimplePlugin()
plugin_manager = PluginManager(plugins=[simple_plugin])
plugin = plugin_manager.get_plugin(simple_plugin.id)
self.assertEqual(plugin, simple_plugin)
self.assertEqual(None... |
def validate_name_email(name_email):
if (not ('#' in name_email)):
return False
(name, email) = name_email.lstrip('').split('#', 1)
if (not re.match('^[\\w.-]+$', name)):
return False
if (not re.match('^[-\\w.]+$', email)):
return False
if (not (email.count('') == 1)):
... |
class AWS(CloudBase):
def __init__(self, aws_access_key_id: Optional[str]=None, aws_secret_access_key: Optional[str]=None, aws_session_token: Optional[str]=None, aws_region: Optional[str]=None) -> None:
aws_access_key_id = (aws_access_key_id or os.environ.get('AWS_ACCESS_KEY_ID'))
aws_secret_access_... |
def main():
build_dir = 'gateware'
platform = arty.Platform(variant='a7-35', toolchain='vivado')
from litex.build.generic_platform import Pins, IOStandard
platform.add_extension([('do', 0, Pins('B7'), IOStandard('LVCMOS33'))])
if ('load' in sys.argv[1:]):
prog = platform.create_programmer()
... |
def test_receiver_contract(accounts, tester):
tx = tester.doNothing({'from': accounts[0]})
assert (type(tx.receiver) is EthAddress)
assert (tester == tx.receiver)
data = tester.revertStrings.encode_input(5)
tx = accounts[0].transfer(tester.address, 0, data=data)
assert (type(tx.receiver) is EthA... |
class HopperLevelRef():
async def get(cls, device_id):
max_hopper_cups = 20.5
tbsp_per_cup = 16
device_results = (await KronosDevices.get(device_hid=device_id))
device = device_results[0]
latest_ref_query = hopper_level_references.select().order_by(desc(hopper_level_reference... |
def find_notifiers(notifier_name):
try:
module = importlib.import_module('google.cloud.forseti.notifier.notifiers.{0}'.format(notifier_name))
for filename in dir(module):
obj = getattr(module, filename)
if (inspect.isclass(obj) and issubclass(obj, BaseNotification) and (obj i... |
class MainHandler(RequestHandler):
def _guess_mime_type(self, fname):
guess = mimetypes.guess_type(fname)[0]
if guess:
self.set_header('Content-Type', guess)
def get(self, full_path):
logger.debug(('Incoming request at %s' % full_path))
parts = [p for p in full_path.s... |
class SelectAttr(bh_plugin.BracketPluginCommand):
def run(self, edit, name, direction='right'):
if (self.left.size() <= 1):
return
tag_settings = sublime.load_settings('bh_tag.sublime-settings')
tag_mode = tags.get_tag_mode(self.view, tag_settings.get('tag_mode', []))
tag... |
def validate(self, method=None):
settings = frappe.get_cached_doc(SETTINGS_DOCTYPE)
if (not settings.is_enabled()):
return
sales_order = self.get('locations')[0].sales_order
unicommerce_order_code = frappe.db.get_value('Sales Order', sales_order, 'unicommerce_order_code')
if unicommerce_orde... |
class TestDeleteFailsWhenDirectoryIsNotAnAEAProject():
def setup_class(cls):
cls.runner = CliRunner()
cls.agent_name = 'myagent'
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
os.chdir(cls.t)
Path(cls.t, cls.agent_name).mkdir()
cls.result = cls.runner.invoke... |
class DollyV2Generator(DefaultGenerator):
def __init__(self, tokenizer: Tokenizer, causal_lm: GPTNeoXCausalLM):
eos_id = tokenizer.tokenizer.token_to_id(END_KEY)
super().__init__(tokenizer, causal_lm, default_config=SampleGeneratorConfig(eos_id=eos_id, max_generated_pieces=256, top_p=0.92))
def ... |
class BeatBarWidget(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.setMinimumSize(100, 12)
self.beat = 0
def setBeat(self, beat):
if (beat != self.beat):
self.beat = beat
self.update()
def paintEvent(self, e):
painter = QPa... |
def test_intrinsics():
string = write_rpc_request(1, 'initialize', {'rootPath': str((test_dir / 'hover'))})
file_path = ((test_dir / 'hover') / 'functions.f90')
string += hover_req(file_path, 39, 23)
(errcode, results) = run_request(string, fortls_args=['-n', '1'])
assert (errcode == 0)
with ope... |
class Markup(object):
def __init__(self, name):
self.__plugin_manager = extension.ExtensionManager(namespace='rmtoo.output.markup', invoke_on_load=False)
self.__impl = self.__plugin_manager[name].plugin()
def replace(self, raw_input_str):
return self.__impl.replace(raw_input_str)
def... |
def analyze_alignment_file_querysorted(bam, options):
alignment_it = bam_iterator(bam)
sv_signatures = []
translocation_signatures_all_bnds = []
read_nr = 0
while True:
try:
alignment_iterator_object = next(alignment_it)
(primary_aln, suppl_aln, sec_aln) = alignment_i... |
.parametrize('calc_cls, kwargs_', [pytest.param(PySCF, {'basis': '321g'}, marks=using('pyscf')), pytest.param(Gaussian16, {'route': 'HF/3-21G'}, marks=using('gaussian16')), pytest.param(Turbomole, {'control_path': './hf_abstr_control_path', 'pal': 1}, marks=using('turbomole'))])
def test_hf_abstraction_dvv(calc_cls, kw... |
.parametrize('endpoint, expected_name', [pytest.param(func_homepage, 'func_homepage', id='function'), pytest.param(Endpoint().my_method, 'my_method', id='method'), pytest.param(Endpoint.my_classmethod, 'my_classmethod', id='classmethod'), pytest.param(Endpoint.my_staticmethod, 'my_staticmethod', id='staticmethod'), pyt... |
.parametrize(argnames=('resource_dict', 'expected_resource_name'), argvalues=(({'cpu': '2'}, _ResourceName.CPU), ({'mem': '1Gi'}, _ResourceName.MEMORY), ({'gpu': '1'}, _ResourceName.GPU), ({'storage': '100Mb'}, _ResourceName.STORAGE), ({'ephemeral_storage': '123Mb'}, _ResourceName.EPHEMERAL_STORAGE)), ids=('CPU', 'MEMO... |
class DateStartStopExpand(StartStopExpand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def parse_config(self):
super().parse_config()
assert isinstance(self.start, datetime.date), (type(self.start), self.start)
assert isinstance(self.end, datetime.date... |
def test_adding_a_secret_mount():
config = '\ndeployment:\n enabled: true\ndaemonset:\n secretMounts:\n - name: elastic-certificates\n secretName: elastic-certificates-name\n path: /usr/share/filebeat/config/certs\n'
r = helm_template(config)
assert ({'mountPath': '/usr/share/filebeat/config/... |
class FaucetUntaggedControllerNfvTest(FaucetUntaggedTest):
def test_untagged(self):
last_host = self.hosts_name_ordered()[(- 1)]
switch = self.first_switch()
last_host_switch_link = switch.connectionsTo(last_host)[0]
last_host_switch_intf = [intf for intf in last_host_switch_link if ... |
class TestNormalizeText():
def test_should_replace_dash_with_hyphen(self):
assert (normalize_text('') == '-')
def test_should_replace_accent_with_quote(self):
assert (normalize_text('') == "'")
def test_should_normalize_multiple_spaces_to_one(self):
assert (normalize_text('a b') ==... |
(MESSAGING_SECRETS, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[MESSAGING_CREATE_OR_UPDATE])], response_model=TestMessagingStatusMessage)
def put_config_secrets(config_key: FidesKey, *, db: Session=Depends(deps.get_db), unvalidated_messaging_secrets: possible_messaging_secrets) -> TestM... |
class TestCLIOpenClosed(CuratorTestCase):
def test_open_closed(self):
(idx1, idx2) = ('dummy', 'my_index')
self.create_index(idx1)
self.create_index(idx2)
self.client.indices.close(index=idx2, ignore_unavailable=True)
args = self.get_runner_args()
args += ['--config',... |
def test_mode_basis_io():
grid = make_pupil_grid(128)
mode_bases = [make_zernike_basis(20, 1, grid, 1), make_xinetics_influence_functions(grid, 8, (1 / 8))]
formats = ['asdf', 'fits', 'fits.gz', 'pkl', 'pickle']
filenames = [('mode_basis_test.' + fmt) for fmt in formats]
for mode_basis in mode_bases... |
def test_generate_gpu_will_overwrite_previous_gpu_version(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
gen = RepresentationGenerator()
gen.version = data['building1_yapi_model_main_v003']
gen.generate_gpu()
r = Representation(version=data['building1_... |
def is_url_whitelisted(url):
found = False
if ((not found) and (url in whitelist['urlExact'])):
found = True
if (not found):
for regex in whitelist['regexDomainsInURLs']:
if re.search(regex, url):
found = True
if (not found):
for regex in whitelist['ur... |
.usefixtures('migrate_db')
class TriggerTestCase(common.BaseTestCase):
def setUp(self):
super().setUp()
self.longMessage = True
self.maxDiff = None
self.request_context = rest.app.test_request_context()
self.request_context.push()
self.connection = rest.db.engine.conn... |
def build_dummy_maze_environment() -> DummyEnvironment:
observation_conversion = ObservationConversion()
return DummyEnvironment(core_env=DummyCoreEnvironment(observation_conversion.space()), action_conversion=[DictDiscreteActionConversion()], observation_conversion=[observation_conversion]) |
class OptionSeriesVennSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesVennSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesVennSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesVennSonificationC... |
('bing')
_options
('-k', '--api-key', type=click.STRING, required=True, envvar='BING_API_KEY', help='Bing Maps API key')
def bing(ctx, database, table, location, delay, latitude, longitude, geojson, spatialite, raw, api_key):
click.echo('Using Bing geocoder')
fill_context(ctx, database, table, location, delay, ... |
class ResourceDailyAvailabilitiesBetweenTestCase(TestCase):
def setUp(self):
self.resource = ResourceFactory()
self.start = date(2016, 1, 10)
self.end = date(2016, 1, 14)
self.booker = UserFactory()
def capacity_on(self, date, quantity):
return CapacityChange.objects.crea... |
class TraitFunction(TraitHandler):
def __init__(self, aFunc):
if (not isinstance(aFunc, CallableTypes)):
raise TraitError('Argument must be callable.')
self.aFunc = aFunc
self.fast_validate = (ValidateTrait.function, aFunc)
def validate(self, object, name, value):
try... |
def test_registry_key_parsing():
s = 'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows HKLM\\Software\\Microsoft\\Windows HKCC\\Software\\Microsoft\\Windows'
iocs = find_iocs(s)
assert (sorted(['HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows', 'HKLM\\Software\\Microsoft\\Windows', 'HKCC\\Software\\Microso... |
def npfromfile(fname: (((str | pathlib.Path) | io.BytesIO) | io.StringIO), dtype: npt.DTypeLike=np.float32, count: int=1, offset: int=0, mmap: bool=False) -> np.ndarray:
try:
if (mmap and (not isinstance(fname, (io.BytesIO, io.StringIO)))):
vals = np.memmap(fname, dtype=dtype, shape=(count,), mo... |
class LakeGetter(BaseAction):
def __init__(self, model_id, config_json):
BaseAction.__init__(self, model_id=model_id, config_json=config_json, credentials_json=None)
self.model_dest = self._model_path(model_id)
self.dvc_fetcher = DVCFetcher(self.model_dest)
def get(self):
self.dv... |
class TestsOklab(util.ColorAssertsPyTest):
COLORS = [('red', 'color(--oklab 0.62796 0.22486 0.12585)'), ('orange', 'color(--oklab 0.79269 0.05661 0.16138)'), ('yellow', 'color(--oklab 0.96798 -0.07137 0.19857)'), ('green', 'color(--oklab 0.51975 -0.1403 0.10768)'), ('blue', 'color(--oklab 0.45201 -0.03246 -0.31153)... |
class OptionSeriesDumbbellSonificationTracksMapping(Options):
def frequency(self) -> 'OptionSeriesDumbbellSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesDumbbellSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionSeriesDumbbellSonificationT... |
def start_command():
parser = argparse.ArgumentParser(description='EmbedChain DiscordBot command line interface')
parser.add_argument('--include-question', help='include question in query reply, otherwise it is hidden behind the slash command.', action='store_true')
global args
args = parser.parse_args(... |
def quartzPathToString(path):
elements = quartzPathElements(path)
output = []
for element in elements:
(elem_type, elem_points) = element
path_points = ' '.join([f'{p.x} {p.y}' for p in elem_points])
output.append(f'{elem_type} {path_points}')
return ' '.join(output) |
class UserFollowGroupDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
if view_kwargs.get('user_id'):
user = safe_query_kwargs(User, view_kwargs, 'user_id')
view_kwargs['id'] = user.id
def after_get_object(self, follower, view_kwargs):
if (not follower):
... |
def create_test_gitlab(monkeypatch, includes=None, excludes=None, in_file=None, root_group=None):
gl = gitlab_tree.GitlabTree(URL, TOKEN, 'ssh', 'name', includes=includes, excludes=excludes, in_file=in_file, root_group=root_group)
nodes = []
projects = Listable(append_node(nodes, PROJECT_NAME, PROJECT_URL))... |
class TestUtil(TestCase):
def test_get_roi_gen_sites(self):
makedb = (lambda sites: {'ATILE': {'bits': {'CLB_IO_CLK': {'baseaddr': '0x00400F00', 'frames': 28, 'height': 2, 'offset': 0, 'words': 2}}, 'grid_x': 10, 'grid_y': 10, 'segment': 'ASEGMENT', 'segment_type': 'bram0_l', 'sites': sites, 'prohibited_sit... |
def extractDemogorgon1912WixsiteCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_ty... |
class OptionSeriesSunburstSonification(Options):
def contextTracks(self) -> 'OptionSeriesSunburstSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesSunburstSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesSunburstSonificationDefaultinstrume... |
def find_store(store):
o = urlparse(store)
if ('' in o.netloc):
(auth, server) = o.netloc.split('')
(user, password) = auth.split(':')
if (o.scheme in [' ' 's3']):
return url_to_s3_store(store)
if os.path.exists(store):
if store.endswith('.zip'):
return zarr.Z... |
def extractRationalistempireTumblrCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_... |
.provider(fields.Dictionary({}))
class TracingCoroutineMiddleware(CoroutineMiddleware):
def before_run_coroutine(self):
before_call_trace.append('TracingCoroutineMiddleware')
def coroutine(self, coroutine):
create_call_trace.append('TracingCoroutineMiddleware')
async def wrapper():
... |
class boxesPyWrapper(inkex.GenerateExtension):
def add_arguments(self, pars):
args = sys.argv[1:]
for arg in args:
key = arg.split('=')[0]
if (key == '--id'):
continue
if (len(arg.split('=')) == 2):
value = arg.split('=')[1]
... |
class LoopIR_Compare():
def __init__(self):
pass
def match_stmts(self, stmts1, stmts2):
return all((self.match_s(s1, s2) for (s1, s2) in zip(stmts1, stmts2)))
def match_s(self, s1, s2):
if (type(s1) is not type(s2)):
return False
if isinstance(s1, (LoopIR.Assign, ... |
.parametrize('test_name', [1, {}, [], 2.3])
def test_raise_incorrect_name_type(test_name):
pol = Polygons()
data = pd.DataFrame({'X_UTME': [1.0, 2.0], 'Y_UTMN': [2.0, 1.0], 'Z_TVDSS': [3.0, 3.0], 'POLY_ID': [3, 3], 'T_DELTALEN': [2.0, 1.0]})
pol.dataframe = data
pol._pname = 'POLY_ID'
pol._tname = '... |
class OptionSeriesPackedbubbleStatesInactive(Options):
def animation(self) -> 'OptionSeriesPackedbubbleStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesPackedbubbleStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
class DivinePickHandler(THBEventHandler):
interested = ['action_after']
def handle(self, evt_type, act):
if ((evt_type == 'action_after') and isinstance(act, DropCardStage)):
dropper = act.target
g = self.game
if (not dropper.has_skill(Divine)):
return... |
def extractZumieditsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return False
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=fra... |
class UnsupportedNodeFixer():
_bmg: BMGraphBuilder
_typer: LatticeTyper
_unsupported_nodes = [bn.Chi2Node, bn.DivisionNode, bn.Exp2Node, bn.IndexNode, bn.ItemNode, bn.Log10Node, bn.Log1pNode, bn.Log2Node, bn.LogSumExpTorchNode, bn.LogAddExpNode, bn.SquareRootNode, bn.SwitchNode, bn.TensorNode, bn.UniformNod... |
class AutomationTool():
def __init__(self, task, resultdir, mock_config_file, log, config):
self.task = task
self.resultdir = resultdir
self.mock_config_file = mock_config_file
self.log = log
self.package_name = task['package_name']
self.chroot = task['chroot']
... |
def chop(A, tol=1e-10):
A.chop(tol)
B = PETSc.Mat().create(comm=A.comm)
B.setType(A.getType())
B.setSizes(A.getSizes())
B.setBlockSize(A.getBlockSize())
B.setUp()
B.setOption(PETSc.Mat.Option.IGNORE_ZERO_ENTRIES, True)
B.setPreallocationCSR(A.getValuesCSR())
B.assemble()
A.destro... |
_repr
class Exhibitor(db.Model, Timestamp):
class Status():
PENDING = 'pending'
ACCEPTED = 'accepted'
STATUSES = [PENDING, ACCEPTED]
__tablename__ = 'exhibitors'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
status = db.Column(db.Str... |
_touched_chat
def cmd_wipe(bot, update, chat=None):
subscriptions = list(Subscription.select().where((Subscription.tg_chat == chat)))
subs = 'You had no subscriptions.'
if subscriptions:
subs = ''.join(['For the record, you were subscribed to these users: ', ', '.join((s.tw_user.screen_name for s in... |
def parseArguments():
parser = ArgumentParser()
parser.add_argument('teamserver', help='The teamserver to post IOCs to.')
parser.add_argument('files', nargs='+', help='The files to post IOCs of.')
parser.add_argument('-j', metavar='java', dest='java', default='/Applications/Cobalt Strike 4/Cobalt Strike... |
class OptionPlotoptionsScatterSonificationTracksMappingPan(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):
self.... |
def test_local_provider_get_empty():
dc = Config.for_sandbox().data_config
with tempfile.TemporaryDirectory() as empty_source:
with tempfile.TemporaryDirectory() as dest_folder:
provider = FileAccessProvider(local_sandbox_dir='/tmp/unittest', raw_output_prefix=empty_source, data_config=dc)
... |
('evennia.server.portal.amp.amp.BinaryBoxProtocol.transport')
class TestAMPClientRecv(_TestAMP):
def test_msgportal2server(self, mocktransport):
self._connect_server(mocktransport)
self.amp_server.send_MsgPortal2Server(self.session, text={'foo': 'bar'})
wire_data = self._catch_wire_read(mock... |
def test_fmpz_mat():
M = flint.fmpz_mat
a = M(2, 3, [1, 2, 3, 4, 5, 6])
b = M(2, 3, [4, 5, 6, 7, 8, 9])
assert (a == a)
assert (a == M(a))
assert (a != b)
assert (a.nrows() == 2)
assert (a.ncols() == 3)
assert (a.entries() == [1, 2, 3, 4, 5, 6])
assert (a.table() == [[1, 2, 3], [... |
def create_default_groups():
from flaskbb.fixtures.groups import fixture
result = []
for (key, value) in fixture.items():
group = Group(name=key)
for (k, v) in value.items():
setattr(group, k, v)
group.save()
result.append(group)
return result |
def _build_wheels(pkg_name: str, pkg_version: str, base_url: str=None, base_url_func: Callable[([str, str, str], str)]=None, pkg_file_func: Callable[([str, str, str, str, OSType], str)]=None, supported_cuda_versions: List[str]=['11.7', '11.8']) -> Optional[str]:
(os_type, _) = get_cpu_avx_support()
cuda_version... |
class TestProvideAppropriateLanguage():
PROVIDER = 'test_provider'
FEATURE = 'test_feature'
SUBFEATURE = 'test_subfeature'
def test_valid_input(self, mocker: MockerFixture):
return_mock = ['en-US', 'fr', 'es']
mocker.patch('edenai_apis.utils.languages.load_language_constraints', return_v... |
class InfosInvoiceParserDataClass(BaseModel):
customer_information: CustomerInformationInvoice = CustomerInformationInvoice.default()
merchant_information: MerchantInformationInvoice = MerchantInformationInvoice.default()
invoice_number: Optional[StrictStr] = None
invoice_total: Optional[float] = None
... |
class InheritedModelSerializationTests(TestCase):
def test_multitable_inherited_model_fields_as_expected(self):
child = ChildModel(name1='parent name', name2='child name')
serializer = DerivedModelSerializer(child)
self.assertEqual(set(serializer.data), {'name1', 'name2', 'id', 'childassocia... |
def test_special_text_special_chunk_merge():
chunks = InputChunks([SpecialPieceChunk('<s>', after=' '), TextChunk('Hello world!'), SpecialPieceChunk('</s>', before=' ')])
chunks_copy = deepcopy(chunks)
chunks.merge_text_chunks()
assert (chunks == chunks_copy)
assert (chunks.merge_text_chunks() == [M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.