code stringlengths 281 23.7M |
|---|
def test_hankel_dlf():
allfilt = ['kong_61_2007', 'kong_241_2007', 'key_101_2009', 'key_201_2009', 'key_401_2009', 'anderson_801_1982', 'key_51_2012', 'key_101_2012', 'key_201_2012', 'wer_201_2018']
for filt in allfilt:
dlf = getattr(filters, filt)()
nr = int(filt.split('_')[1])
fact = n... |
(cache=True)
def vehicle_dynamics_st(x, u_init, mu, C_Sf, C_Sr, lf, lr, h, m, I, s_min, s_max, sv_min, sv_max, v_switch, a_max, v_min, v_max):
g = 9.81
u = np.array([steering_constraint(x[2], u_init[0], s_min, s_max, sv_min, sv_max), accl_constraints(x[3], u_init[1], v_switch, a_max, v_min, v_max)])
if (abs... |
.skipif((not has_tensorflow), reason='needs TensorFlow')
def test_tensorflow_wrapper_thinc_model_subclass(tf_model):
class CustomModel(Model):
def fn(self):
return 1337
model = TensorFlowWrapper(tf_model, model_class=CustomModel)
assert isinstance(model, CustomModel)
assert (model.fn... |
def _write(*args: str) -> None:
args_len = len(args)
c = 0
for arg in args:
c += 1
if _is_debug():
_log(f'writing: {arg}')
sys.stdout.write(arg)
if (c < args_len):
if _is_debug():
_log('writetab')
sys.stdout.write('\t')
... |
class MakeMenu():
def __init__(self, desc, owner, popup=False, window=None):
self.owner = owner
if (window is None):
window = owner
self.window = window
self.indirect = getattr(owner, 'call_menu', None)
self.names = {}
self.desc = desc.split('\n')
... |
('kibana')
_params(*kibana_options)
_context
def kibana_group(ctx: click.Context, **kibana_kwargs):
ctx.ensure_object(dict)
if (sys.argv[(- 1)] in ctx.help_option_names):
click.echo('Kibana client:')
click.echo(format_command_options(ctx))
else:
ctx.obj['kibana'] = get_kibana_client(... |
class JsonInterfaceGenerator(object):
def __init__(self, protocol_version='1.2', debug_prints=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if (protocol_version == None):
protocol_version = '1.2'
self.log = logging.getLogger('Main.ChromeController.WrapperGenerator')
... |
class MultiTagManager():
def __init__(self, logging, client, mind_structure, options):
self.logging = logging
self.client = client
self.mind_structure = mind_structure
self.multi_tag_property = options['multi_tag_property']
def get_multi_select_tags(self, notion_ai, append_tags, ... |
def switch_aliases_to_original_index(index_name=None):
index_name = (index_name or CASE_INDEX)
swapping_index = INDEX_DICT.get(index_name)[3]
es_client = create_es_client()
logger.info(" Moving aliases '{0}' and '{1}' to point to {2}...".format(INDEX_DICT.get(index_name)[1], SEARCH_ALIAS, index_name))
... |
def readFunLite():
from optparse import OptionParser
usage = 'usage: %readFunLite [options] meshFile funFile funOutFile'
parser = OptionParser(usage=usage)
parser.add_option('-x', '--nnodes-x', help='use NX nodes in the x direction', action='store', type='int', dest='nx', default=2)
parser.add_optio... |
def main():
parser = argparse.ArgumentParser(description='LiteX SoC on Arty A7-35')
parser.add_argument('--build', action='store_true', help='Build bitstream')
parser.add_argument('--load', action='store_true', help='Load bitstream')
parser.add_argument('--flash', action='store_true', help='Flash Bitstr... |
class OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMappingHighpassResonance(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... |
def train_with_memory_profiler(output_dir, device='cpu'):
ds_name = create_local_dataset(output_dir, 5, 10, 10)
runner = default_runner.Detectron2GoRunner()
cfg = runner.get_default_cfg()
cfg.MODEL.DEVICE = device
cfg.MODEL.META_ARCHITECTURE = 'MetaArchForTestSimple'
cfg.SOLVER.MAX_ITER = 10
... |
class TestFindProgram(unittest.TestCase):
def setUp(self):
self.ls = None
for d in ('/usr/bin', '/bin'):
ls = os.path.join(d, 'ls')
if os.path.exists(ls):
self.ls = ls
break
if (self.ls is None):
self.fail('unable to locate ... |
class PyfaceAuiManager(aui.AuiManager):
def CalculateDockSizerLimits(self, dock):
(docks, panes) = aui.CopyDocksAndPanes2(self._docks, self._panes)
sash_size = self._art.GetMetric(aui.AUI_DOCKART_SASH_SIZE)
opposite_size = self.GetOppositeDockTotalSize(docks, dock.dock_direction)
for... |
class PseudoDownloader(object):
def __init__(self, overwrite):
self.overwrite = overwrite
def _fetch(self, url, destination):
pass
def _copy_local_directory(self, src, dst):
if os.path.exists(dst):
if self.overwrite:
shutil.rmtree(dst)
else:
... |
class RelationshipTlsDnsRecordDnsRecord(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
... |
class TestURLSnippetsNoMax(util.MdCase):
extension = ['pymdownx.snippets']
extension_configs = {'pymdownx.snippets': {'base_path': [os.path.join(BASE, '_snippets')], 'url_download': True, 'url_max_size': 0}}
('urllib.request.urlopen')
def test_content_length_zero(self, mock_urlopen):
cm = MagicM... |
class Aspect():
def __init__(self, properties):
self.__dict__.update(properties)
self.active = AspectObject(self.active)
self.passive = AspectObject(self.passive)
def exists(self):
return (self.type != const.NO_ASPECT)
def movement(self):
mov = self.active.movement
... |
def jacobian_double(p: Tuple[(int, int, int)]) -> Tuple[(int, int, int)]:
if (not p[1]):
return (0, 0, 0)
ysq = ((p[1] ** 2) % P)
S = (((4 * p[0]) * ysq) % P)
M = (((3 * (p[0] ** 2)) + (A * (p[2] ** 4))) % P)
nx = (((M ** 2) - (2 * S)) % P)
ny = (((M * (S - nx)) - (8 * (ysq ** 2))) % P)
... |
def test_vscode_with_args(vscode_patches, mock_remote_execution):
(mock_process, mock_prepare_interactive_python, mock_exit_handler, mock_download_vscode, mock_signal, mock_prepare_resume_task_python, mock_prepare_launch_json) = vscode_patches
def t():
return
def wf():
t()
wf()
mock_... |
class AudioClipHandler(BaseHandler):
def __init__(self, id_generator, file_index):
super(AudioClipHandler, self).__init__(id_generator, file_index)
def process(self, current_id, obj, cursor, bundle_id):
name = obj['m_Name'].value
size = obj['m_Resource'].value['m_Size'].value
cur... |
class StarletteServerErrorMiddlewareInstrumentation(AsyncAbstractInstrumentedModule):
name = 'starlette'
instrument_list = [('starlette.middleware.errors', 'ServerErrorMiddleware.__call__')]
creates_transactions = True
async def call(self, module, method, wrapped, instance, args, kwargs):
try:
... |
class Exp(Fixed):
codomain = constraints.positive
def _forward(self, x: torch.Tensor, params: Optional[Sequence[torch.Tensor]]) -> Tuple[(torch.Tensor, Optional[torch.Tensor])]:
y = torch.exp(x)
ladj = self._log_abs_det_jacobian(x, y, params)
return (y, ladj)
def _inverse(self, y: to... |
def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
from .event import Event
if json_encode:
data = json.dumps(data, cls=DjangoJSONEncoder)
if (skip_user_ids is None):
skip_user_ids = []
storage = get_storage()
channelmanager = get_cha... |
class ElasticAPM(object):
def __init__(self, application, client) -> None:
self.application = application
self.client = client
def __call__(self, environ, start_response):
try:
for event in self.application(environ, start_response):
(yield event)
excep... |
.slow_integration_test
def test_clone_subgroup_only_archived():
os.environ['GITLAB_URL'] = '
output = io_util.execute(['-p', '--print-format', 'json', '-a', 'only'], 60)
obj = json.loads(output)
assert (obj['children'][0]['name'] == 'Group Test')
assert (obj['children'][0]['children'][0]['name'] == ... |
def _performance_log(func):
def wrapper(*arg):
start = datetime.datetime.now()
res = func(*arg)
if _log_performance:
usage = resource.getrusage(resource.RUSAGE_SELF)
process_memory = (usage.ru_maxrss / 1000)
delta = (datetime.datetime.now() - start)
... |
class IRIPAllowDeny(IRFilter):
parent: IRResource
action: str
principals: List[Tuple[(str, 'CIDRRange')]]
EnvoyTypeMap: ClassVar[Dict[(str, str)]] = {'remote': 'remote_ip', 'peer': 'direct_remote_ip'}
def __init__(self, ir: 'IR', aconf: Config, rkey: str='ir.ipallowdeny', name: str='ir.ipallowdeny',... |
def arg_botcmd(*args, hidden: bool=None, name: str=None, admin_only: bool=False, historize: bool=True, template: str=None, flow_only: bool=False, unpack_args: bool=True, **kwargs) -> Callable[([BotPlugin, Message, Any], Any)]:
argparse_args = args
if ((len(args) >= 1) and callable(args[0])):
argparse_ar... |
class RequestID(namedtuple('RequestID', 'kind timestamp user workerid')):
KIND = types.SimpleNamespace(BENCHMARKS='compile-bench')
_KIND_BY_VALUE = {v: v for (_, v) in vars(KIND).items()}
_workerid_defaulted: bool
def from_raw(cls, raw: Any):
if isinstance(raw, cls):
return raw
... |
def lindh_guess(geom):
atoms = [a.lower() for a in geom.atoms]
alphas = [get_lindh_alpha(a1, a2) for (a1, a2) in it.combinations(atoms, 2)]
pair_cov_radii = get_pair_covalent_radii(geom.atoms)
cdm = pdist(geom.coords3d)
rhos = squareform(np.exp((alphas * ((pair_cov_radii ** 2) - (cdm ** 2)))))
k... |
def should_run(**kwargs):
next_exec_date = kwargs['next_execution_date']
force_to_run = kwargs['dag_run'].conf.setdefault('force_to_run', False)
print('---- weekday: {}, force_to_run: {}, context {}'.format(next_exec_date.weekday(), force_to_run, kwargs))
if force_to_run:
return 'start'
if (... |
def consolidate_query_matches(row: Row, target_path: FieldPath, flattened_matches: Optional[List]=None) -> List[Any]:
if (flattened_matches is None):
flattened_matches = []
if isinstance(row, list):
for elem in row:
consolidate_query_matches(elem, target_path, flattened_matches)
... |
class BackendResponse(ModelComposed):
allowed_values = {}
validations = {('share_key',): {'regex': {'pattern': '^[A-Za-z0-9]+$'}}}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_pr... |
def make_resolution_plan(app: App, bench: 'Bench'):
resolution = OrderedDict()
resolution[app.app_name] = app
for app_name in app._get_dependencies():
dep_app = App(app_name, bench=bench)
is_valid_frappe_branch(dep_app.url, dep_app.branch)
dep_app.required_by = app.name
if (d... |
def build_unix():
if (not check_raylib_installed()):
raise Exception('ERROR: raylib not found by pkg-config. Please install pkg-config and Raylib.')
raylib_h = (get_the_include_path() + '/raylib.h')
rlgl_h = (get_the_include_path() + '/rlgl.h')
raymath_h = (get_the_include_path() + '/raymath.h'... |
def run(globaldb, localdb, verbose=False):
local_db_files = list()
work_db_files = list()
global_entries = {}
local_entries = {}
final_entries = {}
(verbose and print(('removing %s from %s' % (localdb, globaldb))))
for (line, (tag, bits, mode)) in util.parse_db_lines(globaldb):
globa... |
class SF1QuarterlyData():
def __init__(self, data_path: Optional[str]=None, quarter_count: Optional[int]=None, dimension: Optional[str]='ARQ'):
if (data_path is None):
data_path = load_config()['sf1_data_path']
self.data_path = data_path
self.quarter_count = quarter_count
... |
def node_swap_abilities(caller, raw_string, **kwargs):
tmp_character = kwargs['tmp_character']
text = f'''
Your current abilities:
STR +{tmp_character.strength}
CUN +{tmp_character.cunning}
WIL +{tmp_character.will}
You can swap the values of two abilities around.
You can only do this once, so choose carefully!... |
class ConnectionConfigSecretsSchema(BaseModel, abc.ABC):
_required_components: List[str]
def __init_subclass__(cls: BaseModel, **kwargs: Any):
super().__init_subclass__(**kwargs)
if (not getattr(cls, '_required_components')):
raise TypeError(f"Class {cls.__name__} must define '_requi... |
class Game(JsonDeserializable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string)
obj['photo'] = Game.parse_photo(obj['photo'])
if ('text_entities' in obj):
obj['text_entities'] = Game.parse_entities(obj['te... |
class Logout(MethodView):
_required
def get(self):
logger.debug('User logged out: {}'.format(current_user.username))
user = User.query.filter_by(username=current_user.username).first()
crackq.app.session_interface.destroy(session)
user.active = False
db.session.commit()
... |
def test_slate_mixed_vector(Wd):
(u, p) = TrialFunctions(Wd)
(v, q) = TestFunctions(Wd)
a = ((inner(u, v) * dx) + (inner(p, q) * dx))
A = Tensor(a)
f = Function(Wd)
f.sub(0).assign(2)
f.sub(1).assign(1)
B = assemble(((A.inv * A) * AssembledVector(f)))
assert numpy.allclose(B.sub(0).d... |
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('last_imported')
def handle(self, *args, **kwargs):
last_imported = kwargs['last_imported']
prescribing_date = ('-'.join(last_imported.split('_')) + '-01')
date_condition = ('month > TIMESTAMP(DATE_S... |
def test_yaml_loader_with_cache(tmpdir, mocker, _json_cache, expected_from_loader):
mock_get = mocker.patch('requests.get')
mock_mal = mocker.patch('awsrun.acctload.MetaAccountLoader.__init__')
mocker.patch('tempfile.gettempdir', return_value=tmpdir)
acctload.YAMLAccountLoader(' max_age=86400)
mock_... |
def test_shards_no_skipped_field(sync_client):
with patch.object(sync_client, 'options', return_value=sync_client), patch.object(sync_client, 'search', return_value=ObjectApiResponse(raw={'_scroll_id': 'dummy_id', '_shards': {'successful': 5, 'total': 5}, 'hits': {'hits': [{'search_data': 1}]}}, meta=None)), patch.... |
class OptionPlotoptionsOrganizationLevelsDatalabelsTextpath(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):
... |
class OptionSeriesScatterClusterZonesMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get(None)
def fillColor(self, text: str):
self._config(text, js... |
def test_websocket_endpoint_on_receive_text(test_client_factory):
class WebSocketApp(WebSocketEndpoint):
encoding = 'text'
async def on_receive(self, websocket, data):
(await websocket.send_text(f'Message text was: {data}'))
client = test_client_factory(WebSocketApp)
with client.... |
def tco_return_handle(tokens):
internal_assert((len(tokens) >= 1), 'invalid tail-call-optimizable return statement tokens', tokens)
if (len(tokens) == 1):
return (('return _coconut_tail_call(' + tokens[0]) + ')')
else:
return (((('return _coconut_tail_call(' + tokens[0]) + ', ') + ', '.join(... |
class OptionSeriesPieSonificationDefaultinstrumentoptionsMappingPitch(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 get_data_pslab(connection, experiment_type):
while True:
device = connect_to_pslab(experiment_type)
if (device is None):
return None
while True:
measurement = experiment_options[experiment_type][0](device)
if (measurement != 0):
connect... |
_frequency(timedelta(days=1))
def fetch_production(zone_key: str='BD', session: Session=Session(), target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> (dict[(str, Any)] | list[dict[(str, Any)]]):
row_data = query(session, target_datetime, logger)
production_data_list = []
for row... |
class LinkNode(dict):
def __init__(self):
self.links = []
self.methods_counter = Counter()
super().__init__()
def get_available_key(self, preferred_key):
if (preferred_key not in self):
return preferred_key
while True:
current_val = self.methods_co... |
class Category(models.Model):
title = models.CharField(_('title'), max_length=200)
parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children', limit_choices_to={'parent__isnull': True}, verbose_name=_('parent'))
slug = models.SlugField(_('slug'), max_length=1... |
class Tanh(Fixed):
codomain = constraints.interval((- 1.0), 1.0)
def _forward(self, x: torch.Tensor, params: Optional[Sequence[torch.Tensor]]) -> Tuple[(torch.Tensor, Optional[torch.Tensor])]:
y = torch.tanh(x)
ladj = self._log_abs_det_jacobian(x, y, params)
return (y, ladj)
def _inv... |
_page.route('/table')
def table():
if (all_data['token'] != None):
return jsonify(msg='This url needs a token to access. If you did not specify a token when start the server, you may access the wrong ip or port. If you specify a token when start the server, use server ip}:{port}/table/{token} to access.')
... |
class VariableMap(_common.FlyteIdlEntity):
def __init__(self, variables):
self._variables = variables
def variables(self):
return self._variables
def to_flyte_idl(self):
return _interface_pb2.VariableMap(variables={k: v.to_flyte_idl() for (k, v) in self.variables.items()})
def fr... |
class TestRecoverReferenceSequence(unittest.TestCase):
def test_mutations_only(self):
self.assertEqual(recover_reference_sequence('CGATACGGGGACATCCGGCCTGCTCCTTCTCACATG', '36M', 'MD:Z:1A0C0C0C1T0C0T27'), 'CACCCCTCTGACATCCGGCCTGCTCCTTCTCACATG')
def test_insertions(self):
self.assertEqual(recover_r... |
class TestDeleteUser():
(scope='function')
def url(self, user) -> str:
return f'{V1_URL_PREFIX}{USERS}/{user.id}'
def test_delete_user_not_authenticated(self, url, api_client):
response = api_client.delete(url, headers={})
assert (HTTP_401_UNAUTHORIZED == response.status_code)
de... |
class TestNumberOfRowsWithMissingValues(BaseIntegrityMissingValuesValuesTest):
name: ClassVar = 'The Number Of Rows With Missing Values'
def get_condition_from_reference(self, reference: Optional[DatasetMissingValues]):
if (reference is not None):
curr_number_of_rows = self.metric.get_result... |
def find_index_closing_parenthesis(string: str):
assert string.startswith('('), "string has to start with '('"
stack = []
for (index, letter) in enumerate(string):
if (letter == '('):
stack.append(letter)
elif (letter == ')'):
stack.pop()
if (not stack):
... |
class table_features_stats_reply(stats_reply):
version = 6
type = 19
stats_type = 12
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
e... |
(_gemm_matmul_acc)
def do_matmul_acc_i8(N: size, M: size, K: size, A: ([i8][(N, 16)] GEMM_SCRATCH), B: ([i8][(K, 16)] GEMM_SCRATCH), C: ([i32][(N, 16)] GEMM_ACCUM)):
assert (N <= 16)
assert (M <= 16)
assert (K <= 16)
for i in seq(0, N):
for j in seq(0, M):
for k in seq(0, K):
... |
class TestSdmHspaParser(unittest.TestCase):
parser = SdmHspaParser(parent=None, icd_ver=(6, 34))
maxDiff = None
def test_sdm_hspa_ul1_rf_info(self):
self.parser.icd_ver = (4, 54)
payload = binascii.unhexlify('3c2a0000b4ffa8e4')
packet = sdmcmd.generate_sdm_packet(160, sdmcmd.sdm_comm... |
class HistoricalRegionsResponseAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'data': ([str],)}... |
def optimal_iters(func, target_time):
iters = 1
target_time = float(target_time)
max_iters = int(getattr(func, '_benchmark_max_iters', 0))
scale_factor = getattr(func, '_benchmark_scale_factor', 0.0)
for _ in range(10):
if (max_iters and (iters > max_iters)):
return max_iters
... |
class ImmutableFamily(TestCase):
def test_pickle(self):
T = {nutils.types.Immutable: T_Immutable, nutils.types.Singleton: T_Singleton}[self.cls]
a = T(1, 2, z=3)
b = pickle.loads(pickle.dumps(a))
self.assertEqual(a, b)
def test_eq(self):
class T(self.cls):
def... |
class FunctionBasedAsyncViewIntegrationTests(TestCase):
def setUp(self):
self.view = basic_async_view
def test_get_succeeds(self):
request = factory.get('/')
response = async_to_sync(self.view)(request)
assert (response.status_code == status.HTTP_200_OK)
assert (response.... |
def extractVagabondstorytellerBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name,... |
class StackdriverLoggingClient(object):
def __init__(self, global_configs, **kwargs):
(max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME)
cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False)
self.reposi... |
class Type(BaseClass):
def __init__(self, value=None, klass=None, allow_none=True, **metadata):
if (value is None):
if (klass is None):
klass = object
elif (klass is None):
klass = value
if isinstance(klass, str):
self.validate = self.resol... |
def extractAirfalltranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name... |
class ExecuteActions(LogCaptureTestCase):
def setUp(self):
super(ExecuteActions, self).setUp()
self.__jail = DummyJail()
self.__actions = self.__jail.actions
def tearDown(self):
super(ExecuteActions, self).tearDown()
def defaultAction(self, o={}):
self.__actions.add('... |
class DemoVirtualDirectory(DemoTreeNodeObject):
description = Str()
resources = List(Instance(DemoTreeNodeObject))
allows_children = Bool(True)
nice_name = Str('Data')
def has_children(self):
return (len(self.resources) > 0)
def get_children(self):
return self.resources |
class Blob(_common.FlyteIdlEntity):
def __init__(self, metadata, uri):
self._metadata = metadata
self._uri = uri
def uri(self):
return self._uri
def metadata(self):
return self._metadata
def to_flyte_idl(self):
return _literals_pb2.Blob(metadata=self.metadata.to_f... |
def _unpatch(module: ModuleType, name: str, fn: Callable[(..., Any)]) -> None:
if (hasattr(module, '__dict__') and (name in module.__dict__) and isinstance(module.__dict__[name], (classmethod, staticmethod))):
method = module.__dict__[name]
fn = method.__func__
if (not _is_patched(fn)):
... |
def data_files(directory):
paths = defaultdict(list)
for (path, directories, filenames) in os.walk(directory):
filenames = [f for f in filenames if (not (f[0] == '.'))]
directories[:] = [d for d in directories if (not (d[0] == '.'))]
for filename in filenames:
paths[path].app... |
def parse_rpm_output_list(packages_info):
package_lines = packages_info.split('\n')
counter = 0
products = []
for line in package_lines:
if (line.startswith('Name :') or line.startswith('Version :')):
info = line.split(':')[1].rstrip().lstrip()
if (counter == 0... |
def int2ip(ip_int):
try:
return socket.inet_ntoa(struct.pack('!I', ip_int))
except (socket.error, struct.error):
pass
try:
ip_str = socket.inet_ntop(socket.AF_INET6, binascii.unhexlify(dec2hex(ip_int)))
return safeunicode(ip_str, encoding='ascii')
except (socket.error, st... |
class conv2d_depthwise(conv2d):
def __init__(self, stride, pad, dilate=1, group=1) -> None:
super().__init__(stride, pad, dilate=dilate, group=group)
self._attrs['op'] = 'conv2d_depthwise'
def __call__(self, x: Tensor, w: Tensor):
self._attrs['inputs'] = [x, w]
self._set_depth()
... |
def set_pixel(r, g, b):
setup()
if ((not isinstance(r, int)) or (r < 0) or (r > 255)):
raise ValueError('Argument r should be an int from 0 to 255')
if ((not isinstance(g, int)) or (g < 0) or (g > 255)):
raise ValueError('Argument g should be an int from 0 to 255')
if ((not isinstance(b,... |
def E(inp, L):
emsg1 = 'E L is {}, it should be {}'.format(type(L), 'int')
assert (type(L) == int), emsg1
emsg2 = 'E inp is {}, it should be bytearray'.format(type(inp))
assert (type(inp) == bytearray), emsg2
emsg3 = 'E inp len is {}, it should be {}'.format(len(inp), L)
assert (len(inp) == L), ... |
def test_that_shows_reaching_definitions_cannot_deal_with_pointers(basic_block_with_pointers, a, b, c, d):
s0 = Assignment(a, Constant(0))
s2 = Assignment(b, UnaryOperation(OperationType.address, [a]))
s3 = Assignment(c, b)
s4 = Assignment(d, c)
rd = ReachingDefinitions(basic_block_with_pointers)
... |
def test_explicit_params():
model = torch.nn.Linear(10, 2)
with torch.no_grad():
model.weight.fill_(0.0)
ema = ExponentialMovingAverage(model.parameters(), decay=0.9)
model2 = torch.nn.Linear(10, 2)
with torch.no_grad():
model2.weight.fill_(1.0)
ema.update(model2.parameters())
... |
class RouterManager(app_manager.RyuApp):
_ROUTER_CLASSES = {vrrp_event.VRRPInterfaceNetworkDevice: {4: sample_router.RouterIPV4Linux, 6: sample_router.RouterIPV6Linux}, vrrp_event.VRRPInterfaceOpenFlow: {4: sample_router.RouterIPV4OpenFlow, 6: sample_router.RouterIPV6OpenFlow}}
def __init__(self, *args, **kwarg... |
class ProgressRenderer(TableDelegate):
def paint(self, painter, option, index):
column = index.model()._editor.columns[index.column()]
obj = index.data(QtCore.Qt.ItemDataRole.UserRole)
progress_bar_option = QtGui.QStyleOptionProgressBar()
progress_bar_option.rect = option.rect
... |
def extractTdwktranslatesWordpressCom(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_... |
class OptionPlotoptionsScatter3dSonificationDefaultspeechoptionsMappingPlaydelay(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, tex... |
('rig')
def cacheable_attr_to_lowercase(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
progress_controller.maximum = 2
root_nodes = auxiliary.get_root_nodes()
progress_controller.increment()
if root_nodes[0].hasAttr('cacheable'):
... |
def over_limit_error():
if request_wants_json():
return jsonify({'error': 'form over quota'})
return (render_template('error.html', title='Form over quota', text='It looks like this form is getting a lot of submissions and ran out of its quota. Try contacting this website through other means or try subm... |
class FranceConnectOAuth2(BaseOAuth2[FranceConnectOAuth2AuthorizeParams]):
display_name = 'FranceConnect'
logo_svg = LOGO_SVG
def __init__(self, client_id: str, client_secret: str, integration: bool=False, scopes: Optional[List[str]]=BASE_SCOPES, name='franceconnect'):
endpoints = (ENDPOINTS['integr... |
.django_db
def test_correct_response_multiple_defc(client, monkeypatch, helpers, elasticsearch_award_index, cfda_awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = helpers.post_for_spending_endpoint(client, url, def_codes=['L', 'M'])
expected_results = [{'code'... |
class StravaWidget(base._Widget, base.MarginMixin):
orientations = base.ORIENTATION_HORIZONTAL
_experimental = True
defaults = [('font', 'sans', 'Default font'), ('fontsize', None, 'Font size'), ('foreground', 'ffffff', 'Text colour'), ('text', '{CA:%b} {CD:.1f}km', 'Widget text'), ('refresh_interval', 1800... |
class ConfigArgBuilder():
def __init__(self, *args, configs: Optional[List]=None, desc: str='', lazy: bool=False, no_cmd_line: bool=False, s3_config: Optional[_T]=None, key: Optional[Union[(str, ByteString)]]=None, salt: Optional[str]=None, **kwargs):
self._verify_attr(args)
self._configs = (configs... |
def test_ignores_na_in_input_df(df_na):
transformer = ArbitraryOutlierCapper(max_capping_dict=None, min_capping_dict={'Age': 20}, missing_values='ignore')
X = transformer.fit_transform(df_na)
df_transf = df_na.copy()
df_transf['Age'] = np.where((df_transf['Age'] < 20), 20, df_transf['Age'])
assert (... |
class Test(TestCase):
def test_config(self):
field = InlineCKEditorField(config_name='test')
self.assertEqual(field.widget_config, {'ckeditor': None, 'config': 'test'})
field = InlineCKEditorField(config='test2')
self.assertEqual(field.widget_config, {'ckeditor': None, 'config': 'tes... |
class Solution():
def closestValue(self, root: TreeNode, target: float) -> int:
def inorder(node):
if (node is None):
return
(yield from inorder(node.left))
(yield node.val)
(yield from inorder(node.right))
(diff, val) = (None, None)
... |
class BsCards(html.Html.Html):
name = 'Bootstrap Card'
def __init__(self, report, components, title, width, height, options, profile):
super(BsCards, self).__init__(report, [], profile=profile)
self.style.clear_all()
(self.__body, self.__header) = (None, None)
for c in components... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.