code stringlengths 281 23.7M |
|---|
def reload_all_data_by_index(index_name=None):
index_name = (index_name or CASE_INDEX)
if (index_name in INDEX_DICT.keys()):
if (index_name == CASE_INDEX):
load_current_murs()
load_adrs()
load_admin_fines()
elif (index_name == AO_INDEX):
load_advis... |
def sampling(data, shape, single=False):
if (not issequence(data)):
return np.empty(0)
size = len(data)
if (size == 0):
return np.empty(0)
samplesize = np.prod(np.array(shape))
samplecount = (size // samplesize)
if isinstance(data[0], tuple):
elem_shape = (len(data[0]),)
... |
def test_get_balance_serialization():
msg = LedgerApiMessage(performative=LedgerApiMessage.Performative.GET_BALANCE, ledger_id='some_ledger_id', address='some_address')
msg.to = 'receiver'
envelope = Envelope(to=msg.to, sender='sender', message=msg)
envelope_bytes = envelope.encode()
actual_envelope... |
class StockGNSpider(scrapy.Spider):
name = 'stock_gn_spider'
custom_settings = {'ITEM_PIPELINES': {'fooltrader.pipelines.GetFilesPipeline': 1}}
def start_requests(self):
(yield Request(url=self.get_gn_url(1), headers=TONGHUASHUN_GN_HEADER, meta={'index': 1}, callback=self.parse_item))
def parse_... |
def _validate_cmd_settings(cmd_settings: dict) -> dict:
ganache_keys = set((k for f in CLI_FLAGS.values() for k in f.keys()))
CMD_TYPES = {'port': int, 'gas_limit': int, 'block_time': int, 'time': datetime.datetime, 'accounts': int, 'evm_version': str, 'mnemonic': str, 'account_keys_path': str, 'fork': str, 'di... |
class TestBugAddComment(BasePyTestCase):
('bodhi.server.models.bugs.bugtracker.comment')
('bodhi.server.models.log.debug')
def test_parent_security_bug(self, debug, comment):
update = model.Update.query.first()
update.type = model.UpdateType.security
bug = model.Bug.query.first()
... |
class PSCAutocompleteViewSet(BaseAutocompleteViewSet):
endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/autocomplete/psc.md'
_response()
def post(self, request):
(search_text, limit) = self.get_request_payload(request)
queryset = PSC.objects.all()
if ((len(search_text) == 4... |
def _allow_deprecated_init(func):
(func)
def wrapper(cls, *args, **kwargs):
if (('sfile' in kwargs) or (len(args) == 1)):
warnings.warn("Initializing directly from file name is deprecated and will be removed in xtgeo version 4.0. Use: mysurf = xtgeo.surface_from_file('some_name.gri') instead... |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingLowpassResonance(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... |
class Preferences(BasePreferences):
__slots__ = ('_exchange_params_by_currency_id', '_utility_params_by_good_id')
def __init__(self) -> None:
self._exchange_params_by_currency_id = None
self._utility_params_by_good_id = None
def set(self, exchange_params_by_currency_id: ExchangeParams=None, ... |
def get_rich_epilog(self: Command, ctx: click.Context, formatter: RichHelpFormatter) -> None:
if self.epilog:
lines = self.epilog.split('\n\n')
epilog = '\n'.join([x.replace('\n', ' ').strip() for x in lines])
formatter.console.print(Padding(Align(_make_rich_rext(epilog, formatter.config.sty... |
class OptionSeriesPackedbubbleSonificationContexttracksMappingHighpassResonance(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... |
def test_assemble_mass_bcs_2d(V):
u = TrialFunction(V)
v = TestFunction(V)
x = SpatialCoordinate(V.mesh())
if (V.value_size == 1):
expr = x[0]
else:
expr = as_vector(([x[0]] * V.value_size))
f = Function(V).interpolate(expr)
bcs = [DirichletBC(V, 0.0, 1), DirichletBC(V, 1.0, ... |
class TelemetryMessageVehicle(object):
swagger_types = {'adas': 'Adas', 'battery': 'Battery', 'braking_system': 'TelemetryMessageVehicleBrakingSystem', 'doors_state': 'DoorsState', 'energy': 'Energy', 'engines': 'list[Engine]', 'ignition': 'Ignition', 'lighting': 'Lighting', 'safety': 'Safety', 'transmission': 'Tel... |
_implementation(ColumnDriftMetric)
class SparkColumnDriftMetric(SparkMetricImplementation[ColumnDriftMetric]):
def calculate(self, context, data: SparkInputData) -> ColumnDataDriftMetrics:
if (data.reference_data is None):
raise ValueError('Reference dataset should be present')
datetime_... |
class OptionPlotoptionsColumnSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsColumnSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsColumnSonificationContexttracksActivewhen)
def instrument(self):
return self._config_... |
def SetIndexJointPositionDirectly(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'index', 'joint_position']
optional_params = []
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('SetIndexJointPositionDirectly')
... |
class Task(UserControl):
def __init__(self, task_name, task_status_change, task_delete):
super().__init__()
self.completed = False
self.task_name = task_name
self.task_status_change = task_status_change
self.task_delete = task_delete
def build(self):
self.display_... |
class SequenceFace(StaticItemFace, Face):
def __init__(self, seq, seqtype='aa', fsize=10, fg_colors=None, bg_colors=None, codon=None, col_w=None, alt_col_w=3, special_col=None, interactive=False):
self.seq = seq
self.codon = codon
self.fsize = fsize
self.style = seqtype
self.... |
.django_db
def test_invalid_award_type_codes(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, award_type_codes=['ZZ', '08'], def_codes=['L', 'M'])
as... |
class TestSyncTraits(unittest.TestCase, UnittestTools):
def setUp(self):
push_exception_handler((lambda *args: None), reraise_exceptions=True)
def tearDown(self):
pop_exception_handler()
def test_mutual_sync(self):
a = A()
b = B()
a.sync_trait('t', b)
b.t = 10... |
class PackageResponse(ModelComposed):
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():
lazy_import()
... |
.parametrize('keys, default, type_', [(['Options', 'verbose'], None, config.Str), (['Options', 'does not exist'], 10, config.Bool), (['Characters', 'Professor X', 'weight'], 0, config.Bool), (['Characters', 'Professor X', 'weight'], 0, config.Const(1000)), (['Characters', 'Professor X', 'does not exist'], 0, config.Boo... |
def extractAmarytranslationsBlogspotCom(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... |
('backfill', help=_backfill_help)
_option_dec
_option_dec
('-v', '--version', required=False, type=str, default=None, help='Version for the registered workflow. If not specified it is auto-derived using the start and end date')
('-n', '--execution-name', required=False, type=str, default=None, help='Create a named exec... |
def _clear_state(sys, os):
delete = []
for (module, _) in sys.modules.items():
if module.startswith(('xtgeo', 'matplotlib')):
delete.append(module)
for module in delete:
del sys.modules[module]
if ('MPLBACKEND' in os.environ):
del os.environ['MPLBACKEND'] |
def init_epc_client(emacs_server_port):
from epc.client import EPCClient
global epc_client
if (epc_client is None):
try:
epc_client = EPCClient(('127.0.0.1', emacs_server_port), log_traceback=True)
except ConnectionRefusedError:
import traceback
traceback.... |
.parametrize('y_true, y_pred', [(uniform_regression_inputs.target, uniform_regression_inputs.preds)])
def test_msle(y_true, y_pred):
sk_preds = y_pred.numpy()
sk_target = y_true.numpy()
sk_score = mean_squared_log_error(y_true=sk_target, y_pred=sk_preds)
torch_metric = MeanSquaredLogarithmicError()
... |
def get_user_agent():
platforms = {'osx': 'Macintosh', 'linux': 'X11; Linux', 'windows': 'Windows NT 10.0; Win64; x64'}
try:
version = sublime.load_resource('/'.join(['Packages', __package__, 'VERSION']))
except:
version = '1.0.0'
return ('Mozilla/5.0 (%s) EmmetTracker/%s' % (platforms.g... |
class SimpleEditor(Editor):
label = Str()
def init(self, parent):
label = (self.factory.label or self.item.get_label(self.ui))
self.control = wx.Button(parent, (- 1), self.string_value(label))
self.sync_value(self.factory.label_value, 'label', 'from')
self.control.Bind(wx.EVT_BUT... |
class ERC1155Contract(Contract):
contract_id = PUBLIC_ID
def generate_token_ids(cls, token_type: int, nb_tokens: int, starting_index: int=0) -> List[int]:
token_ids = []
for i in range(nb_tokens):
index = (starting_index + i)
token_id = cls._generate_id(index, token_type)... |
class TestCreateComponentTemplateParamSource():
def test_create_component_index_template_from_track(self):
tpl = track.ComponentTemplate(name='default', content={'template': {'mappings': {'properties': {'': {'type': 'date'}}}}})
source = params.CreateComponentTemplateParamSource(track=track.Track(na... |
def delete_by_netloc_internal(netloc):
step = 10000
with db.session_context() as sess:
print('Getting minimum row in need or update..')
start = sess.execute('SELECT min(id) FROM web_pages WHERE netloc = :nl', {'nl': netloc})
start = unwrap_ret(start)
print('Minimum row ID: ', sta... |
(st_privkey=st.binary(min_size=32, max_size=32))
(max_examples=25, suppress_health_check=[HealthCheck.function_scoped_fixture])
def test_get_deployment_address(accounts, st_privkey):
assume(int(st_privkey.hex(), 16))
Foo = compile_source('pragma solidity ^0.6.0; contract Foo {}').Foo
acct = accounts.add(st_... |
('Badge Forms > Get Badge Form By Ticket > Get Badge Form By Ticket')
def get_badge_form_by_ticket(transaction):
with stash['app'].app_context():
event = EventFactoryBasic()
ticket = TicketFactory(event=event, badge_id='example')
badge_form = BadgeFormFactory(event=event, badge_id=ticket.bad... |
class SectorColonyEventProcessor(AbstractGamestateDataProcessor):
ID = 'sectors_colonies'
DEPENDENCIES = [SystemProcessor.ID, SystemOwnershipProcessor.ID, PlanetProcessor.ID, CountryProcessor.ID, LeaderProcessor.ID]
def __init__(self):
super().__init__()
self._planets_dict = None
sel... |
def check_if_address_match(address, addresses):
if (addresses is None):
return True
if is_tuple(addresses):
return any((is_same_address(address, item) for item in addresses))
elif is_address(addresses):
return is_same_address(addresses, address)
else:
raise ValueError(f'U... |
class Request():
def __init__(self, value: Field, fee: Field, hh_sig_salt: Point, hh_excess: Point, metadata: Field):
self.value = value
self.fee = fee
self.hh_sig_salt = hh_sig_salt
self.hh_excess = hh_excess
self.metadata = metadata
def __str__(self):
str_to_pri... |
def upgrade():
op.add_column('privacypreferencehistory', sa.Column('anonymized_ip_address', sqlalchemy_utils.types.encrypted.encrypted_type.StringEncryptedType(), nullable=True))
op.add_column('privacypreferencehistory', sa.Column('method', sa.String(), nullable=True))
op.add_column('privacypreferencehistor... |
class VmReplicaFailover(VmReplicaBaseView):
_api_view_ = 'vm_replica_failover'
_check_node_status = None
def put(self):
(vm, slave_vm) = (self.vm, self.slave_vm)
if slave_vm.rep_reinit_required:
raise PreconditionRequired('Reinitialization is required')
if (not slave_vm.r... |
class OptionPlotoptionsGaugeSonificationTracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
class DiscountStrategyValidator():
def validate(obj: Order, value: Callable) -> bool:
try:
if ((obj.price - value(obj)) < 0):
raise ValueError(f'Discount cannot be applied due to negative price resulting. {value.__name__}')
except ValueError as ex:
print(str(e... |
def urlopen(url):
home_url = '
headers = {'User-Agent': ('nodeenv/%s (%s)' % (nodeenv_version, home_url))}
req = urllib2.Request(url, None, headers)
if ignore_ssl_certs:
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.verify_mode = ssl.CERT_NONE
return urllib2.urlopen(req, con... |
def test_clone_all():
git = 'git'
print(os.path.abspath('.'))
remote_dir = 'test_temp_dir/remote_clone_all'
subprocess.check_call(([git] + ('init %s/meta_project' % remote_dir).split()), cwd='.')
subprocess.check_call(([git] + ('init %s/projectD' % remote_dir).split()), cwd='.')
subprocess.check... |
class FileMetadataCache(SingletonConfigurable):
max_size = Integer(min=1, max=1024, default_value=128, config=True, help='The maximum number of entries allowed in the cache.')
enabled = Bool(default_value=True, config=True, help='Caching is enabled (True) or disabled (False).')
def __init__(self, **kwargs):... |
class MoonrakerOutputModel(PrinterOutputModel):
cameraImageRotationChanged = pyqtSignal()
cameraImageMirrorChanged = pyqtSignal()
def __init__(self, output_controller: MoonrakerOutputController, number_of_extruders: int=1) -> None:
super().__init__(output_controller, number_of_extruders)
sel... |
.integration_test
def test_gen_data_obs_data_mismatch(storage, uniform_parameter, update_config):
resp = GenDataConfig(name='RESPONSE')
obs = xr.Dataset({'observations': (['report_step', 'index'], [[1.0]]), 'std': (['report_step', 'index'], [[0.1]])}, coords={'index': [1000], 'report_step': [0]}, attrs={'respon... |
def test_cli_with_json_output(poetry_venv_factory: PoetryVenvFactory) -> None:
with poetry_venv_factory('example_project') as virtual_env:
issue_report = f'{uuid.uuid4()}.json'
result = virtual_env.run(f'deptry . -o {issue_report}')
expected_output = ['Scanning 2 files...', '', stylize("{BOL... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'policyid'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_pa... |
def test_fit_raises_error_if_df_contains_na(df_enc_na):
encoder = OrdinalEncoder(encoding_method='arbitrary')
with pytest.raises(ValueError) as record:
encoder.fit(df_enc_na)
msg = "Some of the variables in the dataset contain NaN. Check and remove those before using this transformer or set the para... |
def test_linear_solver_change_bc():
mesh = UnitSquareMesh(4, 4, quadrilateral=False)
V = FunctionSpace(mesh, 'P', 1)
u = TrialFunction(V)
v = TestFunction(V)
a = (inner(grad(u), grad(v)) * dx)
bcval = Function(V)
(x, y) = SpatialCoordinate(mesh)
bcval.interpolate((1 + (2 * y)))
bc = ... |
def reference_norm(arr, order=1, axes=None):
if (axes is None):
axes = list(range(len(arr.shape)))
arr = numpy.abs(arr)
out_dtype = arr.dtype
arr = (arr ** order)
for axis in reversed(sorted(axes)):
arr = arr.sum(axis)
res = (arr ** numpy.cast[out_dtype]((1.0 / order)))
retur... |
('aggregate_type', ['non-string-keys'])
def test_deepcopy_with_non_string_keys(aggregate):
provider_copy = providers.deepcopy(aggregate)
assert (aggregate is not provider_copy)
assert isinstance(provider_copy, type(aggregate))
assert (aggregate.providers[ExampleA] is not provider_copy.providers[ExampleA... |
class Tables():
def __init__(self, ui):
self.page = ui.page
self.datatable = self.datatables.table
self.tabulator = self.tabulators.table
self.plotly = self.plotlys.table
self.aggrid = self.aggrids.table
self.pivot = self.pivots.pivot
def aggrids(self) -> CompAgGr... |
class Camera():
def __init__(self, position, look_at, up):
self.position = position.astype(np.float32)
self.look_at = look_at.astype(np.float32)
self.up = up.astype(np.float32)
def get_properties(self, binary_filename):
json_dict = {'type': 'camera', 'position': self.position.tol... |
class OptionPlotoptionsTimelineSonificationDefaultinstrumentoptionsMappingPlaydelay(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 ESP32S2StubLoader(ESP32S2ROM):
FLASH_WRITE_SIZE = 16384
STATUS_BYTES_LENGTH = 2
IS_STUB = True
def __init__(self, rom_loader):
self.secure_download_mode = rom_loader.secure_download_mode
self._port = rom_loader._port
self._trace_enabled = rom_loader._trace_enabled
s... |
def DoFuseIf(f_cursor, s_cursor):
proc = f_cursor.get_root()
if (f_cursor.next() != s_cursor):
raise SchedulingError('expected the two if statements to be fused to come one right after the other')
if1 = f_cursor._node
if2 = s_cursor._node
Check_ExprEqvInContext(proc, if1.cond, [if1], if2.con... |
def enable_ip_forward():
file_path = '/proc/sys/net/ipv4/ip_forward'
try:
with open(file_path) as file:
if (file.read() == 1):
return True
with open(file_path, 'w') as file:
print(1, file=file)
return True
except Exception:
return F... |
def test_mismatching_meshes_indexed_function(mesh1, mesh3):
V1 = VectorFunctionSpace(mesh1, 'CG', 1)
V2 = FunctionSpace(mesh3, 'CG', 1)
donor = Function(V1)
target = Function(V2)
(d1, *_) = split(donor)
with pytest.raises(NotImplementedError):
project(d1, target)
with pytest.raises(N... |
class Migration(migrations.Migration):
dependencies = [('extra_settings', '0007_alter_settings_validator')]
operations = [migrations.AlterField(model_name='setting', name='name', field=models.CharField(help_text='(e.g. SETTING_NAME)', max_length=255, unique=True, verbose_name='Name')), migrations.AlterField(mod... |
def create_very_broken_file(tmpdir, merge_files_oneLR, merge_files_manyLR):
valid = os.path.join(str(tmpdir), 'valid.dlis')
content = ['data/chap3/start.dlis.part', 'data/chap3/template/invalid-repcode-no-value.dlis.part', 'data/chap3/object/object.dlis.part', 'data/chap3/objattr/empty.dlis.part', 'data/chap3/o... |
('pathlib.Path.home', return_value=FAKE_HOME)
.dict(os.environ, {'FOUNDRY_DEV_TOOLS_TRANSFORMS_SQL_SAMPLE_ROW_LIMIT': f'{RANDOM_NUMBER1}'})
def test_env_variable_takes_precedence(tmp):
with PatchConfig(config_overwrite={'jwt': 'whatever', 'foundry_url': 'foundry_config_env_takes_precedence', 'transforms_sql_sample_... |
class OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMapping(Options):
def frequency(self) -> 'OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesBoxplotSonificationDefaultinstrumentoptionsMappingFrequency)
def gapBetwe... |
def test_place_electrodes_equal_spacing_chest_and_spine():
mesh_obj = load_mesh((parent_dir + '/data/mesha06_bumpychestslice_radiological_view_both_lungs_1_0-3.ply'))
plotting_obj = {}
electrode_nodes = place_electrodes_equal_spacing(mesh_obj, 8, 0, 0.5, chest_and_spine_ratio=2, output_obj=plotting_obj)
... |
_PmsiTunnelId.register_type(BGPPathAttributePmsiTunnel.TYPE_INGRESS_REPLICATION)
class PmsiTunnelIdIngressReplication(_PmsiTunnelId):
_VALUE_PACK_STR = '!%ds'
_TYPE = {'ascii': ['tunnel_endpoint_ip']}
def __init__(self, tunnel_endpoint_ip):
super(PmsiTunnelIdIngressReplication, self).__init__()
... |
def gen_sites():
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
for tile_name in sorted(grid.tiles()):
loc = grid.loc_of_tilename(tile_name)
gridinfo = grid.gridinfo_at_loc(loc)
for (site_name, site_type) in gridinfo.sites.items():
if (site_type in ['... |
def strip_buffer_glyphs(view):
line = (- 1)
more = True
last_value = (- 1)
lines = []
mappings = {'crlf': '\r\n', 'cr': '\r', 'lf': '\n'}
while more:
line += 1
value = view.text_point(line, 0)
region = None
for line_type in ('crlf', 'cr', 'lf'):
region... |
class _PopupLayout(configurable.Configurable):
defaults = [('width', 200, 'Width of tooltip'), ('height', 200, 'Height of tooltip'), ('controls', [], 'Controls to display'), ('margin', 5, 'Margin around edge of tooltip'), ('background', '000000', 'Popup background colour'), ('border', '111111', 'Border colour for p... |
class TestUtils():
def make_file(self, filename, text, basedir=None):
if (filename is None):
tmpfile = tempfile.mkstemp(dir=basedir, text=True)
filename = tmpfile[1]
elif (basedir is not None):
filename = os.path.join(basedir, filename)
fp = io.open(filena... |
def test_get_answer_top_p_is_provided(azure_openai_llm, caplog):
with patch('langchain.chat_models.AzureChatOpenAI') as mock_chat:
mock_chat_instance = mock_chat.return_value
mock_chat_instance.return_value = MagicMock(content='Test Response')
prompt = 'Test Prompt'
config = azure_op... |
class Area(Line):
def __init__(self, latlngs: typing.List[s2sphere.LatLng], fill_color: Color=RED, color: Color=TRANSPARENT, width: int=0) -> None:
Line.__init__(self, latlngs, color, width)
if ((latlngs is None) or (len(latlngs) < 3)):
raise ValueError('Trying to create area with less t... |
.django_db
def test_positive_sample_query(award_data_fixture, elasticsearch_transaction_index):
elasticsearch_transaction_index.update_index()
query = {'query': {'bool': {'must': [{'match': {'recipient_location_zip5': 'abcde'}}]}}, '_source': ['award_id']}
client = elasticsearch_transaction_index.client
... |
def test_sampler():
model = SampleModel()
nuts = bm.GlobalNoUTurnSampler()
queries = [model.foo()]
observations = {model.bar(): torch.tensor(0.5)}
num_samples = 10
sampler = nuts.sampler(queries, observations, num_samples, num_adaptive_samples=0)
worlds = list(sampler)
assert (len(worlds... |
class TestSkillLoadingWarningMessages(BaseAEATestCase):
agent_name = 'dummy_aea'
cli_log_options = ['-v', 'DEBUG']
_TEST_HANDLER_CLASS_NAME = 'TestHandler'
_TEST_BEHAVIOUR_CLASS_NAME = 'TestBehaviour'
_test_skill_module_path = 'skill_module_for_testing.py'
_test_skill_module_content = dedent(f''... |
def test_deployment_size_limit(accounts, console_mode):
code = f'''
# 0.2.4
def baz():
assert msg.sender != ZERO_ADDRESS, '{('blah' * 10000)}'
'''
tx = compile_source(code, vyper_version='0.2.4').Vyper.deploy({'from': accounts[0]})
assert (tx.revert_msg == 'exceeds EIP-170 size limit') |
def _tvd_stattest(reference_data: pd.Series, current_data: pd.Series, feature_type: ColumnType, threshold: float) -> Tuple[(float, bool)]:
observed = _total_variation_distance(reference_data, current_data)
p_value = permutation_test(reference_data=reference_data, current_data=current_data, observed=observed, te... |
class EmptySecretHandler(SecretHandler):
def __init__(self, logger: logging.Logger, source_root: Optional[str], cache_dir: Optional[str], version: str) -> None:
super().__init__(logger, '', '', version)
def load_secret(self, resource: 'IRResource', secret_name: str, namespace: str) -> Optional[SecretInf... |
class OptionPlotoptionsFunnel3dSonificationTracksMappingTime(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... |
def subtree_suggester(docs: Iterable[Doc], *, ops: Optional[Ops]=None) -> Ragged:
if (ops is None):
ops = get_current_ops()
spans = []
lengths = []
for doc in docs:
cache = set()
length = 0
for token in doc:
if ((token.left_edge.i, (token.i + 1)) not in cache)... |
def test_match_dualporo():
grid = xtgeo.create_box_grid((4, 3, 5))
grid._dualporo = True
grid._dualperm = True
actnum = np.ones(grid.dimensions, dtype=np.int32)
actnum[(0, 0, 0)] = 0
actnum[(0, 0, 1)] = 1
actnum[(0, 0, 2)] = 2
actnum[(0, 0, 3)] = 3
grid._dualactnum = xtgeo.GridProper... |
class PypiDownloader(PackageGetter):
def __init__(self, client, name, version=None, prerelease=False, save_dir=None):
self.client = client
self.name = name
if version:
if (not self.client.release_urls(name, version)):
raise exceptions.NoSuchPackageException('Packa... |
def fortios_emailfilter(data, fos, check_mode):
fos.do_member_operation('emailfilter', 'bwl')
if data['emailfilter_bwl']:
resp = emailfilter_bwl(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'emailfilter_bwl'))
if check_mode:
return resp
re... |
def test_response_disable_secure_globally(client):
client.app.resp_options.secure_cookies_by_default = False
result = client.simulate_get('/')
cookie = result.cookies['foo']
assert (not cookie.secure)
client.app.resp_options.secure_cookies_by_default = True
result = client.simulate_get('/')
... |
def test_sharding() -> None:
t = staticmaps.TileProvider(name='test', url_pattern='$s/$z/$x/$y', shards=['0', '1', '2'])
shard_counts = [0, 0, 0]
for x in range(0, 100):
for y in range(0, 100):
u = t.url(0, x, y)
for s in [0, 1, 2]:
if (u == f'{s}/0/{x}/{y}'):... |
def schedule(workflow_task_processor, pending_tasks, schedule_time, execution, debug, norender):
if (debug == 'all'):
log.setLevel(10)
pending_tasks = set(pending_tasks)
(execution, run_detached) = execution
thread2tasks = defaultdict(list)
for task in pending_tasks:
thread2tasks[tas... |
def filter_log_fortianalyzer2_override_filter_data(json):
option_list = ['anomaly', 'dlp_archive', 'filter', 'filter_type', 'forward_traffic', 'free_style', 'gtp', 'local_traffic', 'multicast_traffic', 'severity', 'sniffer_traffic', 'voip', 'ztna_traffic']
json = remove_invalid_fields(json)
dictionary = {}
... |
def register():
if (request.method == 'GET'):
return render_template('users/register.html')
g.log = g.log.bind(email=request.form.get('email'))
try:
user = User(request.form['email'], request.form['password'])
DB.session.add(user)
DB.session.commit()
g.log.info('User ... |
class PProfile(pprofile.Profile):
def __init__(self, path, run=True):
self.run = run
self.path = path
pprofile.Profile.__init__(self)
def __enter__(self):
if self.run:
return pprofile.Profile.__enter__(self)
else:
return self
def __exit__(self,... |
class AppleGamesScraper(Scraper):
def get_source() -> Source:
return Source.APPLE
def get_type() -> OfferType:
return OfferType.GAME
def get_schedule() -> list[schedule.Job]:
return [schedule.every().day.at('12:00')]
def get_duration() -> OfferDuration:
return OfferDurati... |
class TestLatestBuilds(BodhiClientTestCase):
def test_latest_builds(self, mocker):
client = bindings.BodhiClient()
client.send_request = mocker.MagicMock(return_value='bodhi-2.4.0-1.fc25')
latest_builds = client.latest_builds('bodhi')
assert (latest_builds == 'bodhi-2.4.0-1.fc25')
... |
def simplify_polygons(self, tolerance: float, preserve_topology: bool) -> bool:
try:
if self.attributes:
raise UserWarning('Attributes are present, but they will be lost when simplifying')
except AttributeError:
pass
recompute_hlen = (self.hname in self.dataframe)
recompute_t... |
def fortios_firewall_service(data, fos, check_mode):
fos.do_member_operation('firewall.service', 'custom')
if data['firewall_service_custom']:
resp = firewall_service_custom(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_service_custom'))
if c... |
def approve(upstream_item: Union[(Tuple[Promise], Promise, VoidPromise)], name: str, timeout: datetime.timedelta):
g = Gate(name, upstream_item=upstream_item, timeout=timeout)
if ((upstream_item is None) or isinstance(upstream_item, VoidPromise)):
raise ValueError("You can't use approval on a task that ... |
class OptionPlotoptionsTilemapSonificationPointgrouping(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.... |
class ActionRecordRolloutRunner(ParallelRolloutRunner):
def __init__(self, max_episode_steps: int, deterministic: bool, action_record_path: str, normalization_samples: int, n_processes: int, verbose: bool):
super().__init__(n_episodes=0, max_episode_steps=max_episode_steps, deterministic=deterministic, reco... |
class UpdateNamespaceResponse(betterproto.Message):
namespace_info: v1namespace.NamespaceInfo = betterproto.message_field(1)
config: v1namespace.NamespaceConfig = betterproto.message_field(2)
replication_config: v1replication.NamespaceReplicationConfig = betterproto.message_field(3)
failover_version: in... |
class OptionPlotoptionsVariwideSonification(Options):
def contextTracks(self) -> 'OptionPlotoptionsVariwideSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionPlotoptionsVariwideSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionPlotoptionsVariwideSonific... |
def sload(evm: Evm) -> None:
key = pop(evm.stack).to_be_bytes32()
if ((evm.message.current_target, key) in evm.accessed_storage_keys):
charge_gas(evm, GAS_WARM_ACCESS)
else:
evm.accessed_storage_keys.add((evm.message.current_target, key))
charge_gas(evm, GAS_COLD_SLOAD)
value = g... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'id'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.