code stringlengths 281 23.7M |
|---|
class OptionPlotoptionsDependencywheelSonificationContexttracksMappingRate(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... |
def _delete(id_):
if (id_ not in CONFIG.networks):
raise ValueError(f"Network '{color('bright magenta')}{id_}{color}' does not exist")
with _get_data_folder().joinpath('network-config.yaml').open() as fp:
networks = yaml.safe_load(fp)
if ('cmd' in CONFIG.networks[id_]):
networks['dev... |
(IWizard)
class Wizard(MWizard, Dialog):
pages = Property(List(IWizardPage))
controller = Instance(IWizardController)
show_cancel = Bool(True)
title = Str('Wizard')
def next(self):
pass
def previous(self):
pass
def _create_contents(self, parent):
pass
def _create_... |
(urls.POLICY_POST_WEBHOOK_DETAIL, status_code=HTTP_200_OK, response_model=schemas.PolicyWebhookResponse, dependencies=[Security(verify_oauth_client, scopes=[scopes.WEBHOOK_READ])])
def get_policy_post_execution_webhook(*, db: Session=Depends(deps.get_db), policy_key: FidesKey, post_webhook_key: FidesKey) -> PolicyPostW... |
def profile_coordinates(point1, point2, size, extra_coords=None):
if (size <= 0):
raise ValueError("Invalid profile size '{}'. Must be > 0.".format(size))
diffs = [(i - j) for (i, j) in zip(point2, point1)]
separation = np.hypot(*diffs)
distances = np.linspace(0, separation, size)
angle = np... |
class RevokedFilter(BooleanListFilter):
title = _('Revoked')
parameter_name = 'revoked'
def queryset(self, request, queryset):
if (self.value() == 'yes'):
return queryset.filter(revoked__isnull=False)
if (self.value() == 'no'):
return queryset.filter(revoked__isnull=T... |
class OptionPlotoptionsOrganizationSonificationContexttracksMappingHighpassFrequency(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,... |
class TestTransactionSet(unittest.TestCase):
_configuration: Configuration
def setUpClass(cls) -> None:
TestTransactionSet._configuration = Configuration('./config/test_data.ini', US())
def setUp(self) -> None:
self.maxDiff = None
def test_good_transaction_set(self) -> None:
tran... |
class OptionPlotoptionsLineOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(text... |
class OptionSonificationGlobalcontexttracksMappingTremoloSpeed(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 OptionPlotoptionsPieSonificationContexttracksMappingLowpassFrequency(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... |
('config, passthrough, err_msg', [param(OmegaConf.create({'_target_': AClass}), {}, re.escape(('Expected a callable target, got' + " '{'a': '???', 'b': '???', 'c': '???', 'd': 'default_value'}' of type 'DictConfig'")), id='instantiate-from-dataclass-in-dict-fails'), param(OmegaConf.create({'foo': {'_target_': AClass}})... |
class TestGetaliases(tests.LimitedTestCase):
def _make_mock_resolver(self):
base_resolver = _make_mock_base_resolver()
resolver = base_resolver()
resolver.aliases = ['cname.example.com']
return resolver
def setUp(self):
self._old_resolver = greendns.resolver
green... |
class TestEventOrder(unittest.TestCase):
def test_lifo_order(self):
foo = Foo(cause='ORIGINAL')
bar = Bar(foo=foo, test=self)
baz = Baz(bar=bar, test=self)
self.events_delivered = []
foo.cause = 'CHANGE'
lifo = ['Bar._caused_changed', 'Baz._effect_changed', 'Baz._caus... |
def cmd_queue_list(jobs: Jobs, *, queueid: Optional[str]=None) -> None:
for _queue in jobs.queues:
queue = _queue.snapshot
if (queueid and (queueid != queue.id)):
continue
print(f'Queue ({queue.id})')
if queue.paused:
logger.warning('job queue is paused')
... |
def extractWirkowritingsBlogspotCom(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... |
.django_db
def test_transactions_elasticsearch_query_only_covid_iija():
baker.make('references.DisasterEmergencyFundCode', code='A', public_law='PUBLIC LAW FOR CODE A', title='TITLE FOR CODE A', group_name=None, earliest_public_law_enactment_date=None)
baker.make('references.DisasterEmergencyFundCode', code='B'... |
class CoreGenerator():
def __init__(self, resource_path='./resources/', gpus=0):
self.gpus = gpus
core_generator = load_model((resource_path + 'core_generator.h5'), custom_objects={'Conv2D_r': Conv2D_r, 'InstanceNormalization': InstanceNormalization, 'tf': tf, 'ConvSN2D': ConvSN2D, 'DenseSN': DenseS... |
_with_error(ValueError)
def parse_function_annotations(f: Callable[(..., Any)], keyword_only_in_message: bool=False, default_keyword_in_message: bool=False, deconstruct_dataclass_return_type: bool=True, single_return_param_name: str='sample', error: Callable[([str], None)]=(lambda x: None)) -> Tuple[(Optional[Dict[(str... |
def main():
global FLAG_FILENAME
parser = argparse.ArgumentParser(description='Generate encrypted flag file')
parser.add_argument('flag_file', help='Unencrypted flag file to encrypt', type=argparse.FileType('rb'))
parser.add_argument('--create-date', '-d', dest='creation_date', type=int)
args = pars... |
def test_save_as_sets_the_version_extension_to_ma(create_test_data, create_maya_env):
data = create_test_data
maya_env = create_maya_env
version1 = Version(task=data['task6'])
version1.extension = '.ma'
version1.update_paths()
version1.extension = ''
maya_env.save_as(version1)
assert (ve... |
class RelationshipWafRules(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_import()... |
class OptionSeriesTimelineSonificationDefaultinstrumentoptionsMappingHighpassResonance(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(sel... |
def make_ipa_multiproof(Cs, fs, indices, ys, display_times=True):
r = (ipa_utils.hash_to_field(((Cs + indices) + ys)) % MODULUS)
log_time_if_eligible(' Hashed to r', 30, display_times)
g = [0 for i in range(WIDTH)]
power_of_r = 1
for (f, index) in zip(fs, indices):
quotient = primefield.co... |
class Iproute2Builder(BuilderBase):
def __init__(self, build_opts, ctx, manifest, src_dir, build_dir, inst_dir) -> None:
super(Iproute2Builder, self).__init__(build_opts, ctx, manifest, src_dir, build_dir, inst_dir)
def _patch(self) -> None:
with open((self.build_dir + '/tc/tc_core.c'), 'r') as ... |
class TestPartitionOptions():
test = CISAudit()
test_id = '1.1'
test_level = 1
option = 'noexec'
(CISAudit, '_shellexec', mock_option_set)
def test_partition_option_is_set(self):
state = self.test.audit_removable_partition_option_is_set(option=self.option)
assert (state == 0)
... |
class RatingWidget(Gtk.EventBox):
__gproperties__ = {'rating': (GObject.TYPE_INT, 'rating', 'The selected rating', 0, 65535, 0, GObject.ParamFlags.READWRITE)}
__gsignals__ = {'rating-changed': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_INT,))}
def __init__(self, rating=0, player=None):
Gtk.E... |
class TapReadProcessor(ProcessorBase.ProcessorBase):
log_name = 'Main.Processor.TapRead'
def wants_url(lowerspliturl, mimetype):
if ('text/html' not in mimetype):
return False
return lowerspliturl.netloc.endswith('tapread.com')
def preprocess_content(self, url, lowerspliturl, mim... |
_registry.register_env(name='SimpleRLEnv')
class SimpleRLEnv(habitat.RLEnv):
def __init__(self, config: Config, dataset: Optional[Dataset]=None):
super().__init__(config.TASK_CONFIG, dataset)
self._core_env_config = config
def get_reward_range(self):
return ((- np.inf), np.inf)
def g... |
(_gemm_st_acc_i8)
def st_acc_i8(n: size, m: size, scale: f32, act: bool, src: ([i32][(n, 16)] GEMM_ACCUM), dst: ([i8][(n, m)] DRAM)):
assert (n <= 16)
assert (m <= 16)
assert (stride(dst, 1) == 1)
assert (stride(src, 0) == 16)
assert (stride(src, 1) == 1)
for i in seq(0, n):
for j in s... |
class NXTSetAsyncConfig(NiciraHeader):
def __init__(self, datapath, packet_in_mask, port_status_mask, flow_removed_mask):
super(NXTSetAsyncConfig, self).__init__(datapath, ofproto.NXT_SET_ASYNC_CONFIG)
self.packet_in_mask = packet_in_mask
self.port_status_mask = port_status_mask
self... |
class TableauCardWidget(Static):
can_focus = True
def __init__(self, card: Card, is_covered=False, **kwargs) -> None:
super().__init__(**kwargs)
self.card = card
self.is_covered = is_covered
self.last_time_clicked = None
def compose(self) -> ComposeResult:
(yield Stat... |
class AbstractModeMonitor(PlanarMonitor, FreqMonitor):
mode_spec: ModeSpec = pydantic.Field(..., title='Mode Specification', description='Parameters to feed to mode solver which determine modes measured by monitor.')
def plot(self, x: float=None, y: float=None, z: float=None, ax: Ax=None, **patch_kwargs) -> Ax:... |
class TestCLIRestore(CuratorTestCase):
def test_restore(self):
indices = []
for i in range(1, 4):
self.add_docs(f'my_index{i}')
indices.append(f'my_index{i}')
snap_name = 'snapshot1'
self.create_snapshot(snap_name, ','.join(indices))
snapshot = get_sna... |
def get_gradle_subdir(build_dir, paths):
first_gradle_dir = None
for path in paths:
if (not first_gradle_dir):
first_gradle_dir = path.parent.relative_to(build_dir)
if (path.exists() and SETTINGS_GRADLE_REGEX.match(str(path.name))):
for m in GRADLE_SUBPROJECT_REGEX.findit... |
('info')
_context
def info(ctx: click.Context):
import flytekit
remote: FlyteRemote = get_and_save_remote_with_click_context(ctx, project='flytesnacks', domain='development')
c = Content.format(version=flytekit.__version__, endpoint=remote.client.url)
rich.print(Panel(c, title='Flytekit CLI Info', borde... |
()
def campaign_machine():
from statemachine import State
from statemachine import StateMachine
class CampaignMachine(StateMachine):
draft = State(initial=True)
producing = State('Being produced')
closed = State(final=True)
add_job = (draft.to(draft) | producing.to(producing)... |
def extractSleepysmutCom(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) in tagm... |
class TestCallReqFrame(TestCase):
def test_read_write(self):
frame: Frame = Frame.read_frame(IOWrapper(BytesIO(SAMPLE_CALLREQ)))
self.assertEqual(3, frame.TYPE)
frame: CallReqFrame = frame
self.assertEqual(1, frame.id)
self.assertEqual(0, frame.flags)
self.assertEqual... |
class TestACEScctSerialize(util.ColorAssertsPyTest):
COLORS = [('color(--acescct 0.1 0.3 0.75 / 0.5)', {}, 'color(--acescct 0.1 0.3 0.75 / 0.5)'), ('color(--acescct 0.1 0.3 0.75)', {'alpha': True}, 'color(--acescct 0.1 0.3 0.75 / 1)'), ('color(--acescct 0.1 0.3 0.75 / 0.5)', {'alpha': False}, 'color(--acescct 0.1 0... |
_oriented
class sph_solver():
def __init__(self, particle_list, wall_mark, grid, bound, alpha=0.5, dx=0.2, max_time=10000, max_steps=1000, gui=None):
self.max_time = max_time
self.max_steps = max_steps
self.gui = gui
self.g = (- 9.8)
self.alpha = alpha
self.rho_0 = 10... |
def safe_name_torrent(string):
string = string.lower()
string = re.sub(u'^\\[.*?\\]', u'', string)
string = re.sub(u'- ([0-9][0-9][0-9][0-9]) ', u' \\g<1>', (string + u' '))
string = re.sub(u'- ([0-9]+) ', u'- EP\\g<1>', (string + u' '))
if ('season' not in string.lower()):
string = string.l... |
def funcparser_callable_pronoun(*args, caller=None, receiver=None, capitalize=False, **kwargs):
if (not args):
return ''
(pronoun, *options) = args
if (len(options) == 1):
options = options[0]
default_pronoun_type = 'subject pronoun'
default_gender = 'neutral'
default_viewpoint =... |
def test_broken_register_and_run_with_args(runner):
result = runner.invoke(broken_cli)
assert (result.exit_code == 0)
for ep in iter_entry_points('_test_click_plugins.broken_plugins'):
cmd_result = runner.invoke(broken_cli, [ep.name, '-a', 'b'])
assert (cmd_result.exit_code != 0)
ass... |
class PiecewiseMechanism(LDPBase):
def __init__(self, epsilon, domain):
self._domain = domain
self._epsilon = epsilon
self._pm_encoder = PMBase(epsilon=epsilon)
def _transform(self, value):
value = self._check_value(value)
(a, b) = self._domain
return ((((2 * valu... |
def _assert_expected_output(generated: str, expected: str, expected_file: Path) -> None:
lines = [line for line in unified_diff(expected.splitlines(), generated.splitlines(), fromfile=str(expected_file), tofile='Generated')]
diff = '\n'.join(lines)
if (generated != expected):
print(diff)
ass... |
.django_db
def test_diff_agencies_using_monthly_and_quarterly():
baker.make('submissions.DABSSubmissionWindowSchedule', id=11, submission_fiscal_year=2020, submission_fiscal_month=9, is_quarter=False, submission_due_date='2020-07-30', submission_reveal_date='2020-07-31')
baker.make('submissions.DABSSubmissionWi... |
class Actions():
def get_toggle_actions(self):
return [('ToolsExplorerAction', self.toggle_explorer, '<Ctrl>e'), ('ViewFullScreenAction', self.toggle_full_screen, 'F11')]
def get_main_actions(self):
return [('FileOpenAction', self.open, '<Ctrl>o'), ('FileSaveAction', self.save, '<Ctrl>s'), ('Fil... |
_tuple
def get_resolvable_backends_for_uri(uri: URI) -> Generator[(Type[BaseURIBackend], None, None)]:
default_ipfs = get_ipfs_backend_class()
if ((default_ipfs in ALL_URI_BACKENDS) and default_ipfs().can_resolve_uri(uri)):
(yield default_ipfs)
else:
for backend_class in ALL_URI_BACKENDS:
... |
def _parseKinetoUnitrace(in_trace: List, target_rank: int) -> List:
newCommsTrace = []
commsCnt = 0
for entry in in_trace:
marker = 'unknown'
pass
if (('name' in entry) and (entry['name'] == 'record_param_comms') and (entry['args']['rank'] == target_rank)):
newComm = comm... |
class StringsTable(list):
def __init__(self, io):
super(StringsTable, self).__init__()
string_table_start = io.tell()
number_of_strings = read_u32(io)
strings_offsets_array = [read_u32(io) for _ in range(number_of_strings)]
strings = ([''] * number_of_strings)
for (i,... |
('land')
('--force', is_flag=True, help='force land even if the PR is closed')
('pull_request', metavar='PR')
def land(force: bool, pull_request: str) -> None:
with cli_context() as (shell, config, github):
ghstack.land.main(pull_request=pull_request, github=github, sh=shell, github_url=config.github_url, r... |
class DbChatOutputParser(BaseOutputParser):
def __init__(self, is_stream_out: bool, **kwargs):
super().__init__(is_stream_out=is_stream_out, **kwargs)
def is_sql_statement(self, statement):
parsed = sqlparse.parse(statement)
if (not parsed):
return False
for stmt in p... |
class PublicKey(BaseKey, LazyBackend):
def __init__(self, public_key_bytes: bytes, backend: 'Union[BaseECCBackend, Type[BaseECCBackend], str, None]'=None) -> None:
validate_uncompressed_public_key_bytes(public_key_bytes)
self._raw_key = public_key_bytes
super().__init__(backend=backend)
... |
.ledger
('aea_ledger_fetchai._cosmos.requests.get')
('aea_ledger_fetchai._cosmos.requests.post')
def test_successful_faucet_operation(mock_post, mock_get):
address = 'a normal cosmos address would be here'
mock_post.return_value = MockRequestsResponse({'uuid': 'a-uuid-v4-would-be-here'})
mock_get.return_val... |
('logs', cls=FandoghCommand)
('-i', '--image', 'image', prompt='Image name', help='The image name', default=(lambda : get_project_config().get('image.name')))
('--version', '-v', prompt='Image version', help='your image version')
('--with_timestamp', 'with_timestamp', is_flag=True, default=False, help='timestamp for ea... |
def osci_change_ranking_dtd_df():
return pd.DataFrame([{OSCIChangeRankingSchema.company: 'Company', OSCIChangeRankingSchema.total: 10, OSCIChangeRankingSchema.active: 5, OSCIChangeRankingSchema.position: 4, OSCIChangeRankingSchema.position_change: 2, OSCIChangeRankingSchema.total_change: 7, OSCIChangeRankingSchema.... |
class ReportBot(Bot):
def react_to(self, who, mid, msg):
if (b'abuse' in msg.lower()):
self._handler._write_out(self._client.report(who, mid))
if self._client.server.should_exit():
sys.exit(0)
return None
else:
return b'Cool story bro' |
(params=[1, 2, 3], ids=['Interval', 'Rectangle', 'Box'])
def mesh(request):
distribution = {'overlap_type': (DistributedMeshOverlapType.VERTEX, 1)}
if (request.param == 1):
return IntervalMesh(3, 5, distribution_parameters=distribution)
if (request.param == 2):
return RectangleMesh(10, 20, 2... |
class Ui_dlgG28_30_1(object):
def setupUi(self, dlgG28_30_1):
dlgG28_30_1.setObjectName('dlgG28_30_1')
dlgG28_30_1.setWindowModality(QtCore.Qt.ApplicationModal)
dlgG28_30_1.resize(403, 304)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(':/cn5X/images/XYZAB.svg'), QtGui.QI... |
class OptionSeriesGaugeSonificationContexttracksMappingVolume(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... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'id'
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': {... |
(scope='function')
def custom_data_category(db: Session) -> Generator:
category = DataCategoryDbModel.create(db=db, data={'name': 'Example Custom Data Category', 'description': 'A custom data category for testing', 'fides_key': 'test_custom_data_category'})
(yield category)
category.delete(db) |
class TestMsgParser(unittest.TestCase):
def _test_msg_parser(self, xid, msg_len):
version = ofproto.OFP_VERSION
msg_type = ofproto.OFPT_HELLO
fmt = ofproto.OFP_HEADER_PACK_STR
buf = pack(fmt, version, msg_type, msg_len, xid)
c = msg_parser(_Datapath, version, msg_type, msg_le... |
(scope='module', autouse=True)
def run_simple_deploy(reset_test_project, tmp_project, request):
if (sys.platform == 'win32'):
re_platform = '.*\\\\unit_tests\\\\platforms\\\\(.*?)\\\\.*'
else:
re_platform = '.*/unit_tests/platforms/(.*?)/.*'
test_module_path = request.path
m = re.match(r... |
class PeriodicCaller():
def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exception_callback: Optional[Callable[([Callable, Exception], None)]]=None, loop: Optional[AbstractEventLoop]=None) -> None:
self._loop = (loop or asyncio.get_event_loop())
self.... |
class TestGc():
def test_sets_options_for_pre_java_9(self):
gc = telemetry.Gc(telemetry_params={}, log_root='/var/log', java_major_version=random.randint(0, 8))
assert (gc.java_opts('/var/log/defaults-node-0.gc.log') == ['-Xloggc:/var/log/defaults-node-0.gc.log', '-XX:+PrintGCDetails', '-XX:+PrintGC... |
class CatalogDiv(Catalog.CatalogGroup):
def basic(self) -> CssStylesDrop.CssDropFile:
return self._set_class(CssStylesDrop.CssDropFile)
def bubble(self) -> CssStylesDiv.CssDivBubble:
return self._set_class(CssStylesDiv.CssDivBubble)
def bubble_comment(self) -> CssStylesDiv.CssDivCommBubble:
... |
def main():
parser = make_arg_parser()
parsed_args = get_args(parser)
try:
validate_all_args(parsed_args)
json_data = get_json_data(os.path.abspath(parsed_args[JSON_ARG]))
doc = make_docxtemplate(os.path.abspath(parsed_args[TEMPLATE_ARG]))
doc = render_docx(doc, json_data)
... |
((LOOK_DEV_TYPES + ['model', 'rig', 'layout']))
def check_extra_cameras(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
if (len(pm.ls(type='camera')) > 4):
progress_controller.complete()
raise PublishError('There should be no ex... |
def extractCircusTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('German Translation' in item['tags']):
return None
if ('Turkish Translation' in item['tags']):... |
class OptionSeriesSplineOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(text, j... |
def set_chat_permissions(token, chat_id, permissions, use_independent_chat_permissions=None):
method_url = 'setChatPermissions'
payload = {'chat_id': chat_id, 'permissions': permissions.to_json()}
if (use_independent_chat_permissions is not None):
payload['use_independent_chat_permissions'] = use_in... |
class FrameBase():
def __init__(self, *args, **kwargs):
self.low_pc = kwargs['low_pc']
self.high_pc = kwargs['high_pc']
self.base_register = kwargs['base_register']
self.offset = kwargs['offset']
def __repr__(self):
return '{} {} {} {}'.format(self.base_register, self.off... |
class Wireguard(IntervalModule):
color_up = '#00ff00'
color_down = '#FF0000'
status_up = ''
status_down = ''
format = '{vpn_name} {status}'
status_command = 'systemctl is-active wg-{vpn_name}'
vpn_up_command = 'sudo /bin/systemctl start wg-{vpn_name}.service'
vpn_down_command = 'sudo /bi... |
class LoggingFtpAdditional(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 {'address': (str,), 'hostnam... |
def _worker(options, proc_num, auth=None):
cid = ('%s-%d' % (options.clientid, proc_num))
if options.bridge:
ts = beem.bridge.BridgingSender(options.host, options.port, cid, auth)
if auth:
cid = auth.split(':')[0]
else:
ts = beem.load.TrackingSender(options.host, options.... |
def extractMeatbuntranslationBlogspotCom(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, ... |
class OptionPlotoptionsWaterfallSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: ... |
class TestSalesInvoice(FrappeTestCase):
def test_set_healthcare_services_should_preserve_state(self):
invoice = frappe.copy_doc(test_records[0])
count = len(invoice.items)
item = invoice.items[0]
checked_values = [{'dt': 'Item', 'dn': item.item_name, 'item': item.item_code, 'qty': Fa... |
def get_event_data(abi_codec: ABICodec, event_abi: ABIEvent, log_entry: LogReceipt) -> EventData:
if event_abi['anonymous']:
log_topics = log_entry['topics']
elif (not log_entry['topics']):
raise MismatchedABI('Expected non-anonymous event to have 1 or more topics')
elif (event_abi_to_log_to... |
def keras_subclass(name: str, X: XType, Y: YType, input_shape: Tuple[(int, ...)], compile_args: Optional[Dict[(str, Any)]]=None) -> Callable[([InFunc], InFunc)]:
compile_defaults = {'optimizer': 'adam', 'loss': 'mse'}
if (compile_args is None):
compile_args = compile_defaults
else:
compile_a... |
class TestNamedTupleV3(TestCase):
def test_fixed_size(self):
class Book(NamedTuple, size=TupleSize.fixed):
title = 0
author = 1
genre = 2
b = Book('Teckla', 'Steven Brust', 'fantasy')
self.assertTrue(('Teckla' in b))
self.assertTrue(('Steven Brust'... |
class OptionSeriesErrorbarSonificationPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._con... |
class OptionSeriesVennDragdropGuideboxDefault(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(self, tex... |
def shields_icons(conf: AppConfig, deps: list, full_name: str):
if (conf.git.source == GitService.LOCAL.host):
repo_host = GitService.LOCAL.host
else:
repo_host = GitService.extract_name_from_host(conf.git.source)
resource_path = utils.get_resource_path(__package__, conf.files.shields_icons)... |
def test():
from instakit.utils.static import asset
from instakit.utils.mode import Mode
image_paths = list(map((lambda image_file: asset.path('img', image_file)), asset.listfiles('img')))
image_inputs = list(map((lambda image_path: Mode.RGB.open(image_path)), image_paths))
noises = [GaussianNoise, ... |
def rivet():
selection_list = pm.filterExpand(sm=32)
if ((selection_list is not None) and (len(selection_list) > 0)):
size = len(selection_list)
if (size != 2):
raise pm.MayaObjectError('No two edges selected')
edge1 = pm.PyNode(selection_list[0])
edge2 = pm.PyNode(se... |
class StreamLogger(AbstractLogger):
stream = sys.stderr
def init(self, *priv):
try:
handler = logging.StreamHandler(self.stream)
except AttributeError as exc:
raise SnmpsimError(('Stream logger failure: %s' % exc))
handler.setFormatter(logging.Formatter('%(message... |
.integration_test
def test_field_param_update(tmpdir):
with tmpdir.as_cwd():
config = dedent('\n NUM_REALIZATIONS 5\n OBS_CONFIG observations\n\n FIELD MY_PARAM PARAMETER my_param.grdecl INIT_FILES:my_param.grdecl FORWARD_INIT:True\n GRID MY_EGRID.EGRID\n\n ... |
def parse_cjson(fn):
with open(fn) as handle:
cml = json.load(handle)
atms = cml['atoms']
coords = (np.array(atms['coords']['3d'], dtype=float) * ANG2BOHR)
atom_nums = atms['elements']['number']
atoms = tuple([INV_ATOMIC_NUMBERS[num].capitalize() for num in atom_nums])
return (atoms, coo... |
.skipif((not torch.cuda.is_available()), reason='requires GPU access to train the model')
def test_normal_normal_guide_step_gpu():
device = torch.device('cuda:0')
model = NormalNormal(device=device)
def phi():
return torch.zeros(2).to(device)
_variable
def q_mu():
params = phi()
... |
class OptionPlotoptionsColumnSonificationDefaultspeechoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsColumnSonificationDefaultspeechoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsColumnSonificationDefaultspeechoptionsActivewhen)
def language(self):
r... |
def _run_command(cmd_args: list[str]) -> str:
logger.debug("Executing '%s'", ' '.join(cmd_args))
try:
creationflags = getattr(subprocess, 'CREATE_NO_WINDOW', None)
kwargs = ({'creationflags': creationflags} if creationflags else {})
proc = subprocess.run(cmd_args, capture_output=True, te... |
class Solution():
def deleteDuplicates(self, head: ListNode) -> ListNode:
nh = ListNode(None)
(np, nc) = (None, nh)
curr = head
should_retreat = False
while (curr is not None):
if (curr.val == nc.val):
should_retreat = True
else:
... |
(params=['scalar', 'vector', pytest.param('tensor', marks=pytest.mark.skip(reason='Prolongation fails for tensors'))])
def shapify(request):
if (request.param == 'scalar'):
return (lambda x: x)
elif (request.param == 'vector'):
return VectorElement
elif (request.param == 'tensor'):
r... |
def setup_switch_btn(editor: Editor):
if (hasattr(editor, 'parentWindow') and isinstance(editor.parentWindow, AddCards)):
win = aqt.dialogs._dialogs['AddCards'][1]
elif (hasattr(editor, 'parentWindow') and isinstance(editor.parentWindow, EditCurrent)):
if (not conf_or_def('useInEdit', False)):
... |
class TestIssue3090(BaseEvenniaTest):
def test_long_aliases(self):
cmdset_g = _CmdSetG()
result = cmdparser.cmdparser('smile at', cmdset_g, None)[0]
self.assertEqual(result[0], 'smile at')
self.assertEqual(result[1], '')
self.assertEqual(result[2].__class__, _CmdG)
se... |
_bp.route((app.config['FLICKET'] + 'category_edit/<int:category_id>/'), methods=['GET', 'POST'])
_required
def category_edit(category_id=False):
if category_id:
form = CategoryForm()
category = FlicketCategory.query.filter_by(id=category_id).first()
form.department_id.data = category.departm... |
def main():
perfolder = {}
for line2 in sys.stdin.readlines():
line = line2.strip()
if ('extract/' in line):
folders = line.split('/')
if (len(folders) < 3):
print('WARN', line)
pass
else:
folder = folders[2]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.