code stringlengths 281 23.7M |
|---|
class AbstractMibInstrumController(object):
def readMibObjects(self, *varBinds, **context):
raise error.NoSuchInstanceError(idx=0)
def readNextMibObjects(self, *varBinds, **context):
raise error.EndOfMibViewError(idx=0)
def writeMibObjects(self, *varBinds, **context):
raise error.NoS... |
class OptionSeriesAreaDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, js_typ... |
def debug_cfg(cunit, mh):
assert isinstance(cunit, Compilation_Unit)
assert isinstance(mh, Message_Handler)
class Function_Visitor(AST_Visitor):
def visit(self, node, n_parent, relation):
if isinstance(node, (Function_Definition, Script_File)):
cfg = build_cfg(node)
c... |
class MultiLineEdit(Widget):
DEFAULT_MIN_SIZE = (100, 50)
CSS = '\n .flx-MultiLineEdit {\n resize: none;\n overflow-y: scroll;\n color: #333;\n padding: 0.2em 0.4em;\n border-radius: 3px;\n border: 1px solid #aaa;\n margin: 2px;... |
class ComputeErrorSolutionHintTemplate(Enum):
CLUSTER_DEFINITION_WRONG_VALUES = f"Please set container values (cpu, memory, image) as ({CONTAINER_CPU},{CONTAINER_MEMORY},'{CONTAINER_IMAGE}')"
ROLE_WRONG_POLICY = 'Set the policy of {role_name} to {role_policy}.'
ROLE_POLICIES_NOT_FOUND = 'Make sure there are... |
_type(ofproto.OFPTFPT_MATCH)
_type(ofproto.OFPTFPT_WILDCARDS)
_type(ofproto.OFPTFPT_WRITE_SETFIELD)
_type(ofproto.OFPTFPT_WRITE_SETFIELD_MISS)
_type(ofproto.OFPTFPT_APPLY_SETFIELD)
_type(ofproto.OFPTFPT_APPLY_SETFIELD_MISS)
_type(ofproto.OFPTFPT_WRITE_COPYFIELD)
_type(ofproto.OFPTFPT_WRITE_COPYFIELD_MISS)
_type(ofproto... |
class EfuseWafer(EfuseField):
def get(self, from_read=True):
rev_bit0 = self.parent['CHIP_VER_REV1'].get(from_read)
assert (self.parent['CHIP_VER_REV1'].bit_len == 1)
rev_bit1 = self.parent['CHIP_VER_REV2'].get(from_read)
assert (self.parent['CHIP_VER_REV2'].bit_len == 1)
apb... |
def _get_wiki_dump_dl_url(t, **kwargs):
_kwargs = {**config, **kwargs}
w = _kwargs['wiki']
v = _kwargs['version']
n = _WIKI_DL_NAME.format(w=w, t=t, v=v)
dp = _kwargs['dumps_path']
if ((dp is not None) and dp.exists()):
path = dp.joinpath(n)
if path.exists():
return p... |
def random_sdp_bram(luts, name, modules, lines):
sdp_choices = set()
for width in (1, 2, 4, 8, 16, 18, 32, 36):
sdp_choices.add((width, (1, max_address_bits(width))))
for nbram in range(2, (MAX_BRAM + 1)):
sdp_choices.add(((nbram * 32), (1, max_address_bits((nbram * 32)))))
sdp_choic... |
def text2sep_kata(text: str) -> (list, list):
parsed = pyopenjtalk.run_frontend(text)
res = []
sep = []
for parts in parsed:
(word, yomi) = (replace_punctuation(parts['orig']), parts['pron'].replace('', ''))
if yomi:
if re.match(_MARKS, yomi):
if (len(word) > ... |
class Pylint(SimpleTool):
name = 'Pylint'
description = 'runs pylint to check for python errors. By default it runs on the entire project. You can specify a relative path to run on a specific file or module.'
def __init__(self, wd: str='.'):
self.workdir = wd
def func(self, args: str) -> str:
... |
class WebsocketRoutingRule(RoutingRule):
__slots__ = ['f', 'hostname', 'name', 'paths', 'pipeline_flow_close', 'pipeline_flow_open', 'pipeline_flow_receive', 'pipeline_flow_send', 'pipeline', 'prefix', 'schemes']
def __init__(self, router, paths=None, name=None, pipeline=None, schemes=None, hostname=None, prefi... |
class TasksListView(QtWidgets.QListView):
def __init__(self, parent=None, *args, **kwargs):
super(TasksListView, self).__init__(*args, *kwargs, parent=parent)
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
def get_selected_items(self):
selection_model = self.selecti... |
class TestSkillBehaviour(BaseSkillTestCase):
path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'generic_seller')
is_agent_to_agent_messages = False
def setup(cls):
super().setup()
cls.service_registration = cast(GenericServiceRegistrationBehaviour, cls._skill.skill_context.beha... |
class FirewallClientIPSetSettings():
_exceptions
def __init__(self, settings=None):
if settings:
self.settings = settings
else:
self.settings = ['', '', '', '', {}, []]
_exceptions
def __repr__(self):
return ('%s(%r)' % (self.__class__, self.settings))
... |
def test_get_raw_transaction_serialization():
kwargs_arg = ContractApiMessage.Kwargs({'key_1': 1, 'key_2': 2})
msg = ContractApiMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION, ledger_id='some_ledger_id', contract_id='some_contrac... |
class TestHNSW(unittest.TestCase):
def _create_random_points(self, n=100, dim=10):
return np.random.rand(n, dim)
def _create_index(self, vecs, keys=None):
hnsw = HNSW(distance_func=l2_distance, m=16, ef_construction=100)
self._insert_points(hnsw, vecs, keys)
return hnsw
def _... |
def _graphs_dangerous_dereference_in_the_same_block_as_target_and_definition_32bit() -> Tuple[(ControlFlowGraph, ControlFlowGraph)]:
in_cfg = ControlFlowGraph()
x = vars('x', 2, aliased=False)
y = vars('y', 2, aliased=True)
ptr = vars('ptr', 1, aliased=False)
c = const(11)
in_node = BasicBlock(0... |
def convert_list_arguments(*indices):
def decorator(f):
sig = signature(f)
names = tuple(sig.parameters.keys())
(f)
def wrapper(*args, **kwargs):
ba = sig.bind(*args, **kwargs)
ba.apply_defaults()
for i in indices:
if isinstance(i, ... |
class WafRuleAttributes(ModelNormal):
allowed_values = {('publisher',): {'FASTLY': 'fastly', 'TRUSTWAVE': 'trustwave', 'OWASP': 'owasp'}, ('type',): {'STRICT': 'strict', 'SCORE': 'score', 'THRESHOLD': 'threshold'}}
validations = {}
_property
def additional_properties_type():
return (bool, date, ... |
def screenshot(figure=None, mode='rgb', antialiased=False):
if (figure is None):
figure = gcf()
(x, y) = tuple(figure.scene.render_window.size)
figure.scene._lift()
if (mode == 'rgb'):
out = tvtk.UnsignedCharArray()
shape = (y, x, 3)
pixel_getter = figure.scene.render_win... |
class OptionPlotoptionsScatter3dSonificationTracksMappingFrequency(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_set_parameter_frequency(la: LogicAnalyzer, master: SPIMaster, slave: SPISlave):
ppre = 0
spre = 2
master.set_parameters(primary_prescaler=ppre, secondary_prescaler=spre)
la.capture(1, block=False)
slave.write8(0)
la.stop()
(sck,) = la.fetch_data()
write_start = sck[0]
write_... |
def test_cursor_pretty_print_gaps(proc_bar, golden):
output = []
c = _find_stmt(proc_bar, 'x: f32').before()
output.append(_print_cursor(c))
c = _find_stmt(proc_bar, 'for i in _: _').before()
output.append(_print_cursor(c))
c = _find_stmt(proc_bar, 'for j in _: _').before()
output.append(_pr... |
class Regression(object):
def __init__(self, n_iterations, learning_rate):
self.n_iterations = n_iterations
self.learning_rate = learning_rate
def initialize_weights(self, n_features):
limit = (1 / math.sqrt(n_features))
self.w = np.random.uniform((- limit), limit, (n_features,))... |
class TestValidationErrorConvertsTuplesToLists(TestCase):
def test_validation_error_details(self):
error = ValidationError(detail=('message1', 'message2'))
assert isinstance(error.detail, list)
assert (len(error.detail) == 2)
assert (str(error.detail[0]) == 'message1')
assert... |
class OptionSeriesBarDataDragdropDraghandle(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):
self... |
class TestSAExtractionError(unittest.TestCase):
def setUp(self):
TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'chimeric_read_errors.bam')
self.samfile = pysam.AlignmentFile(TESTDATA_FILENAME, 'rb')
self.alignments = list(self.samfile.fetch(until_eof=True))
def test_satag_t... |
class FaucetTaggedTargetedResolutionIPv4RouteTest(FaucetTaggedIPv4RouteTest):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\n faucet_vips: ["10.0.0.254/24"]\n targeted_gw_resolution: True\n routes:\n - route:\n ip_dst: "10.0.1.0/24"\n ... |
class Registered(list):
def __init__(self, bot):
super(Registered, self).__init__()
self.bot = weakref.proxy(bot)
def get_config(self, msg):
for conf in self[::(- 1)]:
if ((not conf.enabled) or (conf.except_self and (msg.sender == self.bot.self))):
continue
... |
class PatientMulti(Model):
primary_keys = ['foo', 'bar']
has_many({'appointments': 'AppointmentMulti'}, {'symptoms': 'SymptomMulti.patient'}, {'doctors': {'via': 'appointments.doctor_multi'}})
foo = Field.string(default=(lambda : uuid4().hex))
bar = Field.string(default=(lambda : uuid4().hex))
name ... |
class MultiLineMagic(BaseMagic):
def score(self, ocr_result: OcrResult) -> float:
if ((ocr_result.num_lines > 1) and (ocr_result.num_blocks == 1) and (ocr_result.num_pars == 1)):
return 50.0
return 0
def transform(self, ocr_result: OcrResult) -> str:
return ocr_result.add_lin... |
def verify_statistics_map(fledge_url, skip_verify_north_interface):
get_url = '/fledge/statistics'
jdoc = utils.get_request(fledge_url, get_url)
actual_stats_map = utils.serialize_stats_map(jdoc)
assert (1 <= actual_stats_map[south_asset_name.upper()])
assert (1 <= actual_stats_map['READINGS'])
... |
def hpluv_to_lch(hpluv: Vector) -> Vector:
(h, s, l) = hpluv
c = 0.0
if (l > (100 - 1e-07)):
l = 100
elif (l < 1e-08):
l = 0
elif (not alg.is_nan(h)):
_hx_max = max_safe_chroma_for_l(l)
c = ((_hx_max / 100) * s)
if (c < ACHROMATIC_THRESHOLD):
h = a... |
class CmdlineOpt(object):
positional_count = 0
SUCCESS = 0
SUCCESS_AND_FULL = 1
FAILURE = 2
nonalpha_rgx = re.compile('[^0-9a-zA-Z\\-\\_]')
def __init__(self):
self.value = None
self.opt = None
self.longopt = None
self.type = None
self.var_name = None
... |
class Reindex():
def __init__(self, ilo, request_body, refresh=True, requests_per_second=(- 1), slices=1, timeout=60, wait_for_active_shards=1, wait_for_completion=True, max_wait=(- 1), wait_interval=9, remote_certificate=None, remote_client_cert=None, remote_client_key=None, remote_filters=None, migration_prefix='... |
def get_all_boards_with_last_threads(offset_limit) -> List[Tuple[(BoardModel, ThreadModel, PostModel)]]:
with session() as s:
q = s.query(BoardOrmModel, ThreadOrmModel, PostOrmModel).filter((BoardOrmModel.id == ThreadOrmModel.board_id), (BoardOrmModel.refno_counter == ThreadOrmModel.refno), (ThreadOrmModel.... |
class meter_config(loxi.OFObject):
def __init__(self, flags=None, meter_id=None, entries=None):
if (flags != None):
self.flags = flags
else:
self.flags = 0
if (meter_id != None):
self.meter_id = meter_id
else:
self.meter_id = 0
... |
def deserialize_fn_generator(msg_context, spec, is_numpy=False):
(yield 'if python3:')
(yield (INDENT + 'codecs.lookup_error("rosmsg").msg_type = self._type'))
(yield 'try:')
package = spec.package
for (type_, name) in spec.fields():
if msg_context.is_registered(type_):
(yield ('... |
class OptionSeriesColumnSonificationContexttracksMappingNoteduration(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):
... |
_os(*metadata.platforms)
def main():
powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
common.execute([powershell, '/c', 'Set-MpPreference', '-ExclusionPath', f'{powershell}'], timeout=10)
common.execute([powershell, '/c', f'Remove-MpPreference -ExclusionPath {powershell}'], time... |
.usefixtures('request_1', 'request_2')
def test_endpoint_hits(dashboard_user, endpoint, session):
response = dashboard_user.get('dashboard/api/endpoints_hits')
assert (response.status_code == 200)
total_hits = sum((row['hits'] for row in response.json))
assert (total_hits == session.query(Request).count... |
class ObjectDB(TypedObject):
db_account = models.ForeignKey('accounts.AccountDB', null=True, verbose_name='account', on_delete=models.SET_NULL, help_text='an Account connected to this object, if any.')
db_sessid = models.CharField(null=True, max_length=32, validators=[validate_comma_separated_integer_list], ver... |
def create_tables(lambdas_data, args):
all_table_data = [ALL_TABLE_HEADERS]
for lambda_data in lambdas_data:
function_data = lambda_data['function-data']
last_invocation = 'N/A (no invocations?)'
if (lambda_data['last-invocation'] != (- 1)):
last_invocation = get_days_ago(dat... |
def convert_mxnet_default_outputs(model: Model, X_Ymxnet: Any, is_train: bool):
(X, Ymxnet) = X_Ymxnet
Y = convert_recursive(is_mxnet_array, mxnet2xp, Ymxnet)
def reverse_conversion(dY: Any) -> ArgsKwargs:
dYmxnet = convert_recursive(is_xp_array, xp2mxnet, dY)
return ArgsKwargs(args=((Ymxnet... |
class MarkReportRead(MethodView):
decorators = [allows.requires(IsAtleastModerator, on_fail=FlashAndRedirect(message=_('You are not allowed to view reports.'), level='danger', endpoint='management.overview'))]
def post(self, report_id=None):
json = request.get_json(silent=True)
if (json is not N... |
class OptionSeriesDependencywheelSonificationDefaultinstrumentoptionsMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self... |
class OptionSeriesVectorDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, js_t... |
class permute(Operator):
def __init__(self):
super().__init__()
self._attrs['op'] = 'permute'
def _infer_shapes(self, x: Tensor) -> List[IntVar]:
output_shapes = []
input_shapes = x.shape()
for dim in self._attrs['dims']:
output_shapes.append(input_shapes[dim]... |
def update_latest_block(db_session, block_number) -> None:
db_session.execute('\n UPDATE latest_block_update\n SET block_number = :block_number, updated_at = current_timestamp;\n INSERT INTO latest_block_update\n (block_number, updated_at)\n SELECT :blo... |
class TupleCommandHandler(MethodCommandHandler):
def handle(self, params: str) -> Payload:
tup = self.get_value()
assert isinstance(tup, tuple)
if (params == '*'):
return tup._asdict()
if (params == '*;'):
return string_from_dict(tup._asdict())
elif (p... |
class OptionPlotoptionsPolygonSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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(... |
.django_db
def test_correct_response_multiple_defc(client, monkeypatch, helpers, elasticsearch_award_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = helpers.post_for_spending_endpoint(client, url, def_codes=['L', 'M'], sort='obligation')
expected_resu... |
class TestHasTraitsHelpersHasNamedTrait(unittest.TestCase):
def test_object_has_named_trait_false_for_trait_list(self):
foo = Foo()
self.assertFalse(helpers.object_has_named_trait(foo.list_of_int, 'bar'), 'Expected object_has_named_trait to return false for {!r}'.format(type(foo.list_of_int)))
d... |
class MoveSteering(MoveTank):
def on_for_rotations(self, steering, speed, rotations, brake=True, block=True):
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on_for_rotations(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), rotations, brake, block)
... |
def get_gpuid(gpu_ids: Dict[(str, str)], gpus: List[GpuType]):
vendors = []
for i in range(len(gpus)):
if (gpus[i].vendor not in vendors):
vendors.append(gpus[i].vendor)
gpuvendor = ''.join(vendors).lower()
if (gpuvendor in gpu_ids):
return gpu_ids[gpuvendor]
else:
... |
class TrivializeTopic(MethodView):
decorators = [login_required, allows.requires(IsAtleastModeratorInForum(), on_fail=FlashAndRedirect(message=_('You are not allowed to trivialize this topic'), level='danger', endpoint=(lambda *a, **k: current_topic.url)))]
def post(self, topic_id=None, slug=None):
topi... |
class QuotedEntryField(Gtk.Entry):
def __init__(self):
Gtk.Entry.__init__(self)
def get_state(self):
return urllib.parse.quote(self.get_text())
def set_state(self, state):
if (isinstance(state, list) or isinstance(state, tuple)):
state = state[0]
self.set_text(url... |
def test():
assert Doc.has_extension('has_number'), 'doc?'
ext = Doc.get_extension('has_number')
assert (ext[2] is not None), 'getter?'
assert ('getter=get_has_number' in __solution__), 'get_has_numbergetter?'
assert ('doc._.has_number' in __solution__), '?'
assert doc._.has_number, 'getter'
... |
class BinaryProjector(Filter):
vmin: float = pd.Field(..., title='Min Value', description='Minimum value to project to.')
vmax: float = pd.Field(..., title='Max Value', description='Maximum value to project to.')
beta: float = pd.Field(1.0, title='Beta', description='Steepness of the binarization, higher me... |
def setup_previews():
global ch_preview_thread
global unloading
unloading = True
if (ch_preview_thread is not None):
ch_preview_thread.kill()
for w in sublime.windows():
for v in w.views():
v.settings().clear_on_change('color_helper.reload')
v.settings().erase... |
class OptionSeriesFunnelStatesInactive(Options):
def animation(self) -> 'OptionSeriesFunnelStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesFunnelStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
se... |
class FixedUInt(int):
MAX_VALUE: ClassVar['FixedUInt']
__slots__ = ()
def __init__(self: T, value: int) -> None:
if (not isinstance(value, int)):
raise TypeError()
if ((value < 0) or (value > self.MAX_VALUE)):
raise ValueError()
def __radd__(self: T, left: int) ->... |
class PuzzleSystemCmdSet(CmdSet):
def at_cmdset_creation(self):
super().at_cmdset_creation()
self.add(CmdCreatePuzzleRecipe())
self.add(CmdEditPuzzle())
self.add(CmdArmPuzzle())
self.add(CmdListPuzzleRecipes())
self.add(CmdListArmedPuzzles())
self.add(CmdUsePu... |
def _calc_bezier(target: float, a: Tuple[(float, float)], b: Tuple[(float, float)], c: Tuple[(float, float)], p1: Tuple[(float, float)], p2: Tuple[(float, float)]) -> float:
if (target in (0, 1)):
return target
if ((target > 1) or (target < 0)):
return _extrapolate(target, p1, p2)
t = _solve... |
def test_get(app, elasticapm_client):
client = TestClient(app)
response = client.get('/', headers={constants.TRACEPARENT_HEADER_NAME: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b-03', constants.TRACESTATE_HEADER_NAME: 'foo=bar,bar=baz', 'REMOTE_ADDR': '127.0.0.1'})
assert (response.status_code == 200)
as... |
class PostCreate(PostBase):
('title')
def validate_title(cls: Any, title: str, **kwargs: Any) -> Any:
if (len(title) == 0):
raise ValueError("Title can't be empty")
elif (len(title) > 100):
raise ValueError('Title is too long')
return title
('summary')
def... |
def filter_firewall_dos_policy6_data(json):
option_list = ['anomaly', 'comments', 'dstaddr', 'interface', 'name', 'policyid', 'service', 'srcaddr', 'status']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)... |
class OptionSeriesBellcurveSonificationDefaultspeechoptionsMappingTime(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 generate_mapcss(options: argparse.Namespace) -> None:
directory: Path = workspace.get_mapcss_path()
icons_with_outline_path: Path = workspace.get_mapcss_icons_path()
scheme: Scheme = Scheme.from_file(workspace.DEFAULT_SCHEME_PATH)
extractor: ShapeExtractor = ShapeExtractor(workspace.ICONS_PATH, work... |
.sphinx(buildername='html', srcdir=os.path.join(SOURCE_DIR, 'heading_slug_func'), freshenv=True)
def test_heading_slug_func(app, status, warning, get_sphinx_app_doctree, get_sphinx_app_output):
app.build()
assert ('build succeeded' in status.getvalue())
warnings = warning.getvalue().strip()
assert (warn... |
def test_custom_medium_to_gds(tmp_path):
geometry = td.Box(size=(2, 2, 2))
(nx, ny, nz) = (100, 90, 80)
x = np.linspace(0, 2, nx)
y = np.linspace((- 1), 1, ny)
z = np.linspace((- 1), 1, nz)
f = np.array([td.C_0])
(mx, my, mz, _) = np.meshgrid(x, y, z, f, indexing='ij', sparse=True)
data ... |
def Commutes_Fissioning(a1, a2, aenv1, aenv2, a1_no_loop_var=False):
(W1, R1, RG1, Red1, All1) = getsets([ES.WRITE_H, ES.READ_H, ES.READ_G, ES.REDUCE, ES.ALL_H], a1)
(W2, R2, RG2, Red2, All2) = getsets([ES.WRITE_H, ES.READ_H, ES.READ_G, ES.REDUCE, ES.ALL_H], a2)
WG1 = get_changing_globset(aenv1)
WG2 = g... |
def main():
if sys.stdout.isatty():
bit_colors = ['\x1b[39m', '\x1b[91m', '\x1b[92m', '\x1b[93m', '\x1b[94m', '\x1b[95m', '\x1b[96m', '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[35m', '\x1b[36m']
colors = {'NONE': '\x1b[0m', 'DUPLICATE': '\x1b[101;97m'}
else:
bit_colors = ['']
... |
def extractRainingblackWordpressCom(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... |
(scope='function', name='data_category')
def fixture_data_category(test_config: FidesConfig) -> Generator:
fides_key = 'foo'
(yield DataCategory(fides_key=fides_key, parent_key=None))
_api.delete(url=test_config.cli.server_url, resource_type='data_category', resource_id=fides_key, headers=CONFIG.user.auth_h... |
class EditorAreaPaneTestCase(unittest.TestCase):
(USING_WX, 'EditorAreaPane is not implemented in WX')
def test_create_editor(self):
area = EditorAreaPane()
area.register_factory(Editor, (lambda obj: isinstance(obj, int)))
self.assertTrue(isinstance(area.create_editor(0), Editor))
(U... |
class OptionSeriesScatterSonificationDefaultspeechoptionsMappingTime(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 TestFetchUpdates(UpdateInfoMetadataTestCase):
('bodhi.server.metadata.log.warning')
def test_build_unassociated(self, warning):
update = self.db.query(Update).one()
update.date_stable = update.date_testing = None
u = base.create_update(self.db, ['TurboGears-1.0.2.2-4.fc17'])
... |
def main():
global action
pygame.init()
pygame.joystick.init()
try:
joystick = pygame.joystick.Joystick(0)
except:
print('Please connect the handle first.')
return
joystick.init()
done = False
start_time = 0
while (not done):
for event_ in pygame.event... |
class LDPBase(metaclass=abc.ABCMeta):
def randomize(self, value):
raise NotImplementedError
def _check_epsilon(cls, epsilon):
if (not (epsilon >= 0)):
raise ValueError('ERR: the range of epsilon={} is wrong.'.format(epsilon))
return epsilon
def _check_value(self, value):
... |
def match_ethernet_dst_address(self, of_ports, priority=None):
pkt_matchdst = simple_eth_packet(eth_dst='00:01:01:01:01:01')
match = parse.packet_to_flow_match(pkt_matchdst)
self.assertTrue((match is not None), 'Could not generate flow match from pkt')
match.wildcards = (ofp.OFPFW_ALL ^ ofp.OFPFW_DL_DST... |
class TestAstNodeSerialization():
def save_and_load(node: AbstractSyntaxTreeNode):
serializer = AstNodeSerializer()
data = serializer.serialize(node)
return serializer.deserialize(data)
.parametrize('node', [SeqNode(true_value(LogicCondition.generate_new_context())), SeqNode(logic_cond('... |
class MicrosoftAudioApi(AudioInterface):
def audio__text_to_speech(self, language: str, text: str, option: str, voice_id: str, audio_format: str, speaking_rate: int, speaking_pitch: int, speaking_volume: int, sampling_rate: int) -> ResponseType[TextToSpeechDataClass]:
speech_config = speechsdk.SpeechConfig(... |
class PGEncryptedString(TypeDecorator):
impl = BYTEA
python_type = String
cache_ok = True
def __init__(self):
super().__init__()
self.passphrase = CONFIG.user.encryption_key
def bind_expression(self, bindparam):
bindparam = type_coerce(bindparam, JSON)
return func.pgp... |
def parse_disc(disc_id, device):
xl_tracks = []
disc_tags = dict()
disc_tags['musicbrainz_albumid'] = disc_id.id
disc_tags['__freedb_disc_id'] = disc_id.freedb_id
if (disc_id.mcn and ('' not in disc_id.mcn)):
disc_tags['__mcn'] = disc_id.mcn
for discid_track in disc_id.tracks:
tr... |
class TestParse(unittest.TestCase):
def test_parse_header(self):
import loxi
(msg_ver, msg_type, msg_len, msg_xid) = ofp.message.parse_header('\x01\x04 e\x124Vx')
self.assertEquals(1, msg_ver)
self.assertEquals(4, msg_type)
self.assertEquals(45032, msg_len)
self.asser... |
def extractNovelEndeavorsCom(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 ... |
class OptionSeriesWordcloudSonificationDefaultinstrumentoptionsMappingPitch(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... |
def check_custom_header(url, header_name):
request_header = {'Access-Control-Request-Headers': header_name}
req_custom_header = requests.options(url, header_name, verify=False)
try:
if (req_custom_header.headers['Access-Control-Allow-Headers'] == header_name):
return True
else:
... |
class Context():
def __init__(self, interpreter, tokenizer=None, truncation_threshold=(- 3e+38)):
self.interpreter = interpreter
self.tokenizer = tokenizer
self.truncation_threshold = truncation_threshold
def __enter__(self):
set_context(self)
return self
def __exit__... |
class CreateTransform(Runner):
async def __call__(self, es, params):
transform_id = mandatory(params, 'transform-id', self)
body = mandatory(params, 'body', self)
defer_validation = params.get('defer-validation', False)
(await es.transform.put_transform(transform_id=transform_id, bod... |
def arrow_actor(color=colors.peacock, opacity=1.0, resolution=24):
source = tvtk.ArrowSource(tip_resolution=resolution, shaft_resolution=resolution)
mapper = tvtk.PolyDataMapper()
configure_input_data(mapper, source.output)
prop = tvtk.Property(opacity=opacity, color=color)
actor = tvtk.Actor(mapper... |
class MyDependencyState(depgraph.DependencyState):
def __init__(self, *args, **kwargs):
super(depgraph.DependencyState, self).__init__(*args, **kwargs)
self.pending_links = set()
def get_done_state(self):
return (self.loc_key, frozenset(self.pending))
def extend(self, loc_key):
... |
def filter_firewall_traffic_class_data(json):
option_list = ['class_id', 'class_name']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribute]
return dicti... |
class Cyclopolis(BikeShareSystem):
sync = True
meta = {'system': 'Cyclopolis', 'company': ['Cyclopolis Systems']}
def __init__(self, tag, mapstyle, feed_url, meta):
super(Cyclopolis, self).__init__(tag, meta)
self.feed_url = feed_url
self.mapstyle = mapstyle
def update(self, scra... |
class AsyncContractCaller(BaseContractCaller):
w3: 'AsyncWeb3'
def __init__(self, abi: ABI, w3: 'AsyncWeb3', address: ChecksumAddress, transaction: Optional[TxParams]=None, block_identifier: BlockIdentifier=None, ccip_read_enabled: Optional[bool]=None, decode_tuples: Optional[bool]=False) -> None:
super... |
class TestSuperFencesCustomLegacyArithmatexGeneric(util.MdCase):
extension = ['pymdownx.superfences']
extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': 'math', 'class': 'arithmatex', 'format': arithmatex.fence_generic_format}]}}
def test_legacy_arithmatex_generic(self):
with w... |
class HTTPURLHandler(PathHandler):
MAX_FILENAME_LEN = 250
def __init__(self) -> None:
super().__init__()
self.cache_map: Dict[(str, str)] = {}
def _get_supported_prefixes(self) -> List[str]:
return [' ' 'ftp://']
def _get_local_path(self, path: str, force: bool=False, cache_dir: ... |
def test_butterworth_returns_correct_value_with_bandstop_filter_type_and_float32_precision(trace):
(b, a) = signal.butter(3, [(.0 / (.0 / 2)), (.0 / (.0 / 2))], 'bandstop')
b = b.astype('float32')
a = a.astype('float32')
expected = signal.lfilter(b, a, trace)
result = scared.signal_processing.butter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.