code stringlengths 281 23.7M |
|---|
def django_main(server_getter):
import django
parser = _get_arg_parser()
parser.add_argument('-s', '--settings', help='The settings module to use (must be importable)', required=('DJANGO_SETTINGS_MODULE' not in os.environ))
args = _get_args(parser)
if args.settings:
os.environ['DJANGO_SETTIN... |
class Account():
CONTRACT_TO_ACCOUNT_COUNT = defaultdict(int)
def __init__(self, address, contract, typ=AccountType.DEFAULT, balance=None, storage=None, account_id=None, mapping_id_to_sum=None):
global account_counter
if (account_id is None):
account_counter += 1
self.id = (a... |
.django_db
def test_is_registered_any_way_with_is_attendee_false_and_is_registered_true_should_return_true(mocker, user1, event1):
mock_is_attendee = mocker.patch('manager.templatetags.filters.is_attendee')
mock_is_registered = mocker.patch('manager.templatetags.filters.is_registered')
mock_is_attendee.retu... |
def DoJoinLoops(loop1_c, loop2_c):
if (loop1_c.next() != loop2_c):
raise SchedulingError('expected the second loop to be directly after the first')
loop1 = loop1_c._node
loop2 = loop2_c._node
try:
Check_ExprEqvInContext(loop1_c.get_root(), loop1.hi, [loop1], loop2.lo, [loop2])
except... |
class ExtendedQueue(Queue):
def remove(self, element):
with self.not_empty:
self.queue.remove(element)
self.not_full.notify()
def as_list(self):
with self.mutex:
return [*self.queue]
def put(self, item, put_front=False, **kwargs):
super().put([put_... |
def exposed_filter_links(path):
if (not os.path.exists(path)):
raise IOError(("File at path '%s' doesn't exist!" % path))
with open(path, 'r') as fp:
urls = fp.readlines()
urls = [item.strip() for item in urls if item.strip()]
havestarts = []
for ruleset in WebMirror.rules.load_rules... |
def example():
async def move_vertical_divider(e: ft.DragUpdateEvent):
if (((e.delta_x > 0) and (c.width < 300)) or ((e.delta_x < 0) and (c.width > 100))):
c.width += e.delta_x
(await c.update_async())
async def show_draggable_cursor(e: ft.HoverEvent):
e.control.mouse_cursor ... |
class DummyModel(BaseModel):
def chat(self, messages, max_tokens=None, temperature=0.8):
return 'I am a dummy model.'
def count_tokens(self, messages):
return 0
def get_token_limit(self):
return 4000
def config(self):
return {'class': self.__class__.__name__, 'type': 'mod... |
class LinearEigenproblem():
def __init__(self, A, M=None, bcs=None, bc_shift=0.0):
if (not SLEPc):
raise ImportError('Unable to import SLEPc, eigenvalue computation not possible (try firedrake-update --slepc)')
self.A = A
args = A.arguments()
(v, u) = args
if M:
... |
class Migration(migrations.Migration):
dependencies = [('search', '0014_additional_transaction_search_cols')]
operations = [migrations.AddField(model_name='awardsearch', name='base_and_all_options_value', field=models.DecimalField(blank=True, decimal_places=2, max_digits=23, null=True)), migrations.AddField(mod... |
def run_core() -> None:
import sys
import pathlib
base = (pathlib.Path(__file__) / '..').resolve()
p = (base / 'modmocks')
sys.path.insert(0, str(p.resolve()))
import logging
import utils.log
import settings
utils.log.init_embedded(logging.DEBUG, settings.SENTRY_DSN, settings.VERSION... |
.xfail
.parametrize('expected_txn, raw_tx, expected_tx_hash, r, s, v', (({'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', 'value': , 'gas': 2000000, 'gasPrice': , 'nonce': 0, 'chainId': 1}, HexBytes('0xf86a8086de848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295... |
class OptionSeriesPyramid3dSonificationTracksMappingFrequency(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):
se... |
class UnsignedCharType(Type):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = UNSIGNED_CHAR
self.byte_size = 1
def debug_info(self):
bs = bytearray()
bs.append(ENUM_ABBREV_CODE['BASE_TYPE_WITH_ENCODING'])
bs.append(self.byte_size... |
def train_gpu_with_autocast(model, device, optimizer, data_type, input_size, output_size, batch_size, args):
print('Running with 32-bit weights using autocast to ', data_type, ' data type')
dtype_map = {'float16': torch.float16, 'float': torch.float32, 'tf32': torch.float32, 'bfloat16': torch.bfloat16}
dt =... |
def get_agent_class_from_string(class_name: str) -> GenericAgent:
try:
agent_module = importlib.import_module('.'.join(class_name.split('.')[:(- 1)]))
agent_class = getattr(agent_module, class_name.split('.')[(- 1)])
except Exception as e:
logger.error(f'Not able to load {class_name}. Tr... |
class OptionPlotoptionsColumnZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
... |
class Benchmark(lg.Node):
INPUT = lg.Topic(CaptureResult)
OUTPUT_EXIT = lg.Topic(ExitSignal)
state: BenchmarkState
config: BenchmarkConfig
def setup(self) -> None:
logger.info(f' benchmarking for {self.config.run_time} seconds')
self.state.points = Queue()
self.state.tasks = ... |
def test_message_arity_1() -> None:
def f(a: int) -> str:
pass
(ArgumentMessage, ReturnMessage, _) = function_to_node(f)
assert (ArgumentMessage.__annotations__ == {'a': int})
ArgumentMessage(a=0)
assert (ReturnMessage.__annotations__ == {'sample': str})
ReturnMessage(sample='hello') |
class CupertinoSlider(ConstrainedControl):
def __init__(self, ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=None, bottom: OptionalNumber=None, expand: Union[(None, bool, int)]=None... |
class AmazonVideoApi(VideoInterface):
def video__label_detection_async__launch_job(self, file: str, file_url: str='') -> AsyncLaunchJobResponseType:
return AsyncLaunchJobResponseType(provider_job_id=amazon_launch_video_job(file, 'LABEL'))
def video__text_detection_async__launch_job(self, file: str, file... |
.requires_window_manager
('ert.gui.tools.run_analysis.run_analysis_tool.QMessageBox')
def test_failure(mock_msgbox, mock_tool, qtbot, monkeypatch):
monkeypatch.setattr(run_analysis_tool, 'smoother_update', Mock(side_effect=ErtAnalysisError('some error')))
mock_tool.run()
qtbot.waitUntil((lambda : (len(mock_... |
def extractOldmosstreeWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("Love Rival's Brother", "Love Rival's Brother", 'translated'), ('Thinks I Like Him', 'Everyone... |
class _ContainerProjectsZonesRepository(_base_repository.GCPRepository):
def __init__(self, **kwargs):
super(_ContainerProjectsZonesRepository, self).__init__(component='projects.zones', **kwargs)
def get_serverconfig(self, project_id, zone, fields=None, **kwargs):
arguments = {'projectId': proj... |
class OptionSeriesScatterDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag, js_... |
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):
if errorIndication:
print(('Notification %s not sent: %s' % (sendRequestHandle, errorIndication)))
elif errorStatus:
print(('Notification Receiver returned error for %s: %s %s' % (sendRequestHand... |
class Datalabels(Options):
component_properties = ('color',)
def align(self):
return self._config_get('center')
def align(self, value: str):
self._config(value)
def anchor(self):
return self._config_get('center')
def anchor(self, value: str):
self._config(value)
d... |
class BitgetBot(Passivbot):
def __init__(self, config: dict):
super().__init__(config)
self.ccp = getattr(ccxt_pro, self.exchange)({'apiKey': self.user_info['key'], 'secret': self.user_info['secret'], 'password': self.user_info['passphrase']})
self.ccp.options['defaultType'] = 'swap'
... |
class Solution():
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
def subtree_with_deepest(node):
if (node is None):
return (node, 0)
(lt, ll) = subtree_with_deepest(node.left)
(rt, rl) = subtree_with_deepest(node.right)
if (ll == rl):
... |
def join_returns(cfg, arg_names, function_ast=None):
join_args = [ir.Argument(function_ast, info=n, name=n) for n in arg_names]
join = ir.Block(function_ast, join_args, info='MERGE RETURNS')
returns = list(of_type[ir.Return](cfg.graph.nodes))
if returns:
cfg += CfgSimple.statement(join)
for ... |
class InfoCharacteristic(Characteristic):
def __init__(self, addressfunc=None, modefunc=None):
Characteristic.__init__(self, {'uuid': BLE_INFO_CHAR, 'properties': ['read'], 'descriptors': [Descriptor({'uuid': '2901', 'value': array.array('B', [73, 110, 102, 111, 32, 112, 97, 99, 107, 101, 116])})], 'value':... |
class Calendar():
def __init__(self, ui):
self.page = ui.page
def days(self, month: int=None, content=None, year: int=None, width: types.SIZE_TYPE=(None, '%'), height: types.SIZE_TYPE=(None, 'px'), align: str=None, options: dict=None, html_code: str=None, profile: types.PROFILE_TYPE=None):
width... |
def _find_revert_offset(pc_list: List, source_map: deque, source_node: NodeBase, fn_node: NodeBase, fn_name: Optional[str]) -> None:
if source_map:
if ((len(pc_list) >= 8) and (pc_list[(- 8)]['op'] == 'CALLVALUE')):
pc_list[(- 1)].update(dev='Cannot send ether to nonpayable function', fn=pc_list... |
class BaseTestIssueCertificates(AEATestCaseEmpty):
def setup_class(cls):
super().setup_class()
shutil.copytree(os.path.join(CUR_PATH, 'data', 'dummy_connection'), os.path.join(cls.current_agent_context, 'connections', 'dummy'))
agent_config = cls.load_agent_config(cls.agent_name)
age... |
class IPythonEditor(ILayoutWidget):
dirty = Bool(False)
path = Str()
show_line_numbers = Bool(True)
changed = Event()
key_pressed = Event(KeyPressedEvent)
def load(self, path=None):
def save(self, path=None):
def set_style(self, n, fore, back):
def select_line(self, lineno): |
.object(SpinnakerELB, 'configure_attributes')
.object(SpinnakerELB, 'add_backend_policy')
.object(SpinnakerELB, 'add_listener_policy')
('foremast.elb.create_elb.wait_for_task')
.object(SpinnakerELB, 'make_elb_json', return_value={})
('foremast.elb.create_elb.get_properties')
def test_elb_create_elb(mock_get_properties,... |
def extractWriterupdatesCom(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 t... |
def test_requirements_txt(tmp_path: Path) -> None:
with run_within_dir(tmp_path):
with Path('requirements.txt').open('w') as f:
f.write('foo >= "1.0"')
spec = DependencySpecificationDetector(Path('pyproject.toml')).detect()
assert (spec == DependencyManagementFormat.REQUIREMENTS_... |
class Special():
def __init__(self, constructor, post_deserialize, import_str):
self.constructor = constructor
self.post_deserialize = post_deserialize
self.import_str = import_str
def get_post_deserialize(self, varname):
if self.post_deserialize:
return (self.post_de... |
class OptionSeriesAreaSonificationDefaultspeechoptionsMappingVolume(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def test_gauge(elasticapm_client, prometheus):
metricset = PrometheusMetrics(MetricsRegistry(elasticapm_client))
gauge = prometheus_client.Gauge('a_bare_gauge', 'Bare gauge')
gauge_with_labels = prometheus_client.Gauge('gauge_with_labels', 'Gauge with labels', ['alabel', 'anotherlabel'])
gauge.set(5)
... |
def extractMoonlightnovelsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in... |
class Punpunbikeshare(BikeShareSystem):
sync = True
meta = {'system': 'Smart Bike', 'company': ['BTS Group Holdings']}
def __init__(self, tag, feed_url, meta):
super(Punpunbikeshare, self).__init__(tag, meta)
self.feed_url = feed_url
def update(self, scraper=None):
if (scraper is... |
def test_sandbox_priority():
prio = _PriorityCounter()
assert (prio.get_priority(BuildQueueTask({'build_id': '9', 'task_id': '9', 'project_owner': 'cecil', 'background': False, 'sandbox': 'cecil/foo--submitter'})) == 1)
assert (prio.get_priority(BuildQueueTask({'build_id': '9', 'task_id': '9-fedora-rawhide-... |
class OptionSeriesBulletOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(text, j... |
_projects_ns.route('/')
class Project(Resource):
_to_parameters
_projects_ns.doc(params=fullname_params)
_projects_ns.marshal_with(project_model)
_projects_ns.response(HTTPStatus.OK.value, 'OK, Project data follows...')
_projects_ns.response(HTTPStatus.NOT_FOUND.value, 'No such Copr project found in... |
class OptionPlotoptionsSankeySonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsSankeySonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSankeySonificationDefaultinstrumentoptionsMappingL... |
class SeparatedCoords(Coords):
def __init__(self, separated_coords):
self.separated_coords = [copy.deepcopy(s) for s in separated_coords]
def from_dict(cls, tree):
if (tree['type'] != 'separated'):
raise ValueError('The type of coordinates should be "separated".')
return cls(... |
class TestHNSWJaccard(TestHNSW):
def _create_random_points(self, high=50, n=100, dim=10):
return np.random.randint(0, high, (n, dim))
def _create_index(self, sets, keys=None):
hnsw = HNSW(distance_func=jaccard_distance, m=16, ef_construction=100)
self._insert_points(hnsw, sets, keys)
... |
def merge_ssz_branches(*branches):
o = {}
for branch in branches:
o = {**o, **branch}
keys = sorted(o.keys())[::(- 1)]
pos = 0
while (pos < len(keys)):
k = keys[pos]
if ((k in o) and ((k ^ 1) in o) and ((k // 2) not in o)):
o[(k // 2)] = hash((o[(k & (- 2))] + o[(... |
class TestInlineHilitePlainText(util.MdCase):
extension = ['pymdownx.highlight', 'pymdownx.inlinehilite']
extension_configs = {'pymdownx.inlinehilite': {'style_plain_text': False}}
def test_unstyled_plaintext(self):
self.check_markdown('Lets test inline highlight no guessing and no text styling `imp... |
.parametrize(('exclude', 'expected'), [(('.*file1',), [Path('.cache/file2.py'), Path('dir/subdir/file2.py'), Path('dir/subdir/file3.py'), Path('other_dir/subdir/file2.py')]), (('.cache|other.*subdir',), [Path('dir/subdir/file1.py'), Path('dir/subdir/file2.py'), Path('dir/subdir/file3.py')]), (('.*/subdir/',), [Path('.c... |
class ExpansionTile(ConstrainedControl):
def __init__(self, controls: Optional[List[Control]]=None, ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=None, bottom: OptionalNumber=None,... |
def test_move_block(proc_bar, golden):
c = _find_cursors(proc_bar, 'x = 1.0 ; x = 2.0')[0]
(p0, _) = c._move(c[0].prev().before())
(p1, _) = c._move(c.before())
(p2, _) = c._move(c.after())
(p3, _) = c._move(c[(- 1)].next().after())
(p4, _) = c._move(c[(- 1)].next(2).after())
(p5, _) = c._mo... |
def test_builder_manages_duplicate_compilers(owned_package):
(_, _, compiler_output) = owned_package
manifest = build(BASE_MANIFEST, contract_type('Owned', compiler_output, abi=True, compiler=True, source_id=True), contract_type('Owned', compiler_output, alias='OwnedAlias', abi=True, compiler=True, source_id=Tr... |
class ObjectType(MibNode):
units = ''
maxAccess = 'not-accessible'
status = 'current'
description = ''
reference = ''
def __init__(self, name, syntax=None):
MibNode.__init__(self, name)
self.syntax = syntax
def __eq__(self, other):
return (self.syntax == other)
de... |
class GenericDirectorySource(IndexedSource):
INDEX_CLASS = None
DEFAULT_JSON_FILE = 'climetlab.index'
DEFAULT_DB_FILE = 'climetlab-2.db'
def __init__(self, path, db_path=None, _index=None, **kwargs):
if (_index is not None):
super().__init__(_index, **kwargs)
return
... |
def kube_server_version(version_json=None):
if (not version_json):
version_json = kube_version_json()
server_json = version_json.get('serverVersion', {})
if server_json:
server_major = strip_version(server_json.get('major', None))
server_minor = strip_version(server_json.get('minor',... |
def check_errors(flat_error_nodes, ignored_wires):
error_nodes = {}
for (node, raw_node, generated_nodes) in flat_error_nodes:
if (node not in error_nodes):
error_nodes[node] = {'raw_node': set(raw_node), 'generated_nodes': set()}
assert (error_nodes[node]['raw_node'] == set(raw_node... |
def test_cookies_jar():
class Foo():
def on_get(self, req, resp):
resp.set_cookie('has_permission', 'true')
def on_post(self, req, resp):
if (req.cookies['has_permission'] == 'true'):
resp.status = falcon.HTTP_200
else:
resp.status ... |
class LogManager():
def __init__(self, dbt_log_manager):
self._dbt_log_manager = dbt_log_manager
def applicationbound(self):
with self._dbt_log_manager.applicationbound():
(yield)
def set_debug(self):
self._dbt_log_manager.set_debug()
LOGGER.set_level(logging.DEBU... |
class CommitteeSearch(BaseModel):
__tablename__ = 'ofec_committee_fulltext_mv'
id = db.Column(db.String)
name = db.Column(db.String, doc=docs.COMMITTEE_NAME)
fulltxt = db.Column(TSVECTOR)
receipts = db.Column(db.Numeric(30, 2))
disbursements = db.Column(db.Numeric(30, 2))
independent_expendi... |
def test_config_cycle(testbot):
testbot.push_message('!plugin config Webserver')
m = testbot.pop_message()
assert ('Default configuration for this plugin (you can copy and paste this directly as a command)' in m)
assert ('Current configuration' not in m)
testbot.assertInCommand("!plugin config Webse... |
class ModifyStateAdd(base_tests.SimpleProtocol):
def runTest(self):
logging.info('Running Modify_State_Add test')
of_ports = config['port_map'].keys()
of_ports.sort()
delete_all_flows(self.controller)
logging.info('Inserting a flow entry')
logging.info('Expecting acti... |
def _warn_staging_overrides(ctx: click.core.Context, param: typing.Union[(click.core.Option, click.core.Parameter)], value: str) -> str:
if ctx.params.get('staging', False):
if (((param.name == 'url') and (value != constants.BASE_URL)) or ((param.name == 'id_provider') and (value != constants.IDP))):
... |
class EditForum(MethodView):
decorators = [allows.requires(IsAdmin, on_fail=FlashAndRedirect(message=_('You are not allowed to modify forums.'), level='danger', endpoint='management.overview'))]
form = EditForumForm
def get(self, forum_id):
forum = Forum.query.filter_by(id=forum_id).first_or_404()
... |
class ExecuteWrapInstanceCommand(sublime_plugin.TextCommand):
def run(self, edit):
obj = WrapInstance.obj
value = WrapInstance.value
style = obj._style[value]
obj.insert_regions = []
for sel in obj.view.sel():
if (style == 'indent_block'):
obj.bloc... |
class HTTPMissingParam(HTTPBadRequest):
_args(allowed_positional=1)
def __init__(self, param_name, headers=None, **kwargs):
description = 'The "{0}" parameter is required.'
description = description.format(param_name)
super().__init__(title='Missing parameter', description=description, h... |
def test_named_type_cannot_be_redefined():
schema = {'type': 'record', 'namespace': 'test.avro.training', 'name': 'SomeMessage', 'fields': [{'name': 'is_error', 'type': 'boolean', 'default': False}, {'name': 'outcome', 'type': [{'type': 'record', 'name': 'SomeMessage', 'fields': []}, {'type': 'record', 'name': 'Err... |
class _Chain(References):
def __init__(self, sequence1: References, sequence2: References) -> None:
assert (sequence1.ndims == sequence2.ndims), 'cannot chain sequences with different ndims'
assert (sequence1 and sequence2), 'inefficient; at least one of the sequences is empty'
assert (not _... |
class LatticeTyper(TyperBase[bt.BMGLatticeType]):
_dispatch: Dict[(type, Callable)]
def __init__(self) -> None:
TyperBase.__init__(self)
self._dispatch = {bn.Observation: self._type_observation, bn.Query: self._type_query, bn.DirichletNode: self._type_dirichlet, bn.AdditionNode: self._type_addit... |
class OptionPlotoptionsColumnpyramidTooltipDatetimelabelformats(Options):
def day(self):
return self._config_get('%A, %e %b %Y')
def day(self, text: str):
self._config(text, js_type=False)
def hour(self):
return self._config_get('%A, %e %b, %H:%M')
def hour(self, text: str):
... |
class DerivablePaths():
def to_derivation_data(self) -> Dict[(str, Any)]:
return {'subpaths': list(self._sequence_watermarks.items())}
def set_row(self, row: Optional[MasterKeyRow]=None) -> None:
self._sequence_watermarks: Dict[(Sequence[int], int)] = {}
if (row is not None):
... |
class ColorOptions(Option):
primary_color: str = RED
secondary_color: str = GREY
current_data_color: Optional[str] = None
reference_data_color: Optional[str] = None
additional_data_color: str = '#0a5f38'
color_sequence: Sequence[str] = COLOR_DISCRETE_SEQUENCE
fill_color: str = 'LightGreen'
... |
class Command(BaseCommand):
args = '<on|off>'
help = f'run python manage.py maintenance_mode {args} to change maintenance-mode state'
def add_arguments(self, parser):
parser.add_argument('state')
parser.add_argument('--interactive', dest='interactive', action='store_true')
def get_mainte... |
class tag_filter(object):
MODE_RETAIN = 1
MODE_DROP = 2
__mode = MODE_DROP
__text = None
filter_tag_list = None
filter_property_list = None
def __init__(self, text, filter_mode=MODE_DROP):
self.__mode = filter_mode
self.__text = text
self.filter_property_list = []
... |
def verify(color: 'Color', tolerance: float) -> bool:
channels = alg.no_nans(color[:(- 1)])
for (i, value) in enumerate(channels):
chan = color._space.CHANNELS[i]
a = chan.low
b = chan.high
if (chan.flags & FLG_ANGLE):
continue
if (not chan.bound):
... |
(name='prefix.delete_local', req_args=[ROUTE_DISTINGUISHER, PREFIX], opt_args=[VRF_RF])
def delete_local(route_dist, prefix, route_family=VRF_RF_IPV4):
try:
tm = CORE_MANAGER.get_core_service().table_manager
tm.update_vrf_table(route_dist, prefix, route_family=route_family, is_withdraw=True)
... |
class OptionSeriesWaterfallSonificationTracksMappingPitch(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._c... |
class ObtainJSONWebTokenMixin(JSONWebTokenMixin):
def __init_subclass_with_meta__(cls, name=None, **options):
assert getattr(cls, 'resolve', None), f'{(name or cls.__name__)}.resolve method is required in a JSONWebTokenMutation.'
super().__init_subclass_with_meta__(name=name, **options) |
def get_grouped_critpath_components(collection='master', component_type='rpm', components=None):
critpath_type = config.get('critpath.type')
if (critpath_type != 'json'):
if (not critpath_type):
critpath_type = '(default)'
raise ValueError(f'critpath.type {critpath_type} does not sup... |
class OptionPlotoptionsSunburstLevelsColorvariation(Options):
def key(self):
return self._config_get(None)
def key(self, text: str):
self._config(text, js_type=False)
def to(self):
return self._config_get(None)
def to(self, num: float):
self._config(num, js_type=False) |
def _colorIsCGColorRef(color):
color = (('(CGColorRef)(' + color) + ')')
result = fb.evaluateExpressionValue('(unsigned long)CFGetTypeID({color}) == (unsigned long)CGColorGetTypeID()'.format(color=color))
if ((result.GetError() is not None) and (str(result.GetError()) != 'success')):
print('got erro... |
def warn_stacklevel() -> int:
try:
module_name = __name__.partition('.')[0]
module_path = Path(sys.modules[module_name].__file__)
module_is_folder = (module_path.name == '__init__.py')
if module_is_folder:
module_path = module_path.parent
for (level, frame) in enu... |
def skip_input_signal_add_output_signal(single_output, out_flex_key, in_flex_key, st_flex_key):
def wrapper(f):
(f)
def decorated_function(*args, **kwargs):
(args, kwargs, fltr) = _skip_inputs(args, kwargs, [in_flex_key, st_flex_key])
cached_ctx = fltr[1]
if ((cac... |
class OptionPlotoptionsBulletAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
... |
class BinaryOp(Node):
__slots__ = ('op', 'left', 'right', 'coord', '__weakref__')
def __init__(self, op, left, right, coord=None):
self.op = op
self.left = left
self.right = right
self.coord = coord
def children(self):
nodelist = []
if (self.left is not None):... |
class RoleUser(ModelSimple):
allowed_values = {('value',): {'USER': 'user', 'BILLING': 'billing', 'ENGINEER': 'engineer', 'SUPERUSER': 'superuser'}}
validations = {}
additional_properties_type = None
_nullable = False
_property
def openapi_types():
return {'value': (str,)}
_property
... |
def exposed_test_local_rpc_fetch():
print('Chromium Test')
rpc_interface = common.get_rpyc.RemoteFetchInterface()
rpc_interface.check_ok()
print('RPC:', rpc_interface)
print('Dispatching job engine')
rpc_interface.check_ok()
raw_job3 = WebMirror.JobUtils.buildjob(module='SmartWebRequest', ca... |
class DisrupterCable(Disrupter):
PULL_MESSAGE = "Pull the ethernet cable.\nIf you're using a VM then you can simulate this by disconnecting the network adapter from the VM settings.\nNOTE: You should press enter BEFORE pulling the cable to maximize the chance of detecting a leak.\n"
PLUG_MESSAGE = 'Replace the ... |
class BaseIntegrityOneColumnTest(Test, ABC):
group: ClassVar = DATA_INTEGRITY_GROUP.id
_metric: ColumnSummaryMetric
column_name: ColumnName
def __init__(self, column_name: Union[(str, ColumnName)], is_critical: bool=True):
self.column_name = ColumnName.from_any(column_name)
super().__ini... |
class MagiclinkInternalRefsPattern(_MagiclinkReferencePattern):
ANCESTOR_EXCLUDES = ('a',)
def handleMatch(self, m, data):
if ((not self.user) or (not self.repo)):
return (None, None, None)
is_commit = m.group('commit')
is_diff = m.group('diff')
value = (m.group('comm... |
def remove_tones(sentence):
words = sentence.split()
content = ''
underscored_content = ''
for word in words:
if (word == '.'):
word = 'pau'
last_char = word[(- 1)]
if last_char.isdigit():
c_word = ''.join((k for k in word[:(- 1)]))
u_word = ((... |
class DecisionStateMachineBase(DecisionStateMachine):
id: DecisionId = None
state: DecisionState = DecisionState.CREATED
state_history: List[str] = field(default_factory=list)
def __post_init__(self):
self.state_history.append(str(self))
def get_state(self) -> DecisionState:
return s... |
class Websocket(ASGIIngressMixin, _Websocket):
__slots__ = ['_scope', '_receive', '_send', '_accepted']
def __init__(self, scope: Scope, receive: Receive, send: Send):
super().__init__(scope, receive, send)
self._accepted = False
self._flow_receive = None
self._flow_send = None
... |
def load_model(config, model, optimizer=None):
logger = get_logger()
global_config = config['Global']
checkpoints = global_config.get('checkpoints')
pretrained_model = global_config.get('pretrained_model')
best_model_dict = {}
if checkpoints:
if checkpoints.endswith('.pdparams'):
... |
def flatten_multilists_attributes(data):
multilist_attrs = [['drop_infected'], ['store_infected'], ['drop_machine_learning'], ['store_machine_learning'], ['drop_blocked'], ['store_blocked'], ['drop_heuristic'], ['store_heuristic'], ['drop_intercepted'], ['store_intercepted']]
for attr in multilist_attrs:
... |
class OptionPlotoptionsPolygonSonificationDefaultspeechoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str)... |
def test_when_missing_values_is_ignore(df_vartypes):
df_na = df_vartypes.copy()
df_na.loc[(1, 'Age')] = np.nan
transformer = RelativeFeatures(variables=['Age', 'Marks'], reference=['Age', 'Marks'], func=['sub'], missing_values='ignore')
X = transformer.fit_transform(df_na)
ref = pd.DataFrame.from_di... |
def extractNovelAffairs(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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.