code
stringlengths
281
23.7M
def test_mpi_task(serialization_settings: SerializationSettings): (task_config=MPIJob(num_workers=10, num_launcher_replicas=10, slots=1), requests=Resources(cpu='1'), cache=True, cache_version='1') def my_mpi_task(x: int, y: str) -> int: return x assert (my_mpi_task(x=10, y='hello') == 10) assert (my_mpi_task.task_config is not None) assert (my_mpi_task.get_custom(serialization_settings) == {'launcherReplicas': {'replicas': 10, 'resources': {}}, 'workerReplicas': {'replicas': 10, 'resources': {}}, 'slots': 1}) assert (my_mpi_task.task_type == 'mpi') assert (my_mpi_task.task_type_version == 1)
class JsHtmlIFrame(JsHtml.JsHtml): def src(self, src: Union[(str, primitives.JsDataModel)]): src = JsUtils.jsConvertData(src, None) return self.setAttribute('src', src) def srcdoc(self, content: Union[(str, primitives.JsDataModel)]): content = JsUtils.jsConvertData(content, None) return self.setAttribute('srcdoc', content)
class SlaveVmDefine(object): def __init__(self, slave_vm): self.slave_vm = slave_vm self.vm = slave_vm.vm self._nss = {} def get_zpool(disk): try: return disk['zfs_filesystem'].split('/')[0] except (KeyError, IndexError): raise APIValidationError('Invalid disk configuration.') def _change_zpool(dataset, zpool): fs = dataset.split('/') fs[0] = zpool.strip() return '/'.join(fs) def change_zpool(cls, disk, zpool): try: dataset = disk['zfs_filesystem'] except KeyError: raise APIValidationError('Invalid disk configuration.') else: return cls._change_zpool(dataset, zpool) def _change_zfs_filesystem(self, node_storage, disk_or_json, save_same_zpool=True): new_zpool = node_storage.zpool old_zpool = self.get_zpool(disk_or_json) new_fs = self.change_zpool(disk_or_json, new_zpool) if (old_zpool == new_zpool): new_zpool = None if save_same_zpool: self._nss[old_zpool] = node_storage else: self._nss[new_zpool] = node_storage return (new_fs, new_zpool) def validate_zpool(self, zpool): try: return self.vm.node.get_node_storage(self.vm.dc, zpool) except NodeStorage.DoesNotExist: msg = _('Storage with zpool=%(zpool)s does not exist on target node.') raise APIValidationError((msg % {'zpool': zpool})) def save_root_zpool(self, root_zpool, save_same_zpool=True): vm = self.vm json = vm.json if ((not root_zpool) and save_same_zpool): root_zpool = self.get_zpool(json) if (not root_zpool): return None root_ns = self.validate_zpool(root_zpool) (json['zfs_filesystem'], new_root_zpool) = self._change_zfs_filesystem(root_ns, json, save_same_zpool) if new_root_zpool: json['zpool'] = new_root_zpool if (not vm.is_hvm()): datasets = json.get('datasets', ()) for (i, dataset) in enumerate(datasets): json['datasets'][i] = self._change_zpool(dataset, new_root_zpool) vm.json = json return new_root_zpool def save_disk_zpools(self, disk_zpools, save_same_zpool=True): vm = self.vm json = vm.json disks = vm.json_get_disks() new_disks = [] for (i, disk) in enumerate(disks, start=1): if ((not save_same_zpool) and (i not in disk_zpools)): continue zpool = disk_zpools.get(i, self.get_zpool(disk)) ns = self.validate_zpool(zpool) (disk['zfs_filesystem'], new_disk_zpool) = self._change_zfs_filesystem(ns, disk, save_same_zpool) if new_disk_zpool: disk['zpool'] = zpool else: disk_zpools.pop(i, None) if (not save_same_zpool): continue new_disks.append(disk) json['disks'] = new_disks vm.json = json return disk_zpools def validate_node_resources(self, ignore_cpu_ram=False, ignore_disk=False): vm = self.vm node = vm.node dc_node = node.get_dc_node(vm.dc) vm_resources = vm.get_cpu_ram_disk(zpool=node.zpool, ram_overhead=True, ignore_cpu_ram=ignore_cpu_ram, ignore_disk=ignore_disk) if (not dc_node.check_free_resources(*vm_resources)): raise APIValidationError(_('Not enough free resources on target node.')) def validate_storage_resources(self): for (zpool, size) in self.vm.get_disks().items(): ns = self._nss[zpool] if (not ns.check_free_space(size)): raise APIValidationError((_('Not enough free disk space on target storage with zpool=%s.') % zpool)) def check_required_images(self): for disk in self.vm.json_get_disks(): if ('image_uuid' in disk): ns = self._nss[disk['zpool']] if (not ns.images.filter(uuid=disk['image_uuid']).exists()): return (ns, Image.objects.get(uuid=disk['image_uuid'])) return None def save(self, **kwargs): self.slave_vm.save(update_node_resources=True, update_storage_resources=self._nss.values(), **kwargs)
class OptionSeriesFunnelDataDragdrop(Options): def draggableX(self): return self._config_get(None) def draggableX(self, flag: bool): self._config(flag, js_type=False) def draggableY(self): return self._config_get(None) def draggableY(self, flag: bool): self._config(flag, js_type=False) def dragHandle(self) -> 'OptionSeriesFunnelDataDragdropDraghandle': return self._config_sub_data('dragHandle', OptionSeriesFunnelDataDragdropDraghandle) def dragMaxX(self): return self._config_get(None) def dragMaxX(self, num: float): self._config(num, js_type=False) def dragMaxY(self): return self._config_get(None) def dragMaxY(self, num: float): self._config(num, js_type=False) def dragMinX(self): return self._config_get(None) def dragMinX(self, num: float): self._config(num, js_type=False) def dragMinY(self): return self._config_get(None) def dragMinY(self, num: float): self._config(num, js_type=False) def dragPrecisionX(self): return self._config_get(0) def dragPrecisionX(self, num: float): self._config(num, js_type=False) def dragPrecisionY(self): return self._config_get(0) def dragPrecisionY(self, num: float): self._config(num, js_type=False) def dragSensitivity(self): return self._config_get(2) def dragSensitivity(self, num: float): self._config(num, js_type=False) def groupBy(self): return self._config_get(None) def groupBy(self, text: str): self._config(text, js_type=False) def guideBox(self) -> 'OptionSeriesFunnelDataDragdropGuidebox': return self._config_sub_data('guideBox', OptionSeriesFunnelDataDragdropGuidebox) def liveRedraw(self): return self._config_get(True) def liveRedraw(self, flag: bool): self._config(flag, js_type=False)
def _config_to_hf(cls, curated_config: GPTNeoXConfig) -> Dict[(str, Any)]: out = config_to_hf(curated_config, [k for (k, _) in HF_CONFIG_KEYS]) if issubclass(cls, DecoderModule): return HF_SPECIFIC_CONFIG_DECODER.merge(out) else: return HF_SPECIFIC_CONFIG_CAUSAL_LM.merge(out)
class bsn_gentable_bucket_stats_request(bsn_stats_request): version = 6 type = 18 stats_type = 65535 experimenter = 6035143 subtype = 5 def __init__(self, xid=None, flags=None, table_id=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: self.flags = 0 if (table_id != None): self.table_id = table_id else: self.table_id = 0 return def pack(self): packed = [] packed.append(struct.pack('!B', self.version)) packed.append(struct.pack('!B', self.type)) packed.append(struct.pack('!H', 0)) packed.append(struct.pack('!L', self.xid)) packed.append(struct.pack('!H', self.stats_type)) packed.append(struct.pack('!H', self.flags)) packed.append(('\x00' * 4)) packed.append(struct.pack('!L', self.experimenter)) packed.append(struct.pack('!L', self.subtype)) packed.append(struct.pack('!H', self.table_id)) length = sum([len(x) for x in packed]) packed[2] = struct.pack('!H', length) return ''.join(packed) def unpack(reader): obj = bsn_gentable_bucket_stats_request() _version = reader.read('!B')[0] assert (_version == 6) _type = reader.read('!B')[0] assert (_type == 18) _length = reader.read('!H')[0] orig_reader = reader reader = orig_reader.slice(_length, 4) obj.xid = reader.read('!L')[0] _stats_type = reader.read('!H')[0] assert (_stats_type == 65535) obj.flags = reader.read('!H')[0] reader.skip(4) _experimenter = reader.read('!L')[0] assert (_experimenter == 6035143) _subtype = reader.read('!L')[0] assert (_subtype == 5) obj.table_id = reader.read('!H')[0] return obj def __eq__(self, other): if (type(self) != type(other)): return False if (self.xid != other.xid): return False if (self.flags != other.flags): return False if (self.table_id != other.table_id): return False return True def pretty_print(self, q): q.text('bsn_gentable_bucket_stats_request {') with q.group(): with q.indent(2): q.breakable() q.text('xid = ') if (self.xid != None): q.text(('%#x' % self.xid)) else: q.text('None') q.text(',') q.breakable() q.text('flags = ') value_name_map = {1: 'OFPSF_REQ_MORE'} q.text(util.pretty_flags(self.flags, value_name_map.values())) q.text(',') q.breakable() q.text('table_id = ') q.text(('%#x' % self.table_id)) q.breakable() q.text('}')
def _test_state_change(db, client, user, jwt, new_state, state, event_owner=True, error=True): session = get_session(db, user, event_owner=event_owner, state=state) data = json.dumps({'data': {'type': 'session', 'id': str(session.id), 'attributes': {'state': new_state}}}) response = client.patch(f'/v1/sessions/{session.id}', content_type='application/vnd.api+json', headers=jwt, data=data) db.session.refresh(session) if error: assert (response.status_code == 403) assert (json.loads(response.data) == {'errors': [{'detail': f'You cannot change a session state from "{state}" to "{new_state}"', 'source': {'pointer': '/data/attributes/state'}, 'status': 403, 'title': 'Access Forbidden'}], 'jsonapi': {'version': '1.0'}}) assert (session.state == state) else: assert (response.status_code == 200) assert (session.state == new_state)
def perimeter_point_from_centroid(polygon: Polygon, angle: float, output_obj: Optional[dict]=None) -> Point: if (output_obj is None): output_obj = {} max_distance = Point(polygon.bounds[0], polygon.bounds[1]).distance(Point(polygon.bounds[2], polygon.bounds[3])) endpoint = [(polygon.centroid.x + (max_distance * np.sin(angle))), (polygon.centroid.y + (max_distance * np.cos(angle)))] line = LineString((polygon.centroid, endpoint)) perimeter_point = line.intersection(polygon.exterior) output_obj['intersecting_line'] = line return perimeter_point
class BmmRRRFunction(): def __init__(self, inputs_pool): self._it_pool = 0 self._as = [t['batch_a'] for t in inputs_pool] self._bs = [t['batch_b'] for t in inputs_pool] self._inputs_pool_size = len(inputs_pool) self._module = BmmRRRModule() def next_input(self): self._it_pool += 1 self._it_pool %= self._inputs_pool_size return (self._as[self._it_pool], self._bs[self._it_pool]) def __call__(self): return self._module(*self.next_input())
class Agent(AgentT, Service): supervisor: SupervisorStrategyT = cast(SupervisorStrategyT, None) _channel: Optional[ChannelT] = None _channel_arg: Optional[Union[(str, ChannelT)]] _channel_kwargs: Dict[(str, Any)] _channel_iterator: Optional[AsyncIterator] = None _sinks: List[SinkT] _actors: MutableSet[ActorRefT] _actor_by_partition: MutableMapping[(TP, ActorRefT)] _pending_active_partitions: Optional[Set[TP]] = None _first_assignment_done: bool = False def __init__(self, fun: AgentFun, *, app: AppT, name: Optional[str]=None, channel: Union[(str, ChannelT)]=None, concurrency: int=1, sink: Iterable[SinkT]=None, on_error: AgentErrorHandler=None, supervisor_strategy: Type[SupervisorStrategyT]=None, help: Optional[str]=None, schema: Optional[SchemaT]=None, key_type: ModelArg=None, value_type: ModelArg=None, isolated_partitions: bool=False, use_reply_headers: Optional[bool]=None, **kwargs: Any) -> None: self.app = app self.fun: AgentFun = fun self.name = (name or canonshortname(self.fun)) if (schema is not None): assert ((channel is None) or isinstance(channel, str)) if (key_type is not None): assert ((channel is None) or isinstance(channel, str)) self._key_type = key_type if (value_type is not None): assert ((channel is None) or isinstance(channel, str)) self._schema = schema self._value_type = value_type self._channel_arg = channel self._channel_kwargs = kwargs self.concurrency = (concurrency or 1) self.isolated_partitions = isolated_partitions self.help = (help or '') self._sinks = (list(sink) if (sink is not None) else []) self._on_error: Optional[AgentErrorHandler] = on_error self.supervisor_strategy = supervisor_strategy self._actors = WeakSet() self._actor_by_partition = WeakValueDictionary() if (self.isolated_partitions and (self.concurrency > 1)): raise ImproperlyConfigured('Agent concurrency must be 1 when using isolated partitions') self.use_reply_headers = use_reply_headers Service.__init__(self, loop=app.loop) def on_init_dependencies(self) -> Iterable[ServiceT]: self.beacon.reattach(self.app.agents.beacon) return [] def actor_tracebacks(self) -> List[str]: return [actor.traceback() for actor in self._actors] async def _start_one(self, *, index: Optional[int]=None, active_partitions: Optional[Set[TP]]=None, stream: Optional[StreamT]=None, channel: Optional[ChannelT]=None) -> ActorT: index = (index if (self.concurrency > 1) else None) return (await self._start_task(index=index, active_partitions=active_partitions, stream=stream, channel=channel, beacon=self.beacon)) async def _start_one_supervised(self, index: Optional[int]=None, active_partitions: Optional[Set[TP]]=None, stream: Optional[StreamT]=None) -> ActorT: aref = (await self._start_one(index=index, active_partitions=active_partitions, stream=stream)) self.supervisor.add(aref) (await aref.maybe_start()) return aref async def _start_for_partitions(self, active_partitions: Set[TP]) -> ActorT: assert active_partitions self.log.info('Starting actor for partitions %s', active_partitions) return (await self._start_one_supervised(None, active_partitions)) async def on_start(self) -> None: self.supervisor = self._new_supervisor() (await self._on_start_supervisor()) def _new_supervisor(self) -> SupervisorStrategyT: return self._get_supervisor_strategy()(max_restarts=100.0, over=1.0, replacement=self._replace_actor, loop=self.loop, beacon=self.beacon) async def _replace_actor(self, service: ServiceT, index: int) -> ServiceT: aref = cast(ActorRefT, service) return (await self._start_one(index=index, active_partitions=aref.active_partitions, stream=aref.stream, channel=cast(ChannelT, aref.stream.channel))) def _get_supervisor_strategy(self) -> Type[SupervisorStrategyT]: SupervisorStrategy = self.supervisor_strategy if (SupervisorStrategy is None): return cast(Type[SupervisorStrategyT], self.app.conf.agent_supervisor) else: return SupervisorStrategy async def _on_start_supervisor(self) -> None: active_partitions = self._get_active_partitions() channel: ChannelT = cast(ChannelT, None) for i in range(self.concurrency): res = (await self._start_one(index=i, active_partitions=active_partitions, channel=channel)) if (channel is None): channel = res.stream.channel self.supervisor.add(res) (await self.supervisor.start()) def _get_active_partitions(self) -> Optional[Set[TP]]: active_partitions: Optional[Set[TP]] = None if self.isolated_partitions: active_partitions = self._pending_active_partitions = set() return active_partitions async def on_stop(self) -> None: (await self._stop_supervisor()) with suppress(asyncio.CancelledError): (await asyncio.gather(*[aref.actor_task for aref in self._actors if (aref.actor_task is not None)])) self._actors.clear() async def _stop_supervisor(self) -> None: if self.supervisor: (await self.supervisor.stop()) self.supervisor = cast(SupervisorStrategyT, None) def cancel(self) -> None: for aref in self._actors: aref.cancel() async def on_partitions_revoked(self, revoked: Set[TP]) -> None: T = traced_from_parent_span() if self.isolated_partitions: (await T(self.on_isolated_partitions_revoked)(revoked)) else: (await T(self.on_shared_partitions_revoked)(revoked)) async def on_partitions_assigned(self, assigned: Set[TP]) -> None: T = traced_from_parent_span() if self.isolated_partitions: (await T(self.on_isolated_partitions_assigned)(assigned)) else: (await T(self.on_shared_partitions_assigned)(assigned)) async def on_isolated_partitions_revoked(self, revoked: Set[TP]) -> None: self.log.dev('Partitions revoked') T = traced_from_parent_span() for tp in revoked: aref: Optional[ActorRefT] = self._actor_by_partition.pop(tp, None) if (aref is not None): (await T(aref.on_isolated_partition_revoked)(tp)) async def on_isolated_partitions_assigned(self, assigned: Set[TP]) -> None: T = traced_from_parent_span() for tp in sorted(assigned): (await T(self._assign_isolated_partition)(tp)) async def _assign_isolated_partition(self, tp: TP) -> None: T = traced_from_parent_span() if ((not self._first_assignment_done) and (not self._actor_by_partition)): self._first_assignment_done = True T(self._on_first_isolated_partition_assigned)(tp) (await T(self._maybe_start_isolated)(tp)) def _on_first_isolated_partition_assigned(self, tp: TP) -> None: assert self._actors assert (len(self._actors) == 1) self._actor_by_partition[tp] = next(iter(self._actors)) if (self._pending_active_partitions is not None): assert (not self._pending_active_partitions) self._pending_active_partitions.add(tp) async def _maybe_start_isolated(self, tp: TP) -> None: try: aref = self._actor_by_partition[tp] except KeyError: aref = (await self._start_isolated(tp)) self._actor_by_partition[tp] = aref (await aref.on_isolated_partition_assigned(tp)) async def _start_isolated(self, tp: TP) -> ActorT: return (await self._start_for_partitions({tp})) async def on_shared_partitions_revoked(self, revoked: Set[TP]) -> None: ... async def on_shared_partitions_assigned(self, assigned: Set[TP]) -> None: ... def info(self) -> Mapping: return {'app': self.app, 'fun': self.fun, 'name': self.name, 'channel': self.channel, 'concurrency': self.concurrency, 'help': self.help, 'sink': self._sinks, 'on_error': self._on_error, 'supervisor_strategy': self.supervisor_strategy, 'isolated_partitions': self.isolated_partitions} def clone(self, *, cls: Type[AgentT]=None, **kwargs: Any) -> AgentT: return (cls or type(self))(**{**self.info(), **kwargs}) def test_context(self, channel: Optional[ChannelT]=None, supervisor_strategy: SupervisorStrategyT=None, on_error: AgentErrorHandler=None, **kwargs: Any) -> AgentTestWrapperT: self.app.flow_control.resume() async def on_agent_error(agent: AgentT, exc: BaseException) -> None: if (on_error is not None): (await on_error(agent, exc)) (await cast(AgentTestWrapper, agent).crash_test_agent(exc)) return cast(AgentTestWrapperT, self.clone(cls=AgentTestWrapper, channel=(channel if (channel is not None) else self.app.channel()), supervisor_strategy=(supervisor_strategy or CrashingSupervisor), original_channel=self.channel, on_error=on_agent_error, **kwargs)) def _prepare_channel(self, channel: Union[(str, ChannelT)]=None, internal: bool=True, schema: Optional[SchemaT]=None, key_type: ModelArg=None, value_type: ModelArg=None, **kwargs: Any) -> ChannelT: app = self.app has_prefix = False if (channel is None): channel = f'{app.conf.id}-{self.name}' has_prefix = True if isinstance(channel, ChannelT): return channel elif isinstance(channel, str): return app.topic(channel, internal=internal, schema=schema, key_type=key_type, value_type=value_type, has_prefix=has_prefix, **kwargs) raise TypeError(f'Channel must be channel, topic, or str, not {type(channel)}') def __call__(self, *, index: Optional[int]=None, active_partitions: Optional[Set[TP]]=None, stream: Optional[StreamT]=None, channel: Optional[ChannelT]=None) -> ActorRefT: return self.actor_from_stream(stream, index=index, active_partitions=active_partitions, channel=channel) def actor_from_stream(self, stream: Optional[StreamT], *, index: Optional[int]=None, active_partitions: Optional[Set[TP]]=None, channel: Optional[ChannelT]=None) -> ActorRefT: we_created_stream = False actual_stream: StreamT if (stream is None): actual_stream = self.stream(channel=channel, concurrency_index=index, active_partitions=active_partitions) we_created_stream = True else: assert (stream.concurrency_index == index) assert (stream.active_partitions == active_partitions) actual_stream = stream res = self.fun(actual_stream) if isinstance(res, AsyncIterable): if we_created_stream: actual_stream.add_processor(self._maybe_unwrap_reply_request) return cast(ActorRefT, AsyncIterableActor(self, actual_stream, res, index=actual_stream.concurrency_index, active_partitions=actual_stream.active_partitions, loop=self.loop, beacon=self.beacon)) else: return cast(ActorRefT, AwaitableActor(self, actual_stream, res, index=actual_stream.concurrency_index, active_partitions=actual_stream.active_partitions, loop=self.loop, beacon=self.beacon)) def add_sink(self, sink: SinkT) -> None: if (sink not in self._sinks): self._sinks.append(sink) def stream(self, channel: Optional[ChannelT]=None, active_partitions: Optional[Set[TP]]=None, **kwargs: Any) -> StreamT: if (channel is None): channel = cast(TopicT, self.channel_iterator).clone(is_iterator=False, active_partitions=active_partitions) if (active_partitions is not None): assert (channel.active_partitions == active_partitions) s = self.app.stream(channel, loop=self.loop, active_partitions=active_partitions, prefix=self.name, beacon=self.beacon, **kwargs) return s def _maybe_unwrap_reply_request(self, value: V) -> Any: if isinstance(value, ReqRepRequest): return value.value return value async def _start_task(self, *, index: Optional[int], active_partitions: Optional[Set[TP]]=None, stream: Optional[StreamT]=None, channel: Optional[ChannelT]=None, beacon: Optional[NodeT]=None) -> ActorRefT: actor = self(index=index, active_partitions=active_partitions, stream=stream, channel=channel) return (await self._prepare_actor(actor, (beacon if (beacon is not None) else self.beacon))) async def _prepare_actor(self, aref: ActorRefT, beacon: NodeT) -> ActorRefT: coro: Any if isinstance(aref, Awaitable): coro = aref if self._sinks: raise ImproperlyConfigured('Agent must yield to use sinks') else: coro = self._slurp(aref, aiter(aref)) task = asyncio.Task(self._execute_actor(coro, aref), loop=self.loop) task._beacon = beacon aref.actor_task = task self._actors.add(aref) return aref async def _execute_actor(self, coro: Awaitable, aref: ActorRefT) -> None: _current_agent.set(self) try: (await coro) except asyncio.CancelledError as exc: if self.should_stop: raise else: self.log.info('Restarting on rebalance') (await aref.crash(exc)) self.supervisor.wakeup() except Exception as exc: if (self._on_error is not None): (await self._on_error(self, exc)) (await aref.crash(exc)) self.supervisor.wakeup() async def _slurp(self, res: ActorRefT, it: AsyncIterator) -> None: stream: Optional[StreamT] = None async for value in it: self.log.debug('%r yielded: %r', self.fun, value) if (stream is None): stream = res.stream.get_active_stream() event = stream.current_event if (event is not None): headers = event.headers reply_to: Optional[str] = None correlation_id: Optional[str] = None if isinstance(event.value, ReqRepRequest): req: ReqRepRequest = event.value reply_to = req.reply_to correlation_id = req.correlation_id elif headers: reply_to_bytes = headers.get('Faust-Ag-ReplyTo') if reply_to_bytes: reply_to = want_str(reply_to_bytes) correlation_id_bytes = headers.get('Faust-Ag-CorrelationId') if correlation_id_bytes: correlation_id = want_str(correlation_id_bytes) if (reply_to is not None): (await self._reply(event.key, value, reply_to, cast(str, correlation_id))) (await self._delegate_to_sinks(value)) async def _delegate_to_sinks(self, value: Any) -> None: for sink in self._sinks: if isinstance(sink, AgentT): (await sink.send(value=value)) elif isinstance(sink, ChannelT): (await cast(TopicT, sink).send(value=value)) else: (await maybe_async(cast(Callable, sink)(value))) async def _reply(self, key: Any, value: Any, reply_to: str, correlation_id: str) -> None: assert reply_to response = self._response_class(value)(key=key, value=value, correlation_id=correlation_id) (await self.app.send(reply_to, key=None, value=response)) def _response_class(self, value: Any) -> Type[ReqRepResponse]: if isinstance(value, ModelT): return ModelReqRepResponse return ReqRepResponse async def cast(self, value: V=None, *, key: K=None, partition: Optional[int]=None, timestamp: Optional[float]=None, headers: HeadersArg=None) -> None: (await self.send(key=key, value=value, partition=partition, timestamp=timestamp, headers=headers)) async def ask(self, value: V=None, *, key: K=None, partition: Optional[int]=None, timestamp: Optional[float]=None, headers: HeadersArg=None, reply_to: ReplyToArg=None, correlation_id: Optional[str]=None) -> Any: p = (await self.ask_nowait(value, key=key, partition=partition, timestamp=timestamp, headers=headers, reply_to=(reply_to or self.app.conf.reply_to), correlation_id=correlation_id, force=True)) app = cast(_App, self.app) (await app._reply_consumer.add(p.correlation_id, p)) (await app.maybe_start_client()) return (await p) async def ask_nowait(self, value: V=None, *, key: K=None, partition: Optional[int]=None, timestamp: Optional[float]=None, headers: HeadersArg=None, reply_to: ReplyToArg=None, correlation_id: Optional[str]=None, force: bool=False) -> ReplyPromise: if (reply_to is None): raise TypeError('Missing reply_to argument') reply_to = self._get_strtopic(reply_to) correlation_id = (correlation_id or str(uuid4())) (value, headers) = self._create_req(key, value, reply_to, correlation_id, headers) (await self.channel.send(key=key, value=value, partition=partition, timestamp=timestamp, headers=headers, force=force)) return ReplyPromise(reply_to, correlation_id) def _create_req(self, key: K=None, value: V=None, reply_to: ReplyToArg=None, correlation_id: Optional[str]=None, headers: HeadersArg=None) -> Tuple[(V, Optional[HeadersArg])]: if (reply_to is None): raise TypeError('Missing reply_to argument') topic_name = self._get_strtopic(reply_to) correlation_id = (correlation_id or str(uuid4())) open_headers = prepare_headers((headers or {})) if self.use_reply_headers: merge_headers(open_headers, {'Faust-Ag-ReplyTo': want_bytes(topic_name), 'Faust-Ag-CorrelationId': want_bytes(correlation_id)}) return (value, open_headers) else: req = self._request_class(value)(value=value, reply_to=topic_name, correlation_id=correlation_id) return (req, open_headers) def _request_class(self, value: V) -> Type[ReqRepRequest]: if isinstance(value, ModelT): return ModelReqRepRequest return ReqRepRequest async def send(self, *, key: K=None, value: V=None, partition: Optional[int]=None, timestamp: Optional[float]=None, headers: HeadersArg=None, key_serializer: CodecArg=None, value_serializer: CodecArg=None, callback: Optional[MessageSentCallback]=None, reply_to: ReplyToArg=None, correlation_id: Optional[str]=None, force: bool=False) -> Awaitable[RecordMetadata]: if reply_to: (value, headers) = self._create_req(key, value, reply_to, correlation_id, headers) return (await self.channel.send(key=key, value=value, partition=partition, timestamp=timestamp, headers=headers, key_serializer=key_serializer, value_serializer=value_serializer, force=force)) def _get_strtopic(self, topic: Union[(str, ChannelT, TopicT, AgentT)]) -> str: if isinstance(topic, AgentT): return self._get_strtopic(topic.channel) if isinstance(topic, TopicT): return topic.get_topic_name() if isinstance(topic, ChannelT): raise ValueError('Channels are unnamed topics') return topic async def map(self, values: Union[(AsyncIterable, Iterable)], key: K=None, reply_to: ReplyToArg=None) -> AsyncIterator: async for value in self.kvmap(((key, v) async for v in aiter(values)), reply_to): (yield value) async def kvmap(self, items: Union[(AsyncIterable[Tuple[(K, V)]], Iterable[Tuple[(K, V)]])], reply_to: ReplyToArg=None) -> AsyncIterator[str]: reply_to = self._get_strtopic((reply_to or self.app.conf.reply_to)) barrier = BarrierState(reply_to) async for _ in self._barrier_send(barrier, items, reply_to): try: (_, val) = barrier.get_nowait() except asyncio.QueueEmpty: pass else: (yield val) barrier.finalize() async for (_, value) in barrier.iterate(): (yield value) async def join(self, values: Union[(AsyncIterable[V], Iterable[V])], key: K=None, reply_to: ReplyToArg=None) -> List[Any]: return (await self.kvjoin(((key, value) async for value in aiter(values)), reply_to=reply_to)) async def kvjoin(self, items: Union[(AsyncIterable[Tuple[(K, V)]], Iterable[Tuple[(K, V)]])], reply_to: ReplyToArg=None) -> List[Any]: reply_to = self._get_strtopic((reply_to or self.app.conf.reply_to)) barrier = BarrierState(reply_to) posindex: MutableMapping[(str, int)] = {cid: i async for (i, cid) in aenumerate(self._barrier_send(barrier, items, reply_to))} barrier.finalize() (await barrier) values: List = ([None] * barrier.total) async for (correlation_id, value) in barrier.iterate(): values[posindex[correlation_id]] = value return values async def _barrier_send(self, barrier: BarrierState, items: Union[(AsyncIterable[Tuple[(K, V)]], Iterable[Tuple[(K, V)]])], reply_to: ReplyToArg) -> AsyncIterator[str]: key: K value: V async for (key, value) in aiter(items): correlation_id = str(uuid4()) p = (await self.ask_nowait(key=key, value=value, reply_to=reply_to, correlation_id=correlation_id)) barrier.add(p) app = cast(_App, self.app) (await app.maybe_start_client()) (await app._reply_consumer.add(p.correlation_id, barrier)) (yield correlation_id) def _repr_info(self) -> str: return shorten_fqdn(self.name) def get_topic_names(self) -> Iterable[str]: channel = self.channel if isinstance(channel, TopicT): return channel.topics return [] def channel(self) -> ChannelT: if (self._channel is None): self._channel = self._prepare_channel(self._channel_arg, schema=self._schema, key_type=self._key_type, value_type=self._value_type, **self._channel_kwargs) return self._channel def channel(self, channel: ChannelT) -> None: self._channel = channel def channel_iterator(self) -> AsyncIterator: if (self._channel_iterator is None): self._channel_iterator = self.channel.clone(is_iterator=False) return self._channel_iterator _iterator.setter def channel_iterator(self, it: AsyncIterator) -> None: self._channel_iterator = it def label(self) -> str: return self._agent_label() def _agent_label(self, name_suffix: str='') -> str: s = f'{type(self).__name__}{name_suffix}: ' s += f'{shorten_fqdn(qualname(self.fun))}' return s def shortlabel(self) -> str: return self._agent_label()
class ShellTask(PythonInstanceTask[T]): def __init__(self, name: str, debug: bool=False, script: typing.Optional[str]=None, script_file: typing.Optional[str]=None, task_config: T=None, inputs: typing.Optional[typing.Dict[(str, typing.Type)]]=None, output_locs: typing.Optional[typing.List[OutputLocation]]=None, **kwargs): if (script and script_file): raise ValueError('Only either of script or script_file can be provided') if ((not script) and (not script_file)): raise ValueError('Either a script or script_file is needed') if script_file: if (not os.path.exists(script_file)): raise ValueError(f'FileNotFound: the specified Script file at path {script_file} cannot be loaded') script_file = os.path.abspath(script_file) if (task_config is not None): fully_qualified_class_name = ((task_config.__module__ + '.') + task_config.__class__.__name__) if (not (fully_qualified_class_name == 'flytekitplugins.pod.task.Pod')): raise ValueError('TaskConfig can either be empty - indicating simple container task or a PodConfig.') plugin_class = TaskPlugins.find_pythontask_plugin(type(task_config)) self._config_task_instance = plugin_class(task_config=task_config, task_function=_dummy_task_func) self._config_task_instance._name = f'_bash.{name}' self._script = script self._script_file = script_file self._debug = debug self._output_locs = (output_locs if output_locs else []) self._interpolizer = _PythonFStringInterpolizer() outputs = self._validate_output_locs() super().__init__(name, task_config, task_type=self._config_task_instance.task_type, interface=Interface(inputs=inputs, outputs=outputs), **kwargs) def _validate_output_locs(self) -> typing.Dict[(str, typing.Type)]: outputs = {} for v in self._output_locs: if (v is None): raise ValueError('OutputLocation cannot be none') if (not isinstance(v, OutputLocation)): raise ValueError('Every output type should be an output location on the file-system') if (v.location is None): raise ValueError(f'Output Location not provided for output var {v.var}') if ((not issubclass(v.var_type, FlyteFile)) and (not issubclass(v.var_type, FlyteDirectory))): raise ValueError('Currently only outputs of type FlyteFile/FlyteDirectory and their derived types are supported') outputs[v.var] = v.var_type return outputs def script(self) -> typing.Optional[str]: return self._script def script_file(self) -> typing.Optional[os.PathLike]: return self._script_file def pre_execute(self, user_params: ExecutionParameters) -> ExecutionParameters: return self._config_task_instance.pre_execute(user_params) def execute(self, **kwargs) -> typing.Any: logger.info(f'Running shell script as type {self.task_type}') if self.script_file: with open(self.script_file) as f: self._script = f.read() outputs: typing.Dict[(str, str)] = {} if self._output_locs: for v in self._output_locs: outputs[v.var] = self._interpolizer.interpolate(v.location, inputs=kwargs) if (os.name == 'nt'): self._script = self._script.lstrip().rstrip().replace('\n', '&&') gen_script = self._interpolizer.interpolate(self._script, inputs=kwargs, outputs=outputs) if self._debug: print('\n\n') print(gen_script) print('\n\n') if ((platform.system() == 'Windows') and (os.environ.get('ComSpec') is None)): os.environ['ComSpec'] = 'C:\\Windows\\System32\\cmd.exe' (returncode, stdout, stderr) = _run_script(gen_script) if (returncode != 0): files = os.listdir('.') fstr = '\n-'.join(files) error = f'''Failed to Execute Script, return-code {returncode} Current directory contents: . -{fstr} StdOut: {stdout} StdErr: {stderr} ''' logger.error(error) raise FlyteRecoverableException(error) final_outputs = [] for v in self._output_locs: if issubclass(v.var_type, FlyteFile): final_outputs.append(FlyteFile(outputs[v.var])) if issubclass(v.var_type, FlyteDirectory): final_outputs.append(FlyteDirectory(outputs[v.var])) if (len(final_outputs) == 1): return final_outputs[0] if (len(final_outputs) > 1): return tuple(final_outputs) return None def post_execute(self, user_params: ExecutionParameters, rval: typing.Any) -> typing.Any: return self._config_task_instance.post_execute(user_params, rval)
def extractOddnendsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
def test_is_batchable(): assert (ListTransformer.is_batchable(typing.List[int]) is False) assert (ListTransformer.is_batchable(typing.List[str]) is False) assert (ListTransformer.is_batchable(typing.List[typing.Dict]) is False) assert (ListTransformer.is_batchable(typing.List[typing.Dict[(str, FlytePickle)]]) is False) assert (ListTransformer.is_batchable(typing.List[typing.List[FlytePickle]]) is False) assert (ListTransformer.is_batchable(typing.List[FlytePickle]) is True) assert (ListTransformer.is_batchable(Annotated[(typing.List[FlytePickle], BatchSize(3))]) is True) assert (ListTransformer.is_batchable(Annotated[(typing.List[FlytePickle], HashMethod(function=str), BatchSize(3))]) is True)
def import_datetime(module_type): global datetime_module, mxDateTime_module module_type = (module_type.lower() if module_type else 'datetime') if (module_type == 'datetime'): if (datetime_module is None): import datetime as datetime_module return datetime_module elif (module_type == 'mxdatetime'): if (mxDateTime_module is None): from mx import DateTime as mxDateTime_module return mxDateTime_module else: raise ImportError(('Invalid datetime module %r' % module_type))
class Table(): cushion_segments: CushionSegments pockets: Dict[(str, Pocket)] table_type: TableType model_descr: Optional[TableModelDescr] = field(default=None) height: float = field(default=0.708) lights_height: float = field(default=1.99) def w(self) -> float: x2 = self.cushion_segments.linear['12'].p1[0] x1 = self.cushion_segments.linear['3'].p1[0] return (x2 - x1) def l(self) -> float: y2 = self.cushion_segments.linear['9'].p1[1] y1 = self.cushion_segments.linear['18'].p1[1] return (y2 - y1) def center(self) -> Tuple[(float, float)]: return ((self.w / 2), (self.l / 2)) def copy(self) -> Table: return evolve(self, cushion_segments=self.cushion_segments.copy(), pockets={k: v.copy() for (k, v) in self.pockets.items()}) def from_table_specs(specs: TableSpecs) -> Table: return Table(cushion_segments=specs.create_cushion_segments(), pockets=specs.create_pockets(), table_type=specs.table_type, model_descr=specs.model_descr, height=specs.height, lights_height=specs.lights_height) def prebuilt(cls, name: TableName) -> Table: return cls.from_table_specs(prebuilt_specs(name)) def default(cls, table_type: TableType=TableType.POCKET) -> Table: return cls.from_table_specs(get_default_specs(table_type)) def from_game_type(cls, game_type: GameType) -> Table: _game_table_type_map: Dict[(GameType, TableType)] = {GameType.EIGHTBALL: TableType.POCKET, GameType.NINEBALL: TableType.POCKET, GameType.THREECUSHION: TableType.BILLIARD, GameType.SNOOKER: TableType.SNOOKER, GameType.SANDBOX: TableType.POCKET} return cls.default(_game_table_type_map[game_type])
class Country(): short_name: str alpha2_code: str alpha3_code: str locale: str currency: str region: str country_id: str def __init__(self, shortName, alpha2_code, alpha3_code, locale, currency, region, country_id): self.short_name = shortName self.alpha2_code = alpha2_code self.alpha3_code = alpha3_code self.locale = locale self.region = region self.currency = currency self.country_id = country_id
('/api/ip/<endpoint_id>') def ips(endpoint_id): post_to_back_if_telemetry_enabled(**{'name': f'ip/{endpoint_id}'}) with session_scope() as session: ips_hits = get_ips(session, endpoint_id) dicts = [] for ih in ips_hits: dicts.append({'ip': ih[0], 'hits': ih[1]}) return jsonify(dicts)
class RecommendationAttribute(StrEnum): acousticness = 'acousticness' danceability = 'danceability' duration_ms = 'duration_ms' energy = 'energy' instrumentalness = 'instrumentalness' key = 'key' liveness = 'liveness' loudness = 'loudness' mode = 'mode' popularity = 'popularity' speechiness = 'speechiness' tempo = 'tempo' time_signature = 'time_signature' valence = 'valence'
def get_stack_schemas(stack_version: Optional[str]='0.0.0') -> OrderedDictType[(str, dict)]: stack_version = Version.parse((stack_version or '0.0.0'), optional_minor_and_patch=True) current_package = Version.parse(load_current_package_version(), optional_minor_and_patch=True) stack_map = load_stack_schema_map() versions = {k: v for (k, v) in stack_map.items() if (((mapped_version := Version.parse(k)) >= stack_version) and (mapped_version <= current_package) and v)} if (stack_version > current_package): versions[stack_version] = {'beats': 'main', 'ecs': 'master'} versions_reversed = OrderedDict(sorted(versions.items(), reverse=True)) return versions_reversed
def test_run_pos_args(): source = 'lmql\n "Summarize this text: {t1}{t2}: [SUMMARY]" where len(TOKENS(SUMMARY)) < 4\n return SUMMARY\n ' r1 = lmql.run_sync(source, 'This is ', 'a test.', model=lmql.model('random', seed=123)) r2 = lmql.run_sync(source, t1='This is ', t2='a test.', model=lmql.model('random', seed=123)) assert (r1 == r2), 'using positional and keyword args should result in the same output'
def make_function(name, nargs, function_deps, method_deps): def function_X(self, node): if node.kwarg_nodes: raise JSError(('Function %s does not support keyword args.' % name)) if (len(node.arg_nodes) not in nargs): raise JSError(('Function %s needs #args in %r.' % (name, nargs))) for dep in function_deps: self.use_std_function(dep, []) for dep in method_deps: self.use_std_method('x', dep, []) return self.use_std_function(name, node.arg_nodes) return function_X
.parametrize(['obj', 'expected_requirements'], [(_a, [_a]), ((_r := RegisterPair(_a, _b)), [_r, _a, _b]), (Assignment(_a, _b), [_b]), (Assignment(ListOperation([_a]), _b), [_b]), (Assignment(UnaryOperation(OperationType.cast, [_a], contraction=True), _b), [_b]), (Assignment(UnaryOperation(OperationType.dereference, [_a]), _b), [_a, _b]), (IndirectBranch(_a), [_a]), (Return([_a, _b]), [_a, _b]), (ListOperation([_a, _b]), [_a, _b]), (BinaryOperation(OperationType.plus, [_a, _b]), [_a, _b]), (Call(_a, [_b]), [_a, _b]), (BinaryOperation(OperationType.plus, [_a, _a]), [_a, _a])]) def test_requirements(obj: DataflowObject, expected_requirements: list[Variable]): assert (list(obj.requirements_iter) == expected_requirements)
class YamlRepository(DiskRepository): file_ending = 'yaml' open_mode_for_loading = 'r' open_mode_for_saving = 'w' def load(self, fp): data = yaml.safe_load(fp) if (not data): raise ClusterError('Empty cluster state file: {0}'.format(fp.name)) cluster = Cluster(**data) cluster.repository = self return cluster def dump(cluster, fp): state = cluster.to_dict(omit=('_cloud_provider', '_naming_policy', '_setup_provider', 'repository', 'storage_file')) state = json.loads(json.dumps(state, default=dict)) yaml.safe_dump(state, fp, default_flow_style=False, indent=4)
class MyApp(Mayavi): def run(self): from mayavi.sources.vtk_file_reader import VTKFileReader from mayavi.modules.outline import Outline from mayavi.modules.axes import Axes from mayavi.modules.grid_plane import GridPlane from mayavi.modules.image_plane_widget import ImagePlaneWidget from mayavi.modules.text import Text script = self.script script.new_scene() r = VTKFileReader() r.initialize(join(get_data_dir(dirname(abspath(__file__))), 'heart.vtk')) script.add_source(r) t = Text(text='MayaVi rules!', x_position=0.2, y_position=0.9, width=0.8) t.property.color = (1, 1, 0) script.add_module(t) o = Outline() script.add_module(o) a = Axes() script.add_module(a) try: from mayavi.modules.orientation_axes import OrientationAxes except ImportError: pass else: a = OrientationAxes() a.marker.set_viewport(0.0, 0.8, 0.2, 1.0) script.add_module(a) gp = GridPlane() script.add_module(gp) gp = GridPlane() gp.grid_plane.axis = 'y' script.add_module(gp) gp = GridPlane() script.add_module(gp) gp.grid_plane.axis = 'z' ipw = ImagePlaneWidget() script.add_module(ipw) ipw.ipw.slice_position = 16
class MockFullTextModels(FullTextModels): def __init__(self): model_impl_mock = MagicMock('model_impl') self.cv_model_mock = MagicMock(name='cv_model') super().__init__(segmentation_model=SegmentationModel(model_impl_mock), header_model=HeaderModel(model_impl_mock), name_header_model=NameModel(model_impl_mock), name_citation_model=NameModel(model_impl_mock), affiliation_address_model=AffiliationAddressModel(model_impl_mock), fulltext_model=FullTextModel(model_impl_mock), figure_model=FigureModel(model_impl_mock), table_model=TableModel(model_impl_mock), reference_segmenter_model=ReferenceSegmenterModel(model_impl_mock), citation_model=CitationModel(model_impl_mock), cv_model=self.cv_model_mock) self.segmentation_model_mock = MockDelftModelWrapper(self.segmentation_model) self.header_model_mock = MockDelftModelWrapper(self.header_model) self.name_header_model_mock = MockDelftModelWrapper(self.name_header_model) self.name_citation_model_mock = MockDelftModelWrapper(self.name_citation_model) self.affiliation_address_model_mock = MockDelftModelWrapper(self.affiliation_address_model) self.fulltext_model_mock = MockDelftModelWrapper(self.fulltext_model) self.figure_model_mock = MockDelftModelWrapper(self.figure_model) self.table_model_mock = MockDelftModelWrapper(self.table_model) self.reference_segmenter_model_mock = MockDelftModelWrapper(self.reference_segmenter_model) self.citation_model_mock = MockDelftModelWrapper(self.citation_model)
def DoFuseLoop(f_cursor, s_cursor, unsafe_disable_check=False): proc = f_cursor.get_root() if (f_cursor.next() != s_cursor): raise SchedulingError(f'''expected the two loops to be fused to come one right after the other. However, the statement after the first loop is: {f_cursor.next()._node} , not the provided second loop: {s_cursor._node}''') loop1 = f_cursor._node loop2 = s_cursor._node Check_ExprEqvInContext(proc, loop1.hi, [loop1], loop2.hi, [loop2]) def mk_read(e): return LoopIR.Read(loop1.iter, [], T.index, loop1.srcinfo) (ir, fwd) = (proc, (lambda x: x)) (ir, fwd) = _replace_reads(ir, fwd, s_cursor, loop2.iter, mk_read, only_replace_attrs=False) (ir, fwd_move) = fwd(s_cursor).body()._move(fwd(f_cursor).body()[(- 1)].after()) fwd = _compose(fwd_move, fwd) (ir, fwdDel) = fwd(s_cursor)._delete() fwd = _compose(fwdDel, fwd) if (not unsafe_disable_check): x = LoopIR.Read(loop1.iter, [], T.index, loop1.srcinfo) y = loop2.iter body1 = loop1.body body2 = SubstArgs(loop2.body, {y: x}).result() loop = fwd(f_cursor)._node Check_FissionLoop(ir, loop, body1, body2) return (ir, fwd)
class ObjectGroup(MibNode): status = 'current' objects = () description = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: self.objects = args return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def asn1Print(self): return ('OBJECT-GROUP\n OBJECTS { %s }\n DESCRIPTION "%s"\n' % (', '.join([x for x in self.getObjects()]), self.getDescription()))
_static def get_conda_executable() -> Path: for path in [_FAL_CONDA_HOME, None]: conda_path = shutil.which(_CONDA_COMMAND, path=path) if (conda_path is not None): return conda_path else: raise RuntimeError('Could not find conda executable. Please install conda or set FAL_CONDA_HOME.')
.parametrize('rpc_method', ['eth_getBlockByNumber']) def test_stalecheck_ignores_get_by_block_methods(request_middleware, rpc_method): with patch('web3.middleware.stalecheck._is_fresh', side_effect=[False, True]): request_middleware(rpc_method, []) assert (not request_middleware.web3.eth.get_block.called)
def test_pagination_with_three_items_three_per_page(): from feeder.util.feeder import paginate_response items = ['item1', 'item2', 'item3'] page = paginate_response(items, max_page_size=3) assert (page['size'] == 3) assert (page['data'] == items) assert (page['page'] == 1) assert (page['totalSize'] == 3) assert (page['totalPages'] == 1)
def dict_strip(file_1, file_2): with open(file_1, 'r', encoding='utf-8') as fd: list_A = [line.strip().upper() for line in fd if ((line[0] != '#') and (len(line) > 4))] set_A = set(list_A) with open(file_2, 'r', encoding='utf-8') as fd: for line in fd: if _debug: print(f'>>> {line}', end='', file=sys.stderr) if (line[0] == '#'): if (not line.startswith('# Generated ')): print(line, end='') continue dat = line[:12].upper() if _debug: print('line len =', len(line), file=sys.stderr) print('DAT len =', len(dat), file=sys.stderr) if (dat in set_A): if (del_dups is None): print(f'#- {line}', end='') else: print(dat) print(gen_str) print(f'# Generated {time.ctime()}')
class OptionPlotoptionsTreegraphSonificationDefaultinstrumentoptionsActivewhen(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: float): self._config(num, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def prop(self): return self._config_get(None) def prop(self, text: str): self._config(text, js_type=False)
class SMTPAction(ActionBase): def __init__(self, jail, name, host='localhost', ssl=False, user=None, password=None, sendername='Fail2Ban', sender='fail2ban', dest='root', matches=None): super(SMTPAction, self).__init__(jail, name) self.host = host self.ssl = ssl self.user = user self.password = password self.fromname = sendername self.fromaddr = sender self.toaddr = dest self.matches = matches self.message_values = CallingMap(jailname=self._jail.name, hostname=socket.gethostname, bantime=(lambda : self._jail.actions.getBanTime())) self.norestored = 1 def _sendMessage(self, subject, text): msg = MIMEText(text) msg['Subject'] = subject msg['From'] = formataddr((self.fromname, self.fromaddr)) msg['To'] = self.toaddr msg['Date'] = formatdate() (smtp_host, smtp_port) = self.host.split(':') smtp = smtplib.SMTP(host=smtp_host, port=smtp_port) try: r = smtp.connect(host=smtp_host, port=smtp_port) self._logSys.debug("Connected to SMTP '%s', response: %i: %s", self.host, *r) if self.ssl: r = smtp.starttls()[0] if (r != 220): raise Exception(("Failed to starttls() on '%s': %s" % (self.host, r))) if (self.user and self.password): smtp.login(self.user, self.password) failed_recipients = smtp.sendmail(self.fromaddr, self.toaddr.split(', '), msg.as_string()) except smtplib.SMTPConnectError: self._logSys.error("Error connecting to host '%s'", self.host) raise except smtplib.SMTPAuthenticationError: self._logSys.error("Failed to authenticate with host '%s' user '%s'", self.host, self.user) raise except smtplib.SMTPException: self._logSys.error("Error sending mail to host '%s' from '%s' to '%s'", self.host, self.fromaddr, self.toaddr) raise else: if failed_recipients: self._logSys.warning("Email to '%s' failed to following recipients: %r", self.toaddr, failed_recipients) self._logSys.debug("Email '%s' successfully sent", subject) finally: try: self._logSys.debug("Disconnected from '%s', response %i: %s", self.host, *smtp.quit()) except smtplib.SMTPServerDisconnected: pass def start(self): self._sendMessage(('[Fail2Ban] %(jailname)s: started on %(hostname)s' % self.message_values), (messages['start'] % self.message_values)) def stop(self): self._sendMessage(('[Fail2Ban] %(jailname)s: stopped on %(hostname)s' % self.message_values), (messages['stop'] % self.message_values)) def ban(self, aInfo): if aInfo.get('restored'): return aInfo.update(self.message_values) message = ''.join([messages['ban']['head'], messages['ban'].get(self.matches, ''), messages['ban']['tail']]) self._sendMessage(('[Fail2Ban] %(jailname)s: banned %(ip)s from %(hostname)s' % aInfo), (message % aInfo))
class GraphQLView(BaseGraphQLView): def format_error(error): formatted = BaseGraphQLView.format_error(error) if (isinstance(error, GraphQLError) and (error.original_error is not None)): error = error.original_error if (not extensions_settings.SHOW_ERROR_MESSAGE_HANDLER(error)): formatted['message'] = _('Internal server error') extensions = {'type': error.__class__.__name__, 'code': getattr(error, 'code', 'error'), 'timestamp': timegm(datetime.utcnow().utctimetuple()), **formatted.get('extensions', {})} if hasattr(error, 'error_data'): extensions['data'] = error.error_data if (error.__traceback__ is not None): info = error.__traceback__.tb_frame.f_locals.get('info') if (info is not None): extensions['operation'] = info.operation.operation.name if settings.DEBUG: extensions['trace'] = traceback.format_list(traceback.extract_tb(error.__traceback__)) formatted['extensions'] = extensions return formatted
class AbstractFieldProjectionMonitor(SurfaceIntegrationMonitor, FreqMonitor): custom_origin: Coordinate = pydantic.Field(None, title='Local Origin', description="Local origin used for defining observation points. If ``None``, uses the monitor's center.", units=MICROMETER) far_field_approx: bool = pydantic.Field(True, title='Far Field Approximation', description='Whether to enable the far field approximation when projecting fields. If ``True``, terms that decay as O(1/r^2) are ignored, as are the radial components of fields. Typically, this should be set to ``True`` only when the projection distance is much larger than the size of the device being modeled, and the projected points are in the far field of the device.') interval_space: Tuple[(pydantic.PositiveInt, pydantic.PositiveInt, pydantic.PositiveInt)] = pydantic.Field((1, 1, 1), title='Spatial Interval', description='Number of grid step intervals at which near fields are recorded for projection to the far field, along each direction. If equal to 1, there will be no downsampling. If greater than 1, the step will be applied, but the first and last point of the monitor grid are always included. Using values greater than 1 can help speed up server-side far field projections with minimal accuracy loss, especially in cases where it is necessary for the grid resolution to be high for the FDTD simulation, but such a high resolution is unnecessary for the purpose of projecting the recorded near fields to the far field.') window_size: Tuple[(pydantic.NonNegativeFloat, pydantic.NonNegativeFloat)] = pydantic.Field((0, 0), title='Spatial filtering window size', description='Size of the transition region of the windowing function used to ensure that the recorded near fields decay to zero near the edges of the monitor. The two components refer to the two tangential directions associated with each surface. For surfaces with the normal along ``x``, the two components are (``y``, ``z``). For surfaces with the normal along ``y``, the two components are (``x``, ``z``). For surfaces with the normal along ``z``, the two components are (``x``, ``y``). Each value must be between 0 and 1, inclusive, and denotes the size of the transition region over which fields are scaled to less than a thousandth of the original amplitude, relative to half the size of the monitor in that direction. A value of 0 turns windowing off in that direction, while a value of 1 indicates that the window will be applied to the entire monitor in that direction. This field is applicable for surface monitors only, and otherwise must remain (0, 0).') medium: MediumType = pydantic.Field(None, title='Projection medium', description='Medium through which to project fields. Generally, the fields should be projected through the same medium as the one in which this monitor is placed, and this is the default behavior when ``medium=None``. A custom ``medium`` can be useful in some situations for advanced users, but we recommend trying to avoid using a non-default ``medium``.') ('window_size', always=True) def window_size_for_surface(cls, val, values): size = values.get('size') name = values.get('name') if (size.count(0.0) != 1): if (val != (0, 0)): raise ValidationError(f"A non-zero 'window_size' cannot be used for projection monitor '{name}'. Windowing can be applied only for surface projection monitors.") return val ('window_size', always=True) def window_size_leq_one(cls, val, values): name = values.get('name') if ((val[0] > 1) or (val[1] > 1)): raise ValidationError(f"Each component of 'window_size' for monitor '{name}' must be less than or equal to 1.") return val def projection_surfaces(self) -> Tuple[(FieldProjectionSurface, ...)]: surfaces = self.integration_surfaces return [FieldProjectionSurface(monitor=FieldMonitor(center=surface.center, size=surface.size, freqs=self.freqs, name=surface.name, colocate=True), normal_dir=surface.normal_dir) for surface in surfaces] def local_origin(self) -> Coordinate: if (self.custom_origin is None): return self.center return self.custom_origin def window_parameters(self, custom_bounds: Bound=None) -> Tuple[(Size, Coordinate, Coordinate)]: window_size = [0, 0, 0] window_minus = [0, 0, 0] window_plus = [0, 0, 0] if (self.size.count(0.0) != 1): return (window_size, window_minus, window_plus) (_, plane_inds) = self.pop_axis([0, 1, 2], axis=self.size.index(0.0)) for (i, ind) in enumerate(plane_inds): if custom_bounds: size = min(self.size[ind], (custom_bounds[1][ind] - custom_bounds[0][ind])) bound_min = max(self.bounds[0][ind], custom_bounds[0][ind]) bound_max = min(self.bounds[1][ind], custom_bounds[1][ind]) else: size = self.size[ind] bound_min = self.bounds[0][ind] bound_max = self.bounds[1][ind] window_size[ind] = ((self.window_size[i] * size) / 2) window_minus[ind] = (bound_min + window_size[ind]) window_plus[ind] = (bound_max - window_size[ind]) return (window_size, window_minus, window_plus) def window_function(points: ArrayFloat1D, window_size: Size, window_minus: Coordinate, window_plus: Coordinate, dim: int) -> ArrayFloat1D: rising_window = np.exp((((- 0.5) * WINDOW_FACTOR) * (((points[(points < window_minus[dim])] - window_minus[dim]) / window_size[dim]) ** 2))) falling_window = np.exp((((- 0.5) * WINDOW_FACTOR) * (((points[(points > window_plus[dim])] - window_plus[dim]) / window_size[dim]) ** 2))) window_fn = np.ones_like(points) window_fn[(points < window_minus[dim])] = rising_window window_fn[(points > window_plus[dim])] = falling_window return window_fn
def test_catch_invalid_reference_error() -> None: t = generate_graph_resources(3) field(t, 'dr_1', 'ds_1', 'f1').references.append((FieldAddress('I_dont_exist', 'x', 'y'), None)) field(t, 'dr_1', 'ds_1', 'f1').identity = 'email' with pytest.raises(ValidationError): generate_traversal({'email': 'a'}, *t)
class CredStore(): path: Path = field(default=DEFAULT_CRED_STORE_FILE) store: dict[(str, Cred)] = field(default_factory=dict) def __post_init__(self): if (not isinstance(self.path, Path)): self.path = Path(self.path) def has_sessions(self) -> bool: for (key, cred) in self.store.items(): if cred.session: return True return False def from_file(cls, file: Path=DEFAULT_CRED_STORE_FILE) -> Optional['CredStore']: if file.exists(): logging.info(f'Loaded cred store dump from: {file}') return pickle.loads(file.read_bytes()) def save(self): logging.info(f'Saved cred store to {self.path}') self.path.write_bytes(pickle.dumps(self)) def add(self, key: str, creds: Optional[CRED_TYPES]=None, session: Optional[Credentials]=None, override: bool=False, type: Optional[Literal[('oauth', 'service')]]=None): if ((key in self.store) and (not override)): raise ValueError(f'Value exists for: {key}') cred = Cred(creds=creds, session=session) self.store[key] = cred logging.info(f'Added {type} cred with key: {key}') def remove(self, key: str) -> bool: return (self.store.pop(key, None) is not None) def get(self, key: str, validate_type: Optional[Literal[('oauth', 'service')]]=None, missing_error: bool=True) -> Optional[Cred]: if (key not in self.store): raise ValueError(f'Value not found for: {key} in the cred store') value = self.store.get(key) creds = value.creds if (validate_type and creds): if ((validate_type == 'oauth') and (not isinstance(creds, OAuthCreds))): raise ValueError(f'Value for {key} is not OAuthCreds') elif ((validate_type == 'service') and (not isinstance(creds, ServiceAccountCreds))): raise ValueError(f'Value for {key} is not ServiceAccountCreds') elif (validate_type not in ('oauth', 'service')): raise ValueError(f'Invalid validate_type: {validate_type}, expected "oauth" or "service"') if ((not creds) and missing_error): raise ValueError(f'Value not found for: {key} in the cred store') return value def get_by_client_id(self, client_id: str, validate_type: Optional[Literal[('oauth', 'service')]]=None, missing_error: bool=True) -> Optional[CRED_TYPES]: for (key, value) in self.store.items(): if (value.client_id == client_id): return self.get(key, validate_type, missing_error) def list_credentials(self) -> list[str]: return [f"{k}{(f':{v.creds}' if v.creds else '')}" for (k, v) in self.store.items()] def list_sessions(self) -> list[str]: sessions = [] for (k, v) in self.store.items(): if v.session: if ('service' in v.session.__module__): sessions.append(f'{k}:{v.session.__module__}:{v.session.service_account_email}') else: sessions.append(f'{k}:{v.session.__module__}:{v.session.client_id}') return sessions
class KubernetesNamespaceIterator(ResourceIterator): def iter(self): gcp = self.client try: for (data, metadata) in gcp.iter_kubernetes_namespaces(project_id=self.resource.parent()['projectId'], zone=self.resource['zone'], cluster=self.resource['name']): (yield FACTORIES['kubernetes_namespace'].create_new(data, metadata=metadata)) except ResourceNotSupported as e: LOGGER.debug(e)
class Benchmark(base_benchmark.BaseBenchmark): def __init__(self, job_control: proto_control.JobControl, benchmark_name: str) -> None: self._benchmark_dir = None super(Benchmark, self).__init__(job_control, benchmark_name) def _validate(self) -> None: verify_source = False images = self.get_images() verify_source = ((images is None) or (not images.nighthawk_benchmark_image) or (not images.nighthawk_binary_image) or (not images.envoy_image)) log.debug(f'Source verification needed: {verify_source}') if verify_source: self._verify_sources(images) def _prepare_nighthawk(self) -> None: manager = source_manager.SourceManager(self._control) self._nighthawk_builder = nighthawk_builder.NightHawkBuilder(manager) self._nighthawk_builder.build_nighthawk_benchmarks() nighthawk_source = manager.get_source_tree(proto_source.SourceRepository.SourceIdentity.SRCID_NIGHTHAWK) self._benchmark_dir = nighthawk_source.get_source_directory() log.debug(f'NightHawk benchmark dir {self._benchmark_dir}') def execute_benchmark(self) -> None: self._validate() self._prepare_nighthawk() env = self._control.environment output_dir = env.output_dir images = self.get_images() log.debug(f'Images: {images.nighthawk_benchmark_image}') image_vars = {'NH_DOCKER_IMAGE': images.nighthawk_binary_image, 'ENVOY_DOCKER_IMAGE_TO_TEST': images.envoy_image, 'TMPDIR': output_dir} log.debug(f'Using environment: {image_vars}') for (key, value) in image_vars.items(): if (key not in env.variables): log.debug(f'Building control environment variables: {key}={value}') env.variables[key] = value environment_controller = base_benchmark.BenchmarkEnvController(env) cmd = 'bazel-bin/benchmarks/benchmarks --log-cli-level=info -vvvv -k test_ benchmarks/' cmd_params = cmd_exec.CommandParameters(cwd=self._benchmark_dir) with environment_controller: try: cmd_exec.run_command(cmd, cmd_params) except subprocess.CalledProcessError as cpe: raise base_benchmark.BenchmarkError(f'Unable to execute the benchmark: {cpe}')
def build_riesz_map(V, d): beta = Constant(0.0001) subs = [(1, 3)] if V.mesh().cell_set._extruded: subs += ['top'] x = SpatialCoordinate(V.mesh()) x -= Constant(([0.5] * len(x))) if (V.ufl_element().value_shape == ()): u_exact = exp(((- 10) * dot(x, x))) u_bc = u_exact else: A = (Constant(([([(- 1.0)] * len(x))] * len(x))) + diag(Constant(([len(x)] * len(x))))) u_exact = (dot(A, x) * exp(((- 10) * dot(x, x)))) u_bc = Function(V) u_bc.project(u_exact, solver_parameters={'mat_type': 'matfree', 'pc_type': 'jacobi'}) bcs = [DirichletBC(V, u_bc, sub) for sub in subs] uh = Function(V) test = TestFunction(V) trial = TrialFunction(V) a = (lambda v, u: ((inner(v, (beta * u)) * dx) + (inner(d(v), d(u)) * dx))) return LinearVariationalProblem(a(test, trial), a(test, u_exact), uh, bcs=bcs)
class RegularNode(Node[Metadata]): def __init__(self, label: str, args: Sequence[Node[Metadata]], kwargs: Mapping[(str, Node[Metadata])], metadata: Metadata, subgraph: Optional[Subgraph]=None) -> None: self._label = label self._args = tuple(args) self._kwargs = dict(kwargs) super().__init__(metadata, subgraph) def __bool__(self) -> bool: return True def _generate_asciitree_nodes(self, cache: MutableMapping[(Node[Metadata], str)], id_gen_map: Mapping[(Optional[Subgraph], str)], select: str, bridge: str) -> Generator[(str, None, None)]: if (self in cache): (yield '{}{}\n'.format(select, cache[self])) else: cache[self] = id = next(id_gen_map[self.subgraph]) (yield '{}{} = {}\n'.format(select, id, self._label.replace('\n', '; '))) args = (tuple((('', arg) for arg in self._args if arg)) + tuple((('{} = '.format(name), arg) for (name, arg) in self._kwargs.items()))) for (i, (prefix, arg)) in enumerate(args, (1 - len(args))): (yield from arg._generate_asciitree_nodes(cache, id_gen_map, ((bridge + (' ' if i else ' ')) + prefix), (bridge + (' ' if i else ' ')))) def _collect_graphviz_nodes_edges(self, cache: MutableMapping[(Node[Metadata], str)], id_gen: Iterator[str], nodes: MutableMapping[(Optional[Subgraph], List[str])], edges: List[str], parent_subgraph: Optional[Subgraph], fill_color: Optional[GraphvizColorCallback]=None) -> Optional[str]: if (self in cache): return cache[self] cache[self] = id = next(id_gen) if self._kwargs: table = ['<TABLE BORDER="1" CELLBORDER="0" CELLSPACING="0">'] table += ['<TR>', *('<TD PORT="kwarg{}"><FONT POINT-SIZE="10">{}</FONT></TD>'.format(ikwarg, html.escape(name)) for (ikwarg, name) in enumerate(self._kwargs)), '</TR>'] table += ['<TR><TD COLSPAN="{}">{}</TD></TR>'.format(len(self._kwargs), html.escape(line)) for line in self._label.split('\n')] table += ['</TABLE>'] attributes = ['shape=plain', 'label=<{}>'.format(''.join(table))] else: attributes = ['shape=box', 'label="{}"'.format(self._label.replace('"', '\\"'))] attributes.extend(_graphviz_fill_color_attributes(self, fill_color)) nodes.setdefault(self.subgraph, []).append('{} [{}];'.format(id, ','.join(attributes))) for arg in self._args: arg_id = arg._collect_graphviz_nodes_edges(cache, id_gen, nodes, edges, self.subgraph, fill_color) if arg_id: edges.append('{} -> {};'.format(arg_id, id)) for (ikwarg, arg) in enumerate(self._kwargs.values()): arg_id = arg._collect_graphviz_nodes_edges(cache, id_gen, nodes, edges, self.subgraph, fill_color) if arg_id: edges.append('{} -> {}:kwarg{}:n;'.format(arg_id, id, ikwarg)) return id def walk(self, seen: MutableSet[Node[Metadata]]) -> Iterator[Node[Metadata]]: if (self in seen): return seen.add(self) (yield self) for arg in self._args: (yield from arg.walk(seen)) for arg in self._kwargs.values(): (yield from arg.walk(seen))
class DeltaRLastRounds(): def __new__(cls, guesses=_np.arange(256, dtype='uint8'), words=None, ciphertext_tag='ciphertext', key_tag='key'): return _decorated_selection_function(_AttackSelectionFunctionWrapped, _delta_last_rounds, expected_key_function=_last_key, words=words, guesses=guesses, target_tag=ciphertext_tag, key_tag=key_tag)
def test_dao_get_list_page(dao): for i in range(20): dao.create(ServeRequest(chat_scene='chat_data', sub_chat_scene='excel', prompt_type='common', prompt_name=f'my_prompt_{i}', content='Write a qsort function in python.', user_name=('zhangsan' if ((i % 2) == 0) else 'lisi'), sys_code='dbgpt')) res = dao.get_list_page({'sys_code': 'dbgpt'}, page=1, page_size=8) assert (res.total_count == 20) assert (res.total_pages == 3) assert (res.page == 1) assert (res.page_size == 8) assert (len(res.items) == 8) for (i, r) in enumerate(res.items): assert (r.id == (i + 1)) assert (r.chat_scene == 'chat_data') assert (r.sub_chat_scene == 'excel') assert (r.prompt_type == 'common') assert (r.prompt_name == f'my_prompt_{i}') assert (r.content == 'Write a qsort function in python.') assert ((r.user_name == 'zhangsan') if ((i % 2) == 0) else 'lisi') assert (r.sys_code == 'dbgpt') res_half = dao.get_list_page({'user_name': 'zhangsan'}, page=2, page_size=8) assert (res_half.total_count == 10) assert (res_half.total_pages == 2) assert (res_half.page == 2) assert (res_half.page_size == 8) assert (len(res_half.items) == 2) for (i, r) in enumerate(res_half.items): assert (r.chat_scene == 'chat_data') assert (r.sub_chat_scene == 'excel') assert (r.prompt_type == 'common') assert (r.content == 'Write a qsort function in python.') assert (r.user_name == 'zhangsan') assert (r.sys_code == 'dbgpt')
def evaluate_uni_pos(uni_pos_dict: Dict[(str, List[Tuple[(str, float)]])], data: List[List[Tuple[(str, str)]]]): (total, correct) = (0, 0) for sentence in data: (tokens, gold) = tuple(zip(*sentence)) pred = [t[0] for t in predict_uni_pos_dict(uni_pos_dict, tokens)] total += len(tokens) correct += len([1 for (g, p) in zip(gold, pred) if (g == p)]) print('{:5.2f}% ({}/{})'.format(((100.0 * correct) / total), correct, total))
class SentRouteDetailView(OperatorDetailView): timestamp = fields.DataField('timestamp') filtered = fields.DataField('filtered') path = fields.RelatedViewField('path', 'ryu.services.protocols.bgp.operator.views.bgp.PathDetailView') peer = fields.RelatedViewField('sent_peer', 'ryu.services.protocols.bgp.operator.views.bgp.PeerDetailView') def encode(self): ret = super(SentRouteDetailView, self).encode() ret.update({'path': self.rel('path').encode()}) return ret
class OptionPlotoptionsSunburstSonificationTracksMappingGapbetweennotes(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class ExaQueryError(ExaRequestError): def __init__(self, connection, query, code, message): self.query = query super().__init__(connection, code, message) def get_params_for_print(self): params = super().get_params_for_print() params['session_id'] = self.connection.session_id() if (len(self.query) > constant.EXCEPTION_QUERY_TEXT_MAX_LENGTH): params['query'] = f'''{self.query[:constant.EXCEPTION_QUERY_TEXT_MAX_LENGTH]} ------ TRUNCATED TOO LONG QUERY ------ ''' else: params['query'] = self.query return params
def retry(logger=None): def wrapper(fp): async def retry_loop(*args, **kwargs): last_failed_time = (- 1) while True: try: (await fp(*args, **kwargs)) logger.debug(' decorated function %s exited, ending retry loop', fp.__name__) break except Exception as ex: now = calendar.timegm(time.gmtime()) if ((last_failed_time == (- 1)) or ((now - last_failed_time) > RESET_DELAY_AFTER_SECONDS)): delay_seconds = INITIAL_DELAY_SECONDS else: delay_seconds = (delay_seconds * BACK_OFF_MULTIPLIER) if (delay_seconds > MAX_DELAY_SECONDS): delay_seconds = MAX_DELAY_SECONDS last_failed_time = now logger.error('%s failed: %s, retrying in %d seconds', fp.__name__, ex, delay_seconds, exc_info=True) (await asyncio.sleep(delay_seconds)) return retry_loop return wrapper
def cleanup_snapshots(): for k in snapshot_list: si = snapshot_list[k] keep_last = keep_last_default if (k in servers_keep_last): keep_last = servers_keep_last[k] if (len(si) > keep_last): si.sort(reverse=True) si = si[keep_last:] for s in si: delete_snapshots(snapshot_id=s, server_id=k)
def test_restructure_cfg_dowhile(task): task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[Assignment(variable(name='i', version=0), Constant(0)), Assignment(variable(name='x', version=0), Constant(42))]), BasicBlock(1, instructions=[Phi(variable(name='i', version=1), [variable(name='i', version=0), variable(name='i', version=2)]), Phi(variable(name='x', version=1), [variable(name='x', version=0), variable(name='x', version=2)]), Assignment(variable(name='i', version=2), BinaryOperation(OperationType.plus, [variable(name='i', version=1), Constant(1)])), Assignment(variable(name='x', version=2), BinaryOperation(OperationType.minus, [variable(name='x', version=1), variable(name='i', version=2)]))]), BasicBlock(2, instructions=[Branch(Condition(OperationType.equal, [variable(name='i', version=2), Constant(3)]))]), BasicBlock(3, instructions=[Return([variable(name='x', version=2)])])])) task.graph.add_edges_from([UnconditionalEdge(vertices[0], vertices[1]), UnconditionalEdge(vertices[1], vertices[2]), TrueCase(vertices[2], vertices[1]), FalseCase(vertices[2], vertices[3])]) PatternIndependentRestructuring().run(task) context = LogicCondition.generate_new_context() resulting_ast = AbstractSyntaxTree((seq_node := SeqNode(LogicCondition.initialize_true(context))), {LogicCondition.initialize_symbol('x1', context): Condition(OperationType.equal, [variable(name='i', version=2), Constant(3)])}) code_node = resulting_ast._add_code_node([Assignment(variable('i', 0), Constant(0)), Assignment(variable('x', 0), Constant(42))]) resulting_ast._add_node((while_loop := resulting_ast.factory.create_do_while_loop_node(LogicCondition.initialize_symbol('x1', context)))) loop_body = resulting_ast._add_code_node([Phi(variable('i', 1), [variable('i', 0), variable('i', 2)]), Phi(variable('x', 1), [variable('x', 0), variable('x', 2)]), Assignment(variable('i', 2), BinaryOperation(OperationType.plus, [variable('i', 1), Constant(1)])), Assignment(variable('x', 2), BinaryOperation(OperationType.minus, [variable('x', 1), variable('i', 2)]))]) return_node = resulting_ast._add_code_node([Return([variable('x', 2)])]) resulting_ast._add_edges_from(((seq_node, code_node), (seq_node, while_loop), (while_loop, loop_body), (seq_node, return_node))) resulting_ast._code_node_reachability_graph.add_reachability_from(((code_node, loop_body), (code_node, return_node), (loop_body, return_node))) seq_node.sort_children() assert (ASTComparator.compare(task.syntax_tree, resulting_ast) and (task.syntax_tree.condition_map == resulting_ast.condition_map))
def agency_test_data(db): baker.make('search.AwardSearch', award_id=1, latest_transaction_id=1) baker.make('search.AwardSearch', award_id=2, latest_transaction_id=2) baker.make('search.SubawardSearch', broker_subaward_id=1, latest_transaction_id=1, subaward_amount=50, awarding_agency_id=1003, funding_agency_id=1004, awarding_toptier_agency_name='Awarding Toptier Agency 3', awarding_subtier_agency_name='Awarding Subtier Agency 3', funding_toptier_agency_name='Funding Toptier Agency 4', funding_subtier_agency_name='Funding Subtier Agency 4', awarding_toptier_agency_abbreviation='TA3', awarding_subtier_agency_abbreviation='SA3', funding_toptier_agency_abbreviation='TA4', funding_subtier_agency_abbreviation='SA4') baker.make('search.SubawardSearch', broker_subaward_id=2, latest_transaction_id=2, subaward_amount=100, awarding_agency_id=1003, funding_agency_id=1004, awarding_toptier_agency_name='Awarding Toptier Agency 3', awarding_subtier_agency_name='Awarding Subtier Agency 3', funding_toptier_agency_name='Funding Toptier Agency 4', funding_subtier_agency_name='Funding Subtier Agency 4', awarding_toptier_agency_abbreviation='TA3', awarding_subtier_agency_abbreviation='SA3', funding_toptier_agency_abbreviation='TA4', funding_subtier_agency_abbreviation='SA4') baker.make('search.TransactionSearch', transaction_id=1, award_id=1, awarding_agency_id=1001, awarding_toptier_agency_id=1001, funding_agency_id=1002, funding_toptier_agency_id=1002, federal_action_obligation=5, generated_pragmatic_obligation=5, action_date='2020-01-01', fiscal_action_date='2020-04-01', is_fpds=False, awarding_agency_code='TA1', funding_agency_code='TA2', awarding_sub_tier_agency_c='SA1', funding_sub_tier_agency_co='SA2') baker.make('search.TransactionSearch', transaction_id=2, award_id=2, awarding_agency_id=1001, awarding_toptier_agency_id=1001, funding_agency_id=1002, funding_toptier_agency_id=1002, federal_action_obligation=10, generated_pragmatic_obligation=10, action_date='2020-01-02', fiscal_action_date='2020-04-02', is_fpds=False, awarding_agency_code='TA1', funding_agency_code='TA2', awarding_sub_tier_agency_c='SA1', funding_sub_tier_agency_co='SA2') baker.make('references.ToptierAgency', toptier_agency_id=2001, name='Awarding Toptier Agency 1', abbreviation='TA1', toptier_code='TA1') baker.make('references.SubtierAgency', subtier_agency_id=3001, name='Awarding Subtier Agency 1', abbreviation='SA1', subtier_code='SA1') baker.make('references.ToptierAgency', toptier_agency_id=2003, name='Awarding Toptier Agency 3', abbreviation='TA3', toptier_code='TA3') baker.make('references.SubtierAgency', subtier_agency_id=3003, name='Awarding Subtier Agency 3', abbreviation='SA3', subtier_code='SA3') baker.make('references.ToptierAgency', toptier_agency_id=2002, name='Funding Toptier Agency 2', abbreviation='TA2', toptier_code='TA2') baker.make('references.SubtierAgency', subtier_agency_id=3002, name='Funding Subtier Agency 2', abbreviation='SA2', subtier_code='SA2') baker.make('references.ToptierAgency', toptier_agency_id=2004, name='Funding Toptier Agency 4', abbreviation='TA4', toptier_code='TA4') baker.make('references.SubtierAgency', subtier_agency_id=3004, name='Funding Subtier Agency 4', abbreviation='SA4', subtier_code='SA4') baker.make('references.Agency', id=1001, toptier_agency_id=2001, subtier_agency_id=3001, toptier_flag=True, _fill_optional=True) baker.make('references.Agency', id=1002, toptier_agency_id=2002, subtier_agency_id=3002, toptier_flag=True, _fill_optional=True) baker.make('references.Agency', id=1003, toptier_agency_id=2003, subtier_agency_id=3003, toptier_flag=True, _fill_optional=True) baker.make('references.Agency', id=1004, toptier_agency_id=2004, subtier_agency_id=3004, toptier_flag=True, _fill_optional=True)
class OptionPlotoptionsFunnelSonificationDefaultinstrumentoptionsMappingTime(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
def _user_changed(task_id, user_name, dc_name, affected_groups): try: user = User.objects.get(username=user_name) except User.DoesNotExist: if dc_name: _remove_user_from_monitoring_server(dc_name, user_name) elif affected_groups: _remove_user_from_group_related_monitoring_servers(task_id, user_name, affected_groups) else: _remove_user_from_all_monitoring_servers(task_id, user_name) else: if dc_name: _synchronize_user_on_monitoring_server(dc_name, user) elif affected_groups: _synchronize_user_on_group_related_monitoring_servers(task_id, user, affected_groups) else: _synchronize_user_on_all_related_monitoring_servers(task_id, user)
class IfStatement(Statement, GotoMixin): condition: Expression true_body: Statement false_body: Optional[Statement] arguments_join = synthesized() def push_variables(self, condition) -> (VarStateMixin.variables_pre {true_body, false_body}): return condition.variables_post def variables_post(self): if self.is_reachable_next: return {**self.variables_pre, **to_map(self.arguments_join, value=2)} return {**self.variables_pre} def changed_variables(self, true_body, false_body): return (true_body.changed_variables if (false_body is None) else (true_body.changed_variables | false_body.changed_variables)) def is_reachable_next(self, true_body, false_body): return (true_body.is_reachable_next or ((false_body is None) or false_body.is_reachable_next)) def control_flow_statements(self, true_body, false_body): return (true_body.control_flow_statements if (false_body is None) else (true_body.control_flow_statements | false_body.control_flow_statements)) def arguments_join(self): return self.transfer_arguments(self.changed_variables) def cfg(self, condition, true_body, false_body): block_join = ir.Block(self, info='IF_JOIN', args=list(map(__[1], self.arguments_join))) block_true = ir.Block(true_body, info='IF_TRUE') block_false = ir.Block(false_body, info='IF_FALSE') args_true = self.get_arguments(true_body.variables_post, self.arguments_join) args_false = (self.get_arguments(false_body.variables_post, self.arguments_join) if false_body else None) args_false = (args_false or self.get_arguments(condition.variables_post, self.arguments_join)) branch = ir.Branch(self, condition.expression_value, block_true, block_false, [], []) cfg_true = (true_body.cfg << block_true) cfg_false = ((false_body.cfg if false_body else CfgSimple.empty()) << block_false) cfg_builder = ((condition.cfg >> branch) >> (cfg_true, cfg_false)) if self.is_reachable_next: cfg_builder += CfgSimple.statement(block_join) cfg_builder = self.add_goto(cfg_builder, cfg_true, block_join, args_true, only_if_appendable=True) cfg_builder = self.add_goto(cfg_builder, cfg_false, block_join, args_false, only_if_appendable=True) cfg_builder >>= CfgSimple.statements(*map(__[2], self.arguments_join)) return cfg_builder
class Test_ofctl(unittest.TestCase): def _test(self, name, dp, method, args, request, reply, expected): print(('processing %s ...' % name)) waiters = {} dp.set_reply(reply, waiters) if reply: output = method(dp=dp, waiters=waiters, **args) else: output = method(dp=dp, **args) request.serialize() try: eq_(json.dumps(request.to_jsondict(), sort_keys=True), json.dumps(dp.request_msg.to_jsondict(), sort_keys=True)) except AssertionError as e: json.dump(dp.request_msg.to_jsondict(), open((('/tmp/' + name) + '_request.json'), 'w'), indent=3, sort_keys=True) raise e def _remove(d, names): def f(x): return _remove(x, names) if isinstance(d, list): return list(map(f, d)) if isinstance(d, dict): d2 = {} for (k, v) in d.items(): if (k in names): continue d2[k] = f(v) return d2 return d expected = _remove(expected, ['len', 'length']) output = _remove(output, ['len', 'length']) try: eq_(json.dumps(expected, sort_keys=True), json.dumps(output, sort_keys=True)) except AssertionError as e: json.dump(output, open((('/tmp/' + name) + '_reply.json'), 'w'), indent=4) raise e
def extractAradescentWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
def test_restructure_cfg_loop_two_back_edges(task): task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[Assignment(variable(name='i'), Constant(0)), Assignment(variable(name='x'), Constant(42))]), BasicBlock(1, instructions=[Branch(Condition(OperationType.not_equal, [variable(name='i'), Constant(3)]))]), BasicBlock(2, instructions=[Assignment(variable(name='i'), BinaryOperation(OperationType.plus, [variable(name='i'), Constant(1)])), Assignment(variable(name='x'), BinaryOperation(OperationType.minus, [variable(name='x'), variable(name='i')]))]), BasicBlock(3, instructions=[Return([variable(name='x')])]), BasicBlock(4, instructions=[Assignment(variable(name='j'), Constant(0))]), BasicBlock(5, instructions=[Branch(Condition(OperationType.not_equal, [variable(name='j'), Constant(3)]))]), BasicBlock(6, instructions=[Assignment(variable(name='j'), BinaryOperation(OperationType.plus, [variable(name='j'), Constant(1)]))])])) task.graph.add_edges_from([UnconditionalEdge(vertices[0], vertices[1]), TrueCase(vertices[1], vertices[2]), FalseCase(vertices[1], vertices[3]), UnconditionalEdge(vertices[2], vertices[4]), UnconditionalEdge(vertices[4], vertices[5]), TrueCase(vertices[5], vertices[6]), FalseCase(vertices[5], vertices[1]), UnconditionalEdge(vertices[6], vertices[1])]) PatternIndependentRestructuring().run(task) context = LogicCondition.generate_new_context() resulting_ast = AbstractSyntaxTree((seq_node := SeqNode(LogicCondition.initialize_true(context))), {LogicCondition.initialize_symbol('x1', context): Condition(OperationType.not_equal, [variable('i'), Constant(3)]), LogicCondition.initialize_symbol('x2', context): Condition(OperationType.not_equal, [variable('j'), Constant(3)])}) code_node_0 = resulting_ast._add_code_node([Assignment(variable('i'), Constant(0)), Assignment(variable('x'), Constant(42))]) resulting_ast._add_node((while_loop := resulting_ast.factory.create_while_loop_node(LogicCondition.initialize_symbol('x1', context)))) resulting_ast._add_node((loop_body := resulting_ast.factory.create_seq_node())) code_node_2_4 = resulting_ast._add_code_node([Assignment(variable('i'), BinaryOperation(OperationType.plus, [variable('i'), Constant(1)])), Assignment(variable('x'), BinaryOperation(OperationType.minus, [variable('x'), variable('i')])), Assignment(variable('j'), Constant(0))]) code_node_6 = resulting_ast._add_code_node([Assignment(variable('j'), BinaryOperation(OperationType.plus, [variable('j'), Constant(1)]))]) true_branch = resulting_ast._add_code_node([Continue()]) nested_condition = resulting_ast._add_condition_node_with((~ LogicCondition.initialize_symbol('x2', context)), true_branch) code_node_3 = resulting_ast._add_code_node([Return([variable('x')])]) resulting_ast._add_edges_from(((seq_node, code_node_0), (seq_node, while_loop), (while_loop, loop_body), (loop_body, code_node_2_4), (loop_body, nested_condition), (loop_body, code_node_6), (seq_node, code_node_3))) resulting_ast._code_node_reachability_graph.add_reachability_from(((code_node_0, code_node_3), (code_node_0, code_node_2_4), (code_node_0, code_node_6), (true_branch, code_node_6), (code_node_2_4, code_node_6), (code_node_2_4, code_node_3), (code_node_2_4, true_branch), (code_node_6, code_node_3))) seq_node.sort_children() loop_body.sort_children() assert (ASTComparator.compare(task.syntax_tree, resulting_ast) and (task.syntax_tree.condition_map == resulting_ast.condition_map))
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingVolume(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class OptionsSparkLineBullet(OptionsSpark): def targetColor(self): return self._config_get(None) def targetColor(self, value): self._config(value) def targetWidth(self): return self._config_get(None) def targetWidth(self, value): self._config(value) def performanceColor(self): return self._config_get(None) def performanceColor(self, value): self._config(value) def rangeColors(self): return self._config_get(None) def rangeColors(self, values): self._config(values)
def normalize_obs(dataset, eps=0.001): mean = dataset['observations'].mean(axis=0) std = (dataset['observations'].std(axis=0) + eps) o_t = ((dataset['observations'] - mean) / std) o_tp1 = ((dataset['next_observations'] - mean) / std) normalized_data = {'observations': o_t, 'next_observations': o_tp1, 'rewards': dataset['rewards'], 'actions': dataset['actions'], 'terminals': dataset['terminals']} return (normalized_data, mean, std)
class BugRegressionTest(unittest.TestCase): def test_regress_1312(self) -> None: self.maxDiff = None queries = [unif()] observations = {flip(): torch.tensor(1)} observed = BMGInference().to_dot(queries, observations) expected = '\ndigraph "graph" {\n N00[label=Flat];\n N01[label=Sample];\n N02[label=ToPosReal];\n N03[label=0.1];\n N04[label="+"];\n N05[label=Beta];\n N06[label=Sample];\n N07[label=complement];\n N08[label=Bernoulli];\n N09[label=Sample];\n N10[label="Observation True"];\n N11[label=Query];\n N00 -> N01;\n N01 -> N02;\n N01 -> N11;\n N02 -> N04;\n N03 -> N04;\n N04 -> N05;\n N04 -> N05;\n N05 -> N06;\n N06 -> N07;\n N07 -> N08;\n N08 -> N09;\n N09 -> N10;\n}\n ' self.assertEqual(expected.strip(), observed.strip())
class _ActionChunker(): def __init__(self, chunk_size: int, max_chunk_bytes: int, serializer: Serializer) -> None: self.chunk_size = chunk_size self.max_chunk_bytes = max_chunk_bytes self.serializer = serializer self.size = 0 self.action_count = 0 self.bulk_actions: List[bytes] = [] self.bulk_data: List[Union[(Tuple[_TYPE_BULK_ACTION_HEADER], Tuple[(_TYPE_BULK_ACTION_HEADER, _TYPE_BULK_ACTION_BODY)])]] = [] def feed(self, action: _TYPE_BULK_ACTION_HEADER, data: _TYPE_BULK_ACTION_BODY) -> Optional[Tuple[(List[Union[(Tuple[_TYPE_BULK_ACTION_HEADER], Tuple[(_TYPE_BULK_ACTION_HEADER, _TYPE_BULK_ACTION_BODY)])]], List[bytes])]]: ret = None raw_action = action raw_data = data action_bytes = to_bytes(self.serializer.dumps(action), 'utf-8') cur_size = (len(action_bytes) + 1) data_bytes: Optional[bytes] if (data is not None): data_bytes = to_bytes(self.serializer.dumps(data), 'utf-8') cur_size += (len(data_bytes) + 1) else: data_bytes = None if (self.bulk_actions and (((self.size + cur_size) > self.max_chunk_bytes) or (self.action_count == self.chunk_size))): ret = (self.bulk_data, self.bulk_actions) self.bulk_actions = [] self.bulk_data = [] self.size = 0 self.action_count = 0 self.bulk_actions.append(action_bytes) if (data_bytes is not None): self.bulk_actions.append(data_bytes) self.bulk_data.append((raw_action, raw_data)) else: self.bulk_data.append((raw_action,)) self.size += cur_size self.action_count += 1 return ret def flush(self) -> Optional[Tuple[(List[Union[(Tuple[_TYPE_BULK_ACTION_HEADER], Tuple[(_TYPE_BULK_ACTION_HEADER, _TYPE_BULK_ACTION_BODY)])]], List[bytes])]]: ret = None if self.bulk_actions: ret = (self.bulk_data, self.bulk_actions) self.bulk_actions = [] self.bulk_data = [] return ret
.requires_roxar def test_rox_surfaces_dtype_switching(roxar_project): srf = xtgeo.surface_from_roxar(roxar_project, 'TopReek', SURFCAT1, dtype='float32') assert (srf.ncol == 554) assert (srf.values.mean() == pytest.approx(1698.648, abs=0.01)) assert (srf.dtype == np.float32) srf.to_roxar(roxar_project, 'TopReek_copy', 'SomeFolder', stype='clipboard') srf2 = srf.copy() assert (srf2.dtype == np.float32) srf2.dtype = np.float64 np.testing.assert_allclose(srf.values, srf2.values)
class BsStyles(): def __init__(self, page): self.page = page def remove(self, style: str): self.replate(style, None) return self def replace(self, style: str, new_style: str): for v in self.page.components.values(): if (style in v.attr['class']): if (new_style is None): v.attr['class'].discard(style) else: index = v.attr['class'].index(style) v.attr['class'][index] = new_style return self def apply_calc(self, component: primitives.HtmlModel, style_map: dict): for (s, t) in style_map.items(): if (s in component.attr['class']): if (t is None): component.attr['class'].discard(s) else: index = component.attr['class'].index(s) component.attr['class'][index] = t return self
class ReferenceSegmenterDataGenerator(ContextAwareLayoutTokenModelDataGenerator): def iter_model_data_for_context_layout_token_features(self, token_features: ContextAwareLayoutTokenFeatures) -> Iterable[LayoutModelData]: (yield token_features.get_layout_model_data([token_features.token_text, token_features.get_lower_token_text(), token_features.get_prefix(1), token_features.get_prefix(2), token_features.get_prefix(3), token_features.get_prefix(4), token_features.get_suffix(1), token_features.get_suffix(2), token_features.get_suffix(3), token_features.get_suffix(4), token_features.get_line_status_with_lineend_for_single_token(), token_features.get_alignment_status(), token_features.get_capitalisation_status_using_allcap(), token_features.get_digit_status_using_containsdigits(), token_features.get_str_is_single_char(), token_features.get_dummy_str_is_proper_name(), token_features.get_dummy_str_is_common_name(), token_features.get_str_is_first_name(), token_features.get_dummy_str_is_location_name(), token_features.get_dummy_str_is_year(), token_features.get_dummy_str_is_month(), token_features.get_dummy_str_is_ token_features.get_line_punctuation_profile(), token_features.get_str_line_token_relative_position(), token_features.get_str_line_relative_length(), token_features.get_block_status_with_blockend_for_single_token(), token_features.get_truncated_line_punctuation_profile_length_feature(), token_features.get_dummy_label()]))
def extractKarmatranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Across a Millennium to Love You', 'Across a Millennium to Love You', 'translated')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) titlemap = [('Across a Millennium to Love You Chapter', 'Across a Millennium to Love You', 'translated')] for (titlecomponent, name, tl_type) in titlemap: if (titlecomponent.lower() in item['title'].lower()): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class TestIsProgramInfo(unittest.TestCase): def test_is_program_info(self): self.assertTrue(is_program_info('solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26', 'solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26.solid_qc.programs')) self.assertTrue(is_program_info('solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26', 'solid0127__FRAG_BC_Run_56_pool_LC_CK_F3_CKSEQ26.solid_qc.programs')) def test_is_program_info_with_dots(self): self.assertTrue(is_program_info('ED1.1', 'ED1.1.illumina_qc.programs'))
def _show(package_name: str, version: Optional[str]=None) -> None: logger.info(f'Show package [{package_name}], version {version} information on storage ') if version: package_info = onedocker_repo_svc.package_repo.get_package_info(package_name, version) print(f' Package [{package_info.package_name}], version {package_info.version}: Last modified: {package_info.last_modified}; Size: {package_info.package_size} bytes') else: package_versions = onedocker_repo_svc.package_repo.get_package_versions(package_name) print(f' All available versions for package {package_name} : {package_versions}') for version in package_versions: package_info = onedocker_repo_svc.package_repo.get_package_info(package_name, version) print(f'Package [{package_info.package_name}], version {package_info.version}: Last modified: {package_info.last_modified}; Size: {package_info.package_size} bytes')
class AdAccount(AdAccountMixin, AbstractCrudObject, HasAdLabels): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAccount = True super(AdAccount, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): account_id = 'account_id' account_status = 'account_status' ad_account_promotable_objects = 'ad_account_promotable_objects' age = 'age' agency_client_declaration = 'agency_client_declaration' all_capabilities = 'all_capabilities' amount_spent = 'amount_spent' attribution_spec = 'attribution_spec' balance = 'balance' business = 'business' business_city = 'business_city' business_country_code = 'business_country_code' business_name = 'business_name' business_state = 'business_state' business_street = 'business_street' business_street2 = 'business_street2' business_zip = 'business_zip' can_create_brand_lift_study = 'can_create_brand_lift_study' capabilities = 'capabilities' created_time = 'created_time' currency = 'currency' custom_audience_info = 'custom_audience_info' default_dsa_beneficiary = 'default_dsa_beneficiary' default_dsa_payor = 'default_dsa_payor' disable_reason = 'disable_reason' end_advertiser = 'end_advertiser' end_advertiser_name = 'end_advertiser_name' existing_customers = 'existing_customers' extended_credit_invoice_group = 'extended_credit_invoice_group' failed_delivery_checks = 'failed_delivery_checks' fb_entity = 'fb_entity' funding_source = 'funding_source' funding_source_details = 'funding_source_details' has_migrated_permissions = 'has_migrated_permissions' has_page_authorized_adaccount = 'has_page_authorized_adaccount' id = 'id' io_number = 'io_number' is_attribution_spec_system_default = 'is_attribution_spec_system_default' is_direct_deals_enabled = 'is_direct_deals_enabled' is_in_3ds_authorization_enabled_market = 'is_in_3ds_authorization_enabled_market' is_notifications_enabled = 'is_notifications_enabled' is_personal = 'is_personal' is_prepay_account = 'is_prepay_account' is_tax_id_required = 'is_tax_id_required' liable_address = 'liable_address' line_numbers = 'line_numbers' media_agency = 'media_agency' min_campaign_group_spend_cap = 'min_campaign_group_spend_cap' min_daily_budget = 'min_daily_budget' name = 'name' offsite_pixels_tos_accepted = 'offsite_pixels_tos_accepted' owner = 'owner' owner_business = 'owner_business' partner = 'partner' rf_spec = 'rf_spec' send_bill_to_address = 'send_bill_to_address' show_checkout_experience = 'show_checkout_experience' sold_to_address = 'sold_to_address' spend_cap = 'spend_cap' tax_id = 'tax_id' tax_id_status = 'tax_id_status' tax_id_type = 'tax_id_type' timezone_id = 'timezone_id' timezone_name = 'timezone_name' timezone_offset_hours_utc = 'timezone_offset_hours_utc' tos_accepted = 'tos_accepted' user_access_expire_time = 'user_access_expire_time' user_tasks = 'user_tasks' user_tos_accepted = 'user_tos_accepted' viewable_business = 'viewable_business' class Currency(): aed = 'AED' ars = 'ARS' aud = 'AUD' bdt = 'BDT' bob = 'BOB' brl = 'BRL' cad = 'CAD' chf = 'CHF' clp = 'CLP' cny = 'CNY' cop = 'COP' crc = 'CRC' czk = 'CZK' dkk = 'DKK' dzd = 'DZD' egp = 'EGP' eur = 'EUR' gbp = 'GBP' gtq = 'GTQ' hkd = 'HKD' hnl = 'HNL' huf = 'HUF' idr = 'IDR' ils = 'ILS' inr = 'INR' isk = 'ISK' jpy = 'JPY' kes = 'KES' krw = 'KRW' lkr = 'LKR' mop = 'MOP' mxn = 'MXN' myr = 'MYR' ngn = 'NGN' nio = 'NIO' nok = 'NOK' nzd = 'NZD' pen = 'PEN' php = 'PHP' pkr = 'PKR' pln = 'PLN' pyg = 'PYG' qar = 'QAR' ron = 'RON' sar = 'SAR' sek = 'SEK' sgd = 'SGD' thb = 'THB' value_try = 'TRY' twd = 'TWD' uah = 'UAH' usd = 'USD' uyu = 'UYU' vnd = 'VND' zar = 'ZAR' class Tasks(): aa_analyze = 'AA_ANALYZE' advertise = 'ADVERTISE' analyze = 'ANALYZE' draft = 'DRAFT' manage = 'MANAGE' class ClaimObjective(): automotive_model = 'AUTOMOTIVE_MODEL' collaborative_ads = 'COLLABORATIVE_ADS' home_listing = 'HOME_LISTING' media_title = 'MEDIA_TITLE' product = 'PRODUCT' travel = 'TRAVEL' vehicle = 'VEHICLE' vehicle_offer = 'VEHICLE_OFFER' class ContentType(): automotive_model = 'AUTOMOTIVE_MODEL' destination = 'DESTINATION' flight = 'FLIGHT' home_listing = 'HOME_LISTING' hotel = 'HOTEL' job = 'JOB' local_service_business = 'LOCAL_SERVICE_BUSINESS' location_based_item = 'LOCATION_BASED_ITEM' media_title = 'MEDIA_TITLE' offline_product = 'OFFLINE_PRODUCT' product = 'PRODUCT' vehicle = 'VEHICLE' vehicle_offer = 'VEHICLE_OFFER' class Subtype(): app = 'APP' bag_of_accounts = 'BAG_OF_ACCOUNTS' bidding = 'BIDDING' claim = 'CLAIM' custom = 'CUSTOM' engagement = 'ENGAGEMENT' fox = 'FOX' lookalike = 'LOOKALIKE' managed = 'MANAGED' measurement = 'MEASUREMENT' offline_conversion = 'OFFLINE_CONVERSION' partner = 'PARTNER' primary = 'PRIMARY' regulated_categories_audience = 'REGULATED_CATEGORIES_AUDIENCE' study_rule_audience = 'STUDY_RULE_AUDIENCE' subscriber_segment = 'SUBSCRIBER_SEGMENT' video = 'VIDEO' website = 'WEBSITE' class ActionSource(): physical_store = 'PHYSICAL_STORE' website = 'WEBSITE' def get_endpoint(cls): return 'adaccounts' def api_get(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='NODE', response_parser=ObjectParser(reuse_object=self)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def api_update(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'agency_client_declaration': 'map', 'attribution_spec': 'list<Object>', 'business_info': 'map', 'currency': 'currency_enum', 'custom_audience_info': 'map', 'default_dsa_beneficiary': 'string', 'default_dsa_payor': 'string', 'end_advertiser': 'string', 'existing_customers': 'list<string>', 'is_notifications_enabled': 'bool', 'media_agency': 'string', 'name': 'string', 'partner': 'string', 'spend_cap': 'float', 'spend_cap_action': 'string', 'timezone_id': 'unsigned int', 'tos_accepted': 'map'} enums = {'currency_enum': AdAccount.Currency.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='NODE', response_parser=ObjectParser(reuse_object=self)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_account_controls(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountbusinessconstraints import AdAccountBusinessConstraints param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/account_controls', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountBusinessConstraints, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountBusinessConstraints, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_account_control(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountbusinessconstraints import AdAccountBusinessConstraints param_types = {'audience_controls': 'Object', 'placement_controls': 'Object'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/account_controls', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountBusinessConstraints, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountBusinessConstraints, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_activities(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adactivity import AdActivity param_types = {'add_children': 'bool', 'after': 'string', 'business_id': 'string', 'category': 'category_enum', 'data_source': 'data_source_enum', 'extra_oids': 'list<string>', 'limit': 'int', 'oid': 'string', 'since': 'datetime', 'uid': 'int', 'until': 'datetime'} enums = {'category_enum': AdActivity.Category.__dict__.values(), 'data_source_enum': AdActivity.DataSource.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/activities', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdActivity, api_type='EDGE', response_parser=ObjectParser(target_class=AdActivity, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_place_page_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adplacepageset import AdPlacePageSet param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ad_place_page_sets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdPlacePageSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdPlacePageSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_place_page_set(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adplacepageset import AdPlacePageSet param_types = {'location_types': 'list<location_types_enum>', 'name': 'string', 'parent_page': 'string', 'targeted_area_type': 'targeted_area_type_enum'} enums = {'location_types_enum': AdPlacePageSet.LocationTypes.__dict__.values(), 'targeted_area_type_enum': AdPlacePageSet.TargetedAreaType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/ad_place_page_sets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdPlacePageSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdPlacePageSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_place_page_sets_async(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adplacepageset import AdPlacePageSet param_types = {'location_types': 'list<location_types_enum>', 'name': 'string', 'parent_page': 'string', 'targeted_area_type': 'targeted_area_type_enum'} enums = {'location_types_enum': AdPlacePageSet.LocationTypes.__dict__.values(), 'targeted_area_type_enum': AdPlacePageSet.TargetedAreaType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/ad_place_page_sets_async', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdPlacePageSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdPlacePageSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_saved_keywords(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'fields': 'list<string>'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ad_saved_keywords', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_studies(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adstudy import AdStudy param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ad_studies', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdStudy, api_type='EDGE', response_parser=ObjectParser(target_class=AdStudy, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_cloud_playables(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.cloudgame import CloudGame param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adcloudplayables', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CloudGame, api_type='EDGE', response_parser=ObjectParser(target_class=CloudGame, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_creatives(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adcreative import AdCreative param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adcreatives', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdCreative, api_type='EDGE', response_parser=ObjectParser(target_class=AdCreative, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_creative(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adcreative import AdCreative param_types = {'actor_id': 'unsigned int', 'adlabels': 'list<Object>', 'applink_treatment': 'applink_treatment_enum', 'asset_feed_spec': 'Object', 'authorization_category': 'authorization_category_enum', 'body': 'string', 'branded_content': 'map', 'branded_content_sponsor_page_id': 'string', 'bundle_folder_id': 'string', 'call_to_action': 'Object', 'categorization_criteria': 'categorization_criteria_enum', 'category_media_source': 'category_media_source_enum', 'degrees_of_freedom_spec': 'map', 'destination_set_id': 'string', 'dynamic_ad_voice': 'dynamic_ad_voice_enum', 'enable_launch_instant_app': 'bool', 'facebook_branded_content': 'map', 'image_crops': 'map', 'image_file': 'string', 'image_hash': 'string', 'image_url': 'string', 'instagram_actor_id': 'string', 'instagram_branded_content': 'map', 'instagram_permalink_url': 'string', 'instagram_user_id': 'string', 'interactive_components_spec': 'map', 'is_dco_internal': 'bool', 'link_og_id': 'string', 'link_url': 'string', 'messenger_sponsored_message': 'string', 'name': 'string', 'object_id': 'unsigned int', 'object_story_id': 'string', 'object_story_spec': 'AdCreativeObjectStorySpec', 'object_type': 'string', 'object_url': 'string', 'omnichannel_link_spec': 'map', 'place_page_set_id': 'string', 'platform_customizations': 'Object', 'playable_asset_id': 'string', 'portrait_customizations': 'map', 'product_set_id': 'string', 'recommender_settings': 'map', 'source_instagram_media_id': 'string', 'template_url': 'string', 'template_url_spec': 'string', 'thumbnail_url': 'string', 'title': 'string', 'url_tags': 'string', 'use_page_actor_override': 'bool'} enums = {'applink_treatment_enum': AdCreative.ApplinkTreatment.__dict__.values(), 'authorization_category_enum': AdCreative.AuthorizationCategory.__dict__.values(), 'categorization_criteria_enum': AdCreative.CategorizationCriteria.__dict__.values(), 'category_media_source_enum': AdCreative.CategoryMediaSource.__dict__.values(), 'dynamic_ad_voice_enum': AdCreative.DynamicAdVoice.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adcreatives', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdCreative, api_type='EDGE', response_parser=ObjectParser(target_class=AdCreative, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_creatives_by_labels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adcreative import AdCreative param_types = {'ad_label_ids': 'list<string>', 'operator': 'operator_enum'} enums = {'operator_enum': AdCreative.Operator.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adcreativesbylabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdCreative, api_type='EDGE', response_parser=ObjectParser(target_class=AdCreative, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_ad_images(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'hash': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/adimages', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_images(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adimage import AdImage param_types = {'biz_tag_id': 'unsigned int', 'business_id': 'string', 'hashes': 'list<string>', 'minheight': 'unsigned int', 'minwidth': 'unsigned int', 'name': 'string', 'selected_hashes': 'list<string>'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adimages', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdImage, api_type='EDGE', response_parser=ObjectParser(target_class=AdImage, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_image(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adimage import AdImage param_types = {'bytes': 'string', 'copy_from': 'Object'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adimages', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdImage, api_type='EDGE', allow_file_upload=True, response_parser=ObjectParser(target_class=AdImage, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_labels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adlabel import AdLabel param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adlabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdLabel, api_type='EDGE', response_parser=ObjectParser(target_class=AdLabel, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_label(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adlabel import AdLabel param_types = {'name': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adlabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdLabel, api_type='EDGE', response_parser=ObjectParser(target_class=AdLabel, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_playables(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.playablecontent import PlayableContent param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adplayables', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=PlayableContent, api_type='EDGE', response_parser=ObjectParser(target_class=PlayableContent, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_playable(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.playablecontent import PlayableContent param_types = {'app_id': 'string', 'name': 'string', 'session_id': 'string', 'source': 'file', 'source_url': 'string', 'source_zip': 'file'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adplayables', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=PlayableContent, api_type='EDGE', response_parser=ObjectParser(target_class=PlayableContent, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_rules_history(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountadruleshistory import AdAccountAdRulesHistory param_types = {'action': 'action_enum', 'evaluation_type': 'evaluation_type_enum', 'hide_no_changes': 'bool', 'object_id': 'string'} enums = {'action_enum': AdAccountAdRulesHistory.Action.__dict__.values(), 'evaluation_type_enum': AdAccountAdRulesHistory.EvaluationType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adrules_history', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountAdRulesHistory, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountAdRulesHistory, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_rules_library(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adrule import AdRule param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adrules_library', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdRule, api_type='EDGE', response_parser=ObjectParser(target_class=AdRule, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_rules_library(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adrule import AdRule param_types = {'account_id': 'string', 'evaluation_spec': 'Object', 'execution_spec': 'Object', 'name': 'string', 'schedule_spec': 'Object', 'status': 'status_enum', 'ui_creation_source': 'ui_creation_source_enum'} enums = {'status_enum': AdRule.Status.__dict__.values(), 'ui_creation_source_enum': AdRule.UiCreationSource.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adrules_library', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdRule, api_type='EDGE', response_parser=ObjectParser(target_class=AdRule, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.ad import Ad param_types = {'date_preset': 'date_preset_enum', 'effective_status': 'list<string>', 'time_range': 'map', 'updated_since': 'int'} enums = {'date_preset_enum': Ad.DatePreset.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ads', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Ad, api_type='EDGE', response_parser=ObjectParser(target_class=Ad, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.ad import Ad param_types = {'ad_schedule_end_time': 'datetime', 'ad_schedule_start_time': 'datetime', 'adlabels': 'list<Object>', 'adset_id': 'unsigned int', 'adset_spec': 'AdSet', 'audience_id': 'string', 'bid_amount': 'int', 'conversion_domain': 'string', 'creative': 'AdCreative', 'date_format': 'string', 'display_sequence': 'unsigned int', 'draft_adgroup_id': 'string', 'engagement_audience': 'bool', 'execution_options': 'list<execution_options_enum>', 'include_demolink_hashes': 'bool', 'name': 'string', 'priority': 'unsigned int', 'source_ad_id': 'string', 'status': 'status_enum', 'tracking_specs': 'Object'} enums = {'execution_options_enum': Ad.ExecutionOptions.__dict__.values(), 'status_enum': Ad.Status.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/ads', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Ad, api_type='EDGE', allow_file_upload=True, response_parser=ObjectParser(target_class=Ad, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads_reporting_mmm_reports(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'filtering': 'list<map>'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ads_reporting_mmm_reports', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads_reporting_mmm_schedulers(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ads_reporting_mmm_schedulers', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads_volume(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountadvolume import AdAccountAdVolume param_types = {'page_id': 'int', 'recommendation_type': 'recommendation_type_enum', 'show_breakdown_by_actor': 'bool'} enums = {'recommendation_type_enum': AdAccountAdVolume.RecommendationType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ads_volume', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountAdVolume, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountAdVolume, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads_by_labels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.ad import Ad param_types = {'ad_label_ids': 'list<string>', 'operator': 'operator_enum'} enums = {'operator_enum': Ad.Operator.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adsbylabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Ad, api_type='EDGE', response_parser=ObjectParser(target_class=Ad, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adset import AdSet param_types = {'date_preset': 'date_preset_enum', 'effective_status': 'list<effective_status_enum>', 'is_completed': 'bool', 'time_range': 'map', 'updated_since': 'int'} enums = {'date_preset_enum': AdSet.DatePreset.__dict__.values(), 'effective_status_enum': AdSet.EffectiveStatus.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_set(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adset import AdSet param_types = {'adlabels': 'list<Object>', 'adset_schedule': 'list<Object>', 'attribution_spec': 'list<map>', 'bid_adjustments': 'Object', 'bid_amount': 'int', 'bid_constraints': 'map<string, Object>', 'bid_strategy': 'bid_strategy_enum', 'billing_event': 'billing_event_enum', 'campaign_attribution': 'Object', 'campaign_id': 'string', 'campaign_spec': 'Object', 'creative_sequence': 'list<string>', 'daily_budget': 'unsigned int', 'daily_imps': 'unsigned int', 'daily_min_spend_target': 'unsigned int', 'daily_spend_cap': 'unsigned int', 'date_format': 'string', 'destination_type': 'destination_type_enum', 'dsa_beneficiary': 'string', 'dsa_payor': 'string', 'end_time': 'datetime', 'execution_options': 'list<execution_options_enum>', 'existing_customer_budget_percentage': 'unsigned int', 'frequency_control_specs': 'list<Object>', 'full_funnel_exploration_mode': 'full_funnel_exploration_mode_enum', 'is_dynamic_creative': 'bool', 'lifetime_budget': 'unsigned int', 'lifetime_imps': 'unsigned int', 'lifetime_min_spend_target': 'unsigned int', 'lifetime_spend_cap': 'unsigned int', 'line_number': 'unsigned int', 'multi_optimization_goal_weight': 'multi_optimization_goal_weight_enum', 'name': 'string', 'optimization_goal': 'optimization_goal_enum', 'optimization_sub_event': 'optimization_sub_event_enum', 'pacing_type': 'list<string>', 'promoted_object': 'Object', 'rb_prediction_id': 'string', 'rf_prediction_id': 'string', 'source_adset_id': 'string', 'start_time': 'datetime', 'status': 'status_enum', 'targeting': 'Targeting', 'time_based_ad_rotation_id_blocks': 'list<list<unsigned int>>', 'time_based_ad_rotation_intervals': 'list<unsigned int>', 'time_start': 'datetime', 'time_stop': 'datetime', 'topline_id': 'string', 'tune_for_category': 'tune_for_category_enum'} enums = {'bid_strategy_enum': AdSet.BidStrategy.__dict__.values(), 'billing_event_enum': AdSet.BillingEvent.__dict__.values(), 'destination_type_enum': AdSet.DestinationType.__dict__.values(), 'execution_options_enum': AdSet.ExecutionOptions.__dict__.values(), 'full_funnel_exploration_mode_enum': AdSet.FullFunnelExplorationMode.__dict__.values(), 'multi_optimization_goal_weight_enum': AdSet.MultiOptimizationGoalWeight.__dict__.values(), 'optimization_goal_enum': AdSet.OptimizationGoal.__dict__.values(), 'optimization_sub_event_enum': AdSet.OptimizationSubEvent.__dict__.values(), 'status_enum': AdSet.Status.__dict__.values(), 'tune_for_category_enum': AdSet.TuneForCategory.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_sets_by_labels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adset import AdSet param_types = {'ad_label_ids': 'list<string>', 'operator': 'operator_enum'} enums = {'operator_enum': AdSet.Operator.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adsetsbylabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ads_pixels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adspixel import AdsPixel param_types = {'sort_by': 'sort_by_enum'} enums = {'sort_by_enum': AdsPixel.SortBy.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/adspixels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdsPixel, api_type='EDGE', response_parser=ObjectParser(target_class=AdsPixel, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ads_pixel(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adspixel import AdsPixel param_types = {'name': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/adspixels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdsPixel, api_type='EDGE', response_parser=ObjectParser(target_class=AdsPixel, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_advertisable_applications(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.application import Application param_types = {'app_id': 'string', 'business_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/advertisable_applications', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Application, api_type='EDGE', response_parser=ObjectParser(target_class=Application, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_ad_videos(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'video_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/advideos', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ad_videos(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.advideo import AdVideo param_types = {'max_aspect_ratio': 'float', 'maxheight': 'unsigned int', 'maxlength': 'unsigned int', 'maxwidth': 'unsigned int', 'min_aspect_ratio': 'float', 'minheight': 'unsigned int', 'minlength': 'unsigned int', 'minwidth': 'unsigned int', 'title': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/advideos', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdVideo, api_type='EDGE', response_parser=ObjectParser(target_class=AdVideo, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_ad_video(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.advideo import AdVideo param_types = {'adaptive_type': 'string', 'animated_effect_id': 'unsigned int', 'application_id': 'string', 'asked_fun_fact_prompt_id': 'unsigned int', 'audio_story_wave_animation_handle': 'string', 'chunk_session_id': 'string', 'composer_entry_picker': 'string', 'composer_entry_point': 'string', 'composer_entry_time': 'unsigned int', 'composer_session_events_log': 'string', 'composer_session_id': 'string', 'composer_source_surface': 'string', 'composer_type': 'string', 'container_type': 'container_type_enum', 'content_category': 'content_category_enum', 'creative_tools': 'string', 'description': 'string', 'embeddable': 'bool', 'end_offset': 'unsigned int', 'fbuploader_video_file_chunk': 'string', 'file_size': 'unsigned int', 'file_url': 'string', 'fisheye_video_cropped': 'bool', 'formatting': 'formatting_enum', 'fov': 'unsigned int', 'front_z_rotation': 'float', 'fun_fact_prompt_id': 'unsigned int', 'fun_fact_toastee_id': 'unsigned int', 'guide': 'list<list<unsigned int>>', 'guide_enabled': 'bool', 'has_nickname': 'bool', 'holiday_card': 'string', 'initial_heading': 'unsigned int', 'initial_pitch': 'unsigned int', 'instant_game_entry_point_data': 'string', 'is_boost_intended': 'bool', 'is_group_linking_post': 'bool', 'is_voice_clip': 'bool', 'location_source_id': 'string', 'name': 'string', 'offer_like_post_id': 'unsigned int', 'og_action_type_id': 'string', 'og_icon_id': 'string', 'og_object_id': 'string', 'og_phrase': 'string', 'og_suggestion_mechanism': 'string', 'original_fov': 'unsigned int', 'original_projection_type': 'original_projection_type_enum', 'publish_event_id': 'unsigned int', 'react_mode_metadata': 'string', 'referenced_sticker_id': 'string', 'replace_video_id': 'string', 'slideshow_spec': 'map', 'source': 'file', 'source_instagram_media_id': 'string', 'spherical': 'bool', 'start_offset': 'unsigned int', 'swap_mode': 'swap_mode_enum', 'text_format_metadata': 'string', 'throwback_camera_roll_media': 'string', 'thumb': 'file', 'time_since_original_post': 'unsigned int', 'title': 'string', 'transcode_setting_properties': 'string', 'unpublished_content_type': 'unpublished_content_type_enum', 'upload_phase': 'upload_phase_enum', 'upload_session_id': 'string', 'upload_setting_properties': 'string', 'video_file_chunk': 'file', 'video_id_original': 'string', 'video_start_time_ms': 'unsigned int', 'waterfall_id': 'string'} enums = {'container_type_enum': AdVideo.ContainerType.__dict__.values(), 'content_category_enum': AdVideo.ContentCategory.__dict__.values(), 'formatting_enum': AdVideo.Formatting.__dict__.values(), 'original_projection_type_enum': AdVideo.OriginalProjectionType.__dict__.values(), 'swap_mode_enum': AdVideo.SwapMode.__dict__.values(), 'unpublished_content_type_enum': AdVideo.UnpublishedContentType.__dict__.values(), 'upload_phase_enum': AdVideo.UploadPhase.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/advideos', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdVideo, api_type='EDGE', allow_file_upload=True, response_parser=ObjectParser(target_class=AdVideo, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_affected_ad_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adset import AdSet param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/affectedadsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_agencies(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'business': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/agencies', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_agencies(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.business import Business param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/agencies', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Business, api_type='EDGE', response_parser=ObjectParser(target_class=Business, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_applications(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.application import Application param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/applications', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Application, api_type='EDGE', response_parser=ObjectParser(target_class=Application, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_assigned_users(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'user': 'int'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/assigned_users', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_assigned_users(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.assigneduser import AssignedUser param_types = {'business': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/assigned_users', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AssignedUser, api_type='EDGE', response_parser=ObjectParser(target_class=AssignedUser, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_assigned_user(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'tasks': 'list<tasks_enum>', 'user': 'int'} enums = {'tasks_enum': AdAccount.Tasks.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/assigned_users', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccount, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_async_batch_request(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.campaign import Campaign param_types = {'adbatch': 'list<Object>', 'name': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/async_batch_requests', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Campaign, api_type='EDGE', response_parser=ObjectParser(target_class=Campaign, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_async_requests(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.asyncrequest import AsyncRequest param_types = {'status': 'status_enum', 'type': 'type_enum'} enums = {'status_enum': AsyncRequest.Status.__dict__.values(), 'type_enum': AsyncRequest.Type.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/async_requests', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AsyncRequest, api_type='EDGE', response_parser=ObjectParser(target_class=AsyncRequest, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_async_ad_request_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adasyncrequestset import AdAsyncRequestSet param_types = {'is_completed': 'bool'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/asyncadrequestsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAsyncRequestSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdAsyncRequestSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_async_ad_request_set(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adasyncrequestset import AdAsyncRequestSet param_types = {'ad_specs': 'list<map>', 'name': 'string', 'notification_mode': 'notification_mode_enum', 'notification_uri': 'string'} enums = {'notification_mode_enum': AdAsyncRequestSet.NotificationMode.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/asyncadrequestsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAsyncRequestSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdAsyncRequestSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_block_list_draft(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'publisher_urls_file': 'file'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/block_list_drafts', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccount, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_broad_targeting_categories(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.broadtargetingcategories import BroadTargetingCategories param_types = {'custom_categories_only': 'bool'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/broadtargetingcategories', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=BroadTargetingCategories, api_type='EDGE', response_parser=ObjectParser(target_class=BroadTargetingCategories, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_business_projects(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'business': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/businessprojects', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_campaigns(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'before_date': 'datetime', 'delete_offset': 'unsigned int', 'delete_strategy': 'delete_strategy_enum', 'object_count': 'int'} enums = {'delete_strategy_enum': ['DELETE_ANY', 'DELETE_ARCHIVED_BEFORE', 'DELETE_OLDEST']} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/campaigns', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_campaigns(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.campaign import Campaign param_types = {'date_preset': 'date_preset_enum', 'effective_status': 'list<effective_status_enum>', 'is_completed': 'bool', 'time_range': 'map'} enums = {'date_preset_enum': Campaign.DatePreset.__dict__.values(), 'effective_status_enum': Campaign.EffectiveStatus.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/campaigns', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Campaign, api_type='EDGE', response_parser=ObjectParser(target_class=Campaign, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_campaign(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.campaign import Campaign param_types = {'adlabels': 'list<Object>', 'bid_strategy': 'bid_strategy_enum', 'buying_type': 'string', 'daily_budget': 'unsigned int', 'execution_options': 'list<execution_options_enum>', 'is_skadnetwork_attribution': 'bool', 'iterative_split_test_configs': 'list<Object>', 'lifetime_budget': 'unsigned int', 'name': 'string', 'objective': 'objective_enum', 'pacing_type': 'list<string>', 'promoted_object': 'Object', 'smart_promotion_type': 'smart_promotion_type_enum', 'source_campaign_id': 'string', 'special_ad_categories': 'list<special_ad_categories_enum>', 'special_ad_category_country': 'list<special_ad_category_country_enum>', 'spend_cap': 'unsigned int', 'start_time': 'datetime', 'status': 'status_enum', 'stop_time': 'datetime', 'topline_id': 'string'} enums = {'bid_strategy_enum': Campaign.BidStrategy.__dict__.values(), 'execution_options_enum': Campaign.ExecutionOptions.__dict__.values(), 'objective_enum': Campaign.Objective.__dict__.values(), 'smart_promotion_type_enum': Campaign.SmartPromotionType.__dict__.values(), 'special_ad_categories_enum': Campaign.SpecialAdCategories.__dict__.values(), 'special_ad_category_country_enum': Campaign.SpecialAdCategoryCountry.__dict__.values(), 'status_enum': Campaign.Status.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/campaigns', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Campaign, api_type='EDGE', response_parser=ObjectParser(target_class=Campaign, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_campaigns_by_labels(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.campaign import Campaign param_types = {'ad_label_ids': 'list<string>', 'operator': 'operator_enum'} enums = {'operator_enum': Campaign.Operator.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/campaignsbylabels', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Campaign, api_type='EDGE', response_parser=ObjectParser(target_class=Campaign, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_connected_instagram_accounts(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.iguser import IGUser param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/connected_instagram_accounts', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=IGUser, api_type='EDGE', response_parser=ObjectParser(target_class=IGUser, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_conversion_goals(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/conversion_goals', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_custom_audiences(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customaudience import CustomAudience param_types = {'business_id': 'string', 'fetch_primary_audience': 'bool', 'fields': 'list<string>', 'filtering': 'list<Object>', 'pixel_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/customaudiences', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomAudience, api_type='EDGE', response_parser=ObjectParser(target_class=CustomAudience, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_custom_audience(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customaudience import CustomAudience param_types = {'allowed_domains': 'list<string>', 'associated_audience_id': 'unsigned int', 'claim_objective': 'claim_objective_enum', 'content_type': 'content_type_enum', 'countries': 'string', 'creation_params': 'map', 'customer_file_source': 'customer_file_source_enum', 'dataset_id': 'string', 'description': 'string', 'enable_fetch_or_create': 'bool', 'event_source_group': 'string', 'event_sources': 'list<map>', 'exclusions': 'list<Object>', 'inclusions': 'list<Object>', 'is_snapshot': 'bool', 'is_value_based': 'bool', 'list_of_accounts': 'list<unsigned int>', 'lookalike_spec': 'string', 'name': 'string', 'opt_out_link': 'string', 'origin_audience_id': 'string', 'parent_audience_id': 'unsigned int', 'partner_reference_key': 'string', 'pixel_id': 'string', 'prefill': 'bool', 'product_set_id': 'string', 'regulated_audience_spec': 'string', 'retention_days': 'unsigned int', 'rev_share_policy_id': 'unsigned int', 'rule': 'string', 'rule_aggregation': 'string', 'subtype': 'subtype_enum', 'use_in_campaigns': 'bool', 'video_group_ids': 'list<string>', 'whats_app_business_phone_number_id': 'string'} enums = {'claim_objective_enum': CustomAudience.ClaimObjective.__dict__.values(), 'content_type_enum': CustomAudience.ContentType.__dict__.values(), 'customer_file_source_enum': CustomAudience.CustomerFileSource.__dict__.values(), 'subtype_enum': CustomAudience.Subtype.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/customaudiences', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomAudience, api_type='EDGE', response_parser=ObjectParser(target_class=CustomAudience, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_custom_audiences_tos(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customaudiencestos import CustomAudiencesTOS param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/customaudiencestos', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomAudiencesTOS, api_type='EDGE', response_parser=ObjectParser(target_class=CustomAudiencesTOS, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_custom_audiences_to(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'business_id': 'string', 'tos_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/customaudiencestos', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccount, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_custom_conversions(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customconversion import CustomConversion param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/customconversions', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomConversion, api_type='EDGE', response_parser=ObjectParser(target_class=CustomConversion, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_custom_conversion(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customconversion import CustomConversion param_types = {'advanced_rule': 'string', 'custom_event_type': 'custom_event_type_enum', 'default_conversion_value': 'float', 'description': 'string', 'event_source_id': 'string', 'name': 'string', 'rule': 'string'} enums = {'custom_event_type_enum': CustomConversion.CustomEventType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/customconversions', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomConversion, api_type='EDGE', response_parser=ObjectParser(target_class=CustomConversion, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_delivery_estimate(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountdeliveryestimate import AdAccountDeliveryEstimate param_types = {'optimization_goal': 'optimization_goal_enum', 'promoted_object': 'Object', 'targeting_spec': 'Targeting'} enums = {'optimization_goal_enum': AdAccountDeliveryEstimate.OptimizationGoal.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/delivery_estimate', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountDeliveryEstimate, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountDeliveryEstimate, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_deprecated_targeting_ad_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adset import AdSet param_types = {'type': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/deprecatedtargetingadsets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdSet, api_type='EDGE', response_parser=ObjectParser(target_class=AdSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_dsa_recommendations(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountdsarecommendations import AdAccountDsaRecommendations param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/dsa_recommendations', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountDsaRecommendations, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountDsaRecommendations, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_generate_previews(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adpreview import AdPreview param_types = {'ad_format': 'ad_format_enum', 'creative': 'AdCreative', 'creative_feature': 'creative_feature_enum', 'dynamic_asset_label': 'string', 'dynamic_creative_spec': 'Object', 'dynamic_customization': 'Object', 'end_date': 'datetime', 'height': 'unsigned int', 'locale': 'string', 'place_page_id': 'int', 'post': 'Object', 'product_item_ids': 'list<string>', 'render_type': 'render_type_enum', 'start_date': 'datetime', 'width': 'unsigned int'} enums = {'ad_format_enum': AdPreview.AdFormat.__dict__.values(), 'creative_feature_enum': AdPreview.CreativeFeature.__dict__.values(), 'render_type_enum': AdPreview.RenderType.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/generatepreviews', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdPreview, api_type='EDGE', response_parser=ObjectParser(target_class=AdPreview, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_impacting_ad_studies(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adstudy import AdStudy param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/impacting_ad_studies', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdStudy, api_type='EDGE', response_parser=ObjectParser(target_class=AdStudy, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_insights(self, fields=None, params=None, is_async=False, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adsinsights import AdsInsights if is_async: return self.get_insights_async(fields, params, batch, success, failure, pending) param_types = {'action_attribution_windows': 'list<action_attribution_windows_enum>', 'action_breakdowns': 'list<action_breakdowns_enum>', 'action_report_time': 'action_report_time_enum', 'breakdowns': 'list<breakdowns_enum>', 'date_preset': 'date_preset_enum', 'default_summary': 'bool', 'export_columns': 'list<string>', 'export_format': 'string', 'export_name': 'string', 'fields': 'list<string>', 'filtering': 'list<Object>', 'level': 'level_enum', 'product_id_limit': 'int', 'sort': 'list<string>', 'summary': 'list<string>', 'summary_action_breakdowns': 'list<summary_action_breakdowns_enum>', 'time_increment': 'string', 'time_range': 'map', 'time_ranges': 'list<map>', 'use_account_attribution_setting': 'bool', 'use_unified_attribution_setting': 'bool'} enums = {'action_attribution_windows_enum': AdsInsights.ActionAttributionWindows.__dict__.values(), 'action_breakdowns_enum': AdsInsights.ActionBreakdowns.__dict__.values(), 'action_report_time_enum': AdsInsights.ActionReportTime.__dict__.values(), 'breakdowns_enum': AdsInsights.Breakdowns.__dict__.values(), 'date_preset_enum': AdsInsights.DatePreset.__dict__.values(), 'level_enum': AdsInsights.Level.__dict__.values(), 'summary_action_breakdowns_enum': AdsInsights.SummaryActionBreakdowns.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/insights', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdsInsights, api_type='EDGE', response_parser=ObjectParser(target_class=AdsInsights, api=self._api), include_summary=False) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_insights_async(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adreportrun import AdReportRun from facebook_business.adobjects.adsinsights import AdsInsights param_types = {'action_attribution_windows': 'list<action_attribution_windows_enum>', 'action_breakdowns': 'list<action_breakdowns_enum>', 'action_report_time': 'action_report_time_enum', 'breakdowns': 'list<breakdowns_enum>', 'date_preset': 'date_preset_enum', 'default_summary': 'bool', 'export_columns': 'list<string>', 'export_format': 'string', 'export_name': 'string', 'fields': 'list<string>', 'filtering': 'list<Object>', 'level': 'level_enum', 'product_id_limit': 'int', 'sort': 'list<string>', 'summary': 'list<string>', 'summary_action_breakdowns': 'list<summary_action_breakdowns_enum>', 'time_increment': 'string', 'time_range': 'map', 'time_ranges': 'list<map>', 'use_account_attribution_setting': 'bool', 'use_unified_attribution_setting': 'bool'} enums = {'action_attribution_windows_enum': AdsInsights.ActionAttributionWindows.__dict__.values(), 'action_breakdowns_enum': AdsInsights.ActionBreakdowns.__dict__.values(), 'action_report_time_enum': AdsInsights.ActionReportTime.__dict__.values(), 'breakdowns_enum': AdsInsights.Breakdowns.__dict__.values(), 'date_preset_enum': AdsInsights.DatePreset.__dict__.values(), 'level_enum': AdsInsights.Level.__dict__.values(), 'summary_action_breakdowns_enum': AdsInsights.SummaryActionBreakdowns.__dict__.values()} if (fields is not None): params['fields'] = (params.get('fields') if (params.get('fields') is not None) else list()) params['fields'].extend((field for field in fields if (field not in params['fields']))) request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/insights', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdReportRun, api_type='EDGE', response_parser=ObjectParser(target_class=AdReportRun, api=self._api), include_summary=False) request.add_params(params) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_instagram_accounts(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.instagramuser import InstagramUser param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/instagram_accounts', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=InstagramUser, api_type='EDGE', response_parser=ObjectParser(target_class=InstagramUser, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_ios_fourteen_campaign_limits(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountiosfourteencampaignlimits import AdAccountIosFourteenCampaignLimits param_types = {'app_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/ios_fourteen_campaign_limits', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountIosFourteenCampaignLimits, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountIosFourteenCampaignLimits, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_managed_partner_ad(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'campaign_group_id': 'unsigned int', 'campaign_group_status': 'campaign_group_status_enum', 'conversion_domain': 'string', 'custom_event_type': 'custom_event_type_enum', 'daily_budget': 'unsigned int', 'dsa_beneficiary': 'string', 'dsa_payor': 'string', 'end_time': 'unsigned int', 'lifetime_budget': 'unsigned int', 'override_creative_text': 'string', 'override_targeting_countries': 'list<string>', 'product_set_id': 'string', 'start_time': 'unsigned int', 'use_marketplace_template': 'bool', 'use_seller_template': 'bool'} enums = {'campaign_group_status_enum': ['ACTIVE', 'ADSET_PAUSED', 'ARCHIVED', 'CAMPAIGN_PAUSED', 'DELETED', 'DISAPPROVED', 'IN_PROCESS', 'PAUSED', 'PENDING_BILLING_INFO', 'PENDING_REVIEW', 'PREAPPROVED', 'WITH_ISSUES'], 'custom_event_type_enum': ['ADD_TO_CART', 'CONTENT_VIEW', 'PURCHASE']} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/managed_partner_ads', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_matched_search_applications(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountmatchedsearchapplicationsedgedata import AdAccountMatchedSearchApplicationsEdgeData param_types = {'allow_incomplete_app': 'bool', 'app_store': 'app_store_enum', 'app_store_country': 'string', 'business_id': 'string', 'is_skadnetwork_search': 'bool', 'only_apps_with_permission': 'bool', 'query_term': 'string'} enums = {'app_store_enum': AdAccountMatchedSearchApplicationsEdgeData.AppStore.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/matched_search_applications', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountMatchedSearchApplicationsEdgeData, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountMatchedSearchApplicationsEdgeData, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_max_bid(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountmaxbid import AdAccountMaxBid param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/max_bid', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountMaxBid, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountMaxBid, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_minimum_budgets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.minimumbudget import MinimumBudget param_types = {'bid_amount': 'int'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/minimum_budgets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=MinimumBudget, api_type='EDGE', response_parser=ObjectParser(target_class=MinimumBudget, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_offline_conversion_data_sets(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.offlineconversiondataset import OfflineConversionDataSet param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/offline_conversion_data_sets', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=OfflineConversionDataSet, api_type='EDGE', response_parser=ObjectParser(target_class=OfflineConversionDataSet, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_on_behalf_requests(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.businessownedobjectonbehalfofrequest import BusinessOwnedObjectOnBehalfOfRequest param_types = {'status': 'status_enum'} enums = {'status_enum': BusinessOwnedObjectOnBehalfOfRequest.Status.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/onbehalf_requests', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=BusinessOwnedObjectOnBehalfOfRequest, api_type='EDGE', response_parser=ObjectParser(target_class=BusinessOwnedObjectOnBehalfOfRequest, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_product_audience(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.customaudience import CustomAudience param_types = {'allowed_domains': 'list<string>', 'associated_audience_id': 'unsigned int', 'claim_objective': 'claim_objective_enum', 'content_type': 'content_type_enum', 'creation_params': 'map', 'description': 'string', 'enable_fetch_or_create': 'bool', 'event_source_group': 'string', 'event_sources': 'list<map>', 'exclusions': 'list<Object>', 'inclusions': 'list<Object>', 'is_snapshot': 'bool', 'is_value_based': 'bool', 'name': 'string', 'opt_out_link': 'string', 'parent_audience_id': 'unsigned int', 'product_set_id': 'string', 'rev_share_policy_id': 'unsigned int', 'subtype': 'subtype_enum'} enums = {'claim_objective_enum': AdAccount.ClaimObjective.__dict__.values(), 'content_type_enum': AdAccount.ContentType.__dict__.values(), 'subtype_enum': AdAccount.Subtype.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/product_audiences', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=CustomAudience, api_type='EDGE', response_parser=ObjectParser(target_class=CustomAudience, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_promote_pages(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.page import Page param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/promote_pages', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=Page, api_type='EDGE', response_parser=ObjectParser(target_class=Page, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_publisher_block_lists(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.publisherblocklist import PublisherBlockList param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/publisher_block_lists', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=PublisherBlockList, api_type='EDGE', response_parser=ObjectParser(target_class=PublisherBlockList, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_publisher_block_list(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.publisherblocklist import PublisherBlockList param_types = {'name': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/publisher_block_lists', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=PublisherBlockList, api_type='EDGE', response_parser=ObjectParser(target_class=PublisherBlockList, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_reach_estimate(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountreachestimate import AdAccountReachEstimate param_types = {'adgroup_ids': 'list<string>', 'caller_id': 'string', 'concepts': 'string', 'creative_action_spec': 'string', 'is_debug': 'bool', 'object_store_url': 'string', 'targeting_spec': 'Targeting'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/reachestimate', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountReachEstimate, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountReachEstimate, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_reach_frequency_predictions(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.reachfrequencyprediction import ReachFrequencyPrediction param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/reachfrequencypredictions', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=ReachFrequencyPrediction, api_type='EDGE', response_parser=ObjectParser(target_class=ReachFrequencyPrediction, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_reach_frequency_prediction(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.reachfrequencyprediction import ReachFrequencyPrediction param_types = {'action': 'action_enum', 'ad_formats': 'list<map>', 'auction_entry_option_index': 'unsigned int', 'budget': 'unsigned int', 'buying_type': 'buying_type_enum', 'campaign_group_id': 'string', 'day_parting_schedule': 'list<Object>', 'deal_id': 'string', 'destination_id': 'unsigned int', 'destination_ids': 'list<string>', 'end_time': 'unsigned int', 'exceptions': 'bool', 'existing_campaign_id': 'string', 'expiration_time': 'unsigned int', 'frequency_cap': 'unsigned int', 'grp_buying': 'bool', 'impression': 'unsigned int', 'instream_packages': 'list<instream_packages_enum>', 'interval_frequency_cap_reset_period': 'unsigned int', 'is_balanced_frequency': 'bool', 'is_bonus_media': 'bool', 'is_conversion_goal': 'bool', 'is_full_view': 'bool', 'is_higher_average_frequency': 'bool', 'is_reach_and_frequency_io_buying': 'bool', 'is_reserved_buying': 'bool', 'num_curve_points': 'unsigned int', 'objective': 'string', 'optimization_goal': 'string', 'prediction_mode': 'unsigned int', 'reach': 'unsigned int', 'rf_prediction_id': 'string', 'rf_prediction_id_to_release': 'string', 'rf_prediction_id_to_share': 'string', 'start_time': 'unsigned int', 'stop_time': 'unsigned int', 'story_event_type': 'unsigned int', 'target_cpm': 'unsigned int', 'target_frequency': 'unsigned int', 'target_frequency_reset_period': 'unsigned int', 'target_spec': 'Targeting', 'video_view_length_constraint': 'unsigned int'} enums = {'action_enum': ReachFrequencyPrediction.Action.__dict__.values(), 'buying_type_enum': ReachFrequencyPrediction.BuyingType.__dict__.values(), 'instream_packages_enum': ReachFrequencyPrediction.InstreamPackages.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/reachfrequencypredictions', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=ReachFrequencyPrediction, api_type='EDGE', response_parser=ObjectParser(target_class=ReachFrequencyPrediction, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_saved_audiences(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.savedaudience import SavedAudience param_types = {'business_id': 'string', 'fields': 'list<string>', 'filtering': 'list<Object>'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/saved_audiences', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=SavedAudience, api_type='EDGE', response_parser=ObjectParser(target_class=SavedAudience, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_subscribed_apps(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'app_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/subscribed_apps', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_subscribed_apps(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountsubscribedapps import AdAccountSubscribedApps param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/subscribed_apps', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountSubscribedApps, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountSubscribedApps, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_subscribed_app(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountsubscribedapps import AdAccountSubscribedApps param_types = {'app_id': 'string'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/subscribed_apps', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountSubscribedApps, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountSubscribedApps, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_targeting_browse(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccounttargetingunified import AdAccountTargetingUnified param_types = {'excluded_category': 'string', 'include_nodes': 'bool', 'is_exclusion': 'bool', 'limit_type': 'limit_type_enum', 'regulated_categories': 'list<regulated_categories_enum>', 'regulated_countries': 'list<regulated_countries_enum>', 'whitelisted_types': 'list<whitelisted_types_enum>'} enums = {'limit_type_enum': AdAccountTargetingUnified.LimitType.__dict__.values(), 'regulated_categories_enum': AdAccountTargetingUnified.RegulatedCategories.__dict__.values(), 'regulated_countries_enum': AdAccountTargetingUnified.RegulatedCountries.__dict__.values(), 'whitelisted_types_enum': AdAccountTargetingUnified.WhitelistedTypes.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/targetingbrowse', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountTargetingUnified, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountTargetingUnified, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_targeting_search(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccounttargetingunified import AdAccountTargetingUnified param_types = {'allow_only_fat_head_interests': 'bool', 'app_store': 'app_store_enum', 'countries': 'list<string>', 'is_exclusion': 'bool', 'limit_type': 'limit_type_enum', 'objective': 'objective_enum', 'promoted_object': 'Object', 'q': 'string', 'regulated_categories': 'list<regulated_categories_enum>', 'regulated_countries': 'list<regulated_countries_enum>', 'session_id': 'unsigned int', 'targeting_list': 'list<Object>', 'whitelisted_types': 'list<whitelisted_types_enum>'} enums = {'app_store_enum': AdAccountTargetingUnified.AppStore.__dict__.values(), 'limit_type_enum': AdAccountTargetingUnified.LimitType.__dict__.values(), 'objective_enum': AdAccountTargetingUnified.Objective.__dict__.values(), 'regulated_categories_enum': AdAccountTargetingUnified.RegulatedCategories.__dict__.values(), 'regulated_countries_enum': AdAccountTargetingUnified.RegulatedCountries.__dict__.values(), 'whitelisted_types_enum': AdAccountTargetingUnified.WhitelistedTypes.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/targetingsearch', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountTargetingUnified, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountTargetingUnified, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_targeting_sentence_lines(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.targetingsentenceline import TargetingSentenceLine param_types = {'discard_ages': 'bool', 'discard_placements': 'bool', 'hide_targeting_spec_from_return': 'bool', 'targeting_spec': 'Targeting'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/targetingsentencelines', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=TargetingSentenceLine, api_type='EDGE', response_parser=ObjectParser(target_class=TargetingSentenceLine, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_targeting_suggestions(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccounttargetingunified import AdAccountTargetingUnified param_types = {'app_store': 'app_store_enum', 'countries': 'list<string>', 'limit_type': 'limit_type_enum', 'mode': 'mode_enum', 'objective': 'objective_enum', 'objects': 'Object', 'regulated_categories': 'list<regulated_categories_enum>', 'regulated_countries': 'list<regulated_countries_enum>', 'session_id': 'unsigned int', 'targeting_list': 'list<Object>', 'whitelisted_types': 'list<whitelisted_types_enum>'} enums = {'app_store_enum': AdAccountTargetingUnified.AppStore.__dict__.values(), 'limit_type_enum': AdAccountTargetingUnified.LimitType.__dict__.values(), 'mode_enum': AdAccountTargetingUnified.Mode.__dict__.values(), 'objective_enum': AdAccountTargetingUnified.Objective.__dict__.values(), 'regulated_categories_enum': AdAccountTargetingUnified.RegulatedCategories.__dict__.values(), 'regulated_countries_enum': AdAccountTargetingUnified.RegulatedCountries.__dict__.values(), 'whitelisted_types_enum': AdAccountTargetingUnified.WhitelistedTypes.__dict__.values()} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/targetingsuggestions', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountTargetingUnified, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountTargetingUnified, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_targeting_validation(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccounttargetingunified import AdAccountTargetingUnified param_types = {'id_list': 'list<unsigned int>', 'is_exclusion': 'bool', 'name_list': 'list<string>', 'targeting_list': 'list<Object>'} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/targetingvalidation', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountTargetingUnified, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountTargetingUnified, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_tracking(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccounttrackingdata import AdAccountTrackingData param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/tracking', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountTrackingData, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountTrackingData, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def create_tracking(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'tracking_specs': 'Object'} enums = {} request = FacebookRequest(node_id=self['id'], method='POST', endpoint='/tracking', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccount, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccount, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_users(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') from facebook_business.adobjects.adaccountuser import AdAccountUser param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/users', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AdAccountUser, api_type='EDGE', response_parser=ObjectParser(target_class=AdAccountUser, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def delete_users_of_any_audience(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {'namespace': 'string', 'payload': 'Object', 'session': 'Object'} enums = {} request = FacebookRequest(node_id=self['id'], method='DELETE', endpoint='/usersofanyaudience', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() def get_value_adjustment_rules(self, fields=None, params=None, batch=None, success=None, failure=None, pending=False): from facebook_business.utils import api_utils if ((batch is None) and ((success is not None) or (failure is not None))): api_utils.warning('`success` and `failure` callback only work for batch call.') param_types = {} enums = {} request = FacebookRequest(node_id=self['id'], method='GET', endpoint='/value_adjustment_rules', api=self._api, param_checker=TypeChecker(param_types, enums), target_class=AbstractCrudObject, api_type='EDGE', response_parser=ObjectParser(target_class=AbstractCrudObject, api=self._api)) request.add_params(params) request.add_fields(fields) if (batch is not None): request.add_to_batch(batch, success=success, failure=failure) return request elif pending: return request else: self.assure_call() return request.execute() _field_types = {'account_id': 'string', 'account_status': 'unsigned int', 'ad_account_promotable_objects': 'AdAccountPromotableObjects', 'age': 'float', 'agency_client_declaration': 'AgencyClientDeclaration', 'all_capabilities': 'list<string>', 'amount_spent': 'string', 'attribution_spec': 'list<AttributionSpec>', 'balance': 'string', 'business': 'Business', 'business_city': 'string', 'business_country_code': 'string', 'business_name': 'string', 'business_state': 'string', 'business_street': 'string', 'business_street2': 'string', 'business_zip': 'string', 'can_create_brand_lift_study': 'bool', 'capabilities': 'list<string>', 'created_time': 'datetime', 'currency': 'string', 'custom_audience_info': 'CustomAudienceGroup', 'default_dsa_beneficiary': 'string', 'default_dsa_payor': 'string', 'disable_reason': 'unsigned int', 'end_advertiser': 'string', 'end_advertiser_name': 'string', 'existing_customers': 'list<string>', 'extended_credit_invoice_group': 'ExtendedCreditInvoiceGroup', 'failed_delivery_checks': 'list<DeliveryCheck>', 'fb_entity': 'unsigned int', 'funding_source': 'string', 'funding_source_details': 'FundingSourceDetails', 'has_migrated_permissions': 'bool', 'has_page_authorized_adaccount': 'bool', 'id': 'string', 'io_number': 'string', 'is_attribution_spec_system_default': 'bool', 'is_direct_deals_enabled': 'bool', 'is_in_3ds_authorization_enabled_market': 'bool', 'is_notifications_enabled': 'bool', 'is_personal': 'unsigned int', 'is_prepay_account': 'bool', 'is_tax_id_required': 'bool', 'liable_address': 'CRMAddress', 'line_numbers': 'list<int>', 'media_agency': 'string', 'min_campaign_group_spend_cap': 'string', 'min_daily_budget': 'unsigned int', 'name': 'string', 'offsite_pixels_tos_accepted': 'bool', 'owner': 'string', 'owner_business': 'Business', 'partner': 'string', 'rf_spec': 'ReachFrequencySpec', 'send_bill_to_address': 'CRMAddress', 'show_checkout_experience': 'bool', 'sold_to_address': 'CRMAddress', 'spend_cap': 'string', 'tax_id': 'string', 'tax_id_status': 'unsigned int', 'tax_id_type': 'string', 'timezone_id': 'unsigned int', 'timezone_name': 'string', 'timezone_offset_hours_utc': 'float', 'tos_accepted': 'map<string, int>', 'user_access_expire_time': 'datetime', 'user_tasks': 'list<string>', 'user_tos_accepted': 'map<string, int>', 'viewable_business': 'Business'} def _get_field_enum_info(cls): field_enum_info = {} field_enum_info['Currency'] = AdAccount.Currency.__dict__.values() field_enum_info['Tasks'] = AdAccount.Tasks.__dict__.values() field_enum_info['ClaimObjective'] = AdAccount.ClaimObjective.__dict__.values() field_enum_info['ContentType'] = AdAccount.ContentType.__dict__.values() field_enum_info['Subtype'] = AdAccount.Subtype.__dict__.values() field_enum_info['ActionSource'] = AdAccount.ActionSource.__dict__.values() return field_enum_info
def sortino_ratio(exp_return: FLOAT, downs_risk: FLOAT, risk_free_rate: FLOAT=0.005) -> FLOAT: type_validation(expected_return=exp_return, downside_risk=downs_risk, risk_free_rate=risk_free_rate) if (float(downs_risk) == 0): return np.nan else: return ((exp_return - risk_free_rate) / float(downs_risk))
class OptScale(Options): def name(self): return self._config_get() def name(self, text): self._config(text) def type(self): return self._config_get() def type(self, text): self._config(text) def domainMax(self): return self._config_get() def domainMax(self, num): self._config(num) def domainMin(self): return self._config_get() def domainMin(self, num): self._config(num) def domainMid(self): return self._config_get() def domainMid(self, num): self._config(num) def interpolate(self): return self._config_get() def interpolate(self, text): self._config(text) def reverse(self): return self._config_get() def reverse(self, flag): self._config(flag) def range(self): return self._config_get() def range(self, value): self._config(value) def round(self): return self._config_get() def round(self, flag): self._config(flag) def clamp(self): return self._config_get() def clamp(self, flag): self._config(flag) def padding(self): return self._config_get() def padding(self, num): self._config(num) def nice(self): return self._config_get() def nice(self, num): self._config(num) def zero(self): return self._config_get() def zero(self, flag): self._config(flag)
class TestPathlibGlobmatch(): cases = [['some/*/*/match', 'some/path/to/match', True, pathlib.G], ['some/**/match', 'some/path/to/match', False], ['some/**/match', 'some/path/to/match', True, pathlib.G], ['some/**/match/', 'some/path/to/match/', False, pathlib.G], ['.', '.', True], ['.', '', True], ['some/*/*/match', 'some/path/to/match', True, pathlib.G, 'pure'], ['some/**/match', 'some/path/to/match', False, 0, 'pure'], ['some/**/match', 'some/path/to/match', True, pathlib.G, 'pure'], ['some/**/match/', 'some/path/to/match/', False, pathlib.G, 'pure'], ['.', '.', True, 0, 'pure'], ['.', '', True, 0, 'pure'], ['//?/C:/**/file.log', '\\\\?\\C:\\Path\\path\\file.log', True, pathlib.G, 'windows'], ['/usr/*/bin', '/usr/local/bin', True, pathlib.G, 'unix']] def setup_class(cls): cls.flags = ((pathlib.NEGATE | pathlib.EXTGLOB) | pathlib.BRACE) def evaluate(cls, case): pattern = case[0] name = case[1] goal = case[2] flags = cls.flags path = None platform = 'auto' if (len(case) > 3): flags ^= case[3] if (len(case) > 4): if (case[4] == 'windows'): path = pathlib.PureWindowsPath(name) platform = case[4] elif (case[4] == 'unix'): path = pathlib.PurePosixPath(name) platform = case[4] elif (case[4] == 'pure'): path = pathlib.PurePath(name) if (path is None): path = pathlib.Path(name) print('PATH: ', str(path)) print('PATTERN: ', pattern) print('FILE: ', name) print('GOAL: ', goal) print('FLAGS: ', bin(flags)) print('Platform: ', platform) cls.run(path, pattern, flags, goal) def run(cls, path, pattern, flags, goal): assert (path.globmatch(pattern, flags=flags) == goal), ('Expression did not evaluate as %s' % goal) .parametrize('case', cases) def test_cases(self, case): self.evaluate(case)
def create_range_iter(arg: Dict[(str, Any)]): def create_tensor(attr: Dict[(str, Any)]): logger.debug(f'{attr}') result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) for (key, val) in attr.items(): if (key in ranges): result[key] = arg_factory_iter[key](val) else: result[key] = val return TableProduct(result) return result def create_float(attr: Dict[(str, Any)]): return copy.copy(attr) def create_int(attr: Dict[(str, Any)]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): result['value'] = full_range(*attr['value']) return TableProduct(result) return result def create_str(attr: Dict[(str, Any)]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): result['value'] = IterableList(attr['value']) return TableProduct(result) return result def create_bool(attr: Dict[(str, Any)]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): result['value'] = IterableList(attr['value']) return TableProduct(result) return result def create_none(attr: Dict[(str, Any)]): return copy.copy(attr) def create_dtype(values: List[str]): return IterableList(values) def create_shape(values: List[Any]): shape = [] for val in values: if (type(val) is list): shape.append(full_range(*val)) else: shape.append(val) return ListProduct(shape) def create_device(attr: Dict[(str, Any)]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): result['value'] = IterableList(attr['value']) return TableProduct(result) return result def create_genericlist(attr: List[Any]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): values = [] for item in attr['value']: values.append(arg_factory_iter[item['type']](item)) result['value'] = ListProduct(values) return TableProduct(result) return result def create_tuple(attr: List[Any]): result = copy.copy(attr) if (ATTR_RANGE in attr): ranges = set(attr[ATTR_RANGE]) if ('value' in ranges): values = [] for item in attr['value']: values.append(arg_factory_iter[item['type']](item)) result['value'] = ListProduct(values) return TableProduct(result) return result arg_factory_iter: Dict[(str, Callable)] = {'tensor': create_tensor, 'float': create_float, 'double': create_float, 'int': create_int, 'long': create_int, 'str': create_str, 'none': create_none, 'bool': create_bool, 'dtype': create_dtype, 'shape': create_shape, 'device': create_device, 'genericlist': create_genericlist, 'tuple': create_tuple} return arg_factory_iter[arg['type']](arg)
_admin_required def LocationEditPages(request, location_slug): location = get_object_or_404(Location, slug=location_slug) if (request.method == 'POST'): action = request.POST['action'] logger.debug(('action=%s' % action)) logger.debug(request.POST) if ('Add Menu' == action): try: menu = request.POST['menu'].strip().title() if (menu and (not (LocationMenu.objects.filter(location=location, name=menu).count() > 0))): LocationMenu.objects.create(location=location, name=menu) except Exception as e: messages.add_message(request, messages.ERROR, ('Could not create menu: %s' % e)) elif (('Delete Menu' == action) and ('menu_id' in request.POST)): try: menu = LocationMenu.objects.get(pk=request.POST['menu_id']) menu.delete() except Exception as e: messages.add_message(request, messages.ERROR, ('Could not delete menu: %s' % e)) elif (('Save Changes' == action) and ('page_id' in request.POST)): try: page = LocationFlatPage.objects.get(pk=request.POST['page_id']) menu = LocationMenu.objects.get(pk=request.POST['menu']) page.menu = menu page.save() url_slug = request.POST['slug'].strip().lower() page.flatpage.url = ('/locations/%s/%s/' % (location.slug, url_slug)) page.flatpage.title = request.POST['title'] page.flatpage.content = request.POST['content'] page.flatpage.save() messages.add_message(request, messages.INFO, 'The page was updated.') except Exception as e: messages.add_message(request, messages.ERROR, ('Could not edit page: %s' % e)) elif (('Delete Page' == action) and ('page_id' in request.POST)): logger.debug('in Delete Page') try: page = LocationFlatPage.objects.get(pk=request.POST['page_id']) page.delete() messages.add_message(request, messages.INFO, 'The page was deleted') except Exception as e: messages.add_message(request, messages.ERROR, ('Could not delete page: %s' % e)) elif ('Create Page' == action): try: menu = LocationMenu.objects.get(pk=request.POST['menu']) url_slug = request.POST['slug'].strip().lower() url = ('/locations/%s/%s/' % (location.slug, url_slug)) if ((not url_slug) or (FlatPage.objects.filter(url=url).count() != 0)): raise Exception(('Invalid slug (%s)' % url_slug)) flatpage = FlatPage.objects.create(url=url, title=request.POST['title'], content=request.POST['content']) flatpage.sites.add(Site.objects.get_current()) LocationFlatPage.objects.create(menu=menu, flatpage=flatpage) except Exception as e: messages.add_message(request, messages.ERROR, ('Could not edit page: %s' % e)) menus = location.get_menus() new_page_form = LocationPageForm(location=location) page_forms = {} for page in LocationFlatPage.objects.filter(menu__location=location): form = LocationPageForm(location=location, initial={'menu': page.menu, 'slug': page.slug, 'title': page.title, 'content': page.content}) page_forms[page] = form return render(request, 'location_edit_pages.html', {'page': 'pages', 'location': location, 'menus': menus, 'page_forms': page_forms, 'new_page_form': new_page_form})
class TerminalFormats(QObject): default_color = QColor('#FFFAFA') default_bg = QColor('#010101') re_code = re.compile('\\x1B\\[(?P<code>.*?)m') def __init__(self, parent=None): QObject.__init__(self, parent) self.current_format = QTextCharFormat() self.current_format.setForeground(self.default_color) self.formats = {} self.formats[0] = {'setForeground': self.default_color, 'setBackground': self.default_bg, 'setFontWeight': QFont.Normal, 'setFontItalic': False, 'setFontUnderline': False} self.formats[1] = {'setFontWeight': QFont.Bold} self.formats[2] = {'setFontWeight': QFont.Light} self.formats[3] = {'setFontItalic': True} self.formats[4] = {'setFontUnderline': True, 'setUnderlineStyle': QTextCharFormat.SingleUnderline} self.formats[5] = {'setFontWeight': QFont.Bold} self.formats[6] = {'setFontWeight': QFont.Black} self.formats[7] = {'setForeground': ('background',), 'setBackground': ('foreground',)} self.formats[8] = {'setForeground': ('background',)} self.formats[9] = {'setFontStrikeOut': True} self.formats[10] = {'setFont': QTextCharFormat().font()} self.formats[11] = {'setFont': ('font_style', 0)} self.formats[12] = {'setFont': ('font_style', 1)} self.formats[13] = {'setFont': ('font_style', 2)} self.formats[14] = {'setFont': ('font_style', 3)} self.formats[15] = {'setFont': ('font_style', 4)} self.formats[16] = {'setFont': ('font_style', 5)} self.formats[17] = {'setFont': ('font_style', 6)} self.formats[18] = {'setFont': ('font_style', 7)} self.formats[19] = {'setFont': ('font_style', 8)} self.formats[21] = {'setFontWeight': QFont.Normal} self.formats[22] = {'setFontWeight': QFont.Normal} self.formats[23] = {'setFontItalic': False} self.formats[24] = {'setFontUnderline': False, 'setUnderlineStyle': QTextCharFormat.NoUnderline} self.formats[25] = {'setFontWeight': QFont.Normal} self.formats[27] = {'setBackground': ('foreground',), 'setForeground': ('background',)} self.formats[28] = {'setForeground': ('foreground',), 'setBackground': ('background',)} self.formats[29] = {'setFontStrikeOut': False} self.formats[30] = {'setForeground': QColor(1, 1, 1)} self.formats[31] = {'setForeground': QColor(222, 56, 43)} self.formats[32] = {'setForeground': QColor(57, 181, 74)} self.formats[33] = {'setForeground': QColor(255, 199, 6)} self.formats[34] = {'setForeground': QColor(0, 111, 184)} self.formats[35] = {'setForeground': QColor(118, 38, 113)} self.formats[36] = {'setForeground': QColor(44, 181, 233)} self.formats[37] = {'setForeground': QColor(204, 204, 204)} self.formats[39] = {'setForeground': self.default_color} self.formats[90] = {'setForeground': QColor(128, 128, 128)} self.formats[91] = {'setForeground': QColor(255, 0, 0)} self.formats[92] = {'setForeground': QColor(0, 255, 0)} self.formats[93] = {'setForeground': QColor(255, 255, 0)} self.formats[94] = {'setForeground': QColor(0, 0, 255)} self.formats[95] = {'setForeground': QColor(255, 0, 255)} self.formats[96] = {'setForeground': QColor(0, 255, 255)} self.formats[97] = {'setForeground': QColor(255, 255, 255)} self.formats[40] = {'setBackground': QColor(1, 1, 1)} self.formats[41] = {'setBackground': QColor(222, 56, 43)} self.formats[42] = {'setBackground': QColor(57, 181, 74)} self.formats[43] = {'setBackground': QColor(255, 199, 6)} self.formats[44] = {'setBackground': QColor(0, 111, 184)} self.formats[45] = {'setBackground': QColor(118, 38, 113)} self.formats[46] = {'setBackground': QColor(44, 181, 233)} self.formats[47] = {'setBackground': QColor(204, 204, 204)} self.formats[49] = {'setBackground': self.default_bg} self.formats[100] = {'setBackground': QColor(128, 128, 128)} self.formats[101] = {'setBackground': QColor(255, 0, 0)} self.formats[102] = {'setBackground': QColor(0, 255, 0)} self.formats[103] = {'setBackground': QColor(255, 255, 0)} self.formats[104] = {'setBackground': QColor(0, 0, 255)} self.formats[105] = {'setBackground': QColor(255, 0, 255)} self.formats[106] = {'setBackground': QColor(0, 255, 255)} self.formats[107] = {'setBackground': QColor(255, 255, 255)} def _update_format(self, fmt, updates={}, font_helper=None): for (attr, args) in updates.items(): try: if isinstance(args, list): getattr(fmt, attr)(*args) elif isinstance(args, tuple): if (font_helper is not None): if (len(attr) > 1): getattr(fmt, attr)(getattr(font_helper, attr[0])(attr[1])) else: getattr(fmt, attr)(getattr(font_helper, attr[0])()) else: getattr(fmt, attr)(args) except AttributeError: pass def insert_formated(self, cursor, text, char_format=None): cursor.beginEditBlock() current_char_format = char_format if (current_char_format is None): current_char_format = cursor.charFormat() cidx = 0 for match in self.re_code.finditer(text): code = (- 1) try: code = int(match.group(1)) except Exception: pass cursor.insertText(text[cidx:match.start()], current_char_format) if (code in self.formats): try: font_helper = FormatHelper(current_char_format) self._update_format(current_char_format, self.formats[code], font_helper=font_helper) except Exception as err: rospy.logwarn(('Failed update format for ANSI_escape_code %d: %s' % (code, err))) cidx = match.end() cursor.insertText(text[cidx:], current_char_format) cursor.movePosition(QTextCursor.End) cursor.setCharFormat(current_char_format) cursor.endEditBlock() return current_char_format
def get_single_mur(mur_no): with db.engine.connect() as conn: rs = conn.execute(SINGLE_MUR, mur_no) row = rs.first() if (row is not None): mur_id = row['mur_id'] mur = {'type': get_es_type(), 'doc_id': 'mur_{0}'.format(row['mur_no']), 'no': row['mur_no'], 'case_serial': row['mur_id'], 'url': '/legal/matter-under-review/{0}/'.format(row['mur_no']), 'mur_type': 'archived', 'mur_name': row['mur_name'], 'open_date': row['open_date'], 'close_date': row['close_date']} mur['complainants'] = get_complainants(mur_id) mur['respondents'] = get_respondents(mur_id) mur['citations'] = get_citations_arch_mur(mur_id) mur['subject'] = get_subjects(mur_id) mur['documents'] = get_documents(mur_id) return mur else: logger.error('Not a valid archived mur number.') return None
class OptionSeriesScatterSonificationContexttracksMappingRate(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._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
def test_new_message_user(session): data = {'attachments': [], 'body': 'test', 'irisSeqId': '1111111', 'irisTags': ['DeltaNewMessage'], 'messageMetadata': {'actorFbId': '1234', 'folderId': {'systemFolderId': 'INBOX'}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', 'skipBumpThread': False, 'skipSnippetUpdate': False, 'tags': ['source:messenger:web'], 'threadKey': {'otherUserFbId': '1234'}, 'threadReadStateEffect': 'KEEP_AS_IS', 'timestamp': ''}, 'requestContext': {'apiArgs': {}}, 'class': 'NewMessage'} assert (MessageEvent(author=User(session=session, id='1234'), thread=User(session=session, id='1234'), message=MessageData(thread=User(session=session, id='1234'), id='mid.$XYZ', author='1234', text='test', created_at=datetime.datetime(2020, 9, 13, 12, 26, 40, tzinfo=datetime.timezone.utc)), at=datetime.datetime(2020, 9, 13, 12, 26, 40, tzinfo=datetime.timezone.utc)) == parse_delta(session, data))
class ProxyPopupButton(Gtk.Frame): __gtype_name__ = 'ProxyPopupButton' def __init__(self, *args, **kwargs): super(ProxyPopupButton, self).__init__(*args, **kwargs) self._delegate = None def controller(self): if self._delegate: return self._delegate.controller def controller(self, controller): if self._delegate: self.remove(self._delegate) if (len(controller.options) < 25): self._delegate = PopupButton() else: self._delegate = ListViewButton() self._delegate.set_visible(True) self._delegate.set_has_tooltip(True) self._delegate.set_can_focus(False) self._delegate.controller = controller self.add(self._delegate)
def nthSiblingOfView(view, n): subviews = subviewsOfView(superviewOfView(view)) numViews = fb.evaluateIntegerExpression((('[(id)' + subviews) + ' count]')) idx = fb.evaluateIntegerExpression((((('[(id)' + subviews) + ' indexOfObject:') + view) + ']')) newIdx = (idx + n) while (newIdx < 0): newIdx += numViews newIdx = (newIdx % numViews) return fb.evaluateObjectExpression((((('[(id)' + subviews) + ' objectAtIndex:') + str(newIdx)) + ']'))
('rocm.fused_elementwise.gen_function') def fused_elementwise_gen_function(func_attrs: Dict[(str, Any)]) -> str: custom_libs = Target.current().get_custom_libs(os.path.dirname(__file__), 'custom_math.h') return elementwise_common.fused_elementwise_gen_function(func_attrs=func_attrs, custom_libs=custom_libs, head_template=HEAD_TEMPLATE, backend_spec=ROCMSpec())
class FaceAttributes(BaseModel): headwear: Optional[float] frontal_gaze: Optional[float] eyes_visible: Optional[float] glasses: Optional[float] mouth_open: Optional[float] smiling: Optional[float] brightness: Optional[float] sharpness: Optional[float] pose: VideoFacePoses
class Migration(migrations.Migration): dependencies = [('django_etebase', '0032_auto__1409')] operations = [migrations.AddField(model_name='collection', name='uid', field=models.CharField(db_index=True, max_length=43, null=True, validators=[django.core.validators.RegexValidator(message='Not a valid UID', regex='^[a-zA-Z0-9\\-_]{20,}$')]))]
def unregisterReinitialisationCallback(callback): with _reinitialisation_lock: try: _reinitialisation_callbacks.remove(callback) except ValueError: _logger.error('Callback {!r} is not registered'.format(callback)) return False else: _logger.debug('Unregistered reinitialisation {!r}'.format(callback)) return True
def _filter_schema(schema, schema_tables, exclude_table_columns): tables = {} for (tbl_name, tbl_data) in schema['tables'].items(): if ((not schema_tables) or (tbl_name in schema_tables)): columns = {} exclude_columns = exclude_table_columns.get(tbl_name, []) for (col_name, col_data) in tbl_data['columns'].items(): if (col_name in exclude_columns): continue type_ = col_data.get('type') if type_: if (type_ and isinstance(type_, dict)): key = type_.get('key') if (key and isinstance(key, dict)): ref_tbl = key.get('refTable') if (ref_tbl and isinstance(ref_tbl, six.string_types)): if (ref_tbl not in schema_tables): continue value = type_.get('value') if (value and isinstance(value, dict)): ref_tbl = value.get('refTable') if (ref_tbl and isinstance(ref_tbl, six.string_types)): if (ref_tbl not in schema_tables): continue columns[col_name] = col_data tbl_data['columns'] = columns tables[tbl_name] = tbl_data schema['tables'] = tables return schema
class FragmentCacheHelper(object): lifetime = 60 prefix = None def __init__(self, store, lifetime=None, prefix=None): self.store = store if (lifetime is not None): self.lifetime = lifetime if (prefix is not None): self.prefix = prefix def not_cached(self, cache_key, lifetime=None): context = sys._getframe(1).f_locals['_context'] context['_cache_key'] = cache_key key = ((self.prefix and (self.prefix + cache_key)) or cache_key) value = self.store.get(key) if value: if logger: logger.debug(('[tenjin.not_cached] %r: cached.' % (cache_key,))) context[key] = value return False else: if logger: logger.debug(('[tenjin.not_cached]: %r: not cached.' % (cache_key,))) if (key in context): del context[key] if (lifetime is None): lifetime = self.lifetime context['_cache_lifetime'] = lifetime helpers.start_capture(cache_key, _depth=2) return True def echo_cached(self): f_locals = sys._getframe(1).f_locals context = f_locals['_context'] cache_key = context.pop('_cache_key') key = ((self.prefix and (self.prefix + cache_key)) or cache_key) if (key in context): value = context.pop(key) else: value = helpers.stop_capture(False, _depth=2) lifetime = context.pop('_cache_lifetime') self.store.set(key, value, lifetime) f_locals['_buf'].append(value) def functions(self): return (self.not_cached, self.echo_cached) def cache_as(self, cache_key, lifetime=None): key = ((self.prefix and (self.prefix + cache_key)) or cache_key) _buf = sys._getframe(1).f_locals['_buf'] value = self.store.get(key) if value: if logger: logger.debug(('[tenjin.cache_as] %r: cache found.' % (cache_key,))) _buf.append(value) else: if logger: logger.debug(('[tenjin.cache_as] %r: expired or not cached yet.' % (cache_key,))) _buf_len = len(_buf) (yield None) value = ''.join(_buf[_buf_len:]) self.store.set(key, value, lifetime)
def create_template_simple(): rmap = RegisterMap() rmap.add_registers(Register('DATA', 'Data register', 0).add_bitfields(BitField(width=32, access='rw', hardware='ioe'))) rmap.add_registers(Register('CTRL', 'Control register', 4).add_bitfields(BitField(width=16, access='rw', reset=256, hardware='o'))) rmap.add_registers(Register('STATUS', 'Status register', 8).add_bitfields(BitField(width=8, access='ro', hardware='i'))) rmap.add_registers(Register('START', 'Start register', 256).add_bitfields(BitField(width=1, access='wosc', hardware='o'))) return rmap
def _get_orgs(org_type, org_codes): if (org_type == 'practice'): orgs = Practice.objects.order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter((Q(code__in=org_codes) | Q(ccg_id__in=org_codes))) elif (org_type == 'ccg'): orgs = PCT.objects.filter(org_type='CCG').order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter(code__in=org_codes) elif (org_type == 'pcn'): orgs = PCN.objects.order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter((Q(code__in=org_codes) | Q(practice__ccg_id__in=org_codes))) orgs = orgs.distinct('code') elif (org_type == 'stp'): orgs = STP.objects.order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter(code__in=org_codes) elif (org_type == 'regional_team'): orgs = RegionalTeam.objects.order_by('code').only('code', 'name') if org_codes: orgs = orgs.filter(code__in=org_codes) elif (org_type == 'all_practices'): orgs = [] else: raise ValueError('Unknown org_type: {}'.format(org_type)) return orgs
def dict_args(func): (func) def wrapped(*args, **kwargs): m = [] p = {} for q in args: if isinstance(q, dict): p.update(q) else: m.append(q) p.update(kwargs) return func(*m, **p) return wrapped
.usefixtures('use_tmpdir') .parametrize('run_path_format', ['realization-<IENS>/iter-<ITER>', 'realization-<IENS>']) .parametrize('active_realizations', [[True], [True, True], [True, False], [False], [False, True]]) def test_delete_run_path(run_path_format, active_realizations): simulation_arguments = EnsembleExperimentRunArguments(random_seed=None, active_realizations=active_realizations, current_case=None, target_case=None, start_iteration=0, iter_num=0, minimum_required_realizations=0, ensemble_size=1, stop_long_running=False) expected_remaining = [] expected_removed = [] for (iens, mask) in enumerate(active_realizations): run_path = Path(run_path_format.replace('<IENS>', str(iens)).replace('<ITER>', '0')) os.makedirs(run_path) assert run_path.exists() if (not mask): expected_remaining.append(run_path) else: expected_removed.append(run_path) share_path = Path('share') os.makedirs(share_path) model_config = ModelConfig(runpath_format_string=run_path_format) subs_list = SubstitutionList() config = MagicMock() config.model_config = model_config config.substitution_list = subs_list brm = BaseRunModel(simulation_arguments, config, None, None, None, None) brm.rm_run_path() assert (not any((path.exists() for path in expected_removed))) assert all((path.parent.exists() for path in expected_removed)) assert all((path.exists() for path in expected_remaining)) assert share_path.exists()
def getTrans(): trans = QTranslator() trans.load('./ui/kmain.qm') app.installTranslator(trans) qmNames = ['kmain.qm', 'antiFrida.qm', 'callFunction.qm', 'custom.qm', 'dump_so.qm', 'dumpAddress.qm', 'fart.qm', 'fartBin.qm', 'fdClass.qm', 'jnitrace.qm', 'natives.qm', 'patch.qm', 'port.qm', 'searchMemory.qm', 'selectPackage.qm', 'spawnAttach.qm', 'stalker.qm', 'stalkerMatch.qm', 'tuoke.qm', 'wallBreaker.qm', 'wifi.qm', 'zenTracer.qm', 'kmainForm.qm'] transList = [] for qmName in qmNames: qmPath = ('./ui/' + qmName) trans = QTranslator() trans.load(qmPath) transList.append(trans) formQmNames = ['Custom.qm', 'FartBin.qm', 'SearchMemory.qm', 'Wallbreaker.qm', 'ZenTracer.qm'] for qmName in formQmNames: qmPath = ('./forms/' + qmName) trans = QTranslator() trans.load(qmPath) transList.append(trans) return transList
class Timer(): async def _get_time(self) -> float: library = sniffio.current_async_library() if (library == 'trio'): import trio return trio.current_time() else: import asyncio return asyncio.get_event_loop().time() def sync_start(self) -> None: self.started = time.perf_counter() async def async_start(self) -> None: self.started = (await self._get_time()) def sync_elapsed(self) -> float: now = time.perf_counter() return (now - self.started) async def async_elapsed(self) -> float: now = (await self._get_time()) return (now - self.started)
class WebSocketResponse(): def __init__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable): self.scope = scope self.receive = receive self.send = send def __await__(self): return self.asgi().__await__() async def asgi(self): while True: message = (await self.receive()) message_type = message['type'].replace('.', '_') handler = getattr(self, message_type, None) if (handler is not None): (await handler(message)) if (message_type == 'websocket_disconnect'): break
('ecs_deploy.cli.get_client') def test_diff(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.diff, (TASK_DEFINITION_FAMILY_1, str(TASK_DEFINITION_REVISION_1), str(TASK_DEFINITION_REVISION_3))) assert (not result.exception) assert (result.exit_code == 0) assert ('change: containers.webserver.image' in result.output) assert ('- "webserver:123"' in result.output) assert ('+ "webserver:456"' in result.output) assert ('change: containers.webserver.command' in result.output) assert ('- "run"' in result.output) assert ('+ "execute"' in result.output) assert ('change: containers.webserver.environment.foo' in result.output) assert ('- "bar"' in result.output) assert ('+ "foobar"' in result.output) assert ('remove: containers.webserver.environment' in result.output) assert ('- empty: ' in result.output) assert ('change: containers.webserver.dockerLabels.foo' in result.output) assert ('- "bar"' in result.output) assert ('+ "foobar"' in result.output) assert ('remove: containers.webserver.dockerLabels' in result.output) assert ('- empty: ' in result.output) assert ('change: containers.webserver.secrets.baz' in result.output) assert ('- "qux"' in result.output) assert ('+ "foobaz"' in result.output) assert ('change: containers.webserver.secrets.dolor' in result.output) assert ('- "sit"' in result.output) assert ('+ "loremdolor"' in result.output) assert ('change: role_arn' in result.output) assert ('- "arn:test:role:1"' in result.output) assert ('+ "arn:test:another-role:1"' in result.output) assert ('change: execution_role_arn' in result.output) assert ('- "arn:test:role:1"' in result.output) assert ('+ "arn:test:another-role:1"' in result.output) assert ('add: containers.webserver.environment' in result.output) assert ('+ newvar: "new value"' in result.output) assert ('add: containers.webserver.dockerLabel' in result.output) assert ('+ newlabel: "new value"' in result.output)
class DriftStatsField(MetricResult): class Config(): dict_exclude_fields = {'characteristic_examples', 'characteristic_words', 'correlations'} field_tags = {'characteristic_examples': {IncludeTags.Render}, 'characteristic_words': {IncludeTags.Render}, 'correlations': {IncludeTags.Render}, 'type': {IncludeTags.TypeField}} pd_include = False distribution: Optional[Distribution] characteristic_examples: Optional[Examples] characteristic_words: Optional[Words] small_distribution: Optional[DistributionIncluded] correlations: Optional[Dict[(str, float)]]
def extractZelskytranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Reverend Insanity', 'Reverend Insanity', 'translated')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) titlemap = [('Reverend Insanity Chapter', 'Reverend Insanity', 'translated'), ('Mysterious Hidden Journey Chapter', 'Mysterious Hidden Journey', 'translated'), ('Necromancers Guide To Magic Chapter ', "Necromancer's Guide To Magic", 'translated')] for (titlecomponent, name, tl_type) in titlemap: if (titlecomponent.lower() in item['title'].lower()): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class JsHtmlTabs(JsHtml.JsHtml): def __getitem__(self, i: int): return JsHtmlPanel(self, component=self.component, js_code=("%s.firstChild.querySelector('div:nth-child('+ (parseInt(%s)+1) + ')')" % (self.varId, i)), page=self.page) def add_tab(self, name: str): return JsFncs.JsFunctions([JsObjects.JsNodeDom.JsDoms.new('div', js_code='new_table'), JsObjects.JsNodeDom.JsDoms.new('div', js_code='new_table_content'), JsObjects.JsNodeDom.JsDoms.get('new_table').css({'width': '100px', 'display': 'inline-block', 'vertical-align': 'middle', 'box-sizing': 'border-box', 'text-align': 'left'}), JsObjects.JsNodeDom.JsDoms.get('new_table_content').innerText(name), JsObjects.JsNodeDom.JsDoms.get('new_table_content').setAttribute('name', self.component.tabs_name), JsObjects.JsNodeDom.JsDoms.get('new_table_content').css({'width': '100px'}), JsObjects.JsNodeDom.JsDoms.get('new_table_content').css(self.component.options.css_tab), JsObjects.JsNodeDom.JsDoms.get('new_table_content').css({'padding': '5px 0'}), JsObjects.JsNodeDom.JsDoms.get('new_table').appendChild(JsObjects.JsObjects.get('new_table_content')), JsObjects.JsNodeDom.JsDoms.new('div', js_code='tab_container'), self.querySelector('div').appendChild(JsObjects.JsObjects.get('new_table'))]) def tab(self, i: int): return JsObjects.JsNodeDom.JsDoms.get(("%s.firstChild.querySelector('div:nth-child(%s)')" % (self.varId, (i + 1)))) def set_tab_name(self, i: int, name: Union[(str, primitives.JsDataModel)]): name = JsUtils.jsConvertData(name, None) return JsObjects.JsNodeDom.JsDoms.get(("%s.firstChild.querySelector('div:nth-child(%s)').querySelectorAll('[name=%s]')[0].innerHTML = %s" % (self.varId, (i + 1), self.component.tabs_name, name))) def selected_index(self): return JsObjects.JsObjects.get(("\n(function(node){ var selectedTab = node.querySelector('div[data-selected=true'); \n if(selectedTab == null){ return -1 }\n else{ return selectedTab.getAttribute('data-index')}\n})(%s)" % self.varId)) def selected_name(self): return JsObjects.JsObjects.get(('\n(function(node){ var selectedTab = node.querySelector(\'div[data-selected=true\'); \n if(selectedTab == null){ return "" }\n else{ return selectedTab.innerHTML }\n})(%s)' % self.varId)) def content(self): return JsHtml.ContentFormatters(self.page, ('\n(function(node){ var selectedTab = node.querySelector(\'div[data-selected=true\'); \n if(selectedTab == null){ return ""; }\n else{ var attrVal = null;\n if(typeof selectedTab.firstChild.getAttribute !== \'undefined\'){ \n attrVal = selectedTab.firstChild.getAttribute("data-value")} \n if(attrVal != null){ return attrVal}\n else{return selectedTab.innerText}}\n})(%s)' % self.varId)) def deselect_tabs(self, name: str=None): return JsFncs.JsFunctions([self.page.js.getElementsByName(self.component.tabs_name).all([self.page.js.data.all.element.setAttribute('data-selected', False), self.page.js.getElementsByName(self.component.tabs_name).all([self.page.js.data.all.element.css(self.component.options.tab_not_clicked_style(name))])])])
class OptionsCharts(Options): def y_columns(self): return self._config_get(None) _columns.setter def y_columns(self, cols): self._config(cols) def x_axis(self): return self._config_get(None) _axis.setter def x_axis(self, col): self._config(col) def config(self) -> OptionsChartOpts: return self._config_sub_data('options', OptionsChartOpts) def data(self) -> OptionsChartData: return self._config_sub_data('data', OptionsChartData)
class BufferedQueueIterator(QueueIterator): def __init__(self, queue): super().__init__(queue) self._none = object() self._head = self._none def next(self, block=True, timeout=None): if (self._head is not self._none): item = self._head self._head = self._none return item else: return super().next(block, timeout) def has_next(self): return ((self._head is not self._none) or super().has_next()) def head(self): if (self._head is not self._none): return self._head else: item = self.next_nowait() self._head = item return self._head
def post_import_hook(): home = get_settings_folder() if (home is None): return '' filename = ((home + os.sep) + 'post_import.py') if os.path.isfile(filename): print('process {0}'.format(filename)) return _run_py_file_command(filename) else: return ''