code stringlengths 281 23.7M |
|---|
.parametrize('restrictions', [(('+',), ('+',)), (('+',), ('-',)), (('-',), ('+',)), (('-', '+'), ('+', '+')), (('-', '+'), ('-', '+')), (('-', '+'), ('+', '-')), (('-', '+'), ('-', '-')), (('+', '+'), ('+', '+')), (('+', '+'), ('-', '+')), (('+', '+'), ('+', '-')), (('+', '+'), ('-', '-')), (('-', '-'), ('+', '+')), ((... |
def parse_config(file):
parser = ConfigParser()
with open(file, 'rt') as fh:
parser.read_string(('[cvehound]\n' + fh.read()))
config = dict(parser['cvehound'])
for key in ['cve', 'exclude', 'cwe', 'files', 'ignore_files']:
if (key not in config):
continue
config[key] ... |
def test_create_multi_namespace():
test_registry = catalogue.create('x', 'y')
_registry.register('z')
def z():
pass
items = test_registry.get_all()
assert (len(items) == 1)
assert (items['z'] == z)
assert catalogue.check_exists('x', 'y', 'z')
assert (catalogue._get(('x', 'y', 'z'... |
def extractMuchadoaboutbluebottlesBlogspotCom(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, n... |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsPointgrouping(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, f... |
class TestCmdSet(BaseEvenniaTest):
def test_cmdset_remove_by_key(self):
test_cmd_set = _CmdSetTest()
test_cmd_set.remove('another command')
self.assertNotIn(_CmdTest2, test_cmd_set.commands)
def test_cmdset_gets_by_key(self):
test_cmd_set = _CmdSetTest()
result = test_cmd... |
class TestParseRankList(unittest.TestCase):
def test_comma_separated(self):
comma_rank_list = '0,2,4,6'
bootstrap_info = bootstrap_info_test()
bootstrap_info.world_size = 8
parsed_rank_list = comms_utils.parseRankList(comma_rank_list)
self.assertEqual(4, len(parsed_rank_list)... |
class TestArraySourceAttributes(unittest.TestCase):
def setUp(self):
s1 = numpy.ones((2, 2))
src = ArraySource(scalar_data=s1, scalar_name='s1')
self.src = src
def test_add_attribute_works_for_point_data(self):
src = self.src
s1 = src.scalar_data
s2 = (s1.ravel() ... |
class VectorCutPlane(Module):
__version__ = 0
implicit_plane = Instance(ImplicitPlane, allow_none=False, record=True)
cutter = Instance(Cutter, allow_none=False, record=True)
glyph = Instance(Glyph, allow_none=False, record=True)
actor = Instance(Actor, allow_none=False, record=True)
input_info ... |
def _run_expression_propagation(cfg: ControlFlowGraph) -> None:
options = Options()
options.set('expression-propagation-function-call.maximum_instruction_complexity', 10)
options.set('expression-propagation-function-call.maximum_branch_complexity', 10)
options.set('expression-propagation-function-call.m... |
class FlicketUser(PaginatedAPIMixin, UserMixin, Base):
__tablename__ = 'flicket_users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(user_field_size['username_max']), index=True, unique=True)
name = db.Column(db.String(user_field_size['name_max']))
password = db.Column(... |
class OptionSeriesParetoSonificationDefaultinstrumentoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num... |
class Not(UnaryOp):
__slots__ = ()
__hash__ = Expr.__hash__
opstr = not_sym
def neg(self):
return self.elem
_coconut_tco
def simplify(self, **kwargs):
if (self.neg == top):
return bot
elif (self.neg == bot):
return top
elif isinstance(self.... |
((API + '.get_dataset_identity'), MagicMock(return_value={'dataset_rid': DATASET_RID, 'dataset_path': DATASET_PATH, 'last_transaction_rid': TRANSACTION_RID}))
((API + '.get_dataset'), MagicMock())
((API + '.get_branch'), MagicMock())
((API + '.is_dataset_in_trash'), MagicMock(return_value=False))
((API + '.open_transac... |
class OptionSeriesWindbarbDataEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
d... |
class HelloWithBody(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running Hello test')
logging.info('Sending Hello...')
request = ofp.message.hello()
request.data = 'OpenFlow Will Rule The World'
self.controller.message_send(request)
logging.info('Wait... |
def verify_zip(zip_file: ZipFile, max_file_size: Optional[int]=None) -> None:
if (max_file_size is None):
max_file_size = MAX_FILE_SIZE
for file_info in zip_file.infolist():
file_size = 0
with zip_file.open(file_info) as file:
for chunk in iter((lambda f=file: f.read(CHUNK_SI... |
class Metric_Limit(Config_Item):
def __init__(self, metric_name, enabled, limit=None):
super().__init__()
assert isinstance(metric_name, str)
assert ((metric_name in METRICS) or (metric_name == '*'))
assert isinstance(enabled, bool)
assert (isinstance(limit, int) or (limit is... |
class AdPlacement(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isAdPlacement = True
super(AdPlacement, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
bundle_id = 'bundle_id'
display_format = 'display_format'
... |
class Temperature(IntervalModule, ColorRangeModule):
settings = (('format', 'format string used for output. {temp} is the temperature in degrees celsius'), ('display_if', 'snippet that gets evaluated. if true, displays the module output'), ('lm_sensors_enabled', 'whether or not lm_sensors should be used for obtaini... |
class DistributedActors():
def __init__(self, env_factory: Callable[([], Union[(StructuredEnv, StructuredEnvSpacesMixin, LogStatsEnv)])], policy: TorchPolicy, n_rollout_steps: int, n_actors: int, batch_size: int):
self.env_factory = env_factory
self.policy = policy
self.n_rollout_steps = n_r... |
class FlowRemoveAll(base_tests.SimpleProtocol):
def runTest(self):
for i in range(1, 5):
logging.debug('Adding flow %d', i)
request = ofp.message.flow_add(buffer_id=ofp.OFP_NO_BUFFER, priority=(i * 1000))
self.controller.message_send(request)
do_barrier(self.contr... |
class MarkerHandler():
decision_context: DecisionContext
marker_name: str
mutable_marker_results: Dict[(str, MarkerResult)] = field(default_factory=dict)
def record_mutable_marker(self, id: str, event_id: int, data: Dict[(str, Payloads)], access_count: int):
marker = MarkerData.create(id=id, eve... |
class Comment(Instruction):
STYLES = {'C': ('/*', '*/'), 'html': ('todo', 'todo'), 'debug': ('##', '##')}
DEFAULT_STYLE = 'C'
def __init__(self, comment: str, comment_style: str='C', tags: Optional[Tuple[(Tag, ...)]]=None):
super().__init__(tags)
self._comment = comment
self._comment... |
def multi_lastz_runner(log, output, cores, target, query, huge, coverage=83, identity=92.5, size=):
if (not huge):
with open(target, 'rb') as f:
tb = twobit.TwoBitFile(f)
tb_keys = [i.decode('utf-8') for i in tb.keys()]
chromos = [os.path.join(target, c) for c in tb_keys]
... |
class MyApp(App):
def build(self):
box1 = BoxLayout(orientation='vertical')
box2 = BoxLayout()
box1.add_widget(box2)
label = Label(text='Olar Mundo')
label.font_size = 50
text_input = TextInput()
btn = Button(text='Butaum', on_press=on_press, on_release=on_rel... |
class Client(object):
def __init__(self):
self.gcs_client = gcs.Client(project=settings.BQ_PROJECT)
def bucket(self):
return self.gcs_client.bucket(settings.BQ_PROJECT)
def get_bucket(self):
return self.gcs_client.get_bucket(settings.BQ_PROJECT)
def __getattr__(self, name):
... |
(scope='session', autouse=True)
def fideslang_data_categories(db):
cats = []
for obj in DEFAULT_TAXONOMY.data_category:
try:
cats.append(DataCategoryDbModel.from_fideslang_obj(obj).save(db))
except IntegrityError:
pass
(yield cats)
for cat in cats:
try:
... |
class CharacterCmdSet(CmdSet):
key = 'DefaultCharacter'
priority = 0
def at_cmdset_creation(self):
self.add(general.CmdLook())
self.add(general.CmdHome())
self.add(general.CmdInventory())
self.add(general.CmdPose())
self.add(general.CmdNick())
self.add(general... |
class MacToPort(collections.defaultdict):
def __init__(self):
super(MacToPort, self).__init__(set)
def add_port(self, dpid, port_no, mac_address):
self[mac_address].add(MacPort(dpid, port_no))
def remove_port(self, dpid, port_no, mac_address):
ports = self[mac_address]
ports.... |
class TestLoggingUsingAdminPermissions(CoprsTestCase):
('coprs.app.logger', return_value=MagicMock())
.usefixtures('f_users', 'f_coprs', 'f_db')
def test_update_copr(self, log):
CoprsLogic.update(self.u1, self.c2)
log.info.assert_called_with("Admin '%s' using their permissions to update proj... |
_deserializable
class OpenSearchDB(BaseVectorDB):
BATCH_SIZE = 100
def __init__(self, config: OpenSearchDBConfig):
if (config is None):
raise ValueError('OpenSearchDBConfig is required')
self.config = config
self.client = OpenSearch(hosts=[self.config.opensearch_url], **self... |
def gif_query(query, limit=3):
try:
url = (config.host + ('/giphy/search?limit=%s&query=%s' % (limit, query)))
r = requests.get(url, headers=headers)
return r.json()
except requests.exceptions.RequestException as e:
print('Something went wrong. Could not get your gifs:', e) |
class OptionPlotoptionsDependencywheelTooltipDatetimelabelformats(Options):
def day(self):
return self._config_get('%A, %e %b %Y')
def day(self, text: str):
self._config(text, js_type=False)
def hour(self):
return self._config_get('%A, %e %b, %H:%M')
def hour(self, text: str):
... |
class OptionSeriesItemSonificationContexttracksMappingPitch(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('y')
def mapTo(self, text: str):
self.... |
_set_stats_type(ofproto.OFPMP_EXPERIMENTER, OFPExperimenterMultipart)
_set_msg_type(ofproto.OFPT_MULTIPART_REQUEST)
class ONFFlowMonitorStatsRequest(OFPExperimenterStatsRequestBase):
def __init__(self, datapath, flags, body=None, type_=None, experimenter=None, exp_type=None):
body = (body if body else [])
... |
def extractEternalDreamlandTranslation(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('Amorous Slave Girl' in item['tags']):
return buildReleaseMessageWithType(item, '... |
.network
def test_pooch_download_retry_fails_eventually(monkeypatch):
with TemporaryDirectory() as local_store:
monkeypatch.setattr(core, 'hash_matches', FakeHashMatches(3).hash_matches)
path = Path(local_store)
pup = Pooch(path=path, base_url=BASEURL, registry=REGISTRY, retry_if_failed=1)
... |
class ResonanceHandler(THBEventHandler):
interested = ['action_done']
def handle(self, evt_type, act):
if ((evt_type == 'action_done') and isinstance(act, Attack)):
src = act.source
tgt = act.target
if (act.cancelled or src.dead or tgt.dead):
return ac... |
def test_form_args():
(app, db, admin) = setup()
class BaseModel(peewee.Model):
class Meta():
database = db
class Model(BaseModel):
test = peewee.CharField(null=False)
Model.create_table()
shared_form_args = {'test': {'validators': [validators.Regexp('test')]}}
view =... |
def test_list_tenants(sample_tenant):
page = tenant_mgt.list_tenants()
result = None
for tenant in page.iterate_all():
if (tenant.tenant_id == sample_tenant.tenant_id):
result = tenant
break
assert isinstance(result, tenant_mgt.Tenant)
assert (result.tenant_id == samp... |
.parametrize('fork_fn,vm_class', ((frontier_at, FrontierVM), (homestead_at, HomesteadVM), (tangerine_whistle_at, TangerineWhistleVM), (spurious_dragon_at, SpuriousDragonVM), (byzantium_at, ByzantiumVM), (constantinople_at, ConstantinopleVM), (petersburg_at, PetersburgVM), (istanbul_at, IstanbulVM), (muir_glacier_at, Mu... |
def test_omega():
data = np.array([0.0089, 0.0012, (- 0.002), 0.01, (- 0.0002), 0.02, 0.03, 0.01, (- 0.003), 0.01, 0.0102, (- 0.01)])
mar = 0.01
omega = perf.omega(data, target_rtn=mar, log=True)
assert np.isclose(omega, 0.)
df = pd.DataFrame(data)
omega = perf.omega(df, target_rtn=mar, log=True... |
def get_color_balls_to_be_potted(shot: System, legal: bool, ball_call: str) -> List[str]:
color_balls_to_be_potted = [ball_id for (ball_id, info) in ball_infos_dict.items() if (info.color and (info.points >= ball_info(get_lowest_pottable(shot)).points))]
if ((not legal) and is_ball_pocketed(shot, ball_call)):
... |
class JFCCommittee(BaseModel):
__tablename__ = 'fec_form_1s_vw'
idx = db.Column('sub_id', db.Integer, primary_key=True)
committee_id = db.Column('cmte_id', db.String, doc=docs.COMMITTEE_ID)
joint_committee_id = db.Column('joint_cmte_id', db.String, doc=docs.COMMITTEE_ID)
joint_committee_name = db.Co... |
def extractNegativeInserts(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, post... |
def test_check_flags():
parser = Parser()
(valid, fields, sort_by, max_width, unique, nonzero, output_format, ipv4_only, ipv6_only, ipv4_and_ipv6) = parser._check_flags({'fields': 'all'}, '')
assert (fields == ['ID', 'MAC Address', 'Switch', 'Port', 'VLAN', 'IPv4', 'IPv4 Subnet', 'IPv6', 'IPv6 Subnet', 'Eth... |
def generate_withdrawals_dict(n: Optional[int]=None):
num_countries = 5
countries = [f'country_{i}' for i in range(num_countries)]
country_dist = ([0.9] + ([(0.1 / num_countries)] * (num_countries - 1)))
num_users = 500
users = [f'user_{i}' for i in range(num_users)]
for _ in (range(n) if (n is ... |
def test_aliased_problems_8():
(x0, x1, x2, x3) = [Variable('x', Integer.int32_t(), i) for i in range(4)]
(y0, y1, y2) = [Variable('y', Integer.int32_t(), i, is_aliased=True) for i in range(3)]
cfg = ControlFlowGraph()
cfg.add_nodes_from([(start := BasicBlock(0, instructions=[Assignment(ListOperation([]... |
def test_no_horiz_jump():
mesh = UnitTriangleMesh()
mesh = ExtrudedMesh(mesh, 1)
DG = FunctionSpace(mesh, 'DG', 0)
u = TestFunction(DG)
(_, _, z) = SpatialCoordinate(mesh)
form = (jump((z * u)) * dS_h)
assert np.allclose(assemble(Tensor(form)).dat.data, assemble(form).dat.data) |
def _handle_items(trees, notify):
if trees:
raise ValueError('Unexpected tree: {!r}'.format(trees))
return (((expression_module.trait('items', notify=notify, optional=True) | expression_module.dict_items(notify=notify, optional=True)) | expression_module.list_items(notify=notify, optional=True)) | expre... |
def pct_to_log_return(pct_returns, fillna=True):
if _is_pandas(pct_returns):
if fillna:
pct_returns = pct_returns.fillna(0)
return np.log(((1 + pct_returns) + 1e-08))
else:
if fillna:
pct_returns = np.nan_to_num(pct_returns)
return np.log(((1 + pct_returns... |
class Worker(QRunnable):
class Signals(QObject):
task_name = Signal(str)
result = Signal(tuple)
error = Signal(tuple)
finished = Signal()
def __init__(self, binary_view: BinaryView, function: Function):
super(Worker, self).__init__()
self.binary_view = binary_view... |
class PurePath(pathlib.PurePath):
__slots__ = ()
def __new__(cls, *args: str) -> 'PurePath':
if (cls is PurePath):
cls = (PureWindowsPath if (os.name == 'nt') else PurePosixPath)
if (not util.PY312):
return cls._from_parts(args)
else:
return object.__n... |
def load_results_manually(qtbot, gui, case_name='default'):
def handle_load_results_dialog():
dialog = wait_for_child(gui, qtbot, ClosableDialog)
panel = get_child(dialog, LoadResultsPanel)
case_selector = get_child(panel, CaseSelector)
index = case_selector.findText(case_name, Qt.Ma... |
def reachable_nodes(adjacency_list: Dict[(T, Set[T])], starting_nodes: Set[T]) -> Dict[(T, Set[T])]:
all_nodes = set()
for (node, nodes) in adjacency_list.items():
all_nodes.add(node)
all_nodes.update(nodes)
enforce(all(((s in all_nodes) for s in starting_nodes)), f'These starting nodes are ... |
def test_simple_model_roundtrip_bytes_serializable_attrs():
fwd = (lambda model, X, is_train: (X, (lambda dY: dY)))
attr = SerializableAttr()
assert (attr.value == 'foo')
assert (attr.to_bytes() == b'foo')
model = Model('test', fwd, attrs={'test': attr})
model.initialize()
_attr.register(Ser... |
class BaseEyeTracker():
def __init__(self):
pass
def calibrate(self):
pass
def close(self):
pass
def connected(self):
pass
def drift_correction(self, pos=None, fix_triggered=False):
pass
def fix_triggered_drift_correction(self, pos=None, min_samples=30, ma... |
def with_plugins(plugins: Iterable[pkg_resources.EntryPoint]) -> Callable:
def decorator(group: click.Group) -> click.Group:
if (not isinstance(group, click.Group)):
raise TypeError('Plugins can only be attached to an instance of click.Group()')
for entry_point in (plugins or ()):
... |
def ovlp3d_04(ax, da, A, bx, db, B):
result = numpy.zeros((1, 15), dtype=float)
x0 = (0.5 / (ax + bx))
x1 = ((ax + bx) ** (- 1.0))
x2 = ((x1 * ((ax * A[0]) + (bx * B[0]))) - B[0])
x3 = ((ax * bx) * x1)
x4 = numpy.exp(((- x3) * ((A[0] - B[0]) ** 2)))
x5 = (1. * numpy.sqrt(x1))
x6 = (x4 * ... |
class OptionSeriesWordcloudRotation(Options):
def from_(self):
return self._config_get(0)
_.setter
def from_(self, num: float):
self._config(num, js_type=False)
def orientations(self):
return self._config_get(2)
def orientations(self, num: float):
self._config(num, js... |
class ChooseIndividualCardInputlet(Inputlet):
def __init__(self, initiator: Any, cards: List[Card]):
self.initiator = initiator
self.cards = cards
self.selected: Optional[Card] = None
def parse(self, data):
try:
cid = data
check(isinstance(cid, int))
... |
class SatisfactionRatingRequest(BaseZendeskRequest):
def post(self, ticket_id, satisfaction_rating):
payload = self.build_payload(satisfaction_rating)
url = self.api._build_url(EndpointFactory('satisfaction_ratings').create(id=ticket_id))
return self.api._post(url, payload)
def put(self,... |
def process_shot(shot: Shot, info: dict, image_path: Path, output_dir: Path, cfg: DictConfig) -> List[Shot]:
if (not image_path.exists()):
return None
image_orig = cv2.imread(str(image_path))
max_size = cfg.max_image_size
pano_offset = None
camera = shot.camera
(camera.width, camera.heig... |
def test_process_connection_ids_not_specified():
builder = AEABuilder()
builder.set_name('aea_1')
builder.add_private_key('fetchai')
with pytest.raises(ValueError, match='Connection ids .* not declared in the configuration file.'):
builder._process_connection_ids([ConnectionConfig('conn', 'autho... |
.skipif((not has_mxnet), reason='needs MXNet')
def test_mxnet_wrapper_train_overfits(model: Model[(Array2d, Array2d)], X: Array2d, Y: Array1d, answer: int):
optimizer = Adam()
for i in range(100):
(guesses, backprop) = model(X, is_train=True)
d_guesses = ((guesses - Y) / guesses.shape[0])
... |
class sRGB(RGBish, Space):
BASE = 'srgb-linear'
NAME = 'srgb'
CHANNELS = (Channel('r', 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT), Channel('g', 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT), Channel('b', 0.0, 1.0, bound=True, flags=FLG_OPT_PERCENT))
CHANNEL_ALIASES = {'red': 'r', 'green': 'g', 'blue': ... |
def test_account_db_update_then_make_root_then_read(account_db):
assert (account_db.get_storage(ADDRESS, 1) == 0)
account_db.set_storage(ADDRESS, 1, 2)
assert (account_db.get_storage(ADDRESS, 1) == 2)
account_db.make_state_root()
assert (account_db.get_storage(ADDRESS, 1) == 2)
account_db.persis... |
(array=arrays(np.float32, shape=array_shapes(min_dims=3, max_dims=3)), name=st.text(ascii_letters, min_size=8, max_size=8))
(suppress_health_check=[HealthCheck.function_scoped_fixture])
def test_that_binary_export_and_import_are_inverses(array, name, tmp_path):
masked_array = np.ma.masked_invalid(array)
export_... |
_argument_doc
def parse_return_annotation(return_annotation: type, deconstruct_dataclass_return_type: bool, single_return_param_name: str) -> Tuple[(Optional[Dict[(str, type)]], bool)]:
return_types = None
unpack_return = False
if (return_annotation is not Parameter.empty):
if (return_annotation is ... |
def extractWhitemoonxblacksunCa(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) ... |
class TestSpeakersCallValidation(OpenEventTestCase):
def test_date_db_populate(self):
with self.app.test_request_context():
schema = SpeakersCallSchema()
SpeakersCallFactory()
original_data = {'data': {'id': 1}}
data = {}
SpeakersCallSchema.validat... |
class BytesField(CharField[bytes]):
encoding: str = sys.getdefaultencoding()
errors: str = 'strict'
def __init__(self, *, encoding: Optional[str]=None, errors: Optional[str]=None, **kwargs: Any) -> None:
if (encoding is not None):
self.encoding = encoding
if (errors is not None):... |
(init=True, repr=True, eq=True, frozen=True)
class Config(object):
platform: PlatformConfig = PlatformConfig()
secrets: SecretsConfig = SecretsConfig()
stats: StatsConfig = StatsConfig()
data_config: DataConfig = DataConfig()
local_sandbox_path: str = tempfile.mkdtemp(prefix='flyte')
def with_pa... |
def _dnsify(value: str) -> str:
res = ''
MAX = 63
HASH_LEN = 10
if (len(value) >= MAX):
h = _sha224(value.encode('utf-8')).hexdigest()[:HASH_LEN]
value = '{}-{}'.format(h, value[(- ((MAX - HASH_LEN) - 1)):])
for ch in value:
if ((ch == '_') or (ch == '-') or (ch == '.')):
... |
class OptionPlotoptionsBarSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsBarSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsBarSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionPlotoptionsBarSonificationTracks... |
class Message(BaseMessage):
__slots__ = ['_auto_decode', '_decode_cache']
def __init__(self, channel, auto_decode=True, **message):
super(Message, self).__init__(channel, **message)
self._decode_cache = dict()
self._auto_decode = auto_decode
def create(channel, body, properties=None)... |
class CtlUnary(form):
_fields = ('op', 'child')
_attributes = ('lineno', 'col_offset')
def __init__(self, op, child, lineno=0, col_offset=0, **ARGS):
form.__init__(self, **ARGS)
self.op = op
self.child = child
self.lineno = int(lineno)
self.col_offset = int(col_offset... |
def test_print_coverage(plugintester, mocker):
mocker.spy(output, '_build_coverage_output')
plugintester.runpytest('--coverage')
assert (output._build_coverage_output.call_count == 1)
plugintester.runpytest()
assert (output._build_coverage_output.call_count == 1)
plugintester.runpytest('-C')
... |
class VoiceSettings(API):
stability: float = Field(..., ge=0.0, le=1.0)
similarity_boost: float = Field(..., ge=0.0, le=1.0)
style: Optional[float] = Field(0.0, ge=0.0, le=1.0)
use_speaker_boost: Optional[bool] = False
def from_voice_id(cls, voice_id: str) -> VoiceSettings:
url = f'{api_base... |
class OptionPlotoptionsPieSonificationDefaultspeechoptionsPointgrouping(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):... |
def _validate_saml_provider_id(provider_id):
if (not isinstance(provider_id, str)):
raise ValueError('Invalid SAML provider ID: {0}. Provider ID must be a non-empty string.'.format(provider_id))
if (not provider_id.startswith('saml.')):
raise ValueError('Invalid SAML provider ID: {0}.'.format(pr... |
class EmmetRenameTag(sublime_plugin.TextCommand):
def run(self, edit, **kw):
selection = self.view.sel()
sels = list(selection)
sel_cleared = False
for s in sels:
syntax_name = syntax.from_pos(self.view, s.begin())
if syntax.is_html(syntax_name):
... |
class TestLoggingUsersLogic(CoprsTestCase):
('coprs.app.logger', return_value=MagicMock())
.usefixtures('f_users', 'f_db')
def test_user_get(self, log):
UsersLogic.get('somebody')
log.info.assert_called_once_with("Querying user '%s' by username", 'somebody')
('coprs.app.logger', return_v... |
def __ranking_metrics_heuristic(topology, od_pairs=None):
if (od_pairs is None):
od_pairs = od_pairs_from_topology(topology)
(fan_in, fan_out) = fan_in_out_capacities(topology)
degree = topology.degree()
min_capacity = {(u, v): min(fan_out[u], fan_in[v]) for (u, v) in od_pairs}
min_degree = ... |
.parametrize('sender,nonce,expected', (('0x39fA8c5f2793459D6622857E7D9FbB4BD91766d3', 8, '0xc083e9947Cf02b8FfC7D3090AE9AEA72DF98FD47'), ('0x39fa8c5f2793459d6622857e7d9fbb4bd91766d3', 8, '0xc083e9947Cf02b8FfC7D3090AE9AEA72DF98FD47'), ('0x18dd4e0eb8699ea4fee238de41ecfb95e32272f8', 0, '0x3845badAde8e6dFFd1F14bD3903a5d0'))... |
def get_reports_mapping(period_dir: Text) -> Dict[(Text, Path)]:
names: List[Text] = []
paths: List[Path] = []
for filename in os.listdir(period_dir):
if (not filename.startswith('.')):
paths.append(Path(f'{period_dir}/{filename}'))
paths.sort()
for path in paths:
name: T... |
class OptionPlotoptionsScatterDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag... |
class OptionSeriesBarSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesBarSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesBarSonificationTracksMappingHighpassFrequency)
def resonance(self) -> 'OptionSeriesBarSonificationTra... |
def get_scheme_names(is_jp: bool, scheme_data: list[list[int]]) -> dict[(int, str)]:
file_data = game_data_getter.get_file_latest('resLocal', 'localizable.tsv', is_jp)
if (file_data is None):
helper.error_text('Failed to get scheme names')
return {}
localizable = csv_handler.parse_csv(file_d... |
class OptionSeriesPyramidPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
d... |
def extractGa7AxyTranslationsBlogspotCom(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 getAspect(obj1, obj2, aspList):
ap = _getActivePassive(obj1, obj2)
aspDict = _aspectDict(ap['active'], ap['passive'], aspList)
if (not aspDict):
aspDict = {'type': const.NO_ASPECT, 'orb': 0, 'separation': 0}
aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict)
return Aspect(... |
def example_text(NLP):
try:
examples = importlib.import_module((('spacy.lang.' + NLP.lang) + '.examples'))
sentences = examples.sentences
except Exception:
sentences = ['This is a sentence.', 'This is another sentence.']
punct_fixed = []
sent_sep = ' '
for sent in sentences:
... |
class TestWebaruba(TestCase):
def setUp(self) -> None:
self.session = Session()
self.adapter = Adapter()
self.session.mount(' self.adapter)
def test_fetch_production(self):
self.adapter.register_uri(GET, PRODUCTION_URL, json=json.loads(resources.files('parsers.test.mocks.AW').joi... |
class DockSection(DockGroup):
is_row = Bool(True)
splitters = List(DockSplitter)
dock_window = Instance('pyface.dock.dock_window.DockWindow')
modified = Property
_property
def _get_owner(self):
if (self.dock_window is not None):
return self.dock_window
if (self.parent... |
class DewolfNotifications(UIContextNotification):
def __init__(self, widget):
UIContextNotification.__init__(self)
self.widget = widget
self.widget.destroyed.connect(self.destroyed)
UIContext.registerNotification(self)
def destroyed(self):
UIContext.unregisterNotification... |
def extractHornytranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Junior High School Sex Slave Runa', 'Junior High School Sex Slave Runa', 'translated'),... |
class PluginStore(CRUDMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.Unicode(255), nullable=False)
value = db.Column(db.PickleType, nullable=False)
value_type = db.Column(db.Enum(SettingValueType), nullable=False)
extra = db.Column(db.PickleType, nullable=True)
... |
def test_resolve_prefilled_values():
class Language(object):
def __init__(self):
...
_registry.optimizers('prefilled.v1')
def prefilled(nlp: Language, value: int=10):
return (nlp, value)
config = {'test': {'': 'prefilled.v1', 'nlp': Language(), 'value': 50}}
resolved = my... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.