code stringlengths 281 23.7M |
|---|
def extractAmatertranslationsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('CEO above me below', 'CEO above me below', 'translated')]
for (tagname, name, tl_ty... |
class OptionSeriesVariwideStatesSelectMarker(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._co... |
class FactBackend(FactBase):
PROGRAM_NAME = 'FACT Backend'
PROGRAM_DESCRIPTION = 'Firmware Analysis and Compare Tool (FACT) Backend'
COMPONENT = 'backend'
def __init__(self):
super().__init__()
self.unpacking_lock_manager = UnpackingLockManager()
self._create_docker_base_dir()
... |
def load_processed_data(data_save_dir, classes_save_path, test_ratio=0.2, items_limit_per_label=None):
X = np.load(os.path.join(data_save_dir, ('X_limit_%s.npy' % items_limit_per_label)))
Y = np.load(os.path.join(data_save_dir, ('Y_limit_%s.npy' % items_limit_per_label)))
with open(classes_save_path, 'r') a... |
class TestEos():
def __init__(self, yaml_location):
self._documents = []
self._results = []
if os.path.isdir(yaml_location):
for file in os.listdir(yaml_location):
if (file.endswith('.yml') or file.endswith('.yaml')):
full_path = os.path.join(y... |
class TestLegacyWrappingScheduler():
class SimpleLegacyScheduler():
def __init__(self, params):
pass
def next(self, current):
return current
def setup_method(self, method):
scheduler.register_scheduler('simple', self.SimpleLegacyScheduler)
def teardown_method(... |
def sort_objects(self):
objects = []
bounds = {}
for obj in bpy.context.selected_objects:
if (obj.type == 'MESH'):
objects.append(obj)
bounds[obj] = get_bbox(obj)
print('Objects {}x'.format(len(objects)))
min_side = min(bounds[objects[0]]['size'].x, bounds[objects[0]]... |
def _execute_exploit_query(exploit_id, details):
if (not details):
result = InternalServer.get_mongodb_driver().get_products_by_exploit_db_id(exploit_id)
else:
result = InternalServer.get_mongodb_driver().get_exploit_info_by_id(exploit_id)
if (len(result) == 0):
return (json.dumps({'... |
class Boolean(Field):
errors = {'type': 'Must be a boolean.', 'null': 'May not be null.'}
coerce_values = {'true': True, 'false': False, 'on': True, 'off': False, '1': True, '0': False, '': False, 1: True, 0: False}
coerce_null_values = {'', 'null', 'none'}
def __init__(self, *, coerce_types: bool=True,... |
def extractStrawberryJamNet(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Fox Demon Cultivation Manual', 'Fox Demon Cultivation Manual', 'translated'), ('His Royal Highness, ... |
class OptionPlotoptionsHistogramSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, ... |
class OptionsEditor(Options):
component_properties = ('initialEditType',)
def height(self):
return self._config_get('500px')
def height(self, val):
if isinstance(val, int):
val = ('%spx' % val)
self._config(val)
def initialValue(self):
return self._config_get(... |
class ForwardingRuleRulesEngine(bre.BaseRulesEngine):
RuleViolation = namedtuple('RuleViolation', ['violation_type', 'target', 'rule_index', 'load_balancing_scheme', 'port_range', 'resource_type', 'port', 'ip_protocol', 'ip_address', 'resource_id', 'full_name', 'resource_data', 'resource_name'])
def __init__(se... |
class OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def speed(... |
.skipif((not can_import('magic')), reason='Libmagic is not installed')
def test_flyte_file_type_annotated_hashmethod(local_dummy_file):
def calc_hash(ff: FlyteFile) -> str:
return str(ff.path)
HashedFlyteFile = Annotated[(FlyteFile['jpeg'], HashMethod(calc_hash))]
def t1(path: str) -> HashedFlyteFil... |
(hookwrapper=True)
def pytest_runtest_makereport(item: Item, call: CallInfo):
outcome = (yield)
result = outcome.get_result()
if ((result.when == 'call') and result.failed):
try:
print_windows_coordinates()
except Exception as e:
print('Unable to print windows coordin... |
def as_listener(func=None, signal_name=None):
if ((not func) and signal_name):
def wrapper(func):
func._listener_signal_name = signal_name
return func
return wrapper
signal_name = func.__name__
func._listener_signal_name = signal_name
return func |
class RadioButtonField(ToggleField):
def _create_control(self, parent):
control = wx.RadioButton(parent)
return control
def _set_control_value(self, value):
super()._set_control_value(value)
event = wx.CommandEvent(wx.EVT_RADIOBUTTON.typeId, self.control.GetId())
event.Se... |
def test_publication_date_sort(client, publish_dates_data):
resp = client.get((url + '?fiscal_year=2019&sort=publication_date'))
assert (resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY)
response = resp.json()
assert (response == {'detail': "publication_date sort param must be in the format 'pub... |
.skipif((backend_default == 'numba'), reason='Not supported by Numba')
def test_jit_dict():
from _transonic_testing.for_test_justintime import func_dict
d = dict(a=1, b=2)
func_dict(d)
if (not can_import_accelerator()):
return
mod = modules[module_name]
cjit = mod.jit_functions['func_dic... |
def round_to_n(x, n):
if (isinstance(x, str) or (not math.isfinite(x)) or (not x)):
return x
if (n == 0):
return str(round(x, None))
digits = ((- int(math.floor(math.log10(abs(x))))) + (n - 1))
try:
return str(round(x, (digits or None)))
except ValueError as e:
print(... |
def _load_lexers(module_name):
if module_name.startswith('pygments'):
module_name = module_name.replace('pygments', 'mdpopups.pygments', 1)
mod = __import__(module_name, None, None, ['__all__'])
for lexer_name in mod.__all__:
cls = getattr(mod, lexer_name)
_lexer_cache[cls.name] = cl... |
class ToDotConverter():
ATTRIBUTES = {'color', 'fillcolor', 'label', 'shape', 'style'}
def __init__(self, graph: DiGraph):
self._graph = graph
def write(cls, graph: DiGraph) -> str:
converter = cls(graph)
return converter._create_dot()
def _create_dot(self) -> str:
conten... |
class OptionSeriesCylinderSonificationContexttracksMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesCylinderSonificationContexttracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesCylinderSonificationContexttracksMappingLowpassFrequency)
def resonance(self) -... |
class OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingLowpassResonance(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... |
_after_configure.connect
def setup_scheduled_task(sender, **kwargs):
from celery.schedules import crontab
sender.add_periodic_task(crontab(hour=5, minute=30), send_after_event_mail)
sender.add_periodic_task(crontab(hour=5, minute=30), ticket_sales_end_mail)
sender.add_periodic_task(crontab(minute=0, hou... |
def log_response(self, endpoint_name, params, resp):
if (resp.status_code == 200):
logging.info('fetch_{} response: {}'.format(endpoint_name, resp))
logging.info('params: %s', params)
response_json = json.loads(resp.text)
count = response_json.get('pagination', {}).get('count', None)... |
class CustomAnalysis():
name = 'custom'
def __init__(self, filter_name, builtin_type='custom', **kwargs):
self._builtin_type = builtin_type
self._name = filter_name
super().__init__(**kwargs)
def to_dict(self):
return self._name
def get_definition(self):
d = super... |
class OptionPlotoptionsTreemapDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._confi... |
def get_art(item, server):
art = {'thumb': '', 'fanart': '', 'poster': '', 'banner': '', 'clearlogo': '', 'clearart': '', 'discart': '', 'landscape': '', 'tvshow.fanart': '', 'tvshow.poster': '', 'tvshow.clearart': '', 'tvshow.clearlogo': '', 'tvshow.banner': '', 'tvshow.landscape': ''}
image_tags = item['Image... |
class BackgroundRemovalDataClass(BaseModel):
image_b64: str = Field(..., description='The image in base64 format.')
image_resource_url: str = Field(..., description='The image url.')
def generate_resource_url(img_b64: str, fmt: str='png') -> str:
data = img_b64.encode()
content = BytesIO(bas... |
def register(registry):
handlers = [(MouseClick, (lambda wrapper, _: _interaction_helpers.mouse_click_qwidget(wrapper._target.control, wrapper.delay))), (DisplayedText, (lambda wrapper, _: wrapper._target.control.text()))]
for target_class in [SimpleEditor, CustomEditor]:
for (interaction_class, handler... |
def get_instances(schema=None):
schemas = ([schema] if schema else get_schemas())
for schema in schemas:
data = get_data(schema)
instances = data.get('instances')
for (cls, instance) in _datafile_traversor(data['class'], instances):
(yield (cls, instance)) |
def test_guess_of_dataclass():
class Foo(DataClassJsonMixin):
x: int
y: str
z: typing.Dict[(str, int)]
def hello(self):
...
lt = TypeEngine.to_literal_type(Foo)
foo = Foo(1, 'hello', {'world': 3})
lv = TypeEngine.to_literal(FlyteContext.current_context(), foo,... |
class EntityData():
id: str
unique_id: str
name: str
state: bool
attributes: dict
icon: str
device_name: str
status: str
topic: str
event: str
binary_sensor_device_class: Optional[BinarySensorDeviceClass]
type: str
details: dict
disabled: bool
def __init__(sel... |
class MyPlot(HasTraits):
plot = Instance(Plot)
status_overlay = Instance(StatusLayer)
error_button = Button('Error')
warn_button = Button('Warning')
no_problem_button = Button('No problem')
def _plot_default(self):
index = numpy.array([1, 2, 3, 4, 5])
data_series = (index ** 2)
... |
(name='arrays', params=['single-element', 'multi-element'])
def angles_vectors_as_arrays(request):
if (request.param == 'single-element'):
(intensity, inclination, declination) = tuple((np.atleast_1d(i) for i in ANGLES[0]))
(magnetic_e, magnetic_n, magnetic_u) = tuple((np.atleast_1d(i) for i in VECT... |
class Parameters(torch.nn.Module, metaclass=LazyMeta):
def __init__(self, param_shapes: Sequence[torch.Size], input_shape: torch.Size, context_shape: Optional[torch.Size]) -> None:
super().__init__()
self.input_shape = input_shape
self.param_shapes = param_shapes
self.context_shape =... |
class OptionSeriesWindbarbDragdrop(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, js... |
def test_dolt_table_to_python_value(mocker):
mocker.patch('dolt_integrations.core.save', return_value=True)
table = DoltTable(data=pandas.DataFrame(), config=DoltConfig(db_path='p'))
lv = DoltTableNameTransformer.to_literal(self=None, ctx=None, python_val=table, python_type=DoltTable, expected=None)
ass... |
class OptionSeriesPyramidSonificationTracksMappingPitch(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._con... |
def _estr(e, prec=0, tab=''):
if isinstance(e, A.Var):
return str(e.name)
elif isinstance(e, A.Unk):
return ''
elif isinstance(e, A.Not):
return f"{_estr(e.arg, op_prec['unary'], tab=tab)}"
elif isinstance(e, A.USub):
return f"-{_estr(e.arg, op_prec['unary'], tab=tab)}"
... |
def main():
build_dir = 'gateware'
platform = Platform()
if ('load' in sys.argv[1:]):
prog = platform.create_programmer()
prog.load_bitstream(os.path.join(build_dir, 'impl', 'pnr', 'project.fs'))
exit()
if ('sim' in sys.argv[1:]):
ring = RingSerialCtrl(12, .0)
run... |
class Gc(TelemetryDevice):
internal = False
command = 'gc'
human_name = 'GC log'
help = 'Enables GC logs.'
def __init__(self, telemetry_params, log_root, java_major_version):
super().__init__()
self.telemetry_params = telemetry_params
self.log_root = log_root
self.jav... |
class DBConnectionPool(DBTester):
__test__ = False
def setUp(self):
super().setUp()
self.pool = self.create_pool()
self.connection = self.pool.get()
def tearDown(self):
if self.connection:
self.pool.put(self.connection)
self.pool.clear()
super().te... |
class Migration(migrations.Migration):
dependencies = [('awards', '0076_auto__0312')]
operations = [migrations.RemoveIndex(model_name='financialaccountsbyawards', name='faba_subid_awardkey_sums_idx'), migrations.AddIndex(model_name='financialaccountsbyawards', index=models.Index(condition=models.Q(disaster_emer... |
class Main(base.Module):
parameters = {'iface': 'wlan0'}
completions = list(parameters.keys())
def do_execute(self, line):
try:
self.cp.green(f"{'SSID':<30} {'BSSID':^18} {'CHANNEL':^9} {'SIGNAL':^9} {'BARS':^8} {'SECURITY':^18}")
result = self.scan()
if result:
... |
def run_dev_streamlit_io():
streamlit_run_cmd = ['streamlit', 'run', 'app.py']
try:
console.print(f" [bold cyan]Running Streamlit app with command: {' '.join(streamlit_run_cmd)}[/bold cyan]")
subprocess.run(streamlit_run_cmd, check=True)
except subprocess.CalledProcessError as e:
con... |
class TwoPhase_PCDInv_shell(InvOperatorShell):
def __init__(self, Qp_visc, Qp_dens, Ap_rho, Np_rho, alpha=False, delta_t=0, num_chebyshev_its=0, strong_dirichlet_DOF=[], laplace_null_space=False, par_info=None):
from . import LinearSolvers as LS
self.Qp_visc = Qp_visc
self.Qp_dens = Qp_dens
... |
class HomeAssistantManager():
def __init__(self, hass: HomeAssistant, scan_interval: datetime.timedelta, heartbeat_interval: (datetime.timedelta | None)=None):
self._hass = hass
self._is_initialized = False
self._update_entities_interval = scan_interval
self._update_data_providers_in... |
def extractCheeseburgerbrownCom(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 OptionPlotoptionsOrganizationStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsOrganizationStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsOrganizationStatesHoverAnimation)
def borderColor(self):
return self._config_get(None)
def borderCol... |
def _flatten_params_rec(obj: Any, paths: List[str]) -> List[Tuple[(List[str], str)]]:
res = []
if (isinstance(obj, ColumnName) and (obj == ColumnName.from_any(obj.name))):
return [(paths, obj.name)]
if isinstance(obj, BaseModel):
for (field_name, field) in obj.__fields__.items():
... |
def _print_cursor_block(cur: Block, target: Cursor, env: PrintEnv, indent: str) -> list[str]:
def if_cursor(c, move, k):
try:
return k(move(c))
except InvalidCursorError:
return []
def more_stmts(_):
return [f'{indent}"..."']
def local_stmt(c):
return ... |
def test_text_prefix_suffix(channel, bot_admin):
message = channel.bot_manager.send_message(bot_admin, 'Message', prefix='Prefix', suffix='Suffix')
assert (message.text == 'Prefix\nMessage\nSuffix')
edited = channel.bot_manager.edit_message_text(text='Edited text', prefix='Edited prefix', suffix='Edited suf... |
def check_test_loss(loader, model):
loss = 0
with torch.no_grad():
for (i, (x, y)) in enumerate(loader):
x = x.to(device, dtype=torch.float32)
y = y.to(device, dtype=torch.float32)
y_pred = model(x)
loss_batch = loss_fn(y_pred, y)
loss += loss_... |
def _deploy_contract(w3, contract_factory):
deploy_txn_hash = contract_factory.constructor().transact({'from': w3.eth.coinbase})
deploy_receipt = w3.eth.wait_for_transaction_receipt(deploy_txn_hash)
assert is_dict(deploy_receipt)
contract_address = deploy_receipt['contractAddress']
assert is_checksu... |
def test_AHHY_all_static_residues():
f = open(ahhy_example, 'r')
pdb_string = f.read()
chorizo = LinkedRDKitChorizo(pdb_string)
assert (len(chorizo.residues) == 4)
assert (len(chorizo.getIgnoredResidues()) == 0)
expected_suggested_mutations = {'A:HIS:2': 'A:HID:2', 'A:HIS:3': 'A:HIE:3'}
asse... |
class MockCloudClient(BaseCloudClient):
def __init__(self, maximum_running_instances=2, *args, **kwargs):
super().__init__(*args, **kwargs)
self.maximum_running_instances = maximum_running_instances
self.model_instances: List[dm.ModelInstance] = []
def can_create_instance(self, model: dm... |
def luv_to_hsluv(luv: Vector) -> Vector:
l = luv[0]
(c, h) = alg.rect_to_polar(luv[1], luv[2])
s = 0.0
if (l > (100 - 1e-07)):
l = 100.0
elif (l < 1e-08):
l = 0.0
else:
_hx_max = max_chroma_for_lh(l, h)
s = ((c / _hx_max) * 100.0)
return [util.constrain_hue(h)... |
def get_optimized_pow_patches(_fork_name: str) -> Dict[(str, Any)]:
patches: Dict[(str, Any)] = {}
mod = cast(Any, import_module((('ethereum.' + _fork_name) + '.fork')))
if (not hasattr(mod, 'validate_proof_of_work')):
raise Exception('Attempted to get optimized pow patches for non-pow fork')
ge... |
class bsn_virtual_port_create_reply(bsn_header):
version = 6
type = 4
experimenter = 6035143
subtype = 16
def __init__(self, xid=None, status=None, vport_no=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (status != None):
... |
class UnitValidator(object):
def __init__(self, regex, verbose_pattern, unit_multipliers) -> None:
self.regex = regex
self.verbose_pattern = verbose_pattern
self.unit_multipliers = unit_multipliers
def __call__(self, value, field_name):
value = str(value)
match = re.match... |
def test_complex_types(tmpdir):
_main.__module__ = __name__
main = get_main(tmpdir)
xp = call(main, [])
print(xp.cfg.complex)
assert (xp.cfg.complex.a == [1, 2, 3])
xp = call(main, ['complex.a=[0]'])
assert (xp.cfg.complex.a == [0])
xp = call(main, ['complex.b.a=50'])
assert (xp.cfg.... |
def test_build_mistyped_rule():
config = {u'FilterRules': [Rule('Path', 'contains', '1337', True), Rule('pid', 'is_not', '1338', True), Rule('Event_class', 'is', 'Profiling', False), u'SomeString']}
with pytest.raises(AttributeError):
_ = dumps_configuration(config)
with pytest.raises(TypeError):
... |
class Setup():
def __init__(self, device=None, camres=(640, 480), disptype='window', dispres=(1024, 768), display=None):
if DEBUG:
self.savefile = open('data/savefile.txt', 'w')
if (display == None):
if (disptype == 'window'):
self.disp = pygame.display.set_mo... |
class OptionSeriesTilemapSonificationTracksPointgrouping(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... |
def test_outputs(capfd):
_test_outputs(True, False, 'test_outputs_tensor', 'float16', capfd)
_test_outputs(False, True, 'test_outputs_all', 'float16', capfd)
_test_outputs(True, True, 'test_outputs_both_float16', 'float16', capfd)
_test_outputs(True, True, 'test_outputs_both_float32', 'float32', capfd) |
class BotCommand(JsonSerializable, JsonDeserializable, Dictionaryable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, command, description):
self.command: st... |
def new_access_list_transaction(vm: VM, from_: Address, to: Address, private_key: PrivateKey, amount: int=0, gas_price: int=(10 ** 10), gas: int=100000, data: bytes=b'', nonce: int=None, chain_id: int=1, access_list: Sequence[Tuple[(Address, Sequence[int])]]=None) -> AccessListTransaction:
if (nonce is None):
... |
def test_linear_stretch_user_error():
with Image(width=100, height=100, pseudo='gradient:') as img:
with raises(TypeError):
img.linear_stretch(white_point='NaN', black_point=0.5)
with raises(TypeError):
img.linear_stretch(white_point=0.5, black_point='NaN') |
def lazy_import():
from fastly.model.type_waf_rule_revision import TypeWafRuleRevision
from fastly.model.waf_rule_revision import WafRuleRevision
from fastly.model.waf_rule_revision_attributes import WafRuleRevisionAttributes
from fastly.model.waf_tag import WafTag
globals()['TypeWafRuleRevision'] =... |
_instruction_type([ofproto.OFPIT_METER])
class OFPInstructionMeter(OFPInstruction):
def __init__(self, meter_id=1, type_=None, len_=None):
super(OFPInstructionMeter, self).__init__()
self.type = ofproto.OFPIT_METER
self.len = ofproto.OFP_INSTRUCTION_METER_SIZE
self.meter_id = meter_i... |
def replace_memory_keywords(config, keyword, value):
mems = config['memories']
for (mem_name, mem_config) in list(mems.items()):
for key in mem_config:
if (mem_config[key] == keyword):
print(('Replacing {%s: %s} with {%s:%s}' % (key, mem_config[key], key, value)))
... |
class Analogous(Harmony):
def harmonize(self, color: 'Color', space: Optional[str]) -> List['Color']:
if (space is None):
space = color.HARMONY
orig_space = color.space()
color0 = color.convert(space)
if (not isinstance(color0._space, Cylindrical)):
raise Valu... |
class FlowRoot(FlowNode):
def __init__(self, name: str, description: str):
super().__init__()
self.name = name
self.description = description
self.auto_triggers = set()
self.room_flow = False
def connect(self, node_or_command: Union[('FlowNode', str)], predicate: Predicat... |
def extractYehetstradamusWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('BILIP', 'Brother-in-Law, Im Pregnant!', 'translated')]
for (tagname, name, tl_type) in... |
class TestContour(unittest.TestCase):
def test_contour_trace_levels_no_mask(self):
xs = np.array([0, 1, 2, 3])
ys = np.array([10, 20, 30, 40])
(xg, yg) = np.meshgrid(xs, ys)
data = np.array([[0, 0, 1, 2], [0, 1, 2, 3], [1, 2, 0, 3], [2, 3, 3, 3]])
mask = np.ones(data.shape, d... |
def proto_process_releases(sess, feed_releases):
ret_dict = {'successful': [], 'missed': [], 'ignored': [], 'ignored-w-tumblr-idiots': []}
feed_releases = list(feed_releases)
feed_releases.sort(key=(lambda x: x.published), reverse=True)
print(('Found %s feed releases' % len(feed_releases)))
dp = Rss... |
.skipif((sys.version_info < (2, 7)), reason='These tests should all run because argument evaluates to False')
class TestMockingAndStubbingFixtures(PluginTestingOrderOfOperationsTestCase):
server_class = MockingAndStubbingServer
server_settings = {}
fixture_path = (os.path.dirname(__file__) + '/mocking_and_s... |
def setCmd(snmpDispatcher, authData, transportTarget, *varBinds, **options):
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if (not cbFun):
return
if errorIndication:
cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None, cbCtx=cbCtx, snmpDi... |
def extractPraisethemetalbatWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Running Away From the Hero', 'Running Away From the Hero', 'translated'), ('PRC', 'PRC'... |
.AnalysisPluginTestConfig(plugin_class=AnalysisPlugin)
def test_detect_type_of_file(analysis_plugin):
result = analysis_plugin.analyze(io.FileIO(f'{get_test_data_dir()}/container/test.zip'), {}, {})
summary = analysis_plugin.summarize(result)
assert (result.mime == 'application/zip'), 'mime-type not detecte... |
class TooManyDigitsPattern(AbstractAstPattern):
name = 'Too Many Digit Literals'
description = 'Usage of assembly in Solidity code is discouraged.'
severity = Severity.INFO
tags = {}
def find_matches(self) -> List[PatternMatch]:
ast = self.get_ast_module()
ast_root = self.get_ast_roo... |
class OptionSeriesParetoStatesSelectHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(num, js... |
class OptionPlotoptionsWordcloudSonificationTracksMappingLowpassFrequency(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 File_Based_Message_Handler(Message_Handler):
def __init__(self, tool_id, filename):
super().__init__(tool_id)
self.filename = filename
self.fd = None
def fork(self):
raise ICE('unimplemented abstract class')
def setup_fd(self):
raise ICE('unimplemented abstract ... |
class Text3D(Module):
__version__ = 0
actor = Instance(Actor, allow_none=False, record=True)
vector_text = Instance(tvtk.VectorText, allow_none=False, record=True)
text = Str('Text', desc='the text to be displayed', enter_set=True, auto_set=False)
position = CArray(value=(0.0, 0.0, 0.0), cols=3, des... |
def identity(family, degree):
mesh = UnitCubeMesh(3, 3, 3)
fs = FunctionSpace(mesh, family, degree)
x = SpatialCoordinate(mesh)
f = Function(fs)
out = Function(fs)
u = TrialFunction(fs)
v = TestFunction(fs)
a = (inner(u, v) * dx)
f.interpolate(x[0])
L = (inner(f, v) * dx)
sol... |
class SchemaspaceList(SchemaspaceBase):
json_flag = Flag('--json', name='json', description='List complete instances as JSON', default_value=False)
include_invalid_flag = Flag('--include-invalid', name='include-invalid', description='Include invalid instances (default displays only valid instances)', default_va... |
class OptionSeriesSplineSonificationContexttracksMappingHighpassFrequency(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 extractSeonbiNovels(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, postfix... |
class DocxLoader(BaseLoader):
def __init__(self, file_path: str, encoding: Optional[str]=None):
self.file_path = file_path
self.encoding = encoding
def load(self) -> List[Document]:
docs = []
doc = docx.Document(self.file_path)
content = []
for i in range(len(doc.... |
class Duplicate(Core):
def duplicate_list(self, drive_id: str=None) -> List[DuplicateItem]:
return list(self._core_duplicate_list(drive_id))
def list_to_clean(self, album_drive_id: str, size: int=200, drive_id: str=None) -> List[BaseFile]:
if (drive_id is None):
drive_id = self.defau... |
.integration_external
.integration_bigquery
def test_create_and_process_access_request_bigquery(bigquery_resources, db, cache, policy, run_privacy_request_task):
customer_email = bigquery_resources['email']
customer_name = bigquery_resources['name']
data = {'requested_at': '2021-08-30T16:09:37.359Z', 'polic... |
def verify_ref_count(trie):
enumerated_ref_count = trie.regenerate_ref_count()
tracked_keys = set(trie.ref_count.keys())
enumerated_keys = set(enumerated_ref_count.keys())
untracked_keys = (enumerated_keys - tracked_keys)
assert (len(untracked_keys) == 0)
for unenumerated_key in (tracked_keys - ... |
class ModelBundleDeleter(ErsiliaBase):
def __init__(self, config_json=None):
ErsiliaBase.__init__(self, config_json=config_json)
def _model_path(self, model_id):
folder = os.path.join(self._bundles_dir, model_id)
return folder
def delete(self, model_id):
folder = self._model_... |
.parametrize(('input_data', 'verbose', 'expected'), [(1000, False, '1000.00 Byte'), (1024, False, '1.00 KiB'), ((1024 * 1024), False, '1.00 MiB'), (1234.1234, False, '1.21 KiB'), (1000, True, '1000.00 Byte (1,000 bytes)'), (b'abc', False, 'not available'), (None, False, 'not available')])
def test_byte_number_filter(in... |
class MultiThreadTrajectoryBatcher():
def reset(self, agent_info=DictTensor({}), env_info=DictTensor({})):
n_workers = len(self.workers)
assert (isinstance(agent_info, DictTensor) and (agent_info.empty() or (agent_info.n_elems() == (self.n_envs * n_workers))))
assert (isinstance(env_info, Di... |
def freeze(args=0):
global b, timed, count, times_list, p, avg5, avg5_flo, times_list_5_flo, times_list_5, min_5, max_5, min_c, max_c, avg12, avg12_flo, times_list_12_flo, times_list_12, min_12, max_12, min_c12, max_c12, k, mean
b = (b + 1)
if (float(timed) < 14.96):
messagebox.showinfo('Congratulat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.