code stringlengths 281 23.7M |
|---|
class LoadingPipeline():
def __init__(self, data_loader, columns: List[str]):
self.data_loader = data_loader
self.columns = columns
def fit(self, index):
None
def execute(self, index):
data_df = self.data_loader.load(index)
data_df = data_df[self.columns]
retu... |
def test_parse_config_columns_sanity(raw_config_full):
config = loads_configuration(raw_config_full)
assert (len(config['Columns']) == 64), 'Unexpected columns length'
assert all(((0 <= width <= 65535) for width in config['Columns'])), 'Unexpected column width size'
assert (len(config['ColumnMap']) == 6... |
.gui()
.skipif((sys.platform != 'linux'), reason='Linux specific test')
def test_synchronized_capture_triggers_timeout(monkeypatch, dbus_portal):
timeout = 1
monkeypatch.setattr(dbus_portal, 'TIMEOUT_SECONDS', timeout)
monkeypatch.setattr(dbus_portal.OrgFreedesktopPortalScreenshot, 'grab_full_desktop', (lam... |
_models('spacy.GPT-4.v2')
def openai_gpt_4_v2(config: Dict[(Any, Any)]=SimpleFrozenDict(temperature=_DEFAULT_TEMPERATURE), name: Literal[('gpt-4', 'gpt-4-0314', 'gpt-4-32k', 'gpt-4-32k-0314')]='gpt-4', strict: bool=OpenAI.DEFAULT_STRICT, max_tries: int=OpenAI.DEFAULT_MAX_TRIES, interval: float=OpenAI.DEFAULT_INTERVAL, ... |
class CacheUpdateManager(Thread):
def __init__(self, log: Logger, component_cache: ComponentCacheType, refresh_queue: RefreshQueue, update_queue: UpdateQueue):
super().__init__()
self.daemon = True
self.name = 'CacheUpdateManager'
self.log: Logger = log
self._component_cache:... |
def write_json(save_path, dataset, waves, transcripts):
out_file = os.path.join(save_path, (dataset + '.json'))
with open(out_file, 'w') as fid:
for wave_file in waves:
audio = torchaudio.load(wave_file)
duration = (audio[0].numel() / audio[1])
key = os.path.basename(... |
def test_template_dpa_raises_exceptions_if_matching_sf_is_not_an_attack_selection_function(sf, building_container):
with pytest.raises(TypeError):
scared.TemplateDPAAttack(container_building=building_container, reverse_selection_function=sf, selection_function='foo', model=scared.HammingWeight()) |
def upgrade():
op.add_column('events', sa.Column('icon', sa.String(), nullable=True))
op.add_column('events', sa.Column('large', sa.String(), nullable=True))
op.add_column('events_version', sa.Column('icon', sa.String(), autoincrement=False, nullable=True))
op.add_column('events_version', sa.Column('lar... |
class ListMixinTest(QuickbooksUnitTestCase):
('quickbooks.mixins.ListMixin.where')
def test_all(self, where):
Department.all()
where.assert_called_once_with('', order_by='', max_results=100, start_position='', qb=None)
def test_all_with_qb(self):
with patch.object(self.qb_client, 'qu... |
def readiness_score_recommendation(readiness_score):
try:
readiness_score = int(readiness_score)
if (readiness_score == 0):
return ''
elif (readiness_score >= oura_high_threshold):
return 'High'
elif (readiness_score >= oura_med_threshold):
return ... |
def _get_branch_results(build):
(branch_false, branch_true) = [sorted(i) for i in list(coverage.get_coverage_eval().values())[0]['EVMTester']['0'][1:]]
coverage.clear()
branch_results = {True: [], False: []}
for i in branch_true:
(key, map_) = _get_branch(build, i, True)
branch_results[k... |
def update_function_text(feedrow, new_func):
current = feedrow.func.strip()
new_func = new_func.strip()
print('New function:', new_func)
print('Current function:', current)
if (current == new_func):
return {'error': True, 'message': 'Function has not changed? Nothing to do!', 'reload': False... |
.parametrize('args', [('CG', 1), ('DG', 1), EnrichedElement(HDiv(TensorProductElement(FiniteElement('RT', triangle, 2), FiniteElement('DG', interval, 1))), HDiv(TensorProductElement(FiniteElement('DG', triangle, 1), FiniteElement('CG', interval, 2)))), EnrichedElement(HCurl(TensorProductElement(FiniteElement('RT', tria... |
def issue_refund(payment, amount=None):
if ((payment.payment_service == 'Stripe') and settings.STRIPE_SECRET_KEY):
return stripe_issue_refund(payment, amount)
elif ((payment.payment_service == 'USAePay') and settings.USA_E_PAY_KEY):
return usaepay_issue_refund(payment, amount)
elif ((not (pa... |
class OptionSeriesFunnelSonificationTracksMappingLowpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class ConverterDUT(Module):
def __init__(self, user_data_width, native_data_width, mem_depth, separate_rw=True, read_latency=0):
self.separate_rw = separate_rw
if separate_rw:
self.write_user_port = LiteDRAMNativeWritePort(address_width=32, data_width=user_data_width)
self.wr... |
def add_to_app(components: List[Standalone.Component], app_path: Union[(str, Path)], folder: str='assets', name: str='{selector}', raise_exception: bool=False, view_path: str=node.APP_FOLDER) -> dict:
result = {'dependencies': {}, 'styles': [], 'scripts': [], 'modules': {}}
for component in components:
... |
def create_custom_doctype():
if (not frappe.db.exists('DocType', 'Test Patient Feedback')):
doc = frappe.get_doc({'doctype': 'DocType', 'module': 'Healthcare', 'custom': 1, 'is_submittable': 1, 'fields': [{'label': 'Date', 'fieldname': 'date', 'fieldtype': 'Date'}, {'label': 'Patient', 'fieldname': 'patient... |
def generate_bigquery(bigquery_config: BigQueryConfig) -> List[Dict[(str, str)]]:
log.info('Generating datasets from BigQuery')
try:
bigquery_datasets = generate_bigquery_datasets(bigquery_config)
except ConnectorFailureException as error:
raise HTTPException(status_code=status.HTTP_401_UNAU... |
class SourceCode(_common_models.FlyteIdlEntity):
link: Optional[str] = None
def to_flyte_idl(self):
return description_entity_pb2.SourceCode(link=self.link)
def from_flyte_idl(cls, pb2_object: description_entity_pb2.SourceCode) -> 'SourceCode':
return (cls(link=pb2_object.link) if pb2_object... |
class OptionSeriesSolidgaugeDataDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(te... |
class Channel(str):
def __new__(cls, name: str, low: float, high: float, mirror_range: bool=False, bound: bool=False, flags: int=0, limit: Tuple[(Optional[float], Optional[float])]=(None, None), nans: float=0.0) -> 'Channel':
obj = super().__new__(cls, name)
obj.low = low
obj.high = high
... |
class Solution():
def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]:
G = defaultdict(set)
for (i, j) in edges:
G[i].add(j)
G[j].add(i)
def dfs(node, parent, depth):
ans = 1
for neib in G[node]:
if (neib... |
def _get_kwargs(*, client: Client, start_date: Union[(Unset, None, datetime.date)]=UNSET, end_date: Union[(Unset, None, datetime.date)]=UNSET) -> Dict[(str, Any)]:
url = '{}/billing/user_spending'.format(client.base_url)
headers: Dict[(str, str)] = client.get_headers()
cookies: Dict[(str, Any)] = client.get... |
def construct_ner_instruction(text: str) -> str:
example_output = [{'Entity': 'Barack Obama', 'Type': 'Person', 'Confidence': 0.98}, {'Entity': '44th President', 'Type': 'Position', 'Confidence': 0.95}, {'Entity': 'United States', 'Type': 'Country', 'Confidence': 0.99}]
return f'''Please extract named entities,... |
def test_butterworth_returns_correct_value_with_highpass_filter_type_and_float32_precision(trace):
(b, a) = signal.butter(3, (.0 / (.0 / 2)), 'highpass')
b = b.astype('float32')
a = a.astype('float32')
expected = signal.lfilter(b, a, trace)
result = scared.signal_processing.butterworth(trace, .0, .0... |
def parse_annotations(annot, annot_file):
if (annot == True):
with open(annot_file, 'r') as annot_f:
for line in annot_f:
if line.startswith('#'):
continue
(hit, annotation) = parse_annotation_line(line)
(yield annotation)
e... |
def data_processor(df, logger) -> list:
df = df.dropna(thresh=2)
df.columns = df.columns.str.strip()
df = df.tail(288)
df['Date/Time'] = df['Date/Time'].map(timestamp_converter)
known_keys = (GENERATION_MAPPING.keys() | {'Date/Time', 'Load'})
column_headers = set(df.columns)
unknown_keys = (... |
class WafFirewallVersionResponseDataAttributesAllOf(ModelNormal):
allowed_values = {('last_deployment_status',): {'None': None, 'NULL': 'null', 'PENDING': 'pending', 'IN_PROGRESS': 'in progress', 'COMPLETED': 'completed', 'FAILED': 'failed'}}
validations = {}
_property
def additional_properties_type():
... |
def get_vocab_lists():
return [{'list_name': 'HSK Level 1', 'list_id': '1ebcad3f-5dfd-6bfe-bda4-acde', 'list_difficulty_level': 'Beginner', 'date_created': '2018-12-16T23:06:48.467526', 'created_by': 'admin'}, {'list_name': 'HSK Level 2', 'list_id': '1ebcad3f-adc0-6f42-b8b1-acde', 'list_difficulty_level': 'Beginner... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 59
PLUGIN_NAME = 'Input - Rotary Encoder (TESTING)'
PLUGIN_VALUENAME1 = 'Counter'
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_DUAL
self.vtype = rpieGlobals.SENSOR_TY... |
class CmdMap(MuxCommand):
key = 'map'
def func(self):
size = _BASIC_MAP_SIZE
max_size = _MAX_MAP_SIZE
if self.args.isnumeric():
size = min(max_size, int(self.args))
map_here = Map(self.caller, size=size).show_map()
self.caller.msg((map_here, {'type': 'map'})) |
def check_skin_installed():
params = {'addonid': 'skin.estuary_embycon', 'properties': ['version', 'enabled']}
result = JsonRpc('Addons.GetAddonDetails').execute(params)
log.debug('EmbyCon Skin Details: {0}', result)
installed = (result.get('result') is not None)
version = 'na'
if installed:
... |
class OptionPlotoptionsBellcurveSonificationTracksMappingLowpassResonance(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str)... |
class TestErasureEmailConnectorMethods():
email_defined = EmailSchema(third_party_vendor_name="Dawn's Bookstore", recipient_email_address='', advanced_settings=AdvancedSettings(identity_types=IdentityTypes(email=True, phone_number=False)))
phone_defined = EmailSchema(third_party_vendor_name="Dawn's Bookstore", ... |
def load_exclude_definitions(file_globs: List[str]) -> List[FieldNestedEntry]:
if (not file_globs):
return []
excludes: List[FieldNestedEntry] = loader.load_definitions(file_globs)
if (not excludes):
raise ValueError('--exclude specified, but no exclusions found in {}'.format(file_globs))
... |
class IPv4TCPDstMasked(MatchTest):
def runTest(self):
match = ofp.match([ofp.oxm.eth_type(2048), ofp.oxm.ip_proto(6), ofp.oxm.tcp_dst_masked(52, 254)])
matching = {'tcp dport=53': simple_tcp_packet(tcp_dport=53), 'tcp dport=52': simple_tcp_packet(tcp_dport=52)}
nonmatching = {'tcp dport=54':... |
class desc_stats_request(stats_request):
version = 5
type = 18
stats_type = 0
def __init__(self, xid=None, flags=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self... |
def use_experimental_feature(ctx, param, value):
if (not value):
return
if (value == 'dynamic-feed'):
import bench.cli
bench.cli.dynamic_feed = True
bench.cli.verbose = True
else:
from bench.exceptions import FeatureDoesNotExistError
raise FeatureDoesNotExistE... |
class BstDfs(Bst):
def in_order_traversal(self, node, visit_func):
if (node is not None):
self.in_order_traversal(node.left, visit_func)
visit_func(node)
self.in_order_traversal(node.right, visit_func)
def pre_order_traversal(self, node, visit_func):
if (node ... |
class BaseFileAdmin(BaseView, ActionsMixin):
can_upload = True
can_download = True
can_delete = True
can_delete_dirs = True
can_mkdir = True
can_rename = True
allowed_extensions = None
editable_extensions = tuple()
list_template = 'admin/file/list.html'
upload_template = 'admin/f... |
class Migration(migrations.Migration):
dependencies = [('awards', '0092_transactionfpds_entity_data_source'), ('recipient', '0020_auto__1352'), ('search', '0007_transactionsearch_parent_uei'), ('transactions', '0008_sourceprocurementtransaction_entity_data_source')]
operations = [migrations.RunSQL(sql='CREATE S... |
def test_get_columns():
definition = DataDefinition(columns=[ColumnDefinition('id', ColumnType.Categorical), ColumnDefinition('datetime', ColumnType.Datetime), ColumnDefinition('target', ColumnType.Categorical), ColumnDefinition('predicted', ColumnType.Categorical), ColumnDefinition('class_1', ColumnType.Numerical)... |
def deprecated(warn: bool=True, alternative: Optional[Callable]=None, deprecation_text=None):
def decorator(function):
def wrapper(*args, **kwargs):
info = f'`{function.__name__}` is deprecated.'
if alternative:
info += f' Use `{alternative.__name__}` instead'
... |
_heads([JacobiTheta, JacobiThetaQ])
def tex_JacobiTheta(head, args, **kwargs):
argstr = [arg.latex(**kwargs) for arg in args]
midsep = ','
if (len(args) == 3):
index = args[0].latex(in_small=True)
z = argstr[1]
tau = argstr[2]
return ('\\theta_{%s}\\!\\left(%s %s %s\\right)' ... |
def schedule_jobs(sched):
for (module, name, interval_seconds) in jobs.JOBS:
log.info('Scheduling %s to run every %s hours.', module, (interval_seconds / (60 * 60)))
sched.add_job(run_job, trigger='interval', seconds=interval_seconds, start_date='2000-1-1 0:00:00', name=name, id=name, args=(module,)... |
class RelationshipWafFirewallVersions(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():
la... |
def remove_index_for_records(records, space):
from redis.exceptions import ResponseError
r = frappe.cache()
for d in records:
try:
key = r.make_key(f'{PREFIX}{space}:{d.name}').decode()
r.ft(space).delete_document(key)
except ResponseError:
pass |
def build_request_data(award_ids, subawards):
return json.dumps({'filters': {'time_period': [{'start_date': '2007-10-01', 'end_date': '2020-09-30'}], 'award_type_codes': ['A', 'B', 'C', 'D'], 'award_ids': award_ids}, 'fields': [('Sub-Award ID' if subawards else 'Award ID')], 'sort': ('Sub-Award ID' if subawards els... |
.parametrize('primary_type, expected', (('Mail', 'Mail(Person from,Person to,string contents)Person(string name,address wallet)'), ('Person', 'Person(string name,address wallet)')))
def test_encode_type_eip712(primary_type, expected, eip712_example_types):
assert (encode_type(primary_type, eip712_example_types) == ... |
class BrokenCommand(click.Command):
def __init__(self, name: str) -> None:
click.Command.__init__(self, name)
util_name = os.path.basename(((sys.argv and sys.argv[0]) or __file__))
self.help = ('\nWarning: entry point could not be loaded. Contact its author for help.\n\n\x08\n' + traceback.f... |
class DEITP(DeltaE):
NAME = 'itp'
def __init__(self, scalar: float=720) -> None:
self.scalar = scalar
def distance(self, color: Color, sample: Color, scalar: (float | None)=None, **kwargs: Any) -> float:
if (scalar is None):
scalar = self.scalar
(i1, t1, p1) = color.conve... |
class Line(CommConfigs):
def fill(self):
return self._get_commons()
def fill(self, value: Union[(bool, str)]):
self._set_commons(value)
def stepped(self):
return self._get_commons()
def stepped(self, value: Union[(bool, str)]):
self._set_commons(value)
def showLine(se... |
def major_object_class_with_children(major_code, minor_codes):
retval = []
for minor_code in minor_codes:
retval.append(baker.make('references.ObjectClass', id=minor_code, major_object_class=major_code, major_object_class_name=f'{major_code} name', object_class=f'000{minor_code}', object_class_name=f'00... |
def test_offset_with_connector_param_reference(response_with_body):
config = OffsetPaginationConfiguration(incremental_param='page', increment_by=1, limit={'connector_param': 'limit'})
connector_params = {'limit': 10}
request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/conver... |
class LAD(TC_base):
def __init__(self, M, A, B):
TC_base.__init__(self, nc=1, variableNames=['u'], mass={0: {0: 'linear'}}, advection={0: {0: 'linear'}}, diffusion={0: {0: {0: 'constant'}}}, potential={0: {0: 'u'}}, reaction={0: {0: 'linear'}})
self.M = M
self.A = A
self.B = B
de... |
def extractBobateatranslationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('wfiltu', 'Why fall in love if you can attend Tsinghua University', 'translated'), ('sooew', 'S... |
def add_scorer_args(parser: argparse.ArgumentParser, cli_argument_list: Optional[List[str]]=None):
if (cli_argument_list is None):
(args, _) = parser.parse_known_args()
else:
(args, _) = parser.parse_known_args(cli_argument_list)
for metric in args.latency_metrics:
get_scorer_class('... |
def _tokenize_paren_block(string, pos):
paren_re = re.compile('[()]')
paren_level = (string[:pos].count('(') - string[:pos].count(')'))
while (paren_level > 0):
m = paren_re.search(string[pos:])
if (m.group(0) == '('):
paren_level += 1
else:
paren_level -= 1
... |
class Falcon(HuggingFace):
MODEL_NAMES = Literal[('falcon-rw-1b', 'falcon-7b', 'falcon-7b-instruct', 'falcon-40b-instruct')]
def __init__(self, name: MODEL_NAMES, config_init: Optional[Dict[(str, Any)]], config_run: Optional[Dict[(str, Any)]]):
self._tokenizer: Optional['transformers.AutoTokenizer'] = N... |
class ConditionNode(AbstractSyntaxTreeNode):
def __init__(self, condition: LogicCondition, reaching_condition: LogicCondition, ast: Optional[AbstractSyntaxInterface]=None):
super().__init__(reaching_condition, ast)
self.condition: LogicCondition = condition
def __hash__(self) -> int:
ret... |
def get_price(symbol: str):
info = yfinance.Ticker(symbol).fast_info
change = (info.last_price - info.previous_close)
percent_change = ((change / info.last_price) * 100)
price_str = format_cents(str(info.last_price))
percent_str = format_cents(str(percent_change))
if (percent_str[0] != '-'):
... |
.parametrize('input_vars_1', ['dates_full', None])
.parametrize('input_vars_2', ['dates_na', ['dates_full', 'dates_na'], None])
def test_raises_error_when_nan_in_reference_in_transform(df_nan, input_vars_1, input_vars_2):
tr = DatetimeSubtraction(variables=input_vars_1, reference=input_vars_2, missing_values='raise... |
def get_id(view_kwargs):
if (view_kwargs.get('event_identifier') is not None):
event = safe_query_kwargs(Event, view_kwargs, 'event_identifier', 'identifier')
if (event.id is not None):
view_kwargs['event_id'] = event.id
if (view_kwargs.get('event_id') is not None):
stripe_au... |
def test_invalid_downstream_ref():
node0 = OperatorNode({}, {'name': 'test0', 'type': 'none', 'upstream_dependencies': ['test1']})
node1 = OperatorNode({}, {'name': 'test1', 'type': 'none'})
node2 = OperatorNode({}, {'name': 'test2', 'type': 'none', 'downstream_dependencies': ['test4']})
with pytest.rai... |
(scope='function')
def mariadb_integration_db(mariadb_integration_session):
truncate_all_tables(mariadb_integration_session)
with open('./docker/sample_data/mariadb_example_data.sql', 'r') as query_file:
lines = query_file.read().splitlines()
filtered = [line for line in lines if (not line.start... |
class TranslateFlinger(Flinger):
def __init__(self, size: np.ndarray, scale: np.ndarray, offset: np.ndarray) -> None:
super().__init__(size)
self.scale: np.ndarray = scale
self.offset: np.ndarray = offset
def fling(self, coordinates: np.ndarray) -> np.ndarray:
return (self.scale ... |
def remove_signing_keys(build_dir):
for (root, dirs, files) in os.walk(build_dir):
gradlefile = None
if ('build.gradle' in files):
gradlefile = 'build.gradle'
elif ('build.gradle.kts' in files):
gradlefile = 'build.gradle.kts'
if gradlefile:
path =... |
class TemporalEnsemble(BaseEnsemble):
def __init__(self, step_size=1, burn_in=None, window=None, lag=0, scorer=None, raise_on_exception=True, array_check=None, verbose=False, n_jobs=(- 1), backend='threading', model_selection=False, sample_size=20, layers=None):
super(TemporalEnsemble, self).__init__(shuffl... |
def upgrade() -> None:
op.create_table('announcements', sa.Column('id', sa.Integer(), nullable=False), sa.Column('channel', sa.Enum('ALL', 'FEED', 'TELEGRAM', name='channel'), nullable=False), sa.Column('date', AwareDateTime(), nullable=False), sa.Column('text_markdown', sa.String(), nullable=False), sa.PrimaryKeyC... |
class ReadabilityExtractor(AbstractExtractor):
def __init__(self):
self.name = 'readability'
def extract(self, item):
doc = Document(deepcopy(item['spider_response'].body))
description = doc.summary()
article_candidate = ArticleCandidate()
article_candidate.extractor = se... |
class ArrayField(forms.CharField):
widget = ArrayWidget
def __init__(self, *args, **kwargs):
self.tags = kwargs.pop('tags', False)
super(ArrayField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(ArrayField, self).clean(value)
try:
return pa... |
class OptionPlotoptionsErrorbarDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
def extractSingletranslationsBlogspotCom(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 OptionSeriesOrganizationSonificationContexttracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesOrganizationSonificationContexttracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesOrganizationSonificationContexttracksMappingHighpassFrequency)
def re... |
class PoleHook(Boxes):
def __init__(self) -> None:
Boxes.__init__(self)
self.addSettingsArgs(edges.FingerJointSettings)
self.argparser.add_argument('--diameter', action='store', type=float, default=50.0, help='diameter of the thing to hook')
self.argparser.add_argument('--screw', act... |
def draw_walls(svg: svgwrite.Drawing, building: Building, segment: Segment, height: float, shift_1: np.ndarray, shift_2: np.ndarray, use_building_colors: bool) -> None:
color: Color = (building.wall_color if use_building_colors else building.wall_default_color)
color: Color
if building.is_construction:
... |
def is_ipv4_address(sts_ipaddr):
if (not isinstance(sts_ipaddr, str)):
return False
if (len(sts_ipaddr) < 7):
return False
seq = sts_ipaddr.split('.')
if (len(seq) != 4):
return False
for c in seq:
try:
v = int(c)
if (v > 255):
... |
class OptionPlotoptionsFunnel3dOnpointConnectoroptions(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(... |
def inspect_node(node):
node_information = {}
ssh = node.connect()
if (not ssh):
log.error('Unable to connect to node %s', node.name)
return
(_in, _out, _err) = ssh.exec_command('(type >& /dev/null -a srun && echo slurm) || (type >& /dev/null -a qconf && echo sge) ... |
def _expand_virtual_root(repo: IConfigRepository, root: DefaultsTreeNode, overrides: Overrides, skip_missing: bool) -> DefaultsTreeNode:
children: List[Union[(DefaultsTreeNode, InputDefault)]] = []
assert (root.children is not None)
for d in reversed(root.children):
assert isinstance(d, InputDefault... |
class BaseEditor(Editor):
names = Property()
mapping = Property()
inverse_mapping = Property()
def values_changed(self):
(self._names, self._mapping, self._inverse_mapping) = enum_values_changed(self._value(), self.string_value)
def rebuild_editor(self):
raise NotImplementedError
... |
def get_systems_managed_by_user(user_id: str, auth_header: Dict[(str, str)], server_url: str) -> List[FidesKey]:
get_systems_path = SYSTEM_MANAGER_PATH.format(user_id)
response = requests.get((server_url + get_systems_path), headers=auth_header)
handle_cli_response(response, verbose=False)
return [syste... |
class OptionSeriesCylinderSonificationContexttracksMappingFrequency(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_hosts_priority():
name = 'example.com'
addr_from_ns = '1.0.2.0'
hr = _make_host_resolver()
rp = greendns.ResolverProxy(hosts_resolver=hr, filename=None)
base = _make_mock_base_resolver()
base.rr.address = addr_from_ns
rp._resolver = base()
rrns = greendns.resolve(name, _proxy=rp... |
class OptionSeriesFunnelEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._config(v... |
class PageParking(AbstractObject):
def __init__(self, api=None):
super(PageParking, self).__init__()
self._isPageParking = True
self._api = api
class Field(AbstractObject.Field):
lot = 'lot'
street = 'street'
valet = 'valet'
_field_types = {'lot': 'unsigned in... |
def sub_pub_grouping_map(graph: lg.Graph) -> Dict[(str, str)]:
sub_pub_grouping_map: Dict[(str, str)] = {}
for stream in graph.__streams__.values():
difference = set(stream.topic_paths).difference(LabgraphMonitorNode.in_edges)
if difference:
upstream_edge = max(difference, key=len)
... |
()
('--debug', is_flag=True, help='Enable debug mode.')
('--number', type=click.Choice(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-thre... |
class AnalysisPlugin(AnalysisBasePlugin):
NAME = 'qemu_exec'
DESCRIPTION = 'test binaries for executability in QEMU and display help if available'
VERSION = '0.5.2'
DEPENDENCIES = ['file_type']
FILE = __file__
FILE_TYPES = ['application/x-executable', 'application/x-pie-executable', 'application... |
def zeroInflow(x):
if ((x[0] == 0.0) and (x[1] <= 0.5)):
return (lambda x, t: 0.0)
if ((x[0] == 1.0) and (x[1] >= 0.5)):
return (lambda x, t: 0.0)
if ((x[1] == 0.0) and (x[0] >= 0.5)):
return (lambda x, t: 0.0)
if ((x[1] == 1.0) and (x[0] <= 0.5)):
return (lambda x, t: 0.... |
_icmp_type(ICMP_TIME_EXCEEDED)
class TimeExceeded(_ICMPv4Payload):
_PACK_STR = '!xBxx'
_MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, data_len=0, data=None):
if ((data_len >= 0) and (data_len <= 255)):
self.data_len = data_len
else:
raise ValueError(('Specif... |
def random_range_int(low, high, _randomstate_lambda=None):
def decorator(func):
(func)
_synthetic()
def decorator_inner(self, *args, **kw):
randomstate = __get_random_state(self, _randomstate_lambda)
value = randomstate.uniform(low=low, high=high, size=1)[0]
... |
class TestDialogues():
def setup_class(cls):
cls.agent_addr = 'agent address'
cls.env_addr = 'env address'
cls.agent_dialogues = AgentDialogues(cls.agent_addr)
cls.env_dialogues = EnvironmentDialogues(cls.env_addr)
def test_create_self_initiated(self):
result = self.agent... |
_users_without_mfa.command()
_context
def execute(ctx):
options = '[*] Available options\n[1] Load harvested users from a json file and check their enrolled MFA factors\n[2] Harvest all users and check their enrolled MFA factors\n[0] Exit this menu\n[*] Choose from the above options'
while True:
value =... |
def burn_key_digest(esp, efuses, args):
datafile = args.keyfile
args.keypurpose = ['SECURE_BOOT_DIGEST']
args.block = ['BLOCK_KEY0']
digest = espsecure._digest_sbv2_public_key(datafile)
digest = digest[:16]
num_bytes = (efuses['BLOCK_KEY0_HI_128'].bit_len // 8)
if (len(digest) != num_bytes):... |
def test_array_type_records():
schema = {'type': 'array', 'items': {'type': 'record', 'name': 'test_array_type', 'fields': [{'name': 'field1', 'type': 'string'}, {'name': 'field2', 'type': 'int'}]}}
records = [[{'field1': 'foo', 'field2': 1}], [{'field1': 'bar', 'field2': 2}]]
new_records = roundtrip(schema... |
.sandbox_test
def test_walk_local_copy_to_s3(source_folder):
dc = Config.for_sandbox().data_config
explicit_empty_folder = UUID(int=random.getrandbits(128)).hex
raw_output_path = f's3://my-s3-bucket/testdata/{explicit_empty_folder}'
provider = FileAccessProvider(local_sandbox_dir='/tmp/unittest', raw_ou... |
class ParentFieldListFilter(ChoicesFieldListFilter):
def __init__(self, f, request, params, model, model_admin, field_path=None):
super().__init__(f, request, params, model, model_admin, field_path)
parent_ids = model.objects.exclude(parent=None).values_list('parent__id', flat=True).order_by('parent... |
def test_handle_timer_canceled(decision_context, workflow_clock):
event = HistoryEvent()
decision_context.handle_timer_canceled(event)
workflow_clock.handle_timer_canceled.assert_called_once()
(args, kwargs) = workflow_clock.handle_timer_canceled.call_args_list[0]
assert (args[0] is event) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.