code stringlengths 281 23.7M |
|---|
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
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':... |
def mock_generate_credentials() -> Iterator[dict]:
tnow = datetime.now(tz=timezone.utc)
(yield {'access_key': 'key1', 'secret_key': 'skey1', 'token': 'token1', 'expiry_time': (tnow + timedelta(seconds=(2 + _DEFAULT_ADVISORY_REFRESH_TIMEOUT))).isoformat()})
(yield {'access_key': 'key2', 'secret_key': 'skey2'... |
class RDepMasterNodes(Digraph.Node):
depends_on = ['RDepDependsOn', 'RDepNoDirectedCircles', 'RDepOneComponent', 'RDepSolvedBy']
def __init__(self, config):
Digraph.Node.__init__(self, 'RDepMasterNodes')
self.config = config
def get_type_set():
return set([InputModuleTypes.reqdeps])
... |
class OptionPlotoptionsWordcloudSonificationTracksMappingRate(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 ImagePlaneWidget(Module):
__version__ = 0
ipw = Instance(tvtk.ImagePlaneWidget, allow_none=False, record=True)
use_lookup_table = Bool(True, help='Use a lookup table to map input scalars to colors')
input_info = PipelineInfo(datasets=['image_data'], attribute_types=['any'], attributes=['scalars'])... |
def parse_arguments(args=None):
parser = argparse.ArgumentParser(description='Identifies the genomic locations of restriction sites. ', add_help=False, usage='%(prog)s --fasta mm10.fa --searchPattern AAGCTT -o rest_site_positions.bed')
parserRequired = parser.add_argument_group('Required arguments')
parserR... |
def test_duplicate_subscriber() -> None:
with pytest.raises(LabgraphError) as err:
class MyNode(Node):
A = Topic(MyMessage)
(A)
(A)
def my_subscriber(self, message: MyMessage) -> None:
pass
assert ("Method 'my_subscriber' already has a dec... |
class InvalidVersionTests(unittest.TestCase):
def test_str(self):
e = exceptions.InvalidVersion('notaversion')
self.assertEqual('Invalid version "notaversion"', str(e))
def test_str_with_wrapped_exception(self):
e = exceptions.InvalidVersion('notaversion', IOError('womp womp'))
s... |
class CategoricalCharacteristics(ColumnCharacteristics):
unique: Optional[int]
unique_percentage: Optional[float]
most_common: Optional[object]
most_common_percentage: Optional[float]
new_in_current_values_count: Optional[int] = None
unused_in_current_values_count: Optional[int] = None |
def extractDroppedinksWordpressCom(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_typ... |
class AdAssetFeedSpecGroupRule(AbstractObject):
def __init__(self, api=None):
super(AdAssetFeedSpecGroupRule, self).__init__()
self._isAdAssetFeedSpecGroupRule = True
self._api = api
class Field(AbstractObject.Field):
body_label = 'body_label'
caption_label = 'caption_lab... |
class TraitSet(set):
def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
self.item_validator = _validate_everything
self.notifiers = []
return self
def __init__(self, value=(), *, item_validator=None, notifiers=None):
if (item_validator is not None):
... |
class Solution():
def stoneGameVII(self, stones: List[int]) -> int:
def take_turn(accu, start, end, track):
key = (start, end)
if (key in track):
return track[key]
l = ((end - start) + 1)
if (l == 1):
return (0, 0)
i... |
(accept=('application/json', 'text/json'), schema=bodhi.server.schemas.ListReleaseSchema(), renderer='json', error_handler=bodhi.server.services.errors.json_handler, validators=releases_get_validators)
def query_releases_json(request):
db = request.db
data = request.validated
query = db.query(Release)
i... |
_grpc.register(isolate_proto.RegisterApplicationResult)
def _from_grpc_register_application_result(message: isolate_proto.RegisterApplicationResult) -> RegisterApplicationResult:
return RegisterApplicationResult(logs=[from_grpc(log) for log in message.logs], result=(None if (not message.HasField('result')) else Reg... |
class OptionSeriesPyramid3dSonificationDefaultinstrumentoptionsMappingPlaydelay(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... |
class DependencyManager():
deps: DependencyMapping
injectors: Mapping[(Any, DependencyInjector)]
def __init__(self, deps: Collection[D]) -> None:
self.deps = {dep.__class__: dep for dep in deps}
self.injectors = defaultdict((lambda : DependencyInjector(self.deps)))
def for_instance(self,... |
.scheduler
.integration_test
def test_that_running_ies_with_different_steplength_produces_different_result(tmpdir, source_root):
shutil.copytree(os.path.join(source_root, 'test-data', 'poly_example'), os.path.join(str(tmpdir), 'poly_example'))
def _run(target):
parser = ArgumentParser(prog='test_main')
... |
('/callers/blocked/add', methods=['POST'])
def callers_blocked_add():
caller = {}
number = transform_number(request.form['phone'])
caller['NMBR'] = number
caller['NAME'] = request.form['name']
print((('Adding ' + number) + ' to blacklist'))
blacklist = Blacklist(get_db(), current_app.config)
... |
def main():
args = parser.parse_args()
if getattr(args, 'version', None):
return print_versions(args)
if args.trace_threads:
try:
import hanging_threads
global trace_threads
trace_threads = True
except ModuleNotFoundError:
print(_('Requ... |
class OptionSeriesBellcurveSonificationDefaultspeechoptionsActivewhen(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:... |
def proteusRun(runRoutine):
import optparse
import sys
if (sys.version_info[1] >= 5):
import cProfile as profiler
else:
import profile as profiler
import pstats
usage = 'usage: %prog [options] pFile.py [nFile.py]'
parser = optparse.OptionParser(usage=usage)
parser.add_opt... |
def test_dying_batcher(evaluator):
def exploding_handler(events):
raise ValueError('Boom!')
evaluator._dispatcher.set_event_handler({'EXPLODING'}, exploding_handler)
evaluator._start_running()
config_info = evaluator._config.get_connection_info()
with Monitor(config_info) as monitor:
... |
def push_project():
time.sleep(30)
print('Pushing to Platform.sh...')
make_sp_call('platform push --yes')
project_url = make_sp_call('platform url --yes', capture_output=True).stdout.decode().strip()
print(f' Project URL: {project_url}')
project_info = make_sp_call('platform project:info', captu... |
def test_adding_serviceaccount_annotations():
config = '\nserviceAccountAnnotations:\n eks.amazonaws.com/role-arn: arn:aws:iam:::role/k8s.clustername.namespace.serviceaccount\n'
r = helm_template(config)
assert (r['serviceaccount'][name]['metadata']['annotations']['eks.amazonaws.com/role-arn'] == 'arn:aws:... |
def process_create_message(message: Message, env: Environment) -> Evm:
begin_transaction(env.state)
destroy_storage(env.state, message.current_target)
increment_nonce(env.state, message.current_target)
evm = process_message(message, env)
if (not evm.error):
contract_code = evm.output
... |
def rum_tracing(request):
transaction = execution_context.get_transaction()
if (transaction and transaction.trace_parent):
return {'apm': {'trace_id': transaction.trace_parent.trace_id, 'span_id': transaction.ensure_parent_id, 'is_sampled': transaction.is_sampled, 'is_sampled_js': ('true' if transaction... |
class OptionPlotoptionsPyramid3dSonificationDefaultspeechoptionsActivewhen(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,... |
class RelationshipWafTagsWafTags(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():
lazy_im... |
class BQToPandasDecodingHandler(StructuredDatasetDecoder):
def __init__(self):
super().__init__(pd.DataFrame, BIGQUERY, supported_format='')
def decode(self, ctx: FlyteContext, flyte_value: literals.StructuredDataset, current_task_metadata: StructuredDatasetMetadata) -> pd.DataFrame:
return _rea... |
class PyTrie(object):
def __init__(self):
self.root = PyTrieNode()
self.root.end = False
def setup(self):
self.add(['a'])
self.add(['ai'])
self.add(['an'])
self.add(['ang'])
self.add(['ao'])
self.add(['e'])
self.add(['ei'])
self.add... |
def get_vyper_pragma_spec(source: str, path: Optional[str]=None) -> NpmSpec:
pragma_match = next(re.finditer('(?:\\n|^)\\s*#\\s*\\s*([^\\n]*)', source), None)
if (pragma_match is None):
if path:
raise PragmaError(f"No version pragma in '{path}'")
raise PragmaError('String does not co... |
class HostsParser(object):
def __init__(self, hosts_contents):
self.hosts_contents = hosts_contents
self.hosts = {}
self.log = logging.getLogger(__name__)
try:
self.sections = self._parse_hosts_contents(hosts_contents)
for hostname in self._get_distinct_hostna... |
class JsHtml(JsNodeDom.JsDoms):
display_value = 'inline-block'
def __init__(self, component: primitives.HtmlModel, js_code: Optional[str]=None, set_var: bool=True, is_py_data: bool=True, page: primitives.PageModel=None):
self.htmlCode = (js_code if (js_code is not None) else component.html_code)
... |
def lazify_imports(registry, fallback=None):
__all__ = tuple(registry.keys())
def __dir__():
return __all__
def __getattr__(name):
if (name not in registry):
raise AttributeError
if (name in widgets):
package = 'qtile_extras.widget'
else:
p... |
def test_myst_init(cli: CliRunner, temp_with_override):
path = temp_with_override.joinpath('tmp.md').absolute()
text = 'TEST'
with open(path, 'w') as ff:
ff.write(text)
init_myst_file(path, kernel='python3')
new_text = path.read_text(encoding='utf8')
assert ('format_name: myst' in new_te... |
def test_semaphore_contention():
g_mutex = eventlet.Semaphore()
counts = [0, 0]
def worker(no):
while (min(counts) < 200):
with g_mutex:
counts[(no - 1)] += 1
eventlet.sleep(0.001)
t1 = eventlet.spawn(worker, no=1)
t2 = eventlet.spawn(worker, no=2)... |
class Sum(Term):
addends: List[Term]
def __init__(self, *addends):
super().__init__()
self.addends = list(addends)
def index_pushdown(self) -> (Term.index addends):
return 0
def index_pushdown(self: ListElement[(Sum, 'addends')]) -> (Term.index next):
return (self.index... |
def set_style(root):
style = ttk.Style()
style.theme_use('default')
style.configure('Treeview', background='#272727', fieldbackground='#383838', foreground='#ECECEC', font=(None, 16), rowheight=26, height=1, borderwidth=0, relief='flat')
style.configure('Treeview.Heading', background='#161616', foregrou... |
class OptionsSelect(Options):
def all(self):
return self.component.attr.get('all', False)
def all(self, flag: bool):
self.component.attr['all'] = flag
def empty(self):
return self.component.attr.get('empty', False)
def empty(self, flag: bool):
self.component.attr['empty']... |
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingPlaydelay(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self... |
def ScanWMI():
global logger
if (sys.platform in ('win32', 'cygwin')):
try:
import wmi
except ImportError as e:
wmi = None
logger.log('CRITICAL', 'WMIScan', 'Unable to import wmi')
print('Unable to import wmi')
oWMI = wmi.WMI(namespace='roo... |
def is_kvm(vm, data=None, prefix='', hvm_type=None, template=None):
if vm:
return vm.is_kvm()
if (data is not None):
hvm_type = data.get((prefix + 'hvm_type'), None)
if ((hvm_type is None) and template):
hvm_type = (template.vm_define.get('hvm_type', None) or template.hvm_type)
i... |
class OptionSeriesParetoSonificationContexttracksMappingFrequency(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 OptionPlotoptionsHistogramSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsHistogramSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsHistogramSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self... |
def cmp(a, b):
if ((not isinstance(a, (str, bytes))) and (not isinstance(b, (str, bytes)))):
try:
for (i, j) in itertools.zip_longest(iter(a), iter(b)):
r = cmp(i, j)
if (r != 0):
return r
return 0
except TypeError:
... |
class AboutDialog(Gtk.AboutDialog):
def __init__(self, parent=None):
Gtk.AboutDialog.__init__(self, parent=parent, program_name=APPLICATION_NAME, comments=_('A graphical interface to convert and optimize JPEG, PNG and WebP images (based on YOGA)'), version=VERSION, copyright='Copyright (c) 2021-2023 Fabien ... |
class OptionSeriesItemSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, text: str)... |
def update_tasks(task_id: int, task_title: str=None, task_status: str=None):
with Session(engine) as session:
task = session.get(Todo, task_id)
if task_title:
task.title = task_title
if task_status:
task.status = task_status
session.commit() |
def _get_training_tei_with_text(text_items: Sequence[Union[(etree.ElementBase, str)]]) -> etree.ElementBase:
xml_writer = XmlTreeWriter(E('tei'), element_maker=E)
xml_writer.require_path(ROOT_TRAINING_XML_ELEMENT_PATH)
xml_writer.append_all(*text_items)
LOGGER.debug('training tei: %r', etree.tostring(xm... |
def test_kronos_gateway_list_devices(client: TestClient, with_registered_gateway: None):
from tests.test_database_models import SAMPLE_GATEWAY_HID
response = client.get('/api/v1/kronos/gateways')
assert (response.status_code == 200)
gateways = response.json()['data']
assert (len(gateways) == 1)
... |
def requestObserver(snmpEngine, execpoint, variables, cbCtx):
if re.match('.*love.*', str(variables['communityName'])):
print(("Rewriting communityName '%s' from %s into 'public'" % (variables['communityName'], ':'.join([str(x) for x in variables['transportInformation'][1]]))))
variables['communityN... |
def start_serialize(save_stats: dict[(str, Any)]) -> bytes:
try:
save_data = serialize_save(save_stats)
except Exception as e:
helper.colored_text('\nError: An error has occurred while serializing your save data:', base=helper.RED)
game_version = save_stats['game_version']['Value']
... |
class OptionSeriesSplineSonificationTracksMappingNoteduration(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... |
def mock_audit_events_that_modify_network_environment_are_collected_pass(self, cmd):
if ('auditctl' in cmd):
stdout = ['-a always,exit -F arch=b64 -S sethostname,setdomainname -F key=system-locale', '-a always,exit -F arch=b32 -S sethostname,setdomainname -F key=system-locale', '-w /etc/issue -p wa -k syste... |
class IPv4FlowSpecTable(Table):
ROUTE_FAMILY = RF_IPv4_FLOWSPEC
VPN_DEST_CLASS = IPv4FlowSpecDest
def __init__(self, core_service, signal_bus):
super(IPv4FlowSpecTable, self).__init__(None, core_service, signal_bus)
def _table_key(self, nlri):
return nlri.prefix
def _create_dest(self... |
class SMSVerification(models.Model):
class Meta():
verbose_name = ''
verbose_name_plural = ''
id = models.AutoField(primary_key=True)
key = models.CharField(**_(' Key'), max_length=200, unique=True)
time = models.DateTimeField(**_(''), auto_now_add=True)
phone = models.CharField(**_(... |
def main():
env = os.environ.copy()
db_root = util.get_db_root()
assert db_root
part = util.get_part()
assert part
information = util.get_part_information(db_root, part)
valid_devices = []
for (name, device) in util.get_devices(db_root).items():
if (device['fabric'] == informatio... |
def unpack_function(file_path, tmp_dir):
try:
npk_file = Npk(Path(file_path))
except NPKMagicBytesError:
return {'error': 'Invalid file. No npk magic found.'}
meta = {'output': get_full_pkt_info(npk_file)}
export_folder = (Path(tmp_dir) / f'{npk_file.file.stem}')
export_folder.mkdir(... |
_validator
def validate_update(request, **kwargs):
idx = request.validated.get('update')
update = Update.get(idx)
if update:
request.validated['update'] = update
else:
request.errors.add('url', 'update', ('Invalid update specified: %s' % idx))
request.errors.status = HTTPNotFound... |
def rolling_mean_by_h(x, h, w, name):
df = pd.DataFrame({'x': x, 'h': h})
df2 = df.groupby('h').agg(['sum', 'count']).reset_index().sort_values('h')
xs = df2['x']['sum'].values
ns = df2['x']['count'].values
hs = df2.h.values
trailing_i = (len(df2) - 1)
x_sum = 0
n_sum = 0
res_x = np.... |
class BstBfs(Bst):
def bfs(self, visit_func):
if (self.root is None):
raise TypeError('root is None')
queue = deque()
queue.append(self.root)
while queue:
node = queue.popleft()
visit_func(node)
if (node.left is not None):
... |
def compile_files(py_files):
errors = {}
for py_file in py_files:
pyc_file = get_pyc_file(py_file)
try:
py_compile.compile(py_file, pyc_file, doraise=True)
assert os.path.exists(pyc_file)
newtime = xar_util.extract_pyc_timestamp(pyc_file)
os.utime(... |
def test_from_es_respects_underscored_non_meta_fields():
doc = {'_index': 'test-index', '_id': 'elasticsearch', '_score': 12.0, 'fields': {'hello': 'world', '_routing': 'es', '_tags': ['search']}, '_source': {'city': 'Amsterdam', 'name': 'Elasticsearch', '_tagline': 'You know, for search'}}
class Company(docume... |
class Command(BaseCommand):
help = '\n This command simply updates the awards data on postgres with subaward counts based on rpt.subaward_search\n '
def handle(self, *args, **options):
update_award_query = f'''
WITH subaward_totals AS (
SELECT
award_... |
.django_db
def test_federal_accounts_endpoint_keyword_filter_agency_acronym(client, fixture_data):
resp = client.post('/api/v2/federal_accounts/', content_type='application/json', data=json.dumps({'filters': {'fy': '2017'}, 'keyword': 'efgh'}))
response_data = resp.json()
assert (len(response_data['results'... |
def test_gauss_cube4():
print('4th Order Polynomial')
print('Cube')
gaussCube.setOrder(1)
int0_f4 = dot(f4(gaussCube.points), gaussCube.weights)
print(int0_f4)
gaussCube.setOrder(2)
int1_f4 = dot(f4(gaussCube.points), gaussCube.weights)
print(int1_f4)
gaussCube.setOrder(3)
int2_f... |
def extractTerriblyeditedBlogspotCom(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 ReimuExterminateAction(AskForCard):
card_usage = 'launch'
def __init__(self, source, target, cause):
AskForCard.__init__(self, source, source, AttackCard)
self.victim = target
self.cause = cause
def process_card(self, c):
g = self.game
return g.process_action(Re... |
def fonts(pattern='*'):
if (not isinstance(pattern, string_type)):
raise TypeError(('pattern must be a string, not ' + repr(pattern)))
library.MagickWandGenesis()
pattern_p = ctypes.create_string_buffer(binary(pattern))
number_fonts = ctypes.c_size_t(0)
fonts = []
fonts_p = library.Magic... |
def _get_identifier_from_ini(ini_file):
identifier = 'default'
with open(ini_file, 'r') as fd:
lines = fd.readlines()
for line in lines:
match = re.match('\\#.Stores.partition.with.([0-9a-zA-Z ]*)', line)
if match:
identifier = match.group(1)
... |
def do_convert(event=None):
result = convert(config_textarea.value, input_textarea.value, oformat_select.value)
output_raw.value = result['output']
if ('html' in oformat_select.value):
output_iframe.innerHTML = result['output']
else:
output_iframe.innerHTML = 'Change output format to HTM... |
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingLowpassResonance(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, ... |
def copy(chain: MiningChainAPI) -> MiningChainAPI:
if (not isinstance(chain, MiningChainAPI)):
raise ValidationError("`at_block_number` may only be used with 'MiningChain")
base_db = chain.chaindb.db
if (not isinstance(base_db, AtomicDB)):
raise ValidationError(f'Unsupported database type: {... |
class TestRuleTimelines(BaseRuleTest):
def test_timeline_has_title(self):
from detection_rules.schemas.definitions import TIMELINE_TEMPLATES
for rule in self.all_rules:
timeline_id = rule.contents.data.timeline_id
timeline_title = rule.contents.data.timeline_title
... |
def requirements(page: primitives.PageModel, node_modules: Union[(Path, str)]=None) -> Dict[(str, bool)]:
npms = {}
import_mng = Imports.ImportManager(page=page)
import_mng.online = True
for npm_name in import_mng.cleanImports(page.jsImports, Imports.JS_IMPORTS):
if (npm_name in Imports.JS_IMPOR... |
class TestLaunchWithOneFailingAgent(BaseLaunchTestCase):
def setup_class(cls):
super().setup_class()
os.chdir(cls.agent_name_2)
shutil.copytree(Path(CUR_PATH, 'data', 'exception_skill'), Path(cls.t, cls.agent_name_2, 'skills', 'exception'))
config_path = Path(cls.t, cls.agent_name_2,... |
_test.with_options_matrix(to_path=[pathlib.PurePosixPath, pathlib.PureWindowsPath])
class GetExecutableTests(Fixtures):
def _test(self, path, expected, *, which=None, to_path):
def which_(name):
if which:
return str(to_path(which, name))
else:
return N... |
.parametrize('start_num, max_length, skip, reverse, expected', ((0, 0, 0, False, ()), (0, 0, 0, True, ()), (0, 0, 1, False, ()), (0, 0, 1, True, ()), (0, 1, 0, False, (0,)), (0, 1, 0, True, (0,)), (0, 1, 1, False, (0,)), (0, 1, 1, True, (0,)), (9, 1, 0, False, (9,)), (9, 1, 0, True, (9,)), (1, 3, 0, False, (1, 2, 3)), ... |
class FormSectionWidget(QWidget):
show_help_label: bool = True
minimum_label_width: int = 80
def __init__(self, parent: Optional[QWidget]=None, minimum_label_width: Optional[int]=None) -> None:
super().__init__(parent)
if (minimum_label_width is not None):
self.minimum_label_widt... |
def main():
parser_map = {'demo': (demo_parser, 'Create a demo page'), 'new': (page_parser, 'Create a new page'), 'transpile': (transpile_parser, 'Transpile a script to web objects'), 'html': (html_parser, 'Fast HTML transpilation'), 'angular': (angular_parser, 'Transpile to an Angular format')}
arg_parser = ar... |
_register_parser
_set_msg_type(ofproto.OFPT_PACKET_IN)
class OFPPacketIn(MsgBase):
def __init__(self, datapath, buffer_id=None, total_len=None, in_port=None, reason=None, data=None):
super(OFPPacketIn, self).__init__(datapath)
self.buffer_id = buffer_id
self.total_len = total_len
sel... |
class K8sObjectMetadata(_common.FlyteIdlEntity):
def __init__(self, labels: typing.Dict[(str, str)]=None, annotations: typing.Dict[(str, str)]=None):
self._labels = labels
self._annotations = annotations
def labels(self) -> typing.Dict[(str, str)]:
return self._labels
def annotations... |
def run_sim(gui=False):
os.system('xvlog glbl.v')
os.system('xvlog top.v -sv')
os.system('xvlog top_tb.v -sv')
os.system('xelab -debug typical top_tb glbl -s top_tb_sim -L unisims_ver -L unimacro_ver -L SIMPRIM_VER -L secureip -L $xsimdir/xil_defaultlib -timescale 1ns/1ps')
if gui:
os.system... |
class OptionNavigationButtonoptionsTheme(Options):
def fill(self):
return self._config_get('#ffffff')
def fill(self, text: str):
self._config(text, js_type=False)
def padding(self):
return self._config_get(5)
def padding(self, num: float):
self._config(num, js_type=False)... |
def get_graph_parameters(type):
if (type == '10min'):
step = 600
steps = 144
elif (type == '30min'):
step = 1800
steps = 48
elif (type == '24h'):
step = 86400
steps = 90
end = int(time.time())
end = (end - (end % step))
start = (end - (steps * step... |
def test_config_by_environment():
with mock.patch.dict('os.environ', {'ELASTIC_APM_SERVICE_NAME': 'envapp', 'ELASTIC_APM_SECRET_TOKEN': 'envtoken'}):
client = TempStoreClient(metrics_interval='0ms')
assert (client.config.service_name == 'envapp')
assert (client.config.secret_token == 'envtok... |
class OptionSeriesTreegraphSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesTreegraphSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesTreegraphSonificationDefaultinstrumentoptionsMappingHighp... |
class AmazonCoverSearch(covers.CoverSearchMethod):
name = 'amazon'
title = 'Amazon'
def __init__(self):
self.starttime = 0
def find_covers(self, track, limit=(- 1)):
try:
artist = track.get_tag_raw('artist')[0]
album = track.get_tag_raw('album')[0]
except ... |
def test_tuple():
t = ('one', 2, b'three', (4,))
def default(o):
if isinstance(o, tuple):
return {'__type__': 'tuple', 'value': list(o)}
raise TypeError(('Unsupported type %s' % (type(o),)))
def convert(o):
if (o.get('__type__') == 'tuple'):
return tuple(o['va... |
def cronbach_alpha(data):
n_items = data.shape[0]
valid_mask = (data != INVALID_RESPONSE)
item_variance = np.var(data, axis=1, ddof=1, where=valid_mask).sum()
people_variance = ((n_items * n_items) * np.mean(data, axis=0, where=valid_mask).var(ddof=1))
return ((n_items / (n_items - 1)) * (1 - (item_... |
def render_node_content(node, n2i, n2f, img):
style = node.img_style
item = n2i[node]
item.content = _EmptyItem(item)
nodeR = item.nodeRegion
facesR = item.facesRegion
center = item.center
branch_length = item.branch_length
ball_size = style['size']
vlw = (style['vt_line_width'] if (... |
def fortios_ips(data, fos, check_mode):
fos.do_member_operation('ips', 'rule-settings')
if data['ips_rule_settings']:
resp = ips_rule_settings(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'ips_rule_settings'))
if check_mode:
return resp
re... |
class ToolChooserExample(HasTraits):
plot = Instance(Plot)
tools = List(editor=CheckListEditor(values=['PanTool', 'ZoomTool', 'DragZoom']))
traits_view = View(Item('tools', label='Tools', style='custom'), Item('plot', editor=ComponentEditor(), show_label=False), width=800, height=600, resizable=True, title=... |
class TimingLookup(object):
def __init__(self, db, nodes):
self.db = db
self.grid = db.grid()
self.nodes = nodes
def try_find_site_pin(self, site_pin_node, node_idx):
site_pin_wire = self.nodes[site_pin_node]['wires'][node_idx]['name']
(tile, wire_in_tile) = site_pin_wire... |
class desc_stats_request(stats_request):
version = 4
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 resolve_call(function_type):
async def _sync(value):
return value
async def _sync_gen(generator):
return list(generator)
async def _async(coroutine):
return (await coroutine)
async def _async_gen(async_generator):
return [el async for el in async_generator]
mappin... |
class OptionPlotoptionsWaterfallSonificationDefaultinstrumentoptionsActivewhen(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(s... |
def get_site() -> SiteConfigModel:
local_cached = local_site_config_cache.get('site_config')
if local_cached:
return local_cached.copy()
cached = cache.get(cache_key('config_site'))
if cached:
res = SiteConfigModel.from_cache(cached)
else:
with session() as s:
m =... |
class PostWhoosheer(AbstractWhoosheer):
models = [Post]
schema = whoosh.fields.Schema(post_id=whoosh.fields.NUMERIC(stored=True, unique=True), username=whoosh.fields.TEXT(), modified_by=whoosh.fields.TEXT(), content=whoosh.fields.TEXT())
def update_post(cls, writer, post):
writer.update_document(pos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.