code stringlengths 281 23.7M |
|---|
def _log_post(post_details: PostDetails, result: PostResultModel, insert_time, cache_time):
total = ((insert_time + cache_time) + post_details.file_time)
file_time_str = ('file: {}ms, '.format(post_details.file_time) if post_details.file_time else '')
s = '{}db: {}ms, caches: {}ms, total: {}ms'
timings ... |
class SegmentationLineFeaturesProvider():
def __init__(self, document_features_context: DocumentFeaturesContext, use_first_token_of_block: bool):
self.document_features_context = document_features_context
self.use_first_token_of_block = use_first_token_of_block
def iter_line_features(self, layou... |
def build_sample_db():
db.drop_all()
db.create_all()
first_names = ['Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie', 'Mia', 'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica', 'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy']
... |
class ChangeStatus(object):
def __init__(self, all_changed: bool=False) -> None:
if all_changed:
self.source_files = 1
self.make_files = 1
else:
self.source_files = 0
self.make_files = 0
def record_change(self, file_name) -> None:
file_name... |
def _get_notes(**kwargs) -> str:
if (kwargs['notes_file'] is not None):
if (kwargs['notes'] is None):
with open(kwargs['notes_file'], 'r') as fin:
return fin.read()
else:
click.echo('ERROR: Cannot specify --notes and --notes-file', err=True)
sys.ex... |
class MsgStub(object):
def __init__(self, channel):
self.CreateVestingAccount = channel.unary_unary('/cosmos.vesting.v1beta1.Msg/CreateVestingAccount', request_serializer=cosmos_dot_vesting_dot_v1beta1_dot_tx__pb2.MsgCreateVestingAccount.SerializeToString, response_deserializer=cosmos_dot_vesting_dot_v1beta... |
def _dump_groups(groups, op_type, workdir):
fname = f'fuse_group_{op_type}_groups.txt'
file_path = os.path.join(workdir, fname)
with open(file_path, 'w') as f:
for group in groups:
single_group_str = ','.join((op._attrs['name'] for op in group))
f.write(f'''[{single_group_str... |
class OptionSeriesDumbbellLowmarkerStates(Options):
def hover(self) -> 'OptionSeriesDumbbellLowmarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesDumbbellLowmarkerStatesHover)
def normal(self) -> 'OptionSeriesDumbbellLowmarkerStatesNormal':
return self._config_sub_data('normal... |
class OptionPlotoptionsFunnelSonificationTracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsFunnelSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsFunnelSonificationTracksActivewhen)
def instrument(self):
return self._config_get('piano')
def ... |
def _flush_queue():
global scheduled, queue
scheduled = False
if (not queue):
return
_queue = queue[:MAX_BATCH]
queue = queue[MAX_BATCH:]
entries = []
for q in _queue:
params = {'v': 1, 'tid': TRACK_ID, 'cid': get_settings('uid', '000')}
params.update(q)
entri... |
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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(se... |
class JsonFloatTests(TestCase):
def test_dumps(self):
with self.assertRaises(ValueError):
json.dumps(float('inf'))
with self.assertRaises(ValueError):
json.dumps(float('nan'))
def test_loads(self):
with self.assertRaises(ValueError):
json.loads('Infini... |
def uploaded_file(files, multiple=False):
if multiple:
files_uploaded = []
for file in files:
extension = file.filename.split('.')[1]
filename = ((get_file_name() + '.') + extension)
filedir = (current_app.config.get('BASE_DIR') + '/static/uploads/')
i... |
def delete_post_file(post: PostModel):
if (post.file is None):
raise ArgumentError(MESSAGE_POST_HAS_NO_FILE)
with session() as s:
file_orm_model = s.query(FileOrmModel).filter_by(id=post.file.id).one()
s.delete(file_orm_model)
s.commit()
thread = post.thread
_inva... |
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 extractRpgNovels(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Maou-sama no machizukuri!', 'Maou-sama no Machizukuri!', 'translated')]
for (tagname, name, tl_type) in... |
class JoinedSet(Set):
def _from_set(cls, obj, jdata=[], ljdata=[], auto_select_tables=[]):
rv = cls(obj.db, obj.query, obj.query.ignore_common_filters, obj._model_)
rv._stable_ = obj._model_.tablename
rv._jdata_ = list(jdata)
rv._ljdata_ = list(ljdata)
rv._auto_select_tables_... |
class MongoQueryConfig(QueryConfig[MongoStatement]):
def generate_query(self, input_data: Dict[(str, List[Any])], policy: Optional[Policy]=None) -> Optional[MongoStatement]:
def transform_query_pairs(pairs: Dict[(str, Any)]) -> Dict[(str, Any)]:
if (len(pairs) < 2):
return pairs
... |
class GenericOefSearchHandler(Handler):
SUPPORTED_PROTOCOL = OefSearchMessage.protocol_id
def setup(self) -> None:
def handle(self, message: Message) -> None:
oef_search_msg = cast(OefSearchMessage, message)
oef_search_dialogues = cast(OefSearchDialogues, self.context.oef_search_dialogues)
... |
class SentenceCount(GeneratedFeature):
column_name: str
def __init__(self, column_name: str, display_name: Optional[str]=None):
self.column_name = column_name
self.display_name = display_name
super().__init__()
def generate_feature(self, data: pd.DataFrame, data_definition: DataDefin... |
class flow_removed(message):
version = 3
type = 11
def __init__(self, xid=None, cookie=None, priority=None, reason=None, table_id=None, duration_sec=None, duration_nsec=None, idle_timeout=None, hard_timeout=None, packet_count=None, byte_count=None, match=None):
if (xid != None):
self.xid... |
.usefixtures('use_tmpdir')
def test_that_hook_workflow_without_existing_job_error_is_located():
assert_that_config_leads_to_error(config_file_contents=dedent('\nNUM_REALIZATIONS 1\nHOOK_WORKFLOW NO_SUCH_JOB POST_SIMULATION\n '), expected_error=ExpectedErrorInfo(line=3, column=15, end_column=26)) |
def get_example_tree():
nst1 = NodeStyle()
nst1['bgcolor'] = 'LightSteelBlue'
nst2 = NodeStyle()
nst2['bgcolor'] = 'Moccasin'
nst3 = NodeStyle()
nst3['bgcolor'] = 'DarkSeaGreen'
nst4 = NodeStyle()
nst4['bgcolor'] = 'Khaki'
t = Tree('((((a1,a2),a3), ((b1,b2),(b3,b4))), ((c1,c2),c3));'... |
class TestPopupSave(unittest.TestCase):
def _make_mock_file_dialog(self, return_value):
m = Mock(spec=FileDialog)
m.open.return_value = return_value
m.path = 'mock'
return m
((ETSConfig.toolkit == 'null'), 'Test meaningless with null toolkit.')
def test_popup_save_with_user_o... |
def test_add_after_reset(app_instance, mocker):
mocker.patch('embedchain.vectordb.chroma.chromadb.Client')
config = AppConfig(log_level='DEBUG', collect_metrics=False)
chroma_config = ChromaDbConfig(allow_reset=True)
db = ChromaDB(config=chroma_config)
app_instance = App(config=config, db=db)
mo... |
def ffmpeg_install_windows():
try:
ffmpeg_url = '
ffmpeg_zip_filename = 'ffmpeg.zip'
ffmpeg_extracted_folder = 'ffmpeg'
if os.path.exists(ffmpeg_zip_filename):
os.remove(ffmpeg_zip_filename)
r = requests.get(ffmpeg_url)
with open(ffmpeg_zip_filename, 'wb')... |
def CreateDataset(opt):
dataset = None
if ((opt.name == 'fashion') or (opt.name == 'humanparsing')):
from data.pickle_dataset import PickleDataset
dataset = PickleDataset()
print(('dataset [%s] was created' % dataset.name()))
dataset.initialize(opt)
return dataset |
class LogsGateway(AWSGateway):
def __init__(self, region: str, access_key_id: Optional[str]=None, access_key_data: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None) -> None:
super().__init__(region, access_key_id, access_key_data, config)
self.client: botocore.client.BaseClient = boto3.cl... |
def checkOrigins(tdb, cmdenv, calc):
if cmdenv.origPlace:
if (cmdenv.startJumps and (cmdenv.startJumps > 0)):
cmdenv.origins = expandForJumps(tdb, cmdenv, calc, cmdenv.origPlace.system, cmdenv.startJumps, '--from', 'starting')
cmdenv.origPlace = None
elif isinstance(cmdenv.or... |
def run(args):
from .. import Tree, PhyloTree
features = set()
for ftree in src_tree_iterator(args):
if args.ncbi:
tree = PhyloTree(open(ftree))
features.update(['taxid', 'name', 'rank', 'bgcolor', 'sci_name', 'collapse_subspecies', 'named_lineage', 'lineage'])
tr... |
def start_parse(save_data: bytes, country_code: str) -> dict[(str, Any)]:
try:
save_stats = parse_save(save_data, country_code)
except Exception:
helper.colored_text(f'''
Error: An error has occurred while parsing your save data (address = {address}):''', base=helper.RED)
traceback.print... |
def test_function_score_with_single_function():
d = {'function_score': {'filter': {'term': {'tags': 'python'}}, 'script_score': {'script': "doc['comment_count'] * _score"}}}
q = query.Q(d)
assert isinstance(q, query.FunctionScore)
assert isinstance(q.filter, query.Term)
assert (len(q.functions) == 1... |
def send_from_location_address(subject, text_content, html_content, recipient, location):
mailgun_data = {'from': location.from_email(), 'to': [recipient], 'subject': subject, 'text': text_content}
if html_content:
mailgun_data['html'] = html_content
return mailgun_send(mailgun_data) |
def handle_created_object_record(record: dict, cfg: Config) -> None:
logger.debug({'s3_notification_event': record})
cloudtrail_log_record = get_cloudtrail_log_records(record)
if cloudtrail_log_record:
for cloudtrail_log_event in cloudtrail_log_record['events']:
handle_event(event=cloudt... |
def extractSherleyhimechamaWordpressCom(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... |
def test(config, json_config_file_1):
config.from_json(json_config_file_1)
assert (config() == {'section1': {'value1': 1}, 'section2': {'value2': 2}})
assert (config.section1() == {'value1': 1})
assert (config.section1.value1() == 1)
assert (config.section2() == {'value2': 2})
assert (config.sec... |
def hsva_to_rgba(h_, s, v, a):
(r, g, b, a) = (v, v, v, a)
h = (h_ * 360.0)
if (s < 0.0001):
return (r, g, b, a)
hue_slice_index = int((h / 60.0))
hue_partial = ((h / 60.0) - hue_slice_index)
p = (v * (1 - s))
q = (v * (1 - (hue_partial * s)))
t = (v * (1 - ((1 - hue_partial) * s... |
class OptionPlotoptionsScatterSonificationTracksMappingTime(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):
self... |
class FundNameGenerator():
_metrics.timeit
def __init__(self, random_state):
self.random_state = random_state
_metrics.timeit
def make(self, legal_entity):
provider = self.get_fund_provider(legal_entity)
region = self.get_geographic_region()
asset = self.get_asset()
... |
def plot_data(data: Data, datetime_data: Optional[Data], target_data: Optional[Data], agg_data: bool, merge_small_categories: Optional[int]=MAX_CATEGORIES) -> Tuple[(Optional[Histogram], Optional[DataInTime], Optional[DataByTarget])]:
(column_name, column_type, current_data, reference_data) = data
if (column_ty... |
.parametrize('_func', [['div'], ['truediv'], ['floordiv'], ['mod']])
def test_error_when_division_by_zero_and_fill_value_is_none(_func, df_vartypes):
df_zero = df_vartypes.copy()
df_zero.loc[(1, 'Marks')] = 0
transformer = RelativeFeatures(variables=['Age'], reference=['Marks'], func=_func)
transformer.... |
def inv_fft_at_point(vals, modulus, root_of_unity, x):
if (len(vals) == 1):
return vals[0]
half = ((modulus + 1) // 2)
inv_root = pow(root_of_unity, (len(vals) - 1), modulus)
f_of_minus_x_vals = (vals[(len(vals) // 2):] + vals[:(len(vals) // 2)])
evens = [(((f + g) * half) % modulus) for (f,... |
class OptionSeriesHistogramZones(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 GetVersionsByRegexTests(unittest.TestCase):
('anitya.lib.backends.BaseBackend.call_url')
def test_get_versions_by_regex_not_modified(self, mock_call_url):
mock_response = mock.Mock(spec=object)
mock_response.status_code = 304
mock_call_url.return_value = mock_response
mock_... |
def output_model_to_output_infer(output_model: dm.OutputModel) -> dm.OutputInfer:
output_json_encoded = json.dumps(output_model.output)
def __define_name(value: Any) -> Dict[(str, Any)]:
if isinstance(value, str):
return {'string_param': value}
if isinstance(value, bool):
... |
.skipcomplex
def test_interpolate_vector_valued():
from firedrake.adjoint import ReducedFunctional, Control, taylor_test
mesh = UnitSquareMesh(10, 10)
V1 = VectorFunctionSpace(mesh, 'CG', 1)
V2 = VectorFunctionSpace(mesh, 'DG', 0)
V3 = VectorFunctionSpace(mesh, 'CG', 2)
x = SpatialCoordinate(mes... |
class ConstantVelocityGaussian3D():
def __init__(self, sigma=(1.0 / 8.0), b=[1.0, 0.0, 0.0], xc=0.25, yc=0.5, zc=0.5):
self.sigma = sigma
self.xc = xc
self.yc = yc
self.zc = zc
self.b = b
def uOfXT(self, x, t):
centerX = ((self.xc + (self.b[0] * t)) % 1.0)
... |
def digest_private_key(args):
_check_output_is_not_input(args.keyfile, args.digest_file)
sk = _load_ecdsa_signing_key(args.keyfile)
repr(sk.to_string())
digest = hashlib.sha256()
digest.update(sk.to_string())
result = digest.digest()
if (args.keylen == 192):
result = result[0:24]
... |
def test_triangle_mixed(mesh_triangle):
V1 = FunctionSpace(mesh_triangle, 'DG', 1)
V2 = FunctionSpace(mesh_triangle, 'RT', 2)
V = (V1 * V2)
f = Function(V)
(f1, f2) = f.subfunctions
x = SpatialCoordinate(mesh_triangle)
f1.interpolate((x[0] + (1.2 * x[1])))
f2.project(as_vector((x[1], (0.... |
class QAgent(RL_Agent):
def __init__(self, model=None, n_actions=None):
super().__init__()
self.model = model
self.n_actions = n_actions
def update(self, sd):
self.model.load_state_dict(sd)
def initial_state(self, agent_info, B):
return DictTensor({})
def __call__... |
class PerfectCoronagraph(OpticalElement):
def __init__(self, aperture, order=2, coeffs=None):
self.pupil_grid = aperture.grid
modes = []
if (coeffs is not None):
order = int((2 * np.ceil((0.5 * (np.sqrt(((8 * len(coeffs)) + 1)) - 1)))))
self.coeffs = coeffs
el... |
def __callback_on_warc_completed(warc_path, counter_article_passed, counter_article_discarded, counter_article_error, counter_article_total):
global __counter_article_passed
global __counter_article_discarded
global __counter_article_error
global __counter_article_total
global __counter_warc_process... |
def extractThepotatoroomCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('non-human sub-district office', 'non-human sub-district office', 'translated'), ('as the demon king,... |
def display(image, server_name=':0'):
if (not isinstance(image, Image)):
raise TypeError(('image must be a wand.image.Image instance, not ' + repr(image)))
system = platform.system()
if (system == 'Windows'):
try:
image.save(filename='win:.')
except DelegateError:
... |
def make_render_children(separator: str) -> Render:
def render_children(node: RenderTreeNode, context: RenderContext) -> str:
render_outputs = (child.render(context) for child in node.children)
return separator.join((out for out in render_outputs if out))
return render_children |
class ExecutionTrace():
def __init__(self, json):
self.nodes = {}
self.clean_nodes = {}
self.tensors = {}
self.proc_group = {}
self.iteration_ids = []
self.schema: str = json['schema']
pid = json['pid']
self.proc_group = {pid: {}}
nodes_list = ... |
class OptionPlotoptionsBulletSonificationDefaultspeechoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsBulletSonificationDefaultspeechoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsBulletSonificationDefaultspeechoptionsActivewhen)
def language(self):
r... |
class nd_option_la(nd_option):
_PACK_STR = '!BB6s'
_MIN_LEN = struct.calcsize(_PACK_STR)
_TYPE = {'ascii': ['hw_src']}
def __init__(self, length, hw_src, data):
super(nd_option_la, self).__init__(self.option_type(), length)
self.hw_src = hw_src
self.data = data
def parser(cls... |
def execute_code(message: Message, env: Environment) -> Evm:
code = message.code
valid_jump_destinations = get_valid_jump_destinations(code)
evm = Evm(pc=Uint(0), stack=[], memory=bytearray(), code=code, gas_left=message.gas, env=env, valid_jump_destinations=valid_jump_destinations, logs=(), refund_counter=... |
class ethereumNameIdentifier(Module):
config = Config({Option('ADDRESS', 'Provide your target address or ENS', True): str('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')})
def run(self):
TABLE_DATA = []
address = self.config.option('ADDRESS').value
url = (' + address)
response = re... |
class CRUDDictData(CRUDBase[(DictData, CreateDictData, UpdateDictData)]):
async def get(self, db: AsyncSession, pk: int) -> (DictData | None):
return (await self.get_(db, pk=pk))
async def get_all(self, label: str=None, value: str=None, status: int=None) -> Select:
se = select(self.model).option... |
def destroy_s3_event(app, env, region):
generated = get_details(app=app, env=env)
bucket = generated.s3_app_bucket()
session = boto3.Session(profile_name=env, region_name=region)
s3_client = session.client('s3')
config = {}
s3_client.put_bucket_notification_configuration(Bucket=bucket, Notificat... |
def serialize(obj, name=None, result=None):
if (result is None):
result = {}
def make_name(obj, name=None):
objname = obj.__class__.__name__
if (name is None):
return '({})'.format(objname)
return '{} ({})'.format(name, objname)
name = make_name(obj, name)
try... |
def test__RfqLimitOrder_swap(trace_classifier: TraceClassifier):
transaction_hash = '0x4f66832e654f8a4d773ddfd6bb56626db29b90'
block_number =
swap = Swap(abi_name='INativeOrdersFeature', transaction_hash=transaction_hash, transaction_position=168, block_number=block_number, trace_address=[1, 0, 1, 0, 1], c... |
def execute_exp(config: Config) -> None:
seed = ((os.getpid() + int(datetime.now().strftime('%S%f'))) + int.from_bytes(os.urandom(2), 'big'))
print('Using a generated random seed {}'.format(seed))
config.defrost()
if (config.RUN_TYPE == 'eval'):
config.TASK_CONFIG.TASK.ANGLE_SUCCESS.USE_TRAIN_SU... |
class TargetingDynamicRule(AbstractObject):
def __init__(self, api=None):
super(TargetingDynamicRule, self).__init__()
self._isTargetingDynamicRule = True
self._api = api
class Field(AbstractObject.Field):
field_action_type = 'action.type'
ad_group_id = 'ad_group_id'
... |
def TimerTab(timer, accent_color, text_color, background_color, is_shut_down: bool, is_hibernate: bool, is_sleep: bool):
do_nothing = (not (is_shut_down or is_hibernate or is_sleep))
if (time.time() < timer):
timer_date = datetime.fromtimestamp(timer)
timer_date = timer_date.strftime('%#I:%M %p'... |
(name='vrf.get', req_args=[ROUTE_DISTINGUISHER], opt_args=[VRF_RF])
def get_vrf(route_dist, route_family=VRF_RF_IPV4):
vrf_conf = CORE_MANAGER.vrfs_conf.get_vrf_conf(route_dist, vrf_rf=route_family)
if (not vrf_conf):
raise RuntimeConfigError(desc=('No VrfConf with vpn id %s' % route_dist))
return v... |
def get_data(num_examples: int, num_fl_users: int, examples_per_user: int, fl_batch_size: int, nonfl_batch_size: int, model: IFLModel) -> Tuple[(IFLDataProvider, torch.utils.data.DataLoader)]:
fl_data_provider = get_fl_data_provider(num_examples=num_examples, num_fl_users=num_fl_users, examples_per_user=examples_pe... |
class OptionSeriesPyramidSonificationContexttracksMappingLowpassFrequency(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 node_show_races(caller, raw_string, **kwargs):
text = ' Select a |cRace|n.\n\n Select one by number below to view its details, or |whelp|n\n at any time for more info.\n '
options = []
for race in _SORTED_RACES:
options.append({'desc': '|c{}|n'.format(race.name), 'goto': ... |
class TraceCallGraphTestCase(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
test_data_path = Path(__file__).parent.parent.joinpath('tests/data/call_stack/backward_thread.json')
self.test_trace_backward_threads: str = str(test_data_path)
self.t_backward_threads: Trace = ... |
.asyncio
class TestAEAHelperTCPSocketChannel():
.asyncio
async def test_connection_communication(self):
pipe = TCPSocketChannel()
assert ((pipe.in_path is not None) and (pipe.out_path is not None)), 'TCPSocketChannel not properly setup'
connected = asyncio.ensure_future(pipe.connect())
... |
class HPPrinterEntity(Entity):
hass: HomeAssistant = None
integration_name: str = None
entity: EntityData = None
remove_dispatcher = None
current_domain: str = None
ha = None
entity_manager = None
device_manager = None
def initialize(self, hass: HomeAssistant, integration_name: str, ... |
.parametrize('arguments,expected', (({}, [EVENT_1_TOPIC]), ({'arg0': 1}, [EVENT_1_TOPIC]), ({'arg0': 1, 'arg3': [1, 2]}, [EVENT_1_TOPIC]), ({'arg1': 1}, [EVENT_1_TOPIC, hex_and_pad(1)]), ({'arg1': [1, 2]}, [EVENT_1_TOPIC, [hex_and_pad(1), hex_and_pad(2)]]), ({'arg1': [1], 'arg2': [2]}, [EVENT_1_TOPIC, hex_and_pad(1), h... |
class OptionPlotoptionsPolygon(Options):
def accessibility(self) -> 'OptionPlotoptionsPolygonAccessibility':
return self._config_sub_data('accessibility', OptionPlotoptionsPolygonAccessibility)
def allowPointSelect(self):
return self._config_get(False)
def allowPointSelect(self, flag: bool):... |
class TestHanoi(unittest.TestCase):
def test_hanoi(self):
hanoi = Hanoi()
num_disks = 3
src = Stack()
buff = Stack()
dest = Stack()
print('Test: None towers')
self.assertRaises(TypeError, hanoi.move_disks, num_disks, None, None, None)
print('Test: 0 di... |
class CoprChroot(db.Model, helpers.Serializer):
id = db.Column('id', db.Integer, primary_key=True)
__table_args__ = (db.UniqueConstraint('mock_chroot_id', 'copr_id', name='copr_chroot_mock_chroot_id_copr_id_uniq'),)
copr_id = db.Column(db.Integer, db.ForeignKey('copr.id'))
buildroot_pkgs = db.Column(db.... |
def ensureTensorFlush(tensors: Union[(List[torch.Tensor], torch.Tensor)]) -> float:
x = None
if (isinstance(tensors, list) and (len(tensors) > 0) and (len(tensors[(- 1)]) > 0)):
x = tensors[(- 1)][(- 1)].item()
elif (isinstance(tensors, torch.Tensor) and (tensors.nelement() > 0)):
x = tensor... |
class OptionSeriesPictorialSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool)... |
class EventDetail(ResourceDetail):
def before_get(self, args, kwargs):
kwargs = get_id(kwargs)
if (is_logged_in() and has_access('is_coorganizer', event_id=kwargs['id'])):
self.schema = EventSchema
else:
self.schema = EventSchemaPublic
def before_get_object(self, ... |
class OptionSeriesPyramid3dSonificationDefaultinstrumentoptionsMappingTime(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 FlaskServer(AbstractServer):
def __init__(self, *args, **kwargs):
global app
self._app = app
self._server = None
self._serving = None
super().__init__(*args, **kwargs)
def _open(self, host, port, **kwargs):
if port:
try:
port = in... |
def log_fortianalyzer2_override_setting(data, fos):
vdom = data['vdom']
log_fortianalyzer2_override_setting_data = data['log_fortianalyzer2_override_setting']
filtered_data = underscore_to_hyphen(filter_log_fortianalyzer2_override_setting_data(log_fortianalyzer2_override_setting_data))
return fos.set('l... |
()
_context
('fides_dir', default='.', type=click.Path(exists=True))
('--opt-in', is_flag=True, help='Automatically opt-in to anonymous usage analytics.')
def init(ctx: click.Context, fides_dir: str, opt_in: bool) -> None:
executed_at = datetime.now(timezone.utc)
config = ctx.obj['CONFIG']
click.echo(FIDES_... |
class OptionPlotoptionsHistogramStatesSelect(Options):
def animation(self) -> 'OptionPlotoptionsHistogramStatesSelectAnimation':
return self._config_sub_data('animation', OptionPlotoptionsHistogramStatesSelectAnimation)
def borderColor(self):
return self._config_get('#000000')
def borderColo... |
class UpdateView(GenericModelView):
success_url = None
template_name_suffix = '_form'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form(instance=self.object)
context = self.get_context_data(form=form)
return self.render_to_response(... |
class SSLVerifier(object):
class VerificationError(ValueError):
pass
user_cert = None
ca_cert = None
def __init__(self, cert_user=None, cert_ca=None):
self.__class__.user_cert = cert_user
self.__class__.ca_cert = cert_ca
def verify(cls):
if (cls.user_cert is None):
... |
def parse_args(parser):
args = parser.parse_args()
if ('EGGNOG_DATA_DIR' in os.environ):
set_data_path(os.environ['EGGNOG_DATA_DIR'])
if args.data_dir:
set_data_path(args.data_dir)
if args.version:
version = ''
try:
version = get_full_version_info()
ex... |
class Health(object):
def Check(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None):
return grpc.experimental.unary_unary(request, target, '/grpc.health.v1.Health/Check', health__pb2.HealthCheckRequ... |
class CmdUnloggedinLook(Command):
key = syscmdkeys.CMD_LOGINSTART
locks = 'cmd:all()'
arg_regex = '^$'
def func(self):
menu_nodes = {'node_enter_username': node_enter_username, 'node_enter_password': node_enter_password, 'node_quit_or_login': node_quit_or_login}
MenuLoginEvMenu(self.call... |
def add_new_changes(prev_changes: str):
changes = set(prev_changes.split('\n'))
with open(CHANGELOG_FILE, encoding='utf-8') as _file:
add_changes = False
line = _file.readline()
while line:
line = line.strip()
if (line == VERSION):
add_changes = Tr... |
def getData(s, address):
s.flush()
n = s.write(bytearray(('H%d\r' % address), 'utf-8'))
buf = s.read(3)
print(buf)
buf = s.read(1)
print(buf)
buf = bytearray()
while True:
if (not s.in_waiting):
time.sleep(1)
if (not s.in_waiting):
break
... |
class AutumnWindAction(UserAction):
def __init__(self, source, target_list):
self.source = source
self.target = source
self.target_list = target_list
def apply_action(self):
g = self.game
src = self.source
for p in self.target_list:
g.process_action(Au... |
class KnowledgeSpaceEntity(Model):
__tablename__ = 'knowledge_space'
id = Column(Integer, primary_key=True)
name = Column(String(100))
vector_type = Column(String(100))
desc = Column(String(100))
owner = Column(String(100))
context = Column(Text)
gmt_created = Column(DateTime)
gmt_mo... |
class Settings(object):
def __init__(self, common):
self.c = common
self.system = self.c.os
if (self.system == 'Windows'):
appdata = os.environ['APPDATA']
self.appdata_path = '{0}\\gpgsync'.format(appdata)
elif (self.system == 'Darwin'):
self.appda... |
class OptionSeriesCylinderMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config(te... |
class Committee(BaseConcreteCommittee):
__table_args__ = {'extend_existing': True}
__tablename__ = 'ofec_committee_detail_mv'
sponsor_candidate_list = db.relationship('PacSponsorCandidate', primaryjoin='and_(\n foreign(PacSponsorCandidate.committee_id) == Committee.committee_id,\n ... |
class TestValidatePathTests():
def test_path_does_not_exist(self):
with pytest.raises(ValueError) as exc:
config.validate_path('/does/not/exist')
assert (str(exc.value) == "'/does/not/exist' does not exist.")
def test_path_is_none(self):
with pytest.raises(ValueError) as exc:... |
class TestRefResolverExceptions():
def test_cast_raise(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', [''])
with pytest.raises(_SpockResolverError):
config = SpockBuilder(RefCastRaise, RefClass, desc='Test Builder')
config.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.