code stringlengths 281 23.7M |
|---|
class TestOrderAsStack(TestCase):
mode = 'static'
def setUp(self):
self.pool = IntPool(max_size=3, order_as_stack=True)
def test_ordering(self):
(one, two) = (self.pool.get(), self.pool.get())
self.pool.put(one)
self.pool.put(two)
self.assertEqual(self.pool.get(), two... |
class MT41K64M16(DDR3Module):
nbanks = 8
nrows = 8192
ncols = 1024
technology_timings = _TechnologyTimings(tREFI=(.0 / 8192), tWTR=(4, 7.5), tCCD=(4, None), tRRD=(4, 10), tZQCS=(64, 80))
speedgrade_timings = {'800': _SpeedgradeTimings(tRP=13.1, tRCD=13.1, tWR=13.1, tRFC=(64, None), tFAW=(None, 50), ... |
.integration_saas
.integration_mailchimp
class TestSaasConnectorIntegration():
def test_saas_connector(self, db: Session, mailchimp_connection_config, mailchimp_dataset_config):
connector = get_connector(mailchimp_connection_config)
assert (connector.__class__ == SaaSConnector)
assert (conne... |
def extractWordofCraft(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('Toaru Ossan no VRMMO katsudouki' in item['tags']):
return buildReleaseMessageWithType(item, 'Toa... |
class OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingLowpassFre... |
class DistributionRestClient(Distribution):
API_URL = '/cosmos/distribution/v1beta1'
def __init__(self, rest_api: RestClient) -> None:
self._rest_api = rest_api
def CommunityPool(self) -> QueryCommunityPoolResponse:
json_response = self._rest_api.get(f'{self.API_URL}/community_pool')
... |
def test_parse_schema():
schema = {'type': 'record', 'name': 'test_parse_schema', 'fields': [{'name': 'field', 'type': 'string'}]}
parsed_schema = parse_schema(schema)
assert ('__fastavro_parsed' in parsed_schema)
parsed_schema_again = parse_schema(parsed_schema)
assert (parsed_schema_again == parse... |
_os(*metadata.platforms)
def main():
firefox = 'C:\\Users\\Public\\firefox.exe'
msdt = 'C:\\Users\\Public\\msdt.exe'
common.copy_file(EXE_FILE, firefox)
common.copy_file(EXE_FILE, msdt)
common.execute([firefox, '/c', 'msdt.exe /c', 'echo', '/cab', 'C:\\Users\\Public\\'], timeout=10)
common.remov... |
def test_unwrapped_task():
completed_process = subprocess.run([sys.executable, str((test_module_dir / 'unwrapped_decorator.py'))], env={'SCRIPT_INPUT': '10', 'SYSTEMROOT': 'C:\\Windows', 'HOMEPATH': 'C:\\Windows'}, text=True, capture_output=True)
error = completed_process.stderr
error_str = ''
for line ... |
class TxtRecord(Record):
def __init__(self, tioconfig):
super(TxtRecord, self).__init__()
self.tioconfig = tioconfig
self.comment_raw = None
def from_string(cls, in_str, rid, tioconfig):
Encoding.check_unicode(in_str)
obj = cls(tioconfig)
obj.parse(in_str, rid)
... |
def main():
args = docopt(__doc__)
project_path = project.check_for_project('.')
if (project_path is None):
raise ProjectNotFound
build_path = project_path.joinpath(_load_project_structure_config(project_path)['build'])
contract_artifact_path = build_path.joinpath('contracts')
interface_... |
def extractShuranomichiWordpressCom(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 WOFF2LocaTableTest(unittest.TestCase):
def setUp(self):
self.font = font = ttLib.TTFont(recalcBBoxes=False, recalcTimestamp=False)
font['head'] = ttLib.newTable('head')
font['loca'] = WOFF2LocaTable()
font['glyf'] = WOFF2GlyfTable()
def test_compile_short_loca(self):
... |
def sync_domains(site, domains, bench_path='.'):
changed = False
existing_domains = get_domains_dict(get_domains(site, bench_path))
new_domains = get_domains_dict(domains)
if (set(existing_domains.keys()) != set(new_domains.keys())):
changed = True
else:
for d in list(existing_domain... |
def extractGolemcreationkitCom(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) i... |
class OptionSeriesOrganizationDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(flag... |
class Runner():
def __init__(self, options: dict):
self.options = options
self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
def run_jobs(self, job_names, releases):
jobs = build_jobs_list(job_names, releases=releases, options=self.options)
self._run_jobs(jobs)
d... |
class NotificationSettings(FidesSettings):
notification_service_type: Optional[str] = Field(default=None, description='Sets the notification service type used to send notifications. Accepts mailchimp_transactional, mailgun, twilio_sms, or twilio_email.')
send_request_completion_notification: bool = Field(defaul... |
def parse_aces(input_buffer, count):
out = []
while (len(out) < count):
ace = dict()
fields = ('Raw Type', 'Raw Flags', 'Size', 'Raw Access Required')
for (k, v) in zip(fields, unpack('<BBHI', input_buffer[:8])):
ace[k] = v
ace['Type'] = parse_sddl_dacl_ace_type(ace['... |
class BasicFormatter(object):
avg_label_width = 7.0
use_scientific = True
scientific_limits = ((- 3), 5)
def __init__(self, **kwds):
self.__dict__.update(kwds)
def oldformat(self, ticks, numlabels=None, char_width=None):
labels = []
if (len(ticks) == 0):
return []... |
_group.command('delete-job')
('job-name')
('job-type')
_context
def delete_job(ctx: click.Context, job_name, job_type, verbose=True):
es_client: Elasticsearch = ctx.obj['es']
ml_client = MlClient(es_client)
try:
if (job_type == 'anomaly_detection'):
ml_client.delete_job(job_name)
... |
class TestStartStopNotificationService():
def test_shutdown_service_with_schedule_disable(self, fledge_url, disable_schedule, wait_time):
disable_schedule(fledge_url, SERVICE_NAME)
pause_for_x_seconds(x=wait_time)
_verify_service(fledge_url, status='shutdown')
pause_for_x_seconds(x=w... |
class MFBias(nn.Module):
def __init__(self, emb_size, emb_dim, c_vector=1e-06, c_bias=1e-06):
super().__init__()
self.emb_size = emb_size
self.emb_dim = emb_dim
self.c_vector = c_vector
self.c_bias = c_bias
self.product_embedding = nn.Embedding(emb_size, emb_dim)
... |
def test_find_repr_is_working_properly(create_ref_test_data, create_maya_env):
data = create_ref_test_data
maya_env = create_maya_env
maya_env.save_as(data['asset2_model_take1_v001'])
ref = maya_env.reference(data['repr_version1'])
assert (ref.path == data['repr_version1'].absolute_full_path)
re... |
class CommonRangeTests(object):
def test_accepts_int(self):
self.model.percentage = 35
self.assertIs(type(self.model.percentage), int)
self.assertEqual(self.model.percentage, 35)
with self.assertRaises(TraitError):
self.model.percentage = (- 1)
with self.assertRai... |
_app.route('/history')
_app.route('/history/<game_id>')
_app.route('/checkversion/<version>/history')
_app.route('/checkversion/<version>/history/<game_id>')
def history_page(game_id='', version=None):
show_old_version_notice = ((version is not None) and utils.is_old_version(version))
matches = datamodel.get_kn... |
class AnityaTestCase(unittest.TestCase):
def setUp(self):
self.config = config.config.copy()
self.config['TESTING'] = True
self.flask_app = app.create(self.config)
cwd = os.path.dirname(os.path.realpath(__file__))
my_vcr = vcr.VCR(cassette_library_dir=os.path.join(cwd, 'reque... |
class Settings(object):
PKG_NAME = 'fkie_node_manager'
try:
PACKAGE_DIR = roslib.packages.get_pkg_dir(PKG_NAME)
except Exception:
PACKAGE_DIR = ('%s/../..' % os.path.realpath(os.path.dirname(__file__)))
if ('dist-packages' in __file__):
PACKAGE_DIR = ('%s/../../share/fkie... |
class DownloadAdministrator():
def __init__(self):
self.download_job = None
def search_for_a_download(self, **kwargs):
queryset_filter = self.craft_queryset_filter(**kwargs)
self.get_download_job(queryset_filter)
def craft_queryset_filter(**kwargs):
if (len(kwargs) == 0):
... |
def test_that_the_manage_cases_tool_can_be_used_with_clean_storage(opened_main_window_clean, qtbot):
gui = opened_main_window_clean
def handle_dialog(dialog, cases_panel):
cases_panel.setCurrentIndex(0)
current_tab = cases_panel.currentWidget()
assert (current_tab.objectName() == 'create... |
class OptionSeriesLollipopLowmarker(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._config(num,... |
class TelemetryMessageVehicleTransmissionGearboxGear(object):
swagger_types = {'recommended': 'str'}
attribute_map = {'recommended': 'recommended'}
def __init__(self, recommended=None):
self._recommended = None
self.discriminator = None
if (recommended is not None):
self.... |
class TestAPIOrgViews(TestCase):
fixtures = ['orgs', 'practices']
api_prefix = '/api/1.0'
def test_api_view_org_code(self):
url = ('%s/org_code?q=ainsdale&format=json' % self.api_prefix)
response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200)
... |
def _check_memory_usage():
memory_usage = psutil.virtual_memory().percent
if (memory_usage > 95.0):
logging.critical(f'System memory is critically low: {memory_usage}%')
elif (memory_usage > 80.0):
logging.warning(f'System memory is running low: {memory_usage}%')
else:
logging.in... |
def display_livetv_type(menu_params, view):
handle = int(sys.argv[1])
xbmcplugin.setContent(handle, 'files')
view_name = view.get('Name')
params = {}
params['UserId'] = '{userid}'
params['Recursive'] = False
params['ImageTypeLimit'] = 1
params['Fields'] = '{field_filters}'
path = get... |
class ciligogo(object):
url = '
name = 'ciligogo'
support_sort = ['relevance', 'addtime', 'size', 'popular']
page_result_count = 10
supported_categories = {'all': ''}
def __init__(self):
pass
def getsearchurl(self):
try:
magneturls = plugin.get_storage('magneturls... |
def get_basic_config():
time_alignment_config = FilteringConfig()
time_alignment_config.smoothing_kernel_size_A = 25
time_alignment_config.clipping_percentile_A = 99.5
time_alignment_config.smoothing_kernel_size_B = 25
time_alignment_config.clipping_percentile_B = 99.0
hand_eye_config = HandEyeC... |
def read_schemaless(iostream, schema, num_records, runs):
schema = fastavro.parse_schema(schema)
schemaless_reader = fastavro.schemaless_reader
duration = timeit.repeat('iostream.seek(0);schemaless_reader(iostream, schema);', number=num_records, repeat=runs, globals=locals())
print(TIMEIT_FORMAT.format(... |
def is_text(path, prob_lines=1000, probe_size=4096):
try:
with open(path, 'rb') as f:
if (0 in f.read(probe_size)):
return False
with open(path, 'r', encoding='utf-8') as f:
for (i, _) in enumerate(f):
if (i > prob_lines):
b... |
class ExtendedCodecsTest(unittest.TestCase):
def test_decode_mac_japanese(self):
self.assertEqual(b'x\xfe\xfdy'.decode('x_mac_japanese_ttx'), (((chr(120) + chr(8482)) + chr(169)) + chr(121)))
def test_encode_mac_japanese(self):
self.assertEqual(b'x\xfe\xfdy', (((chr(120) + chr(8482)) + chr(169))... |
def compute_eigvals_eigvecs(score: Tensor, node_val: Tensor) -> Tuple[(bool, Tensor, Tensor, Tensor)]:
(first_gradient, hessian) = tensorops.gradients(score, node_val)
is_valid_first_grad_and_hessian = (is_valid(first_gradient) or is_valid(hessian))
if (not is_valid_first_grad_and_hessian):
return (... |
class GamePad(Input, Output):
def get_gampad_count():
return pygame.joystick.get_count()
def __init__(self, gamepad_id, track_button_events=True, track_motion_events=False):
if (not _internals.active_exp.is_initialized):
raise RuntimeError('Cannot create GamePad before expyriment.ini... |
class Test_icmpv6_echo_request(unittest.TestCase):
type_ = 128
code = 0
csum = 42354
id_ = 30240
seq = 0
data = b'\x01\xc9\xe76\xd39\x06\x00'
buf = b'\x80\x00\xa5rv \x00\x00'
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
echo = icmpv6... |
class MessageStorageItem(StorageItem):
def identifier(self) -> MessageIdentifier:
return self._id
def __init__(self, conv_uid: str, index: int, message_detail: Dict):
self.conv_uid = conv_uid
self.index = index
self.message_detail = message_detail
self._id = MessageIdenti... |
def get_searcher(args, mode, data_path):
searcher = None
if (mode in [SEARCH_MODE_NO_SEARCH, SEARCH_MODE_CACHE]):
searcher = None
elif (mode == SEARCH_MODE_DIAMOND):
searcher = DiamondSearcher(args, get_eggnog_dmnd_db(args.dmnd_db, mode, data_path))
elif (mode == SEARCH_MODE_HMMER):
... |
class OptionPlotoptionsBarSonificationDefaultinstrumentoptionsMappingPlaydelay(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:... |
('\n{out_data} = _mm256_blendv_pd ({z_data}, {y_data},\n_mm256_cmp_pd ({x_data}, {v_data}, _CMP_LT_OQ));\n')
def avx2_select_pd(out: ([f64][4] AVX2), x: ([f64][4] AVX2), v: ([f64][4] AVX2), y: ([f64][4] AVX2), z: ([f64][4] AVX2)):
assert (stride(out, 0) == 1)
assert (stride(x, 0) == 1)
assert (stride(v... |
class OptionSeriesColumnrangeSonificationDefaultspeechoptionsMappingRate(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 Origin(NamedTuple):
callee_name: Method
callee_port: Port
def from_json(leaf_json: Dict[(str, Any)], leaf_kind: str) -> 'Origin':
callee = leaf_json.get('method', leaf_json.get('field', leaf_json.get('canonical_name')))
if (not callee):
raise sapp.ParseError(f'No callee fou... |
def detect_db_config():
system = platform.system()
if (system == 'Windows'):
try:
directory = os.environ['APPDATA']
except KeyError:
return (None, None)
config = os.path.join(directory, 'BloodHound', 'config.json')
try:
with open(config, 'r') a... |
(IPythonEditor)
class PythonEditor(MPythonEditor, LayoutWidget):
dirty = Bool(False)
path = Str()
show_line_numbers = Bool(True)
changed = Event()
key_pressed = Event(KeyPressedEvent)
def __init__(self, parent=None, **traits):
create = traits.pop('create', None)
super().__init__(... |
def load_environment_backend(env_backend: str) -> BackendAPI:
if (env_backend in SUPPORTED_BACKENDS):
try:
return load_backend(env_backend)
except ImportError as e:
raise ImportError(f"""The backend specified in ETH_HASH_BACKEND, '{env_backend}', is not installed. Install wit... |
def confirm_email(nonce):
form = Form.confirm(nonce)
if (not form):
return (render_template('error.html', title='Not a valid link', text='Confirmation token not found.<br />Please check the link and try again.'), 400)
else:
return render_template('forms/email_confirmed.html', email=form.emai... |
class OptionPlotoptionsHeatmapOnpointConnectoroptions(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(t... |
def find_uncategorized_dataset_fields(existing_dataset: Optional[Dataset], source_dataset: Dataset) -> Tuple[(List[str], int)]:
uncategorized_fields = []
total_field_count = 0
for source_dataset_collection in source_dataset.collections:
existing_dataset_collection = (next((existing_dataset_collectio... |
class batched_nms(Operator):
def __init__(self, iou_threshold=0.5, keep_n=(- 1)) -> None:
super().__init__()
self._attrs['op'] = 'batched_nms'
self._attrs['has_profiler'] = False
self._attrs['keep_n'] = keep_n
self._attrs['iou_threshold'] = iou_threshold
self.exec_key... |
def data_cmap(data: pd.Series) -> Tuple:
data_family = infer_data_family(data)
if (data_family == 'categorical'):
base_cmap = qualitative
num_categories = max(len(data.unique()), 3)
if (num_categories > 12):
raise ValueError(f"It appears you have >12 categories for the key {d... |
def _derive_pbkdf_key(crypto: Dict[(str, Any)], password: str) -> bytes:
kdf_params = crypto['kdfparams']
salt = decode_hex(kdf_params['salt'])
dklen = kdf_params['dklen']
(should_be_hmac, _, hash_name) = kdf_params['prf'].partition('-')
assert (should_be_hmac == 'hmac')
iterations = kdf_params[... |
def extractBluebugsstory(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=frag, postf... |
_os(*metadata.platforms)
def main():
common.log('Exporting the boot configuration....')
bcdedit = 'bcdedit.exe'
backup_file = Path('boot.cfg').resolve()
common.execute(['bcdedit.exe', '/export', backup_file])
common.log('Changing boot configuration', log_type='!')
common.execute([bcdedit, '/set'... |
class Calendar(Html.Html):
name = 'ToastCalendar'
requirements = ('tui-calendar',)
_option_cls = OptToastCalendar.OptionCalendar
def __init__(self, page, width, height, html_code, options, profile):
self.height = height[0]
super(Calendar, self).__init__(page, [], html_code=html_code, pro... |
_os(*metadata.platforms)
def main():
masquerade = '/tmp/Installer'
masquerade2 = '/tmp/curl'
common.create_macos_masquerade(masquerade)
common.create_macos_masquerade(masquerade2)
common.log('Launching fake macOS installer commands to download payload')
common.execute([masquerade], timeout=10, k... |
def extractCabnovelsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('xi ling empire' in item['tags']):
return buildReleaseMessageWithType(item, 'Xyrin Empire', vol... |
class TestContest(object):
def testContest(self):
env = Environ()
t = EventTap()
s = env.server_core()
proton = env.client_core()
(a, b, c, d, e) = [env.client_core() for _ in range(5)]
t.tap(proton, a, b, c, d, e)
proton.auth.login('Proton')
a.auth.lo... |
class Test_SlidingWindow():
def test_constructor(self):
x = SlidingWindow(10.1, 20.2, 30.3)
assert (x.before == 10.1)
assert (x.after == 20.2)
assert (x.expires == 30.3)
def test_has_ranges_including_the_value(self):
size = 10
step = 5
timestamp = 6
... |
def annotate_pips_speed_model(pips, speed_data):
for (pip_name, pip_data) in pips.items():
speed_model_index = pip_data['speed_model_index']
pip_speed_data = speed_data[speed_model_index]
assert (pip_speed_data['resource_name'] == 'pip'), (pip_speed_data['resource_name'], speed_model_index)
... |
def register(blueprint: DashBlueprint, name: str, prefix=None, **kwargs):
if (prefix is not None):
prefix_transform = PrefixIdTransform(prefix)
blueprint.transforms.append(prefix_transform)
blueprint.register_callbacks(GLOBAL_BLUEPRINT)
dash.register_page(name, layout=blueprint._layout_value... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 23
PLUGIN_NAME = 'Display - Simple OLED'
PLUGIN_VALUENAME1 = 'OLED'
P23_Nlines = 8
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_I2C
self.vtype = rpieGlobals.SENSO... |
.django_db
def test_category_awarding_agency_subawards(agency_test_data):
test_payload = {'category': 'awarding_agency', 'subawards': True, 'page': 1, 'limit': 50}
spending_by_category_logic = AwardingAgencyViewSet().perform_search(test_payload, {})
expected_response = {'category': 'awarding_agency', 'limit... |
def get_schema(action):
options = {}
defaults = [option_defaults.allow_ilm_indices(), option_defaults.continue_if_exception(), option_defaults.disable_action(), option_defaults.ignore_empty_list(), option_defaults.timeout_override(action)]
for each in defaults:
options.update(each)
for each in a... |
def extractMandarinducktalesWordpressCom(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 OptionSeriesWindbarbSonificationPointgrouping(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... |
def gen_accessor_doc(out, name):
common_top_matter(out, name)
out.write('/* DOCUMENTATION ONLY */\n')
for cls in of_g.standard_class_order:
if type_maps.class_is_virtual(cls):
pass
out.write(('\n/**\n * Structure for %(cls)s object. Get/set\n * accessors available in all version... |
def eit_loc_eval(ds: np.ndarray, mesh_obj: mesh.PyEITMesh, mode: str='element'):
loc = np.argmax(np.abs(ds))
if (mode == 'node'):
loc_xyz = mesh_obj.node[loc]
else:
loc_xyz = mesh_obj.elem_centers[loc]
ds_max = ds[loc]
ds_sign = np.sign(ds_max)
return (loc_xyz, ds_max, ds_sign) |
class SATATestSoC(SoCMini):
def __init__(self, platform, gen='gen3', with_analyzer=False):
assert (gen in ['gen1', 'gen2', 'gen3'])
sys_clk_freq = int(.0)
sata_clk_freq = {'gen1': .0, 'gen2': .0, 'gen3': .0}[gen]
self.submodules.crg = _CRG(platform, sys_clk_freq)
SoCMini.__in... |
def getDBC_v(x, flag):
if (flag in [boundaryTags['left']]):
return (lambda x, t: 0.0)
elif (flag in [boundaryTags['front'], boundaryTags['back'], boundaryTags['top'], boundaryTags['bottom'], boundaryTags['obstacle']]):
return (lambda x, t: 0.0)
elif ((ns_forceStrongDirichlet == False) and (f... |
def pdf_to_string(pdf_file):
fp = open(pdf_file, 'rb')
parser = PDFParser(fp)
doc = PDFDocument()
parser.set_document(doc)
doc.set_parser(parser)
doc.initialize('')
rsrcmgr = PDFResourceManager()
laparams = LAParams()
laparams.line_margin = 0.3
laparams.word_margin = 0.3
devi... |
def test_create_and_link_node_from_remote_ignore():
def wf(i: int, j: int):
...
lp = LaunchPlan.get_or_create(wf, name='promise-test', fixed_inputs={'i': 1}, default_inputs={'j': 10})
ctx = context_manager.FlyteContext.current_context().with_compilation_state(CompilationState(prefix=''))
with py... |
class TestZillizVectorDBConfig():
.dict(os.environ, {'ZILLIZ_CLOUD_URI': 'mocked_uri', 'ZILLIZ_CLOUD_TOKEN': 'mocked_token'})
def test_init_with_uri_and_token(self):
expected_uri = 'mocked_uri'
expected_token = 'mocked_token'
db_config = ZillizDBConfig()
assert (db_config.uri == ... |
class OptionSeriesVariablepieTooltip(Options):
def clusterFormat(self):
return self._config_get('Clustered points: {point.clusterPointsAmount}')
def clusterFormat(self, text: str):
self._config(text, js_type=False)
def dateTimeLabelFormats(self) -> 'OptionSeriesVariablepieTooltipDatetimelabe... |
def add_resource_b(db_session, resource_id, resource_name='test_resource'):
Resource.__possible_permissions__ = ['test_perm', 'test_perm1', 'test_perm2', 'foo_perm', 'group_perm', 'group_perm2']
resource = ResourceTestobjB(resource_id=resource_id, resource_name=resource_name)
db_session.add(resource)
db... |
def get_matched_value_counts(value_counts: pd.Series, other_to_match: pd.Series) -> pd.Series:
matched_series = pd.Series(index=other_to_match.index, dtype=float)
for ind in matched_series.index:
if (ind in value_counts):
matched_series[ind] = value_counts[ind]
else:
matc... |
def philox_round(W, N, rnd, ctr, key):
ctr = ctr.copy()
rnd = numpy.cast[ctr.dtype](rnd)
if (N == 2):
key0 = (key[0] + (PHILOX_W[W][0] * rnd))
(hi, lo) = philox_mulhilo(W, PHILOX_M[(W, N)][0], ctr[0])
ctr[0] = ((hi ^ key0) ^ ctr[1])
ctr[1] = lo
else:
key0 = (key[0... |
class Folder(Boxes):
def __init__(self) -> None:
Boxes.__init__(self)
self.addSettingsArgs(edges.FlexSettings)
self.buildArgParser('x', 'y', 'h')
self.argparser.add_argument('--r', action='store', type=float, default=10.0, help='radius of the corners')
self.argparser.set_defa... |
class Invite(object):
SIGNATURE = 2100
def build(server_peer_id: PeerID, client_peer_id: PeerID) -> Invite:
data = InviteData(server_peer_id, client_peer_id)
header = Header.build(Invite.SIGNATURE, 0, len(data.to_binary_plist()))
msg = Invite(header, data)
msg.fix_checksum()
... |
def ecdsa_raw_sign(msg_hash: bytes, private_key_bytes: bytes) -> Tuple[(int, int, int)]:
z = big_endian_to_int(msg_hash)
k = deterministic_generate_k(msg_hash, private_key_bytes)
(r, y) = fast_multiply(G, k)
s_raw = ((inv(k, N) * (z + (r * big_endian_to_int(private_key_bytes)))) % N)
v = (27 + ((y %... |
class RunTest(tester.TestFlowBase):
OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(RunTest, self).__init__(*args, **kwargs)
self._verify = None
self.n_tables = ofproto_v1_2.OFPTT_MAX
def start_next_test(self, dp):
self._verify = None
... |
class ObjectTypeMibTableMultipleIndicesTestCase(unittest.TestCase):
def setUp(self):
ast = parserFactory()().parse(self.__class__.__doc__)[0]
(mibInfo, symtable) = SymtableCodeGen().genCode(ast, {}, genTexts=True)
(self.mibInfo, pycode) = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}... |
def test_model_to_dict(tresults, tbands):
out = model_to_dict(tresults, peak_org=1)
assert isinstance(out, dict)
assert ('cf_0' in out)
assert (out['cf_0'] == tresults.peak_params[(0, 0)])
assert (not ('cf_1' in out))
out = model_to_dict(tresults, peak_org=2)
assert ('cf_0' in out)
asser... |
def example():
return ft.Column(controls=[ft.TextField(label='Underlined', border='underline', hint_text='Enter text here'), ft.TextField(label='Underlined filled', border=ft.InputBorder.UNDERLINE, filled=True, hint_text='Enter text here'), ft.TextField(label='Borderless', border='none', hint_text='Enter text here'... |
def router():
router = DefaultRouter()
router.add_route('/repos', ResourceWithId(1))
router.add_route('/repos/{org}', ResourceWithId(2))
router.add_route('/repos/{org}/{repo}', ResourceWithId(3))
router.add_route('/repos/{org}/{repo}/commits', ResourceWithId(4))
router.add_route('/repos/{org}/{r... |
def test_horizontal_alignment_enum():
r = ft.Column(horizontal_alignment=ft.CrossAxisAlignment.STRETCH)
assert isinstance(r.horizontal_alignment, ft.CrossAxisAlignment)
assert isinstance(r._get_attr('horizontalAlignment'), str)
cmd = r._build_add_commands()
assert (cmd[0].attrs['horizontalalignment'... |
_meta(characters.youmu.NitoryuuWearEquipmentAction)
class NitoryuuWearEquipmentAction():
def sound_effect(self, act):
card = act.card
tgt = act.target
equips = tgt.equips
cat = card.equipment_category
if ((cat == 'weapon') and [e for e in equips if (e.equipment_category == 'w... |
def isFiltered(link, badwords, badcompounds):
if link.startswith('data:'):
return True
linkl = link.lower()
if any([(badword in linkl) for badword in badwords]):
return True
if any([all([(badword in linkl) for badword in badcompound]) for badcompound in badcompounds]):
print('Com... |
class Migration(migrations.Migration):
dependencies = [('forum_permission', '0001_initial')]
operations = [migrations.AlterField(model_name='forumpermission', name='codename', field=models.CharField(db_index=True, max_length=150, unique=True, verbose_name='Permission codename')), migrations.AlterField(model_nam... |
class ReplicateApi(ProviderInterface, ImageInterface, TextInterface):
provider_name = 'replicate'
def __init__(self, api_keys: Dict={}):
api_settings = load_provider(ProviderDataEnum.KEY, provider_name=self.provider_name, api_keys=api_keys)
self.headers = {'Content-Type': 'application/json', 'Ac... |
class OptionSeriesTimelineDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
sel... |
def test_integration_parse_arg_outformat_csv(caplog):
args = [path.relpath(__file__), '--debug', '--outformat', 'csv']
cis_audit.parse_arguments(argv=args)
status = False
for record in caplog.records:
if (record.msg == 'Going to use "csv" outputter'):
status = True
break
... |
.parametrize('params,sequence', ((FORWARD_0_to_5, (0, 1, 2, 3, 4, 5, 6)), (FORWARD_0_to_5, (0, 1, 3, 5, 6)), (FORWARD_0_to_5_SKIP_1, (0, 2, 4, 6)), (FORWARD_0_to_5_SKIP_1, (0, 2, 3, 4)), (FORWARD_0_to_5_SKIP_1, (0, 2, 3))))
def test_header_request_sequence_matching_unexpected(params, sequence):
validator = BlockHea... |
class ipv6(packet_base.PacketBase):
_PACK_STR = '!IHBB16s16s'
_MIN_LEN = struct.calcsize(_PACK_STR)
_IPV6_EXT_HEADER_TYPE = {}
_TYPE = {'ascii': ['src', 'dst']}
def register_header_type(type_):
def _register_header_type(cls):
ipv6._IPV6_EXT_HEADER_TYPE[type_] = cls
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.