code stringlengths 281 23.7M |
|---|
def _cmd_reference(args):
usage_err_msg = 'Give .cnn samples OR targets and (optionally) antitargets.'
if args.targets:
assert (not args.references), usage_err_msg
ref_probes = reference.do_reference_flat(args.targets, args.antitargets, args.fasta, args.male_reference)
elif args.references:
... |
def test_equal_szts_more_images():
kwargs = copy.copy(KWARGS)
kwargs['images'] = 7
convergence = {'rms_force_thresh': 2.4}
kwargs['convergence'] = convergence
szts_equal = SimpleZTS(get_geoms(), param='equal')
opt = run_cos_opt(szts_equal, SteepestDescent, **kwargs)
assert opt.is_converged
... |
def apispec_to_template(app, spec, definitions=None, paths=None):
definitions = (definitions or [])
paths = (paths or [])
with app.app_context():
for definition in definitions:
if isinstance(definition, (tuple, list)):
(name, schema) = definition
else:
... |
class GetSentencesTest(unittest.TestCase):
('get_sentences.app.pull_user_sentences', side_effect=mocked_pull_user_sentences)
def test_build(self, pull_user_sentences_mock):
response = lambda_handler(self.sub_apig_event(), '')
def sub_apig_event(self):
return {'resource': '/sentence', 'path':... |
class TetrisMainWindow(QMainWindow):
def __init__(self, parent=None):
super(TetrisMainWindow, self).__init__(parent)
self.setWindowTitle(('PyQtris v%s' % pyqtris_version))
self.setWindowIcon(QIcon(get_icon_pixmap()))
self.figurebank = self.make_figure_bank()
self.create_main_... |
class OptionPlotoptionsTimelineMarker(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(0)
def enabledThreshold(self, num: float):
self._config(nu... |
class BigBlueButton():
api_url: str
secret: str
def build_url(self, action: str, params: Optional[Dict[(str, str)]]=None) -> str:
url = (((self.api_url + '/') + action) + '?')
params = (params or {})
params = {key: val for (key, val) in params.items() if val}
query = urlencod... |
(once={'graceful': True}, base=QueueOnce)
def weekly_reload_all_aos():
logger.info(' Weekly (%s) reload of all AOs ', datetime.date.today().strftime('%A'))
load_advisory_opinions()
logger.info(' Weekly (%s) reload of all AOs completed successfully', datetime.date.today().strftime('%A'))
slack_message = ... |
class MyTestCase(unittest.TestCase):
('netplot.config.config.Config')
def test_tcp_incoming_arg_incoming_True(self, config):
packets = sniff(offline='./test/packets/tcp_incoming.pcap')
config.incoming = True
provider = DomainProvider(config)
provider.get_domain = MagicMock(return... |
def extractBlackhatmagickCom(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 ... |
('/users', response_model=schemas.User, status_code=status.HTTP_201_CREATED, summary='Create a user')
def create_new_user(user: schemas.UserCreate, db: Session=Depends(get_db)) -> Any:
db_username = get_user_by_username(db, username=user.username)
db_email = get_user_by_email(db, email=user.email)
if db_use... |
def assert_output_has_error(cmd, expected_error, env):
env['HOME'] = '.'
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
has_error = False
output = ''
for line in (list(p.stdout) + list(p.stderr)):
line = line.decode('utf-8').strip()
output += (line... |
def runForDuration(cmdline, duration, loggingDir):
outLogFile = logFile(loggingDir)
teeCommand = ['tee', '-a', outLogFile]
cmdline = [str(x) for x in cmdline]
print(cmdline)
try:
p1 = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
_ = subprocess.Popen(tee... |
class UpdateNamespaceRequest(betterproto.Message):
name: str = betterproto.string_field(1)
update_info: v1namespace.UpdateNamespaceInfo = betterproto.message_field(2)
config: v1namespace.NamespaceConfig = betterproto.message_field(3)
replication_config: v1replication.NamespaceReplicationConfig = betterp... |
class OptionPlotOptionsBar(Options):
def horizontal(self):
return self._config_get()
def horizontal(self, flag: bool):
self._config(flag)
def barHeight(self):
return self._config_get()
def barHeight(self, value: int):
self._config(value)
def dataLabels(self) -> Option... |
()
_context
('--no-pull', is_flag=True, help='Use a local image instead of trying to pull from DockerHub.')
('--no-init', is_flag=True, help='Disable the initialization of the Fides CLI, to run in headless mode.')
('--env-file', type=click.Path(exists=True), help='Use a custom ENV file for the Fides container to overri... |
def parse_args():
parser = argparse.ArgumentParser(description='LiteScope Client utility')
parser.add_argument('-r', '--rising-edge', action='append', help='Add rising edge trigger.')
parser.add_argument('-f', '--falling-edge', action='append', help='Add falling edge trigger.')
parser.add_argument('-v',... |
class DUNS(models.Model):
awardee_or_recipient_uniqu = models.TextField(null=True, blank=True)
legal_business_name = models.TextField(null=True, blank=True)
dba_name = models.TextField(null=True, blank=True)
ultimate_parent_unique_ide = models.TextField(null=True, blank=True)
ultimate_parent_legal_e... |
class Migration(migrations.Migration):
dependencies = [('search', '0033_add_total_outlays_column')]
operations = [migrations.AddField(model_name='subawardsearch', name='legal_entity_congressional_current', field=models.TextField(blank=True, null=True)), migrations.AddField(model_name='subawardsearch', name='pla... |
def run_async_local_bwd(folder_name: str, path_dir: str, callback_url: str, verbose: bool, num_workers: int, task_name_suffix: str, res: tuple, batch_data_vjp: Tuple[(JaxSimulationData, ...)]) -> Tuple[Dict[(str, JaxSimulation)]]:
(batch_data_fwd,) = res
task_name_suffix_adj = _task_name_adj('')
grad_data_f... |
class GzipTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Module\nname: ambassador\nconfig:\n gzip:\... |
def write_navbar(htmlhandle, brandname, nav_list, activelink=None):
htmlhandle.write('\n <nav class="navbar navbar-inverse navbar-fixed-top">\n <div class="container-fluid">\n <div class="navbar-header">\n <a class="navbar-brand">{}</a>\n </div>\n <ul class="nav navbar-nav navbar-right">\n ... |
class OptionSeriesTreemapSonificationDefaultspeechoptionsPointgrouping(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: bool):
... |
class ClassificationDetail(Base):
__tablename__ = 'cls_classification_detail'
instance_id = Column(String(255))
status = Column(Text)
dataset = Column(Text)
collection = Column(Text)
field = Column(Text)
labels = Column(JSON)
created_at = Column(DateTime(timezone=True), server_default=fu... |
def extractDevildante777SBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, p... |
(TCP_OPTION_KIND_USER_TIMEOUT, 4)
class TCPOptionUserTimeout(TCPOption):
_PACK_STR = '!BBH'
def __init__(self, granularity, user_timeout, kind=None, length=None):
super(TCPOptionUserTimeout, self).__init__(kind, length)
self.granularity = granularity
self.user_timeout = user_timeout
... |
def migrate_property(name, property, property_info, class_dict):
get = _property_method(class_dict, ('_get_' + name))
set = _property_method(class_dict, ('_set_' + name))
val = _property_method(class_dict, ('_validate_' + name))
if ((get is not None) or (set is not None) or (val is not None)):
(... |
class Encoder(nn.Module):
def __init__(self, d_input=320, n_layers=6, n_head=8, d_k=64, d_v=64, d_model=512, d_inner=2048, dropout=0.1, pe_maxlen=5000):
super(Encoder, self).__init__()
self.d_input = d_input
self.n_layers = n_layers
self.n_head = n_head
self.d_k = d_k
... |
class Polyline():
def __init__(self, positions, color, alpha, edge_width, visible):
self.positions = positions
self.color = color
self.alpha = alpha
self.edge_width = edge_width
self.visible = visible
def get_properties(self, binary_filename):
json_dict = {'type':... |
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
def initialize_options(self) -> None:
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self) -> None:
TestCommand.finalize_options(self)
self.test_... |
class PresidentialBySize(db.Model):
__table_args__ = {'schema': 'public'}
__tablename__ = 'ofec_presidential_by_size_vw'
idx = db.Column(db.Integer, primary_key=True)
candidate_id = db.Column(db.String(0), doc=docs.CANDIDATE_ID_PRESIDENTIAL)
contribution_receipt_amount = db.Column(db.Numeric(30, 2),... |
def _serialize_and_read_object(pb_obj):
with tempfile.NamedTemporaryFile(mode='w', delete=True) as tmp:
_write_object_to_disk(pb_obj, tmp.name)
with open(tmp.name, 'r') as json_file:
json_object = json.loads(json_file.read())
assert (json_object is not None)
asser... |
class TestPathAccessors(unittest.TestCase):
def test_001_simple_put(self):
out = {}
path_put(out, 'foo', 'bar')
self.assertEqual(out, {'foo': 'bar'})
self.assertEqual(path_get(out, 'foo'), 'bar')
def test_002_nested_put(self):
out = {}
path_put(out, 'foo.bar', 'ba... |
def normalize_url(url):
if (not re.match('^[a-z]+://', url, re.I)):
url = (' % url)
purl = urlsplit(url)
if (not purl.path):
return ('%s/' % purl.geturl())
new_path = re.sub('/+', '/', purl.path)
new_path = posixpath.normpath(new_path)
if (purl.path.endswith('/') and (not new_pat... |
class UpdateBackupForm(BackupForm):
disk_id = forms.TypedChoiceField(label=_('Disk ID'), required=True, coerce=int, widget=forms.Select(attrs={'class': 'input-select2 narrow', 'disabled': 'disabled'}))
name = forms.CharField(label=_('Backup Name'), required=True, max_length=24, widget=forms.TextInput(attrs={'cl... |
class memoize(object):
def __init__(self, ttl):
self.cache = {}
self.ttl = ttl
def __call__(self, f):
(f)
def wrapped_f(*args):
now = time.time()
try:
(value, last_update) = self.cache[args]
if ((self.ttl > 0) and ((now - la... |
def push_script(data_hex: str) -> str:
data = bfh(data_hex)
data_len = len(data)
if ((data_len == 0) or ((data_len == 1) and (data[0] == 0))):
return bh2u(bytes([Ops.OP_0]))
elif ((data_len == 1) and (data[0] <= 16)):
return bh2u(bytes([((Ops.OP_1 - 1) + data[0])]))
elif ((data_len =... |
class AbstractForum(MPTTModel, DatedModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE, verbose_name=_('Parent'))
name = models.CharField(max_length=100, verbose_name=_('Name'))
slug = models.SlugField(max_length=255, verbose_name=_('Slug'))
... |
def test_remove_component_success():
dep_manager = _DependenciesManager()
protocol = ProtocolConfig('a_protocol', 'author', '0.1.0', protocol_specification_id='some/author:0.1.0')
skill = SkillConfig('skill', 'author', '0.1.0', protocols=[protocol.public_id])
dep_manager.add_component(protocol)
dep_... |
class VampireKissHandler(THBEventHandler):
interested = ['action_apply', 'calcdistance']
def handle(self, evt_type, act):
if ((evt_type == 'action_apply') and isinstance(act, Damage)):
(src, tgt) = (act.source, act.target)
if (not (src and src.has_skill(VampireKiss))):
... |
class TextualInversionConfig(BaseModel):
placeholder_token: str = '*'
initializer_token: (str | None) = None
style_mode: bool = False
def apply_textual_inversion_to_target(self, text_encoder: CLIPTextEncoder) -> None:
adapter = ConceptExtender(target=text_encoder)
tokenizer = text_encode... |
class Thumbnailer():
_MAX_WORKERS = 2
def __init__(self):
self._pending = {}
self._executor = ThreadPoolExecutor(max_workers=self._MAX_WORKERS)
def generate(self, uuid, iter_, image_path, callback):
if (uuid in self._pending):
return
def _thumbnail_callback(future... |
class ImgCarousel(Html.Html):
name = 'Carousel'
_option_cls = OptImg.OptionsImage
def __init__(self, page, images, path, selected, width, height, options, profile):
(self.items, self.__click_items) = ([], [])
super(ImgCarousel, self).__init__(page, '', css_attrs={'width': width, 'height': he... |
def test_literal_types():
obj = _types.LiteralType(simple=_types.SimpleType.INTEGER)
assert (obj.simple == _types.SimpleType.INTEGER)
assert (obj.schema is None)
assert (obj.collection_type is None)
assert (obj.map_value_type is None)
assert (obj == _types.LiteralType.from_flyte_idl(obj.to_flyte... |
class Ship():
def __init__(self, ss_game):
self.screen = ss_game.screen
self.settings = ss_game.settings
self.screen_rect = ss_game.screen.get_rect()
self.image = pygame.image.load('images/rocket_small.png')
self.rect = self.image.get_rect()
self.center_ship()
... |
_to_return_value(b'|'.join)
_tuple
def bytes_repr(value):
if is_bytes(value):
(yield value)
elif is_text(value):
(yield to_bytes(text=value))
elif is_list_like(value):
(yield b''.join((b'(', b','.join((bytes_repr(item) for item in value)), b')')))
elif is_dict(value):
(yi... |
class RuleAppliesTo(object):
SELF = 'self'
CHILDREN = 'children'
SELF_AND_CHILDREN = 'self_and_children'
apply_types = frozenset([SELF, CHILDREN, SELF_AND_CHILDREN])
def verify(cls, applies_to):
if (applies_to not in cls.apply_types):
raise audit_errors.InvalidRulesSchemaError('I... |
def unpack_function(file_path, tmp_dir):
decrypted_file = Path(tmp_dir, 'decrypted_image')
extraction_command = f'python3 {TOOL_PATH} -i {file_path} -o {decrypted_file}'
process = run(split(extraction_command), stdout=PIPE, stderr=STDOUT, text=True, check=False)
return {'output': process.stdout} |
def extractMesmerizingmemoirsCom(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 filter_ips_sensor_data(json):
option_list = ['block_malicious_url', 'comment', 'entries', 'extended_log', 'filter', 'name', 'override', 'replacemsg_group', 'scan_botnet_connections']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and ... |
class TestEngine():
def __init__(self, args):
self.args = args
self.ds = JsonDataset(args)
self.all_results = self.emptyResults(self.ds.num_classes, args.total_num)
self.all_boxes = self.all_results['all_boxes']
self.all_segms = self.all_results['all_segms']
self.inde... |
class TestMockConstructorIntegration(TestDSLBase):
def test_mock_constructor_integration(self):
def fail_top(context):
_context
def fail_sub_context(context):
def expect_fail(self):
self.mock_constructor('subprocess', 'Popen').for_call(['cmd']).to_... |
class View(MView):
def create_control(self, parent):
from pyface.qt import QtGui
control = QtGui.QWidget(parent)
palette = control.palette()
palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor('red'))
control.setPalette(palette)
control.setAutoFillBackgroun... |
class ModeManager():
def __init__(self, mode_classes):
self.mode_classes = mode_classes
self.baseline_events = []
self.modes = None
self.last_mode = None
self.mode_stroked_from = None
self.mode = None
_showbase
def init_modes(self):
self.modes = {name:... |
('method', ['resize', 'sample'])
def test_resize_and_sample(method):
with Image(filename='wizard:') as img:
with img.clone() as a:
assert (a.size == (480, 640))
getattr(a, method)(100, 100)
assert (a.size == (100, 100))
with img.clone() as b:
assert (b... |
class ModelField():
def __init__(self, primary_key: bool=False, index: bool=False, unique: bool=False, **kwargs: typing.Any) -> None:
if primary_key:
kwargs['read_only'] = True
self.allow_null = kwargs.get('allow_null', False)
self.primary_key = primary_key
self.index = i... |
class SimpleChatIO(ChatIO):
def prompt_for_input(self, role: str) -> str:
return input(f'{role}: ')
def prompt_for_output(self, role: str) -> str:
print(f'{role}: ', end='', flush=True)
def stream_output(self, output_stream, skip_echo_len: int):
pre = 0
for outputs in output_... |
def get_z3vars(f):
r = set()
def collect(f):
if z3.is_const(f):
if ((f.decl().kind() == z3.Z3_OP_UNINTERPRETED) and (not (askey(f) in r))):
r.add(askey(f))
else:
for c in f.children():
collect(c)
collect(f)
return r |
def medals(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
medal_stats = save_stats['medals']
remove = (user_input_handler.colored_input('Do you want to add or remove medals? (&a&/&r&):') == 'r')
names = get_medal_names(helper.check_data_is_jp(save_stats))
if (names is None):
return save_stat... |
class Tag(SimpleEntity):
__auto_name__ = False
__tablename__ = 'Tags'
__mapper_args__ = {'polymorphic_identity': 'Tag'}
tag_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True)
def __init__(self, **kwargs):
super(Tag, self).__init__(**kwargs)
def __eq__(self, oth... |
class BaseMessage(object):
__slots__ = ['_body', '_channel', '_method', '_properties']
def __init__(self, channel, **message):
self._channel = channel
self._body = message.get('body', None)
self._method = message.get('method', None)
self._properties = message.get('properties', {'... |
def extractMyWayHoneyBlogspotCom(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)... |
.parametrize('local_head,remote_forkid,expected_error', [(7987396, ForkID(hash=to_bytes(hexstr='0x668db0af'), next=0), None), (7987396, ForkID(hash=to_bytes(hexstr='0x668db0af'), next=sys.maxsize), None), (7279999, ForkID(hash=to_bytes(hexstr='0xa00bc324'), next=0), None), (7279999, ForkID(hash=to_bytes(hexstr='0xa00bc... |
def get_icon_for_mime(mime_type: (str | None)) -> str:
if (mime_type is None):
return MIME_TO_ICON_PATH['unknown']
if (mime_type.replace('/', '-') in MIME_TO_ICON_PATH):
return MIME_TO_ICON_PATH[mime_type.replace('/', '-')]
if (mime_type in ARCHIVE_FILE_TYPES):
return MIME_TO_ICON_PA... |
def test_integration_parse_arg_outformat_text(caplog):
args = [path.relpath(__file__), '--debug', '--outformat', 'text']
cis_audit.parse_arguments(argv=args)
status = False
for record in caplog.records:
if (record.msg == 'Going to use "text" outputter'):
status = True
bre... |
('/nu_api/', methods=['GET', 'POST'])
_required
def nu_api():
if (not request.json):
js = {'error': True, 'message': 'This endpoint only accepts JSON POST requests.'}
resp = jsonify(js)
resp.status_code = 200
resp.mimetype = 'application/json'
return resp
print('API Reque... |
class TensorAccessorTestCase(unittest.TestCase):
def test_dim_mapping_for_stride(self):
tc = TensorAccessor(Tensor(shape=[2, 2, 4]))
self.assertListEqual(tc._dim_mapping, [([0], [0]), ([1], [1]), ([2], [2])])
tc.update_base_tensor(Tensor(shape=[2, 2, 4]), stride_dim=2, stride_dim_offset=10)
... |
.parametrize('media_type', media_types, ids=str)
def test_verify_media_msg(chat, master_channel, media_type):
with NamedTemporaryFile() as f:
msg = Message(deliver_to=master_channel, author=chat.other, chat=chat, type=media_type, file=f, filename='test.bin', path=f.name, mime='application/octet-stream')
... |
class LidHoleEdge(FingerHoleEdge):
char = 'L'
description = 'Edge for slide on lid (box back)'
def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw) -> None:
hole_width = self.settings.hole_width
if (hole_width > 0):
super().__call__(((length - hole_width) / 2))
... |
def test_get_vfps_in_parent(common_db, backend_db):
(fo, fw) = create_fw_with_child_fo()
fo_2 = create_test_file_object(uid='fo_2')
add_included_file(fo_2, fw, fw, ['/foo', '/bar'])
backend_db.insert_multiple_objects(fw, fo, fo_2)
result = common_db.get_vfps_in_parent(fw.uid)
assert (fo.uid in r... |
class RecursivelyCensoredDictWrapper(object):
SENSITIVE_FIELDS = frozenset({'password', 'pass', 'passwd', 'passphrase', 'pass_phrase', 'pass-phrase', 'passPhrase', 'passwords', 'passwds', 'passphrases', 'pass_phrases', 'pass-phrases', 'passPhrases', 'private', 'private_key', 'private-key', 'privateKey', 'privates',... |
class RecipientOverView(APIView):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/recipient/recipient_id.md'
_response()
def get(self, request, recipient_id):
get_request = request.query_params
year = validate_year(get_request.get('year', 'latest'))
(recipient_hash, recipi... |
def test_revert_removes_journal_entries(journal_db):
checkpoint_a = journal_db.record()
assert journal_db.has_checkpoint(checkpoint_a)
checkpoint_b = journal_db.record()
assert journal_db.has_checkpoint(checkpoint_a)
assert journal_db.has_checkpoint(checkpoint_b)
journal_db.discard(checkpoint_b)... |
class DeliveryCheckExtraInfo(AbstractObject):
def __init__(self, api=None):
super(DeliveryCheckExtraInfo, self).__init__()
self._isDeliveryCheckExtraInfo = True
self._api = api
class Field(AbstractObject.Field):
adgroup_ids = 'adgroup_ids'
campaign_ids = 'campaign_ids'
... |
def convert_image(value, level=3):
if (not isinstance(value, str)):
return value
key = value
is_pyface_image = value.startswith('')
if (not is_pyface_image):
search_path = get_resource_path(level)
key = ('%s[%s]' % (value, search_path))
result = image_resource_cache.get(key)
... |
class TestUtil(unittest.TestCase):
def test_compare_coords(self):
self.assertTrue(util.cmp_coords([1, 2, 3], [1, 2, 3]))
self.assertTrue(util.cmp_coords([1, NaN, 3], [1, NaN, 3]))
self.assertFalse(util.cmp_coords([1, 3, 2], [1, 2, 3]))
self.assertFalse(util.cmp_coords([1, 2, NaN], [1... |
def extractTofutranslations1090WordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['tags'] == ['Uncategorized']):
titlemap = [('Ah, Senior Brother is Actually a S... |
def simulate_request_post_query_params(client, path, query_string, **kwargs):
if client.app._ASGI:
pytest.skip('The ASGI implementation does not support RequestOptions.auto_parse_form_urlencoded')
headers = kwargs.setdefault('headers', {})
headers['Content-Type'] = 'application/x-www-form-urlencoded... |
class Migration(migrations.Migration):
dependencies = [('typeclasses', '0013_auto__1922')]
operations = [migrations.AlterField(model_name='tag', name='db_category', field=models.CharField(blank=True, db_index=True, help_text='tag category', max_length=64, null=True, verbose_name='category'))] |
.parametrize('with_spiders', [True, False])
def test_vlti_aperture(with_spiders):
name = 'vlti/pupil'
name += ('_without_spiders' if (not with_spiders) else '')
check_aperture(make_vlti_aperture, 125.0, name, check_normalization=False, check_segmentation=True, with_spiders=with_spiders, zenith_angle=0.0, az... |
def node():
global frontiers, mapData, global1, global2, global3, globalmaps
rospy.init_node('assigner', anonymous=False)
map_topic = rospy.get_param('~map_topic', 'map')
info_radius = rospy.get_param('~info_radius', 1.0)
info_multiplier = rospy.get_param('~info_multiplier', 3.0)
hysteresis_radi... |
class App(qt.QWidget):
SAMPLE_RATES = {rate: i for (i, rate) in enumerate([8000, 11025, 16000, 22050, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000])}
def __init__(self):
super().__init__()
self.paused = False
self.analyzer = None
self.refAnalyzer = None
self... |
class TestHCTGamut(util.ColorAsserts, unittest.TestCase):
def test_blue(self):
hct = Color('#0000ff').convert('hct')
tones = [100, 95, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
expect = ['#ffffff', '#f1efff', '#e0e0ff', '#bec2ff', '#9da3ff', '#7c84ff', '#5a64ff', '#343dff', '#0000ef', '#0001ac'... |
class ChatMessage(JSONSerializable):
human_message: Optional[BaseMessage] = None
ai_message: Optional[BaseMessage] = None
def add_user_message(self, message: str, metadata: Optional[dict]=None):
if self.human_message:
logging.info('Human message already exists in the chat message, ... |
def gethead(url, data=None, referer=None, h=None):
if h:
headers.update(h)
req = urllib2.Request(url, headers=headers)
if referer:
req.add_header('Referer', referer)
req.get_method = (lambda : 'HEAD')
opener = urllib2.build_opener(PassRedirectHandler)
return opener.open(req, time... |
def test_fill_transaction_defaults_for_all_params(w3):
default_transaction = fill_transaction_defaults(w3, {})
assert (default_transaction == {'chainId': w3.eth.chain_id, 'data': b'', 'gas': w3.eth.estimate_gas({}), 'maxFeePerGas': (w3.eth.max_priority_fee + (2 * w3.eth.get_block('latest')['baseFeePerGas'])), '... |
class EfuseDefineFields(EfuseFieldsBase):
def __init__(self) -> None:
self.EFUSES = []
self.KEYBLOCKS = []
self.BLOCK2_CALIBRATION_EFUSES = []
self.CALC = []
dir_name = os.path.dirname(os.path.abspath(__file__))
(dir_name, file_name) = os.path.split(dir_name)
... |
class CatalogButton(Catalog.CatalogGroup):
def basic(self) -> CssStylesButton.CssButtonBasic:
return self._set_class(CssStylesButton.CssButtonBasic)
def important(self) -> CssStylesButton.CssButtonImportant:
return self._set_class(CssStylesButton.CssButtonImportant)
def reset(self) -> CssSty... |
class TestFlinkRowWriter(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.env = StreamExecutionEnvironment.get_execution_environment()
self.env.add_jars('file://{}'.format(find_jar_path()))
self.env.set_parallelism(1)
self.t_env = StreamTableEnvironment.creat... |
class OptionSeriesVennSonificationTracks(Options):
def activeWhen(self) -> 'OptionSeriesVennSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesVennSonificationTracksActivewhen)
def instrument(self):
return self._config_get('piano')
def instrument(self, text... |
class PlotToolbar(Container, AbstractOverlay):
buttons = List(Type(ToolbarButton))
hiding = Bool(True)
auto_hide = Bool(True)
end_radius = Float(4.0)
button_spacing = Float(5.0)
horizontal_padding = Float(5.0)
vertical_padding = Float(5.0)
location = Enum('top', 'right', 'bottom', 'left'... |
def unwrap_edges_pipe(self, context, padding):
me = bpy.context.active_object.data
bm = bmesh.from_edit_mesh(me)
uv_layers = bm.loops.layers.uv.verify()
for face in bm.faces:
if face.select:
bpy.ops.mesh.select_all(action='DESELECT')
self.report({'INFO'}, 'No faces should... |
class meter_features_stats_reply(stats_reply):
version = 4
type = 19
stats_type = 11
def __init__(self, xid=None, flags=None, features=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
... |
class TestC(TestCase):
def test_quadratic(self):
dimensions = 1
M = 12
param = Parameter(distribution='Uniform', lower=0, upper=1.0, order=2)
myParameters = [param for i in range(dimensions)]
x_train = np.asarray([0.0, 0.0714, 0.1429, 0.2857, 0.3571, 0.4286, 0.5714, 0.6429, 0... |
def test_missing_other_thlr(tmpdir, merge_lis_prs, assert_log):
fpath = os.path.join(str(tmpdir), 'missing_other_th.lis')
content = ['data/lis/records/RHLR-1.lis.part', 'data/lis/records/THLR-1.lis.part', 'data/lis/records/FHLR-1.lis.part', 'data/lis/records/FTLR-1.lis.part', 'data/lis/records/TTLR-1.lis.part',... |
def double_fpds_awards_with_same_special_case_recipients(award_count_sub_schedule, award_count_submission, defc_codes):
transaction_fpds_1 = baker.make('search.TransactionSearch', transaction_id=7, award_id=600, type='A', action_date='2022-05-01', fiscal_action_date='2022-09-01', is_fpds=True, recipient_name='MULTI... |
def test_generate_gpu_will_end_up_with_an_empty_scene(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
gen = RepresentationGenerator(version=data['building1_yapi_model_main_v003'])
gen.generate_gpu()
assert (pm.sceneName() == '') |
def m2_tests(verbose=1):
if (verbose > 0):
print(('-' * 70))
print('Running TVTK tests.')
tests = find_tests(['tvtk'])
err = run(tests, verbose)
if (verbose > 0):
print(('-' * 70))
print('Running Mayavi tests.')
tests = find_tests(['mayavi'])
err += run(tests, ver... |
def test_nested_and_object_inner_doc():
class MySubDocWithNested(MyDoc):
nested_inner = field.Nested(MyInner)
props = MySubDocWithNested._doc_type.mapping.to_dict()['properties']
assert (props == {'created_at': {'type': 'date'}, 'inner': {'properties': {'old_field': {'type': 'text'}}, 'type': 'objec... |
class Monitors(object):
swagger_types = {'embedded': 'MonitorsEmbedded'}
attribute_map = {'embedded': '_embedded'}
def __init__(self, embedded=None):
self._embedded = None
self.discriminator = None
if (embedded is not None):
self.embedded = embedded
def embedded(self)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.