code stringlengths 281 23.7M |
|---|
_register_parser
_set_msg_type(ofproto.OFPT_QUEUE_GET_CONFIG_REPLY)
class OFPQueueGetConfigReply(MsgBase):
def __init__(self, datapath, queues=None, port=None):
super(OFPQueueGetConfigReply, self).__init__(datapath)
self.queues = queues
self.port = port
def parser(cls, datapath, version,... |
def distance(point_p, point_q, coordinate_system='cartesian', ellipsoid=None):
check_coordinate_system(coordinate_system)
if (coordinate_system == 'cartesian'):
dist = distance_cartesian(point_p, point_q)
if (coordinate_system == 'spherical'):
dist = distance_spherical(point_p, point_q)
... |
def test_mariadb_connector_build_uri(connection_config_mariadb, db: Session):
connector = MariaDBConnector(configuration=connection_config_mariadb)
s = connection_config_mariadb.secrets
port = ((s['port'] and f":{s['port']}") or '')
uri = f"mariadb+pymysql://{s['username']}:{s['password']}{s['host']}{po... |
((MAGICK_VERSION_NUMBER < 1800), reason='Complex requires ImageMagick-7.0.8.')
def test_complex():
with Image(width=1, height=1, pseudo='xc:gray25') as a:
with Image(width=1, height=1, pseudo='xc:gray50') as b:
a.image_add(b)
a.iterator_reset()
with a.complex('add') as im... |
class TestTachoMotorMaxSpeedValue(ptc.ParameterizedTestCase):
def test_max_speed_value(self):
self.assertEqual(self._param['motor'].max_speed, motor_info[self._param['motor'].driver_name]['max_speed'])
def test_max_speed_value_is_read_only(self):
with self.assertRaises(AttributeError):
... |
_api_tests
def test_get_favorites():
result = get_favorites(screen_name='twitter', count=5, tweet_mode='extended')
assert (type(result) == pd.core.frame.DataFrame)
assert (len(result) <= 5)
assert ('tweet_full_text' in result)
assert all([(embd_uid == uid) for (embd_uid, uid) in zip([x['id'] for x i... |
class SpiderHandler(BaseHandler):
_separate(APP_DEBUG)
.authenticated
def get(self, slug=None):
print()
app_log.info('SpiderHandler.get... ')
app_log.info('SpiderHandler.get / slug : %s', slug)
slug_ = self.request.arguments
app_log.info('SpiderHandler.get / slug_ : \... |
def get_current_alertmanager_version():
version = UNKNOWN_VERSION
try:
process_result = subprocess.run([(ALERTMANAGER_INSTALLED_PATH + 'alertmanager'), '--version'], capture_output=True, text=True)
process_output = ((process_result.stdout + '\n') + process_result.stderr)
result = re.sear... |
_dependency(plt, 'matplotlib')
def plot_scatter_1(data, label=None, title=None, x_val=0, ax=None):
ax = check_ax(ax)
x_data = ((np.ones_like(data) * x_val) + np.random.normal(0, 0.025, data.shape))
ax.scatter(x_data, data, s=36, alpha=set_alpha(len(data)))
if label:
ax.set_ylabel(label, fontsize... |
.skip
def test_deployments_changed_source(tp_path, deployments, mainnet_uri):
address = '0xdAC17F958D2ee523aC13D831ec7'
path = tp_path.joinpath(f'build/deployments/mainnet/{address}.json')
with path.open() as fp:
build_json = json.load(fp)
build_json['bytecode'] += 'ff'
with path.open('w') a... |
def flag_project(session, project, reason, user_email, user_id):
flag = models.ProjectFlag(user=user_email, project=project, reason=reason)
session.add(flag)
try:
session.flush()
except exc.SQLAlchemyError as err:
_log.exception(err)
session.rollback()
raise exceptions.An... |
_os(*metadata.platforms)
def main():
if (Path(ISO).is_file() and Path(PS_SCRIPT).is_file()):
print(f'[+] - ISO File {ISO} will be mounted and executed via powershell')
command = f'powershell.exe -ExecutionPol Bypass -c import-module {PS_SCRIPT}; ExecFromISO -ISOFile {ISO} -procname {PROC};'
... |
def verticalMetricsKeptInSync(varfont):
current_os2_vmetrics = [getattr(varfont['OS/2'], attr) for attr in ('sTypoAscender', 'sTypoDescender', 'sTypoLineGap')]
metrics_are_synced = (current_os2_vmetrics == [getattr(varfont['hhea'], attr) for attr in ('ascender', 'descender', 'lineGap')])
(yield metrics_are_... |
def test_span_finder_component():
nlp = Language()
docs = [nlp('This is an example.'), nlp('This is the second example.')]
docs[0].spans[TRAINING_KEY] = [docs[0][3:4]]
docs[1].spans[TRAINING_KEY] = [docs[1][3:5]]
span_finder = nlp.add_pipe('experimental_span_finder', config={'training_key': TRAINING... |
class dnsHost(Module):
config = Config({Option('DOMAIN', 'Provide your target Domain', True): str('laet4x.com')})
def run(self):
domain = self.config.option('DOMAIN').value
print(("\n Analyzing '%s'..." % domain))
request = requests.get((' + domain))
res = request.text
pr... |
class LoginView(View):
def post(self, request):
res = {'code': 425, 'msg': '!', 'self': None}
form = LoginForm(request.data, request=request)
if (not form.is_valid()):
(res['self'], res['msg']) = clean_form(form)
return JsonResponse(res)
user = form.cleaned_da... |
class ShellCommand():
def __init__(self, *args, **kwargs) -> None:
self.verbose = kwargs.pop('verbose', False)
for arg in ('stdout', 'stderr'):
if (arg not in kwargs):
kwargs[arg] = subprocess.PIPE
self.cmdline = ' '.join([quote(x) for x in args])
if self.... |
class TransformerCausalLM(Generic[ConfigT], CausalLMModule[(ConfigT, KeyValueCache)]):
decoder: TransformerDecoder
output_embeddings: Module
def forward(self, piece_ids: Tensor, attention_mask: AttentionMask, cache: Optional[List[KeyValueCache]]=None, positions: Optional[Tensor]=None, store_cache: bool=Fals... |
class OptionSeriesTreemapStatesSelectMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._con... |
class OptionPlotoptionsBulletSonificationDefaultspeechoptionsMappingPlaydelay(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: ... |
def retrieve_airflow_info(dag_id: Optional[str], host: str, username: str, password: str) -> Generator:
airflow_api_config = Configuration(host=host, username=username, password=password)
with ApiClient(configuration=airflow_api_config) as api_client:
airflow_api_tree = AirflowApiTree(api_client)
... |
class OptionSeriesSolidgaugeEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._conf... |
class NodesListWidget(QTreeWidget):
def __init__(self, parent):
QTreeWidget.__init__(self)
self.parent = parent
self.setHeaderLabels([_('Connected node'), _('Height')])
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.create_menu)
... |
class normalize(Decorator):
def __init__(self, name, values=None, **kwargs):
assert ((name is None) or isinstance(name, str))
self.name = name
if isinstance(values, str):
assert (kwargs.get('type') is None), f"Cannot mix values={values} and type={kwargs.get('type')}"
... |
class OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingLowpassFrequency... |
class GreetingWorkflow():
_method
async def get_status(self, arg1: QueryArgType1, arg2: QueryArgType2) -> QueryRetType:
raise NotImplementedError
_method
async def push_status(self, arg1: SignalArgType1, arg2: SignalArgType2):
raise NotImplementedError
_method(task_queue=TASK_QUEUE)
... |
def test_interference_graph_of_group_first_graph_a():
interference_graph = construct_graph(1)
sub_graph = interference_graph.get_subgraph_of(InsertionOrderedSet([x_1, x_3]))
assert (InsertionOrderedSet(sub_graph.nodes) == InsertionOrderedSet([x_1]))
assert (set(sub_graph.edges) == set()) |
def construct_field(name_or_field, **params):
if isinstance(name_or_field, collections.abc.Mapping):
if params:
raise ValueError('construct_field() cannot accept parameters when passing in a dict.')
params = name_or_field.copy()
if ('type' not in params):
if ('propert... |
def test_setFromModule():
import os
from proteus import Context
with open('context_module.py', 'w') as f:
f.write('nnx=11; T=10.0; g=9.8\n')
sys.path.append(os.getcwd())
import context_module
os.remove('context_module.py')
Context.setFromModule(context_module)
check_eq(Context.co... |
def _preprocess(csource):
csource = _r_comment.sub(' ', csource)
macros = {}
for match in _r_define.finditer(csource):
(macroname, macrovalue) = match.groups()
macros[macroname] = macrovalue
csource = _r_define.sub('', csource)
csource = _r_partial_array.sub('[__dotdotdotarray__]', c... |
def test_revert_previous_kick(paragon_chain):
head = paragon_chain.get_canonical_head()
clique = get_clique(paragon_chain)
snapshot = validate_seal_and_get_snapshot(clique, head)
assert (len(snapshot.tallies) == 0)
alice_votes_bob = make_next_header(paragon_chain, head, ALICE_PK, coinbase=BOB, nonce... |
def extractAthanasiafrostWordpressCom(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_... |
class u5Ex(object):
def __init__(self):
pass
def uOfX(self, x):
return (((x[0] ** 2) + (x[1] ** 2)) + (x[2] ** 2))
def uOfXT(self, X, T):
return self.uOfX(X)
def duOfX(self, X):
du = (2.0 * numpy.reshape(X[0:3], (3,)))
return du
def duOfXT(self, X, T):
... |
def enable_disk_checkpointing(dirname=None, comm=COMM_WORLD, cleanup=True):
tape = get_working_tape()
if ('firedrake' not in tape._package_data):
tape._package_data['firedrake'] = DiskCheckpointer(dirname, comm, cleanup)
if (not disk_checkpointing()):
continue_disk_checkpointing() |
class TestRegistryPackage(unittest.TestCase):
def setUpClass(cls) -> None:
assert ('registry_data' in package_configs), f'Missing registry_data in {PACKAGE_FILE}'
cls.registry_config = package_configs['registry_data']
stack_version = Version.parse(cls.registry_config['conditions']['kibana.ve... |
(accept=('application/json', 'text/json'), renderer='json', error_handler=bodhi.server.services.errors.json_handler)
(accept='application/javascript', renderer='jsonp', error_handler=bodhi.server.services.errors.jsonp_handler)
(accept='text/html', renderer='override.html', error_handler=bodhi.server.services.errors.htm... |
def test_align_convert_align_mafft_fasta_to_nexus(o_dir, e_dir, request):
program = 'bin/align/phyluce_align_convert_one_align_to_another'
output = os.path.join(o_dir, 'mafft-fasta-to-nexus')
cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft'), '--output', outp... |
def evaluate(node, g, loop=False):
if (loop and isinstance(node, ast.Break)):
raise Break
if (loop and isinstance(node, ast.Continue)):
raise Continue
if isinstance(node, ast.Expr):
_eval = ast.Expression(node.value)
(yield eval(compile(_eval, '<string>', 'eval'), g))
eli... |
def combine_clusters(signature_clusters, options):
(deletion_signature_clusters, insertion_signature_clusters, inversion_signature_clusters, tandem_duplication_signature_clusters, insertion_from_signature_clusters, translocation_signature_clusters) = signature_clusters
inversion_candidates = []
for inv_clus... |
class FrameContinue(FrameWithArgs, CallFlags):
PREFIX = ''
def __init__(self):
FrameWithArgs.__init__(self)
CallFlags.__init__(self)
self.csumtype = 0
def read_payload(self, fp: IOWrapper, size: int):
offset = 0
self.flags = fp.read_byte((self.PREFIX + '.flags'))
... |
class FilterClass():
def __init__(self, app, program_version, db: FrontendDatabase, **_):
self._program_version = program_version
self._app = app
self.db = db
self._setup_filters()
def _filter_print_program_version(self, *_):
return f'{self._program_version}'
def _fil... |
class hashie(plugins.Plugin):
__author__ = 'junohea.'
__version__ = '1.0.1'
__license__ = 'GPL3'
__description__ = '\n Attempt to automatically convert pcaps to a crackable format.\n If successful, the files containing the hashes will be saved \n ... |
class OptionSeriesWindbarbSonificationTracksMappingHighpassFrequency(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 test_fmpq():
Q = flint.fmpq
assert (Q() == Q(0))
assert (Q(0) != Q(1))
assert (Q(0) == 0)
assert (0 == Q(0))
assert (Q(2) != 1)
assert (1 != Q(2))
assert (Q(1) != ())
assert (Q(1, 2) != 1)
assert (Q(2, 3) == Q(flint.fmpz(2), long(3)))
assert (Q((- 2), (- 4)) == Q(1, 2))
... |
class CrossAttention(fl.Attention):
def __init__(self, embedding_dim: int, cross_embedding_dim: (int | None)=None, num_heads: int=1, inner_dim: (int | None)=None, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None:
super().__init__(embedding_dim=embedding_dim, key_embedding_dim=cross_... |
class ArtistManager(GObject.Object):
instance = None
progress = GObject.property(type=float, default=0)
__gsignals__ = {'sort': (GObject.SIGNAL_RUN_LAST, None, (object,))}
def __init__(self, plugin, album_manager, shell):
super(ArtistManager, self).__init__()
self.db = plugin.shell.props... |
class SimpleApplication(HasStrictTraits):
gui = Instance(IGUI)
application_running = Event()
def __init__(self):
super().__init__()
self.gui = GUI()
def start(self):
self.gui.set_trait_later(self, 'application_running', True)
self.gui.start_event_loop()
def stop(self)... |
def extractTyralionsBlogspotCom(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) ... |
def _loop_once():
global patch, name, path, monitor
global p, device, rate, blocksize, nchans, format, info, stream, lock, control, trigger, devinfo, block, offset, autoscale
global BUFFER, t, last, vco_pitch, vco_sin, vco_tri, vco_saw, vco_sqr, lfo_depth, lfo_frequency, adsr_attack, adsr_decay, adsr_sustai... |
('foremast.elb.create_elb.boto3.session.Session')
('foremast.elb.create_elb.get_properties')
def test_elb_add_listener_policy(mock_get_properties, mock_boto3_session):
test_app = 'myapp'
test_port = 80
test_policy_list = ['policy_name']
json_data = {'job': [{'listeners': [{'externalPort': test_port, 'li... |
class FilesLoader(jinja2.BaseLoader):
def __init__(self, files):
self.files = files
def get_source(self, environment, template):
for template_file in self.files:
if (os.path.basename(template_file) == template):
with open(template_file) as f:
conte... |
class NXFlowStatsRequest(NXStatsRequest):
def __init__(self, datapath, flags, out_port, table_id, rule=None):
super(NXFlowStatsRequest, self).__init__(datapath, flags, ofproto.NXST_FLOW)
self.out_port = out_port
self.table_id = table_id
self.rule = rule
self.match_len = 0
... |
def extractJjkjuuutranslationsWordpressCom(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... |
def main():
args = parse_args(argv=(None if sys.argv[1:] else ['--help']))
if args.version:
print(VERSION)
sys.exit(0)
if (args.token is None):
print("Please specify a valid token with the -t flag or the 'GITLAB_TOKEN' environment variable")
sys.exit(1)
if (args.url is No... |
def test_substitute_loop_node_with_parent():
asgraph = AbstractSyntaxInterface()
code_node = asgraph._add_code_node([Assignment(var('a'), const(2))])
inner_loop = asgraph.add_endless_loop_with_body(code_node)
outer_loop = asgraph.add_endless_loop_with_body(inner_loop)
replacement_loop = asgraph.fact... |
def _split_addr(addr):
e = ValueError(('Invalid IP address and port pair: "%s"' % addr))
pair = addr.rsplit(':', 1)
if (len(pair) != 2):
raise e
(addr, port) = pair
if (addr.startswith('[') and addr.endswith(']')):
addr = addr.lstrip('[').rstrip(']')
if (not ip.valid_ipv6(add... |
def main(POST_ID=None) -> None:
global redditid, reddit_object
reddit_object = get_subreddit_threads(POST_ID)
redditid = id(reddit_object)
(length, number_of_comments) = save_text_to_mp3(reddit_object)
length = math.ceil(length)
get_screenshots_of_reddit_posts(reddit_object, number_of_comments)
... |
def wrap_data_response(data):
if (data is not None):
return Response(return_code=str(SUCCESS), error_msg=None, data=MessageToJson(data, preserving_proto_field_name=True))
else:
return Response(return_code=str(RESOURCE_DOES_NOT_EXIST), error_msg=ReturnCode.Name(RESOURCE_DOES_NOT_EXIST).lower(), d... |
def unpackb(packed, **kwargs):
if ('object_pairs_hook' not in kwargs):
object_hook = kwargs.get('object_hook')
for decoder in msgpack_decoders.get_all().values():
object_hook = functools.partial(decoder, chain=object_hook)
kwargs['object_hook'] = object_hook
return _unpackb(p... |
def extractWasabilinusWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("The Forerunner's Odyssey", "The Forerunner's Odyssey", 'oel')]
for (tagname, name, tl_typ... |
_routes.route('/<int:group_id>/contact-organizer', methods=['POST'])
_required
def contact_group_organizer(group_id):
group = Group.query.get_or_404(group_id)
organizer_role = Role.query.filter_by(name='organizer').first()
group_roles = UsersGroupsRoles.query.filter_by(group_id=group_id, role_id=organizer_r... |
class base():
elements = [const.FIRE, const.EARTH, const.AIR, const.WATER]
temperaments = [const.CHOLERIC, const.MELANCHOLIC, const.SANGUINE, const.PHLEGMATIC]
genders = [const.MASCULINE, const.FEMININE]
factions = [const.DIURNAL, const.NOCTURNAL]
sunseasons = [const.SPRING, const.SUMMER, const.AUTU... |
class OptionPlotoptionsCylinderSonificationTracksMappingNoteduration(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 TestLinearDisplayP3(util.ColorAssertsPyTest):
COLORS = [('red', 'color(--display-p3-linear 0.82246 0.03319 0.01708)'), ('orange', 'color(--display-p3-linear 0.88926 0.39697 0.04432)'), ('yellow', 'color(--display-p3-linear 1 1 0.08948)'), ('green', 'color(--display-p3-linear 0.03832 0.2087 0.01563)'), ('blue'... |
def to_datetime_list(datetimes):
if isinstance(datetimes, (datetime.datetime, np.datetime64)):
return to_datetime_list([datetimes])
if isinstance(datetimes, (list, tuple)):
if ((len(datetimes) == 3) and isinstance(datetimes[1], str) and (datetimes[1].lower() == 'to')):
return mars_li... |
class AlienInvasion():
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption('Alien Invasion')
self.stat... |
_routes.route('/token/refresh', methods=['POST'])
_refresh_token_required
def refresh_token():
current_user = get_jwt_identity()
expiry_time = timedelta(minutes=90)
new_token = create_access_token(identity=current_user, fresh=False, expires_delta=expiry_time)
return jsonify({'access_token': new_token}) |
class _ZebraInterfaceNbrAddress(_ZebraMessageBody):
_HEADER_FMT = '!I'
HEADER_SIZE = struct.calcsize(_HEADER_FMT)
def __init__(self, ifindex, family, prefix):
super(_ZebraInterfaceNbrAddress, self).__init__()
self.ifindex = ifindex
self.family = family
if isinstance(prefix, (... |
_handler(func=(lambda message: True))
def all_messages(message):
if (message.text == 'Done'):
markup = telebot.types.ReplyKeyboardRemove()
bot.send_message(message.from_user.id, 'Done with Keyboard', reply_markup=markup)
elif (message.text == 'Symbols'):
bot.send_message(message.from_use... |
(scope='function')
def mailchimp_override_connection_config(db: session, mailchimp_override_config, mailchimp_secrets) -> Generator:
fides_key = mailchimp_override_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.... |
def read_kaggle_dataset(dataset_name, data_types=None, delimiter=','):
dataset_files = kaggle.api.dataset_list_files(dataset_name)
try:
kaggle.api.dataset_download_files(dataset_name, USER_DATASETS, unzip=True)
except Exception as e:
print(e)
file_path = ((USER_DATASETS + '/') + dataset_... |
def add_hydrogens(ref_geom, ref_zmat, geom, inner=False):
G1 = geom_to_graph(ref_geom)
G2 = geom_to_graph(geom)
subgraph = find_subgraph(G1, G2)
(h_map, h_tot) = missing_hydrogens(G1, G2, subgraph)
print(h_map, h_tot)
coords3d = np.zeros(((len(geom.atoms) + h_tot), 3))
print(coords3d.shape)
... |
class OptionSeriesPyramidSonificationContexttracksMappingVolume(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 TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
test_suite = TestLoader().discover('./tests', pattern='*_test.py')
test_results = TextTestRunner(verbosity=2).run(test_suite) |
class InsertPhpConstructorPropertyCommand(sublime_plugin.TextCommand):
placeholder = 'PROPERTY'
def description(self):
return 'Insert a constructor argument.'
def is_enabled(self):
return ('php' in self.view.settings().get('syntax').lower())
def run(self, edit):
self.edit = edit
... |
def queue_privacy_request(privacy_request_id: str, from_webhook_id: Optional[str]=None, from_step: Optional[str]=None) -> str:
cache: FidesopsRedis = get_cache()
logger.info('queueing privacy request')
task = run_privacy_request.delay(privacy_request_id=privacy_request_id, from_webhook_id=from_webhook_id, f... |
def extractMahoutsuki(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (('Uncategorized' in item['tags']) and chp and (('Chapter' in item['title']) or ('prologue' in item['title']))):
... |
class QtPlugin(QtPluginBase):
device: str
def create_handler(self, window: HandlerWindow) -> QtHandlerBase:
return QtHandler(window, self.device)
def show_settings_dialog(self, window: ElectrumWindow, keystore: Hardware_KeyStore) -> None:
device_id = self.choose_device(window, keystore)
... |
def fortios_firewall(data, fos, check_mode):
fos.do_member_operation('firewall', 'DoS-policy6')
if data['firewall_dos_policy6']:
resp = firewall_dos_policy6(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_dos_policy6'))
if check_mode:
r... |
class SlurmInfoWatcher(core.InfoWatcher):
def _make_command(self) -> tp.Optional[tp.List[str]]:
to_check = {x.split('_')[0] for x in (self._registered - self._finished)}
if (not to_check):
return None
command = ['sacct', '-o', 'JobID,State,NodeList', '--parsable2']
for ji... |
def unknown_actions():
iam_actions_from_api_calls = set()
for api_call in all_aws_api_methods():
x = api_call.split(':')
r = Record((x[0] + '.amazonaws.com'), x[1])
statement = r.to_statement()
if (statement is not None):
iam_actions_from_api_calls.add(statement.Actio... |
def test_get_entities_in_file():
e = get_entities_in_file(WORKFLOW_FILE, False)
assert (e.workflows == ['my_wf', 'wf_with_none'])
assert (e.tasks == ['get_subset_df', 'print_all', 'show_sd', 'task_with_optional', 'test_union1', 'test_union2'])
assert (e.all() == ['my_wf', 'wf_with_none', 'get_subset_df'... |
def _vm_shutdown(vm):
cmd = ('vmadm stop -F ' + vm.uuid)
lock = ('vmadm stop ' + vm.uuid)
meta = {'replace_text': ((vm.uuid, vm.hostname),), 'msg': LOG_STOP_FORCE, 'vm_uuid': vm.uuid}
(tid, err) = execute(ERIGONES_TASK_USER, None, cmd, meta=meta, lock=lock, callback=False, expires=None, queue=vm.node.fa... |
class OptionAccessibilityKeyboardnavigationSeriesnavigation(Options):
def mode(self):
return self._config_get('normal')
def mode(self, text: str):
self._config(text, js_type=False)
def pointNavigationEnabledThreshold(self):
return self._config_get(False)
def pointNavigationEnable... |
def test_deepcopy_with_sys_streams():
provider = providers.Callable(example)
provider.add_args(sys.stdin)
provider.add_kwargs(a2=sys.stdout)
provider_copy = providers.deepcopy(provider)
assert (provider is not provider_copy)
assert isinstance(provider_copy, providers.Callable)
assert (provid... |
def process_pinned_projects_post(owner, url_on_success):
if isinstance(owner, models.Group):
UsersLogic.raise_if_not_in_group(flask.g.user, owner)
form = PinnedCoprsForm(owner)
if (not form.validate_on_submit()):
return render_pinned_projects(owner, form=form)
PinnedCoprsLogic.delete_by_... |
class DataHandler(BaseHandler):
def initialize(self, app):
self.state = app.state
self.subs = app.subs
self.port = app.port
self.env_path = app.env_path
self.login_enabled = app.login_enabled
def wrap_func(handler, args):
eid = extract_eid(args)
if ('data'... |
.django_db
def test_spending_by_geography_failure(client, monkeypatch, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_geography/', content_type='application/json', data=json.dumps({'scope': 'test', 'filters'... |
class Command(betterproto.Message):
command_type: v1enums.CommandType = betterproto.enum_field(1)
schedule_activity_task_command_attributes: 'ScheduleActivityTaskCommandAttributes' = betterproto.message_field(2, group='attributes')
start_timer_command_attributes: 'StartTimerCommandAttributes' = betterproto.... |
def filter_by_defc_closed_periods() -> Q:
q = Q()
for sub in final_submissions_for_all_fy():
if (((sub.fiscal_year == REPORTING_PERIOD_MIN_YEAR) and (sub.fiscal_period >= REPORTING_PERIOD_MIN_MONTH)) or (sub.fiscal_year > REPORTING_PERIOD_MIN_YEAR)):
q |= ((Q(submission__reporting_fiscal_yea... |
def test_synchronizer_run_raises_exception_with_run_called_twice(sample_directory, output_filename):
def sync_function(trace_object):
return trace_object.samples.array
input_filename = f'{sample_directory}/synchronization/ets_file.ets'
ths = estraces.read_ths_from_ets_file(input_filename)[:10]
s... |
class TestGetRuleDetail():
(scope='function')
def rule(self, policy: Policy) -> Rule:
return policy.get_rules_for_action(ActionType.access.value)[0]
(scope='function')
def url(self, policy: Policy, rule: Rule) -> str:
return (V1_URL_PREFIX + RULE_DETAIL_URI.format(policy_key=policy.key, ... |
def update_preview_frame_slider() -> gradio.Slider:
if is_video(facefusion.globals.target_path):
video_frame_total = count_video_frame_total(facefusion.globals.target_path)
return gradio.Slider(maximum=video_frame_total, visible=True)
return gradio.Slider(value=None, maximum=None, visible=False) |
(('s', 'expected'), [param('abc', 'abc', id='no_esc'), param('\\', '\\\\', id='esc_backslash'), param('\\\\\\', '', id='esc_backslash_x3'), param('()', '\\(\\)', id='esc_parentheses'), param('[]', '\\[\\]', id='esc_brackets'), param('{}', '\\{\\}', id='esc_braces'), param(':=,', '\\:\\=\\,', id='esc_symbols'), param(' ... |
class TreeContentProvider(ContentProvider):
def get_elements(self, element):
return self.get_children(element)
def get_parent(self, element):
return None
def get_children(self, element):
raise NotImplementedError()
def has_children(self, element):
raise NotImplementedErro... |
def InstallSysroot(target_platform, target_arch):
sysroot_dict = GetSysrootDict(target_platform, target_arch)
tarball_filename = sysroot_dict['Tarball']
tarball_sha1sum = sysroot_dict['Sha1Sum']
linux_dir = os.path.dirname(SCRIPT_DIR)
sysroot = os.path.join(linux_dir, sysroot_dict['SysrootDir'])
... |
def test_custom_form_complex_fields_complete(db, client, jwt, user):
attendee = get_complex_custom_form_attendee(db, user)
data = json.dumps({'data': {'type': 'attendee', 'id': str(attendee.id), 'attributes': {'firstname': 'Areeb', 'lastname': 'Jamal', 'job-title': 'Software Engineer', 'complex-field-values': {... |
def test_data(db):
baker.make('references.CGAC', cgac_code='000', agency_name='Agency 000', agency_abbreviation='A000')
baker.make('references.CGAC', cgac_code='002', agency_name='Agency 002', agency_abbreviation='A002')
award = baker.make('search.AwardSearch', award_id=1)
taa = baker.make('accounts.Tre... |
def test_should_erase_return_data_with_revert(computation):
assert (computation.get_gas_remaining() == 100)
computation.return_data = b'\x1337'
with computation:
raise Revert('Triggered VMError for tests')
assert (not computation.should_erase_return_data)
assert (computation.return_data == b... |
class YahooQuarterlyData():
def __init__(self, data_path: str, quarter_count: Optional[int]=None):
self.data_path = data_path
self.quarter_count = quarter_count
def load(self, index: List[str]) -> pd.DataFrame:
result = []
for ticker in index:
path = '{}/quarterly/{}.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.