code stringlengths 281 23.7M |
|---|
class GivReg(RegBase):
total = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.binary = kwargs['binary']
def __repr__(self):
return '(GivReg {}.{})'.format(self.base_register, self.index)
def __str__(self):
return repr(self)
def add_pc(se... |
class FieldTextArea(Field):
name = 'Field Textarea'
def __init__(self, page: primitives.PageModel, value, label, placeholder, icon, width, height, html_code, helper, options, profile):
html_input = page.ui.inputs.textarea(page.inputs.get(html_code, value), width=(100, '%'), placeholder=placeholder, opti... |
class File(BaseAligo):
def _core_get_file_list(self, body: GetFileListRequest) -> Iterator[BaseFile]:
(yield from self._list_file(ADRIVE_V3_FILE_LIST, body, GetFileListResponse, params={'jsonmask': 'next_marker,items(name,file_id,drive_id,type,size,created_at,updated_at,category,file_extension,parent_file_i... |
def get_data():
return {'fieldname': 'encounter', 'non_standard_fieldnames': {'Patient Medical Record': 'reference_name', 'Inpatient Medication Order': 'patient_encounter', 'Nursing Task': 'reference_name', 'Service Request': 'order_group', 'Medication Request': 'order_group'}, 'transactions': [{'label': _('Records... |
def gen_profiler(sorted_graph: List[Tensor], workdir: str, dynamic_profiling_strategy):
results = []
for node in sorted_graph:
for func in node.src_ops():
if (('has_profiler' in func._attrs) and func._attrs['has_profiler']):
results.append(func.gen_profiler(workdir, dynamic_p... |
class Migration(migrations.Migration):
dependencies = [('transactions', '0001_initial')]
operations = [migrations.AlterField(model_name='sourceassistancetransaction', name='created_at', field=usaspending_api.common.custom_django_fields.NaiveTimestampField(blank=True, db_index=True, help_text='record creation da... |
def extractWwwDanoveltranslationsCom(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_t... |
class OptionSeriesDumbbellSonificationTracksMappingFrequency(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):
sel... |
('overrides,expected', [(['--cfg', 'job', '-p', 'baud_rate'], '19200'), (['--cfg', 'hydra', '-p', 'hydra.job.name'], 'frozen'), (['--cfg', 'job', '--resolve', '-p', 'baud_rate'], '19200'), (['--cfg', 'hydra', '--resolve', '-p', 'hydra.job.name'], 'frozen'), (['--info', 'config'], 'baud_rate: 19200'), (['--hydra-help'],... |
class MTextField(HasTraits):
value = Str()
update_text = Enum('auto', 'editing_finished')
placeholder = Str()
echo = Enum('normal', 'password')
read_only = Bool()
def _initialize_control(self):
super()._initialize_control()
self._set_control_echo(self.echo)
self._set_cont... |
()
def create_simple_saddle_point_problem(request):
class Output_Storage(object):
def __init__(self, petsc_matF, petsc_matD, petsc_matB, petsc_matBt, petsc_matC, x_vec, y_vec, num_p_unkwn, num_v_unkwn):
self.petsc_matF = petsc_matF
self.petsc_matD = petsc_matD
self.petsc_... |
def fetch_mixed(ctx: Context, public_id: PublicId, alias: Optional[str]=None, target_dir: Optional[str]=None) -> None:
try:
fetch_agent_locally(ctx, public_id, alias=alias, target_dir=target_dir)
except click.ClickException as e:
logger.debug(f'Fetch from local registry failed (reason={str(e)}),... |
.usefixtures('use_tmpdir')
def test_that_substitution_happens_in_workflow():
with open('workflow', 'w', encoding='utf-8') as f:
f.write('JOB <A> <B>\n')
substlist = SubstitutionList()
substlist['<A>'] = 'a'
substlist['<B>'] = 'b'
job = WorkflowJob(name='JOB', internal=False, min_args=None, m... |
.skip
def test_pin_and_get(dep_project):
package_config = ETHPM_CONFIG.copy()
package_config['settings']['include_dependencies'] = False
(manifest, uri) = ethpm.create_manifest(dep_project._path, package_config, True)
process = ethpm.process_manifest(manifest, uri)
get = ethpm.get_manifest(uri)
... |
class OefSearchHandler(Handler):
SUPPORTED_PROTOCOL = OefSearchMessage.protocol_id
def setup(self) -> None:
def handle(self, message: Message) -> None:
oef_search_msg = cast(OefSearchMessage, message)
oef_search_dialogues = cast(OefSearchDialogues, self.context.oef_search_dialogues)
... |
def upgrade():
op.execute('COMMIT')
try:
op.execute('SHOW bdr.permit_ddl_locking')
op.execute('SET LOCAL bdr.permit_ddl_locking = true')
except exc.ProgrammingError:
pass
op.execute("UPDATE updates SET status = 'pending' WHERE status = 'processing'")
op.execute('ALTER TYPE ck... |
class AuthView(APIView):
_decorator(ensure_csrf_cookie)
def get(self, request):
if request.user.is_authenticated:
username = request.user.username
else:
username = None
return Response({'username': username})
_decorator(csrf_protect)
def post(self, request... |
def test_error_when_nan_introduced_during_transform():
rng = default_rng()
random = skewnorm.rvs(a=(- 50), loc=4, size=100)
random = (random - min(random))
train = pd.concat([pd.Series(rng.standard_normal(100)), pd.Series(random)], axis=1)
train.columns = ['var_a', 'var_b']
test = pd.concat([pd.... |
()
def sqs_client_and_queue():
sqs = boto3.client('sqs', endpoint_url=LOCALSTACK_ENDPOINT)
response = sqs.create_queue(QueueName='myqueue', Attributes={'MessageRetentionPeriod': '86400'})
queue_url = response['QueueUrl']
(yield (sqs, queue_url))
sqs.delete_queue(QueueUrl=queue_url) |
def extractTraetranslationsWordpressCom(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, t... |
class flow_modify(flow_mod):
version = 1
type = 14
_command = 1
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if (xid != None):
self.xid = xid
else:
... |
def get_registry_load_or_rename_extra_details(metadata, event, extra_detail_io, details_info):
new_path = read_detail_string(extra_detail_io, details_info['new_path_info'])
if (event.operation == RegistryOperation.RegLoadKey.name):
event.details['Hive Path'] = new_path
elif (event.operation == Regis... |
class TestMultipleChoiceFieldHTMLFormRenderer(TestCase):
def setUp(self):
self.renderer = HTMLFormRenderer()
def test_render_selected_option_with_string_option_ids(self):
choices = (('1', 'Option1'), ('2', 'Option2'), ('12', 'Option12'), ('}', 'OptionBrace'))
class TestSerializer(seriali... |
.unit_saas
class TestSaasConnector():
def test_handle_errored_response_ignore_errors(self):
fake_request: SaaSRequest = SaaSRequest(path='test/path', method=HTTPMethod.GET, ignore_errors=True)
fake_errored_response: Response = Response()
fake_errored_response.status_code = HTTP_404_NOT_FOUND... |
class Command(BaseCommand):
help = 'Updates empty awarding and funding agency fields on transactions and awards due to subtier/toptier mapping'
def update_awarding_funding_agency(fiscal_year=None, file_type=None, page=1, limit=500000):
offset = ((page - 1) * limit)
range_low = offset
ran... |
class InstructionLengthHandler(PipelineStage):
name = 'instruction-length-handler'
def __init__(self):
self._bounds: Optional[ComplexityBounds] = None
def run(self, task: DecompilerTask):
self._bounds = ComplexityBounds.from_options(task.options)
target_generator = TargetGenerator(ta... |
class ResourceSpecSchema(StrictSchema):
name = ma.fields.String(required=True)
create_operator_type = ma.fields.String(required=True)
destroy_operator_type = ma.fields.String()
provides_args = ma.fields.List(ma.fields.String(), required=True)
disable_sentinel_node = ma.fields.Boolean() |
def import_petromod(mfile, **_):
cfhandle = mfile.get_cfhandle()
logger.info('Enter function %s', __name__)
(dsc, _) = _cxtgeo.surf_import_petromod_bin(cfhandle, 0, 0.0, 0, 0, 0)
fields = dsc.split(',')
rota_xori = 0
rota_yori = 0
undef = 999999.0
args = {}
for field in fields:
... |
class Migration(migrations.Migration):
initial = True
dependencies = [('reversion', '0001_squashed_0004_auto__1202'), ('contenttypes', '0002_remove_content_type_name')]
operations = [migrations.CreateModel(name='TestModel', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False... |
def is_string(value, min=None, max=None):
if (not isinstance(value, str)):
raise VdtTypeError(value)
(min_len, max_len) = _is_num_param(('min', 'max'), (min, max))
try:
num_members = len(value)
except TypeError:
raise VdtTypeError(value)
if ((min_len is not None) and (num_mem... |
class TestLabTest(FrappeTestCase):
def test_lab_test_item(self):
lab_template = create_lab_test_template()
self.assertTrue(frappe.db.exists('Item', lab_template.item))
self.assertEqual(frappe.db.get_value('Item Price', {'item_code': lab_template.item}, 'price_list_rate'), lab_template.lab_te... |
class HostType(object):
def __init__(self, ostype=None, distro=None, distrovers=None) -> None:
if (ostype is None):
distro = None
distrovers = None
if sys.platform.startswith('linux'):
(ostype, distro, distrovers) = get_linux_type()
elif sys.pl... |
def main(args_=None):
(args, default_config) = parse_args(args_)
formatters.configure_logger(verbose=args.verbose, format_=args.format)
logger.debug(f'Creosote version: {__version__}')
logger.debug(f"Command: creosote {' '.join(sys.argv[1:])}")
logger.debug(f'Default configuration (may have loaded p... |
class Handler(HasPrivateTraits):
def init_info(self, info):
pass
def init(self, info: UIInfo) -> bool:
return True
def position(self, info):
toolkit().position(info.ui)
def close(self, info, is_ok):
return True
def closed(self, info, is_ok):
return
def rev... |
def test_zero_encoding_for_new_categories():
df_fit = pd.DataFrame({'col1': ['a', 'a', 'b', 'a', 'c'], 'col2': ['1', '2', '3', '1', '2']})
df_transf = pd.DataFrame({'col1': ['a', 'd', 'b', 'a', 'c'], 'col2': ['1', '2', '3', '1', '4']})
encoder = CountFrequencyEncoder(unseen='encode').fit(df_fit)
result ... |
class Test_Worker():
def worker(self, app):
return Worker(app)
def test_constructor(self, app):
w = Worker(app)
assert (w.app is app)
assert (w.sensors == set())
assert (w.workdir == Path.cwd())
assert isinstance(w.spinner, terminal.Spinner)
w2 = Worker(ap... |
class OptionPlotoptionsPieOnpoint(Options):
def connectorOptions(self) -> 'OptionPlotoptionsPieOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionPlotoptionsPieOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text: str):
... |
def call_with_error(error_type):
def _call_with_error(f):
def error(log, msg):
log.append(msg)
(f)
def wrapped(*args, **kwargs):
log = []
result = f(*args, error=error(log), **kwargs)
if (len(log) > 0):
raise error_type('\n'.joi... |
class ExpressionPropagationMemory(ExpressionPropagationBase):
name = 'expression-propagation-memory'
def __init__(self):
ExpressionPropagationBase.__init__(self)
def run(self, task: DecompilerTask):
self._initialize_pointers(task.graph)
super().run(task)
def perform(self, graph, ... |
class RedisCli(Redis):
def __init__(self):
super(RedisCli, self).__init__(host=settings.REDIS_HOST, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD, db=settings.REDIS_DATABASE, socket_timeout=settings.REDIS_TIMEOUT, decode_responses=True)
async def open(self):
try:
(await ... |
class Event():
def __init__(self, sse_event):
self._sse_event = sse_event
self._data = json.loads(sse_event.data)
def data(self):
return self._data['data']
def path(self):
return self._data['path']
def event_type(self):
return self._sse_event.event_type |
def test_encoding_unknown_performative():
msg = LedgerApiMessage(performative=LedgerApiMessage.Performative.GET_BALANCE, ledger_id='some_ledger_id', address='some_address')
with pytest.raises(ValueError, match='Performative not valid:'):
with mock.patch.object(LedgerApiMessage.Performative, '__eq__', re... |
class Sync(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag)
def group(self):
return self._config_get(1)
def group(self, num: int):
self._config(num)
def suppressTooltips(self):
return self._config_get... |
class ABIType():
__slots__ = ('arrlist', 'node')
def __init__(self, arrlist=None, node=None):
self.arrlist = arrlist
self.node = node
def __repr__(self):
return f'<{type(self).__qualname__} {repr(self.to_type_str())}>'
def __eq__(self, other):
return ((type(self) is type(... |
class BuildProgramTest(unittest.TestCase):
def setUp(self):
self.fake_file = os.path.join(gettempdir(), 'aibenchtest1', 'test')
self.actual_file = os.path.join(gettempdir(), 'aibenchtest2', 'program')
_setUpTempDirectory(self.actual_file)
with open(self.actual_file, 'a'):
... |
def parse_argv(tokens: Tokens, options: List[Option], options_first: bool=False, more_magic: bool=False) -> List[Pattern]:
def isanumber(x):
try:
float(x)
return True
except ValueError:
return False
parsed: List[Pattern] = []
current_token = tokens.current... |
def read_process_stats() -> ProcessStats:
main_trinity_process = get_main_trinity_process()
child_processes = main_trinity_process.children(recursive=True)
num_processes = (len(child_processes) + 1)
num_child_threads = sum(collect_thread_counts_for_processes(child_processes))
num_threads = (num_chil... |
class ClassifierOnlineTest(object):
def __init__(self, model_path, action_labels, window_size, human_id=0):
self.human_id = human_id
with open(model_path, 'rb') as f:
self.model = pickle.load(f)
if (self.model is None):
print('my Error: failed to load model')
... |
class TraitCoerceType(TraitHandler):
def __init__(self, aType):
if (not isinstance(aType, type)):
aType = type(aType)
self.aType = aType
try:
self.fast_validate = CoercableTypes[aType]
except:
self.fast_validate = (ValidateTrait.coerce, aType)
... |
class ReversedList(object):
def __init__(self, list):
self.list = list
def insert(self, index, value):
return self.list.insert(self._index((index - 1)), value)
def index(self, value):
list = self.list[:]
list.reverse()
return list.index(value)
def __len__(self):
... |
def extractNocturnetlsNet(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 tag... |
class github_issue_0038_test_case(unittest.TestCase):
def get_dict_generator():
(yield from enumerate('abcd'))
def test_init_with_generator(self):
b = benedict(self.get_dict_generator())
self.assertEqual(b, {0: 'a', 1: 'b', 2: 'c', 3: 'd'})
self.assertEqual(b.to_json(), '{"0": "a... |
class StrWrapper(Wrapper):
def __init__(self, data):
self.data = data
def to_bounding_box(self):
from climetlab.utils.domains import domain_to_area
return domain_to_area(self.data)
def to_datetime(self):
return parse_date(self.data)
def to_datetime_list(self):
fro... |
.end_to_end
def test_cpa_on_dpa_v2():
ths = traces.read_ths_from_ets_file('tests/end_to_end/dpa_v2_sub.ets')
expected_key = aes.key_schedule(key=ths[0].key)[(- 1)]
sf = aes.selection_functions.encrypt.DeltaRLastRounds()
container = scared.Container(ths)
att = scared.CPAAttack(selection_function=sf, ... |
class TestWrongRepeatedClass():
def test_class_unknown(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test_incorrect_repeated_class.yaml'])
with pytest.raises(ValueError):
ConfigArgBuilder(*all_configs, ... |
class InstructionDataset(Dataset):
def __init__(self, dataset_config, tokenizer, partition='train'):
self.ann = json.load(open(dataset_config.data_path))
if (partition == 'train'):
self.ann = self.ann[200:]
else:
self.ann = self.ann[:200]
self.tokenizer = toke... |
class OptionPlotoptionsSplineSonificationContexttracksMappingNoteduration(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)... |
.parametrize('use_weak_dirichlet', [False, True])
def test_load_vector_use_weak(use_weak_dirichlet):
from . import poisson_het_2d_p
reload(poisson_het_2d_p)
from . import poisson_het_2d_c0pk_n
pList = [poisson_het_2d_p]
nList = [poisson_het_2d_c0pk_n]
reload(default_so)
so = default_so
s... |
class ToolBar():
def __init__(self, plot):
self.plot = plot
def _get_subplot_dropdown_value(self) -> str:
raise NotImplemented
def current_subplot(self) -> Subplot:
if hasattr(self.plot, '_subplots'):
current = self._get_subplot_dropdown_value()
if (current[0]... |
class DirectOutput(object):
def __init__(self, dll_path):
logging.debug('DirectOutput.__init__')
self.DirectOutputDLL = ctypes.WinDLL(dll_path)
def Initialize(self, application_name):
logging.debug('DirectOutput.Initialize')
return self.DirectOutputDLL.DirectOutput_Initialize(cty... |
class _TestGlobmatch(unittest.TestCase):
def mktemp(self, *parts):
filename = self.norm(*parts)
(base, file) = os.path.split(filename)
if (not os.path.exists(base)):
retry = 3
while retry:
try:
os.makedirs(base)
... |
class OptionSeriesVariwideMarker(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._config(num, js... |
class _ExtendedCommunity(StringifyMixin, TypeDisp, _Value):
_PACK_STR = '!B7s'
_PACK_STR_SIZE = struct.calcsize(_PACK_STR)
_SUBTYPE_PACK_STR = '!B'
IANA_AUTHORITY = 128
TRANSITIVE = 64
_TYPE_HIGH_MASK = (~ TRANSITIVE)
TWO_OCTET_AS_SPECIFIC = 0
IPV4_ADDRESS_SPECIFIC = 1
FOUR_OCTET_AS_... |
class TestActionFileReindex(CuratorTestCase):
def test_reindex_manual(self):
source = 'my_source'
dest = 'my_dest'
expected = 3
self.create_index(source)
self.add_docs(source)
self.write_config(self.args['configfile'], testvars.client_config.format(HOST))
self... |
def get_solar_capacities() -> pd.DataFrame:
solar_capacity_base_url = '
START_YEAR = 2010
end_year = arrow.now().year
years = list(range(START_YEAR, (end_year + 1)))
url_solar_capacity = copy(solar_capacity_base_url)
for (i, year) in enumerate(years):
if (i == (len(years) - 1)):
... |
class ReadWriteSerializerMixin(object):
read_serializer_class = None
write_serializer_class = None
def get_serializer_class(self):
if (self.action in ['create', 'update', 'partial_update', 'destroy']):
return self.get_write_serializer_class()
return self.get_read_serializer_class... |
def test_deposit_sets_start_dynasty(concise_casper, funded_account, validation_key, deposit_amount, deposit_validator):
validator_index = deposit_validator(funded_account, validation_key, deposit_amount)
expected_start_dynasty = (concise_casper.dynasty() + 2)
assert (concise_casper.validators__start_dynasty... |
class AutoReconnectTest(unittest.TestCase):
client = None
auto_reconnect = None
response = None
def setUp(self):
self.client = ami.AMIClient(**connection)
self.auto_reconnect = ami.AutoReconnect(self.client, on_reconnect=debug, on_disconnect=debug)
def tearDown(self):
future ... |
def _save_json(name, json_blob):
folder = os.path.split(__file__)[0]
protocol_file_path = os.path.join(folder, '../', 'protocols', name)
protocol_file_path = os.path.abspath(protocol_file_path)
with open(protocol_file_path, 'w') as fp:
fp.write(json.dumps(json_blob, indent=4)) |
class TransposeTest(unittest.TestCase):
dot_from_normal = '\ndigraph "graph" {\n N00[label=0.0];\n N01[label=1.0];\n N02[label=Normal];\n N03[label=Sample];\n N04[label=Sample];\n N05[label=Sample];\n N06[label=Sample];\n N07[label=2];\n N08[label=ToMatrix];\n N09[label=Transpose];\n N10[label=Query];\n ... |
def add_args(subparsers):
parser = subparsers.add_parser('publish', formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=__doc__, help='Publish a stream of messages')
parser.add_argument('-c', '--clientid', default=('beem.loadr-%s-%d' % (socket.gethostname(), os.getpid())), help='Set the client i... |
def test_dont_raise_vector():
mesh = UnitIntervalMesh(1)
V = VectorFunctionSpace(mesh, 'CG', 1, dim=2)
x = SpatialCoordinate(mesh)
f = Function(V).interpolate(as_vector((x[0], (2.0 * x[0]))))
with pytest.raises(PointNotInDomainError):
f.at((- 1))
assert (f.at((- 1), dont_raise=True) is N... |
class IPv6ProtoUDP(MatchTest):
def runTest(self):
match = ofp.match([ofp.oxm.eth_type(34525), ofp.oxm.ip_proto(17)])
matching = {'udp': simple_udpv6_packet()}
nonmatching = {'tcp': simple_tcpv6_packet(), 'icmp': simple_icmpv6_packet()}
self.verify_match(match, matching, nonmatching) |
.usefixtures('_run_around_tests')
def test_transform_output_write_to_folder(tmp_path_factory):
transforms_output_folder = pathlib.Path(tmp_path_factory.mktemp('transforms_output_folder'))
with PatchConfig(initial_config_overwrite={'transforms_output_folder': os.fspath(transforms_output_folder)}):
(outpu... |
class HasLoggerMeta(type):
logger_class = logging.Logger
def __new__(mcls: Type[THasLoggerMeta], name: str, bases: Tuple[Type[Any]], namespace: Dict[(str, Any)]) -> THasLoggerMeta:
if ('logger' in namespace):
return super().__new__(mcls, name, bases, namespace)
if ('__qualname__' not... |
def test_list_of_serializable_decoding_rlp_caching(rlp_obj):
rlp_obj_code = encode(rlp_obj, cache=False)
L = [rlp_obj, rlp_obj]
list_code = encode(L, cache=False)
L2 = decode(list_code, sedes=List((type(rlp_obj), type(rlp_obj))), recursive_cache=True)
assert (L2[0]._cached_rlp == rlp_obj_code)
a... |
def register(registry):
_IndexedCustomEditor.register(registry)
registry.register_interaction(target_class=SimpleEditor, interaction_class=MouseClick, handler=(lambda wrapper, _: mouse_click_button(control=wrapper._target._button, delay=wrapper.delay)))
register_traitsui_ui_solvers(registry, SimpleEditor, _... |
def connect_input(source_node, source_attr_name, target_node, target_attr_name):
inputs = source_node.attr(source_attr_name).inputs(p=1)
if inputs:
(inputs[0] >> target_node.attr(target_attr_name))
else:
target_node.attr(target_attr_name).set(source_node.attr(source_attr_name).get()) |
def test_insert_forward_orelse():
def example_old():
x: f32
if (1 < 2):
x = 1.0
else:
x = 2.0
x1_old = _find_stmt(example_old, 'x = 1.0')
x2_old = _find_stmt(example_old, 'x = 2.0')
gap = x1_old.after()
stmt = [LoopIR.Pass(None, x1_old._node.srcinfo)]
... |
def indexed_event_contract(w3, wait_for_block, wait_for_transaction, address_conversion_func):
wait_for_block(w3)
indexed_event_contract_factory = w3.eth.contract(**INDEXED_EVENT_CONTRACT_DATA)
deploy_txn_hash = indexed_event_contract_factory.constructor().transact({'from': w3.eth.coinbase, 'gas': 1000000})... |
def _sort_sweep(sweep: Union[(ChoiceSweep, RangeSweep)], reverse: bool) -> Union[(ChoiceSweep, RangeSweep)]:
sweep = copy(sweep)
if isinstance(sweep, ChoiceSweep):
sweep.list = sorted(sweep.list, reverse=reverse)
return sweep
elif isinstance(sweep, RangeSweep):
assert (sweep.start is... |
class Atom(Expr):
__slots__ = ('name',)
__hash__ = Expr.__hash__
def __init__(self, name):
if isinstance(name, Atom):
name = name.name
assert isinstance(name, str), name
self.name = name
def __repr__(self):
return (((self.__class__.__name__ + '("') + self.name... |
class QGradientEditor(QtGui.QMainWindow):
def __init__(self, vtk_table, on_change_color_table=None, colors=None):
super(QGradientEditor, self).__init__()
self.setWindowTitle('Color Gradient Editor')
self.widget = QGradientEditorWidget(master=self, vtk_table=vtk_table, on_change_color_table=o... |
class SparkAPI():
def __init__(self, appid: str, api_key: str, api_secret: str, spark_url: str) -> None:
self.appid = appid
self.api_key = api_key
self.api_secret = api_secret
self.host = urlparse(spark_url).netloc
self.path = urlparse(spark_url).path
self.spark_url =... |
def req_with_pagination(f):
(f)
def wrapper(*args, **kwargs):
try:
page = flask.request.args.get('page', 1)
page = int(page)
except ValueError as err:
raise ObjectNotFound('Invalid pagination format') from err
return f(*args, page=page, **kwargs)
r... |
def assemble_data(data_list):
data = _dict()
tmp = _dict()
partitions = _get_partitions(data_list)
for (name, data_dict) in data_list:
if (not data_dict):
continue
(prefix, name) = _split(name, '/', a_s='/')
splitted = name.split('.')
if partitions:
... |
(ignore_format=_ignore_format_docstring, variables=_variables_categorical_docstring, unseen=_unseen_docstring, variables_=_variables_attribute_docstring, feature_names_in_=_feature_names_in_docstring, n_features_in_=_n_features_in_docstring, fit_transform=_fit_transform_docstring, transform=_transform_encoders_docstrin... |
def mock_password_expiration_warning_is_configured_pass(self, cmd):
returncode = 0
stderr = ['']
if ('PASS_WARN_AGE' in cmd):
stdout = ['PASS_WARN_AGE 7']
elif ('shadow' in cmd):
stdout = ['root:7', 'vagrant:7']
return SimpleNamespace(returncode=returncode, stderr=stderr, stdout=s... |
def test_subset_prune_gdef_markglyphsetsdef():
fb = FontBuilder(unitsPerEm=1000, isTTF=True)
glyph_order = ['.notdef', 'A', 'Aacute', 'Acircumflex', 'Adieresis', 'a', 'aacute', 'acircumflex', 'adieresis', 'dieresiscomb', 'acutecomb', 'circumflexcomb']
fb.setupGlyphOrder(glyph_order)
fb.setupGlyf({g: TTG... |
def test_justification_and_finalization(casper, concise_casper, funded_accounts, validation_keys, deposit_amount, new_epoch, induct_validators, send_vote, mk_suggested_vote):
validator_indexes = induct_validators(funded_accounts, validation_keys, ([deposit_amount] * len(funded_accounts)))
assert (concise_casper... |
_models('spacy.Text-Babbage.v1')
def openai_text_babbage(config: Dict[(Any, Any)]=SimpleFrozenDict(), name: Literal['text-babbage-001']='text-babbage-001', strict: bool=OpenAI.DEFAULT_STRICT, max_tries: int=OpenAI.DEFAULT_MAX_TRIES, interval: float=OpenAI.DEFAULT_INTERVAL, max_request_time: float=OpenAI.DEFAULT_MAX_REQ... |
class CheckBox(BaseButton):
def _create_dom(self):
global window
outernode = window.document.createElement('label')
node = window.document.createElement('input')
outernode.appendChild(node)
node.setAttribute('type', 'checkbox')
node.setAttribute('id', self.id)
... |
class TestEnum():
def test_declaration(self, color):
assert (color.declaration() == 'enum Color {\n\tred = 0,\n\tgreen = 1,\n\tblue = 2\n}')
def test_str(self, color):
assert (str(color) == 'Color')
def test_copy(self, color):
new_color = color.copy()
assert (new_color == col... |
class CustomSharedMemorySize(ElyraProperty):
applies_to_generic = True
applies_to_custom = True
property_id = KUBERNETES_SHARED_MEM_SIZE
property_display_name = 'Shared Memory Size'
property_description = 'Configure a custom shared memory size in\n gigabytes (10^9 bytes) for the pod that executes... |
class DesktopVPNApplication(VPNApplication):
def __init__(self, app_path, device, config):
super().__init__(device, config)
self._app_path = app_path
self._vpn_detectors = [OpenVPNDetector(self._device), L2TPDetector(self._device), NEDetector(self._device)]
self._routes_before_connec... |
def run_test(quadrilateral):
if quadrilateral:
mesh = UnitCubedSphereMesh(refinement_level=2)
RT_elt = FiniteElement('RTCF', 'quadrilateral', 1)
else:
mesh = UnitIcosahedralSphereMesh(refinement_level=2)
RT_elt = FiniteElement('RT', 'triangle', 1)
x = SpatialCoordinate(mesh)
... |
class CoreStickBallCollision(ABC):
def resolve(self, cue: Cue, ball: Ball, inplace: bool=False) -> Tuple[(Cue, Ball)]:
if (not inplace):
cue = cue.copy()
ball = ball.copy()
return self.solve(cue, ball)
def solve(self, cue: Cue, ball: Ball) -> Tuple[(Cue, Ball)]:
p... |
()
('-i', 'infile', type=click.File('r'), default='-', help='Input file (Default: stdin)')
('-v', 'verbose', is_flag=True, default=False, help='Verbose output')
('--json', 'json_output', is_flag=True, default=False, help='JSON output')
('field', type=click.STRING)
def cmd_data_select(infile, json_output, verbose, field... |
def convert_timestamp(zone_key: str, timestamp_string: str, logger: Logger=getLogger(__name__)):
timestamp_string = re.sub('\\s+', ' ', timestamp_string)
logger.debug(f"PARSED TIMESTAMP {arrow.get(timestamp_string, 'MM/DD/YYYY HH:mm:ss A', tzinfo=timezone_name)}", extra={'key': zone_key})
return arrow.get(t... |
def draw_pdf(filename, size=(800, 600)):
from chaco.pdf_graphics_context import PdfPlotGraphicsContext
container = create_plot()
container.outer_bounds = list(size)
container.do_layout(force=True)
gc = PdfPlotGraphicsContext(filename=filename, dest_box=(0.5, 0.5, 5.0, 5.0))
for i in range(2):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.