code
stringlengths
281
23.7M
def _test_get(client, _id, expected_response=None, expected_status_code=status.HTTP_200_OK): endpoint = ((ENDPOINT + str(_id)) + '/') response = client.get(endpoint) assert (response.status_code == expected_status_code) if (expected_response is not None): assert (json.loads(response.content.deco...
def parse_imports(filepath: str) -> List[ImportedItem]: with open(filepath, 'r') as filehandle: filecontent = filehandle.read() imports = [] for node in ast.parse(filecontent, filename=filepath).body: if isinstance(node, ast.Import): imports += [ImportedItem(alias.name, None) for...
class ESMasterRunner(TrainingRunner, ABC): shared_noise_table_size: int shared_noise: Optional[SharedNoiseTable] = dataclasses.field(default=None, init=False) (TrainingRunner) def setup(self, cfg: DictConfig) -> None: super().setup(cfg) print(' Init Shared Noise Table ') self.sha...
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingVolume(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, te...
class TestCommentedMapMerge(): def test_in_operator(self): data = round_trip_load('\n x: &base\n a: 1\n b: 2\n c: 3\n y:\n <<: *base\n k: 4\n l: 5\n ') assert (data['x']['a'] == 1) assert ('a' in data['x']) as...
class HeapMax(): def __init__(self, size): self.nheap = 0 self.maxheap = size self.heap = ([0] * size) def downheap(self): tmp = 0 i = 0 while True: left = ((i << 1) + 1) right = (left + 1) if (left >= self.nheap): ...
class WebFrontEnd(): def __init__(self, db: (FrontendDatabase | None)=None, intercom=None, status_interface=None): self.program_version = __VERSION__ self.intercom = (InterComFrontEndBinding() if (intercom is None) else intercom()) self.db = (FrontendDatabase() if (db is None) else db) ...
class ThresholdArgs(): def __init__(self, arguments): self.max = arguments([]) area_threshold = arguments['--area-threshold'] self.volume_distance = arguments['--volume-distance'] min_threshold = arguments['--min-threshold'] max_threshold = arguments['--max-threshold'] ...
class TestShrinkIndex(): ('elasticsearch.Elasticsearch') ('asyncio.sleep') .asyncio async def test_shrink_index_with_shrink_node(self, sleep, es): es.indices.get = mock.AsyncMock(return_value={'src': {}}) es.cluster.health = mock.AsyncMock(return_value={'status': 'green', 'relocating_sha...
def extractDianilleBlogspotCom(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) i...
class Decoder(): def __init__(self): self.vm = None def loaded(self): return bool(self.vm) def load(self, bili_js_url): bili_js = grabhtml(bili_js_url) js = (('\n\t\tconst window = {};\n\t\tconst self = window;\n\t\t' + bili_js) + '\n\t\tlet decode;\n\t\tlet factory;\n\t\tlet...
def instance_norm(x, num_filters): epsilon = 0.001 shape = [num_filters] scale = tf.Variable(tf.ones(shape), name='scale') shift = tf.Variable(tf.zeros(shape), name='shift') (mean, var) = tf.nn.moments(x, [1, 2], keep_dims=True) x_normed = tf.div(tf.subtract(x, mean), tf.sqrt(tf.add(var, epsilon...
def update_mix(): scale = patch.getfloat('scale', 'mix', default=1.0) offset = patch.getfloat('offset', 'mix', default=0.0) mix = np.zeros((input_nchans, output_nchans), dtype=float) for o in range(0, output_nchans): channame = ('mix%d' % (o + 1)) chanmix = patch.getfloat('output', chann...
class MyIterator(): def __init__(self, data): self.index = 0 self.data = data def __iter__(self): return self def __next__(self): if (self.index >= len(self.data)): raise StopIteration result = self.data[self.index] self.index += 1 return r...
def script_name_for_python_version(name, version, minor=False, default_number=True): if (not default_number): if (version == settings.DEFAULT_PYTHON_VERSIONS[name_convertor.NameConvertor.distro][0]): return name if minor: if (len(version) > 1): return '{0}-{1}'.format(nam...
class SettingsDialog(QtWidgets.QDialog): def __init__(self, common): super(SettingsDialog, self).__init__() self.c = common self.setWindowTitle('GPG Sync Settings') self.setMinimumSize(425, 200) self.setMaximumSize(425, 400) self.settings = self.c.settings sel...
(CreateSearchFunctionSQL) def compile_create_search_function_sql(element, compiler): return f'''CREATE FUNCTION {element.search_function_name}() RETURNS TRIGGER AS $$ BEGIN NEW.{element.tsvector_column.name} = {element.search_vector(compiler)}; RETURN NEW; END ...
.parametrize('calc_cls, start, ref_cycle, ref_coords', [(AnaPot, (0.667, 1.609, 0.0), 18, (1.941, 3.8543, 0.0)), (AnaPot3, ((- 0.36), 0.93, 0.0), 10, ((- 1.0), 0.0, 0.0)), (AnaPot4, ((- 0.5), 3.32, 0.0), 11, ((- 2.2102), 0.3297, 0.0)), (AnaPotCBM, ((- 0.32), 0.71, 0.0), 10, ((- 1.0), 0.0, 0.0)), (CerjanMiller, ((- 0.46...
_admin_required def BookingSendReceipt(request, location_slug, booking_id): if (not (request.method == 'POST')): return HttpResponseRedirect('/404') location = get_object_or_404(Location, slug=location_slug) booking = Booking.objects.get(id=booking_id) if booking.is_paid(): status = send...
class OFPQueueProp(OFPQueuePropHeader): _QUEUE_PROP_PROPERTIES = {} def register_property(property_, len_): def _register_property(cls): cls.cls_property = property_ cls.cls_len = len_ OFPQueueProp._QUEUE_PROP_PROPERTIES[cls.cls_property] = cls return cls ...
def fill_state_test(filler: Dict[(str, Any)]) -> Dict[(str, Dict[(str, Any)])]: test_name = get_test_name(filler) test = filler[test_name] environment = normalize_environment(test['env']) pre_state = normalize_state(test['pre']) transaction_group = normalize_transaction_group(test['transaction']) ...
class TestSessionValidation(OpenEventTestCase): def test_date_db_populate(self): with self.app.test_request_context(): schema = SessionSchema() SessionFactory() original_data = {'data': {'id': 1}} data = {} SessionSchema.validate_fields(schema, dat...
def test_tensor_spatialcoordinate_interpolation(parentmesh, vertexcoords): if (parentmesh.name == 'immersedsphere'): vertexcoords = immersed_sphere_vertexcoords(parentmesh, vertexcoords) vm = VertexOnlyMesh(parentmesh, vertexcoords, missing_points_behaviour=None) vertexcoords = vm.coordinates.dat.da...
class KthLargest(object): def __init__(self, k, nums): self.hp = nums heapq.heapify(self.hp) self.k = k while (len(self.hp) > k): heapq.heappop(self.hp) def add(self, val): heapq.heappush(self.hp, val) if (len(self.hp) > self.k): heapq.heap...
class Plugin(plugin.PluginProto): PLUGIN_ID = 19 PLUGIN_NAME = 'Extra IO - PCF8574' PLUGIN_VALUENAME1 = 'State' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskindex) self.dtype = rpieGlobals.DEVICE_TYPE_I2C self.vtype = rpieGlobals.SENSOR_TYPE_SWITCH ...
.usefixtures('use_tmpdir') def test_queue_option_max_running_non_int(): assert_that_config_leads_to_error(config_file_contents=dedent('\n NUM_REALIZATIONS 1\n QUEUE_SYSTEM LOCAL\n QUEUE_OPTION LOCAL MAX_RUNNING s\n '), expected_error=ExpectedErrorInfo(line=4, column=32, e...
class ModelTransformer(): def __init__(self, model: Any, feature_names: Sequence[str], classification_labels: Optional[Sequence[str]]=None, classification_weights: Optional[Sequence[float]]=None): self._feature_names = feature_names self._model = model self._classification_labels = classific...
.parametrize('node,description', [(OBJ, '```TypeScript\n\nobject: { // Object Description\n number: number // Number Description\n text: string // Text Description\n selection: "blue" // Selection Description\n selection2: Array<"blue" | "red"> // Selection2 Description\n bool: boolean // Bool Description\n}\n```\n')])...
_default class FileAttachment(Attachment): url = attr.ib(None, type=Optional[str]) size = attr.ib(None, type=Optional[int]) name = attr.ib(None, type=Optional[str]) is_malicious = attr.ib(None, type=Optional[bool]) def _from_graphql(cls, data, size=None): return cls(url=data.get('url'), size...
(stop_max_attempt_number=5, wait_fixed=5000) def get_image_build(image_name, version, image_offset, with_timestamp): response = get_session().get((((((base_images_url + '/') + image_name) + '/versions/') + version) + '/builds'), params={'image_offset': image_offset, 'with_timestamp': with_timestamp}, timeout=3.5) ...
class TestDataFrameCount(TestData): filter_data = ['AvgTicketPrice', 'Cancelled', 'dayOfWeek', 'timestamp', 'DestCountry'] def test_count(self, df): df.load_dataset('ecommerce') df.count() def test_count_flights(self): pd_flights = self.pd_flights().filter(self.filter_data) e...
def _validate_parameter(code: ExampleFunction, name: str, index: int, allow_async: bool=True) -> None: parameters = list(inspect.signature(code).parameters.keys()) if ((not parameters) or (parameters[index] != name)): raise ValueError(f"Function must receive parameter #{(index + 1)} named '{name}', but ...
class FBPrintAsCurl(fb.FBCommand): def name(self): return 'pcurl' def description(self): return 'Print the NSURLRequest (HTTP) as curl command.' def options(self): return [fb.FBCommandArgument(short='-e', long='--embed-data', arg='embed', boolean=True, default=False, help='Embed requ...
class ButtonsWidget(QWidget): buttons_mode = ButtonsMode.INTERNAL qt_css_extra = '' def __init__(self): super().__init__() self.buttons: Iterable[QAbstractButton] = [] def resizeButtons(self): frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) if (self.bu...
def dipole_magnetic(coordinates, dipoles, magnetic_moments, parallel=True, dtype='float64', disable_checks=False): cast = np.broadcast(*coordinates[:3]) (b_e, b_n, b_u) = tuple((np.zeros(cast.size, dtype=dtype) for _ in range(3))) coordinates = tuple((np.atleast_1d(i).ravel() for i in coordinates[:3])) ...
class multi_level_roi_align(roi_ops_base): def __init__(self, num_rois, pooled_size, sampling_ratio, spatial_scale, position_sensitive, continuous_coordinate, im_shape) -> None: super().__init__(num_rois, pooled_size, sampling_ratio, spatial_scale, position_sensitive, continuous_coordinate) self._at...
.usefixtures('migrate_db') class CandidatesTestCase(common.BaseTestCase): def setUp(self): super().setUp() self.longMessage = True self.maxDiff = None self.request_context = rest.app.test_request_context() self.request_context.push() self.connection = db.engine.connec...
('click.echo') class TestNothingToUpgrade(AEATestCaseEmpty): def test_nothing_to_upgrade(self, mock_click_echo): agent_config = self.load_agent_config(self.agent_name) result = self.run_cli_command('upgrade', cwd=self._get_cwd()) assert (result.exit_code == 0) mock_click_echo.assert_...
class SystemStatus(): def __init__(self) -> None: self.status: Dict[(str, StatusInfo)] = {} def failure(self, key: str, message: str) -> None: self.info_for_key(key).failure(message) def OK(self, key: str, message: str) -> None: self.info_for_key(key).OK(message) def info_for_key...
class ValidatedTuple(BaseTuple): def __init__(self, *types, **metadata): metadata.setdefault('fvalidate', None) metadata.setdefault('fvalidate_info', '') super().__init__(*types, **metadata) def validate(self, object, name, value): values = super().validate(object, name, value) ...
def check_event_user_ticket_holders(order, data, element): if ((element in ['event', 'user']) and (data[element] != str(getattr(order, element, None).id))): raise ForbiddenError({'pointer': f'data/{element}'}, f'You cannot update {element} of an order') if (element == 'ticket_holders'): ticket_h...
class MultiNetworkIPForm(SerializerForm): _api_call = net_ip_list template = 'gui/dc/network_ips_form.html' ips = ArrayField(required=True, widget=forms.HiddenInput()) def __init__(self, request, net, ip, *args, **kwargs): self.net = net super(MultiNetworkIPForm, self).__init__(request, ...
class TraitsTool(BaseTool): draw_mode = 'none' visible = False classes = List([PlotAxis, ColorBar]) views = Dict event = Str('left_dclick') def _dispatch_stateful_event(self, event, suffix): if (suffix != self.event): return x = event.x y = event.y can...
class LocalBinaryPath(BinaryPath): def __init__(self, exe_folder: str, binary_info: BinaryInfo) -> None: self.exe_folder: str = exe_folder self.binary: str = (binary_info.binary or binary_info.package.rsplit('/')[(- 1)]) def _stringify(self) -> str: return f'{self.exe_folder}{self.binary...
class OptionPlotoptionsParetoSonificationDefaultinstrumentoptionsMappingTremoloDepth(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,...
(max_runs=3) def test_miner_set_extra(web3_empty, wait_for_block): web3 = web3_empty initial_extra = decode_hex(web3.eth.get_block(web3.eth.block_number)['extraData']) new_extra_data = b'-this-is-32-bytes-of-extra-data-' assert (initial_extra != new_extra_data) web3.geth.miner.set_extra(new_extra_da...
class Logger(): _static_cache = set() def __init__(self): self.handlers = {} self.suppression = True self._counts = None self._stack = None self._capture = False self._captured_warnings = [] def set_capture(self, capture: bool): self._capture = capture...
class VideoUploader(): def __init__(self, protect: ProtectApiClient, upload_queue: VideoQueue, rclone_destination: str, rclone_args: str, file_structure_format: str, db: aiosqlite.Connection, color_logging: bool): self._protect: ProtectApiClient = protect self.upload_queue: VideoQueue = upload_queue...
def _build_token_prices(coingecko_price_data, token_address) -> List[Price]: time_series = coingecko_price_data['prices'] prices = [] for entry in time_series: timestamp = datetime.fromtimestamp((entry[0] / 1000)) token_price = entry[1] prices.append(Price(timestamp=timestamp, usd_pr...
class ACEScc(sRGB): BASE = 'acescg' NAME = 'acescc' SERIALIZE = ('--acescc',) WHITE = (0.32168, 0.33767) CHANNELS = (Channel('r', CC_MIN, CC_MAX, bound=True, nans=CC_MIN), Channel('g', CC_MIN, CC_MAX, bound=True, nans=CC_MIN), Channel('b', CC_MIN, CC_MAX, bound=True, nans=CC_MIN)) DYNAMIC_RANGE ...
class RelationshipMemberWafRule(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_imp...
def extractMagnogartenBlogspotCom(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...
class DBStorageConversationItemAdapter(StorageItemAdapter[(StorageConversation, ChatHistoryEntity)]): def to_storage_format(self, item: StorageConversation) -> ChatHistoryEntity: message_ids = ','.join(item.message_ids) messages = None if ((not item.save_message_independent) and item.message...
class OptionSeriesHistogramSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionSeriesHistogramSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionSeriesHistogramSonificationContexttracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionSer...
def consolidate_data_for_date(date): pattern = '{}*.csv.gz'.format(local_storage_prefix_for_date(date)) input_files = glob.glob(pattern) target_file = get_prescribing_filename(date) temp_file = get_temp_filename(target_file) logger.info('Consolidating %s data files into %s', len(input_files), target...
def flatten(inputs: List[Optional[typing.Union[(bn.BMGNode, List[bn.BMGNode])]]]) -> List[bn.BMGNode]: parents = [] for input in inputs: if (input is None): continue if isinstance(input, List): for i in input: parents.append(i) else: pa...
def check_repo_clean(root: Path, main: DecoratedMain): out = run_command(['git', 'status', '--porcelain']) filtered = [] grid_name = main.dora.grid_package if (grid_name is None): grid_name = (main.package + '.grids') spec = importlib.util.find_spec(grid_name) grid_path: tp.Optional[Path...
def _discover_test_functions_in_sample_code(sample: pathlib.Path) -> List[str]: test_names = list() with sample.open('r', encoding='utf-8') as f: for line in f.readlines(): if (match := re.match('\\w+ (?P<test_name>test\\d+)\\(.*\\)', line)): test_names.append(match.group('te...
def check_terminal_encoding(): if (sys.stdout.isatty() and ((sys.stdout.encoding == None) or (sys.stdin.encoding == None))): print(_("WARNING: The terminal encoding is not correctly configured. gitinspector might malfunction. The encoding can be configured with the environment variable 'PYTHONIOENCODING'.")...
def get_stats(paths): cc = CCHarvester(paths, cc_config) raw = RawHarvester(paths, cc_config) cc.run() raw.run() header = ['Filename', 'SLOC', '#Functions', '#Intercepts', 'Max CC', 'Ave CC', 'Median CC', 'Min CC'] data = {} for file_data in cc.results: (filename, cc_results) = file_...
class LedgerDialogues(ContractApiDialogues): def __init__(self, self_address: Address) -> None: def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role: return ContractApiDialogue.Role.LEDGER ContractApiDialogues.__init__(self, self_address=self_addr...
def additionals(utils): obj = (lambda : None) obj.maxDiff = None obj.emptyAnalyserName = 'empty' obj.WHITELIST = ['sel1/an1', 'sel1/an2', 'sel2'] obj.sel1 = 'sel1' obj.sel2 = 'sel2' obj.sel1_elements = ['el1', 'el2'] obj.sel2_elements = ['el4', 'el5', 'el6'] utils.scaffold_empty(obj....
class TestTimezoneField(): class TimezoneForm(Form): timezone = TimezoneField() .parametrize('timezone', ['Europe/Nantes', 'US/Paris']) def test_invalid(self, timezone: str): form = TestTimezoneField.TimezoneForm(FormData({'timezone': timezone})) assert (form.validate() is False) ...
_abort.register_cause_code _error.register_cause_code class cause_missing_param(cause): _PACK_STR = '!HHI' _MIN_LEN = struct.calcsize(_PACK_STR) def cause_code(cls): return CCODE_MISSING_PARAM def __init__(self, types=None, num=0, length=0): super(cause_missing_param, self).__init__(leng...
def modify_function_body(function_definition: ast.FunctionDefinition, modifiers: List[ast.ModifierInvocation]): modifiers = [m for m in modifiers if (not m.is_constructor)] cfg = function_definition.cfg_body cfg = wrap_function(cfg, function_definition.arguments, function_definition.returns, function_defini...
class AdPromotedObject(AbstractObject): def __init__(self, api=None): super(AdPromotedObject, self).__init__() self._isAdPromotedObject = True self._api = api class Field(AbstractObject.Field): application_id = 'application_id' conversion_goal_id = 'conversion_goal_id' ...
class PySOALogContextFilter(logging.Filter): def __init__(self): super(PySOALogContextFilter, self).__init__('') def filter(self, record): context = self.get_logging_request_context() if context: setattr(record, 'correlation_id', (context.get('correlation_id') or '--')) ...
def csl(): datasets_name = sys._getframe().f_code.co_name writer = csv.writer(open('./pretrain_datasets/output/{}.txt'.format(datasets_name), 'w'), delimiter='\t') base_dir = './pretrain_datasets/csl/' for (root, dirs, files) in os.walk(base_dir): for file in files: file_path = ((roo...
class BaseTrainer(): def __init__(self, datamodule: video_transformers.data.VideoDataModule, model: VideoModel, max_epochs: int=12, cpu: bool=False, mixed_precision: str='no', output_dir: str='runs', seed: int=42, trackers: List[GeneralTracker]=None, checkpoint_save: bool=True, checkpoint_save_interval: int=1, chec...
def test_parse_parameter_event(): data = bytes.fromhex(rcl_interfaces__ParameterEvent) reader = CdrReader(data) assert (reader.uint32() == ) assert (reader.int32() == ) assert (reader.string() == '/_ros2cli_378363') assert (reader.sequence_length() == 1) assert (reader.string() == 'use_sim_t...
def cluster_lines(node): node.collapsed = False node.img_style['fgcolor'] = '#3333FF' node.img_style['size'] = 4 matrix_max = numpy.max(node.arraytable._matrix_max) matrix_min = numpy.min(node.arraytable._matrix_min) matrix_avg = (matrix_min + ((matrix_max - matrix_min) / 2)) ProfileFace = f...
def check_label_consistency(task: SpanTask) -> List[SpanExample]: assert task.prompt_examples assert issubclass(task.prompt_example_type, SpanExample) example_labels = {task.normalizer(key): key for example in task.prompt_examples for key in example.entities} unspecified_labels = {example_labels[key] fo...
class DataSetClipper(Filter): __version__ = 0 widget = Instance(ImplicitWidgets, allow_none=False, record=True) filter = Instance(tvtk.Object, allow_none=False, record=True) update_mode = Delegate('widget', modify=True) input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=...
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 extract_domain(data): regexp = re.compile('([a-zA-Z0-9_.-]+)') match = regexp.finditer(data) result = set() for m in match: candidate = m.group(0).lower() if ('.' not in candidate): continue if (not re.match('[a-z]+', candidate)): continue if (...
class AnalyseSummaryTotalsTest(SeleniumTestCase): def test_summary_totals_on_analyse_page(self): self.browser.get((self.live_server_url + '/analyse/#org=CCG&numIds=0212000AA')) expected = {'panel-heading': 'Total prescribing for Rosuvastatin Calcium across all Sub-ICB Locations in NHS England', 'js-...
class TestTicketGeneratorSlice(ZenpyApiTestCase): __test__ = False def test_ticket_slice_low_bound(self): with self.recorder.use_cassette(self.generate_cassette_name(), serialize_with='prettyjson'): ticket_generator = self.zenpy_client.tickets() values = ticket_generator[:1] ...
class OrderControl(StateMachine): waiting_for_payment = State(initial=True) processing = State() shipping = State() completed = State(final=True) add_to_order = waiting_for_payment.to(waiting_for_payment) receive_payment = (waiting_for_payment.to(processing, cond='payments_enough') | waiting_for...
class CustomResponseCode(CustomCodeBase): HTTP_200 = (200, '') HTTP_201 = (201, '') HTTP_202 = (202, ',') HTTP_204 = (204, ',') HTTP_400 = (400, '') HTTP_401 = (401, '') HTTP_403 = (403, '') HTTP_404 = (404, '') HTTP_410 = (410, '') HTTP_422 = (422, '') HTTP_425 = (425, ',') ...
def calc_greit_figures_of_merit(target_image, reconstruction_image, conductive_target=True, return_extras=False) -> (Tuple | Tuple[(Tuple, Dict)]): extras = {'shape_deformation': {}, 'ringing': {}} amplitude = calc_amplitude(reconstruction_image) position_error = calc_position_error(target_image, reconstruc...
class BuildTimedeltaSchema(StrictSchema): units = ma.fields.String(required=True) _schema def check_valid_units(self, data): ALLOWED_UNITS = ['seconds', 'minutes', 'hours', 'days'] if (data.get('units') not in ALLOWED_UNITS): raise ma.ValidationError('`units` must be one of `{}`'...
def getCbText(): txt = wx.TextDataObject() while True: try: if (not wx.TheClipboard.IsOpened()): if wx.TheClipboard.Open(): wx.TheClipboard.GetData(txt) wx.TheClipboard.Close() break pass exce...
class JoyStickKey(Enum): StartKey = 7 SelectKey = 6 ModeKey = 8 RLeftKey = 2 RRightKey = 1 RTopKey = 3 RBottomKey = 0 R1 = 5 L1 = 4 LJoyStickKey = 9 RJoyStickKey = 10 ArrowUp = (0, 1) ArrowDown = (0, (- 1)) ArrowLeft = ((- 1), 0) ArrowRight = (1, 0) ArrowR...
class Agg(DslBase): _type_name = 'agg' _type_shortcut = staticmethod(A) name = None def __contains__(self, key): return False def to_dict(self): d = super().to_dict() if ('meta' in d[self.name]): d['meta'] = d[self.name].pop('meta') return d def result...
def extractDaydreamTranslations(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,...
class OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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...
def test_shutdown_raises(): class HandlerA(): def __init__(self): self._startup_called = False async def process_startup(self, scope, event): self._startup_called = True async def process_shutdown(self, scope, event): raise Exception('testing 321') cla...
def test_discriminant_raises_exception_if_called_with_incorrect_data_type(): def d(data, axis): return np.nanmax(data, axis=axis) with pytest.raises(TypeError): d('foo') with pytest.raises(TypeError): d(np.array(['foo'])) with pytest.raises(TypeError): d([1, 2, 3])
class OptionPlotoptionsNetworkgraphSonificationContexttracksMappingVolume(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 QueryServicer(object): def ClientState(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ClientStates(self, request, context): context.set_code(grp...
class OptionPlotoptionsDumbbellSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionPlotoptionsDumbbellSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsDumbbellSonificationDefaultinstrumentoptionsMappingFrequency...
class OptionPlotoptionsArearangeSonificationTracksMappingPlaydelay(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): ...
_cache(maxsize=1024) def arp_reply(vid, eth_src, eth_dst, src_ip, dst_ip): pkt = build_pkt_header(vid, eth_src, eth_dst, valve_of.ether.ETH_TYPE_ARP) arp_pkt = arp.arp(opcode=arp.ARP_REPLY, src_mac=eth_src, src_ip=src_ip, dst_mac=eth_dst, dst_ip=dst_ip) pkt.add_protocol(arp_pkt) pkt.serialize() retu...
class BaseF3XFilingSchema(BaseEfileSchema): class Meta(BaseEfileSchema.Meta): model = models.BaseF3XFiling def parse_summary_rows(self, obj, **kwargsj): descriptions = decoders.f3x_description line_list = extract_columns(obj, decoders.f3x_col_a, decoders.f3x_col_b, descriptions) ...
def main(args): images_loader = ReadFromFolder(args.input_folder_path) video_writer = VideoWriter(args.output_video_path, args.framerate) img_displayer = ImageDisplayer() N = len(images_loader) i = 0 while (i < N): print('Processing {}/{}th image'.format(i, N)) img = images_loade...
def generic_create(evm: Evm, endowment: U256, contract_address: Address, memory_start_position: U256, memory_size: U256) -> None: from ...vm.interpreter import STACK_DEPTH_LIMIT, process_create_message evm.accessed_addresses.add(contract_address) create_message_gas = max_message_call_gas(Uint(evm.gas_left))...
def prioritize_dtypes(cell_outputs: List[NotebookNode]) -> Tuple[(List[List[str]], List[bool])]: cell_output_dtypes = [(list(cell_output['data'].keys()) if ('data' in cell_output) else [cell_output['output_type']]) for cell_output in cell_outputs] prioritized_cell_output_dtypes = [sorted(set(dtypes).intersectio...
def test_signal_integration(django_elasticapm_client): try: int('hello') except ValueError: got_request_exception.send(sender=None, request=None) assert (len(django_elasticapm_client.events[ERROR]) == 1) event = django_elasticapm_client.events[ERROR][0] assert ('exception' in event) ...
class Email(DB.Model): __tablename__ = 'emails' address = DB.Column(DB.Text, primary_key=True) owner_id = DB.Column(DB.Integer, DB.ForeignKey('users.id'), primary_key=True) registered_on = DB.Column(DB.DateTime, default=DB.func.now()) def send_confirmation(addr, user_id): g.log = g.log.new(a...
class Config(object): def __init__(self, path=None): cconfig = ffi.new('git_config **') if (not path): err = C.git_config_new(cconfig) else: assert_string(path, 'path') err = C.git_config_open_ondisk(cconfig, to_bytes(path)) check_error(err, True) ...