id
int64
0
6k
code
stringlengths
4k
8k
code_compressed
null
0
#-*- coding: utf-8 -*- from vi import utils from vi.widgets import ListWidget, EditWidget from vi.priorityqueue import actionDelegateSelector, ModuleWidgetSelector from flare.i18n import translate from vi.config import conf from vi.pane import Pane from flare.button import Button class ContextAction(Button): def __init__(self, module, handler, actionName, *args, **kwargs): dsc = actionName.split(".", 3) assert dsc[0] == "context", u"Invalid definition!" mod = dsc[1] vars = dsc[2].split(",") assert mod in conf["modules"], "The module '%s' must provide an adminInfo when run in a context action" adminInfo = conf["modules"][mod] if "name" in adminInfo: title = adminInfo["name"] else: title = mod icon = adminInfo.get("icon") super(ContextAction, self).__init__(text=title, icon=icon) self.widget = None self.adminInfo = adminInfo self.contextModule = mod self.contextVariables = vars self.title = title self.filter = filter self.icon = icon self.addClass("context-%s" % self.contextModule) self["class"].extend(["bar-item","btn--small"]) self.disable() def onAttach(self): super(ContextAction, self).onAttach() self.widget = self.parent().parent() if isinstance(self.widget, ListWidget): self.widget.selectionChangedEvent.register(self) elif isinstance(self.widget, EditWidget) and self.widget.mode == "edit": self.enable() def onDetach(self): if isinstance(self.widget, ListWidget): self.widget.selectionChangedEvent.unregister(self) super(ContextAction, self).onDetach() def onSelectionChanged(self, table, selection, *args, **kwargs): if len(selection) > 0: self.enable() else: self.disable() def METHOD_NAME(self, sender=None): assert self.widget, u"This action must be attached first!" if isinstance(self.widget, ListWidget): for s in self.widget.getCurrentSelection(): self.openModule(s) elif isinstance(self.widget, EditWidget): d = self.widget.serializeForDocument() self.openModule(d) def openModule(self, data, title=None): # Generate title if title is None: for key in conf["vi.context.title.bones"]: if title := data.get(key): if isinstance(title, dict) and conf["flare.language.current"] in title: title = title[conf["flare.language.current"]] break # Merge contexts context = {} context.update(self.widget.context or {}) context.update(self.adminInfo.get("context", {})) # Evaluate context variables for var in self.contextVariables: if "=" in var: key, value = var.split("=", 1) if value[0] == "$": value = data.get(value[1:]) else: key = var value = data.get("key") context[key] = value # Open a new view for the context module conf["mainWindow"].openView( translate("{{module}} - {{name}}", module=self.title, name=title), self.adminInfo.get("icon") or "icon-edit", self.contextModule + self.adminInfo["handler"], self.contextModule, None, # is not used... data=utils.mergeDict(self.adminInfo, {"context": context}), target="popup" if self.parent().parent().isSelector else "mainNav" ) # OLD VERSION OPENS THE HANDLER DIRECTLY IN A POPUP. # # Have a handler? # assert (widgen := ModuleWidgetSelector.select(self.contextModule, self.adminInfo)) # # #print(widgen, context, utils.mergeDict(self.adminInfo, {"context": context})) # widget = widgen(self.contextModule, **utils.mergeDict(self.adminInfo, {"context": context})) # # if widget: # widget.isSelector = True # this is done so that subsequent views are stacked in Popups... # # conf["mainWindow"].stackWidget( # widget, # title=translate("{{module}} - {{name}}", module=self.title, name=title), # icon=self.adminInfo.get("icon") # ) # # else: # print("Widget could not be generated") @staticmethod def isSuitableFor(module, handler, actionName): if module is None or module not in conf["modules"].keys(): return False if not actionName.startswith("context."): return False mod = actionName.split(".", 3)[1] cuser = conf["currentUser"] return "root" in cuser["access"] or ("%s-view" % mod) in cuser["access"] actionDelegateSelector.insert(1, ContextAction.isSuitableFor, ContextAction)
null
1
from __future__ import annotations import asyncio import enum import time from functools import wraps from typing import Any, Callable, Coroutine, MutableMapping, TypeVar, Protocol from lru import LRU R = TypeVar('R') # Can't use ParamSpec due to https://github.com/python/typing/discussions/946 class CacheProtocol(Protocol[R]): METHOD_NAME: MutableMapping[str, asyncio.Task[R]] def __call__(self, *args: Any, **kwds: Any) -> asyncio.Task[R]: ... def get_key(self, *args: Any, **kwargs: Any) -> str: ... def invalidate(self, *args: Any, **kwargs: Any) -> bool: ... def invalidate_containing(self, key: str) -> None: ... def get_stats(self) -> tuple[int, int]: ... class ExpiringCache(dict): def __init__(self, seconds: float): self.__ttl: float = seconds super().__init__() def __verify_cache_integrity(self): # Have to do this in two steps... current_time = time.monotonic() to_remove = [k for (k, (v, t)) in self.items() if current_time > (t + self.__ttl)] for k in to_remove: del self[k] def __contains__(self, key: str): self.__verify_cache_integrity() return super().__contains__(key) def __getitem__(self, key: str): self.__verify_cache_integrity() return super().__getitem__(key) def __setitem__(self, key: str, value: Any): super().__setitem__(key, (value, time.monotonic())) class Strategy(enum.Enum): lru = 1 raw = 2 timed = 3 def METHOD_NAME( maxsize: int = 128, strategy: Strategy = Strategy.lru, ignore_kwargs: bool = False, ) -> Callable[[Callable[..., Coroutine[Any, Any, R]]], CacheProtocol[R]]: def decorator(func: Callable[..., Coroutine[Any, Any, R]]) -> CacheProtocol[R]: if strategy is Strategy.lru: _internal_cache = LRU(maxsize) _stats = _internal_cache.get_stats elif strategy is Strategy.raw: _internal_cache = {} _stats = lambda: (0, 0) elif strategy is Strategy.timed: _internal_cache = ExpiringCache(maxsize) _stats = lambda: (0, 0) def _make_key(args: tuple[Any, ...], kwargs: dict[str, Any]) -> str: # this is a bit of a cluster fuck # we do care what 'self' parameter is when we __repr__ it def _true_repr(o): if o.__class__.__repr__ is object.__repr__: return f'<{o.__class__.__module__}.{o.__class__.__name__}>' return repr(o) key = [f'{func.__module__}.{func.__name__}'] key.extend(_true_repr(o) for o in args) if not ignore_kwargs: for k, v in kwargs.items(): # note: this only really works for this use case in particular # I want to pass asyncpg.Connection objects to the parameters # however, they use default __repr__ and I do not care what # connection is passed in, so I needed a bypass. if k == 'connection' or k == 'pool': continue key.append(_true_repr(k)) key.append(_true_repr(v)) return ':'.join(key) @wraps(func) def wrapper(*args: Any, **kwargs: Any): key = _make_key(args, kwargs) try: task = _internal_cache[key] except KeyError: _internal_cache[key] = task = asyncio.create_task(func(*args, **kwargs)) return task else: return task def _invalidate(*args: Any, **kwargs: Any) -> bool: try: del _internal_cache[_make_key(args, kwargs)] except KeyError: return False else: return True def _invalidate_containing(key: str) -> None: to_remove = [] for k in _internal_cache.keys(): if key in k: to_remove.append(k) for k in to_remove: try: del _internal_cache[k] except KeyError: continue wrapper.METHOD_NAME = _internal_cache wrapper.get_key = lambda *args, **kwargs: _make_key(args, kwargs) wrapper.invalidate = _invalidate wrapper.get_stats = _stats wrapper.invalidate_containing = _invalidate_containing return wrapper # type: ignore return decorator
null
2
import logging import os import subprocess import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional from fastapi import FastAPI, HTTPException from meerkat.interactive.server import Server from meerkat.tools.utils import WeakMapping if TYPE_CHECKING: from meerkat.interactive.modification import Modification from meerkat.mixins.identifiable import IdentifiableMixin logger = logging.getLogger(__name__) @dataclass class Secrets: api_keys: Dict[str, str] = field(default_factory=dict) def add(self, api: str, api_key: str): self.api_keys[api] = api_key def get(self, api: str): try: return self.api_keys[api] except KeyError: raise HTTPException( status_code=404, detail=f"No API key found for {api}.\ Add one with `secrets.add(api, api_key)`.", ) @dataclass class LanguageModel: manifest: Any = None def set(self, client: str = "ai21", engine: str = "j1-jumbo"): from manifest import Manifest self.manifest = Manifest( client_name=client, client_connection=state.secrets.get(client), engine=engine, cache_name="sqlite", cache_connection="./logs", ) def get(self): return self.manifest @dataclass class APIInfo: api: Optional[FastAPI] port: Optional[int] server: Optional[Server] = None name: str = "localhost" shared: bool = False process: Optional[subprocess.Popen] = None _url: Optional[str] = None @property def url(self): if self._url: return self._url if self.shared: return f"http://{self.name}" return f"http://{self.name}:{self.port}" @property def docs_url(self): return f"{self.url}/docs" @property def docs(self): from IPython.display import IFrame return IFrame(self.docs_url, width=800, height=600) @dataclass class FrontendInfo: package_manager: Optional[str] port: Optional[int] name: str = "localhost" shared: bool = False process: Optional[subprocess.Popen] = None _url: Optional[str] = None @property def url(self): if self._url: return self._url if self.shared: return f"http://{self.name}" return f"http://{self.name}:{self.port}" @dataclass class Identifiables: """We maintain a separate group for each type of identifiable object. Objects in the group are identified by a unique id. """ columns: WeakMapping = field(default_factory=WeakMapping) dataframes: WeakMapping = field(default_factory=WeakMapping) pages: Mapping = field(default_factory=dict) slicebys: WeakMapping = field(default_factory=WeakMapping) aggregations: WeakMapping = field(default_factory=WeakMapping) box_operations: WeakMapping = field(default_factory=WeakMapping) components: WeakMapping = field(default_factory=WeakMapping) refs: WeakMapping = field(default_factory=WeakMapping) stores: WeakMapping = field(default_factory=WeakMapping) endpoints: WeakMapping = field(default_factory=WeakMapping) routers: WeakMapping = field(default_factory=WeakMapping) nodes: WeakMapping = field(default_factory=WeakMapping) states: WeakMapping = field(default_factory=WeakMapping) def add(self, obj: "IdentifiableMixin"): group = getattr(self, obj.identifiable_group) group[obj.id] = obj def get(self, id: str, group: str): group, group_name = getattr(self, group), group try: value = group[id] except KeyError: raise HTTPException( status_code=404, detail=f"No object in group '{group_name}' with id '{id}'", ) return value @dataclass class ModificationQueue: """A queue of modifications to be applied to a dataframe.""" queue: List["Modification"] = field(default_factory=list) # Boolean attribute that controls whether the queue is accepting new # modifications # When _ready is False, `add` will no-op _ready: bool = False def add(self, modification: "Modification"): if self._ready: logger.debug(f"Adding modification {modification} to queue.") self.queue.append(modification) return # Do nothing if not ready logger.debug(f"Modification queue not ready. Ignoring {modification}.") def clear(self) -> List["Modification"]: """Clear the modification queue, and return the old queue.""" logger.debug("Clearing modification queue.") current_queue = self.queue self.queue = [] return current_queue def METHOD_NAME(self): """Ready the queue for accepting new modifications.""" count = 0 while self._ready: # Modification queue is already in use # Wait for it to be unready logger.debug("Modification queue is already in use. Waiting...") time.sleep(0.1) count += 1 if count == 1e-3: logger.warn( "Modification queue is taking a long time to unready." "Check for deadlocks." ) self._ready = True logger.debug("Modification queue is now ready.") def unready(self): """Unready the queue for accepting new modifications.""" self._ready = False logger.debug("Modification queue is now unready.") @dataclass class ProgressQueue: """A queue of progress messages to be displayed to the user.""" queue: list = field(default_factory=list) def add(self, message: str): self.queue.append(message) def clear(self) -> list: """Clear the progress queue, and return the old queue.""" current_queue = self.queue self.queue = [] return current_queue @dataclass class GlobalState: api_info: Optional[APIInfo] = None frontend_info: Optional[FrontendInfo] = None identifiables: Identifiables = field(default_factory=Identifiables) secrets: Secrets = field(default_factory=Secrets) llm: LanguageModel = field(default_factory=LanguageModel) modification_queue: ModificationQueue = field(default_factory=ModificationQueue) progress_queue: ProgressQueue = field(default_factory=ProgressQueue) global state state = GlobalState() def add_secret(api: str, api_key: str): """Add an API key to the global state.""" state.secrets.add(api, api_key) def run_on_startup(): """Run on startup.""" frontend_url = os.environ.get("MEERKAT_FRONTEND_URL", None) if frontend_url: state.frontend_info = FrontendInfo(None, None, _url=frontend_url) api_url = os.environ.get("MEERKAT_API_URL", None) if api_url: state.api_info = APIInfo(None, None, _url=api_url) run_on_startup()
null
3
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkiot.endpoint import endpoint_data class UpdateSubscribeRelationRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Iot', '2018-01-20', 'UpdateSubscribeRelation') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_OtaEventFlag(self): return self.get_query_params().get('OtaEventFlag') def set_OtaEventFlag(self,OtaEventFlag): self.add_query_param('OtaEventFlag',OtaEventFlag) def get_DeviceTopoLifeCycleFlag(self): return self.get_query_params().get('DeviceTopoLifeCycleFlag') def set_DeviceTopoLifeCycleFlag(self,DeviceTopoLifeCycleFlag): self.add_query_param('DeviceTopoLifeCycleFlag',DeviceTopoLifeCycleFlag) def get_Type(self): return self.get_query_params().get('Type') def set_Type(self,Type): self.add_query_param('Type',Type) def get_DeviceLifeCycleFlag(self): return self.get_query_params().get('DeviceLifeCycleFlag') def set_DeviceLifeCycleFlag(self,DeviceLifeCycleFlag): self.add_query_param('DeviceLifeCycleFlag',DeviceLifeCycleFlag) def get_IotInstanceId(self): return self.get_query_params().get('IotInstanceId') def set_IotInstanceId(self,IotInstanceId): self.add_query_param('IotInstanceId',IotInstanceId) def get_DeviceStatusChangeFlag(self): return self.get_query_params().get('DeviceStatusChangeFlag') def set_DeviceStatusChangeFlag(self,DeviceStatusChangeFlag): self.add_query_param('DeviceStatusChangeFlag',DeviceStatusChangeFlag) def get_OtaVersionFlag(self): return self.get_query_params().get('OtaVersionFlag') def set_OtaVersionFlag(self,OtaVersionFlag): self.add_query_param('OtaVersionFlag',OtaVersionFlag) def get_DeviceTagFlag(self): return self.get_query_params().get('DeviceTagFlag') def set_DeviceTagFlag(self,DeviceTagFlag): self.add_query_param('DeviceTagFlag',DeviceTagFlag) def get_ConsumerGroupIdss(self): return self.get_query_params().get('ConsumerGroupIds') def set_ConsumerGroupIdss(self, ConsumerGroupIdss): for depth1 in range(len(ConsumerGroupIdss)): if ConsumerGroupIdss[depth1] is not None: self.add_query_param('ConsumerGroupIds.' + str(depth1 + 1) , ConsumerGroupIdss[depth1]) def get_ProductKey(self): return self.get_query_params().get('ProductKey') def set_ProductKey(self,ProductKey): self.add_query_param('ProductKey',ProductKey) def get_ThingHistoryFlag(self): return self.get_query_params().get('ThingHistoryFlag') def set_ThingHistoryFlag(self,ThingHistoryFlag): self.add_query_param('ThingHistoryFlag',ThingHistoryFlag) def get_FoundDeviceListFlag(self): return self.get_query_params().get('FoundDeviceListFlag') def set_FoundDeviceListFlag(self,FoundDeviceListFlag): self.add_query_param('FoundDeviceListFlag',FoundDeviceListFlag) def get_OtaJobFlag(self): return self.get_query_params().get('OtaJobFlag') def METHOD_NAME(self,OtaJobFlag): self.add_query_param('OtaJobFlag',OtaJobFlag) def get_SubscribeFlags(self): return self.get_query_params().get('SubscribeFlags') def set_SubscribeFlags(self,SubscribeFlags): self.add_query_param('SubscribeFlags',SubscribeFlags) def get_DeviceDataFlag(self): return self.get_query_params().get('DeviceDataFlag') def set_DeviceDataFlag(self,DeviceDataFlag): self.add_query_param('DeviceDataFlag',DeviceDataFlag) def get_MnsConfiguration(self): return self.get_query_params().get('MnsConfiguration') def set_MnsConfiguration(self,MnsConfiguration): self.add_query_param('MnsConfiguration',MnsConfiguration
null
4
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George # This file contains the core TaskQueue based on a pairing heap, and the core Task class. # They can optionally be replaced by C implementations. # This file is a modified version, based on the extmod in Circuitpython, for # unit testing in KMK only. from supervisor import ticks_ms from kmk.kmktime import ticks_diff cur_task = None __task_queue = None class CancelledError(BaseException): pass # pairing-heap meld of 2 heaps; O(1) def ph_meld(h1, h2): if h1 is None: return h2 if h2 is None: return h1 lt = ticks_diff(h1.ph_key, h2.ph_key) < 0 if lt: if h1.ph_child is None: h1.ph_child = h2 else: h1.ph_child_last.ph_next = h2 h1.ph_child_last = h2 h2.ph_next = None h2.ph_rightmost_parent = h1 return h1 else: h1.ph_next = h2.ph_child h2.ph_child = h1 if h1.ph_next is None: h2.ph_child_last = h1 h1.ph_rightmost_parent = h2 return h2 # pairing-heap pairing operation; amortised O(log N) def ph_pairing(child): heap = None while child is not None: n1 = child child = child.ph_next n1.ph_next = None if child is not None: n2 = child child = child.ph_next n2.ph_next = None n1 = ph_meld(n1, n2) heap = ph_meld(heap, n1) return heap # pairing-heap delete of a node; stable, amortised O(log N) def ph_delete(heap, node): if node is heap: child = heap.ph_child node.ph_child = None return ph_pairing(child) # Find parent of node parent = node while parent.ph_next is not None: parent = parent.ph_next parent = parent.ph_rightmost_parent if parent is None or parent.ph_child is None: return heap # Replace node with pairing of its children if node is parent.ph_child and node.ph_child is None: parent.ph_child = node.ph_next node.ph_next = None return heap elif node is parent.ph_child: child = node.ph_child next = node.ph_next node.ph_child = None node.ph_next = None node = ph_pairing(child) parent.ph_child = node else: n = parent.ph_child while node is not n.ph_next: n = n.ph_next if not n: return heap child = node.ph_child next = node.ph_next node.ph_child = None node.ph_next = None node = ph_pairing(child) if node is None: node = n else: n.ph_next = node node.ph_next = next if next is None: node.ph_rightmost_parent = parent parent.ph_child_last = node return heap # TaskQueue class based on the above pairing-heap functions. class TaskQueue: def __init__(self): self.heap = None def peek(self): return self.heap def METHOD_NAME(self, v, key): v.data = None v.ph_key = key v.ph_child = None v.ph_next = None self.heap = ph_meld(v, self.heap) def push_head(self, v): self.METHOD_NAME(v, ticks_ms()) def pop_head(self): v = self.heap self.heap = ph_pairing(v.ph_child) # v.ph_child = None return v def remove(self, v): self.heap = ph_delete(self.heap, v) # Task class representing a coroutine, can be waited on and cancelled. class Task: def __init__(self, coro, globals=None): self.coro = coro # Coroutine of this Task self.data = None # General data for queue it is waiting on self.state = True # None, False, True or a TaskQueue instance self.ph_key = 0 # Pairing heap self.ph_child = None # Paring heap self.ph_child_last = None # Paring heap self.ph_next = None # Paring heap self.ph_rightmost_parent = None # Paring heap def __await__(self): if not self.state: # Task finished, signal that is has been await'ed on. self.state = False elif self.state is True: # Allocated head of linked list of Tasks waiting on completion of this task. self.state = TaskQueue() return self def __next__(self): if not self.state: if self.data is None: # Task finished but has already been sent to the loop's exception handler. raise StopIteration else: # Task finished, raise return value to caller so it can continue. raise self.data else: # Put calling task on waiting queue. self.state.push_head(cur_task) # Set calling task's data to this task that it waits on, to double-link it. cur_task.data = self def done(self): return not self.state def cancel(self): # Check if task is already finished. if not self.state: return False # Can't cancel self (not supported yet). if self is cur_task: raise RuntimeError("can't cancel self") # If Task waits on another task then forward the cancel to the one it's waiting on. while isinstance(self.data, Task): self = self.data # Reschedule Task as a cancelled task. if hasattr(self.data, 'remove'): # Not on the main running queue, remove the task from the queue it's on. self.data.remove(self) __task_queue.push_head(self) elif ticks_diff(self.ph_key, ticks_ms()) > 0: # On the main running queue but scheduled in the future, so bring it forward to now. __task_queue.remove(self) __task_queue.push_head(self) self.data = CancelledError return True
null
5
#!/usr/bin/env python #/*########################################################################## # # The PyMca X-Ray Fluorescence Toolkit # # Copyright (c) 2004-2014 European Synchrotron Radiation Facility # # This file is part of the PyMca X-ray Fluorescence Toolkit developed at # the ESRF by the Software group. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # #############################################################################*/ __author__ = "V.A. Sole - ESRF Data Analysis" __contact__ = "[email protected]" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" """ This class just puts in evidence the Specfile methods called from PyMca. It can be used to wrap other formats as specile """ import os import numpy import logging _logger = logging.getLogger(__name__) class SpecFileAbstractClass(object): def __init__(self, filename): if not os.path.exists(filename): return None self.motorNames = [] def list(self): """ If there is only one scan returns 1:1 with two scans returns 1:2 """ _logger.debug("list method called") return "1:1" def __getitem__(self, item): """ Returns the scan data """ _logger.debug("__getitem__ called") return self.scandata[item] def select(self, key): """ key is of the from s.o scan number, scan order """ n = key.split(".") return self.__getitem__(int(n[0])-1) def scanno(self): """ Gives back the number of scans in the file """ return 0 def allmotors(self): return self.motorNames class SpecFileAbstractScan(object): def __init__(self, data, scantype=None, identification=None, scanheader=None, labels=None,point=True): if identification is None:identification='1.1' if scantype is None:scantype='SCAN' self.scanheader = scanheader if hasattr(data, "shape"): if len(data.shape) == 1: data.shape = -1, 1 self.__point = point if scantype == 'SCAN': (rows, cols) = data.shape if self.__point: self.__data = numpy.zeros((rows, cols +1 ), numpy.float32) self.__data[:,0] = numpy.arange(rows) * 1.0 self.__data[:,1:] = data * 1 self.__cols = cols + 1 self.labels = ['Point'] else: self.__data = numpy.zeros((rows, cols), numpy.float32) self.__data[:,0:] = data * 1 self.__cols = cols self.labels = [] else: self.__data = data if isinstance(self.__data, numpy.ndarray): (rows, cols) = data.shape else: #we have a list of MCAs rows = 0 cols = len(data) self.__cols = cols self.labels = [] self.scantype = scantype self.rows = rows if labels is None: for i in range(cols): self.labels.append('Column %d' % i) else: for label in labels: self.labels.append('%s' % label) n = identification.split(".") self.__number = int(n[0]) self.__order = int(n[1]) def alllabels(self): """ These are the labels associated to the counters """ if self.scantype == 'SCAN': return self.labels else: return [] def allmotorpos(self): return [] def cols(self): return self.__cols def METHOD_NAME(self): _logger.debug("command called") text = "" if self.scanheader is not None: if len(self.scanheader): text = self.scanheader[0] return text def data(self): return numpy.transpose(self.__data) def datacol(self,col): return self.__data[:,col] def dataline(self,line): return self.__data[line,:] def date(self): text = 'sometime' return text def fileheader(self): _logger.debug("file header called") labels = '#L ' for label in self.labels: labels += ' '+label if self.scanheader is None: if self.scantype == 'SCAN': return ['#S 1 Unknown command','#N %d' % self.cols(),labels] else: return ['#S 1 Unknown command'] else: _logger.debug("returning %s", self.scanheader) return self.scanheader def header(self,key): if key == 'S': return self.fileheader()[0] elif key == 'N':return self.fileheader()[-2] elif key == 'L':return self.fileheader()[-1] elif key == '@CALIB': output = [] if self.scanheader is None: return output for line in self.scanheader: if line.startswith(key) or\ line.startswith('#'+key): output.append(line) return output elif key == '@CTIME': # expected to send Preset Time, Live Time, Real (Elapsed) Time output = [] if self.scanheader is None: return output for line in self.scanheader: if line.startswith(key) or\ line.startswith('#'+key): output.append(line) return output elif key == "" or key == " ": return self.fileheader() elif self.scanheader is None: return [] else: output = [] for line in self.scanheader: if line.startswith("#"+key) or\ line.startswith(key): output.append(line) return output def order(self): return self.__order def number(self): return self.__number def lines(self): if self.scantype == 'SCAN': return self.rows else: return 0 def nbmca(self): if self.scantype == 'SCAN': return 0 else: return self.__cols def mca(self,number): if number <= 0: raise IndexError("Mca numbering starts at 1") elif number > self.nbmca(): raise IndexError("Only %d MCAs in file" % self.nbmca()) if hasattr(self.__data, "shape"): return self.__data[:,number-1] else: return self.__data[number-1] def test(): pass if __name__ == "__main__": test()
null
6
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkunimkt.endpoint import endpoint_data class ListSlotRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'UniMkt', '2018-12-12', 'ListSlot') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_AdSlotType(self): # String return self.get_query_params().get('AdSlotType') def set_AdSlotType(self, AdSlotType): # String self.add_query_param('AdSlotType', AdSlotType) def get_UserId(self): # String return self.get_query_params().get('UserId') def set_UserId(self, UserId): # String self.add_query_param('UserId', UserId) def get_OriginSiteUserId(self): # String return self.get_query_params().get('OriginSiteUserId') def set_OriginSiteUserId(self, OriginSiteUserId): # String self.add_query_param('OriginSiteUserId', OriginSiteUserId) def get_PageNumber(self): # Integer return self.get_query_params().get('PageNumber') def set_PageNumber(self, PageNumber): # Integer self.add_query_param('PageNumber', PageNumber) def get_MediaName(self): # String return self.get_query_params().get('MediaName') def set_MediaName(self, MediaName): # String self.add_query_param('MediaName', MediaName) def get_AppName(self): # String return self.get_query_params().get('AppName') def set_AppName(self, AppName): # String self.add_query_param('AppName', AppName) def get_AdSlotStatus(self): # String return self.get_query_params().get('AdSlotStatus') def set_AdSlotStatus(self, AdSlotStatus): # String self.add_query_param('AdSlotStatus', AdSlotStatus) def get_TenantId(self): # String return self.get_query_params().get('TenantId') def set_TenantId(self, TenantId): # String self.add_query_param('TenantId', TenantId) def get_AdSlotId(self): # String return self.get_query_params().get('AdSlotId') def set_AdSlotId(self, AdSlotId): # String self.add_query_param('AdSlotId', AdSlotId) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_AdSlotCorporateStatus(self): # String return self.get_query_params().get('AdSlotCorporateStatus') def set_AdSlotCorporateStatus(self, AdSlotCorporateStatus): # String self.add_query_param('AdSlotCorporateStatus', AdSlotCorporateStatus) def get_EndCreateTime(self): # Long return self.get_query_params().get('EndCreateTime') def set_EndCreateTime(self, EndCreateTime): # Long self.add_query_param('EndCreateTime', EndCreateTime) def get_Business(self): # String return self.get_query_params().get('Business') def set_Business(self, Business): # String self.add_query_param('Business', Business) def get_MediaId(self): # String return self.get_query_params().get('MediaId') def set_MediaId(self, MediaId): # String self.add_query_param('MediaId', MediaId) def get_Environment(self): # String return self.get_query_params().get('Environment') def METHOD_NAME(self, Environment): # String self.add_query_param('Environment', Environment) def get_StartCreateTime(self): # Long return self.get_query_params().get('StartCreateTime') def set_StartCreateTime(self, StartCreateTime): # Long self.add_query_param('StartCreateTime', StartCreateTime) def get_UserSite(self): # String return self.get_query_params().get('UserSite') def set_UserSite(self, UserSite): # String self.add_query_param('UserSite', UserSite) def get_AdSlotName(self): # String return self.get_query_params().get('AdSlotName') def set_AdSlotName(self, AdSlotName): # String self.add_query_param('AdSlotName', AdSlotName)
null
7
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class CreateLoadBalancerHTTPSListenerRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ens', '2017-11-10', 'CreateLoadBalancerHTTPSListener','ens') self.set_method('POST') def get_ListenerForward(self): # String return self.get_query_params().get('ListenerForward') def set_ListenerForward(self, ListenerForward): # String self.add_query_param('ListenerForward', ListenerForward) def get_HealthCheckTimeout(self): # Integer return self.get_query_params().get('HealthCheckTimeout') def set_HealthCheckTimeout(self, HealthCheckTimeout): # Integer self.add_query_param('HealthCheckTimeout', HealthCheckTimeout) def get_HealthCheckURI(self): # String return self.get_query_params().get('HealthCheckURI') def set_HealthCheckURI(self, HealthCheckURI): # String self.add_query_param('HealthCheckURI', HealthCheckURI) def get_HealthCheck(self): # String return self.get_query_params().get('HealthCheck') def set_HealthCheck(self, HealthCheck): # String self.add_query_param('HealthCheck', HealthCheck) def get_Cookie(self): # String return self.get_query_params().get('Cookie') def set_Cookie(self, Cookie): # String self.add_query_param('Cookie', Cookie) def get_HealthCheckMethod(self): # String return self.get_query_params().get('HealthCheckMethod') def set_HealthCheckMethod(self, HealthCheckMethod): # String self.add_query_param('HealthCheckMethod', HealthCheckMethod) def get_HealthCheckDomain(self): # String return self.get_query_params().get('HealthCheckDomain') def set_HealthCheckDomain(self, HealthCheckDomain): # String self.add_query_param('HealthCheckDomain', HealthCheckDomain) def get_RequestTimeout(self): # Integer return self.get_query_params().get('RequestTimeout') def set_RequestTimeout(self, RequestTimeout): # Integer self.add_query_param('RequestTimeout', RequestTimeout) def get_LoadBalancerId(self): # String return self.get_query_params().get('LoadBalancerId') def set_LoadBalancerId(self, LoadBalancerId): # String self.add_query_param('LoadBalancerId', LoadBalancerId) def get_HealthCheckInterval(self): # Integer return self.get_query_params().get('HealthCheckInterval') def set_HealthCheckInterval(self, HealthCheckInterval): # Integer self.add_query_param('HealthCheckInterval', HealthCheckInterval) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def METHOD_NAME(self): # Integer return self.get_query_params().get('UnhealthyThreshold') def set_UnhealthyThreshold(self, UnhealthyThreshold): # Integer self.add_query_param('UnhealthyThreshold', UnhealthyThreshold) def get_HealthyThreshold(self): # Integer return self.get_query_params().get('HealthyThreshold') def set_HealthyThreshold(self, HealthyThreshold): # Integer self.add_query_param('HealthyThreshold', HealthyThreshold) def get_Scheduler(self): # String return self.get_query_params().get('Scheduler') def set_Scheduler(self, Scheduler): # String self.add_query_param('Scheduler', Scheduler) def get_ForwardPort(self): # Integer return self.get_query_params().get('ForwardPort') def set_ForwardPort(self, ForwardPort): # Integer self.add_query_param('ForwardPort', ForwardPort) def get_CookieTimeout(self): # Integer return self.get_query_params().get('CookieTimeout') def set_CookieTimeout(self, CookieTimeout): # Integer self.add_query_param('CookieTimeout', CookieTimeout) def get_StickySessionType(self): # String return self.get_query_params().get('StickySessionType') def set_StickySessionType(self, StickySessionType): # String self.add_query_param('StickySessionType', StickySessionType) def get_ListenerPort(self): # Integer return self.get_query_params().get('ListenerPort') def set_ListenerPort(self, ListenerPort): # Integer self.add_query_param('ListenerPort', ListenerPort) def get_ServerCertificateId(self): # String return self.get_query_params().get('ServerCertificateId') def set_ServerCertificateId(self, ServerCertificateId): # String self.add_query_param('ServerCertificateId', ServerCertificateId) def get_IdleTimeout(self): # Integer return self.get_query_params().get('IdleTimeout') def set_IdleTimeout(self, IdleTimeout): # Integer self.add_query_param('IdleTimeout', IdleTimeout) def get_HealthCheckConnectPort(self): # Integer return self.get_query_params().get('HealthCheckConnectPort') def set_HealthCheckConnectPort(self, HealthCheckConnectPort): # Integer self.add_query_param('HealthCheckConnectPort', HealthCheckConnectPort) def get_HealthCheckHttpCode(self): # String return self.get_query_params().get('HealthCheckHttpCode') def set_HealthCheckHttpCode(self, HealthCheckHttpCode): # String self.add_query_param('HealthCheckHttpCode', HealthCheckHttpCode)
null
8
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksmartag.endpoint import endpoint_data class ModifyACLRuleRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Smartag', '2018-03-13', 'ModifyACLRule','smartag') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DpiGroupIdss(self): # RepeatList return self.get_query_params().get('DpiGroupIds') def set_DpiGroupIdss(self, DpiGroupIds): # RepeatList pass def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_SourcePortRange(self): # String return self.get_query_params().get('SourcePortRange') def set_SourcePortRange(self, SourcePortRange): # String self.add_query_param('SourcePortRange', SourcePortRange) def get_SourceCidr(self): # String return self.get_query_params().get('SourceCidr') def set_SourceCidr(self, SourceCidr): # String self.add_query_param('SourceCidr', SourceCidr) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_Type(self): # String return self.get_query_params().get('Type') def METHOD_NAME(self, Type): # String self.add_query_param('Type', Type) def get_DestCidr(self): # String return self.get_query_params().get('DestCidr') def set_DestCidr(self, DestCidr): # String self.add_query_param('DestCidr', DestCidr) def get_DpiSignatureIdss(self): # RepeatList return self.get_query_params().get('DpiSignatureIds') def set_DpiSignatureIdss(self, DpiSignatureIds): # RepeatList pass def get_Direction(self): # String return self.get_query_params().get('Direction') def set_Direction(self, Direction): # String self.add_query_param('Direction', Direction) def get_Policy(self): # String return self.get_query_params().get('Policy') def set_Policy(self, Policy): # String self.add_query_param('Policy', Policy) def get_AclId(self): # String return self.get_query_params().get('AclId') def set_AclId(self, AclId): # String self.add_query_param('AclId', AclId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_IpProtocol(self): # String return self.get_query_params().get('IpProtocol') def set_IpProtocol(self, IpProtocol): # String self.add_query_param('IpProtocol', IpProtocol) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_Priority(self): # Integer return self.get_query_params().get('Priority') def set_Priority(self, Priority): # Integer self.add_query_param('Priority', Priority) def get_AcrId(self): # String return self.get_query_params().get('AcrId') def set_AcrId(self, AcrId): # String self.add_query_param('AcrId', AcrId) def get_DestPortRange(self): # String return self.get_query_params().get('DestPortRange') def set_DestPortRange(self, DestPortRange): # String self.add_query_param('DestPortRange', DestPortRange) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name)
null
9
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkidaas_doraemon.endpoint import endpoint_data class VerifyUserAuthenticationRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'idaas-doraemon', '2021-05-20', 'VerifyUserAuthentication') self.set_protocol_type('https') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_LogParams(self): # String return self.get_query_params().get('LogParams') def METHOD_NAME(self, LogParams): # String self.add_query_param('LogParams', LogParams) def get_ClientExtendParamsJson(self): # String return self.get_query_params().get('ClientExtendParamsJson') def set_ClientExtendParamsJson(self, ClientExtendParamsJson): # String self.add_query_param('ClientExtendParamsJson', ClientExtendParamsJson) def get_UserId(self): # String return self.get_query_params().get('UserId') def set_UserId(self, UserId): # String self.add_query_param('UserId', UserId) def get_LogTag(self): # String return self.get_query_params().get('LogTag') def set_LogTag(self, LogTag): # String self.add_query_param('LogTag', LogTag) def get_ServerExtendParamsJson(self): # String return self.get_query_params().get('ServerExtendParamsJson') def set_ServerExtendParamsJson(self, ServerExtendParamsJson): # String self.add_query_param('ServerExtendParamsJson', ServerExtendParamsJson) def get_RequireBindHashBase64(self): # String return self.get_query_params().get('RequireBindHashBase64') def set_RequireBindHashBase64(self, RequireBindHashBase64): # String self.add_query_param('RequireBindHashBase64', RequireBindHashBase64) def get_AuthenticationContext(self): # String return self.get_query_params().get('AuthenticationContext') def set_AuthenticationContext(self, AuthenticationContext): # String self.add_query_param('AuthenticationContext', AuthenticationContext) def get_RequireChallengeBase64(self): # String return self.get_query_params().get('RequireChallengeBase64') def set_RequireChallengeBase64(self, RequireChallengeBase64): # String self.add_query_param('RequireChallengeBase64', RequireChallengeBase64) def get_AuthenticatorType(self): # String return self.get_query_params().get('AuthenticatorType') def set_AuthenticatorType(self, AuthenticatorType): # String self.add_query_param('AuthenticatorType', AuthenticatorType) def get_ClientExtendParamsJsonSign(self): # String return self.get_query_params().get('ClientExtendParamsJsonSign') def set_ClientExtendParamsJsonSign(self, ClientExtendParamsJsonSign): # String self.add_query_param('ClientExtendParamsJsonSign', ClientExtendParamsJsonSign) def get_UserSourceIp(self): # String return self.get_query_params().get('UserSourceIp') def set_UserSourceIp(self, UserSourceIp): # String self.add_query_param('UserSourceIp', UserSourceIp) def get_ApplicationExternalId(self): # String return self.get_query_params().get('ApplicationExternalId') def set_ApplicationExternalId(self, ApplicationExternalId): # String self.add_query_param('ApplicationExternalId', ApplicationExternalId)
null
10
#!/usr/bin/env python # -*- coding: utf-8 -*- """`cssmin` - A Python port of the YUI CSS compressor.""" """ Home page: https://github.com/zacharyvoase/cssmin License: BSD: https://github.com/zacharyvoase/cssmin/blob/master/LICENSE Original author: Zachary Voase Modified for inclusion into web2py by: Ross Peoples <[email protected]> """ try: from StringIO import StringIO except ImportError: from io import StringIO import re __version__ = '0.1.4' def remove_comments(css): """Remove all CSS comment blocks.""" iemac = False preserve = False comment_start = css.find("/*") while comment_start >= 0: # Preserve comments that look like `/*!...*/`. # Slicing is used to make sure we don"t get an IndexError. preserve = css[comment_start + 2:comment_start + 3] == "!" comment_end = css.find("*/", comment_start + 2) if comment_end < 0: if not preserve: css = css[:comment_start] break elif comment_end >= (comment_start + 2): if css[comment_end - 1] == "\\": # This is an IE Mac-specific comment; leave this one and the # following one alone. comment_start = comment_end + 2 iemac = True elif iemac: comment_start = comment_end + 2 iemac = False elif not preserve: css = css[:comment_start] + css[comment_end + 2:] else: comment_start = comment_end + 2 comment_start = css.find("/*", comment_start) return css def remove_unnecessary_whitespace(css): """Remove unnecessary whitespace characters.""" def pseudoclasscolon(css): """ Prevents 'p :link' from becoming 'p:link'. Translates 'p :link' into 'p ___PSEUDOCLASSCOLON___link'; this is translated back again later. """ regex = re.compile(r"(^|\})(([^\{\:])+\:)+([^\{]*\{)") match = regex.search(css) while match: css = ''.join([ css[:match.start()], match.group().replace(":", "___PSEUDOCLASSCOLON___"), css[match.end():]]) match = regex.search(css) return css css = pseudoclasscolon(css) # Remove spaces from before things. css = re.sub(r"\s+([!{};:>+\(\)\],])", r"\1", css) # If there is a `@charset`, then only allow one, and move to the beginning. css = re.sub(r"^(.*)(@charset \"[^\"]*\";)", r"\2\1", css) css = re.sub(r"^(\s*@charset [^;]+;\s*)+", r"\1", css) # Put the space back in for a few cases, such as `@media screen` and # `(-webkit-min-device-pixel-ratio:0)`. css = re.sub(r"\band\(", "and (", css) # Put the colons back. css = css.replace('___PSEUDOCLASSCOLON___', ':') # Remove spaces from after things. css = re.sub(r"([!{}:;>+\(\[,])\s+", r"\1", css) return css def remove_unnecessary_semicolons(css): """Remove unnecessary semicolons.""" return re.sub(r";+\}", "}", css) def remove_empty_rules(css): """Remove empty rules.""" return re.sub(r"[^\}\{]+\{\}", "", css) def normalize_rgb_colors_to_hex(css): """Convert `rgb(51,102,153)` to `#336699`.""" regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)") match = regex.search(css) while match: colors = map(lambda s: s.strip(), match.group(1).split(",")) hexcolor = '#%.2x%.2x%.2x' % tuple(map(int, colors)) css = css.replace(match.group(), hexcolor) match = regex.search(css) return css def condense_zero_units(css): """Replace `0(px, em, %, etc)` with `0`.""" return re.sub(r"([\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", r"\1\2", css) def condense_multidimensional_zeros(css): """Replace `:0 0 0 0;`, `:0 0 0;` etc. with `:0;`.""" css = css.replace(":0 0 0 0;", ":0;") css = css.replace(":0 0 0;", ":0;") css = css.replace(":0 0;", ":0;") # Revert `background-position:0;` to the valid `background-position:0 0;`. css = css.replace("background-position:0;", "background-position:0 0;") return css def condense_floating_points(css): """Replace `0.6` with `.6` where possible.""" return re.sub(r"(:|\s)0+\.(\d+)", r"\1.\2", css) def condense_hex_colors(css): """Shorten colors from #AABBCC to #ABC where possible.""" regex = re.compile(r"([^\"'=\s])(\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])") match = regex.search(css) while match: first = match.group(3) + match.group(5) + match.group(7) second = match.group(4) + match.group(6) + match.group(8) if first.lower() == second.lower(): css = css.replace( match.group(), match.group(1) + match.group(2) + '#' + first) match = regex.search(css, match.end() - 3) else: match = regex.search(css, match.end()) return css def METHOD_NAME(css): """Condense multiple adjacent whitespace characters into one.""" return re.sub(r"\s+", " ", css) def condense_semicolons(css): """Condense multiple adjacent semicolon characters into one.""" return re.sub(r";;+", ";", css) def wrap_css_lines(css, line_length): """Wrap the lines of the given CSS to an approximate length.""" lines = [] line_start = 0 for i, char in enumerate(css): # It's safe to break after `}` characters. if char == '}' and (i - line_start >= line_length): lines.append(css[line_start:i + 1]) line_start = i + 1 if line_start < len(css): lines.append(css[line_start:]) return '\n'.join(lines) def cssmin(css, wrap=None): css = remove_comments(css) css = METHOD_NAME(css) # A pseudo class for the Box Model Hack # (see http://tantek.com/CSS/Examples/boxmodelhack.html) css = css.replace('"\\"}\\""', "___PSEUDOCLASSBMH___") css = remove_unnecessary_whitespace(css) css = remove_unnecessary_semicolons(css) css = condense_zero_units(css) css = condense_multidimensional_zeros(css) css = condense_floating_points(css) css = normalize_rgb_colors_to_hex(css) css = condense_hex_colors(css) if wrap is not None: css = wrap_css_lines(css, wrap) css = css.replace("___PSEUDOCLASSBMH___", '"\\"}\\""') css = condense_semicolons(css) return css.strip() def main(): import optparse import sys p = optparse.OptionParser( prog="cssmin", version=__version__, usage="%prog [--wrap N]", description="""Reads raw CSS from stdin, and writes compressed CSS to stdout.""") p.add_option( '-w', '--wrap', type='int', default=None, metavar='N', help="Wrap output to approximately N chars per line.") options, args = p.parse_args() sys.stdout.write(cssmin(sys.stdin.read(), wrap=options.wrap)) if __name__ == '__main__': main()
null
11
from io import StringIO as TextIO from io import BytesIO as BytesIO from typing import Any, AnyStr, Callable, Generic, IO, List, Optional, Text, Tuple, TypeVar, Union, overload from typing_extensions import Final import sys _T = TypeVar("_T") class FDCapture(Generic[AnyStr]): def __init__(self, targetfd: int, tmpfile: Optional[IO[AnyStr]] = ..., now: bool = ..., patchsys: bool = ...) -> None: ... def start(self) -> None: ... def done(self) -> IO[AnyStr]: ... def writeorg(self, data: AnyStr) -> None: ... class StdCaptureFD: def __init__( self, out: Union[bool, IO[str]] = ..., err: Union[bool, IO[str]] = ..., mixed: bool = ..., in_: bool = ..., patchsys: bool = ..., now: bool = ..., ) -> None: ... @classmethod def call(cls, func: Callable[..., _T], *args: Any, **kwargs: Any) -> Tuple[_T, str, str]: ... def reset(self) -> Tuple[str, str]: ... def suspend(self) -> Tuple[str, str]: ... def startall(self) -> None: ... def resume(self) -> None: ... def done(self, save: bool = ...) -> Tuple[IO[str], IO[str]]: ... def readouterr(self) -> Tuple[str, str]: ... class StdCapture: def __init__( self, out: Union[bool, IO[str]] = ..., err: Union[bool, IO[str]] = ..., in_: bool = ..., mixed: bool = ..., now: bool = ..., ) -> None: ... @classmethod def call(cls, func: Callable[..., _T], *args: Any, **kwargs: Any) -> Tuple[_T, str, str]: ... def reset(self) -> Tuple[str, str]: ... def suspend(self) -> Tuple[str, str]: ... def startall(self) -> None: ... def resume(self) -> None: ... def done(self, save: bool = ...) -> Tuple[IO[str], IO[str]]: ... def readouterr(self) -> Tuple[IO[str], IO[str]]: ... # XXX: The type here is not exactly right. If f is IO[bytes] and # encoding is not None, returns some weird hybrid, not exactly IO[bytes]. def dupfile( f: IO[AnyStr], mode: Optional[str] = ..., buffering: int = ..., raising: bool = ..., encoding: Optional[str] = ..., ) -> IO[AnyStr]: ... def get_terminal_width() -> int: ... def ansi_print( text: Union[str, Text], esc: Union[Union[str, Text], Tuple[Union[str, Text], ...]], file: Optional[IO[Any]] = ..., newline: bool = ..., flush: bool = ..., ) -> None: ... def saferepr(obj, maxsize: int = ...) -> str: ... class TerminalWriter: stringio: TextIO encoding: Final[str] hasmarkup: bool def __init__(self, file: Optional[IO[str]] = ..., stringio: bool = ..., encoding: Optional[str] = ...) -> None: ... @property def fullwidth(self) -> int: ... @fullwidth.setter def fullwidth(self, value: int) -> None: ... @property def chars_on_current_line(self) -> int: ... @property def width_of_current_line(self) -> int: ... def markup( self, text: str, *, black: int = ..., red: int = ..., green: int = ..., yellow: int = ..., blue: int = ..., purple: int = ..., cyan: int = ..., white: int = ..., Black: int = ..., Red: int = ..., Green: int = ..., Yellow: int = ..., Blue: int = ..., Purple: int = ..., Cyan: int = ..., White: int = ..., bold: int = ..., light: int = ..., blink: int = ..., invert: int = ..., ) -> str: ... def sep( self, sepchar: str, title: Optional[str] = ..., fullwidth: Optional[int] = ..., *, black: int = ..., red: int = ..., green: int = ..., yellow: int = ..., blue: int = ..., purple: int = ..., cyan: int = ..., white: int = ..., Black: int = ..., Red: int = ..., Green: int = ..., Yellow: int = ..., Blue: int = ..., Purple: int = ..., Cyan: int = ..., White: int = ..., bold: int = ..., light: int = ..., blink: int = ..., invert: int = ..., ) -> None: ... def METHOD_NAME( self, msg: str, *, black: int = ..., red: int = ..., green: int = ..., yellow: int = ..., blue: int = ..., purple: int = ..., cyan: int = ..., white: int = ..., Black: int = ..., Red: int = ..., Green: int = ..., Yellow: int = ..., Blue: int = ..., Purple: int = ..., Cyan: int = ..., White: int = ..., bold: int = ..., light: int = ..., blink: int = ..., invert: int = ..., ) -> None: ... def line( self, s: str = ..., *, black: int = ..., red: int = ..., green: int = ..., yellow: int = ..., blue: int = ..., purple: int = ..., cyan: int = ..., white: int = ..., Black: int = ..., Red: int = ..., Green: int = ..., Yellow: int = ..., Blue: int = ..., Purple: int = ..., Cyan: int = ..., White: int = ..., bold: int = ..., light: int = ..., blink: int = ..., invert: int = ..., ) -> None: ... def reline( self, line: str, *, black: int = ..., red: int = ..., green: int = ..., yellow: int = ..., blue: int = ..., purple: int = ..., cyan: int = ..., white: int = ..., Black: int = ..., Red: int = ..., Green: int = ..., Yellow: int = ..., Blue: int = ..., Purple: int = ..., Cyan: int = ..., White: int = ..., bold: int = ..., light: int = ..., blink: int = ..., invert: int = ..., ) -> None: ...
null
12
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkhbase.endpoint import endpoint_data class CreateMultiZoneClusterRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'HBase', '2019-01-01', 'CreateMultiZoneCluster','hbase') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ArchVersion(self): return self.get_query_params().get('ArchVersion') def set_ArchVersion(self,ArchVersion): self.add_query_param('ArchVersion',ArchVersion) def get_ClusterName(self): return self.get_query_params().get('ClusterName') def set_ClusterName(self,ClusterName): self.add_query_param('ClusterName',ClusterName) def get_EngineVersion(self): return self.get_query_params().get('EngineVersion') def set_EngineVersion(self,EngineVersion): self.add_query_param('EngineVersion',EngineVersion) def get_LogDiskType(self): return self.get_query_params().get('LogDiskType') def set_LogDiskType(self,LogDiskType): self.add_query_param('LogDiskType',LogDiskType) def get_ResourceGroupId(self): return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self,ResourceGroupId): self.add_query_param('ResourceGroupId',ResourceGroupId) def get_PrimaryVSwitchId(self): return self.get_query_params().get('PrimaryVSwitchId') def set_PrimaryVSwitchId(self,PrimaryVSwitchId): self.add_query_param('PrimaryVSwitchId',PrimaryVSwitchId) def get_LogInstanceType(self): return self.get_query_params().get('LogInstanceType') def set_LogInstanceType(self,LogInstanceType): self.add_query_param('LogInstanceType',LogInstanceType) def get_AutoRenewPeriod(self): return self.get_query_params().get('AutoRenewPeriod') def set_AutoRenewPeriod(self,AutoRenewPeriod): self.add_query_param('AutoRenewPeriod',AutoRenewPeriod) def get_Period(self): return self.get_query_params().get('Period') def set_Period(self,Period): self.add_query_param('Period',Period) def get_LogNodeCount(self): return self.get_query_params().get('LogNodeCount') def METHOD_NAME(self,LogNodeCount): self.add_query_param('LogNodeCount',LogNodeCount) def get_SecurityIPList(self): return self.get_query_params().get('SecurityIPList') def set_SecurityIPList(self,SecurityIPList): self.add_query_param('SecurityIPList',SecurityIPList) def get_PeriodUnit(self): return self.get_query_params().get('PeriodUnit') def set_PeriodUnit(self,PeriodUnit): self.add_query_param('PeriodUnit',PeriodUnit) def get_CoreDiskType(self): return self.get_query_params().get('CoreDiskType') def set_CoreDiskType(self,CoreDiskType): self.add_query_param('CoreDiskType',CoreDiskType) def get_ArbiterZoneId(self): return self.get_query_params().get('ArbiterZoneId') def set_ArbiterZoneId(self,ArbiterZoneId): self.add_query_param('ArbiterZoneId',ArbiterZoneId) def get_ClientToken(self): return self.get_query_params().get('ClientToken') def set_ClientToken(self,ClientToken): self.add_query_param('ClientToken',ClientToken) def get_MultiZoneCombination(self): return self.get_query_params().get('MultiZoneCombination') def set_MultiZoneCombination(self,MultiZoneCombination): self.add_query_param('MultiZoneCombination',MultiZoneCombination) def get_PrimaryZoneId(self): return self.get_query_params().get('PrimaryZoneId') def set_PrimaryZoneId(self,PrimaryZoneId): self.add_query_param('PrimaryZoneId',PrimaryZoneId) def get_Engine(self): return self.get_query_params().get('Engine') def set_Engine(self,Engine): self.add_query_param('Engine',Engine) def get_StandbyVSwitchId(self): return self.get_query_params().get('StandbyVSwitchId') def set_StandbyVSwitchId(self,StandbyVSwitchId): self.add_query_param('StandbyVSwitchId',StandbyVSwitchId) def get_StandbyZoneId(self): return self.get_query_params().get('StandbyZoneId') def set_StandbyZoneId(self,StandbyZoneId): self.add_query_param('StandbyZoneId',StandbyZoneId) def get_MasterInstanceType(self): return self.get_query_params().get('MasterInstanceType') def set_MasterInstanceType(self,MasterInstanceType): self.add_query_param('MasterInstanceType',MasterInstanceType) def get_CoreNodeCount(self): return self.get_query_params().get('CoreNodeCount') def set_CoreNodeCount(self,CoreNodeCount): self.add_query_param('CoreNodeCount',CoreNodeCount) def get_LogDiskSize(self): return self.get_query_params().get('LogDiskSize') def set_LogDiskSize(self,LogDiskSize): self.add_query_param('LogDiskSize',LogDiskSize) def get_CoreInstanceType(self): return self.get_query_params().get('CoreInstanceType') def set_CoreInstanceType(self,CoreInstanceType): self.add_query_param('CoreInstanceType',CoreInstanceType) def get_CoreDiskSize(self): return self.get_query_params().get('CoreDiskSize') def set_CoreDiskSize(self,CoreDiskSize): self.add_query_param('CoreDiskSize',CoreDiskSize) def get_VpcId(self): return self.get_query_params().get('VpcId') def set_VpcId(self,VpcId): self.add_query_param('VpcId',VpcId) def get_PayType(self): return self.get_query_params().get('PayType') def set_PayType(self,PayType): self.add_query_param('PayType',PayType) def get_ArbiterVSwitchId(self): return self.get_query_params().get('ArbiterVSwitchId') def set_ArbiterVSwitchId(self,ArbiterVSwitchId): self.add_query_param('ArbiterVSwitchId',ArbiterVSwitchId
null
13
from plugin import plugin # General values for connect 4 game and board numberRows = 6 numberColumns = 7 numToWin = 4 GameBoard = [[0] * numberColumns for j in range(numberRows)] def restartBoard(): for i in range(numberRows): for j in range(numberColumns): GameBoard[i][j] = str(' ') # Function to check if the column is open def checkIfFree(c): if whatsAtPos(0, c) == ' ': return True else: return False # Function that calls all win conditions def checkForWin(c): for i in range(numberRows): if whatsAtPos(i, c) != ' ': row = i if checkHorizWin(row, c, whatsAtPos(row, c)) or checkVertWin(row, c, whatsAtPos(row, c)) \ or checkDiagWin(row, c, whatsAtPos(row, c)): return True break return False # Place token at the lowest available row in the selected column def placeToken(p, c): startIndex = numberRows - 1 stopIndex = -1 step = -1 # Loop through column to find top most available row to place token for i in range(startIndex, stopIndex, step): if whatsAtPos(i, c) == ' ': GameBoard[i][c] = str(p) break # Check for a horizontal win def checkHorizWin(r, c, p): # Temp row and col values to manipulate throughout function row = r col = c # Count matching tokens to the right. Stop when at end of board rightCounter = 0 while col < numberColumns: if whatsAtPos(row, col) == p: rightCounter += 1 else: row = r break col += 1 # Count matching tokens to the left. Stop when at end of board leftCounter = 0 col = c while col >= 0: # break if at first column if col == 0: break col -= 1 if whatsAtPos(row, col) == p: leftCounter += 1 else: break # Add left and right together to check if numToWin was reached if leftCounter + rightCounter >= numToWin: print("Congrats, player ", p, " you win horizontally!\n") return True else: return False def checkVertWin(r, c, p): winCheck = False counter = 0 if r > numberRows - numToWin: return False for i in range(r, numberRows, 1): if whatsAtPos(i, c) == p: counter += 1 else: counter = 0 if counter == numToWin: winCheck = True print("Congrats, player ", p, ", you win vertically!\n") break return winCheck def checkDiagWin(r, c, p): row = r col = c upRight = 0 while row >= 0 and col <= numberColumns: if whatsAtPos(row, col) == p: upRight += 1 else: row = r col = c break # If the column is he last column on the board, break the loop if col == numberColumns - 1 or row == 0: row = r col = c break row -= 1 col += 1 downLeft = 0 while row < numberRows - 1 and col > 0: row += 1 col -= 1 if whatsAtPos(row, col) == p: downLeft += 1 else: row = r col = c break if upRight + downLeft >= numToWin: print('Congrats! You won diagonally!') return True upLeft = 0 while row >= 0 and col >= 0: if whatsAtPos(row, col) == p: upLeft += 1 else: row = r col = c break if col == 0 or row == 0: row = r col = c break row -= 1 col -= 1 downRight = 0 while row < numberRows - 1 and col < numberColumns - 1: row += 1 col += 1 if whatsAtPos(row, col) == p: downRight += 1 else: break if downRight + upLeft >= numToWin: print("Congrats, player ", p, " you win diagonally!\n") return True return False # Function to return value of gameboard location def whatsAtPos(r, c): if not GameBoard[r][c]: return ' ' else: return str(GameBoard[r][c]) # Check to see if players tied def checkTie(): startIndex = 0 # players have not tied if there is still an empty place in the first row for i in range(startIndex, numberColumns, 1): if checkIfFree(i): return False # If there is no space left and checkForWin already passed the players tied print('Tie game! Thanks for playing!\n') return True # Function to print the gameboard def printBoard(): ss = '' startIndex = 0 # Create column headers (1-7) for i in range(startIndex, numberColumns, 1): ss += '|' ss = ss + str(i + 1) ss += '|' ss += '\n' # Create current GameBoard startIndex = 0 startIndex_j = 0 for i in range(startIndex, numberRows, 1): for j in range(startIndex_j, numberColumns, 1): ss += '|' ss = ss + str(whatsAtPos(i, j)) ss += '|' ss += '\n' print(ss) @plugin("connect_four") def METHOD_NAME(jarvis, s): # Welcome message and rules explanation print('Welcome to Connect Four! This is a two player game.\n') print('Enter numbers to place your token in the corresponding column!\n') print('Match four of your tokens in a row to win. Good Luck!\n') playerTracker = 0 playAgainFlag = 'y' while playAgainFlag == 'y': restartBoard() printBoard() while True: # Make sure column is numeric. If not then ask user for numeric input again instead of throwing error. notNumericInputFlag = True while notNumericInputFlag == True: try: column = int(input('Pick a column (1-7):\n')) notNumericInputFlag = False except ValueError: print("Enter a valid numeric input.") column -= 1 # Make sure column is inbounds while column < 0 or column > numberColumns: print('Out of bounds. Pick another column.') printBoard() column = int(input('Pick a column (1-7):\n')) column -= 1 # Make sure column is empty while not checkIfFree(column): print('Column is full. Pick another.\n') printBoard() column = int(input('Pick a column (1-7):\n')) column -= 1 # get the players turn and place token now that conditions are met if playerTracker % 2 == 0: placeToken("X", column) else: placeToken("O", column) # print updated gameboard printBoard() # Check for a win on the last move if checkForWin(column): break # Make sure no one tied with the last move if checkTie(): break # increment player tracker playerTracker += 1 playAgainFlag = input('Would you like the play again? (Y/N)\n') playAgainFlag = playAgainFlag.strip() playAgainFlag = playAgainFlag.lower() while playAgainFlag != 'n' and playAgainFlag != 'y': playAgainFlag = input('Please enter Y or N\n') playAgainFlag = playAgainFlag.strip() playAgainFlag = playAgainFlag.lower() print('Thanks for playing!\n') if __name__ == "__main__": METHOD_NAME()
null
14
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkcloudapi.endpoint import endpoint_data class CreateApiRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'CloudAPI', '2016-07-14', 'CreateApi','apigateway') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_WebSocketApiType(self): # String return self.get_query_params().get('WebSocketApiType') def set_WebSocketApiType(self, WebSocketApiType): # String self.add_query_param('WebSocketApiType', WebSocketApiType) def get_ErrorCodeSamples(self): # String return self.get_query_params().get('ErrorCodeSamples') def set_ErrorCodeSamples(self, ErrorCodeSamples): # String self.add_query_param('ErrorCodeSamples', ErrorCodeSamples) def get_AppCodeAuthType(self): # String return self.get_query_params().get('AppCodeAuthType') def set_AppCodeAuthType(self, AppCodeAuthType): # String self.add_query_param('AppCodeAuthType', AppCodeAuthType) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_DisableInternet(self): # Boolean return self.get_query_params().get('DisableInternet') def set_DisableInternet(self, DisableInternet): # Boolean self.add_query_param('DisableInternet', DisableInternet) def get_BackendId(self): # String return self.get_query_params().get('BackendId') def set_BackendId(self, BackendId): # String self.add_query_param('BackendId', BackendId) def get_ConstantParameters(self): # String return self.get_query_params().get('ConstantParameters') def METHOD_NAME(self, ConstantParameters): # String self.add_query_param('ConstantParameters', ConstantParameters) def get_AuthType(self): # String return self.get_query_params().get('AuthType') def set_AuthType(self, AuthType): # String self.add_query_param('AuthType', AuthType) def get_AllowSignatureMethod(self): # String return self.get_query_params().get('AllowSignatureMethod') def set_AllowSignatureMethod(self, AllowSignatureMethod): # String self.add_query_param('AllowSignatureMethod', AllowSignatureMethod) def get_ServiceParameters(self): # String return self.get_query_params().get('ServiceParameters') def set_ServiceParameters(self, ServiceParameters): # String self.add_query_param('ServiceParameters', ServiceParameters) def get_FailResultSample(self): # String return self.get_query_params().get('FailResultSample') def set_FailResultSample(self, FailResultSample): # String self.add_query_param('FailResultSample', FailResultSample) def get_SystemParameters(self): # String return self.get_query_params().get('SystemParameters') def set_SystemParameters(self, SystemParameters): # String self.add_query_param('SystemParameters', SystemParameters) def get_ServiceParametersMap(self): # String return self.get_query_params().get('ServiceParametersMap') def set_ServiceParametersMap(self, ServiceParametersMap): # String self.add_query_param('ServiceParametersMap', ServiceParametersMap) def get_SecurityToken(self): # String return self.get_query_params().get('SecurityToken') def set_SecurityToken(self, SecurityToken): # String self.add_query_param('SecurityToken', SecurityToken) def get_OpenIdConnectConfig(self): # String return self.get_query_params().get('OpenIdConnectConfig') def set_OpenIdConnectConfig(self, OpenIdConnectConfig): # String self.add_query_param('OpenIdConnectConfig', OpenIdConnectConfig) def get_RequestParameters(self): # String return self.get_query_params().get('RequestParameters') def set_RequestParameters(self, RequestParameters): # String self.add_query_param('RequestParameters', RequestParameters) def get_ResultDescriptions(self): # String return self.get_query_params().get('ResultDescriptions') def set_ResultDescriptions(self, ResultDescriptions): # String self.add_query_param('ResultDescriptions', ResultDescriptions) def get_Visibility(self): # String return self.get_query_params().get('Visibility') def set_Visibility(self, Visibility): # String self.add_query_param('Visibility', Visibility) def get_GroupId(self): # String return self.get_query_params().get('GroupId') def set_GroupId(self, GroupId): # String self.add_query_param('GroupId', GroupId) def get_ServiceConfig(self): # String return self.get_query_params().get('ServiceConfig') def set_ServiceConfig(self, ServiceConfig): # String self.add_query_param('ServiceConfig', ServiceConfig) def get_ResultType(self): # String return self.get_query_params().get('ResultType') def set_ResultType(self, ResultType): # String self.add_query_param('ResultType', ResultType) def get_ApiName(self): # String return self.get_query_params().get('ApiName') def set_ApiName(self, ApiName): # String self.add_query_param('ApiName', ApiName) def get_ResultSample(self): # String return self.get_query_params().get('ResultSample') def set_ResultSample(self, ResultSample): # String self.add_query_param('ResultSample', ResultSample) def get_BackendEnable(self): # Boolean return self.get_query_params().get('BackendEnable') def set_BackendEnable(self, BackendEnable): # Boolean self.add_query_param('BackendEnable', BackendEnable) def get_ForceNonceCheck(self): # Boolean return self.get_query_params().get('ForceNonceCheck') def set_ForceNonceCheck(self, ForceNonceCheck): # Boolean self.add_query_param('ForceNonceCheck', ForceNonceCheck) def get_RequestConfig(self): # String return self.get_query_params().get('RequestConfig') def set_RequestConfig(self, RequestConfig): # String self.add_query_param('RequestConfig', RequestConfig) def get_ResultBodyModel(self): # String return self.get_query_params().get('ResultBodyModel') def set_ResultBodyModel(self, ResultBodyModel): # String self.add_query_param('ResultBodyModel', ResultBodyModel)
null
15
from pathlib import Path import pytest from click.testing import CliRunner from ggshield.__main__ import cli from ggshield.verticals.hmsl.crypto import hash_string from tests.unit.conftest import assert_invoke_exited_with, assert_invoke_ok RESULTS_CONTENT = ( '{"hint": "f7f17c88638b42465b6c620a0c7648ef470e611c1fdf90166aac613601799f81", "payload": ' '"KzzhJEq/pM2RaWav9NAvjw45Gfp/26UGDDzYiDNuOCup0PfoAHNViOGX14/a7uUNWLk53zGIar3s2xOW/xxzMEgTT2owjH52gGalhwKBfTY="}\n' '{"hint": "71d27eee3aa6c1751110ea338f23a5cfe11da717ea27453e7fe09e1594c3f8e7", "payload": ' '"zmrGtuhTtgxNkk9SA250HTxXQ+mfoJQlZ76CPx50juK4XFCCTbFNv6ZeahGRQqW4+vf92DEwpGTHVzjiQEF6JebJsoRuaMQDSntHQ17z0UU="}\n' '{"hint": "f1b2fcaf134f3a08513ec6603ee3281511f349166fea5ef3356dd62051a76aa8", "payload": ' '"Qzp7zRkFeIlPhiy6VMeUyo4vaCJAFmuqDQITH4WFC1BH51eHDNcL1UOw5u8dKmBWRJMfY7Zh7atyTl++hbsYDnIItJi8LFO5Yyzj+xte+ik="}\n' '{"hint": "89740ad4cd63fa9a7637325a7bef91c0ba93d0a45bbf687beb76bacaf5fa8da3", "payload": ' '"kUlYx2lO5dOtFAM7XPT7uyk5v81ajJeg7Uepq1D4oyWQcf3ijMRThqsMrkKkUXSXHcAL182yCAgbub/NDF2wFA+Lyr5qBdb3qBBFLztfFz0="}\n' '{"hint": "3be2d605a3d143bfea373887ed16e7935be0e3c189cbee4d343c92ed6c89fdb8", "payload": ' '"GZIG82jOLH5gXB5NNJt7NyfUOQUpk720wA3LItmVrXKCIK2PursytFkg/pPtzBXyPifNZtsOaNf5an+5Pz3mVysVMoCF9dXGFt1AFRi8lXk="}\n' '{"hint": "16787b637f7787685909539f65cc100b591d8c8d1074d0e5491aab33f364c86b", "payload": ' '"4XgUM9pXWrLbQ8tH0AH7Za3u7tObAmlDXBSgwS+IE2m/NeDn3y7KF5H7yPB/faFDfKFirNiijhEfkBgfCz+FmZhDLCCzsga6hZN0S9he6EM="}\n' '{"hint": "e9ecc350e213860e9472057339443c830581c53e2b4dfb3aaa7e5fa4a854d5a3", "payload": ' '"UDIP09t3tSk2IyQhxnJmF2gaDxhOY4zgrGpOzLeakIOZEmRxlyXYfdN3uFuTutnfdT7ZY+2Am2Q0Vst0L3EfuvomNdx/yL3desUApHq5o5I="}\n' '{"hint": "31ded0b51235ebde7d5fa10685d33b95e8a20a4e284220351812ca98ed20836b", "payload": ' '"+FuUB48xvYQg1VTf1Jvyif14T8rLJETu3L0y2SJa7fJ+P7HDTDf/ESH8pLjJmadyNB3vl3t8KS3VH+lveCae53yVY66LncUCwuXVKd9s7G0="}\n' '{"hint": "19b9ba15c838c44d8965ac2300718fd8f9e2a038ff3ca7b3982fae50ec4afbfa", "payload": ' '"YKk5NCIkiS5tmab2lXO1V2mpsPbRC+vAsz+TNHroEcpo8b0YhEjy6SCUXWkYMm2mBUFz3Kmvkqqd59Pdj4EXmvqrl1yNV2LlCCoJGD91SUY="}\n' '{"hint": "23ef947812513a59de504af2e291f9bbab287b941e0551f442e63f19f979679d", "payload": ' '"0XmzWJNyq3gHbeqb5+T5xSjuwP1qFdrIbvsW4K5Spk+Yn2mfBs92Z3ipEngis2nZMNS+K99h/sh3+hvqTH5T5Z0p/YnCd2f+1E4suGEbVnA="}\n' '{"hint": "9c9e78a410131e548c733e08b1de9a3dcccbe5cda970cb6ad740655b7741e7b3", "payload": ' '"WDmh3FQvY+i5DO+6bWeOkY5J78jHBHCsEFjl9u1PEpftDS5Htzcc/dQqrzFcYvBwU+RbPLag2z/w7PBW+m472D9R1OExamCWs6MjN65j3L0="}\n' ) RESULTS_CLEARTEXT_CONTENT = ( '{"hash": "743d9fde380b7064cc6a8d3071184fc47905cf7440e5615cd46c7b6cbfb46d47", ' '"count": 14, "url": "https://github.com/edly-io/devstack/commit/ccfc9c2d63c29' '17be60a9fd2a4c36ff3a8b9bb8c#diff-e45e45baeda1c1e73482975a664062aa56f20c03dd9d64a827aba57775bed0d3L158"}' ) @pytest.fixture def mapping_path(cli_fs_runner, tmp_path: Path): """Prepare a mapping file""" mapping_path = tmp_path / "mapping.txt" secrets = ["foo", "bar", "password", "1234"] mapping = {hash_string(secret): secret for secret in secrets} mapping_path.write_text( "\n".join(f"{key}:{value}" for key, value in mapping.items()) ) return mapping_path @pytest.fixture def results_path(mapping_path: Path): """Prepare a results file""" results_path = mapping_path.parent / "results.txt" results_path.write_text(RESULTS_CONTENT) return results_path @pytest.fixture def full_hash_result(mapping_path: Path): """Prepare a results file""" results_path = mapping_path.parent / "results.txt" results_path.write_text(RESULTS_CLEARTEXT_CONTENT) return results_path @pytest.mark.parametrize( "command", [ ["hmsl", "decrypt"], ["hmsl", "decrypt", "none.txt"], ["hmsl", "decrypt", "-m", "none.txt"], ["hmsl", "decrypt", "-m", "none.txt", "void.txt"], ], ) def METHOD_NAME(cli_fs_runner: CliRunner, command) -> None: """ GIVEN a cli WHEN running on non-existing files or other issues THEN the return code is 2 """ result = cli_fs_runner.invoke(cli, command) assert_invoke_exited_with(result, 2) def test_hmsl_decrypt_default_behavior( cli_fs_runner: CliRunner, mapping_path, results_path: Path ) -> None: """ GIVEN some secrets WHEN running the decrypt command on a file THEN the secrets are correctly decrypted """ result = cli_fs_runner.invoke( cli, ["hmsl", "decrypt", "-m", str(mapping_path), str(results_path)] ) assert_invoke_ok(result) assert result.output.count("> Secret ") == 1 assert 'Secret name: "foo"' in result.output def test_hmsl_decrypt_full_hashes_behavior( cli_fs_runner: CliRunner, mapping_path, full_hash_result: Path ) -> None: """ GIVEN a some full hashes response WHEN running the decrypt command on a file THEN the command accepts the decrypted payloads seamlessly """ result = cli_fs_runner.invoke( cli, ["hmsl", "decrypt", "-m", str(mapping_path), str(full_hash_result)] ) assert_invoke_ok(result) assert result.output.count("> Secret ") == 1 assert 'Secret name: "password"' in result.output
null
16
## @file # process FD generation # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # from __future__ import absolute_import from . import Region from . import Fv import Common.LongFilePathOs as os from io import BytesIO import sys from struct import * from .GenFdsGlobalVariable import GenFdsGlobalVariable from CommonDataClass.FdfClass import FDClassObject from Common import EdkLogger from Common.BuildToolError import * from Common.Misc import SaveFileOnChange from Common.DataType import BINARY_FILE_TYPE_FV ## generate FD # # class FD(FDClassObject): ## The constructor # # @param self The object pointer # def __init__(self): FDClassObject.__init__(self) ## GenFd() method # # Generate FD # # @retval string Generated FD file name # def METHOD_NAME (self, Flag = False): if self.FdUiName.upper() + 'fd' in GenFdsGlobalVariable.ImageBinDict: return GenFdsGlobalVariable.ImageBinDict[self.FdUiName.upper() + 'fd'] # # Print Information # FdFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.FdUiName + '.fd') if not Flag: GenFdsGlobalVariable.InfLogger("\nFd File Name:%s (%s)" %(self.FdUiName, FdFileName)) Offset = 0x00 for item in self.BlockSizeList: Offset = Offset + item[0] * item[1] if Offset != self.Size: EdkLogger.error("GenFds", GENFDS_ERROR, 'FD %s Size not consistent with block array' % self.FdUiName) GenFdsGlobalVariable.VerboseLogger('Following Fv will be add to Fd !!!') for FvObj in GenFdsGlobalVariable.FdfParser.Profile.FvDict: GenFdsGlobalVariable.VerboseLogger(FvObj) HasCapsuleRegion = False for RegionObj in self.RegionList: if RegionObj.RegionType == 'CAPSULE': HasCapsuleRegion = True break if HasCapsuleRegion: TempFdBuffer = BytesIO() PreviousRegionStart = -1 PreviousRegionSize = 1 for RegionObj in self.RegionList : if RegionObj.RegionType == 'CAPSULE': continue if RegionObj.Offset + RegionObj.Size <= PreviousRegionStart: pass elif RegionObj.Offset <= PreviousRegionStart or (RegionObj.Offset >=PreviousRegionStart and RegionObj.Offset < PreviousRegionStart + PreviousRegionSize): pass elif RegionObj.Offset > PreviousRegionStart + PreviousRegionSize: if not Flag: GenFdsGlobalVariable.InfLogger('Padding region starting from offset 0x%X, with size 0x%X' %(PreviousRegionStart + PreviousRegionSize, RegionObj.Offset - (PreviousRegionStart + PreviousRegionSize))) PadRegion = Region.Region() PadRegion.Offset = PreviousRegionStart + PreviousRegionSize PadRegion.Size = RegionObj.Offset - PadRegion.Offset if not Flag: PadRegion.AddToBuffer(TempFdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFdsGlobalVariable.ImageBinDict, self.DefineVarDict) PreviousRegionStart = RegionObj.Offset PreviousRegionSize = RegionObj.Size # # Call each region's AddToBuffer function # if PreviousRegionSize > self.Size: pass GenFdsGlobalVariable.VerboseLogger('Call each region\'s AddToBuffer function') RegionObj.AddToBuffer (TempFdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFdsGlobalVariable.ImageBinDict, self.DefineVarDict) FdBuffer = BytesIO() PreviousRegionStart = -1 PreviousRegionSize = 1 for RegionObj in self.RegionList : if RegionObj.Offset + RegionObj.Size <= PreviousRegionStart: EdkLogger.error("GenFds", GENFDS_ERROR, 'Region offset 0x%X in wrong order with Region starting from 0x%X, size 0x%X\nRegions in FDF must have offsets appear in ascending order.'\ % (RegionObj.Offset, PreviousRegionStart, PreviousRegionSize)) elif RegionObj.Offset <= PreviousRegionStart or (RegionObj.Offset >=PreviousRegionStart and RegionObj.Offset < PreviousRegionStart + PreviousRegionSize): EdkLogger.error("GenFds", GENFDS_ERROR, 'Region offset 0x%X overlaps with Region starting from 0x%X, size 0x%X' \ % (RegionObj.Offset, PreviousRegionStart, PreviousRegionSize)) elif RegionObj.Offset > PreviousRegionStart + PreviousRegionSize: if not Flag: GenFdsGlobalVariable.InfLogger('Padding region starting from offset 0x%X, with size 0x%X' %(PreviousRegionStart + PreviousRegionSize, RegionObj.Offset - (PreviousRegionStart + PreviousRegionSize))) PadRegion = Region.Region() PadRegion.Offset = PreviousRegionStart + PreviousRegionSize PadRegion.Size = RegionObj.Offset - PadRegion.Offset if not Flag: PadRegion.AddToBuffer(FdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFdsGlobalVariable.ImageBinDict, self.DefineVarDict) PreviousRegionStart = RegionObj.Offset PreviousRegionSize = RegionObj.Size # # Verify current region fits within allocated FD section Size # if PreviousRegionStart + PreviousRegionSize > self.Size: EdkLogger.error("GenFds", GENFDS_ERROR, 'FD %s size too small to fit region with offset 0x%X and size 0x%X' % (self.FdUiName, PreviousRegionStart, PreviousRegionSize)) # # Call each region's AddToBuffer function # GenFdsGlobalVariable.VerboseLogger('Call each region\'s AddToBuffer function') RegionObj.AddToBuffer (FdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFdsGlobalVariable.ImageBinDict, self.DefineVarDict, Flag=Flag) # # Write the buffer contents to Fd file # GenFdsGlobalVariable.VerboseLogger('Write the buffer contents to Fd file') if not Flag: SaveFileOnChange(FdFileName, FdBuffer.getvalue()) FdBuffer.close() GenFdsGlobalVariable.ImageBinDict[self.FdUiName.upper() + 'fd'] = FdFileName return FdFileName ## generate flash map file # # @param self The object pointer # def GenFlashMap (self): pass
null
17
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkecs.endpoint import endpoint_data class DescribeSnapshotsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'DescribeSnapshots','ecs') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_Filter2Value(self): # String return self.get_query_params().get('Filter.2.Value') def set_Filter2Value(self, Filter2Value): # String self.add_query_param('Filter.2.Value', Filter2Value) def get_SnapshotIds(self): # String return self.get_query_params().get('SnapshotIds') def set_SnapshotIds(self, SnapshotIds): # String self.add_query_param('SnapshotIds', SnapshotIds) def get_Usage(self): # String return self.get_query_params().get('Usage') def METHOD_NAME(self, Usage): # String self.add_query_param('Usage', Usage) def get_SnapshotLinkId(self): # String return self.get_query_params().get('SnapshotLinkId') def set_SnapshotLinkId(self, SnapshotLinkId): # String self.add_query_param('SnapshotLinkId', SnapshotLinkId) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_Filter1Key(self): # String return self.get_query_params().get('Filter.1.Key') def set_Filter1Key(self, Filter1Key): # String self.add_query_param('Filter.1.Key', Filter1Key) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) def get_DryRun(self): # Boolean return self.get_query_params().get('DryRun') def set_DryRun(self, DryRun): # Boolean self.add_query_param('DryRun', DryRun) def get_Filter1Value(self): # String return self.get_query_params().get('Filter.1.Value') def set_Filter1Value(self, Filter1Value): # String self.add_query_param('Filter.1.Value', Filter1Value) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_InstanceId(self): # String return self.get_query_params().get('InstanceId') def set_InstanceId(self, InstanceId): # String self.add_query_param('InstanceId', InstanceId) def get_MaxResults(self): # Integer return self.get_query_params().get('MaxResults') def set_MaxResults(self, MaxResults): # Integer self.add_query_param('MaxResults', MaxResults) def get_Status(self): # String return self.get_query_params().get('Status') def set_Status(self, Status): # String self.add_query_param('Status', Status) def get_SnapshotName(self): # String return self.get_query_params().get('SnapshotName') def set_SnapshotName(self, SnapshotName): # String self.add_query_param('SnapshotName', SnapshotName) def get_PageNumber(self): # Integer return self.get_query_params().get('PageNumber') def set_PageNumber(self, PageNumber): # Integer self.add_query_param('PageNumber', PageNumber) def get_NextToken(self): # String return self.get_query_params().get('NextToken') def set_NextToken(self, NextToken): # String self.add_query_param('NextToken', NextToken) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_DiskId(self): # String return self.get_query_params().get('DiskId') def set_DiskId(self, DiskId): # String self.add_query_param('DiskId', DiskId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_SourceDiskType(self): # String return self.get_query_params().get('SourceDiskType') def set_SourceDiskType(self, SourceDiskType): # String self.add_query_param('SourceDiskType', SourceDiskType) def get_Filter2Key(self): # String return self.get_query_params().get('Filter.2.Key') def set_Filter2Key(self, Filter2Key): # String self.add_query_param('Filter.2.Key', Filter2Key) def get_Encrypted(self): # Boolean return self.get_query_params().get('Encrypted') def set_Encrypted(self, Encrypted): # Boolean self.add_query_param('Encrypted', Encrypted) def get_SnapshotType(self): # String return self.get_query_params().get('SnapshotType') def set_SnapshotType(self, SnapshotType): # String self.add_query_param('SnapshotType', SnapshotType) def get_KMSKeyId(self): # String return self.get_query_params().get('KMSKeyId') def set_KMSKeyId(self, KMSKeyId): # String self.add_query_param('KMSKeyId', KMSKeyId) def get_Category(self): # String return self.get_query_params().get('Category') def set_Category(self, Category): # String self.add_query_param('Category', Category)
null
18
import IMP import IMP.atom import IMP.pmi import IMP.test import IMP.isd import IMP.pmi.restraints.proteomics import IMP.pmi.io import IMP.pmi.restraints import IMP.pmi.restraints.basic import IMP.rmf import RMF import math import sys class MembraneRestraintPrototype(IMP.Restraint): def __init__(self, m, z_nuisance, thickness=30.0, softness=3.0, plateau=0.0000000001, linear=0.02): ''' input a list of particles, the slope and theta of the sigmoid potential theta is the cutoff distance for a protein-protein contact ''' IMP.Restraint.__init__(self, m, "MembraneRestraintPrototype_ %1%") self.set_was_used(True) self.thickness = thickness self.z_nuisance = z_nuisance self.softness = softness self.plateau = plateau self.particle_list_below = [] self.particle_list_above = [] self.particle_list_inside = [] self.max_float = sys.float_info.max self.log_max_float = math.log(self.max_float) self.linear = linear def add_particles_below(self, particles): self.particle_list_below += particles def add_particles_above(self, particles): self.particle_list_above += particles def add_particles_inside(self, particles): self.particle_list_inside += particles def score_above(self, z): argvalue = (z - self.z_slope_center_upper) / self.softness prob = (1.0 - self.plateau) / (1.0 + math.exp(-argvalue)) return -math.log(prob * self.max_float) + self.log_max_float def score_below(self, z): argvalue = (z - self.z_slope_center_lower) / self.softness prob = (1.0 - self.plateau) / (1.0 + math.exp(argvalue)) return -math.log(prob * self.max_float) + self.log_max_float def score_inside(self, z): argvalue = (z - self.z_slope_center_upper) / self.softness prob1 = 1.0 - (1.0 - self.plateau) / (1.0 + math.exp(-argvalue)) argvalue = (z - self.z_slope_center_lower) / self.softness prob2 = 1.0 - (1.0 - self.plateau) / (1.0 + math.exp(argvalue)) return (-math.log(prob1 * self.max_float) - math.log(prob2 * self.max_float) + 2 * self.log_max_float) def unprotected_evaluate(self, da): z_center = IMP.isd.Nuisance(self.z_nuisance).get_nuisance() self.z_slope_center_lower = z_center - self.thickness / 2.0 self.z_slope_center_upper = z_center + self.thickness / 2.0 score_above = sum([self.score_above(IMP.core.XYZ(p).get_z()) for p in self.particle_list_above]) score_below = sum([self.score_below(IMP.core.XYZ(p).get_z()) for p in self.particle_list_below]) score_inside = sum([self.score_inside(IMP.core.XYZ(p).get_z()) for p in self.particle_list_inside]) return score_above + score_below + score_inside def do_get_inputs(self): particle_list = self.particle_list_above + \ self.particle_list_inside + self.particle_list_below return particle_list class MembraneRestraint(IMP.test.TestCase): def test_inside(self): m = IMP.Model() atom = IMP.Particle(m) d = IMP.core.XYZ.setup_particle(atom) p = IMP.Particle(m) z_center = IMP.isd.Nuisance.setup_particle(p) z_center.set_nuisance(0.0) r = MembraneRestraintPrototype(m, z_center) r.add_particles_inside([atom]) r2 = IMP.pmi.MembraneRestraint( m, z_center.get_particle_index(), 30.0, 3.0, 0.0000000001, 0.02) r2.set_was_used(True) r2.add_particles_inside([atom.get_index()]) for z_c in range(-500, 500, 100): z_center.set_nuisance(z_c) for z in range(-500, 500, 10): IMP.core.XYZ(atom).set_z(z) self.assertAlmostEqual( r.unprotected_evaluate(None), r2.unprotected_evaluate(None), delta=1e-4) self.assertEqual(r2.get_inputs(), [atom, z_center.get_particle()]) def test_above(self): m = IMP.Model() atom = IMP.Particle(m) d = IMP.core.XYZ.setup_particle(atom) p = IMP.Particle(m) z_center = IMP.isd.Nuisance.setup_particle(p) z_center.set_nuisance(0.0) r = MembraneRestraintPrototype(m, z_center) r.add_particles_above([atom]) r2 = IMP.pmi.MembraneRestraint( m, z_center.get_particle_index(), 30.0, 3.0, 0.0000000001, 0.02) r2.set_was_used(True) r2.add_particles_above([atom.get_index()]) for z_c in range(-500, 500, 100): z_center.set_nuisance(z_c) for z in range(-500, 500, 10): IMP.core.XYZ(atom).set_z(z) self.assertAlmostEqual( r.unprotected_evaluate(None), r2.unprotected_evaluate(None), delta=1e-4) def test_below(self): m = IMP.Model() atom = IMP.Particle(m) d = IMP.core.XYZ.setup_particle(atom) p = IMP.Particle(m) z_center = IMP.isd.Nuisance.setup_particle(p) z_center.set_nuisance(0.0) r = MembraneRestraintPrototype(m, z_center) r.add_particles_below([atom]) r2 = IMP.pmi.MembraneRestraint( m, z_center.get_particle_index(), 30.0, 3.0, 0.0000000001, 0.02) r2.set_was_used(True) r2.add_particles_below([atom.get_index()]) for z_c in range(-500, 500, 100): z_center.set_nuisance(z_c) for z in range(-500, 500, 10): IMP.core.XYZ(atom).set_z(z) self.assertAlmostEqual( r.unprotected_evaluate(None), r2.unprotected_evaluate(None), delta=1e-4) def METHOD_NAME(self): m = IMP.Model() s = IMP.pmi.topology.System(m) st = s.create_state() len_helix = 40 mol = st.create_molecule("helix",sequence='A'*len_helix, chain_id='A') mol.add_representation(mol, resolutions=[1], ideal_helix=True) hier = s.build() mr = IMP.pmi.restraints.basic.MembraneRestraint(hier, objects_inside=[(11,30,'helix')], objects_above=[(1,10,'helix')], objects_below = [(31,40,'helix')]) p_inside = mr.get_particles_inside() self.assertEqual(len(p_inside), 20) p_above = mr.get_particles_above() self.assertEqual(len(p_above), 10) p_below = mr.get_particles_below() self.assertEqual(len(p_below), 10) if __name__ == '__main__': IMP.test.main()
null
19
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkga.endpoint import endpoint_data class CreateAcceleratorRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ga', '2019-11-20', 'CreateAccelerator','gaplus') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_IpSetConfig(self): # Struct return self.get_query_params().get('IpSetConfig') def set_IpSetConfig(self, IpSetConfig): # Struct if IpSetConfig.get('AccessMode') is not None: self.add_query_param('IpSetConfig.AccessMode', IpSetConfig.get('AccessMode')) def get_AutoUseCoupon(self): # String return self.get_query_params().get('AutoUseCoupon') def set_AutoUseCoupon(self, AutoUseCoupon): # String self.add_query_param('AutoUseCoupon', AutoUseCoupon) def get_AutoRenewDuration(self): # Integer return self.get_query_params().get('AutoRenewDuration') def set_AutoRenewDuration(self, AutoRenewDuration): # Integer self.add_query_param('AutoRenewDuration', AutoRenewDuration) def get_Spec(self): # String return self.get_query_params().get('Spec') def set_Spec(self, Spec): # String self.add_query_param('Spec', Spec) def get_Duration(self): # Integer return self.get_query_params().get('Duration') def set_Duration(self, Duration): # Integer self.add_query_param('Duration', Duration) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) def get_InstanceChargeType(self): # String return self.get_query_params().get('InstanceChargeType') def set_InstanceChargeType(self, InstanceChargeType): # String self.add_query_param('InstanceChargeType', InstanceChargeType) def get_AutoPay(self): # Boolean return self.get_query_params().get('AutoPay') def set_AutoPay(self, AutoPay): # Boolean self.add_query_param('AutoPay', AutoPay) def METHOD_NAME(self): # Boolean return self.get_query_params().get('DryRun') def set_DryRun(self, DryRun): # Boolean self.add_query_param('DryRun', DryRun) def get_PromotionOptionNo(self): # String return self.get_query_params().get('PromotionOptionNo') def set_PromotionOptionNo(self, PromotionOptionNo): # String self.add_query_param('PromotionOptionNo', PromotionOptionNo) def get_BandwidthBillingType(self): # String return self.get_query_params().get('BandwidthBillingType') def set_BandwidthBillingType(self, BandwidthBillingType): # String self.add_query_param('BandwidthBillingType', BandwidthBillingType) def get_AutoRenew(self): # Boolean return self.get_query_params().get('AutoRenew') def set_AutoRenew(self, AutoRenew): # Boolean self.add_query_param('AutoRenew', AutoRenew) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name) def get_PricingCycle(self): # String return self.get_query_params().get('PricingCycle') def set_PricingCycle(self, PricingCycle): # String self.add_query_param('PricingCycle', PricingCycle)
null
20
from __future__ import print_function ## @file # Utility functions and classes for BaseTools unit tests # # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # import base64 import os import os.path import random import shutil import subprocess import sys import unittest import codecs TestsDir = os.path.realpath(os.path.split(sys.argv[0])[0]) BaseToolsDir = os.path.realpath(os.path.join(TestsDir, '..')) CSourceDir = os.path.join(BaseToolsDir, 'Source', 'C') PythonSourceDir = os.path.join(BaseToolsDir, 'Source', 'Python') TestTempDir = os.path.join(TestsDir, 'TestTempDir') if PythonSourceDir not in sys.path: # # Allow unit tests to import BaseTools python modules. This is very useful # for writing unit tests. # sys.path.append(PythonSourceDir) def MakeTheTestSuite(localItems): tests = [] for name, item in localItems.items(): if isinstance(item, type): if issubclass(item, unittest.TestCase): tests.append(unittest.TestLoader().loadTestsFromTestCase(item)) elif issubclass(item, unittest.TestSuite): tests.append(item()) return lambda: unittest.TestSuite(tests) def GetBaseToolsPaths(): if sys.platform in ('win32', 'win64'): return [ os.path.join(BaseToolsDir, 'Bin', sys.platform.title()) ] else: uname = os.popen('uname -sm').read().strip() for char in (' ', '/'): uname = uname.replace(char, '-') return [ os.path.join(BaseToolsDir, 'Bin', uname), os.path.join(BaseToolsDir, 'BinWrappers', uname), os.path.join(BaseToolsDir, 'BinWrappers', 'PosixLike') ] BaseToolsBinPaths = GetBaseToolsPaths() class BaseToolsTest(unittest.TestCase): def cleanOutDir(self, dir): for dirItem in os.listdir(dir): if dirItem in ('.', '..'): continue dirItem = os.path.join(dir, dirItem) self.RemoveFileOrDir(dirItem) def CleanUpTmpDir(self): if os.path.exists(self.testDir): self.cleanOutDir(self.testDir) def HandleTreeDeleteError(self, function, path, excinfo): os.chmod(path, stat.S_IWRITE) function(path) def METHOD_NAME(self, dir): shutil.rmtree(dir, False, self.HandleTreeDeleteError) def RemoveFileOrDir(self, path): if not os.path.exists(path): return elif os.path.isdir(path): self.METHOD_NAME(path) else: os.remove(path) def DisplayBinaryData(self, description, data): print(description, '(base64 encoded):') b64data = base64.b64encode(data) print(b64data) def DisplayFile(self, fileName): sys.stdout.write(self.ReadTmpFile(fileName)) sys.stdout.flush() def FindToolBin(self, toolName): for binPath in BaseToolsBinPaths: bin = os.path.join(binPath, toolName) if os.path.exists(bin): break assert os.path.exists(bin) return bin def RunTool(self, *args, **kwd): if 'toolName' in kwd: toolName = kwd['toolName'] else: toolName = None if 'logFile' in kwd: logFile = kwd['logFile'] else: logFile = None if toolName is None: toolName = self.toolName bin = self.FindToolBin(toolName) if logFile is not None: logFile = open(os.path.join(self.testDir, logFile), 'w') popenOut = logFile else: popenOut = subprocess.PIPE args = [toolName] + list(args) Proc = subprocess.Popen( args, executable=bin, stdout=popenOut, stderr=subprocess.STDOUT ) if logFile is None: Proc.stdout.read() return Proc.wait() def GetTmpFilePath(self, fileName): return os.path.join(self.testDir, fileName) def OpenTmpFile(self, fileName, mode = 'r'): return open(os.path.join(self.testDir, fileName), mode) def ReadTmpFile(self, fileName): f = open(self.GetTmpFilePath(fileName), 'r') data = f.read() f.close() return data def WriteTmpFile(self, fileName, data): if isinstance(data, bytes): with open(self.GetTmpFilePath(fileName), 'wb') as f: f.write(data) else: with codecs.open(self.GetTmpFilePath(fileName), 'w', encoding='utf-8') as f: f.write(data) def GenRandomFileData(self, fileName, minlen = None, maxlen = None): if maxlen is None: maxlen = minlen f = self.OpenTmpFile(fileName, 'w') f.write(self.GetRandomString(minlen, maxlen)) f.close() def GetRandomString(self, minlen = None, maxlen = None): if minlen is None: minlen = 1024 if maxlen is None: maxlen = minlen return ''.join( [chr(random.randint(0, 255)) for x in range(random.randint(minlen, maxlen)) ]) def setUp(self): self.savedEnvPath = os.environ['PATH'] self.savedSysPath = sys.path[:] for binPath in BaseToolsBinPaths: os.environ['PATH'] = \ os.path.pathsep.join((os.environ['PATH'], binPath)) self.testDir = TestTempDir if not os.path.exists(self.testDir): os.mkdir(self.testDir) else: self.cleanOutDir(self.testDir) def tearDown(self): self.RemoveFileOrDir(self.testDir) os.environ['PATH'] = self.savedEnvPath sys.path = self.savedSysPath
null
21
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksmartag.endpoint import endpoint_data class CreateSmartAccessGatewayRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Smartag', '2018-03-13', 'CreateSmartAccessGateway','smartag') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ReceiverTown(self): # String return self.get_query_params().get('ReceiverTown') def set_ReceiverTown(self, ReceiverTown): # String self.add_query_param('ReceiverTown', ReceiverTown) def get_ReceiverDistrict(self): # String return self.get_query_params().get('ReceiverDistrict') def set_ReceiverDistrict(self, ReceiverDistrict): # String self.add_query_param('ReceiverDistrict', ReceiverDistrict) def get_BuyerMessage(self): # String return self.get_query_params().get('BuyerMessage') def set_BuyerMessage(self, BuyerMessage): # String self.add_query_param('BuyerMessage', BuyerMessage) def get_ReceiverState(self): # String return self.get_query_params().get('ReceiverState') def set_ReceiverState(self, ReceiverState): # String self.add_query_param('ReceiverState', ReceiverState) def get_Period(self): # Integer return self.get_query_params().get('Period') def set_Period(self, Period): # Integer self.add_query_param('Period', Period) def METHOD_NAME(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_ReceiverPhone(self): # String return self.get_query_params().get('ReceiverPhone') def set_ReceiverPhone(self, ReceiverPhone): # String self.add_query_param('ReceiverPhone', ReceiverPhone) def get_HaType(self): # String return self.get_query_params().get('HaType') def set_HaType(self, HaType): # String self.add_query_param('HaType', HaType) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name) def get_ReceiverCountry(self): # String return self.get_query_params().get('ReceiverCountry') def set_ReceiverCountry(self, ReceiverCountry): # String self.add_query_param('ReceiverCountry', ReceiverCountry) def get_MaxBandWidth(self): # Integer return self.get_query_params().get('MaxBandWidth') def set_MaxBandWidth(self, MaxBandWidth): # Integer self.add_query_param('MaxBandWidth', MaxBandWidth) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_ReceiverAddress(self): # String return self.get_query_params().get('ReceiverAddress') def set_ReceiverAddress(self, ReceiverAddress): # String self.add_query_param('ReceiverAddress', ReceiverAddress) def get_HardWareSpec(self): # String return self.get_query_params().get('HardWareSpec') def set_HardWareSpec(self, HardWareSpec): # String self.add_query_param('HardWareSpec', HardWareSpec) def get_ReceiverEmail(self): # String return self.get_query_params().get('ReceiverEmail') def set_ReceiverEmail(self, ReceiverEmail): # String self.add_query_param('ReceiverEmail', ReceiverEmail) def get_ReceiverCity(self): # String return self.get_query_params().get('ReceiverCity') def set_ReceiverCity(self, ReceiverCity): # String self.add_query_param('ReceiverCity', ReceiverCity) def get_AutoPay(self): # Boolean return self.get_query_params().get('AutoPay') def set_AutoPay(self, AutoPay): # Boolean self.add_query_param('AutoPay', AutoPay) def get_CPEVersion(self): # String return self.get_query_params().get('CPEVersion') def set_CPEVersion(self, CPEVersion): # String self.add_query_param('CPEVersion', CPEVersion) def get_ReceiverMobile(self): # String return self.get_query_params().get('ReceiverMobile') def set_ReceiverMobile(self, ReceiverMobile): # String self.add_query_param('ReceiverMobile', ReceiverMobile) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_ReceiverName(self): # String return self.get_query_params().get('ReceiverName') def set_ReceiverName(self, ReceiverName): # String self.add_query_param('ReceiverName', ReceiverName) def get_AlreadyHaveSag(self): # Boolean return self.get_query_params().get('AlreadyHaveSag') def set_AlreadyHaveSag(self, AlreadyHaveSag): # Boolean self.add_query_param('AlreadyHaveSag', AlreadyHaveSag) def get_ChargeType(self): # String return self.get_query_params().get('ChargeType') def set_ChargeType(self, ChargeType): # String self.add_query_param('ChargeType', ChargeType) def get_ReceiverZip(self): # String return self.get_query_params().get('ReceiverZip') def set_ReceiverZip(self, ReceiverZip): # String self.add_query_param('ReceiverZip', ReceiverZip)
null
22
import asyncio import pytest import falcon from falcon import testing from falcon.asgi import App from falcon.errors import UnsupportedError, UnsupportedScopeError class CustomCookies: def items(self): return [('foo', 'bar')] def test_missing_asgi_version(): scope = testing.create_scope() del scope['asgi'] resource = _call_with_scope(scope) # NOTE(kgriffs): According to the ASGI spec, the version should # default to "2.0". assert resource.captured_req.scope['asgi']['version'] == '2.0' @pytest.mark.parametrize('http_version', ['0.9', '1.9', '4.0', '1337']) def test_unsupported_http_version(http_version): scope = testing.create_scope() scope['http_version'] = http_version with pytest.raises(UnsupportedError): _call_with_scope(scope) @pytest.mark.parametrize( 'version, supported', [ ('3.0', True), ('3.1', True), ('3.10', True), ('30.0', False), ('31.0', False), ('4.0', False), ('4.1', False), ('4.10', False), ('40.0', False), ('41.0', False), ('2.0', False), ('2.1', False), ('2.10', False), (None, False), ], ) def test_supported_asgi_version(version, supported): scope = { 'type': 'lifespan', 'asgi': {'spec_version': '2.0', 'version': version}, } if version is None: del scope['asgi']['version'] app = App() resource = testing.SimpleTestResourceAsync() app.add_route('/', resource) shutting_down = asyncio.Condition() req_event_emitter = testing.ASGILifespanEventEmitter(shutting_down) resp_event_collector = testing.ASGIResponseEventCollector() async def task(): coro = asyncio.get_event_loop().create_task( app(scope, req_event_emitter, resp_event_collector) ) # NOTE(vytas): Yield to the lifespan task above. await asyncio.sleep(0) assert len(resp_event_collector.events) == 1 event = resp_event_collector.events[0] if supported: assert event['type'] == 'lifespan.startup.complete' else: assert event['type'] == 'lifespan.startup.failed' assert event['message'].startswith('Falcon requires ASGI version 3.x') async with shutting_down: shutting_down.notify() await coro falcon.async_to_sync(task) @pytest.mark.parametrize('scope_type', ['tubes', 'http3', 'htt']) def test_unsupported_scope_type(scope_type): scope = testing.create_scope() scope['type'] = scope_type with pytest.raises(UnsupportedScopeError): _call_with_scope(scope) @pytest.mark.parametrize( 'spec_version, supported', [ ('0.0', False), ('1.0', False), ('11.0', False), ('2.0', True), ('2.1', True), ('2.10', True), ('20.0', False), ('22.0', False), ('3.0', False), ('3.1', False), ('30.0', False), ], ) def test_supported_http_spec(spec_version, supported): scope = testing.create_scope() scope['asgi']['spec_version'] = spec_version if supported: _call_with_scope(scope) else: with pytest.raises(UnsupportedScopeError): _call_with_scope(scope) def test_lifespan_scope_default_version(): app = App() resource = testing.SimpleTestResourceAsync() app.add_route('/', resource) shutting_down = asyncio.Condition() req_event_emitter = testing.ASGILifespanEventEmitter(shutting_down) resp_event_collector = testing.ASGIResponseEventCollector() scope = {'type': 'lifespan'} async def t(): t = asyncio.get_event_loop().create_task( app(scope, req_event_emitter, resp_event_collector) ) # NOTE(kgriffs): Yield to the lifespan task above await asyncio.sleep(0.001) async with shutting_down: shutting_down.notify() await t falcon.async_to_sync(t) assert not resource.called @pytest.mark.parametrize( 'spec_version, supported', [ ('0.0', False), ('1.0', True), ('1.1', True), ('1.10', True), ('2.0', True), ('2.1', True), ('2.10', True), ('3.0', False), ('4.0', False), ('11.0', False), ('22.0', False), ], ) def test_lifespan_scope_version(spec_version, supported): app = App() shutting_down = asyncio.Condition() req_event_emitter = testing.ASGILifespanEventEmitter(shutting_down) resp_event_collector = testing.ASGIResponseEventCollector() scope = { 'type': 'lifespan', 'asgi': {'spec_version': spec_version, 'version': '3.0'}, } if not supported: with pytest.raises(UnsupportedScopeError): falcon.async_to_sync( app.__call__, scope, req_event_emitter, resp_event_collector ) return async def t(): t = asyncio.get_event_loop().create_task( app(scope, req_event_emitter, resp_event_collector) ) # NOTE(kgriffs): Yield to the lifespan task above await asyncio.sleep(0.001) async with shutting_down: shutting_down.notify() await t falcon.async_to_sync(t) def test_query_string_values(): with pytest.raises(ValueError): testing.create_scope(query_string='?catsup=y') with pytest.raises(ValueError): testing.create_scope(query_string='?') for qs in ('', None): scope = testing.create_scope(query_string=qs) assert scope['query_string'] == b'' resource = _call_with_scope(scope) assert resource.captured_req.query_string == '' qs = 'a=1&b=2&c=%3E%20%3C' scope = testing.create_scope(query_string=qs) assert scope['query_string'] == qs.encode() resource = _call_with_scope(scope) assert resource.captured_req.query_string == qs @pytest.mark.parametrize( 'scheme, valid', [ ('http', True), ('https', True), ('htt', False), ('http:', False), ('https:', False), ('ftp', False), ('gopher', False), ], ) def METHOD_NAME(scheme, valid): if valid: testing.create_scope(scheme=scheme) else: with pytest.raises(ValueError): testing.create_scope(scheme=scheme) @pytest.mark.parametrize('cookies', [{'foo': 'bar', 'baz': 'foo'}, CustomCookies()]) def test_cookies(cookies): scope = testing.create_scope(cookies=cookies) assert any(header == b'cookie' for header, _ in scope['headers']) def test_cookies_options_meathod(): scope = testing.create_scope(method='OPTIONS', cookies={'foo': 'bar'}) assert not any(header == b'cookie' for header, _ in scope['headers']) def _call_with_scope(scope): app = App() resource = testing.SimpleTestResourceAsync() app.add_route('/', resource) req_event_emitter = testing.ASGIRequestEventEmitter() resp_event_collector = testing.ASGIResponseEventCollector() falcon.async_to_sync(app.__call__, scope, req_event_emitter, resp_event_collector) assert resource.called return resource
null
23
# coding: utf-8 """ Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator """ import unittest from unittest.mock import patch import urllib3 import typing_extensions import unit_test_api from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import operation as post # noqa: E501 from unit_test_api import schemas, api_client from unit_test_api.configurations import api_configuration, schema_configuration from .. import ApiTestMixin class TestPost(ApiTestMixin, unittest.TestCase): """ Post unit test stubs """ api_config = api_configuration.ApiConfiguration() schema_config = schema_configuration.SchemaConfiguration() used_api_client = api_client.ApiClient(configuration=api_config, schema_configuration=schema_config) api = post.ApiForPost(api_client=used_api_client) # noqa: E501 response_status = 200 response_body_schema = post.response_200.ResponseFor200.content["application/json"].schema assert response_body_schema is not None def test_false_is_valid_passes(self): # false is valid accept_content_type = 'application/json' with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( False ) mock_request.return_value = self.response( self.json_bytes(payload), status=self.response_status ) api_response = self.api.post( accept_content_types=(accept_content_type,) ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes", method='post'.upper(), accept_content_type=accept_content_type, ) assert isinstance(api_response.response, urllib3.HTTPResponse) deserialized_response_body = self.response_body_schema.validate( payload, configuration=self.schema_config ) assert api_response.body == deserialized_response_body def METHOD_NAME(self): # float zero is invalid accept_content_type = 'application/json' with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( 0.0 ) mock_request.return_value = self.response( self.json_bytes(payload), status=self.response_status ) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): self.api.post( accept_content_types=(accept_content_type,) ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes", method='post'.upper(), content_type=None, accept_content_type=accept_content_type, ) def test_integer_zero_is_invalid_fails(self): # integer zero is invalid accept_content_type = 'application/json' with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( 0 ) mock_request.return_value = self.response( self.json_bytes(payload), status=self.response_status ) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): self.api.post( accept_content_types=(accept_content_type,) ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes", method='post'.upper(), content_type=None, accept_content_type=accept_content_type, ) if __name__ == '__main__': unittest.main()
null
24
import abc from typing import List, Tuple from boa3.internal import constants from boa3.internal.model.type.classes import classtype from boa3.internal.neo.vm.opcode.Opcode import Opcode from boa3.internal.neo.vm.type.AbiType import AbiType from boa3.internal.neo.vm.type.StackItem import StackItemType class PythonClass(classtype.ClassType, abc.ABC): def __init__(self, identifier: str, instance_variables: dict = None, instance_methods: dict = None, METHOD_NAME: dict = None, class_variables: dict = None, class_methods: dict = None, static_methods: dict = None): self._instance_methods = instance_methods if isinstance(instance_methods, dict) else None self._instance_variables = instance_variables if isinstance(instance_variables, dict) else None self._properties = METHOD_NAME if isinstance(METHOD_NAME, dict) else None self._class_variables = class_variables if isinstance(class_variables, dict) else None self._class_methods = class_methods if isinstance(class_methods, dict) else None self._static_methods = static_methods if isinstance(static_methods, dict) else None is_init_defined = isinstance(instance_methods, dict) and constants.INIT_METHOD_ID in instance_methods self._is_init_set = is_init_defined self._constructor = (instance_methods[constants.INIT_METHOD_ID] if is_init_defined else None) super().__init__(identifier) def _init_class_symbols(self): """ Overwrite this method to set variables and methods from this type. Always call super()._init_class_symbols in the beginning Used to avoid circular imports between the init classes """ # TODO: May be removed when class inheritance is implemented if not isinstance(self._instance_methods, dict): self._instance_methods = {} if not isinstance(self._instance_variables, dict): self._instance_variables = {} if not isinstance(self._properties, dict): self._properties = {} if not isinstance(self._class_variables, dict): self._class_variables = {} if not isinstance(self._class_methods, dict): self._class_methods = {} if not isinstance(self._static_methods, dict): self._static_methods = {} @property def class_variables(self): if not isinstance(self._class_variables, dict): self._init_class_symbols() return self._class_variables.copy() @property def instance_variables(self): if not isinstance(self._instance_variables, dict): self._init_class_symbols() return self._instance_variables.copy() @property def METHOD_NAME(self): if not isinstance(self._properties, dict): self._init_class_symbols() return self._properties.copy() @property def static_methods(self): if not isinstance(self._static_methods, dict): self._init_class_symbols() return self._static_methods.copy() @property def class_methods(self): if not isinstance(self._class_methods, dict): self._init_class_symbols() return self._class_methods.copy() @property def instance_methods(self): if not isinstance(self._instance_methods, dict): self._init_class_symbols() return self._instance_methods.copy() def constructor_method(self): if not isinstance(self._instance_variables, dict): self._init_class_symbols() if not self._is_init_set: self._constructor = (self._instance_methods[constants.INIT_METHOD_ID] if constants.INIT_METHOD_ID in self._instance_methods else None) self._is_init_set = True return self._constructor @property def abi_type(self) -> AbiType: return super().abi_type @property def stack_item(self) -> StackItemType: """ Get the Neo VM stack item type representation for this type :return: the stack item type of this type. Any by default. """ return super().stack_item def is_instance_opcodes(self) -> List[Tuple[Opcode, bytes]]: """ Get the list of opcodes to check if an value is of this type :return: A list of opcodes to check a value type """ return [(Opcode.ISTYPE, self.stack_item)]
null
25
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksmartag.endpoint import endpoint_data class AddACLRuleRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Smartag', '2018-03-13', 'AddACLRule','smartag') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DpiGroupIdss(self): # RepeatList return self.get_query_params().get('DpiGroupIds') def set_DpiGroupIdss(self, DpiGroupIds): # RepeatList pass def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_SourcePortRange(self): # String return self.get_query_params().get('SourcePortRange') def set_SourcePortRange(self, SourcePortRange): # String self.add_query_param('SourcePortRange', SourcePortRange) def get_SourceCidr(self): # String return self.get_query_params().get('SourceCidr') def set_SourceCidr(self, SourceCidr): # String self.add_query_param('SourceCidr', SourceCidr) def get_Description(self): # String return self.get_query_params().get('Description') def METHOD_NAME(self, Description): # String self.add_query_param('Description', Description) def get_Type(self): # String return self.get_query_params().get('Type') def set_Type(self, Type): # String self.add_query_param('Type', Type) def get_DestCidr(self): # String return self.get_query_params().get('DestCidr') def set_DestCidr(self, DestCidr): # String self.add_query_param('DestCidr', DestCidr) def get_DpiSignatureIdss(self): # RepeatList return self.get_query_params().get('DpiSignatureIds') def set_DpiSignatureIdss(self, DpiSignatureIds): # RepeatList pass def get_Direction(self): # String return self.get_query_params().get('Direction') def set_Direction(self, Direction): # String self.add_query_param('Direction', Direction) def get_Policy(self): # String return self.get_query_params().get('Policy') def set_Policy(self, Policy): # String self.add_query_param('Policy', Policy) def get_AclId(self): # String return self.get_query_params().get('AclId') def set_AclId(self, AclId): # String self.add_query_param('AclId', AclId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_IpProtocol(self): # String return self.get_query_params().get('IpProtocol') def set_IpProtocol(self, IpProtocol): # String self.add_query_param('IpProtocol', IpProtocol) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_Priority(self): # Integer return self.get_query_params().get('Priority') def set_Priority(self, Priority): # Integer self.add_query_param('Priority', Priority) def get_DestPortRange(self): # String return self.get_query_params().get('DestPortRange') def set_DestPortRange(self, DestPortRange): # String self.add_query_param('DestPortRange', DestPortRange) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name)
null
26
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkvpc.endpoint import endpoint_data class CreateRouteEntryRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'CreateRouteEntry','vpc') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def METHOD_NAME(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_RouteEntryName(self): # String return self.get_query_params().get('RouteEntryName') def set_RouteEntryName(self, RouteEntryName): # String self.add_query_param('RouteEntryName', RouteEntryName) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_NextHopId(self): # String return self.get_query_params().get('NextHopId') def set_NextHopId(self, NextHopId): # String self.add_query_param('NextHopId', NextHopId) def get_NextHopType(self): # String return self.get_query_params().get('NextHopType') def set_NextHopType(self, NextHopType): # String self.add_query_param('NextHopType', NextHopType) def get_RouteTableId(self): # String return self.get_query_params().get('RouteTableId') def set_RouteTableId(self, RouteTableId): # String self.add_query_param('RouteTableId', RouteTableId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_DestinationCidrBlock(self): # String return self.get_query_params().get('DestinationCidrBlock') def set_DestinationCidrBlock(self, DestinationCidrBlock): # String self.add_query_param('DestinationCidrBlock', DestinationCidrBlock) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_NextHopLists(self): # RepeatList return self.get_query_params().get('NextHopList') def set_NextHopLists(self, NextHopList): # RepeatList for depth1 in range(len(NextHopList)): if NextHopList[depth1].get('Weight') is not None: self.add_query_param('NextHopList.' + str(depth1 + 1) + '.Weight', NextHopList[depth1].get('Weight')) if NextHopList[depth1].get('NextHopId') is not None: self.add_query_param('NextHopList.' + str(depth1 + 1) + '.NextHopId', NextHopList[depth1].get('NextHopId')) if NextHopList[depth1].get('NextHopType') is not None: self.add_query_param('NextHopList.' + str(depth1 + 1) + '.NextHopType', NextHopList[depth1].get('NextHopType'))
null
27
import unittest import machine_common_sense as mcs class MyEmptyclass: def __init__(self): pass class MySubclass: def __init__(self): self.my_integer = 7 self.my_string = "h" self.my_list = [8, "i"] self.my_dict = { "my_integer": 9, "my_string": "j", } def __str__(self): return mcs.Stringifier.class_to_str(self) class MyClass: def __init__(self): self.my_boolean = True self.my_float = 1.234 self.my_integer = 0 self.my_string = "a" self.my_list = [1, "b", { "my_integer": 2, "my_string": "c", "my_list": [3, "d"] }] self.my_dict = { "my_integer": 4, "my_string": "e", "my_list": [5, "f"], "my_dict": { "my_integer": 6, "my_string": "g", } } self.my_list_empty = [] self.my_dict_empty = {} self.my_subclass = MySubclass() self.__my_private = "z" def my_function(): pass class TestStringifier(unittest.TestCase): def test_class_to_str_with_class(self): self.maxDiff = 10000 expected = "{\n \"my_boolean\": true,\n \"my_float\": 1.234,\n \"my_integer\": 0,\n \"my_string\": \"a\",\n \"my_list\": [\n 1,\n \"b\",\n {\n \"my_integer\": 2,\n \"my_string\": \"c\",\n \"my_list\": [3,\"d\"]\n }\n ],\n \"my_dict\": {\n \"my_integer\": 4,\n \"my_string\": \"e\",\n \"my_list\": [5,\"f\"],\n \"my_dict\": {\n \"my_integer\": 6,\n \"my_string\": \"g\"\n }\n },\n \"my_list_empty\": [],\n \"my_dict_empty\": {},\n \"my_subclass\": {\n \"my_integer\": 7,\n \"my_string\": \"h\",\n \"my_list\": [8,\"i\"],\n \"my_dict\": {\n \"my_integer\": 9,\n \"my_string\": \"j\"\n }\n }\n}" # noqa: E501 self.assertEqual(mcs.Stringifier.class_to_str(MyClass()), expected) def test_class_to_str_with_empty_class(self): self.assertEqual(mcs.Stringifier.class_to_str(MyEmptyclass()), "{}") def test_generate_pretty_object_output(self): object_list = [ mcs.ObjectMetadata( uuid='id1', shape='', state_list=[], texture_color_list=[], held=True, visible=True, position=None, dimensions=None, distance_in_world=0, direction=None ), mcs.ObjectMetadata( uuid='really_long_id2', shape='sofa', state_list=['state1', 'state2'], texture_color_list=['black', 'white'], held=False, visible=False, position={ 'x': 1, 'y': 2, 'z': 3 }, dimensions=[{ 'x': 4, 'y': 5, 'z': 6 }], distance_in_world=1234567890987654321, direction={ 'x': 10000, 'y': 20000, 'z': 30000 } ) ] self.assertEqual(mcs.Stringifier.generate_pretty_object_output( object_list), [ 'OBJECT ID SHAPE COLORS HELD VISIBLE STATE POSITION (WORLD) DISTANCE (WORLD) DIRECTION (WORLD) DIMENSIONS (WORLD)', # noqa: E501 'id1 True True None 0 None None ', # noqa: E501 'really_long_id2 sofa black, white False False state1, state2 (1,2,3) 1234567890987654321 (10000,20000,30000) [(4,5,6)] ' # noqa: E501 ]) def test_value_to_str_with_boolean(self): self.assertEqual(mcs.Stringifier.value_to_str(True), "true") self.assertEqual(mcs.Stringifier.value_to_str(False), "false") def test_value_to_str_with_dict(self): self.assertEqual(mcs.Stringifier.value_to_str({}), "{}") self.assertEqual(mcs.Stringifier.value_to_str({ "number": 1, "string": "a" }), "{\n \"number\": 1,\n \"string\": \"a\"\n}") def test_value_to_str_with_float(self): self.assertEqual(mcs.Stringifier.value_to_str(0.0), "0.0") self.assertEqual(mcs.Stringifier.value_to_str(1234.5678), "1234.5678") self.assertEqual(mcs.Stringifier.value_to_str(0.12345678), "0.123457") self.assertEqual( mcs.Stringifier.value_to_str(-0.12345678), "-0.123457" ) def test_value_to_str_with_integer(self): self.assertEqual(mcs.Stringifier.value_to_str(0), "0") self.assertEqual(mcs.Stringifier.value_to_str(1234), "1234") def test_value_to_str_with_list(self): self.assertEqual(mcs.Stringifier.value_to_str([]), "[]") self.assertEqual(mcs.Stringifier.value_to_str([1, "a"]), "[1,\"a\"]") def test_value_to_str_with_list_with_nested_dict(self): self.assertEqual(mcs.Stringifier.value_to_str([]), "[]") self.assertEqual( mcs.Stringifier.value_to_str([1, "a", {"b": 2}]), "[\n 1,\n \"a\",\n {\n \"b\": 2\n }\n]" ) def METHOD_NAME(self): self.assertEqual(mcs.Stringifier.value_to_str([]), "[]") self.assertEqual( mcs.Stringifier.value_to_str([1, "a", [2, "b"]]), "[\n 1,\n \"a\",\n [2,\"b\"]\n]" ) def test_value_to_str_with_string(self): self.assertEqual(mcs.Stringifier.value_to_str(""), "\"\"") self.assertEqual( mcs.Stringifier.value_to_str("a b c d"), "\"a b c d\"") def test_vector_to_string(self): self.assertEqual(mcs.Stringifier.vector_to_string(None), 'None') self.assertEqual(mcs.Stringifier.vector_to_string({ 'x': 1, 'y': 2, 'z': 3 }), '(1,2,3)') if __name__ == '__main__': unittest.main()
null
28
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkuis.endpoint import endpoint_data class CreateUisRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Uis', '2018-08-21', 'CreateUis','uis') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_BandwidthType(self): return self.get_query_params().get('BandwidthType') def set_BandwidthType(self,BandwidthType): self.add_query_param('BandwidthType',BandwidthType) def get_ClientToken(self): return self.get_query_params().get('ClientToken') def set_ClientToken(self,ClientToken): self.add_query_param('ClientToken',ClientToken) def get_Description(self): return self.get_query_params().get('Description') def set_Description(self,Description): self.add_query_param('Description',Description) def get_ServiceRegion(self): return self.get_query_params().get('ServiceRegion') def set_ServiceRegion(self,ServiceRegion): self.add_query_param('ServiceRegion',ServiceRegion) def get_Duration(self): return self.get_query_params().get('Duration') def set_Duration(self,Duration): self.add_query_param('Duration',Duration) def get_UisProtocol(self): return self.get_query_params().get('UisProtocol') def set_UisProtocol(self,UisProtocol): self.add_query_param('UisProtocol',UisProtocol) def get_InstanceChargeType(self): return self.get_query_params().get('InstanceChargeType') def set_InstanceChargeType(self,InstanceChargeType): self.add_query_param('InstanceChargeType',InstanceChargeType) def get_AccessType(self): return self.get_query_params().get('AccessType') def set_AccessType(self,AccessType): self.add_query_param('AccessType',AccessType) def get_AutoPay(self): return self.get_query_params().get('AutoPay') def set_AutoPay(self,AutoPay): self.add_query_param('AutoPay',AutoPay) def get_ConnectionCount(self): return self.get_query_params().get('ConnectionCount') def set_ConnectionCount(self,ConnectionCount): self.add_query_param('ConnectionCount',ConnectionCount) def get_ResourceOwnerAccount(self): return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self,ResourceOwnerAccount): self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount) def get_Bandwidth(self): return self.get_query_params().get('Bandwidth') def set_Bandwidth(self,Bandwidth): self.add_query_param('Bandwidth',Bandwidth) def get_OwnerAccount(self): return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self,OwnerAccount): self.add_query_param('OwnerAccount',OwnerAccount) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_InternetChargeType(self): return self.get_query_params().get('InternetChargeType') def set_InternetChargeType(self,InternetChargeType): self.add_query_param('InternetChargeType',InternetChargeType) def get_Name(self): return self.get_query_params().get('Name') def set_Name(self,Name): self.add_query_param('Name',Name) def get_PricingCycle(self): return self.get_query_params().get('PricingCycle') def METHOD_NAME(self,PricingCycle): self.add_query_param('PricingCycle',PricingCycle) def get_ConnectionBandwidth(self): return self.get_query_params().get('ConnectionBandwidth') def set_ConnectionBandwidth(self,ConnectionBandwidth): self.add_query_param('ConnectionBandwidth',ConnectionBandwidth
null
29
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkrds.endpoint import endpoint_data class DescribeDBInstancesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Rds', '2014-08-15', 'DescribeDBInstances') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ConnectionString(self): # String return self.get_query_params().get('ConnectionString') def set_ConnectionString(self, ConnectionString): # String self.add_query_param('ConnectionString', ConnectionString) def get_EngineVersion(self): # String return self.get_query_params().get('EngineVersion') def set_EngineVersion(self, EngineVersion): # String self.add_query_param('EngineVersion', EngineVersion) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_proxyId(self): # String return self.get_query_params().get('proxyId') def set_proxyId(self, proxyId): # String self.add_query_param('proxyId', proxyId) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_DBInstanceType(self): # String return self.get_query_params().get('DBInstanceType') def set_DBInstanceType(self, DBInstanceType): # String self.add_query_param('DBInstanceType', DBInstanceType) def get_DBInstanceClass(self): # String return self.get_query_params().get('DBInstanceClass') def set_DBInstanceClass(self, DBInstanceClass): # String self.add_query_param('DBInstanceClass', DBInstanceClass) def get_Tags(self): # String return self.get_query_params().get('Tags') def set_Tags(self, Tags): # String self.add_query_param('Tags', Tags) def get_VSwitchId(self): # String return self.get_query_params().get('VSwitchId') def set_VSwitchId(self, VSwitchId): # String self.add_query_param('VSwitchId', VSwitchId) def get_ZoneId(self): # String return self.get_query_params().get('ZoneId') def set_ZoneId(self, ZoneId): # String self.add_query_param('ZoneId', ZoneId) def get_MaxResults(self): # Integer return self.get_query_params().get('MaxResults') def set_MaxResults(self, MaxResults): # Integer self.add_query_param('MaxResults', MaxResults) def get_InstanceNetworkType(self): # String return self.get_query_params().get('InstanceNetworkType') def set_InstanceNetworkType(self, InstanceNetworkType): # String self.add_query_param('InstanceNetworkType', InstanceNetworkType) def METHOD_NAME(self): # String return self.get_query_params().get('ConnectionMode') def set_ConnectionMode(self, ConnectionMode): # String self.add_query_param('ConnectionMode', ConnectionMode) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_InstanceLevel(self): # Integer return self.get_query_params().get('InstanceLevel') def set_InstanceLevel(self, InstanceLevel): # Integer self.add_query_param('InstanceLevel', InstanceLevel) def get_SearchKey(self): # String return self.get_query_params().get('SearchKey') def set_SearchKey(self, SearchKey): # String self.add_query_param('SearchKey', SearchKey) def get_PageNumber(self): # Integer return self.get_query_params().get('PageNumber') def set_PageNumber(self, PageNumber): # Integer self.add_query_param('PageNumber', PageNumber) def get_Expired(self): # String return self.get_query_params().get('Expired') def set_Expired(self, Expired): # String self.add_query_param('Expired', Expired) def get_Engine(self): # String return self.get_query_params().get('Engine') def set_Engine(self, Engine): # String self.add_query_param('Engine', Engine) def get_NextToken(self): # String return self.get_query_params().get('NextToken') def set_NextToken(self, NextToken): # String self.add_query_param('NextToken', NextToken) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_DBInstanceStatus(self): # String return self.get_query_params().get('DBInstanceStatus') def set_DBInstanceStatus(self, DBInstanceStatus): # String self.add_query_param('DBInstanceStatus', DBInstanceStatus) def get_DBInstanceId(self): # String return self.get_query_params().get('DBInstanceId') def set_DBInstanceId(self, DBInstanceId): # String self.add_query_param('DBInstanceId', DBInstanceId) def get_DedicatedHostGroupId(self): # String return self.get_query_params().get('DedicatedHostGroupId') def set_DedicatedHostGroupId(self, DedicatedHostGroupId): # String self.add_query_param('DedicatedHostGroupId', DedicatedHostGroupId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_DedicatedHostId(self): # String return self.get_query_params().get('DedicatedHostId') def set_DedicatedHostId(self, DedicatedHostId): # String self.add_query_param('DedicatedHostId', DedicatedHostId) def get_Filter(self): # String return self.get_query_params().get('Filter') def set_Filter(self, Filter): # String self.add_query_param('Filter', Filter) def get_VpcId(self): # String return self.get_query_params().get('VpcId') def set_VpcId(self, VpcId): # String self.add_query_param('VpcId', VpcId) def get_Category(self): # String return self.get_query_params().get('Category') def set_Category(self, Category): # String self.add_query_param('Category', Category) def get_PayType(self): # String return self.get_query_params().get('PayType') def set_PayType(self, PayType): # String self.add_query_param('PayType', PayType)
null
30
import os.path from typing import Optional from pcs import settings from pcs.common import file_type_codes as code from pcs.common.file import FileMetadata def METHOD_NAME(filename: str) -> FileMetadata: return FileMetadata( # The filename is expected to be complete (i.e. booth.conf) and verified # (i.e. no slashes in it). The caller is responsible for doing both. file_type_code=code.BOOTH_CONFIG, path=os.path.join(settings.booth_config_dir, filename), owner_user_name="root", owner_group_name="root", permissions=0o644, is_binary=False, ) def _for_booth_key(filename: str) -> FileMetadata: return FileMetadata( # The filename is expected to be complete (i.e. booth.key) and verified # (i.e. no slashes in it). The caller is responsible for doing both. file_type_code=code.BOOTH_KEY, path=os.path.join(settings.booth_config_dir, filename), owner_user_name=settings.pacemaker_uname, owner_group_name=settings.pacemaker_gname, permissions=settings.booth_authkey_file_mode, is_binary=True, ) def _for_corosync_conf() -> FileMetadata: return FileMetadata( file_type_code=code.COROSYNC_CONF, path=settings.corosync_conf_file, owner_user_name="root", owner_group_name="root", permissions=0o644, is_binary=False, ) def _for_corosync_qnetd_ca_cert() -> FileMetadata: return FileMetadata( file_type_code=code.COROSYNC_QNETD_CA_CERT, path=os.path.join( settings.corosync_qdevice_net_server_certs_dir, settings.corosync_qdevice_net_server_ca_file_name, ), owner_user_name="coroqnetd", owner_group_name="coroqnetd", permissions=0o600, is_binary=True, ) def _for_pacemaker_authkey() -> FileMetadata: return FileMetadata( file_type_code=code.PACEMAKER_AUTHKEY, path=settings.pacemaker_authkey_file, owner_user_name=settings.pacemaker_uname, owner_group_name=settings.pacemaker_gname, permissions=0o400, is_binary=True, ) def _for_pcs_dr_config() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_DR_CONFIG, path=settings.pcsd_dr_config_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_known_hosts() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_KNOWN_HOSTS, path=settings.pcsd_known_hosts_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_users_conf() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_USERS_CONF, path=settings.pcsd_users_conf_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_settings_conf() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_SETTINGS_CONF, path=settings.pcsd_settings_conf_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def for_file_type( file_type_code: code.FileTypeCode, filename: Optional[str] = None ) -> FileMetadata: # pylint: disable=too-many-return-statements if file_type_code == code.BOOTH_CONFIG: if not filename: raise AssertionError("filename must be set") return METHOD_NAME(filename) if file_type_code == code.BOOTH_KEY: if not filename: raise AssertionError("filename must be set") return _for_booth_key(filename) if file_type_code == code.COROSYNC_CONF: return _for_corosync_conf() if file_type_code == code.COROSYNC_QNETD_CA_CERT: return _for_corosync_qnetd_ca_cert() if file_type_code == code.PACEMAKER_AUTHKEY: return _for_pacemaker_authkey() if file_type_code == code.PCS_DR_CONFIG: return _for_pcs_dr_config() if file_type_code == code.PCS_KNOWN_HOSTS: return _for_pcs_known_hosts() if file_type_code == code.PCS_USERS_CONF: return _for_pcs_users_conf() if file_type_code == code.PCS_SETTINGS_CONF: return _for_pcs_settings_conf() raise AssertionError("Unknown file_type_code")
null
31
""" @file @brief This file manages the optional Sentry SDK @author Jonathan Thomas <[email protected]> @author FeRD (Frank Dana) <[email protected]> @section LICENSE Copyright (c) 2008-2021 OpenShot Studios, LLC (http://www.openshotstudios.com). This file is part of OpenShot Video Editor (http://www.openshot.org), an open-source project dedicated to delivering high quality video editing and animation solutions to the world. OpenShot Video Editor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenShot Video Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>. """ import platform import datetime from classes.logger import log from classes import info from classes.logger import log try: import distro except ModuleNotFoundError: distro = None try: import sentry_sdk as sdk except ModuleNotFoundError: sdk = None # seconds required between errors min_error_freq = 1 last_send_time = None last_event_message = None def init_tracing(): """Init all Sentry tracing""" if not sdk: log.info('No sentry_sdk module detected (error reporting is disabled)') return # Determine sample rate for errors & transactions sample_rate = 0.0 traces_sample_rate = 0.0 if info.VERSION == info.ERROR_REPORT_STABLE_VERSION: sample_rate = info.ERROR_REPORT_RATE_STABLE traces_sample_rate = info.TRANS_REPORT_RATE_STABLE environment = "production" else: sample_rate = info.ERROR_REPORT_RATE_UNSTABLE traces_sample_rate = info.TRANS_REPORT_RATE_UNSTABLE environment = "unstable" if info.ERROR_REPORT_STABLE_VERSION: log.info("Sentry initialized for '%s': %s sample rate, %s transaction rate" % (environment, sample_rate, traces_sample_rate)) def METHOD_NAME(event,hint): """ Function to filter out repetitive Sentry.io errors before sending them """ global last_send_time global last_event_message # Prevent rapid errors current_time = datetime.datetime.now() if last_send_time: time_since_send = (current_time - last_send_time).total_seconds() if time_since_send < min_error_freq: log.debug("Report prevented: Recent error reported") return None # Prevent repeated errors event_message = event.\ get("logentry", {"message": None}).\ get("message", None) if last_event_message and last_event_message == event_message: log.debug("Report prevented: Same as last Error") return None # This error will send. Update the last time and last message log.debug("Sending Error") last_send_time = current_time last_event_message = event_message return event # Initialize sentry exception tracing sdk.init( "https://[email protected]/5795985", sample_rate=sample_rate, traces_sample_rate=traces_sample_rate, release=f"openshot@{info.VERSION}", environment=environment, debug=False, METHOD_NAME=METHOD_NAME ) if _supports_tagging(): configure_platform_tags(sdk) else: sdk.configure_scope(platform_scope) def platform_scope(scope): configure_platform_tags(scope) def configure_platform_tags(sdk_or_scope): sdk_or_scope.set_tag("system", platform.system()) sdk_or_scope.set_tag("machine", platform.machine()) sdk_or_scope.set_tag("processor", platform.processor()) sdk_or_scope.set_tag("platform", platform.platform()) if distro and platform.system() == "linux": sdk_or_scope.set_tag("distro", " ".join(distro.linux_distribution())) sdk_or_scope.set_tag("locale", info.CURRENT_LANGUAGE) def disable_tracing(): """Disable all Sentry tracing requests""" if sdk: sdk.init() def set_tag(*args): if sdk and _supports_tagging(): sdk.set_tag(*args) def set_user(*args): if sdk and _supports_tagging(): sdk.set_user(*args) def set_context(*args): if sdk and _supports_tagging(): sdk.set_context(*args) def _supports_tagging(): """Returns whether the imported sentry-sdk has tag-related methods such as set_tag, set_user, set_context. Those methods were introduce on 0.13.1 version. Checking this before calling those methods on the sentry-sdk avoids crashing Openshot in case an old sdk is installed. """ return all([hasattr(sdk, method) for method in ["set_tag", "set_user", "set_context"]])
null
32
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from __future__ import annotations import os import pathlib import re import shutil import tempfile from pathlib import Path from typing import Optional from types import TracebackType import torch # File-related constants CHECKPOINT_FOLDER_PREFIX = "checkpoint" CHECKPOINT_REGEX = re.compile(r"^" + CHECKPOINT_FOLDER_PREFIX + r"\-(\d+)$") def calculate_onnx_model_size(model_path: str) -> float: """Calculate the size of an ONNX model. This function calculates the size of an ONNX model by reading the size of the file on disk. Args: model_path: The path to the ONNX model on disk. Returns: The size of the model in megabytes. """ size = os.path.getsize(model_path) / 1e6 return size def calculate_torch_model_size(model: torch.nn.Module) -> float: """Calculate the size of a PyTorch model. This function calculates the size of a PyTorch model by saving its state dictionary to a temporary file and reading the size of the file on disk. Args: model: The PyTorch model. Returns: The size of the model in megabytes. """ torch.save(model.state_dict(), "temp.p") size = os.path.getsize("temp.p") / 1e6 os.remove("temp.p") return size def check_available_checkpoint(folder_name: str) -> bool: """Check if there are any available checkpoints in a given folder. This function checks if a given folder contains any checkpoints by looking for directories that match a regular expression for checkpoint names. Args: folder_name: The path to the folder that might contain checkpoints. Returns: `True` if there are available checkpoints, `False` otherwise. """ if not os.path.exists(folder_name): return False folder_content = os.listdir(folder_name) checkpoints = [ path for path in folder_content if CHECKPOINT_REGEX.search(path) is not None and os.path.isdir(os.path.join(folder_name, path)) ] if len(checkpoints) == 0: return False return True def create_file_name_identifier(file_name: str, identifier: str) -> str: """Create a new file name by adding an identifier to the end of an existing file name (before the file extension). Args: file_name: The original file name. identifier: The identifier to be added to the file name. Returns: The new file name with the added identifier. """ file_name = Path(file_name) file_name_identifier = file_name.parent.joinpath(file_name.stem + identifier).with_suffix(file_name.suffix) return file_name_identifier.as_posix() def create_empty_file(file_path: str) -> None: """Create an empty file at the given path. Args: file_path: The path to the file to be created. """ open(file_path, "w").close() def create_file_with_string(file_path: str, content: str) -> None: """Create a file at the given path and writes the given string to it. Args: file_path: The path to the file to be created. content: The string to be written to the file. """ pathlib.Path(file_path).write_text(content) def METHOD_NAME( src_file_path: str, dest_file_path: str, force_shutil: Optional[bool] = True, keep_metadata: Optional[bool] = False ) -> str: """Copy a file from one location to another. Args: src_file_path: The path to the source file. dest_file_path: The path to the destination file. force_shutil: Whether to use `shutil` to copy the file. keep_metadata: Whether to keep source file metadata when copying. Returns: The path to the destination file. """ def _copy_file_basic_mode(src_file_path: str, dest_file_path: str) -> str: if os.path.isdir(dest_file_path): dest_file_path = os.path.join(dest_file_path, pathlib.Path(src_file_path).name) with open(src_file_path, "rb") as src, open(dest_file_path, "wb") as dest: dest.write(src.read()) return dest_file_path if not force_shutil: return _copy_file_basic_mode(src_file_path, dest_file_path) # Note shutil.copy2 might fail on Azure if file system does not support OS level copystats # Use keep_metadata=True only if needed for maximum compatibility try: copy_fn = shutil.copy2 if keep_metadata else shutil.copy return copy_fn(src_file_path, dest_file_path) except OSError as e: if keep_metadata or e.errno != 38: # OSError 38: Function not implemented raise return _copy_file_basic_mode(src_file_path, dest_file_path) def get_full_path(path: str, create_folder: Optional[bool] = False) -> str: """Get the full path to a file or folder. Args: path: The path to the file or folder. create_folder: Whether to create the folder if it does not exist. Returns: The full path to the file or folder. """ assert path path = os.path.abspath(os.path.expanduser(os.path.expandvars(path))) if create_folder: os.makedirs(path, exist_ok=True) return path class TemporaryFiles: """ Windows has a weird quirk where the tempfile.NamedTemporaryFile cannot be opened a second time. """ def __init__(self): self.files_to_delete = [] def __enter__(self): return self def __exit__(self, exc_type: type[BaseException], exc_val: BaseException, exc_tb: TracebackType) -> None: for name in self.files_to_delete: os.unlink(name) self.files_to_delete = [] def get_temp_file(self) -> str: result = None with tempfile.NamedTemporaryFile(delete=False) as tmp: result = tmp.name self.files_to_delete += [result] return result
null
33
"""Condense HTML. 1. Put short html tags back on one line 2. Put short template tags back on one line """ from functools import partial import regex as re from ..helpers import ( inside_ignored_block, inside_protected_trans_block, is_safe_closing_tag, ) from ..settings import Config def METHOD_NAME(html: str, config: Config) -> str: """Compress back tags that do not need to be expanded.""" # put empty tags on one line def strip_space(config: Config, html: str, match: re.Match) -> str: """Trim leading whitespace.""" # either inside a block, or this is a newline + closing block tag. # if it is a newline + closing block we can format it. if inside_ignored_block(config, html, match) and not is_safe_closing_tag( config, match.group() ): return match.group() # trimmed blocks should not be here. # we need to full html to check what type of # opening block it was - trimmed or not trimmed if inside_protected_trans_block(config, html[: match.end()], match): return match.group().rstrip() lines = len( re.findall( r"\n", match.group(2), ) ) blank_lines = "\n" * lines if lines > config.max_blank_lines: blank_lines = "\n" * max(config.max_blank_lines, 0) return match.group(1) + blank_lines func = partial(strip_space, config, html) line_contents = r"(.*?)" trailing_contents = r"\n \t" if config.preserve_blank_lines: line_contents = r"([^\n]+?)" trailing_contents = r" \t" if not config.preserve_leading_space: # remove any leading/trailing space html = re.sub( re.compile(rf"^[ \t]*{line_contents}([{trailing_contents}]*)$", re.M), func, html, ) else: # only remove leading space in front of tags # <, {% html = re.sub( re.compile(rf"^[ \t]*((?:<|{{%).*?)([{trailing_contents}]*)$", re.M), func, html, ) html = re.sub( re.compile(rf"^{line_contents}([{trailing_contents}]*)$", re.M), func, html ) def add_blank_line_after(config: Config, html: str, match: re.Match) -> str: """Add break after if not in ignored block.""" if inside_ignored_block(config, html, match): return match.group() # check that next line is not blank. if html[match.end() : match.end() + 1] != "\n": # noqa:E203 return match.group() + "\n" return match.group() func = partial(add_blank_line_after, config, html) # should we add blank lines after load tags? if config.blank_line_after_tag: for tag in [x.strip() for x in config.blank_line_after_tag.split(",")]: html = re.sub( re.compile( rf"((?:{{%\s*?{tag}\b[^}}]+?%}}\n?)+)", re.IGNORECASE | re.MULTILINE | re.DOTALL, ), func, html, ) def add_blank_line_before(config: Config, html: str, match: re.Match) -> str: """Add break before if not in ignored block and not first line in file.""" if inside_ignored_block(config, html, match) or match.start() == 0: return match.group() return "\n" + match.group() func = partial(add_blank_line_before, config, html) # should we add blank lines before load tags? if config.blank_line_before_tag: for tag in [x.strip() for x in config.blank_line_before_tag.split(",")]: html = re.sub( re.compile( rf"(?<!^\n)((?:{{%\s*?{tag}\b[^}}]+?%}}\n?)+)", re.IGNORECASE | re.MULTILINE | re.DOTALL, ), func, html, ) # add line after yaml front matter def yaml_add_blank_line_after(html: str, match: re.Match) -> str: """Add break after if not in ignored block.""" if match.start() == 0 and not html.startswith("\n\n", match.end()): # verify there are not already blank lines return match.group() + "\n" return match.group() if config.no_line_after_yaml is False: func = partial(yaml_add_blank_line_after, html) html = re.sub( re.compile( r"(^---.+?---)$", re.MULTILINE | re.DOTALL, ), func, html, ) return html def condense_html(html, config): """Put short tags back on a single line.""" if config.preserve_leading_space: # if a user is attempting to reuse any leading # space for other purposes, we should not try to remove it. return html def condense_line(config: Config, html: str, match: re.Match) -> str: """Put contents on a single line if below max line length.""" if config.line_break_after_multiline_tag: # always force a break by pretending the line is too long. combined_length = config.max_line_length + 1 else: combined_length = len( match.group(1).splitlines()[-1] + match.group(3) + match.group(4) ) if ( not inside_ignored_block(config, html, match) and combined_length < config.max_line_length and if_blank_line_after_match(config, match.group(3)) and if_blank_line_before_match(config, match.group(3)) ): return match.group(1) + match.group(3) + match.group(4) return match.group() def if_blank_line_after_match(config: Config, html: str) -> bool: """Check if there should be a blank line after.""" if config.blank_line_after_tag: return not any( re.findall( re.compile( rf"((?:{{%\s*?{tag}[^}}]+?%}}\n?)+)", re.IGNORECASE | re.MULTILINE | re.DOTALL, ), html, ) for tag in [x.strip() for x in config.blank_line_after_tag.split(",")] ) return True def if_blank_line_before_match(config: Config, html: str) -> bool: """Check if there should be a blank line before.""" if config.blank_line_before_tag: return not any( re.findall( re.compile( rf"((?:{{%\s*?{tag}[^}}]+?%}}\n?)+)", re.IGNORECASE | re.MULTILINE | re.DOTALL, ), html, ) for tag in [x.strip() for x in config.blank_line_before_tag.split(",")] ) return True # add blank lines before tags func = partial(condense_line, config, html) # put short single line tags on one line html = re.sub( re.compile( rf"(<({config.optional_single_line_html_tags})\b(?:\"[^\"]*\"|'[^']*'|{{[^}}]*}}|[^'\">{{}}])*>)\s*([^<\n]*?)\s*?(</(\2)>)", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE, ), func, html, ) # put short template tags back on one line. must have leading space # jinja +%} and {%+ intentionally omitted. html = re.sub( re.compile( rf"((?:\s|^){{%-?[ ]*?({config.optional_single_line_template_tags})\b(?:(?!\n|%}}).)*?%}})\s*([^%\n]*?)\s*?({{%-?[ ]+?end(\2)[ ]*?%}})", flags=re.IGNORECASE | re.MULTILINE | re.VERBOSE, ), func, html, ) return html
null
34
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkoutboundbot.endpoint import endpoint_data class SearchTaskRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'OutboundBot', '2019-12-26', 'SearchTask') self.set_method('GET') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ActualTimeLte(self): # Long return self.get_query_params().get('ActualTimeLte') def set_ActualTimeLte(self, ActualTimeLte): # Long self.add_query_param('ActualTimeLte', ActualTimeLte) def get_OtherId(self): # String return self.get_query_params().get('OtherId') def set_OtherId(self, OtherId): # String self.add_query_param('OtherId', OtherId) def get_TaskCreateTimeLte(self): # Long return self.get_query_params().get('TaskCreateTimeLte') def set_TaskCreateTimeLte(self, TaskCreateTimeLte): # Long self.add_query_param('TaskCreateTimeLte', TaskCreateTimeLte) def get_JobId(self): # String return self.get_query_params().get('JobId') def set_JobId(self, JobId): # String self.add_query_param('JobId', JobId) def get_TaskCreateTimeGte(self): # Long return self.get_query_params().get('TaskCreateTimeGte') def set_TaskCreateTimeGte(self, TaskCreateTimeGte): # Long self.add_query_param('TaskCreateTimeGte', TaskCreateTimeGte) def get_CalledNumber(self): # String return self.get_query_params().get('CalledNumber') def set_CalledNumber(self, CalledNumber): # String self.add_query_param('CalledNumber', CalledNumber) def get_UserIdMatch(self): # String return self.get_query_params().get('UserIdMatch') def set_UserIdMatch(self, UserIdMatch): # String self.add_query_param('UserIdMatch', UserIdMatch) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_ScriptNameQuery(self): # String return self.get_query_params().get('ScriptNameQuery') def set_ScriptNameQuery(self, ScriptNameQuery): # String self.add_query_param('ScriptNameQuery', ScriptNameQuery) def get_PageIndex(self): # Integer return self.get_query_params().get('PageIndex') def set_PageIndex(self, PageIndex): # Integer self.add_query_param('PageIndex', PageIndex) def get_SortOrder(self): # String return self.get_query_params().get('SortOrder') def set_SortOrder(self, SortOrder): # String self.add_query_param('SortOrder', SortOrder) def get_TaskStatusStringList(self): # String return self.get_query_params().get('TaskStatusStringList') def set_TaskStatusStringList(self, TaskStatusStringList): # String self.add_query_param('TaskStatusStringList', TaskStatusStringList) def get_JobGroupNameQuery(self): # String return self.get_query_params().get('JobGroupNameQuery') def set_JobGroupNameQuery(self, JobGroupNameQuery): # String self.add_query_param('JobGroupNameQuery', JobGroupNameQuery) def get_TaskId(self): # String return self.get_query_params().get('TaskId') def set_TaskId(self, TaskId): # String self.add_query_param('TaskId', TaskId) def get_InstanceId(self): # String return self.get_query_params().get('InstanceId') def set_InstanceId(self, InstanceId): # String self.add_query_param('InstanceId', InstanceId) def get_RecordingDurationGte(self): # Long return self.get_query_params().get('RecordingDurationGte') def set_RecordingDurationGte(self, RecordingDurationGte): # Long self.add_query_param('RecordingDurationGte', RecordingDurationGte) def get_CallDurationLte(self): # Long return self.get_query_params().get('CallDurationLte') def set_CallDurationLte(self, CallDurationLte): # Long self.add_query_param('CallDurationLte', CallDurationLte) def get_JobGroupId(self): # String return self.get_query_params().get('JobGroupId') def set_JobGroupId(self, JobGroupId): # String self.add_query_param('JobGroupId', JobGroupId) def get_SortBy(self): # String return self.get_query_params().get('SortBy') def set_SortBy(self, SortBy): # String self.add_query_param('SortBy', SortBy) def get_JobStatusStringList(self): # String return self.get_query_params().get('JobStatusStringList') def set_JobStatusStringList(self, JobStatusStringList): # String self.add_query_param('JobStatusStringList', JobStatusStringList) def METHOD_NAME(self): # Long return self.get_query_params().get('ActualTimeGte') def set_ActualTimeGte(self, ActualTimeGte): # Long self.add_query_param('ActualTimeGte', ActualTimeGte) def get_CallDurationGte(self): # Long return self.get_query_params().get('CallDurationGte') def set_CallDurationGte(self, CallDurationGte): # Long self.add_query_param('CallDurationGte', CallDurationGte) def get_RecordingDurationLte(self): # Long return self.get_query_params().get('RecordingDurationLte') def set_RecordingDurationLte(self, RecordingDurationLte): # Long self.add_query_param('RecordingDurationLte', RecordingDurationLte)
null
35
import pytest from framework.auth.core import Auth from api_tests.utils import disconnected_from_listeners from osf.models import ( DraftNode, Registration, DraftRegistration, NodeLicense, NodeLog, ) from osf.exceptions import NodeStateError from osf.utils.permissions import READ, WRITE, ADMIN from osf_tests.factories import ( DraftNodeFactory, DraftRegistrationFactory, AuthUserFactory, SubjectFactory, UserFactory, InstitutionFactory, ProjectFactory, get_default_metaschema, ) from website.project.signals import after_create_registration pytestmark = pytest.mark.django_db NEW_YEAR = '2014' COPYLEFT_HOLDERS = ['Richard Stallman'] @pytest.fixture() def user(): return UserFactory() @pytest.fixture() def draft_node(user): return DraftNodeFactory(creator=user) @pytest.fixture() def project(user): return ProjectFactory(creator=user) @pytest.fixture() def draft_registration(user, project): return DraftRegistrationFactory(branched_from=project) @pytest.fixture() def auth(user): return Auth(user) @pytest.fixture() def write_contrib(): return AuthUserFactory() @pytest.fixture() def subject(): return SubjectFactory() @pytest.fixture() def institution(): return InstitutionFactory() @pytest.fixture() def METHOD_NAME(): return 'A Study of Elephants' @pytest.fixture() def description(): return 'Loxodonta africana' @pytest.fixture() def category(): return 'Methods and Materials' @pytest.fixture() def license(): return NodeLicense.objects.get(license_id='GPL3') @pytest.fixture() def make_complex_draft_registration(METHOD_NAME, institution, description, category, write_contrib, license, subject, user): def make_draft_registration(node=None): draft_registration = DraftRegistration.create_from_node( user=user, schema=get_default_metaschema(), data={}, node=node if node else None ) user.add_or_update_affiliated_institution(institution) draft_registration.set_title(METHOD_NAME, Auth(user)) draft_registration.set_description(description, Auth(user)) draft_registration.category = category draft_registration.add_contributor(write_contrib, permissions=WRITE) draft_registration.set_node_license( { 'id': license.license_id, 'year': NEW_YEAR, 'copyrightHolders': COPYLEFT_HOLDERS }, auth=Auth(user), save=True ) draft_registration.add_tag('savanna', Auth(user)) draft_registration.add_tag('taxonomy', Auth(user)) draft_registration.set_subjects([[subject._id]], auth=Auth(draft_registration.creator)) draft_registration.affiliated_institutions.add(institution) draft_registration.save() return draft_registration return make_draft_registration class TestDraftNode: def test_draft_node_creation(self, user): draft_node = DraftNode.objects.create(METHOD_NAME='Draft Registration', creator_id=user.id) assert draft_node.is_public is False assert draft_node.has_addon('osfstorage') is True def test_create_draft_registration_without_node(self, user): data = {'some': 'data'} draft = DraftRegistration.create_from_node( user=user, schema=get_default_metaschema(), data=data, ) assert draft.METHOD_NAME == 'Untitled' assert draft.branched_from.METHOD_NAME == 'Untitled' assert draft.branched_from.type == 'osf.draftnode' assert draft.branched_from.creator == user assert len(draft.logs.all()) == 0 def test_register_draft_node(self, user, draft_node, draft_registration): assert draft_node.type == 'osf.draftnode' with disconnected_from_listeners(after_create_registration): registration = draft_node.register_node(get_default_metaschema(), Auth(user), draft_registration, None) assert type(registration) is Registration assert draft_node._id != registration._id draft_node.reload() assert draft_node.type == 'osf.node' assert len(draft_node.logs.all()) == 1 assert draft_node.logs.first().action == NodeLog.PROJECT_CREATED_FROM_DRAFT_REG def test_draft_registration_fields_are_copied_back_to_draft_node(self, user, institution, subject, write_contrib, METHOD_NAME, description, category, license, make_complex_draft_registration): draft_registration = make_complex_draft_registration() draft_node = draft_registration.branched_from with disconnected_from_listeners(after_create_registration): draft_registration.register(auth=Auth(user), save=True) draft_node.reload() assert draft_node.type == 'osf.node' assert draft_node.METHOD_NAME == METHOD_NAME assert draft_node.description == description assert draft_node.category == category assert user in draft_node.contributors.all() assert write_contrib in draft_node.contributors.all() assert draft_node.get_permissions(user) == [READ, WRITE, ADMIN] assert draft_node.get_permissions(write_contrib) == [READ, WRITE] assert draft_node.node_license.license_id == license.license_id assert draft_node.node_license.name == license.name assert draft_node.node_license.copyright_holders == COPYLEFT_HOLDERS draft_tags = draft_node.tags.values_list('name', flat=True) assert 'savanna' in draft_tags assert 'taxonomy' in draft_tags assert subject in draft_node.subjects.all() assert institution in draft_node.affiliated_institutions.all() def test_draft_registration_fields_are_not_copied_back_to_original_node(self, user, institution, project, subject, write_contrib, METHOD_NAME, description, category, license, make_complex_draft_registration): draft_registration = make_complex_draft_registration(node=project) with disconnected_from_listeners(after_create_registration): draft_registration.register(auth=Auth(user), save=True) project.reload() assert project.type == 'osf.node' assert project.METHOD_NAME != METHOD_NAME assert project.description != description assert project.category != category assert user in project.contributors.all() assert write_contrib not in project.contributors.all() assert project.get_permissions(user) == [READ, WRITE, ADMIN] assert project.node_license is None project_tags = project.tags.values_list('name', flat=True) assert 'savanna' not in project_tags assert 'taxonomy' not in project_tags assert subject not in project.subjects.all() assert institution not in project.affiliated_institutions.all() def test_cannot_make_draft_node_public(self, draft_node): with pytest.raises(NodeStateError): draft_node.set_privacy('public', save=True)
null
36
"""Tests the xonsh lexer.""" import os import pytest from xonsh.pytest.tools import ON_WINDOWS, skip_if_on_unix, skip_if_on_windows @pytest.fixture def check_eval(xonsh_execer, xonsh_session, monkeypatch): def factory(input): env = { "AUTO_CD": False, "XONSH_ENCODING": "utf-8", "XONSH_ENCODING_ERRORS": "strict", "PATH": [], } for key, val in env.items(): monkeypatch.setitem(xonsh_session.env, key, val) if ON_WINDOWS: monkeypatch.setitem( xonsh_session.env, "PATHEXT", [".COM", ".EXE", ".BAT", ".CMD"] ) xonsh_execer.eval(input) return True return factory @skip_if_on_unix def test_win_ipconfig(check_eval): assert check_eval(os.environ["SYSTEMROOT"] + "\\System32\\ipconfig.exe /all") @skip_if_on_unix def test_ipconfig(check_eval): assert check_eval("ipconfig /all") @skip_if_on_windows def METHOD_NAME(check_eval): assert check_eval("/bin/ls -l") def test_ls_dashl(xonsh_execer_parse): assert xonsh_execer_parse("ls -l") def test_which_ls(xonsh_execer_parse): assert xonsh_execer_parse("which ls") def test_echo_hello(xonsh_execer_parse): assert xonsh_execer_parse("echo hello") def test_echo_star_with_semi(xonsh_execer_parse): assert xonsh_execer_parse("echo * spam ; ![echo eggs]\n") def test_simple_func(xonsh_execer_parse): code = "def prompt():\n" " return '{user}'.format(user='me')\n" assert xonsh_execer_parse(code) def test_lookup_alias(xonsh_execer_parse): code = "def foo(a, s=None):\n" ' return "bar"\n' "@(foo)\n" assert xonsh_execer_parse(code) def test_lookup_anon_alias(xonsh_execer_parse): code = 'echo "hi" | @(lambda a, s=None: a[0]) foo bar baz\n' assert xonsh_execer_parse(code) def test_simple_func_broken(xonsh_execer_parse): code = "def prompt():\n" " return '{user}'.format(\n" " user='me')\n" assert xonsh_execer_parse(code) def test_bad_indent(xonsh_execer_parse): code = "if True:\n" "x = 1\n" with pytest.raises(SyntaxError): xonsh_execer_parse(code) def test_comment_colon_ending(xonsh_execer_parse): code = "# this is a comment:\necho hello" assert xonsh_execer_parse(code) def test_good_rhs_subproc(): # nonsense but parsable code = "str().split() | ![grep exit]\n" assert code def test_bad_rhs_subproc(xonsh_execer_parse): # nonsense but unparsable code = "str().split() | grep exit\n" with pytest.raises(SyntaxError): xonsh_execer_parse(code) def test_indent_with_empty_line(xonsh_execer_parse): code = "if True:\n" "\n" " some_command for_sub_process_mode\n" assert xonsh_execer_parse(code) def test_command_in_func(xonsh_execer_parse): code = "def f():\n" " echo hello\n" assert xonsh_execer_parse(code) def test_command_in_func_with_comment(xonsh_execer_parse): code = "def f():\n" " echo hello # comment\n" assert xonsh_execer_parse(code) def test_pyeval_redirect(xonsh_execer_parse): code = 'echo @("foo") > bar\n' assert xonsh_execer_parse(code) def test_pyeval_multiline_str(xonsh_execer_parse): code = 'echo @("""hello\nmom""")\n' assert xonsh_execer_parse(code) def test_echo_comma(xonsh_execer_parse): code = "echo ,\n" assert xonsh_execer_parse(code) def test_echo_comma_val(xonsh_execer_parse): code = "echo ,1\n" assert xonsh_execer_parse(code) def test_echo_comma_2val(xonsh_execer_parse): code = "echo 1,2\n" assert xonsh_execer_parse(code) def test_echo_line_cont(xonsh_execer_parse): code = 'echo "1 \\\n2"\n' assert xonsh_execer_parse(code) @pytest.mark.parametrize( "code", [ "echo a and \\\necho b\n", "echo a \\\n or echo b\n", "echo a \\\n or echo b and \\\n echo c\n", "if True:\\\n echo a \\\n b\n", ], ) def test_two_echo_line_cont(code, xonsh_execer_parse): assert xonsh_execer_parse(code) def test_eval_eol(check_eval): assert check_eval("0") and check_eval("0\n") def test_annotated_assign(xonsh_execer_exec): # issue #3959 - didn't work because of `CtxAwareTransformer` assert xonsh_execer_exec("x : int = 42") def test_exec_eol(xonsh_execer_exec): locs = dict() assert xonsh_execer_exec("a=0", locs=locs) and xonsh_execer_exec("a=0\n", locs=locs) def test_exec_print(capsys, xonsh_execer_exec): ls = {"nested": "some long list"} xonsh_execer_exec("print(ls)", locs=dict(ls=ls)) out, err = capsys.readouterr() assert out.strip() == repr(ls) def test_exec_function_scope(xonsh_execer_exec): # issue 4363 assert xonsh_execer_exec("x = 0; (lambda: x)()") assert xonsh_execer_exec("x = 0; [x for _ in [0]]") def test_exec_scope_reuse(xonsh_execer_exec): # Scopes should not be reused between execs. # A first-pass incorrect solution to issue 4363 made this mistake. assert xonsh_execer_exec("x = 0") with pytest.raises(NameError): xonsh_execer_exec("print(x)")
null
37
""" This type stub file was generated by pyright. """ from collections import UserDict from celery.utils.serialization import strtobool """Worker remote control command implementations.""" __all__ = ("Panel",) DEFAULT_TASK_INFO_ITEMS = ... logger = ... controller_info_t = ... def ok(value): ... def nok(value): ... class Panel(UserDict): """Global registry of remote control commands.""" data = ... meta = ... @classmethod def register(cls, *args, **kwargs): ... def control_command(**kwargs): ... def inspect_command(**kwargs): ... @inspect_command() def report(state): # -> dict[str, Unknown]: """Information about Celery installation for bug reports.""" ... @inspect_command( alias="dump_conf", signature="[include_defaults=False]", args=[("with_defaults", strtobool)], ) def conf( state, with_defaults=..., **kwargs ): # -> dict[Unknown, Unknown | Any] | list[Unknown] | dict[Unknown, Unknown] | str: """List configuration.""" ... @inspect_command(variadic="ids", signature="[id1 [id2 [... [idN]]]]") def query_task( state, ids, **kwargs ): # -> dict[Unknown, tuple[Literal['active', 'reserved', 'ready'], Unknown]]: """Query for task information by id.""" ... @control_command(variadic="task_id", signature="[id1 [id2 [... [idN]]]]") def revoke(state, task_id, terminate=..., signal=..., **kwargs): # -> dict[str, str]: """Revoke task by task id (or list of ids). Keyword Arguments: terminate (bool): Also terminate the process if the task is active. signal (str): Name of signal to use for terminate (e.g., ``KILL``). """ ... @control_command( variadic="task_id", args=[("signal", str)], signature="<signal> [id1 [id2 [... [idN]]]]", ) def terminate(state, signal, task_id, **kwargs): # -> dict[str, str]: """Terminate task by task id (or list of ids).""" ... @control_command( args=[("task_name", str), ("rate_limit", str)], signature="<task_name> <rate_limit (e.g., 5/s | 5/m | 5/h)>", ) def rate_limit(state, task_name, rate_limit, **kwargs): # -> dict[str, str]: """Tell worker(s) to modify the rate limit for a task by type. See Also: :attr:`celery.app.task.Task.rate_limit`. Arguments: task_name (str): Type of task to set rate limit for. rate_limit (int, str): New rate limit. """ ... @control_command( args=[("task_name", str), ("soft", float), ("hard", float)], signature="<task_name> <soft_secs> [hard_secs]", ) def time_limit(state, task_name=..., hard=..., soft=..., **kwargs): # -> dict[str, str]: """Tell worker(s) to modify the time limit for task by type. Arguments: task_name (str): Name of task to change. hard (float): Hard time limit. soft (float): Soft time limit. """ ... @inspect_command() def clock(state, **kwargs): # -> dict[str, Unknown]: """Get current logical clock value.""" ... @control_command() def election(state, id, topic, action=..., **kwargs): # -> None: """Hold election. Arguments: id (str): Unique election id. topic (str): Election topic. action (str): Action to take for elected actor. """ ... @control_command() def enable_events(state): # -> dict[str, str]: """Tell worker(s) to send task-related events.""" ... @control_command() def disable_events(state): # -> dict[str, str]: """Tell worker(s) to stop sending task-related events.""" ... @control_command() def heartbeat(state): # -> None: """Tell worker(s) to send event heartbeat immediately.""" ... @inspect_command(visible=False) def hello( state, from_node, revoked=..., **kwargs ): # -> dict[str, Unknown | dict[Unknown, Unknown]] | None: """Request mingle sync-data.""" ... @inspect_command(default_timeout=0.2) def METHOD_NAME(state, **kwargs): # -> dict[str, str]: """Ping worker(s).""" ... @inspect_command() def stats(state, **kwargs): """Request worker statistics/information.""" ... @inspect_command(alias="dump_schedule") def scheduled( state, **kwargs ): # -> list[dict[str, Unknown | str | dict[str, Unknown | bool | dict[str, Unknown | Any | None] | None] | None]]: """List of currently scheduled ETA/countdown tasks.""" ... @inspect_command(alias="dump_reserved") def reserved(state, **kwargs): # -> list[Unknown]: """List of currently reserved tasks, not including scheduled/active.""" ... @inspect_command(alias="dump_active") def active(state, safe=..., **kwargs): # -> list[Unknown]: """List of tasks currently being executed.""" ... @inspect_command(alias="dump_revoked") def revoked(state, **kwargs): # -> list[Unknown]: """List of revoked task-ids.""" ... @inspect_command( alias="dump_tasks", variadic="taskinfoitems", signature="[attr1 [attr2 [... [attrN]]]]", ) def registered( state, taskinfoitems=..., builtins=..., **kwargs ): # -> list[str | Unknown]: """List of registered tasks. Arguments: taskinfoitems (Sequence[str]): List of task attributes to include. Defaults to ``exchange,routing_key,rate_limit``. builtins (bool): Also include built-in tasks. """ ... @inspect_command( default_timeout=60, args=[("type", str), ("num", int), ("max_depth", int)], signature="[object_type=Request] [num=200 [max_depth=10]]", ) def objgraph(state, num=..., max_depth=..., type=...): # -> dict[str, str]: """Create graph of uncollected objects (memory-leak debugging). Arguments: num (int): Max number of objects to graph. max_depth (int): Traverse at most n levels deep. type (str): Name of object to graph. Default is ``"Request"``. """ ... @inspect_command() def memsample(state, **kwargs): # -> str | None: """Sample current RSS memory usage.""" ... @inspect_command(args=[("samples", int)], signature="[n_samples=10]") def memdump(state, samples=..., **kwargs): # -> str: """Dump statistics of previous memsample requests.""" ... @control_command(args=[("n", int)], signature="[N=1]") def pool_grow(state, n=..., **kwargs): # -> dict[str, str]: """Grow pool by n processes/threads.""" ... @control_command(args=[("n", int)], signature="[N=1]") def pool_shrink(state, n=..., **kwargs): # -> dict[str, str]: """Shrink pool by n processes/threads.""" ... @control_command() def pool_restart( state, modules=..., reload=..., reloader=..., **kwargs ): # -> dict[str, str]: """Restart execution pool.""" ... @control_command(args=[("max", int), ("min", int)], signature="[max [min]]") def autoscale(state, max=..., min=...): # -> dict[str, str]: """Modify autoscale settings.""" ... @control_command() def shutdown(state, msg=..., **kwargs): """Shutdown worker(s).""" ... @control_command( args=[ ("queue", str), ("exchange", str), ("exchange_type", str), ("routing_key", str), ], signature="<queue> [exchange [type [routing_key]]]", ) def add_consumer( state, queue, exchange=..., exchange_type=..., routing_key=..., **options ): # -> dict[str, str]: """Tell worker(s) to consume from task queue by name.""" ... @control_command(args=[("queue", str)], signature="<queue>") def cancel_consumer(state, queue, **_): # -> dict[str, str]: """Tell worker(s) to stop consuming from task queue by name.""" ... @inspect_command() def active_queues(state): # -> list[dict[Unknown, Unknown]]: """List the task queues a worker is currently consuming from.""" ...
null
38
"""Decorators used by moviepy.""" import inspect import os import decorator from moviepy.tools import convert_to_seconds @decorator.decorator def outplace(func, clip, *args, **kwargs): """Applies ``func(clip.copy(), *args, **kwargs)`` and returns ``clip.copy()``.""" new_clip = clip.copy() func(new_clip, *args, **kwargs) return new_clip @decorator.decorator def convert_masks_to_RGB(func, clip, *args, **kwargs): """If the clip is a mask, convert it to RGB before running the function.""" if clip.is_mask: clip = clip.to_RGB() return func(clip, *args, **kwargs) @decorator.decorator def apply_to_mask(func, clip, *args, **kwargs): """Applies the same function ``func`` to the mask of the clip created with ``func``. """ new_clip = func(clip, *args, **kwargs) if getattr(new_clip, "mask", None): new_clip.mask = func(new_clip.mask, *args, **kwargs) return new_clip @decorator.decorator def apply_to_audio(func, clip, *args, **kwargs): """Applies the function ``func`` to the audio of the clip created with ``func``.""" new_clip = func(clip, *args, **kwargs) if getattr(new_clip, "audio", None): new_clip.audio = func(new_clip.audio, *args, **kwargs) return new_clip @decorator.decorator def requires_duration(func, clip, *args, **kwargs): """Raises an error if the clip has no duration.""" if clip.duration is None: raise ValueError("Attribute 'duration' not set") else: return func(clip, *args, **kwargs) @decorator.decorator def requires_fps(func, clip, *args, **kwargs): """Raises an error if the clip has no fps.""" if not hasattr(clip, "fps") or clip.fps is None: raise ValueError("Attribute 'fps' not set") else: return func(clip, *args, **kwargs) @decorator.decorator def audio_video_fx(func, clip, *args, **kwargs): """Use an audio function on a video/audio clip. This decorator tells that the function func (audioclip -> audioclip) can be also used on a video clip, at which case it returns a videoclip with unmodified video and modified audio. """ if hasattr(clip, "audio"): new_clip = clip.copy() if clip.audio is not None: new_clip.audio = func(clip.audio, *args, **kwargs) return new_clip else: return func(clip, *args, **kwargs) def preprocess_args(fun, varnames): """Applies fun to variables in varnames before launching the function.""" def wrapper(func, *args, **kwargs): names = inspect.getfullargspec(func).args new_args = [ fun(arg) if (name in varnames) and (arg is not None) else arg for (arg, name) in zip(args, names) ] new_kwargs = { kwarg: fun(value) if kwarg in varnames else value for (kwarg, value) in kwargs.items() } return func(*new_args, **new_kwargs) return decorator.decorator(wrapper) def METHOD_NAME(varnames): """Converts the specified variables to seconds.""" return preprocess_args(convert_to_seconds, varnames) def convert_path_to_string(varnames): """Converts the specified variables to a path string.""" return preprocess_args(os.fspath, varnames) @decorator.decorator def add_mask_if_none(func, clip, *args, **kwargs): """Add a mask to the clip if there is none.""" if clip.mask is None: clip = clip.add_mask() return func(clip, *args, **kwargs) @decorator.decorator def use_clip_fps_by_default(func, clip, *args, **kwargs): """Will use ``clip.fps`` if no ``fps=...`` is provided in **kwargs**.""" def find_fps(fps): if fps is not None: return fps elif getattr(clip, "fps", None): return clip.fps raise AttributeError( "No 'fps' (frames per second) attribute specified" " for function %s and the clip has no 'fps' attribute. Either" " provide e.g. fps=24 in the arguments of the function, or define" " the clip's fps with `clip.fps=24`" % func.__name__ ) names = inspect.getfullargspec(func).args[1:] new_args = [ find_fps(arg) if (name == "fps") else arg for (arg, name) in zip(args, names) ] new_kwargs = { kwarg: find_fps(value) if kwarg == "fps" else value for (kwarg, value) in kwargs.items() } return func(clip, *new_args, **new_kwargs)
null
39
# container-service-extension # Copyright (c) 2020 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause from typing import Dict, Optional import container_service_extension.common.utils.pyvcloud_utils as vcd_utils import container_service_extension.common.utils.server_utils as server_utils import container_service_extension.logging.logger as logger import container_service_extension.security.context.user_context as user_context # noqa: E501 class OperationContext: def __init__( self, auth_token: str, request_id: Optional[str] = None, mqtt_publisher=None ): self._auth_token: str = auth_token # Request ID; may be None if OperationContext is initialized outside of # request_dispatcher.py self.request_id: Optional[str] = request_id # map for storing user's context at different api versions # `None` key, maps to the client at the highest api version supported # by the vCD and pyvcloud self._user_context_map: Dict[Optional[str], user_context.UserContext] = {} # noqa: E501 # map for storing sys admin user's context at different api versions # `None` key maps to the client at the highest api version supported # by the vCD and pyvcloud self._sysadmin_user_context_map: Dict[Optional[str], user_context.UserContext] = {} # noqa: E501 # async operations should call end() when they are finished self.is_async: bool = False self.mqtt_publisher = mqtt_publisher @property def client(self): return self.user.client @property def cloudapi_client(self): return self.user.cloud_api_client @property def sysadmin_client(self): return self.sysadmin_user.client @property def sysadmin_cloudapi_client(self): return self.sysadmin_user.cloud_api_client @property def user(self): api_version = None # marker for default api version return self.get_user_context(api_version) @property def sysadmin_user(self): api_version = None # marker for default api version return self.get_sysadmin_user_context(api_version) def get_client(self, api_version: Optional[str]): return self.get_user_context(api_version).client def METHOD_NAME(self, api_version: Optional[str]): return self.get_user_context(api_version).cloud_api_client def get_sysadmin_client(self, api_version: Optional[str]): return self.get_sysadmin_user_context(api_version).client def get_sysadmin_cloudapi_client(self, api_version: Optional[str]): return self.get_sysadmin_user_context(api_version).cloud_api_client def get_user_context(self, api_version: Optional[str]): if api_version not in self._user_context_map: self._update_user_context_map(api_version=api_version) return self._user_context_map[api_version] def get_sysadmin_user_context(self, api_version: Optional[str]): if api_version not in self._sysadmin_user_context_map: self._update_sysadmin_user_context_map(api_version=api_version) return self._sysadmin_user_context_map[api_version] def _update_user_context_map(self, api_version: Optional[str]): _client = vcd_utils.connect_vcd_user_via_token( tenant_auth_token=self._auth_token, api_version=api_version ) log_wire = server_utils.get_server_runtime_config().get_value_at('service.log_wire') # noqa: E501 logger_wire = logger.NULL_LOGGER if log_wire: logger_wire = logger.SERVER_CLOUDAPI_WIRE_LOGGER _cloudapi_client = vcd_utils.get_cloudapi_client_from_vcd_client( client=_client, logger_debug=logger.SERVER_LOGGER, logger_wire=logger_wire) _user_context = user_context.UserContext( client=_client, cloud_api_client=_cloudapi_client) self._user_context_map[api_version] = _user_context def _update_sysadmin_user_context_map(self, api_version: Optional[str]): _sysadmin_client = vcd_utils.get_sys_admin_client( api_version=api_version) log_wire = server_utils.get_server_runtime_config().get_value_at('service.log_wire') # noqa: E501 logger_wire = logger.NULL_LOGGER if log_wire: logger_wire = logger.SERVER_CLOUDAPI_WIRE_LOGGER _sysadmin_cloudapi_client = \ vcd_utils.get_cloudapi_client_from_vcd_client( client=_sysadmin_client, logger_debug=logger.SERVER_LOGGER, logger_wire=logger_wire) _sysadmin_user_context = user_context.UserContext( client=_sysadmin_client, cloud_api_client=_sysadmin_cloudapi_client) self._sysadmin_user_context_map[api_version] = _sysadmin_user_context def end(self): for api_version, sysadmin_user_context in \ self._sysadmin_user_context_map.items(): try: sysadmin_user_context.client.logout() except Exception: if not api_version: api_version = "Default api version" msg = f"Failed to logout user: {sysadmin_user_context.name}" \ f"at api_version: {api_version}." logger.SERVER_LOGGER.debug(msg, exc_info=True) self._user_context_map.clear() self._sysadmin_user_context_map.clear()
null
40
"""CheckpointHook with validation results for classification task.""" # Copyright (C) 2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # Copyright (c) Open-MMLab. All rights reserved. from pathlib import Path from typing import Optional from mmcv.runner import BaseRunner from mmcv.runner.dist_utils import allreduce_params, master_only from mmcv.runner.hooks.hook import HOOKS, Hook @HOOKS.register_module() class CheckpointHookWithValResults(Hook): # pylint: disable=too-many-instance-attributes """Save checkpoints periodically. Args: interval (int): The saving period. If ``by_epoch=True``, interval indicates epochs, otherwise it indicates iterations. Default: -1, which means "never". by_epoch (bool): Saving checkpoints by epoch or by iteration. Default: True. save_optimizer (bool): Whether to save optimizer state_dict in the checkpoint. It is usually used for resuming experiments. Default: True. out_dir (str, optional): The directory to save checkpoints. If not specified, ``runner.work_dir`` will be used by default. max_keep_ckpts (int, optional): The maximum checkpoints to keep. In some cases we want only the latest few checkpoints and would like to delete old ones to save the disk space. Default: -1, which means unlimited. sync_buffer (bool): Whether to synchronize buffers in different gpus. Default: False. """ def __init__( self, interval=-1, by_epoch=True, save_optimizer=True, out_dir=None, max_keep_ckpts=-1, sync_buffer=False, **kwargs, ) -> None: self.interval = interval self.by_epoch = by_epoch self.save_optimizer = save_optimizer self.out_dir = out_dir self.max_keep_ckpts = max_keep_ckpts self.args = kwargs self.sync_buffer = sync_buffer self._best_model_weight: Optional[Path] = None def before_run(self, runner): """Set output directopy if not set.""" if not self.out_dir: self.out_dir = runner.work_dir def after_train_epoch(self, runner): """Checkpoint stuffs after train epoch.""" if not self.by_epoch or not self.every_n_epochs(runner, self.interval): return if self.sync_buffer: allreduce_params(runner.model.buffers()) save_ema_model = hasattr(runner, "save_ema_model") and runner.save_ema_model if save_ema_model: backup_model = runner.model runner.model = runner.ema_model if getattr(runner, "save_ckpt", False): runner.logger.info(f"Saving best checkpoint at {runner.epoch + 1} epochs") self.METHOD_NAME(runner) runner.save_ckpt = False self._save_latest_checkpoint(runner) if save_ema_model: runner.model = backup_model runner.save_ema_model = False @master_only def METHOD_NAME(self, runner): """Save the current checkpoint and delete unwanted checkpoint.""" if self._best_model_weight is not None: # remove previous best model weight prev_model_weight = self.out_dir / self._best_model_weight if prev_model_weight.exists(): prev_model_weight.unlink() if self.by_epoch: weight_name = f"best_epoch_{runner.epoch + 1}.pth" else: weight_name = f"best_iter_{runner.iter + 1}.pth" runner.save_checkpoint(self.out_dir, filename_tmpl=weight_name, save_optimizer=self.save_optimizer, **self.args) self._best_model_weight = Path(weight_name) if runner.meta is not None: runner.meta.setdefault("hook_msgs", dict()) runner.meta["hook_msgs"]["best_ckpt"] = str(self.out_dir / self._best_model_weight) @master_only def _save_latest_checkpoint(self, runner): """Save the current checkpoint and delete unwanted checkpoint.""" if self.by_epoch: weight_name_format = "epoch_{}.pth" cur_step = runner.epoch + 1 else: weight_name_format = "iter_{}.pth" cur_step = runner.iter + 1 runner.save_checkpoint( self.out_dir, filename_tmpl=weight_name_format.format(cur_step), save_optimizer=self.save_optimizer, **self.args, ) # remove other checkpoints if self.max_keep_ckpts > 0: for _step in range(cur_step - self.max_keep_ckpts * self.interval, 0, -self.interval): ckpt_path = self.out_dir / Path(weight_name_format.format(_step)) if ckpt_path.exists(): ckpt_path.unlink() if runner.meta is not None: cur_ckpt_filename = Path(self.args.get("filename_tmpl", weight_name_format.format(cur_step))) runner.meta.setdefault("hook_msgs", dict()) runner.meta["hook_msgs"]["last_ckpt"] = str(self.out_dir / cur_ckpt_filename) def after_train_iter(self, runner): """Checkpoint stuffs after train iteration.""" if self.by_epoch or not self.every_n_iters(runner, self.interval): return if hasattr(runner, "save_ckpt"): if runner.save_ckpt: runner.logger.info(f"Saving checkpoint at {runner.iter + 1} iterations") if self.sync_buffer: allreduce_params(runner.model.buffers()) self._save_checkpoint(runner) runner.save_ckpt = False @HOOKS.register_module() class EnsureCorrectBestCheckpointHook(Hook): """EnsureCorrectBestCheckpointHook. This hook makes sure that the 'best_mAP' checkpoint points properly to the best model, even if the best model is created in the last epoch. """ def after_run(self, runner: BaseRunner): """Called after train epoch hooks.""" runner.call_hook("after_train_epoch") @HOOKS.register_module() class SaveInitialWeightHook(Hook): """Save the initial weights before training.""" def __init__(self, save_path, file_name: str = "weights.pth", **kwargs): self._save_path = save_path self._file_name = file_name self._args = kwargs def before_run(self, runner): """Save initial the weights before training.""" runner.logger.info("Saving weight before training") runner.save_checkpoint( self._save_path, filename_tmpl=self._file_name, save_optimizer=False, create_symlink=False, **self._args )
null
41
import os.path from typing import Optional from pcs import settings from pcs.common import file_type_codes as code from pcs.common.file import FileMetadata def _for_booth_config(filename: str) -> FileMetadata: return FileMetadata( # The filename is expected to be complete (i.e. booth.conf) and verified # (i.e. no slashes in it). The caller is responsible for doing both. file_type_code=code.BOOTH_CONFIG, path=os.path.join(settings.booth_config_dir, filename), owner_user_name="root", owner_group_name="root", permissions=0o644, is_binary=False, ) def METHOD_NAME(filename: str) -> FileMetadata: return FileMetadata( # The filename is expected to be complete (i.e. booth.key) and verified # (i.e. no slashes in it). The caller is responsible for doing both. file_type_code=code.BOOTH_KEY, path=os.path.join(settings.booth_config_dir, filename), owner_user_name=settings.pacemaker_uname, owner_group_name=settings.pacemaker_gname, permissions=settings.booth_authkey_file_mode, is_binary=True, ) def _for_corosync_conf() -> FileMetadata: return FileMetadata( file_type_code=code.COROSYNC_CONF, path=settings.corosync_conf_file, owner_user_name="root", owner_group_name="root", permissions=0o644, is_binary=False, ) def _for_corosync_qnetd_ca_cert() -> FileMetadata: return FileMetadata( file_type_code=code.COROSYNC_QNETD_CA_CERT, path=os.path.join( settings.corosync_qdevice_net_server_certs_dir, settings.corosync_qdevice_net_server_ca_file_name, ), owner_user_name="coroqnetd", owner_group_name="coroqnetd", permissions=0o600, is_binary=True, ) def _for_pacemaker_authkey() -> FileMetadata: return FileMetadata( file_type_code=code.PACEMAKER_AUTHKEY, path=settings.pacemaker_authkey_file, owner_user_name=settings.pacemaker_uname, owner_group_name=settings.pacemaker_gname, permissions=0o400, is_binary=True, ) def _for_pcs_dr_config() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_DR_CONFIG, path=settings.pcsd_dr_config_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_known_hosts() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_KNOWN_HOSTS, path=settings.pcsd_known_hosts_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_users_conf() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_USERS_CONF, path=settings.pcsd_users_conf_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def _for_pcs_settings_conf() -> FileMetadata: return FileMetadata( file_type_code=code.PCS_SETTINGS_CONF, path=settings.pcsd_settings_conf_location, owner_user_name="root", owner_group_name="root", permissions=0o600, is_binary=False, ) def for_file_type( file_type_code: code.FileTypeCode, filename: Optional[str] = None ) -> FileMetadata: # pylint: disable=too-many-return-statements if file_type_code == code.BOOTH_CONFIG: if not filename: raise AssertionError("filename must be set") return _for_booth_config(filename) if file_type_code == code.BOOTH_KEY: if not filename: raise AssertionError("filename must be set") return METHOD_NAME(filename) if file_type_code == code.COROSYNC_CONF: return _for_corosync_conf() if file_type_code == code.COROSYNC_QNETD_CA_CERT: return _for_corosync_qnetd_ca_cert() if file_type_code == code.PACEMAKER_AUTHKEY: return _for_pacemaker_authkey() if file_type_code == code.PCS_DR_CONFIG: return _for_pcs_dr_config() if file_type_code == code.PCS_KNOWN_HOSTS: return _for_pcs_known_hosts() if file_type_code == code.PCS_USERS_CONF: return _for_pcs_users_conf() if file_type_code == code.PCS_SETTINGS_CONF: return _for_pcs_settings_conf() raise AssertionError("Unknown file_type_code")
null
42
# ************************************************************************** # * # * Authors: Javier Vargas ([email protected]) # * # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC # * # * This program is free software; you can redistribute it and/or modify # * it under the terms of the GNU General Public License as published by # * the Free Software Foundation; either version 2 of the License, or # * (at your option) any later version. # * # * This program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; if not, write to the Free Software # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA # * 02111-1307 USA # * # * All comments concerning this program package may be sent to the # * e-mail address '[email protected]' # * # ************************************************************************** import pwem.emlib.metadata as md import pyworkflow.protocol.params as params from pwem.protocols import ProtProcessParticles from xmipp3.convert import writeSetOfParticles, xmippToLocation class XmippProtCTFCorrectWiener2D(ProtProcessParticles): """ Perform CTF correction by Wiener filtering. """ _label = 'ctf_correct_wiener2d' def __init__(self, *args, **kwargs): ProtProcessParticles.__init__(self, *args, **kwargs) #self.stepsExecutionMode = STEPS_PARALLEL #--------------------------- DEFINE param functions -------------------------------------------- def _defineParams(self, form): form.addSection(label='Input') form.addParam('inputParticles', params.PointerParam, pointerClass='SetOfParticles', label="Input particles", help='Select the input projection images .') form.addParam('isIsotropic', params.BooleanParam, default='True', label="Isotropic Correction", help='If true, Consider that there is not astigmatism and then it is performed an isotropic correction.') form.addParam('padding_factor', params.IntParam, default=2,expertLevel=params.LEVEL_ADVANCED, label="Padding factor", help='Padding factor for Wiener correction ') form.addParam('wiener_constant', params.FloatParam, default=-1,expertLevel=params.LEVEL_ADVANCED, label="Wiener constant", help=' Wiener-filter constant (if < 0: use FREALIGN default)') form.addParam('correctEnvelope', params.BooleanParam, default='False',expertLevel=params.LEVEL_ADVANCED, label="Correct for CTF envelope", help=' Only in cases where the envelope is well estimated correct for it') form.addParallelSection(threads=1, mpi=1) #--------------------------- INSERT steps functions -------------------------------------------- def _insertAllSteps(self): self._insertFunctionStep('convertInputStep',self.inputParticles.get().getObjId()) self._insertFunctionStep('wienerStep') self._insertFunctionStep('createOutputStep') def convertInputStep(self, particlesId): """ Write the input images as a Xmipp metadata file. particlesId: is only need to detect changes in input particles and cause restart from here. """ writeSetOfParticles(self.inputParticles.get(), self._getPath('input_particles.xmd')) def wienerStep(self): params = ' -i %s' % self._getPath('input_particles.xmd') params += ' -o %s' % self._getPath('corrected_ctf_particles.stk') params += ' --save_metadata_stack %s' % self._getPath('corrected_ctf_particles.xmd') params += ' --pad %s' % self.padding_factor.get() params += ' --wc %s' % self.wiener_constant.get() params += ' --sampling_rate %s' % self.inputParticles.get().getSamplingRate() if (self.inputParticles.get().isPhaseFlipped()): params += ' --phase_flipped ' if (self.correctEnvelope): params += ' --correct_envelope ' print(params) nproc = self.numberOfMpi.get() nT=self.numberOfThreads.get() self.runJob('xmipp_ctf_correct_wiener2d', params, numberOfMpi=nproc,numberOfThreads=nT) def createOutputStep(self): imgSet = self.inputParticles.get() partSet = self._createSetOfParticles() imgFn = self._getPath('corrected_ctf_particles.xmd') partSet.copyInfo(imgSet) partSet.setIsPhaseFlipped(True) partSet.copyItems(imgSet, updateItemCallback=self._updateLocation, itemDataIterator=md.iterRows(imgFn, sortByLabel=md.MDL_ITEM_ID)) self._defineOutputs(outputParticles=partSet) self._defineSourceRelation(imgSet, partSet) #--------------------------- INFO functions -------------------------------------------- def _validate(self): pass def _summary(self): pass def _methods(self): messages = [] return messages def METHOD_NAME(self): return [] #--------------------------- UTILS functions -------------------------------------------- def _updateLocation(self, item, row): index, filename = xmippToLocation(row.getValue(md.MDL_IMAGE)) item.setLocation(index, filename)
null
43
from base_test import ArkoudaTest from context import arkouda as ak """ Tests basic Arkouda client functionality """ from server_util.test.server_test_util import start_arkouda_server class ClientTest(ArkoudaTest): def test_client_connected(self): """ Tests the following methods: ak.client.connected() ak.client.disconnect() ak.client.connect() :return: None :raise: AssertionError if an assert* method returns incorrect value or if there is a error in connecting or disconnecting from the Arkouda server """ self.assertTrue(ak.client.connected) try: ak.disconnect() except Exception as e: raise AssertionError(e) self.assertFalse(ak.client.connected) try: ak.connect(server=ArkoudaTest.server, port=ArkoudaTest.port) except Exception as e: raise AssertionError(e) self.assertTrue(ak.client.connected) def test_disconnect_on_disconnected_client(self): """ Tests the ak.disconnect() method invoked on a client that is already disconnect to ensure there is no error """ ak.disconnect() self.assertFalse(ak.client.connected) ak.disconnect() ak.connect(server=ArkoudaTest.server, port=ArkoudaTest.port) def test_shutdown(self): """ Tests the ak.shutdown() method """ ak.shutdown() start_arkouda_server(numlocales=1) def METHOD_NAME(self): """ Tests the ak.client.get_config() method :return: None :raise: AssertionError if one or more Config values are not as expected or the call to ak.client.get_config() fails """ try: config = ak.client.get_config() except Exception as e: raise AssertionError(e) self.assertEqual(ArkoudaTest.port, config["ServerPort"]) self.assertTrue("arkoudaVersion" in config) self.assertTrue("INFO", config["logLevel"]) def test_get_mem_used(self): """ Tests the ak.get_mem_used and ak.get_mem_avail methods :return: None :raise: AssertionError if one or more ak.get_mem_used values are not as expected or the call to ak.client.get_mem_used() fails """ try: config = ak.client.get_config() a = ak.ones(1024 * 1024 * config["numLocales"]) mem_used = ak.client.get_mem_used() except Exception as e: raise AssertionError(e) self.assertTrue(mem_used > 0) # test units mem_used = ak.get_mem_used() mem_avail = ak.get_mem_avail() for u, f in ak.client._memunit2factor.items(): self.assertEqual(round(mem_used / f), ak.get_mem_used(u)) self.assertEqual(round(mem_avail / f), ak.get_mem_avail(u)) # test as_percent tot_mem = ak.get_mem_used() + ak.get_mem_avail() self.assertEqual(ak.get_mem_used(as_percent=True), round((ak.get_mem_used() / tot_mem) * 100)) self.assertEqual(ak.get_mem_avail(as_percent=True), round((ak.get_mem_avail() / tot_mem) * 100)) self.assertEqual(100, ak.get_mem_used(as_percent=True) + ak.get_mem_avail(as_percent=True)) def test_no_op(self): """ Tests the ak.client._no_op method :return: None :raise: AssertionError if return message is not 'noop' """ self.assertEqual("noop", ak.client._no_op()) def test_ruok(self): """ Tests the ak.client.ruok method :return: None :raise: AssertionError if return message is not 'imok' """ self.assertEqual("imok", ak.client.ruok()) def test_client_configuration(self): """ Tests the ak.client.set_defaults() method as well as set/get parrayIterThresh, maxTransferBytes, and verbose config params. """ ak.client.pdarrayIterThresh = 50 ak.client.maxTransferBytes = 1048576000 ak.client.verbose = True self.assertEqual(50, ak.client.pdarrayIterThresh) self.assertEqual(1048576000, ak.client.maxTransferBytes) self.assertTrue(ak.client.verbose) ak.client.set_defaults() self.assertEqual(100, ak.client.pdarrayIterThresh) self.assertEqual(1073741824, ak.client.maxTransferBytes) self.assertFalse(ak.client.verbose) def test_client_get_server_commands(self): """ Tests the ak.client.get_server_commands() method contains an expected sample of commands. """ cmds = ak.client.get_server_commands() for cmd in ["connect", "array", "create", "tondarray", "info", "str"]: self.assertTrue(cmd in cmds)
null
44
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkcloudapi.endpoint import endpoint_data class ModifyApiRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'CloudAPI', '2016-07-14', 'ModifyApi','apigateway') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_WebSocketApiType(self): # String return self.get_query_params().get('WebSocketApiType') def set_WebSocketApiType(self, WebSocketApiType): # String self.add_query_param('WebSocketApiType', WebSocketApiType) def get_ErrorCodeSamples(self): # String return self.get_query_params().get('ErrorCodeSamples') def set_ErrorCodeSamples(self, ErrorCodeSamples): # String self.add_query_param('ErrorCodeSamples', ErrorCodeSamples) def get_AppCodeAuthType(self): # String return self.get_query_params().get('AppCodeAuthType') def set_AppCodeAuthType(self, AppCodeAuthType): # String self.add_query_param('AppCodeAuthType', AppCodeAuthType) def get_Description(self): # String return self.get_query_params().get('Description') def METHOD_NAME(self, Description): # String self.add_query_param('Description', Description) def get_DisableInternet(self): # Boolean return self.get_query_params().get('DisableInternet') def set_DisableInternet(self, DisableInternet): # Boolean self.add_query_param('DisableInternet', DisableInternet) def get_BackendId(self): # String return self.get_query_params().get('BackendId') def set_BackendId(self, BackendId): # String self.add_query_param('BackendId', BackendId) def get_ConstantParameters(self): # String return self.get_query_params().get('ConstantParameters') def set_ConstantParameters(self, ConstantParameters): # String self.add_query_param('ConstantParameters', ConstantParameters) def get_AuthType(self): # String return self.get_query_params().get('AuthType') def set_AuthType(self, AuthType): # String self.add_query_param('AuthType', AuthType) def get_AllowSignatureMethod(self): # String return self.get_query_params().get('AllowSignatureMethod') def set_AllowSignatureMethod(self, AllowSignatureMethod): # String self.add_query_param('AllowSignatureMethod', AllowSignatureMethod) def get_ServiceParameters(self): # String return self.get_query_params().get('ServiceParameters') def set_ServiceParameters(self, ServiceParameters): # String self.add_query_param('ServiceParameters', ServiceParameters) def get_FailResultSample(self): # String return self.get_query_params().get('FailResultSample') def set_FailResultSample(self, FailResultSample): # String self.add_query_param('FailResultSample', FailResultSample) def get_SystemParameters(self): # String return self.get_query_params().get('SystemParameters') def set_SystemParameters(self, SystemParameters): # String self.add_query_param('SystemParameters', SystemParameters) def get_ServiceParametersMap(self): # String return self.get_query_params().get('ServiceParametersMap') def set_ServiceParametersMap(self, ServiceParametersMap): # String self.add_query_param('ServiceParametersMap', ServiceParametersMap) def get_SecurityToken(self): # String return self.get_query_params().get('SecurityToken') def set_SecurityToken(self, SecurityToken): # String self.add_query_param('SecurityToken', SecurityToken) def get_OpenIdConnectConfig(self): # String return self.get_query_params().get('OpenIdConnectConfig') def set_OpenIdConnectConfig(self, OpenIdConnectConfig): # String self.add_query_param('OpenIdConnectConfig', OpenIdConnectConfig) def get_RequestParameters(self): # String return self.get_query_params().get('RequestParameters') def set_RequestParameters(self, RequestParameters): # String self.add_query_param('RequestParameters', RequestParameters) def get_ResultDescriptions(self): # String return self.get_query_params().get('ResultDescriptions') def set_ResultDescriptions(self, ResultDescriptions): # String self.add_query_param('ResultDescriptions', ResultDescriptions) def get_Visibility(self): # String return self.get_query_params().get('Visibility') def set_Visibility(self, Visibility): # String self.add_query_param('Visibility', Visibility) def get_GroupId(self): # String return self.get_query_params().get('GroupId') def set_GroupId(self, GroupId): # String self.add_query_param('GroupId', GroupId) def get_ServiceConfig(self): # String return self.get_query_params().get('ServiceConfig') def set_ServiceConfig(self, ServiceConfig): # String self.add_query_param('ServiceConfig', ServiceConfig) def get_ResultType(self): # String return self.get_query_params().get('ResultType') def set_ResultType(self, ResultType): # String self.add_query_param('ResultType', ResultType) def get_ApiName(self): # String return self.get_query_params().get('ApiName') def set_ApiName(self, ApiName): # String self.add_query_param('ApiName', ApiName) def get_ResultSample(self): # String return self.get_query_params().get('ResultSample') def set_ResultSample(self, ResultSample): # String self.add_query_param('ResultSample', ResultSample) def get_BackendEnable(self): # Boolean return self.get_query_params().get('BackendEnable') def set_BackendEnable(self, BackendEnable): # Boolean self.add_query_param('BackendEnable', BackendEnable) def get_ForceNonceCheck(self): # Boolean return self.get_query_params().get('ForceNonceCheck') def set_ForceNonceCheck(self, ForceNonceCheck): # Boolean self.add_query_param('ForceNonceCheck', ForceNonceCheck) def get_RequestConfig(self): # String return self.get_query_params().get('RequestConfig') def set_RequestConfig(self, RequestConfig): # String self.add_query_param('RequestConfig', RequestConfig) def get_ResultBodyModel(self): # String return self.get_query_params().get('ResultBodyModel') def set_ResultBodyModel(self, ResultBodyModel): # String self.add_query_param('ResultBodyModel', ResultBodyModel) def get_ApiId(self): # String return self.get_query_params().get('ApiId') def set_ApiId(self, ApiId): # String self.add_query_param('ApiId', ApiId)
null
45
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RoaRequest from aliyunsdkcs.endpoint import endpoint_data class ScaleOutClusterRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'CS', '2015-12-15', 'ScaleOutCluster') self.set_uri_pattern('/api/v2/clusters/[ClusterId]') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_worker_data_disk(self): return self.get_body_params().get('worker_data_disk') def set_worker_data_disk(self,worker_data_disk): self.add_body_params('worker_data_disk', worker_data_disk) def get_key_pair(self): return self.get_body_params().get('key_pair') def set_key_pair(self,key_pair): self.add_body_params('key_pair', key_pair) def get_count(self): return self.get_body_params().get('count') def set_count(self,count): self.add_body_params('count', count) def METHOD_NAME(self): return self.get_body_params().get('worker_system_disk_category') def set_worker_system_disk_category(self,worker_system_disk_category): self.add_body_params('worker_system_disk_category', worker_system_disk_category) def get_cloud_monitor_flags(self): return self.get_body_params().get('cloud_monitor_flags') def set_cloud_monitor_flags(self,cloud_monitor_flags): self.add_body_params('cloud_monitor_flags', cloud_monitor_flags) def get_ClusterId(self): return self.get_path_params().get('ClusterId') def set_ClusterId(self,ClusterId): self.add_path_param('ClusterId',ClusterId) def get_user_data(self): return self.get_body_params().get('user_data') def set_user_data(self,user_data): self.add_body_params('user_data', user_data) def get_worker_period_unit(self): return self.get_body_params().get('worker_period_unit') def set_worker_period_unit(self,worker_period_unit): self.add_body_params('worker_period_unit', worker_period_unit) def get_worker_auto_renew(self): return self.get_body_params().get('worker_auto_renew') def set_worker_auto_renew(self,worker_auto_renew): self.add_body_params('worker_auto_renew', worker_auto_renew) def get_worker_auto_renew_period(self): return self.get_body_params().get('worker_auto_renew_period') def set_worker_auto_renew_period(self,worker_auto_renew_period): self.add_body_params('worker_auto_renew_period', worker_auto_renew_period) def get_worker_period(self): return self.get_body_params().get('worker_period') def set_worker_period(self,worker_period): self.add_body_params('worker_period', worker_period) def get_login_password(self): return self.get_body_params().get('login_password') def set_login_password(self,login_password): self.add_body_params('login_password', login_password) def get_worker_system_disk_size(self): return self.get_body_params().get('worker_system_disk_size') def set_worker_system_disk_size(self,worker_system_disk_size): self.add_body_params('worker_system_disk_size', worker_system_disk_size) def get_cpu_policy(self): return self.get_body_params().get('cpu_policy') def set_cpu_policy(self,cpu_policy): self.add_body_params('cpu_policy', cpu_policy) def get_disable_rollback(self): return self.get_body_params().get('disable_rollback') def set_disable_rollback(self,disable_rollback): self.add_body_params('disable_rollback', disable_rollback) def get_image_id(self): return self.get_body_params().get('image_id') def set_image_id(self,image_id): self.add_body_params('image_id', image_id) def get_worker_instance_charge_type(self): return self.get_body_params().get('worker_instance_charge_type') def set_worker_instance_charge_type(self,worker_instance_charge_type): self.add_body_params('worker_instance_charge_type', worker_instance_charge_type
null
46
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkcloudapi.endpoint import endpoint_data class ModifyApiGroupRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'CloudAPI', '2016-07-14', 'ModifyApiGroup','apigateway') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DefaultDomain(self): # String return self.get_query_params().get('DefaultDomain') def set_DefaultDomain(self, DefaultDomain): # String self.add_query_param('DefaultDomain', DefaultDomain) def get_BasePath(self): # String return self.get_query_params().get('BasePath') def set_BasePath(self, BasePath): # String self.add_query_param('BasePath', BasePath) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_SecurityToken(self): # String return self.get_query_params().get('SecurityToken') def set_SecurityToken(self, SecurityToken): # String self.add_query_param('SecurityToken', SecurityToken) def get_RpcPattern(self): # String return self.get_query_params().get('RpcPattern') def set_RpcPattern(self, RpcPattern): # String self.add_query_param('RpcPattern', RpcPattern) def get_UserLogConfig(self): # String return self.get_query_params().get('UserLogConfig') def set_UserLogConfig(self, UserLogConfig): # String self.add_query_param('UserLogConfig', UserLogConfig) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) def get_CustomerConfigs(self): # String return self.get_query_params().get('CustomerConfigs') def set_CustomerConfigs(self, CustomerConfigs): # String self.add_query_param('CustomerConfigs', CustomerConfigs) def get_GroupId(self): # String return self.get_query_params().get('GroupId') def METHOD_NAME(self, GroupId): # String self.add_query_param('GroupId', GroupId) def get_GroupName(self): # String return self.get_query_params().get('GroupName') def set_GroupName(self, GroupName): # String self.add_query_param('GroupName', GroupName) def get_PassthroughHeaders(self): # String return self.get_query_params().get('PassthroughHeaders') def set_PassthroughHeaders(self, PassthroughHeaders): # String self.add_query_param('PassthroughHeaders', PassthroughHeaders) def get_CompatibleFlags(self): # String return self.get_query_params().get('CompatibleFlags') def set_CompatibleFlags(self, CompatibleFlags): # String self.add_query_param('CompatibleFlags', CompatibleFlags) def get_CustomTraceConfig(self): # String return self.get_query_params().get('CustomTraceConfig') def set_CustomTraceConfig(self, CustomTraceConfig): # String self.add_query_param('CustomTraceConfig', CustomTraceConfig)
null
47
# -*- mode: python; coding: utf-8 -*- # Copyright (c) 2021 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """pytest fixtures for UVData tests.""" import os import pytest import pyuvdata.tests as uvtest from pyuvdata import UVData from pyuvdata.data import DATA_PATH from pyuvdata.uvdata.mir_parser import MirParser casa_tutorial_uvfits = os.path.join( DATA_PATH, "day2_TDEM0003_10s_norx_1src_1spw.uvfits" ) paper_miriad_file = os.path.join(DATA_PATH, "zen.2456865.60537.xy.uvcRREAA") @pytest.fixture(scope="session") def casa_uvfits_main(): """Read in CASA tutorial uvfits file.""" uv_in = UVData() with uvtest.check_warnings( UserWarning, [ "Telescope EVLA is not in known_telescopes", "The uvw_array does not match the expected values", ], ): uv_in.read(casa_tutorial_uvfits, use_future_array_shapes=True) yield uv_in # cleanup del uv_in @pytest.fixture(scope="function") def casa_uvfits(casa_uvfits_main): """Make function level CASA tutorial uvfits object.""" casa_uvfits = casa_uvfits_main.copy() yield casa_uvfits # clean up when done del casa_uvfits return @pytest.fixture(scope="session") def hera_uvh5_main(): # read in test file for the resampling in time functions uv_object = UVData() testfile = os.path.join(DATA_PATH, "zen.2458661.23480.HH.uvh5") uv_object.read(testfile, use_future_array_shapes=True) yield uv_object # cleanup del uv_object @pytest.fixture(scope="function") def hera_uvh5(hera_uvh5_main): # read in test file for the resampling in time functions uv_object = hera_uvh5_main.copy() yield uv_object # cleanup del uv_object return @pytest.fixture(scope="session") def METHOD_NAME(): """Read in PAPER miriad file.""" pytest.importorskip("pyuvdata.uvdata.aipy_extracts") uv_in = UVData() uv_in.read(paper_miriad_file, use_future_array_shapes=True) yield uv_in # cleanup del uv_in @pytest.fixture(scope="function") def paper_miriad(METHOD_NAME): """Make function level PAPER miriad object.""" uv_in = METHOD_NAME.copy() yield uv_in # cleanup del uv_in @pytest.fixture(scope="session") def sma_mir_main(): # read in test file for the resampling in time functions uv_object = UVData() testfile = os.path.join(DATA_PATH, "sma_test.mir") with uvtest.check_warnings( UserWarning, match="The lst_array is not self-consistent with the time_array and telescope " "location. Consider recomputing with the `set_lsts_from_time_array` method.", ): uv_object.read(testfile, use_future_array_shapes=True) uv_object.set_lsts_from_time_array() yield uv_object @pytest.fixture(scope="function") def sma_mir(sma_mir_main): # read in test file for the resampling in time functions uv_object = sma_mir_main.copy() yield uv_object @pytest.fixture(scope="session") def mir_data_main(): testfile = os.path.join(DATA_PATH, "sma_test.mir") mir_data = MirParser(testfile, load_cross=True, load_auto=True, has_auto=True) yield mir_data @pytest.fixture(scope="function") def mir_data(mir_data_main): mir_data = mir_data_main.copy() yield mir_data @pytest.fixture(scope="session") def uv_phase_comp_main(): file1 = os.path.join(DATA_PATH, "1133866760.uvfits") file2 = os.path.join(DATA_PATH, "1133866760_rephase.uvfits") # These files came from an external source, don't want to rewrite them, so use # checkwarnings to capture the warning about non-real autos with uvtest.check_warnings( UserWarning, match=[ "Fixing auto-correlations to be be real-only, after some imaginary " "values were detected in data_array." ] * 2, ): uvd1 = UVData.from_file(file1, use_future_array_shapes=True) uvd2 = UVData.from_file(file2, use_future_array_shapes=True) yield uvd1, uvd2 @pytest.fixture(scope="function") def uv_phase_comp(uv_phase_comp_main): uvd1, uvd2 = uv_phase_comp_main uvd1_copy = uvd1.copy() uvd2_copy = uvd2.copy() yield uvd1_copy, uvd2_copy
null
48
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkmts.endpoint import endpoint_data class AddSmarttagTemplateRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Mts', '2014-06-18', 'AddSmarttagTemplate','mts') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_KnowledgeConfig(self): # String return self.get_query_params().get('KnowledgeConfig') def set_KnowledgeConfig(self, KnowledgeConfig): # String self.add_query_param('KnowledgeConfig', KnowledgeConfig) def get_Industry(self): # String return self.get_query_params().get('Industry') def set_Industry(self, Industry): # String self.add_query_param('Industry', Industry) def get_LabelVersion(self): # String return self.get_query_params().get('LabelVersion') def set_LabelVersion(self, LabelVersion): # String self.add_query_param('LabelVersion', LabelVersion) def get_Scene(self): # String return self.get_query_params().get('Scene') def set_Scene(self, Scene): # String self.add_query_param('Scene', Scene) def get_FaceCustomParamsConfig(self): # String return self.get_query_params().get('FaceCustomParamsConfig') def set_FaceCustomParamsConfig(self, FaceCustomParamsConfig): # String self.add_query_param('FaceCustomParamsConfig', FaceCustomParamsConfig) def get_TemplateName(self): # String return self.get_query_params().get('TemplateName') def set_TemplateName(self, TemplateName): # String self.add_query_param('TemplateName', TemplateName) def get_IsDefault(self): # Boolean return self.get_query_params().get('IsDefault') def set_IsDefault(self, IsDefault): # Boolean self.add_query_param('IsDefault', IsDefault) def get_FaceCategoryIds(self): # String return self.get_query_params().get('FaceCategoryIds') def set_FaceCategoryIds(self, FaceCategoryIds): # String self.add_query_param('FaceCategoryIds', FaceCategoryIds) def get_KeywordConfig(self): # String return self.get_query_params().get('KeywordConfig') def set_KeywordConfig(self, KeywordConfig): # String self.add_query_param('KeywordConfig', KeywordConfig) def get_LandmarkGroupIds(self): # String return self.get_query_params().get('LandmarkGroupIds') def set_LandmarkGroupIds(self, LandmarkGroupIds): # String self.add_query_param('LandmarkGroupIds', LandmarkGroupIds) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_ObjectGroupIds(self): # String return self.get_query_params().get('ObjectGroupIds') def set_ObjectGroupIds(self, ObjectGroupIds): # String self.add_query_param('ObjectGroupIds', ObjectGroupIds) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_AnalyseTypes(self): # String return self.get_query_params().get('AnalyseTypes') def set_AnalyseTypes(self, AnalyseTypes): # String self.add_query_param('AnalyseTypes', AnalyseTypes) def METHOD_NAME(self): # String return self.get_query_params().get('LabelType') def set_LabelType(self, LabelType): # String self.add_query_param('LabelType', LabelType)
null
49
# coding=utf-8 # Copyright 2023 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Lazy imports for heavy dependencies.""" import functools import importlib from typing import Any, Callable, TypeVar from tensorflow_datasets.core.utils import py_utils as utils _Fn = TypeVar("_Fn") def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError as e: err_msg = ( "Failed importing {name}. This likely means that the dataset " "requires additional dependencies that have to be " "manually installed (usually with `pip install {name}`). See " "setup.py extras_require." ).format(name=module_name) utils.reraise(e, suffix=err_msg) class LazyImporter(object): """Lazy importer for heavy dependencies. Some datasets require heavy dependencies for data generation. To allow for the default installation to remain lean, those heavy dependencies are lazily imported here. """ @utils.classproperty @classmethod def apache_beam(cls): return _try_import("apache_beam") @utils.classproperty @classmethod def bs4(cls): return _try_import("bs4") @utils.classproperty @classmethod def crepe(cls): return _try_import("crepe") @utils.classproperty @classmethod def cv2(cls): return _try_import("cv2") @utils.classproperty @classmethod def datasets(cls): return _try_import("datasets") @utils.classproperty @classmethod def envlogger(cls): return _try_import("envlogger.reader") @utils.classproperty @classmethod def gcsfs_store(cls): return _try_import("gcsfs").GCSFileSystem(token='anon').get_mapper @utils.classproperty @classmethod def gcld3(cls): return _try_import("gcld3") # pylint: disable=unreachable @utils.classproperty @classmethod def h5py(cls): return _try_import("h5py") @utils.classproperty @classmethod def jax(cls): return _try_import("jax") @utils.classproperty @classmethod def langdetect(cls): return _try_import("langdetect") @utils.classproperty @classmethod def librosa(cls): return _try_import("librosa") @utils.classproperty @classmethod def lxml(cls): return _try_import("lxml") @utils.classproperty @classmethod def matplotlib(cls): _try_import("matplotlib.pyplot") return _try_import("matplotlib") @utils.classproperty @classmethod def mwparserfromhell(cls): return _try_import("mwparserfromhell") @utils.classproperty @classmethod def mwxml(cls): return _try_import("mwxml") @utils.classproperty @classmethod def networkx(cls): return _try_import("networkx") @utils.classproperty @classmethod def nltk(cls): return _try_import("nltk") @utils.classproperty @classmethod def pandas(cls): return _try_import("pandas") @utils.classproperty @classmethod def PIL_Image(cls): # pylint: disable=invalid-name # TiffImagePlugin need to be activated explicitly on some systems # https://github.com/python-pillow/Pillow/blob/5.4.x/src/PIL/Image.py#L407 _try_import("PIL.TiffImagePlugin") return _try_import("PIL.Image") @utils.classproperty @classmethod def PIL_ImageDraw(cls): # pylint: disable=invalid-name return _try_import("PIL.ImageDraw") @utils.classproperty @classmethod def pretty_midi(cls): return _try_import("pretty_midi") @utils.classproperty @classmethod def pycocotools(cls): return _try_import("pycocotools.mask") @utils.classproperty @classmethod def pydub(cls): return _try_import("pydub") @utils.classproperty @classmethod def scipy(cls): _try_import("scipy.io") _try_import("scipy.io.wavfile") _try_import("scipy.ndimage") return _try_import("scipy") @utils.classproperty @classmethod def skimage(cls): _try_import("skimage.color") _try_import("skimage.filters") try: _try_import("skimage.external.tifffile") except ImportError: pass return _try_import("skimage") @utils.classproperty @classmethod def tifffile(cls): return _try_import("tifffile") @utils.classproperty @classmethod def tensorflow_data_validation(cls): return _try_import("tensorflow_data_validation") @utils.classproperty @classmethod def tensorflow_io(cls): return _try_import("tensorflow_io") @utils.classproperty @classmethod def METHOD_NAME(cls): return _try_import("tldextract") @utils.classproperty @classmethod def os(cls): """For testing purposes only.""" return _try_import("os") @utils.classproperty @classmethod def test_foo(cls): """For testing purposes only.""" return _try_import("test_foo") @utils.classproperty @classmethod def zarr(cls): return _try_import("zarr") @utils.classproperty @classmethod def conllu(cls): return _try_import("conllu") @utils.classproperty @classmethod def huggingface_hub(cls): return _try_import("huggingface_hub") lazy_imports = LazyImporter # pylint: disable=invalid-name def beam_ptransform_fn(fn: Callable[..., Any]) -> Callable[..., Any]: """Lazy version of `@beam.ptransform_fn`.""" lazy_decorated_fn = None @functools.wraps(fn) def decorated(*args, **kwargs): nonlocal lazy_decorated_fn # Actually decorate the function only the first time it is called if lazy_decorated_fn is None: lazy_decorated_fn = lazy_imports.apache_beam.ptransform_fn(fn) return lazy_decorated_fn(*args, **kwargs) return decorated
null
50
# -*- coding: utf-8 -*- import pytest from django.utils.timezone import now from api.base.settings.defaults import API_BASE from api_tests.registrations.filters.test_filters import RegistrationListFilteringMixin from osf_tests.factories import ( AuthUserFactory, CollectionFactory, ProjectFactory, RegistrationFactory, OSFGroupFactory ) from osf.utils import permissions from tests.base import ApiTestCase from website.views import find_bookmark_collection @pytest.mark.django_db class TestUserRegistrations: @pytest.fixture() def user_one(self): user_one = AuthUserFactory() user_one.social['twitter'] = 'rheisendennis' user_one.save() return user_one @pytest.fixture() def user_two(self): return AuthUserFactory() @pytest.fixture() def group_member(self): return AuthUserFactory() @pytest.fixture() def osf_group(self, group_member): return OSFGroupFactory(creator=group_member) @pytest.fixture() def project_public_user_one(self, user_one): return ProjectFactory( title='Public Project User One', is_public=True, creator=user_one) @pytest.fixture() def project_private_user_one(self, user_one): return ProjectFactory( title='Private Project User One', is_public=False, creator=user_one) @pytest.fixture() def project_public_user_two(self, user_two): return ProjectFactory( title='Public Project User Two', is_public=True, creator=user_two) @pytest.fixture() def project_private_user_two(self, user_two): return ProjectFactory( title='Private Project User Two', is_public=False, creator=user_two) @pytest.fixture() def project_private_group_member(self, user_one, osf_group): project = ProjectFactory( title='Private Project Group Member', is_public=False, creator=user_one ) project.add_osf_group(osf_group, permissions.ADMIN) return project @pytest.fixture() def project_deleted_user_one(self, user_one): return CollectionFactory( title='Deleted Project User One', is_public=False, creator=user_one, deleted=now()) @pytest.fixture() def folder(self): return CollectionFactory() @pytest.fixture() def folder_deleted(self, user_one): return CollectionFactory( title='Deleted Folder User One', is_public=False, creator=user_one, deleted=now()) @pytest.fixture() def bookmark_collection(self, user_one): return find_bookmark_collection(user_one) @pytest.fixture() def reg_project_public_user_one(self, user_one, project_public_user_one): return RegistrationFactory( project=project_public_user_one, creator=user_one, is_public=True) @pytest.fixture() def reg_project_private_user_one(self, user_one, project_private_user_one): return RegistrationFactory( project=project_private_user_one, creator=user_one, is_private=True) @pytest.fixture() def reg_project_public_user_two(self, user_two, project_public_user_two): return RegistrationFactory( project=project_public_user_two, creator=user_two, is_public=True) @pytest.fixture() def reg_project_private_user_two(self, user_two, project_private_user_two): return RegistrationFactory( project=project_private_user_two, creator=user_two, is_private=True) @pytest.fixture() def METHOD_NAME(self, user_one, project_private_group_member): return RegistrationFactory( project=project_private_group_member, creator=user_one, is_private=True) def test_user_registrations( self, app, user_one, user_two, group_member, reg_project_public_user_one, reg_project_public_user_two, reg_project_private_user_one, reg_project_private_user_two, METHOD_NAME, folder, folder_deleted, project_deleted_user_one): # test_authorized_in_gets_200 url = '/{}users/{}/registrations/'.format(API_BASE, user_one._id) res = app.get(url, auth=user_one.auth) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' # test_anonymous_gets_200 url = '/{}users/{}/registrations/'.format(API_BASE, user_one._id) res = app.get(url) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' # test_get_registrations_logged_in url = '/{}users/{}/registrations/'.format(API_BASE, user_one._id) res = app.get(url, auth=user_one.auth) node_json = res.json['data'] ids = [each['id'] for each in node_json] assert reg_project_public_user_one._id in ids assert reg_project_private_user_one._id in ids assert reg_project_public_user_two._id not in ids assert reg_project_private_user_two._id not in ids assert folder._id not in ids assert folder_deleted._id not in ids assert project_deleted_user_one._id not in ids # test_get_registrations_not_logged_in url = '/{}users/{}/registrations/'.format(API_BASE, user_one._id) res = app.get(url) node_json = res.json['data'] ids = [each['id'] for each in node_json] assert reg_project_public_user_one._id in ids assert reg_project_private_user_one._id not in ids assert reg_project_public_user_two._id not in ids assert reg_project_private_user_two._id not in ids assert folder._id not in ids assert folder_deleted._id not in ids assert project_deleted_user_one._id not in ids # test_get_registrations_logged_in_as_different_user url = '/{}users/{}/registrations/'.format(API_BASE, user_two._id) res = app.get(url, auth=user_one.auth) node_json = res.json['data'] ids = [each['id'] for each in node_json] assert reg_project_public_user_one._id not in ids assert reg_project_private_user_one._id not in ids assert reg_project_public_user_two._id in ids assert reg_project_private_user_two._id not in ids assert folder._id not in ids assert folder_deleted._id not in ids assert project_deleted_user_one._id not in ids # test_get_registrations_logged_in_group_member url = '/{}users/{}/registrations/'.format(API_BASE, group_member._id) res = app.get(url, auth=group_member.auth) node_json = res.json['data'] ids = [each['id'] for each in node_json] assert reg_project_public_user_one._id not in ids assert reg_project_private_user_one._id not in ids assert reg_project_public_user_two._id not in ids assert reg_project_private_user_two._id not in ids assert folder._id not in ids assert folder_deleted._id not in ids assert project_deleted_user_one._id not in ids # project group members not copied to registration. assert METHOD_NAME not in ids class TestRegistrationListFiltering( RegistrationListFilteringMixin, ApiTestCase): url = '/{}users/me/registrations/?'.format(API_BASE)
null
51
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from abc import ABC, abstractmethod from time import time from typing import Any, Dict, List, Optional from streampipes.functions.broker.output_collector import OutputCollector from streampipes.functions.utils.function_context import FunctionContext from streampipes.model.resource import FunctionDefinition from streampipes.model.resource.function_definition import FunctionId class StreamPipesFunction(ABC): """Abstract implementation of a StreamPipesFunction. A StreamPipesFunction allows users to get the data of a StreamPipes data streams easily. It makes it possible to work with the live data in python and enables to use the powerful data analytics libraries there. Parameters ---------- function_definition: FunctionDefinition the definition of the function that contains metadata about the connected function Attributes ---------- output_collectors: Dict[str, OutputCollector] List of all output collectors which are created based on the provided function definitions. """ def __init__(self, function_definition: Optional[FunctionDefinition] = None): self.function_definition = function_definition or FunctionDefinition() self.output_collectors = { stream_id: OutputCollector(data_stream) for stream_id, data_stream in self.function_definition.output_data_streams.items() } def add_output(self, stream_id: str, event: Dict[str, Any]): """Send an event via an output data stream to StreamPipes Parameters ---------- stream_id: str The id of the output data stream event: Dict[str, Any] The event which should be sent Returns ------- None """ event["timestamp"] = int(1000 * time()) self.output_collectors[stream_id].collect(event) def METHOD_NAME(self) -> FunctionId: """Returns the id of the function. Returns ------- function_id: FunctionId Identification object of the StreamPipes function """ return self.function_definition.function_id def stop(self) -> None: """Stops the function and disconnects from the output streams""" for collector in self.output_collectors.values(): collector.disconnect() self.onServiceStopped() def requiredStreamIds(self) -> List[str]: """Get the ids of the streams needed by the function. Returns ------- stream_ids: List[str] List of the stream ids """ return self.function_definition.consumed_streams @abstractmethod def onServiceStarted(self, context: FunctionContext) -> None: """Is called when the function gets started. Parameters ---------- context: FunctionContext The context in which the function gets started. Returns ------- None """ raise NotImplementedError # pragma: no cover @abstractmethod def onEvent(self, event: Dict[str, Any], streamId: str) -> None: """Is called for every event of a data stream. Parameters ---------- event: Dict[str, Any] The received event from the data stream. streamId: str The id of the data stream which the event belongs to. Returns ------- None """ raise NotImplementedError # pragma: no cover @abstractmethod def onServiceStopped(self) -> None: """Is called when the function gets stopped. Returns ------- None """ raise NotImplementedError # pragma: no cover
null
52
"""Tests for the natural numbers range data type""" from typing import * import pytest from hypothesis import Phase, given, settings, strategies as st from looper.utils import NatIntervalException, NatIntervalInclusive gen_pos_int = st.integers(min_value=1) gen_opt_int = st.one_of(st.integers(), st.none()) def is_non_pos(opt_int: Optional[int]) -> bool: """Determine whether the given value is non-positive (and non-null).""" return opt_int is not None and opt_int < 1 def pytest_generate_tests(metafunc): if "legit_delim" in metafunc.fixturenames: metafunc.parametrize("legit_delim", [":", "-"]) def nondecreasing_pair_strategy(**kwargs): """Generate a pair of values in which first respects given upper bound and second is no more than first.""" return st.tuples(st.integers(**kwargs), st.integers(**kwargs)).filter( lambda p: p[0] <= p[1] ) class NaturalRangePureConstructorTests: """Tests for direct use of natural range primary constructor""" @given(upper_bound=gen_pos_int) def test_zero_is_prohibited(self, upper_bound): """Separate this case since it's an edge case.""" with pytest.raises(NatIntervalException): NatIntervalInclusive(0, upper_bound) @given(bounds=nondecreasing_pair_strategy(max_value=0)) def test_non_positive_is_prohibited(self, bounds): lo, hi = bounds with pytest.raises(NatIntervalException): NatIntervalInclusive(lo, hi) @given(bounds=st.tuples(st.integers(), st.integers()).filter(lambda p: p[0] > p[1])) def test_upper_less_than_lower__fails_as_expected(self, bounds): lo, hi = bounds with pytest.raises(NatIntervalException): NatIntervalInclusive(lo, hi) class NaturalRangeFromStringTests: """Tests for parsing of natural number range from text, like CLI arg""" @pytest.mark.parametrize( "arg_template", ["0{sep}0", "{sep}0", "0{sep}", "0{sep}0", "{sep}0", "0{sep}"] ) @given(upper_bound=gen_pos_int) def test_zero__does_not_parse(self, arg_template, legit_delim, upper_bound): arg = arg_template.format(sep=legit_delim) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @given(upper_bound=st.integers()) def test_just_delimiter__does_not_parse(self, legit_delim, upper_bound): with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(legit_delim, upper_bound=upper_bound) @given( lo_hi_upper=st.tuples(gen_opt_int, gen_opt_int, st.integers()).filter( lambda t: (t[0] is not None or t[1] is not None) and any(is_non_pos(n) for n in t) ) ) def test_nonpositive_values__fail_with_expected_error( self, lo_hi_upper, legit_delim ): lo, hi, upper_bound = lo_hi_upper if lo is None and hi is None: raise ValueError("Both lower and upper bound generated are null.") if lo is None: arg = legit_delim + str(hi) elif hi is None: arg = str(lo) + legit_delim else: arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @pytest.mark.parametrize("arg", ["1,2", "1;2", "1_2", "1/2", "1.2", "1~2"]) @given(upper_bound=st.integers(min_value=3)) def test_illegal_delimiter__fail_with_expected_error(self, arg, upper_bound): with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @given( lower_and_limit=st.tuples(st.integers(), st.integers()).filter( lambda p: p[1] < p[0] ) ) def test_one_sided_lower_with_samples_lt_bound__fails( self, lower_and_limit, legit_delim ): lower, limit = lower_and_limit arg = str(lower) + legit_delim with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=limit) @given(lower_and_upper=nondecreasing_pair_strategy(min_value=1)) def test_one_sided_lower_with_samples_gteq_bound__succeeds( self, lower_and_upper, legit_delim ): lo, upper_bound = lower_and_upper exp = NatIntervalInclusive(lo, upper_bound) arg = str(lo) + legit_delim obs = NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) assert obs == exp @given(upper_and_limit=nondecreasing_pair_strategy(min_value=1)) def test_one_sided_upper_with_samples_gteq_bound__succeeds( self, upper_and_limit, legit_delim ): upper, limit = upper_and_limit exp = NatIntervalInclusive(1, upper) arg = legit_delim + str(upper) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( upper_and_limit=st.tuples( st.integers(min_value=1), st.integers(min_value=1) ).filter(lambda p: p[1] < p[0]) ) def test_one_sided_upper_with_samples_lt_bound__uses_bound( self, upper_and_limit, legit_delim ): upper, limit = upper_and_limit exp = NatIntervalInclusive(1, limit) arg = legit_delim + str(upper) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( lower_upper_limit=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[1] < t[0] or t[2] < t[0] ) ) def test_two_sided_parse_upper_lt_lower(self, lower_upper_limit, legit_delim): lo, hi, lim = lower_upper_limit arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=lim) @given( lo_hi_limit=st.tuples( st.integers(min_value=2), gen_pos_int, gen_pos_int ).filter(lambda t: t[2] < t[0] <= t[1]) ) def test_two_sided_parse_upper_gteq_lower_with_upper_limit_lt_lower( self, lo_hi_limit, legit_delim ): lo, hi, limit = lo_hi_limit arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=limit) @given( lo_hi_limit=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[0] < t[2] < t[1] ) ) def test_two_sided_parse_upper_gteq_lower_with_upper_limit_between_lower_and_upper( self, lo_hi_limit, legit_delim, ): lo, hi, limit = lo_hi_limit exp = NatIntervalInclusive(lo, limit) arg = str(lo) + legit_delim + str(hi) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( lo_hi_upper=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[0] <= t[1] <= t[2] ) ) def METHOD_NAME( self, lo_hi_upper, legit_delim ): lo, hi, upper_bound = lo_hi_upper exp = NatIntervalInclusive(lo, hi) arg = f"{str(lo)}{legit_delim}{str(hi)}" obs = NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) assert obs == exp
null
53
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 import os import os.path import re import string import sys import time from glideinwms.frontend import glideinFrontendConfig, glideinFrontendDowntimeLib def usage(): print("Usage:") print(" manageFrontendDowntimes.py -dir frontend_dir -cmd [command] [options]") print("where command is one of:") print(" add - Add a scheduled downtime period") print(" down - Put the factory down now(+delay)") print(" up - Get the factory back up now(+delay)") print(" check - Report if the factory is in downtime now(+delay)") print("Other options:") print(" -start [[[YYYY-]MM-]DD-]HH:MM[:SS] (start time for adding a downtime)") print(" -end [[[YYYY-]MM-]DD-]HH:MM[:SS] (end time for adding a downtime)") print(" -delay [HHh][MMm][SS[s]] (delay a downtime for down, up, and check cmds)") # [[[YYYY-]MM-]DD-]HH:MM[:SS] def strtxt2time(timeStr): deftime = time.localtime(time.time()) year = deftime[0] month = deftime[1] day = deftime[2] seconds = 0 darr = timeStr.split("-") # [[[YYYY-]MM-]DD-]HH:MM[:SS] if len(darr) > 1: # we have at least part of the date timeStr = darr[-1] day = int(darr[-2]) if len(darr) > 2: month = int(darr[-3]) if len(darr) > 3: year = int(darr[-4]) tarr = timeStr.split(":") hours = int(tarr[0]) minutes = int(tarr[1]) if len(tarr) > 2: seconds = int(tarr[2]) outtime = time.mktime((year, month, day, hours, minutes, seconds, 0, 0, -1)) return outtime # this is epoch format # [[[YYYY-]MM-]DD-]HH:MM[:SS] # or # unix_time def str2time(timeStr): if len(timeStr.split(":", 1)) > 1: return strtxt2time(timeStr) # has a :, so it must be a text representation else: print(timeStr) return int(timeStr) # should be a simple number # [HHh][MMm][SS[s]] def delay2time(delayStr): hours = 0 minutes = 0 seconds = 0 # getting hours harr = delayStr.split("h", 1) if len(harr) == 2: hours = int(harr[0]) delayStr = harr[1] # getting minutes marr = delayStr.split("m", 1) if len(marr) == 2: minutes = int(marr[0]) delayStr = marr[1] # getting seconds if delayStr[-1:] == "s": delayStr = delayStr[:-1] # remove final s if present if len(delayStr) > 0: seconds = int(delayStr) return seconds + 60 * (minutes + 60 * hours) def get_downtime_fd(work_dir): frontendDescript = glideinFrontendConfig.FrontendDescript(work_dir) fd = glideinFrontendDowntimeLib.DowntimeFile(os.path.join(work_dir, frontendDescript.data["DowntimesFile"])) return fd # major commands def add(opt_dict): # glideinFrontendDowntimeLib.DowntimeFile( self.elementDescript.frontend_data['DowntimesFile'] ) down_fd = get_downtime_fd(opt_dict["dir"]) start_time = str2time(opt_dict["start"]) end_time = str2time(opt_dict["end"]) down_fd.addPeriod(start_time=start_time, end_time=end_time) return 0 # this calls checkDowntime(with delayed_start_time ) first and then startDowntime(with delayed_start_time and end_time) def down(opt_dict): down_fd = get_downtime_fd(opt_dict["dir"]) when = delay2time(opt_dict["delay"]) if opt_dict["start"] == "None": when += int(time.time()) else: # delay applies only to the start time when += str2time(opt_dict["start"]) if opt_dict["end"] == "None": end_time = None else: end_time = str2time(opt_dict["end"]) if not down_fd.checkDowntime(check_time=when): # only add a new line if not in downtime at that time return down_fd.startDowntime(start_time=when, end_time=end_time) else: print("Frontend is already down. ") return 0 # calls endDowntime( with end_time only ) def up(opt_dict): down_fd = get_downtime_fd(opt_dict["dir"]) when = delay2time(opt_dict["delay"]) if opt_dict["end"] == "None": when += int(time.time()) else: # delay applies only to the end time when += str2time(opt_dict["end"]) rtn = down_fd.endDowntime(end_time=when) if rtn > 0: return 0 else: print("Frontend is not in downtime.") return 1 def METHOD_NAME(opt_dict): down_fd = get_downtime_fd(opt_dict["dir"]) when = delay2time(opt_dict["delay"]) + int(time.time()) down_fd.printDowntime(check_time=when) def get_args(argv): opt_dict = {"comment": "", "sec": "All", "delay": "0", "end": "None", "start": "None", "frontend": "All"} index = 0 for arg in argv: if len(argv) <= index + 1: continue if arg == "-cmd": opt_dict["cmd"] = argv[index + 1] if arg == "-dir": opt_dict["dir"] = argv[index + 1] if arg == "-start": opt_dict["start"] = argv[index + 1] if arg == "-end": opt_dict["end"] = argv[index + 1] if arg == "-delay": opt_dict["delay"] = argv[index + 1] index = index + 1 return opt_dict def main(argv): if len(argv) < 3: usage() return 1 # Get the command line arguments opt_dict = get_args(argv) try: frontend_dir = opt_dict["dir"] cmd = opt_dict["cmd"] except KeyError as e: usage() print("-cmd -dir argument is required.") return 1 try: os.chdir(frontend_dir) except OSError as e: usage() print("Failed to locate factory %s" % frontend_dir) print("%s" % e) return 1 if cmd == "add": return add(opt_dict) elif cmd == "down": return down(opt_dict) elif cmd == "up": return up(opt_dict) elif cmd == "check": return METHOD_NAME(opt_dict) else: usage() print("Invalid command %s" % cmd) return 1 if __name__ == "__main__": sys.exit(main(sys.argv))
null
54
#!/usr/bin/env python3 from pathlib import Path import sys import cv2 import depthai as dai import numpy as np # Press WASD to move a manual ROI window for auto-exposure control. # Press N to go back to the region controlled by the NN detections. # Get argument first nnPath = str((Path(__file__).parent / Path('../models/mobilenet-ssd_openvino_2021.4_6shave.blob')).resolve().absolute()) if len(sys.argv) > 1: nnPath = sys.argv[1] if not Path(nnPath).exists(): import sys raise FileNotFoundError(f'Required file/s not found, please run "{sys.executable} install_requirements.py"') previewSize = (300, 300) # Create pipeline pipeline = dai.Pipeline() # Define source and outputs camRgb = pipeline.create(dai.node.ColorCamera) camRgb.setPreviewSize(*previewSize) camRgb.setInterleaved(False) camControlIn = pipeline.create(dai.node.XLinkIn) camControlIn.setStreamName('camControl') camControlIn.out.link(camRgb.inputControl) # Define a neural network that will make predictions based on the source frames nn = pipeline.create(dai.node.MobileNetDetectionNetwork) nn.setConfidenceThreshold(0.5) nn.setBlobPath(nnPath) nn.setNumInferenceThreads(2) nn.input.setBlocking(False) camRgb.preview.link(nn.input) # Linking xoutRgb = pipeline.create(dai.node.XLinkOut) xoutRgb.setStreamName("rgb") camRgb.preview.link(xoutRgb.input) nnOut = pipeline.create(dai.node.XLinkOut) nnOut.setStreamName("nn") nn.out.link(nnOut.input) # MobilenetSSD label texts labelMap = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] def clamp(num, v0, v1): return max(v0, min(num, v1)) def asControl(roi): camControl = dai.CameraControl() camControl.setAutoExposureRegion(*roi) return camControl class AutoExposureRegion: step = 10 position = (0, 0) size = (100, 100) resolution = camRgb.getResolutionSize() maxDims = previewSize[0], previewSize[1] def grow(self, x=0, y=0): self.size = ( clamp(x + self.size[0], 1, self.maxDims[0]), clamp(y + self.size[1], 1, self.maxDims[1]) ) def move(self, x=0, y=0): self.position = ( clamp(x + self.position[0], 0, self.maxDims[0]), clamp(y + self.position[1], 0, self.maxDims[1]) ) def endPosition(self): return ( clamp(self.position[0] + self.size[0], 0, self.maxDims[0]), clamp(self.position[1] + self.size[1], 0, self.maxDims[1]), ) def toRoi(self): roi = np.array([*self.position, *self.size]) # Convert to absolute camera coordinates roi = roi * self.resolution[1] // 300 roi[0] += (self.resolution[0] - self.resolution[1]) // 2 # x offset for device crop return roi @staticmethod def METHOD_NAME(bbox): startX, startY = bbox[:2] width, height = bbox[2] - startX, bbox[3] - startY roi = frameNorm(np.empty(camRgb.getResolutionSize()), (startX, startY, width, height)) return roi # Connect to device and start pipeline with dai.Device(pipeline) as device: # Output queues will be used to get the rgb frames and nn data from the outputs defined above qControl = device.getInputQueue(name="camControl") qRgb = device.getOutputQueue(name="rgb", maxSize=4, blocking=False) qDet = device.getOutputQueue(name="nn", maxSize=4, blocking=False) frame = None detections = [] nnRegion = True region = AutoExposureRegion() # nn data (bounding box locations) are in <0..1> range - they need to be normalized with frame width/height def frameNorm(frame, bbox): normVals = np.full(len(bbox), frame.shape[0]) normVals[::2] = frame.shape[1] return (np.clip(np.array(bbox), 0, 1) * normVals).astype(int) def displayFrame(name, frame): for detection in detections: bbox = frameNorm(frame, (detection.xmin, detection.ymin, detection.xmax, detection.ymax)) cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (255, 0, 0), 2) cv2.putText(frame, labelMap[detection.label], (bbox[0] + 10, bbox[1] + 20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, 255) cv2.putText(frame, f"{int(detection.confidence * 100)}%", (bbox[0] + 10, bbox[1] + 40), cv2.FONT_HERSHEY_TRIPLEX, 0.5, 255) if not nnRegion: cv2.rectangle(frame, region.position, region.endPosition(), (0, 255, 0), 2) cv2.imshow(name, frame) while True: # Instead of get (blocking), we use tryGet (non-blocking) which will return the available data or None otherwise inRgb = qRgb.tryGet() inDet = qDet.tryGet() if inRgb is not None: frame = inRgb.getCvFrame() if inDet is not None: detections = inDet.detections if nnRegion and len(detections) > 0: bbox = (detections[0].xmin, detections[0].ymin, detections[0].xmax, detections[0].ymax) qControl.send(asControl(AutoExposureRegion.METHOD_NAME(bbox))) if frame is not None: displayFrame("rgb", frame) key = cv2.waitKey(1) if key == ord('n'): print("AE ROI controlled by NN") nnRegion = True elif key in [ord('w'), ord('a'), ord('s'), ord('d'), ord('+'), ord('-')]: nnRegion = False if key == ord('a'): region.move(x=-region.step) if key == ord('d'): region.move(x=region.step) if key == ord('w'): region.move(y=-region.step) if key == ord('s'): region.move(y=region.step) if key == ord('+'): region.grow(x=10, y=10) region.step = region.step + 1 if key == ord('-'): region.grow(x=-10, y=-10) region.step = max(region.step - 1, 1) print(f"Setting static AE ROI: {region.toRoi()} (on frame: {[*region.position, *region.endPosition()]})") qControl.send(asControl(region.toRoi())) elif key == ord('q'): break
null
55
# Copyright 2017-2022 EPAM Systems, Inc. (https://www.epam.com/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from src.api.entity import Entity from .base import API import json from ..model.object_permission_model import ObjectPermissionModel class User(API): def __init__(self): super(User, self).__init__() @classmethod def METHOD_NAME(cls, identifier, acl_class): entity = Entity.load_by_id_or_name(identifier, acl_class) return cls.permissions(entity['id'], entity['aclClass']), entity['owner'] @classmethod def permissions(cls, id, acl_class): api = cls.instance() response_data = api.call('permissions?id={}&aclClass={}'.format(id, acl_class.upper()), None) if 'payload' in response_data and 'permissions' in response_data['payload']: permissions = [] for permission_json in response_data['payload']['permissions']: permission_object = ObjectPermissionModel.load(permission_json) permission_object.parse_mask(True) permissions.append(permission_object) return permissions else: return [] @classmethod def grant_permission(cls, identifier, acl_class, user_name, principal, mask): api = cls.instance() payload = {} if acl_class is not None: payload['aclClass'] = acl_class.upper() if identifier is not None: payload['id'] = identifier if mask is not None: payload['mask'] = mask if principal is not None: payload['principal'] = principal if user_name is not None: payload['userName'] = user_name data = json.dumps(payload) api.call('grant', data) @classmethod def change_owner(cls, user_name, class_name, object_id): api = cls.instance() response_data = api.call('/grant/owner?userName={}&aclClass={}&id={}'.format( user_name, str(class_name).upper(), object_id), None, http_method='POST') if 'payload' in response_data and 'entity' in response_data['payload']: return response_data['payload']['entity'] if 'message' in response_data: raise RuntimeError(response_data['message']) else: raise RuntimeError("Failed to change owner.") @classmethod def generate_user_token(cls, user_name, duration): api = cls.instance() query = '/user/token?name=%s' % user_name if duration: query = '&expiration='.join([query, str(duration)]) response_data = api.call(query, None) if 'payload' in response_data and 'token' in response_data['payload']: return response_data['payload']['token'] if 'message' in response_data: raise RuntimeError(response_data['message']) else: raise RuntimeError("Failed to generate user token.") @classmethod def import_users(cls, file_path, create_user, create_group, create_metadata): api = cls.instance() query = '/users/import?createUser=%s&createGroup=%s' % (create_user, create_group) if create_metadata: query = '%s&createMetadata=%s' % (query, ",".join(create_metadata)) response_data = api.upload(query, file_path) if 'payload' in response_data: return response_data['payload'] if 'message' in response_data: raise RuntimeError(response_data['message']) else: return [] @classmethod def whoami(cls): api = cls.instance() return api.retryable_call('GET', '/whoami') or {} @classmethod def load_launch_limits(cls, load_all=False): api = cls.instance() return api.retryable_call('GET', '/user/launchLimits?loadAll={}'.format(load_all)) or {}
null
56
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RoaRequest from aliyunsdkcs.endpoint import endpoint_data class ScaleOutClusterRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'CS', '2015-12-15', 'ScaleOutCluster') self.set_uri_pattern('/api/v2/clusters/[ClusterId]') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_worker_data_disk(self): return self.get_body_params().get('worker_data_disk') def set_worker_data_disk(self,worker_data_disk): self.add_body_params('worker_data_disk', worker_data_disk) def METHOD_NAME(self): return self.get_body_params().get('key_pair') def set_key_pair(self,key_pair): self.add_body_params('key_pair', key_pair) def get_count(self): return self.get_body_params().get('count') def set_count(self,count): self.add_body_params('count', count) def get_worker_system_disk_category(self): return self.get_body_params().get('worker_system_disk_category') def set_worker_system_disk_category(self,worker_system_disk_category): self.add_body_params('worker_system_disk_category', worker_system_disk_category) def get_cloud_monitor_flags(self): return self.get_body_params().get('cloud_monitor_flags') def set_cloud_monitor_flags(self,cloud_monitor_flags): self.add_body_params('cloud_monitor_flags', cloud_monitor_flags) def get_ClusterId(self): return self.get_path_params().get('ClusterId') def set_ClusterId(self,ClusterId): self.add_path_param('ClusterId',ClusterId) def get_user_data(self): return self.get_body_params().get('user_data') def set_user_data(self,user_data): self.add_body_params('user_data', user_data) def get_worker_period_unit(self): return self.get_body_params().get('worker_period_unit') def set_worker_period_unit(self,worker_period_unit): self.add_body_params('worker_period_unit', worker_period_unit) def get_worker_auto_renew(self): return self.get_body_params().get('worker_auto_renew') def set_worker_auto_renew(self,worker_auto_renew): self.add_body_params('worker_auto_renew', worker_auto_renew) def get_worker_auto_renew_period(self): return self.get_body_params().get('worker_auto_renew_period') def set_worker_auto_renew_period(self,worker_auto_renew_period): self.add_body_params('worker_auto_renew_period', worker_auto_renew_period) def get_worker_period(self): return self.get_body_params().get('worker_period') def set_worker_period(self,worker_period): self.add_body_params('worker_period', worker_period) def get_login_password(self): return self.get_body_params().get('login_password') def set_login_password(self,login_password): self.add_body_params('login_password', login_password) def get_worker_system_disk_size(self): return self.get_body_params().get('worker_system_disk_size') def set_worker_system_disk_size(self,worker_system_disk_size): self.add_body_params('worker_system_disk_size', worker_system_disk_size) def get_cpu_policy(self): return self.get_body_params().get('cpu_policy') def set_cpu_policy(self,cpu_policy): self.add_body_params('cpu_policy', cpu_policy) def get_disable_rollback(self): return self.get_body_params().get('disable_rollback') def set_disable_rollback(self,disable_rollback): self.add_body_params('disable_rollback', disable_rollback) def get_image_id(self): return self.get_body_params().get('image_id') def set_image_id(self,image_id): self.add_body_params('image_id', image_id) def get_worker_instance_charge_type(self): return self.get_body_params().get('worker_instance_charge_type') def set_worker_instance_charge_type(self,worker_instance_charge_type): self.add_body_params('worker_instance_charge_type', worker_instance_charge_type
null
57
#/############################################################################ # # This module is based on an answer published in: # # http://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application # # by Tim Rae # # This file is part of the PyMca X-ray Fluorescence Toolkit developed at # the ESRF. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # #############################################################################*/ __author__ = "Tim Rae, V.A. Sole" __contact__ = "[email protected]" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" # Set the QT API import os import sys from PyMca5.PyMcaGui.PyMcaQt import QApplication, QWidget, \ QPushButton, QVBoxLayout, QMessageBox, \ BINDING # this seems to be obsolete stuff if BINDING == "PySide": os.environ['QT_API'] = 'pyside' elif BINDING == "PySide2": os.environ['QT_API'] = 'pyside2' elif BINDING == "PyQt4": os.environ['QT_API'] = 'pyqt' else: os.environ['QT_API'] = 'pyqt5' QTCONSOLE = True if sys.version_info < (3,): import IPython if IPython.__version__.startswith("2"): QTCONSOLE = False else: try: import qtconsole except ImportError: QTCONSOLE = False import IPython if QTCONSOLE: try: from qtconsole.rich_ipython_widget import RichJupyterWidget as RichIPythonWidget except Exception: from qtconsole.rich_ipython_widget import RichIPythonWidget from qtconsole.inprocess import QtInProcessKernelManager else: # Import the console machinery from ipython # Check if we using a frozen version because # the test of IPython does not find the Qt bindings executables = ["PyMcaMain.exe", "QStackWidget.exe", "PyMcaPostBatch.exe"] if os.path.basename(sys.executable) in executables: import IPython.external.qt_loaders def has_binding(*var, **kw): return True IPython.external.qt_loaders.has_binding = has_binding from IPython.qt.console.rich_ipython_widget import RichIPythonWidget from IPython.qt.inprocess import QtInProcessKernelManager class QIPythonWidget(RichIPythonWidget): """ Convenience class for a live IPython console widget. We can replace the standard banner using the customBanner argument""" def __init__(self,customBanner=None,*args,**kwargs): super(QIPythonWidget, self).__init__(*args,**kwargs) if customBanner != None: self.banner = customBanner self.setWindowTitle(self.banner) self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() try: # https://github.com/ipython/ipykernel/issues/370 from ipykernel import version_info if version_info < (5, 1, 1): def _abort_queues(kernel): pass kernel_manager.kernel._abort_queues = _abort_queues except Exception: pass if BINDING in ["PySide", "PyQt4"]: kernel_manager.kernel.gui = 'qt4' self.kernel_client = kernel_client = self._kernel_manager.client() kernel_client.start_channels() def stop(): #clear workspace msg = QMessageBox(self) msg.setWindowTitle("Console cleanup") msg.setText("Do you want to clean the console workspace?") msg.setStandardButtons(QMessageBox.No | QMessageBox.Yes) msg.setDefaultButton(QMessageBox.Yes) ret = msg.exec() try: if ret == QMessageBox.Yes: self.kernel_manager.kernel.shell.magic('reset -sf') kernel_client.stop_channels() kernel_manager.shutdown_kernel() except Exception: print("Error cleaning console variables") kernel_client.stop_channels() kernel_manager.shutdown_kernel() # close widget instead of quitting application self.close() self.exit_requested.connect(stop) def METHOD_NAME(self,variableDict): """ Given a dictionary containing name / value pairs, push those variables to the IPython console widget """ self.kernel_manager.kernel.shell.push(variableDict) def clearTerminal(self): """ Clears the terminal """ self._control.clear() def printText(self,text): """ Prints some plain text to the console """ self._append_plain_text(text) def executeCommand(self,command): """ Execute a command in the frame of the console widget """ self._execute(command,False) def show(self): if self.kernel_manager.kernel is None: # we need to restart the kernel self.kernel_manager.start_kernel() self.kernel_client.start_channels() return RichIPythonWidget.show(self) class ExampleWidget(QWidget): """ Main GUI Widget including a button and IPython Console widget inside vertical layout """ def __init__(self, parent=None): super(ExampleWidget, self).__init__(parent) layout = QVBoxLayout(self) self.button = QPushButton('Another widget') ipyConsole = QIPythonWidget(customBanner="Welcome to the embedded ipython console\n") layout.addWidget(self.button) layout.addWidget(ipyConsole) # This allows the variable foo and method print_process_id to be accessed from the ipython console ipyConsole.METHOD_NAME({"foo":43,"print_process_id":print_process_id}) ipyConsole.printText("The variable 'foo' and the method 'print_process_id()' are available. Use the 'whos' command for information.") def print_process_id(): print('Process ID is:', os.getpid()) def main(): app = QApplication([]) widget = ExampleWidget() widget.show() app.exec() if __name__ == '__main__': main()
null
58
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkconfig.endpoint import endpoint_data class CreateAggregateConfigDeliveryChannelRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Config', '2020-09-07', 'CreateAggregateConfigDeliveryChannel') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_NonCompliantNotification(self): # Boolean return self.get_query_params().get('NonCompliantNotification') def set_NonCompliantNotification(self, NonCompliantNotification): # Boolean self.add_query_param('NonCompliantNotification', NonCompliantNotification) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def METHOD_NAME(self): # Boolean return self.get_query_params().get('ConfigurationSnapshot') def set_ConfigurationSnapshot(self, ConfigurationSnapshot): # Boolean self.add_query_param('ConfigurationSnapshot', ConfigurationSnapshot) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_AggregatorId(self): # String return self.get_query_params().get('AggregatorId') def set_AggregatorId(self, AggregatorId): # String self.add_query_param('AggregatorId', AggregatorId) def get_DeliveryChannelTargetArn(self): # String return self.get_query_params().get('DeliveryChannelTargetArn') def set_DeliveryChannelTargetArn(self, DeliveryChannelTargetArn): # String self.add_query_param('DeliveryChannelTargetArn', DeliveryChannelTargetArn) def get_DeliveryChannelCondition(self): # String return self.get_query_params().get('DeliveryChannelCondition') def set_DeliveryChannelCondition(self, DeliveryChannelCondition): # String self.add_query_param('DeliveryChannelCondition', DeliveryChannelCondition) def get_ConfigurationItemChangeNotification(self): # Boolean return self.get_query_params().get('ConfigurationItemChangeNotification') def set_ConfigurationItemChangeNotification(self, ConfigurationItemChangeNotification): # Boolean self.add_query_param('ConfigurationItemChangeNotification', ConfigurationItemChangeNotification) def get_DeliveryChannelName(self): # String return self.get_query_params().get('DeliveryChannelName') def set_DeliveryChannelName(self, DeliveryChannelName): # String self.add_query_param('DeliveryChannelName', DeliveryChannelName) def get_DeliverySnapshotTime(self): # String return self.get_query_params().get('DeliverySnapshotTime') def set_DeliverySnapshotTime(self, DeliverySnapshotTime): # String self.add_query_param('DeliverySnapshotTime', DeliverySnapshotTime) def get_OversizedDataOSSTargetArn(self): # String return self.get_query_params().get('OversizedDataOSSTargetArn') def set_OversizedDataOSSTargetArn(self, OversizedDataOSSTargetArn): # String self.add_query_param('OversizedDataOSSTargetArn', OversizedDataOSSTargetArn) def get_DeliveryChannelType(self): # String return self.get_query_params().get('DeliveryChannelType') def set_DeliveryChannelType(self, DeliveryChannelType): # String self.add_query_param('DeliveryChannelType', DeliveryChannelType)
null
59
from methods.regular.regular_api import * from shared.utils.task.task_update_manager import Task_Update @routes.route('/api/v1/project/<string:project_string_id>' + '/task/next', methods = ['POST']) @limiter.limit("1 per second, 50 per minute, 1000 per day") @Project_permissions.user_has_project( ["admin", "Editor", "annotator"]) def api_get_next_task_annotator(project_string_id): log = regular_input.regular_log.default_api_log() with sessionMaker.session_scope() as session: project = Project.get(session, project_string_id) user = User.get(session) if not user: log['error']['usage'] = "Designed for human users." return jsonify( log = log), 200 task = get_next_task_by_project( session = session, user = user, project = project) if task is None: log['info']['task'] = "No tasks available." return jsonify( log = log), 200 task_serialized = task.serialize_trainer_annotate(session) log['success'] = True return jsonify( log = log, task = task_serialized), 200 def get_next_task_by_project( session, user, project): task = Task.get_last_task( session = session, user = user, status_allow_list = ["available", "in_progress"]) if task: return task task = Task.request_next_task_by_project( session = session, project = project, user = user) if task: task.add_assignee(session, user) task_update_manager = Task_Update( session = session, task = task, status = 'in_progress' ) task_update_manager.main() # This updates the task status session.add(task) session.add(user) return task def get_next_task_by_job( session, user, job): task = Task.get_last_task( session = session, user = user, status_allow_list = ["available", "in_progress"], job=job) if task: return task task = recursively_get_next_available(session = session, job = job, user = user) if task: task.add_assignee(session, user) task_update_manager = Task_Update( session = session, task = task, status = 'in_progress' ) # set status task_update_manager.main() # This updates the task status session.add(task) session.add(user) return task @routes.route('/api/v1/job/<int:job_id>/task/next', methods = ['POST']) @limiter.limit("1 per second, 1000 per day") @Job_permissions.by_job_id( mode = "builder", apis_user_list = ['builder_or_trainer', 'security_email_verified']) def METHOD_NAME(job_id): log = regular_input.regular_log.default_api_log() with sessionMaker.session_scope() as session: job = Job.get_by_id(session, job_id) user = User.get(session) task = get_next_task_by_job( session = session, user = user, job = job) if task is None: log['info']['task'] = "No tasks available." return jsonify( log = log), 200 task_serialized = task.serialize_trainer_annotate(session) log['success'] = True return jsonify( log = log, task = task_serialized), 200 def recursively_get_next_available(session, job, user): """ Goal, give consideration to task types, and not expect that first result from shared.database matches "business?" logic Example of saying a person can't review their own task """ ignore_task_IDS_list = [] while True: task = Task.get_next_available_task_by_job_id( session = session, job_id = job.id, ignore_task_IDS_list = ignore_task_IDS_list) if task is None: return None if task.task_type == 'draw': return task if task.task_type == 'review': result = valid_review_task_for_user(session = session, task = task, user = user) if result is True: return task else: ignore_task_IDS_list.append(task.id) def valid_review_task_for_user(session, task, user): parent = Task.get_by_id(session, task.parent_id) # task.parent not working for some reason if parent: if user == parent.assignee_user: return False return Tru
null
60
""" Models for the Financial Aid App """ from django.contrib.auth.models import User from django.db import ( models, transaction, ) from rest_framework.exceptions import ValidationError from courses.models import Program from financialaid.constants import FinancialAidStatus from micromasters.models import ( AuditableModel, AuditModel, TimestampedModel, ) from micromasters.utils import serialize_model_object class Tier(TimestampedModel): """ The possible tiers to be used """ name = models.TextField() description = models.TextField() def __str__(self): return self.name class TierProgram(TimestampedModel): """ The tiers for discounted pricing assigned to a program """ program = models.ForeignKey(Program, null=False, related_name="tier_programs", on_delete=models.CASCADE) tier = models.ForeignKey(Tier, null=False, related_name="tier_programs", on_delete=models.CASCADE) discount_amount = models.IntegerField(null=False) current = models.BooleanField(null=False, default=False) income_threshold = models.IntegerField(null=False) class Meta: unique_together = ('program', 'tier') def __str__(self): return 'tier "{0}" for program "{1}"'.format(self.tier.name, self.program.title) @transaction.atomic def save(self, *args, **kwargs): # pylint: disable=signature-differs """ Override the save to enforce the existence of only one `current` = True per program and tier """ if self.current: TierProgram.objects.filter(program=self.program, tier=self.tier, current=True).update(current=False) return super().save(*args, **kwargs) class FinancialAid(TimestampedModel, AuditableModel): """ An application for financial aid/personal pricing """ user = models.ForeignKey(User, null=False, on_delete=models.CASCADE) tier_program = models.ForeignKey(TierProgram, null=False, on_delete=models.CASCADE) status = models.CharField( null=False, choices=[(status, status) for status in FinancialAidStatus.ALL_STATUSES], default=FinancialAidStatus.CREATED, max_length=30, ) income_usd = models.FloatField(null=True) original_income = models.FloatField(null=True) original_currency = models.CharField(null=True, max_length=10) country_of_income = models.CharField(null=True, max_length=100) date_exchange_rate = models.DateTimeField(null=True) date_documents_sent = models.DateField(null=True, blank=True) justification = models.TextField(null=True) country_of_residence = models.TextField() def save(self, *args, **kwargs): # pylint: disable=signature-differs """ Override save to make sure only one FinancialAid object exists for a User and the associated Program """ # if this is a change just save if FinancialAid.objects.filter(id=self.id).exists(): super().save(*args, **kwargs) return # otherwise see if we can create another one if FinancialAid.objects.filter( user=self.user, tier_program__program=self.tier_program.program ).exclude(status=FinancialAidStatus.RESET).exists(): raise ValidationError("Cannot have multiple FinancialAid objects for the same User and Program.") super().save(*args, **kwargs) @classmethod def get_audit_class(cls): return FinancialAidAudit def to_dict(self): return serialize_model_object(self) def __str__(self): return 'FA for user "{user}" in status "{status}"'.format( user=self.user.username, status=self.status ) class FinancialAidAudit(AuditModel): """ Audit table for the Financial Aid """ financial_aid = models.ForeignKey(FinancialAid, null=True, on_delete=models.SET_NULL) @classmethod def METHOD_NAME(cls): return 'financial_aid' class CurrencyExchangeRate(TimestampedModel): """ Table of currency exchange rates for converting foreign currencies into USD """ currency_code = models.CharField(null=False, max_length=3) exchange_rate = models.FloatField(null=False) # how much foreign currency is per 1 USD class CountryIncomeThreshold(TimestampedModel): """ Table of country income thresholds for financial aid auto approval """ country_code = models.CharField(null=False, unique=True, max_length=2) income_threshold = models.IntegerField(null=False)
null
61
# Copyright cocotb contributors # Licensed under the Revised BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-3-Clause """ Tests of cocotb.test functionality * expect_error * expect_fail * timeout """ from collections.abc import Coroutine import pytest from common import MyBaseException, MyException import cocotb from cocotb.triggers import NullTrigger, Timer @cocotb.test(expect_error=NameError) async def METHOD_NAME(dut): """Error in the test""" await Timer(100, "ns") fail # noqa @cocotb.test() async def test_tests_are_tests(dut): """ Test that things annotated with cocotb.test are tests """ assert isinstance(test_tests_are_tests, cocotb.test) # just to be sure... @cocotb.test(expect_fail=True) async def test_async_test_can_fail(dut): assert False @cocotb.test() async def test_immediate_test(dut): """Test that tests can return immediately""" return @cocotb.test(expect_fail=True) async def test_assertion_is_failure(dut): assert False @cocotb.test(expect_error=MyException) async def test_expect_particular_exception(dut): raise MyException() @cocotb.test(expect_error=(MyException, ValueError)) async def test_expect_exception_list(dut): raise MyException() @cocotb.test( expect_error=cocotb.result.SimTimeoutError, timeout_time=1, timeout_unit="ns" ) async def test_timeout_testdec_fail(dut): await Timer(10, "ns") @cocotb.test(timeout_time=100, timeout_unit="ns") async def test_timeout_testdec_pass(dut): await Timer(10, "ns") @cocotb.test(timeout_time=10, timeout_unit="ns") async def test_timeout_testdec_simultaneous(dut): try: await cocotb.triggers.with_timeout( Timer(1, "ns"), timeout_time=1, timeout_unit="ns" ) except cocotb.result.SimTimeoutError: pass else: assert False, "Expected a Timeout" # Whether this test fails or passes depends on the behavior of the # scheduler, simulator, and the implementation of the timeout function. # CAUTION: THIS MAY CHANGE # these tests should run in definition order, not lexicographic order last_ordered_test = None @cocotb.test() async def test_ordering_3(dut): global last_ordered_test val, last_ordered_test = last_ordered_test, 3 assert val is None @cocotb.test() async def test_ordering_2(dut): global last_ordered_test val, last_ordered_test = last_ordered_test, 2 assert val == 3 @cocotb.test() async def test_ordering_1(dut): global last_ordered_test val, last_ordered_test = last_ordered_test, 1 assert val == 2 @cocotb.test() class TestClass(Coroutine): def __init__(self, dut): self._coro = self.run(dut) async def run(self, dut): pass def send(self, value): self._coro.send(value) def throw(self, exception): self._coro.throw(exception) def __await__(self): yield from self._coro.__await__() @cocotb.test() async def test_empty_docstring(dut) -> None: """""" @cocotb.test(expect_fail=True) async def test_pytest_raises_fail(dut): with pytest.raises(AssertionError): assert True @cocotb.test(expect_fail=True) async def test_pytest_warns_fail(dut): def test_func(): pass with pytest.warns(RuntimeWarning): test_func() @cocotb.test(expect_fail=True) async def test_pytest_deprecated_call_fail(dut): def test_func(): pass with pytest.deprecated_call(): test_func() @cocotb.test(expect_fail=True) async def test_pytest_raises_fail_in_task(dut): async def test_func(): with pytest.raises(AssertionError): assert True cocotb.start_soon(test_func()) await NullTrigger() @cocotb.test(expect_fail=True) async def test_pytest_warns_fail_in_task(dut): def inner_func(): pass async def test_func(): with pytest.warns(RuntimeWarning): inner_func() cocotb.start_soon(test_func()) await NullTrigger() @cocotb.test(expect_fail=True) async def test_pytest_deprecated_call_fail_in_task(dut): def inner_func(): pass async def test_func(): with pytest.deprecated_call(): inner_func() cocotb.start_soon(test_func()) await NullTrigger() @cocotb.test(expect_error=MyBaseException) async def test_base_exception_expect_fail(dut): raise MyBaseException @cocotb.test(expect_error=MyBaseException) async def test_base_exception_in_task_expect_fail(dut): async def test_func(): raise MyBaseException cocotb.start_soon(test_func()) await NullTrigger() @cocotb.test async def test_without_parenthesis(dut): pass
null
62
"""Tests for the natural numbers range data type""" from typing import * import pytest from hypothesis import Phase, given, settings, strategies as st from looper.utils import NatIntervalException, NatIntervalInclusive gen_pos_int = st.integers(min_value=1) gen_opt_int = st.one_of(st.integers(), st.none()) def is_non_pos(opt_int: Optional[int]) -> bool: """Determine whether the given value is non-positive (and non-null).""" return opt_int is not None and opt_int < 1 def pytest_generate_tests(metafunc): if "legit_delim" in metafunc.fixturenames: metafunc.parametrize("legit_delim", [":", "-"]) def nondecreasing_pair_strategy(**kwargs): """Generate a pair of values in which first respects given upper bound and second is no more than first.""" return st.tuples(st.integers(**kwargs), st.integers(**kwargs)).filter( lambda p: p[0] <= p[1] ) class NaturalRangePureConstructorTests: """Tests for direct use of natural range primary constructor""" @given(upper_bound=gen_pos_int) def test_zero_is_prohibited(self, upper_bound): """Separate this case since it's an edge case.""" with pytest.raises(NatIntervalException): NatIntervalInclusive(0, upper_bound) @given(bounds=nondecreasing_pair_strategy(max_value=0)) def test_non_positive_is_prohibited(self, bounds): lo, hi = bounds with pytest.raises(NatIntervalException): NatIntervalInclusive(lo, hi) @given(bounds=st.tuples(st.integers(), st.integers()).filter(lambda p: p[0] > p[1])) def test_upper_less_than_lower__fails_as_expected(self, bounds): lo, hi = bounds with pytest.raises(NatIntervalException): NatIntervalInclusive(lo, hi) class NaturalRangeFromStringTests: """Tests for parsing of natural number range from text, like CLI arg""" @pytest.mark.parametrize( "arg_template", ["0{sep}0", "{sep}0", "0{sep}", "0{sep}0", "{sep}0", "0{sep}"] ) @given(upper_bound=gen_pos_int) def test_zero__does_not_parse(self, arg_template, legit_delim, upper_bound): arg = arg_template.format(sep=legit_delim) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @given(upper_bound=st.integers()) def test_just_delimiter__does_not_parse(self, legit_delim, upper_bound): with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(legit_delim, upper_bound=upper_bound) @given( lo_hi_upper=st.tuples(gen_opt_int, gen_opt_int, st.integers()).filter( lambda t: (t[0] is not None or t[1] is not None) and any(is_non_pos(n) for n in t) ) ) def test_nonpositive_values__fail_with_expected_error( self, lo_hi_upper, legit_delim ): lo, hi, upper_bound = lo_hi_upper if lo is None and hi is None: raise ValueError("Both lower and upper bound generated are null.") if lo is None: arg = legit_delim + str(hi) elif hi is None: arg = str(lo) + legit_delim else: arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @pytest.mark.parametrize("arg", ["1,2", "1;2", "1_2", "1/2", "1.2", "1~2"]) @given(upper_bound=st.integers(min_value=3)) def test_illegal_delimiter__fail_with_expected_error(self, arg, upper_bound): with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) @given( lower_and_limit=st.tuples(st.integers(), st.integers()).filter( lambda p: p[1] < p[0] ) ) def test_one_sided_lower_with_samples_lt_bound__fails( self, lower_and_limit, legit_delim ): lower, limit = lower_and_limit arg = str(lower) + legit_delim with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=limit) @given(lower_and_upper=nondecreasing_pair_strategy(min_value=1)) def test_one_sided_lower_with_samples_gteq_bound__succeeds( self, lower_and_upper, legit_delim ): lo, upper_bound = lower_and_upper exp = NatIntervalInclusive(lo, upper_bound) arg = str(lo) + legit_delim obs = NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) assert obs == exp @given(upper_and_limit=nondecreasing_pair_strategy(min_value=1)) def test_one_sided_upper_with_samples_gteq_bound__succeeds( self, upper_and_limit, legit_delim ): upper, limit = upper_and_limit exp = NatIntervalInclusive(1, upper) arg = legit_delim + str(upper) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( upper_and_limit=st.tuples( st.integers(min_value=1), st.integers(min_value=1) ).filter(lambda p: p[1] < p[0]) ) def test_one_sided_upper_with_samples_lt_bound__uses_bound( self, upper_and_limit, legit_delim ): upper, limit = upper_and_limit exp = NatIntervalInclusive(1, limit) arg = legit_delim + str(upper) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( lower_upper_limit=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[1] < t[0] or t[2] < t[0] ) ) def test_two_sided_parse_upper_lt_lower(self, lower_upper_limit, legit_delim): lo, hi, lim = lower_upper_limit arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=lim) @given( lo_hi_limit=st.tuples( st.integers(min_value=2), gen_pos_int, gen_pos_int ).filter(lambda t: t[2] < t[0] <= t[1]) ) def METHOD_NAME( self, lo_hi_limit, legit_delim ): lo, hi, limit = lo_hi_limit arg = str(lo) + legit_delim + str(hi) with pytest.raises(NatIntervalException): NatIntervalInclusive.from_string(arg, upper_bound=limit) @given( lo_hi_limit=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[0] < t[2] < t[1] ) ) def test_two_sided_parse_upper_gteq_lower_with_upper_limit_between_lower_and_upper( self, lo_hi_limit, legit_delim, ): lo, hi, limit = lo_hi_limit exp = NatIntervalInclusive(lo, limit) arg = str(lo) + legit_delim + str(hi) obs = NatIntervalInclusive.from_string(arg, upper_bound=limit) assert obs == exp @given( lo_hi_upper=st.tuples(gen_pos_int, gen_pos_int, gen_pos_int).filter( lambda t: t[0] <= t[1] <= t[2] ) ) def test_two_sided_parse_upper_gteq_lower_with_upper_limit_gteq_upper( self, lo_hi_upper, legit_delim ): lo, hi, upper_bound = lo_hi_upper exp = NatIntervalInclusive(lo, hi) arg = f"{str(lo)}{legit_delim}{str(hi)}" obs = NatIntervalInclusive.from_string(arg, upper_bound=upper_bound) assert obs == exp
null
63
# Copyright 2019 Camptocamp (http://www.camptocamp.com). # @author Simone Orsi <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.component.core import Component # TODO: this exception is not handled yet on Locomotive side. # Currently if we raise the error the frontend is broken. # Hence, let's rely on `enabled` flag to adjust the UI # until we handle the exception client side, # from ..exceptions import PartnerNotValidatedError class PartnerValidator(Component): _name = "shopinvader.partner.validator" _inherit = "base.shopinvader.component" _usage = "partner.validator" _apply_on = "res.partner" def validate_partner(self, partner): if self.backend.validate_customers: validator = getattr( self, "_validate_partner_{}".format(self.backend.validate_customers_type), lambda partner: True, ) # TODO: this should raise an exception if not satisfied # but the validation is done in the controller # and the frontend is not able to handle it properly yet. # See `InvaderController._get_partner_from_headers` validator(partner) def _validate_partner_all(self, partner): if not partner.is_shopinvader_active: # raise PartnerNotValidatedError( # "Customer found but not validated yet." # ) pass def _validate_partner_address(self, partner): if not partner.shopinvader_enabled and not partner.address_type == "address": # raise PartnerNotValidatedError( # "Address found but not validated yet." # ) pass def _validate_partner_company(self, partner): if ( not partner.is_shopinvader_active and partner.is_company and partner.address_type == "profile" ): # raise PartnerNotValidatedError( # "Company found but not validated yet." # ) pass def _validate_partner_user(self, partner): if ( not partner.is_shopinvader_active and not partner.is_company and partner.address_type == "profile" ): # raise PartnerNotValidatedError( # "Customer found but not validated yet." # ) pass def _validate_partner_company_and_user(self, partner): self._validate_partner_company(partner) self._validate_partner_user(partner) def _allowed_partner_types(self): return [x[0] for x in self.model._fields["address_type"].selection] def enabled_by_params(self, params, partner_type="profile"): """Check if partner is enabled via given params by given partner type. This is mostly used by services to check if the partner they are dealing with is enabled or should be enabled (create case). """ assert partner_type in self._allowed_partner_types() if not self.backend.validate_customers: return True backend_policy = self.backend.validate_customers_type if backend_policy == "all": return False handler = getattr( self, "_enabled_by_params_for_{}".format(partner_type), lambda backend_policy, params: True, ) return handler(backend_policy, params) def _enabled_by_params_for_profile(self, backend_policy, params): """Check if enabled by partner type == "profile".""" is_company = "is_company" in params and params["is_company"] if backend_policy == "company": return not is_company elif backend_policy == "user": if "is_company" not in params: # definetely not a company return False # rely on the flag: got a company -> enabled return is_company elif backend_policy == "company_and_user": return False return True def _enabled_by_params_for_address(self, backend_policy, params): """Check if enabled by partner type == "address".""" if backend_policy == "address": return not params["is_company"] and params.get("parent_id") return True def METHOD_NAME(self, partner): """Check if given partner is enabled for current backend.""" if self.backend.validate_customers and not partner.is_shopinvader_active: return False return True
null
64
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkunimkt.endpoint import endpoint_data class ListRuleAreaRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'UniMkt', '2018-12-12', 'ListRuleArea') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_AdSlotType(self): # String return self.get_query_params().get('AdSlotType') def set_AdSlotType(self, AdSlotType): # String self.add_query_param('AdSlotType', AdSlotType) def get_RuleName(self): # String return self.get_query_params().get('RuleName') def set_RuleName(self, RuleName): # String self.add_query_param('RuleName', RuleName) def get_UserId(self): # String return self.get_query_params().get('UserId') def set_UserId(self, UserId): # String self.add_query_param('UserId', UserId) def get_OriginSiteUserId(self): # String return self.get_query_params().get('OriginSiteUserId') def METHOD_NAME(self, OriginSiteUserId): # String self.add_query_param('OriginSiteUserId', OriginSiteUserId) def get_PageNumber(self): # Integer return self.get_query_params().get('PageNumber') def set_PageNumber(self, PageNumber): # Integer self.add_query_param('PageNumber', PageNumber) def get_AppName(self): # String return self.get_query_params().get('AppName') def set_AppName(self, AppName): # String self.add_query_param('AppName', AppName) def get_TenantId(self): # String return self.get_query_params().get('TenantId') def set_TenantId(self, TenantId): # String self.add_query_param('TenantId', TenantId) def get_AdSlotId(self): # String return self.get_query_params().get('AdSlotId') def set_AdSlotId(self, AdSlotId): # String self.add_query_param('AdSlotId', AdSlotId) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_EndCreateTime(self): # Long return self.get_query_params().get('EndCreateTime') def set_EndCreateTime(self, EndCreateTime): # Long self.add_query_param('EndCreateTime', EndCreateTime) def get_Business(self): # String return self.get_query_params().get('Business') def set_Business(self, Business): # String self.add_query_param('Business', Business) def get_RuleType(self): # String return self.get_query_params().get('RuleType') def set_RuleType(self, RuleType): # String self.add_query_param('RuleType', RuleType) def get_MediaId(self): # String return self.get_query_params().get('MediaId') def set_MediaId(self, MediaId): # String self.add_query_param('MediaId', MediaId) def get_MediaStatus(self): # String return self.get_query_params().get('MediaStatus') def set_MediaStatus(self, MediaStatus): # String self.add_query_param('MediaStatus', MediaStatus) def get_Environment(self): # String return self.get_query_params().get('Environment') def set_Environment(self, Environment): # String self.add_query_param('Environment', Environment) def get_StartCreateTime(self): # Long return self.get_query_params().get('StartCreateTime') def set_StartCreateTime(self, StartCreateTime): # Long self.add_query_param('StartCreateTime', StartCreateTime) def get_UserSite(self): # String return self.get_query_params().get('UserSite') def set_UserSite(self, UserSite): # String self.add_query_param('UserSite', UserSite) def get_RuleId(self): # String return self.get_query_params().get('RuleId') def set_RuleId(self, RuleId): # String self.add_query_param('RuleId', RuleId)
null
65
# Drakkar-Software OctoBot-Tentacles # Copyright (c) Drakkar-Software, All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3.0 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. import requests # comment imports to remove twitter from dependencies when tentacle is disabled # import twitter # import twitter.api # import twitter.twitter_utils import octobot_services.constants as services_constants import octobot_services.services as services import octobot.constants as constants # disable inheritance to disable tentacle visibility. Disabled as starting from feb 9 2023, API is now paid only # class TwitterService(services.AbstractService): class TwitterService: API_KEY = "api-key" API_SECRET = "api-secret" ACCESS_TOKEN = "access-token" ACCESS_TOKEN_SECRET = "access-token-secret" def __init__(self): super().__init__() self.twitter_api = None self._account_url = None def get_fields_description(self): return { self.API_KEY: "Your Twitter API key.", self.API_SECRET: "Your Twitter API-secret key.", self.ACCESS_TOKEN: "Your Twitter access token key.", self.ACCESS_TOKEN_SECRET: "Your Twitter access token secret key." } def get_default_value(self): return { self.API_KEY: "", self.API_SECRET: "", self.ACCESS_TOKEN: "", self.ACCESS_TOKEN_SECRET: "" } def get_required_config(self): return [self.API_KEY, self.API_SECRET, self.ACCESS_TOKEN, self.ACCESS_TOKEN_SECRET] def get_read_only_info(self): return { "Connected to": self._account_url } if self._account_url else {} @classmethod def get_help_page(cls) -> str: return f"{constants.OCTOBOT_DOCS_URL}/interfaces/twitter-interface" @staticmethod def is_setup_correctly(config): return services_constants.CONFIG_TWITTER in config[services_constants.CONFIG_CATEGORY_SERVICES] \ and services_constants.CONFIG_SERVICE_INSTANCE in config[services_constants.CONFIG_CATEGORY_SERVICES][ services_constants.CONFIG_TWITTER] def get_user_id(self, user_account): user = self.twitter_api.GetUser(screen_name=user_account) return user.id def get_history(self, user_id): return self.twitter_api.GetUserTimeline(user_id=user_id) async def prepare(self): if not self.twitter_api: self.twitter_api = twitter.Api( self.config[services_constants.CONFIG_CATEGORY_SERVICES][services_constants.CONFIG_TWITTER][ self.API_KEY], self.config[services_constants.CONFIG_CATEGORY_SERVICES][services_constants.CONFIG_TWITTER][ self.API_SECRET], self.config[services_constants.CONFIG_CATEGORY_SERVICES][services_constants.CONFIG_TWITTER][ self.ACCESS_TOKEN], self.config[services_constants.CONFIG_CATEGORY_SERVICES][services_constants.CONFIG_TWITTER][ self.ACCESS_TOKEN_SECRET], sleep_on_rate_limit=True ) def get_type(self): return services_constants.CONFIG_TWITTER def METHOD_NAME(self): return "https://twitter.com/" def get_endpoint(self): return self.twitter_api def has_required_configuration(self): return services_constants.CONFIG_CATEGORY_SERVICES in self.config \ and services_constants.CONFIG_TWITTER in self.config[services_constants.CONFIG_CATEGORY_SERVICES] \ and self.check_required_config( self.config[services_constants.CONFIG_CATEGORY_SERVICES][services_constants.CONFIG_TWITTER]) @staticmethod def decode_tweet(tweet): if "extended_tweet" in tweet and "full_text" in tweet: return tweet["extended_tweet"]["full_text"] elif "text" in tweet: return tweet["text"] return "" async def post(self, content, error_on_failure=True): try: return self.split_if_necessary_and_send_tweet(content=content, tweet_id=None) except Exception as e: error = f"Failed to send tweet : {e} tweet:{content}" if error_on_failure: self.logger.error(error) else: self.logger.info(error) return None async def respond(self, tweet_id, content, error_on_failure=True): try: return self.split_if_necessary_and_send_tweet(content=content, tweet_id=tweet_id) except Exception as e: error = f"Failed to send response tweet : {e} tweet:{content}" if error_on_failure: self.logger.error(error) else: self.logger.info(error) return None def split_if_necessary_and_send_tweet(self, content, counter=None, counter_max=None, tweet_id=None): # add twitter counter at the beginning if counter is not None and counter_max is not None: content = f"{counter}/{counter_max} {content}" counter += 1 # get the current content size post_size = twitter.twitter_utils.calc_expected_status_length(content) # check if the current content size can be posted if post_size > twitter.api.CHARACTER_LIMIT: # calculate the number of post required for the whole content if not counter_max: counter_max = post_size // twitter.api.CHARACTER_LIMIT counter = 1 # post the current tweet # no async call possible yet post = self.twitter_api.PostUpdate(status=content[:twitter.api.CHARACTER_LIMIT], in_reply_to_status_id=tweet_id) # recursive call for all post while content > twitter.api.CHARACTER_LIMIT self.split_if_necessary_and_send_tweet(content[twitter.api.CHARACTER_LIMIT:], counter=counter, counter_max=counter_max, tweet_id=tweet_id) return post else: return self.twitter_api.PostUpdate(status=content[:twitter.api.CHARACTER_LIMIT], in_reply_to_status_id=tweet_id) def get_tweet_text(self, tweet): try: return TwitterService.decode_tweet(tweet) except Exception as e2: self.logger.error(e2) return "" @staticmethod def get_twitter_id_from_url(url): return str(url).split("/")[-1] def get_tweet(self, tweet_id): return self.twitter_api.GetStatus(tweet_id) def _fetch_twitter_url(self): self._account_url = f"https://twitter.com/{self.twitter_api.VerifyCredentials().screen_name}" return self._account_url def get_successful_startup_message(self): try: return f"Successfully initialized and accessible at: {self._fetch_twitter_url()}.", True except requests.exceptions.ConnectionError as e: self.log_connection_error_message(e) return "", False
null
66
################################################################################ # Creme is a free/open-source Customer Relationship Management software # Copyright (C) 2013-2023 Hybird # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ################################################################################ from __future__ import annotations import logging from typing import Iterable from django.db.models import Model from django.db.models.query import Q, QuerySet from ..core import entity_cell from ..models import CustomField, FieldsConfig, SearchConfigItem from ..utils.string import smart_split logger = logging.getLogger(__name__) # TODO: see creme_core.forms.listview.CustomCharField/CustomChoiceField def _q_for_customfield(cell, word): field_type = cell.custom_field.field_type if field_type == CustomField.ENUM: # TODO: avoid a JOIN by doing a first query in Enum values ? return Q( pk__in=cell.custom_field .value_class .objects .filter(custom_field=cell.custom_field, value__value__icontains=word) .values_list('entity_id', flat=True) ) elif field_type == CustomField.MULTI_ENUM: enum_ids = ( cell.custom_field .customfieldenumvalue_set .filter(value__icontains=word) .values_list('id', flat=True) ) return Q( pk__in=cell.custom_field .value_class .objects .filter(custom_field=cell.custom_field, value__in=enum_ids) .values_list('entity_id', flat=True) ) else: return Q( pk__in=cell.custom_field .value_class .objects .filter(custom_field=cell.custom_field, value__icontains=word) .values_list('entity_id', flat=True) ) class Searcher: """Build QuerySets to search strings contained in instances of some given models. The search configuration (see the model SearchConfigItem) is used to know which fields to use. Hidden fields (see model FieldsConfig) are ignored. """ CELL_TO_Q = { entity_cell.EntityCellRegularField.type_id: lambda cell, word: Q(**{f'{cell.value}__icontains': word}), entity_cell.EntityCellCustomField.type_id: _q_for_customfield, } def __init__(self, models: Iterable[type[Model]], user): """Constructor. @param models: Iterable of classes inheriting <django.db.models.Model>. @param user: Instance of <django.contrib.auth.get_user_model()>. """ self.user = user search_map: dict[type[Model], list[entity_cell.EntityCell]] = {} models = [*models] # Several iterations # TODO: move in iter_for_models() ? FieldsConfig.objects.get_for_models(models) # Fill cache for sci in SearchConfigItem.objects.iter_for_models(models, user): if not sci.disabled: model = sci.content_type.model_class() search_map[model] = [*sci.refined_cells] self._search_map = search_map def METHOD_NAME(self, words, cells) -> Q: """Build a Q with given fields for the given search. Each word must be contained in (at least) one field. @param words: Searched strings. @param cells: Sequence of <creme_core.core.entity_cell.EntityCell> objects. @return: Instance of <django.db.models.query.Q>. """ result_q = Q() get_q_builder = self.CELL_TO_Q.get for word in words: word_q = Q() for cell in cells: builder = get_q_builder(cell.type_id) if builder: word_q |= builder(cell, word) else: logger.warning( '%s._build_query: cell type not managed "%s".', type(self).__name__, cell.type_id, ) result_q &= word_q return result_q def get_cells(self, model: type[Model]) -> list[entity_cell.EntityCell]: """Get the list of EntityCells instances used to search in 'model'.""" return self._search_map[model] @property def models(self): "View on the models this Searcher use." return self._search_map.keys() def search(self, model: type[Model], research: str) -> QuerySet | None: """Return a query with the models which fields contain the wanted value. @param model: Class inheriting django.db.Model (CremeEntity) @param research: Searched string ; it's split in words (see utils.string.smart_split()). @return: Queryset on model or None ; None means 'All fields are hidden'. """ cells = self.get_cells(model) assert cells is not None # search on a disabled model ? strings = smart_split(research) # TODO: distinct() only if there is a JOIN... return model.objects.filter( self.METHOD_NAME(strings, cells) ).distinct() if cells else None
null
67
# coding: utf-8 """ Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator """ import unittest from unittest.mock import patch import urllib3 import typing_extensions import unit_test_api from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import operation as post # noqa: E501 from unit_test_api import schemas, api_client from unit_test_api.configurations import api_configuration, schema_configuration from .. import ApiTestMixin class TestPost(ApiTestMixin, unittest.TestCase): """ Post unit test stubs """ api_config = api_configuration.ApiConfiguration() schema_config = schema_configuration.SchemaConfiguration() used_api_client = api_client.ApiClient(configuration=api_config, schema_configuration=schema_config) api = post.ApiForPost(api_client=used_api_client) # noqa: E501 response_status = 200 response_body = '' def test_too_short_is_invalid_fails(self): content_type = 'application/json' # too short is invalid with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( [ ] ) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): body = post.request_body.RequestBody.content["application/json"].schema.validate( payload, configuration=self.schema_config ) self.api.post(body=body) def test_ignores_non_arrays_passes(self): content_type = 'application/json' # ignores non-arrays with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( "" ) body = post.request_body.RequestBody.content["application/json"].schema.validate( payload, configuration=self.schema_config ) mock_request.return_value = self.response( self.json_bytes(self.response_body), status=self.response_status ) api_response = self.api.post( body=body, ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/requestBody/postMinitemsValidationRequestBody", method='post'.upper(), body=self.json_bytes(payload), content_type=content_type, ) assert isinstance(api_response.response, urllib3.HTTPResponse) assert isinstance(api_response.body, schemas.Unset) def test_longer_is_valid_passes(self): content_type = 'application/json' # longer is valid with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( [ 1, 2, ] ) body = post.request_body.RequestBody.content["application/json"].schema.validate( payload, configuration=self.schema_config ) mock_request.return_value = self.response( self.json_bytes(self.response_body), status=self.response_status ) api_response = self.api.post( body=body, ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/requestBody/postMinitemsValidationRequestBody", method='post'.upper(), body=self.json_bytes(payload), content_type=content_type, ) assert isinstance(api_response.response, urllib3.HTTPResponse) assert isinstance(api_response.body, schemas.Unset) def METHOD_NAME(self): content_type = 'application/json' # exact length is valid with patch.object(urllib3.PoolManager, 'request') as mock_request: payload = ( [ 1, ] ) body = post.request_body.RequestBody.content["application/json"].schema.validate( payload, configuration=self.schema_config ) mock_request.return_value = self.response( self.json_bytes(self.response_body), status=self.response_status ) api_response = self.api.post( body=body, ) self.assert_pool_manager_request_called_with( mock_request, self.api_config.get_server_url('servers', None) + "/requestBody/postMinitemsValidationRequestBody", method='post'.upper(), body=self.json_bytes(payload), content_type=content_type, ) assert isinstance(api_response.response, urllib3.HTTPResponse) assert isinstance(api_response.body, schemas.Unset) if __name__ == '__main__': unittest.main()
null
68
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkdyvmsapi.endpoint import endpoint_data class SmartCallRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Dyvmsapi', '2017-05-25', 'SmartCall','dyvms') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_VoiceCodeParam(self): return self.get_query_params().get('VoiceCodeParam') def set_VoiceCodeParam(self,VoiceCodeParam): self.add_query_param('VoiceCodeParam',VoiceCodeParam) def get_EarlyMediaAsr(self): return self.get_query_params().get('EarlyMediaAsr') def set_EarlyMediaAsr(self,EarlyMediaAsr): self.add_query_param('EarlyMediaAsr',EarlyMediaAsr) def get_BackgroundSpeed(self): return self.get_query_params().get('BackgroundSpeed') def set_BackgroundSpeed(self,BackgroundSpeed): self.add_query_param('BackgroundSpeed',BackgroundSpeed) def get_BackgroundVolume(self): return self.get_query_params().get('BackgroundVolume') def set_BackgroundVolume(self,BackgroundVolume): self.add_query_param('BackgroundVolume',BackgroundVolume) def get_Speed(self): return self.get_query_params().get('Speed') def set_Speed(self,Speed): self.add_query_param('Speed',Speed) def get_AsrBaseId(self): return self.get_query_params().get('AsrBaseId') def set_AsrBaseId(self,AsrBaseId): self.add_query_param('AsrBaseId',AsrBaseId) def get_SessionTimeout(self): return self.get_query_params().get('SessionTimeout') def set_SessionTimeout(self,SessionTimeout): self.add_query_param('SessionTimeout',SessionTimeout) def get_DynamicId(self): return self.get_query_params().get('DynamicId') def set_DynamicId(self,DynamicId): self.add_query_param('DynamicId',DynamicId) def get_CalledNumber(self): return self.get_query_params().get('CalledNumber') def set_CalledNumber(self,CalledNumber): self.add_query_param('CalledNumber',CalledNumber) def get_TtsSpeed(self): return self.get_query_params().get('TtsSpeed') def set_TtsSpeed(self,TtsSpeed): self.add_query_param('TtsSpeed',TtsSpeed) def get_VoiceCode(self): return self.get_query_params().get('VoiceCode') def set_VoiceCode(self,VoiceCode): self.add_query_param('VoiceCode',VoiceCode) def get_CalledShowNumber(self): return self.get_query_params().get('CalledShowNumber') def set_CalledShowNumber(self,CalledShowNumber): self.add_query_param('CalledShowNumber',CalledShowNumber) def get_EnableITN(self): return self.get_query_params().get('EnableITN') def set_EnableITN(self,EnableITN): self.add_query_param('EnableITN',EnableITN) def get_ActionCodeTimeBreak(self): return self.get_query_params().get('ActionCodeTimeBreak') def set_ActionCodeTimeBreak(self,ActionCodeTimeBreak): self.add_query_param('ActionCodeTimeBreak',ActionCodeTimeBreak) def get_TtsConf(self): return self.get_query_params().get('TtsConf') def set_TtsConf(self,TtsConf): self.add_query_param('TtsConf',TtsConf) def get_ActionCodeBreak(self): return self.get_query_params().get('ActionCodeBreak') def set_ActionCodeBreak(self,ActionCodeBreak): self.add_query_param('ActionCodeBreak',ActionCodeBreak) def METHOD_NAME(self): return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self,ResourceOwnerAccount): self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount) def get_RecordFlag(self): return self.get_query_params().get('RecordFlag') def set_RecordFlag(self,RecordFlag): self.add_query_param('RecordFlag',RecordFlag) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_TtsVolume(self): return self.get_query_params().get('TtsVolume') def set_TtsVolume(self,TtsVolume): self.add_query_param('TtsVolume',TtsVolume) def get_StreamAsr(self): return self.get_query_params().get('StreamAsr') def set_StreamAsr(self,StreamAsr): self.add_query_param('StreamAsr',StreamAsr) def get_Volume(self): return self.get_query_params().get('Volume') def set_Volume(self,Volume): self.add_query_param('Volume',Volume) def get_MuteTime(self): return self.get_query_params().get('MuteTime') def set_MuteTime(self,MuteTime): self.add_query_param('MuteTime',MuteTime) def get_BackgroundFileCode(self): return self.get_query_params().get('BackgroundFileCode') def set_BackgroundFileCode(self,BackgroundFileCode): self.add_query_param('BackgroundFileCode',BackgroundFileCode) def get_OutId(self): return self.get_query_params().get('OutId') def set_OutId(self,OutId): self.add_query_param('OutId',OutId) def get_AsrModelId(self): return self.get_query_params().get('AsrModelId') def set_AsrModelId(self,AsrModelId): self.add_query_param('AsrModelId',AsrModelId) def get_PauseTime(self): return self.get_query_params().get('PauseTime') def set_PauseTime(self,PauseTime): self.add_query_param('PauseTime',PauseTime) def get_TtsStyle(self): return self.get_query_params().get('TtsStyle') def set_TtsStyle(self,TtsStyle): self.add_query_param('TtsStyle',TtsStyle
null
69
import json from django.conf import settings from django.test import TestCase from django.urls import reverse from parameterized import parameterized from experimenter.legacy.legacy_experiments.api.v1.serializers import ( ExperimentSerializer, ) from experimenter.legacy.legacy_experiments.constants import ExperimentConstants from experimenter.legacy.legacy_experiments.models import Experiment from experimenter.legacy.legacy_experiments.tests.factories import ExperimentFactory from experimenter.legacy.normandy.serializers import ExperimentRecipeSerializer class TestExperimentListView(TestCase): def METHOD_NAME(self): experiments = [] for i in range(3): experiment = ExperimentFactory.create_with_variants() experiments.append(experiment) response = self.client.get(reverse("experiments-api-list")) self.assertEqual(response.status_code, 200) json_data = json.loads(response.content) serialized_experiments = ExperimentSerializer( Experiment.objects.get_prefetched(), many=True ).data self.assertEqual(serialized_experiments, json_data) def test_list_view_filters_by_status(self): pending_experiments = [] # new experiments should be excluded for i in range(2): ExperimentFactory.create_with_variants() # pending experiments should be included for i in range(3): experiment = ExperimentFactory.create_with_variants() experiment.status = experiment.STATUS_REVIEW experiment.save() pending_experiments.append(experiment) response = self.client.get( reverse("experiments-api-list"), {"status": Experiment.STATUS_REVIEW} ) self.assertEqual(response.status_code, 200) json_data = json.loads(response.content) serialized_experiments = ExperimentSerializer( Experiment.objects.get_prefetched().filter(status=Experiment.STATUS_REVIEW), many=True, ).data self.assertEqual(serialized_experiments, json_data) class TestExperimentDetailView(TestCase): def test_get_experiment_returns_experiment_info(self): user_email = "[email protected]" experiment = ExperimentFactory.create_with_variants() response = self.client.get( reverse("experiments-api-detail", kwargs={"slug": experiment.slug}), **{settings.OPENIDC_EMAIL_HEADER: user_email}, ) self.assertEqual(response.status_code, 200) json_data = json.loads(response.content) serialized_experiment = ExperimentSerializer(experiment).data self.assertEqual(serialized_experiment, json_data) class TestExperimentRecipeView(TestCase): @parameterized.expand( [ ExperimentConstants.STATUS_SHIP, ExperimentConstants.STATUS_ACCEPTED, ExperimentConstants.STATUS_LIVE, ExperimentConstants.STATUS_COMPLETE, ] ) def test_get_experiment_recipe_returns_recipe_info_for_launched_experiment( self, status ): user_email = "[email protected]" experiment = ExperimentFactory.create_with_status(status) response = self.client.get( reverse("experiments-api-recipe", kwargs={"slug": experiment.slug}), **{settings.OPENIDC_EMAIL_HEADER: user_email}, ) self.assertEqual(response.status_code, 200) json_data = json.loads(response.content) serialized_experiment = ExperimentRecipeSerializer(experiment).data self.assertEqual(serialized_experiment, json_data) @parameterized.expand( [ExperimentConstants.STATUS_DRAFT, ExperimentConstants.STATUS_REVIEW] ) def test_get_experiment_recipe_returns_404_for_not_launched_experiment(self, status): user_email = "[email protected]" experiment = ExperimentFactory.create_with_status(status) response = self.client.get( reverse("experiments-api-recipe", kwargs={"slug": experiment.slug}), **{settings.OPENIDC_EMAIL_HEADER: user_email}, ) self.assertEqual(response.status_code, 404)
null
70
# Copyright 2023 EPAM Systems, Inc. (https://www.epam.com/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os from pipefuse.fsclient import FileSystemClientDecorator PATH_SEPARATOR = '/' class ArchivedFilesFilterFileSystemClient(FileSystemClientDecorator): def __init__(self, inner, pipe, bucket): """ Filters files that have GLACIER or DEEP_ARCHIVE storage class and not restored. :param inner: Decorating file system client. :param pipe: Cloud Pipeline API client. :param bucket: Bucket object. """ super(ArchivedFilesFilterFileSystemClient, self).__init__(inner) self._inner = inner self._pipe = pipe self._bucket = bucket def ls(self, path, depth=1): items = self._inner.ls(path, depth) restored_paths = None result = [] folder_restored = False is_file = not path.endswith(PATH_SEPARATOR) for item in items: if not item.is_dir and item.storage_class != 'STANDARD' and item.storage_class != 'INTELLIGENT_TIERING': path = self._normalize_path(path) if restored_paths is None: restored_paths = self._get_restored_paths(path, is_file) folder_restored = self._folder_restored(path, restored_paths) if not folder_restored: file_path = path if is_file else path + item.name if not restored_paths.__contains__(file_path): continue result.append(item) return result @staticmethod def _normalize_path(path): if not path: return PATH_SEPARATOR if not path.startswith(PATH_SEPARATOR): path = PATH_SEPARATOR + path return path def _get_restored_paths(self, path, is_file=False): try: response = self._pipe.get_storage_lifecycle(self._bucket, path, is_file) items = [] if not response: return set() for item in response: if item.is_restored(): items.append(item.path) return set(items) except Exception: logging.exception('Storage lifecycle retrieving has failed') return set() @staticmethod def _folder_restored(folder_path, storage_lifecycle): for path in storage_lifecycle: if folder_path.startswith(path): return True return False class ArchivedAttributesFileSystemClient(FileSystemClientDecorator): def __init__(self, inner, pipe, bucket): """ Adds storage class attribute :param inner: Decorating file system client. :param pipe: Cloud Pipeline API client. :param bucket: Bucket object. """ super(ArchivedAttributesFileSystemClient, self).__init__(inner) self._inner = inner self._pipe = pipe self._bucket = bucket def download_xattrs(self, path): try: tags = self._inner.download_xattrs(path) source_file = self._get_archived_file(path) return tags if not source_file else self.METHOD_NAME(tags, source_file, self._get_storage_lifecycle(path)) except Exception: logging.exception('Download archived tags has failed') return {} def _get_archived_file(self, path): items = self._inner.ls(path, depth=1) if not items: return None files = [item for item in items if not item.is_dir and item.storage_class and item.storage_class != 'STANDARD' and item.storage_class != 'INTELLIGENT_TIERING'] if not files or len(files) != 1: return None return files[0] def METHOD_NAME(self, tags, source_file, lifecycle): tag_value = self._get_storage_class_tag_value(lifecycle, source_file.storage_class) if tag_value: tags.update({'user.system.lifecycle.status': tag_value}) return tags @staticmethod def _get_storage_class_tag_value(lifecycle, storage_class): if not lifecycle or not storage_class: return storage_class if lifecycle.is_restored(): retired_till = (' till ' + lifecycle.restored_till) if lifecycle.restored_till else '' return '%s (Restored%s)' % (storage_class, retired_till) return storage_class def _get_storage_lifecycle(self, path, is_file=True): try: lifecycle_items = self._pipe.get_storage_lifecycle(self._bucket, path, is_file) return None if not lifecycle_items or len(lifecycle_items) == 0 else lifecycle_items[0] except Exception: logging.exception('Storage last lifecycle retrieving has failed') return None
null
71
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkslb.endpoint import endpoint_data class CreateLoadBalancerRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Slb', '2014-05-15', 'CreateLoadBalancer','slb') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_AddressIPVersion(self): # String return self.get_query_params().get('AddressIPVersion') def set_AddressIPVersion(self, AddressIPVersion): # String self.add_query_param('AddressIPVersion', AddressIPVersion) def METHOD_NAME(self): # String return self.get_query_params().get('MasterZoneId') def set_MasterZoneId(self, MasterZoneId): # String self.add_query_param('MasterZoneId', MasterZoneId) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_LoadBalancerName(self): # String return self.get_query_params().get('LoadBalancerName') def set_LoadBalancerName(self, LoadBalancerName): # String self.add_query_param('LoadBalancerName', LoadBalancerName) def get_SlaveZoneId(self): # String return self.get_query_params().get('SlaveZoneId') def set_SlaveZoneId(self, SlaveZoneId): # String self.add_query_param('SlaveZoneId', SlaveZoneId) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) def get_LoadBalancerSpec(self): # String return self.get_query_params().get('LoadBalancerSpec') def set_LoadBalancerSpec(self, LoadBalancerSpec): # String self.add_query_param('LoadBalancerSpec', LoadBalancerSpec) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_VSwitchId(self): # String return self.get_query_params().get('VSwitchId') def set_VSwitchId(self, VSwitchId): # String self.add_query_param('VSwitchId', VSwitchId) def get_InternetChargeType(self): # String return self.get_query_params().get('InternetChargeType') def set_InternetChargeType(self, InternetChargeType): # String self.add_query_param('InternetChargeType', InternetChargeType) def get_PricingCycle(self): # String return self.get_query_params().get('PricingCycle') def set_PricingCycle(self, PricingCycle): # String self.add_query_param('PricingCycle', PricingCycle) def get_ModificationProtectionReason(self): # String return self.get_query_params().get('ModificationProtectionReason') def set_ModificationProtectionReason(self, ModificationProtectionReason): # String self.add_query_param('ModificationProtectionReason', ModificationProtectionReason) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_Duration(self): # Integer return self.get_query_params().get('Duration') def set_Duration(self, Duration): # Integer self.add_query_param('Duration', Duration) def get_AddressType(self): # String return self.get_query_params().get('AddressType') def set_AddressType(self, AddressType): # String self.add_query_param('AddressType', AddressType) def get_InstanceChargeType(self): # String return self.get_query_params().get('InstanceChargeType') def set_InstanceChargeType(self, InstanceChargeType): # String self.add_query_param('InstanceChargeType', InstanceChargeType) def get_DeleteProtection(self): # String return self.get_query_params().get('DeleteProtection') def set_DeleteProtection(self, DeleteProtection): # String self.add_query_param('DeleteProtection', DeleteProtection) def get_AutoPay(self): # Boolean return self.get_query_params().get('AutoPay') def set_AutoPay(self, AutoPay): # Boolean self.add_query_param('AutoPay', AutoPay) def get_Address(self): # String return self.get_query_params().get('Address') def set_Address(self, Address): # String self.add_query_param('Address', Address) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_Bandwidth(self): # Integer return self.get_query_params().get('Bandwidth') def set_Bandwidth(self, Bandwidth): # Integer self.add_query_param('Bandwidth', Bandwidth) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_ModificationProtectionStatus(self): # String return self.get_query_params().get('ModificationProtectionStatus') def set_ModificationProtectionStatus(self, ModificationProtectionStatus): # String self.add_query_param('ModificationProtectionStatus', ModificationProtectionStatus) def get_VpcId(self): # String return self.get_query_params().get('VpcId') def set_VpcId(self, VpcId): # String self.add_query_param('VpcId', VpcId) def get_PayType(self): # String return self.get_query_params().get('PayType') def set_PayType(self, PayType): # String self.add_query_param('PayType', PayType)
null
72
from typing import Optional from AnyQt.QtCore import Qt, QSizeF, QRectF, QPointF from AnyQt.QtGui import QPixmap, QTransform, QPainter from AnyQt.QtWidgets import ( QGraphicsWidget, QGraphicsItem, QStyleOptionGraphicsItem, QWidget, ) from Orange.widgets.utils.graphicslayoutitem import scaled class GraphicsPixmapWidget(QGraphicsWidget): def __init__( self, parent: Optional[QGraphicsItem] = None, pixmap: Optional[QPixmap] = None, scaleContents=False, aspectMode=Qt.KeepAspectRatio, **kwargs ) -> None: self.__scaleContents = scaleContents self.__aspectMode = aspectMode self.__pixmap = QPixmap(pixmap) if pixmap is not None else QPixmap() super().__init__(None, **kwargs) self.setFlag(QGraphicsWidget.ItemUsesExtendedStyleOption, True) self.setContentsMargins(0, 0, 0, 0) if parent is not None: self.setParentItem(parent) def METHOD_NAME(self, pixmap: QPixmap) -> None: self.prepareGeometryChange() self.__pixmap = QPixmap(pixmap) self.updateGeometry() def pixmap(self) -> QPixmap: return QPixmap(self.__pixmap) def setAspectRatioMode(self, mode: Qt.AspectRatioMode) -> None: if self.__aspectMode != mode: self.__aspectMode = mode sp = self.sizePolicy() sp.setHeightForWidth( self.__aspectMode != Qt.IgnoreAspectRatio and self.__scaleContents ) self.setSizePolicy(sp) self.updateGeometry() def aspectRatioMode(self) -> Qt.AspectRatioMode: return self.__aspectMode def setScaleContents(self, scale: bool) -> None: if self.__scaleContents != scale: self.__scaleContents = bool(scale) sp = self.sizePolicy() sp.setHeightForWidth( self.__aspectMode != Qt.IgnoreAspectRatio and self.__scaleContents ) self.setSizePolicy(sp) self.updateGeometry() def scaleContents(self) -> bool: return self.__scaleContents def sizeHint(self, which, constraint=QSizeF(-1, -1)) -> QSizeF: if which == Qt.PreferredSize: sh = QSizeF(self.__pixmap.size()) if self.__scaleContents: sh = scaled(sh, constraint, self.__aspectMode) return sh elif which == Qt.MinimumSize: if self.__scaleContents: return QSizeF(0, 0) else: return QSizeF(self.__pixmap.size()) elif which == Qt.MaximumSize: if self.__scaleContents: return QSizeF() else: return QSizeF(self.__pixmap.size()) else: # Qt.MinimumDescent return QSizeF() def pixmapTransform(self) -> QTransform: if self.__pixmap.isNull(): return QTransform() pxsize = QSizeF(self.__pixmap.size()) crect = self.contentsRect() transform = QTransform() transform = transform.translate(crect.left(), crect.top()) if self.__scaleContents: csize = scaled(pxsize, crect.size(), self.__aspectMode) else: csize = pxsize xscale = csize.width() / pxsize.width() yscale = csize.height() / pxsize.height() return transform.scale(xscale, yscale) def paint( self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: Optional[QWidget] = None ) -> None: if self.__pixmap.isNull(): return pixmap = self.__pixmap crect = self.contentsRect() exposed = option.exposedRect exposedcrect = crect.intersected(exposed) pixmaptransform = self.pixmapTransform() # map exposed rect to exposed pixmap coords assert pixmaptransform.type() in ( QTransform.TxNone, QTransform.TxTranslate, QTransform.TxScale ) pixmaptransform, ok = pixmaptransform.inverted() if not ok: painter.drawPixmap( crect, pixmap, QRectF(QPointF(0, 0), QSizeF(pixmap.size())) ) else: exposedpixmap = pixmaptransform.mapRect(exposed) painter.drawPixmap(exposedcrect, pixmap, exposedpixmap)
null
73
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksas.endpoint import endpoint_data class DescribeImageListWithBaselineNameRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Sas', '2018-12-03', 'DescribeImageListWithBaselineName') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Pod(self): # String return self.get_query_params().get('Pod') def set_Pod(self, Pod): # String self.add_query_param('Pod', Pod) def get_ClusterName(self): # String return self.get_query_params().get('ClusterName') def set_ClusterName(self, ClusterName): # String self.add_query_param('ClusterName', ClusterName) def get_Criteria(self): # String return self.get_query_params().get('Criteria') def set_Criteria(self, Criteria): # String self.add_query_param('Criteria', Criteria) def get_RepoNamespace(self): # String return self.get_query_params().get('RepoNamespace') def set_RepoNamespace(self, RepoNamespace): # String self.add_query_param('RepoNamespace', RepoNamespace) def get_ImageDigest(self): # String return self.get_query_params().get('ImageDigest') def set_ImageDigest(self, ImageDigest): # String self.add_query_param('ImageDigest', ImageDigest) def get_ScanRanges(self): # RepeatList return self.get_query_params().get('ScanRange') def set_ScanRanges(self, ScanRange): # RepeatList for depth1 in range(len(ScanRange)): self.add_query_param('ScanRange.' + str(depth1 + 1), ScanRange[depth1]) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_CriteriaType(self): # String return self.get_query_params().get('CriteriaType') def set_CriteriaType(self, CriteriaType): # String self.add_query_param('CriteriaType', CriteriaType) def get_Lang(self): # String return self.get_query_params().get('Lang') def set_Lang(self, Lang): # String self.add_query_param('Lang', Lang) def get_Image(self): # String return self.get_query_params().get('Image') def set_Image(self, Image): # String self.add_query_param('Image', Image) def get_CurrentPage(self): # Integer return self.get_query_params().get('CurrentPage') def set_CurrentPage(self, CurrentPage): # Integer self.add_query_param('CurrentPage', CurrentPage) def get_ClusterId(self): # String return self.get_query_params().get('ClusterId') def set_ClusterId(self, ClusterId): # String self.add_query_param('ClusterId', ClusterId) def get_RepoName(self): # String return self.get_query_params().get('RepoName') def set_RepoName(self, RepoName): # String self.add_query_param('RepoName', RepoName) def METHOD_NAME(self): # String return self.get_query_params().get('Namespace') def set_Namespace(self, Namespace): # String self.add_query_param('Namespace', Namespace) def get_BaselineNameKey(self): # String return self.get_query_params().get('BaselineNameKey') def set_BaselineNameKey(self, BaselineNameKey): # String self.add_query_param('BaselineNameKey', BaselineNameKey) def get_RepoInstanceId(self): # String return self.get_query_params().get('RepoInstanceId') def set_RepoInstanceId(self, RepoInstanceId): # String self.add_query_param('RepoInstanceId', RepoInstanceId) def get_ContainerId(self): # String return self.get_query_params().get('ContainerId') def set_ContainerId(self, ContainerId): # String self.add_query_param('ContainerId', ContainerId)
null
74
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause import errno import os import uuid from contextlib import contextmanager from errno import EACCES, ENOENT, EPERM, EROFS from os.path import isfile, join, lexists from shutil import rmtree from stat import ( S_IRGRP, S_IROTH, S_IRUSR, S_IRWXG, S_IRWXO, S_IRWXU, S_IXGRP, S_IXOTH, S_IXUSR, ) from tempfile import gettempdir from unittest.mock import patch import pytest from conda.gateways.disk.update import touch def create_temp_location(): tempdirdir = gettempdir() dirname = str(uuid.uuid4())[:8] return join(tempdirdir, dirname) @contextmanager def tempdir(): prefix = create_temp_location() try: os.makedirs(prefix) yield prefix finally: if lexists(prefix): rmtree(prefix, ignore_errors=False, onerror=_remove_read_only) def _remove_read_only(func, path, exc): excvalue = exc[1] if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: os.chmod(path, S_IRWXU | S_IRWXG | S_IRWXO) func(path) else: pass def _make_read_only(path): os.chmod(path, S_IRUSR | S_IRGRP | S_IROTH) def _can_write_file(test, content): try: with open(test, "w+") as fh: fh.write(content) fh.close() if os.stat(test).st_size == 0.0: return False else: return True except Exception as e: eno = getattr(e, "errono", None) if eno == 13: return False def _try_open(path): try: f = open(path, "a+") except: raise else: f.close() def METHOD_NAME(path): return bool(os.stat(path).st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) def test_make_writable(): from conda.gateways.disk.permissions import make_writable with tempdir() as td: test_path = join(td, "test_path") touch(test_path) assert isfile(test_path) _try_open(test_path) _make_read_only(test_path) pytest.raises((IOError, OSError), _try_open, test_path) make_writable(test_path) _try_open(test_path) assert _can_write_file(test_path, "welcome to the ministry of silly walks") os.remove(test_path) assert not isfile(test_path) def test_make_writable_doesnt_exist(): from conda.gateways.disk.permissions import make_writable with pytest.raises((IOError, OSError)) as exc: make_writable(join("some", "path", "that", "definitely", "doesnt", "exist")) assert exc.value.errno == ENOENT def test_make_writable_dir_EPERM(): import conda.gateways.disk.permissions from conda.gateways.disk.permissions import make_writable with patch.object(conda.gateways.disk.permissions, "chmod") as chmod_mock: chmod_mock.side_effect = IOError(EPERM, "some message", "foo") with tempdir() as td: assert not make_writable(td) def test_make_writable_dir_EACCES(): import conda.gateways.disk.permissions from conda.gateways.disk.permissions import make_writable with patch.object(conda.gateways.disk.permissions, "chmod") as chmod_mock: chmod_mock.side_effect = IOError(EACCES, "some message", "foo") with tempdir() as td: assert not make_writable(td) def test_make_writable_dir_EROFS(): import conda.gateways.disk.permissions from conda.gateways.disk.permissions import make_writable with patch.object(conda.gateways.disk.permissions, "chmod") as chmod_mock: chmod_mock.side_effect = IOError(EROFS, "some message", "foo") with tempdir() as td: assert not make_writable(td) def test_recursive_make_writable(): from conda.gateways.disk.permissions import recursive_make_writable with tempdir() as td: test_path = join(td, "test_path") touch(test_path) assert isfile(test_path) _try_open(test_path) _make_read_only(test_path) pytest.raises((IOError, OSError), _try_open, test_path) recursive_make_writable(test_path) _try_open(test_path) assert _can_write_file(test_path, "welcome to the ministry of silly walks") os.remove(test_path) assert not isfile(test_path) def test_make_executable(): from conda.gateways.disk.permissions import make_executable with tempdir() as td: test_path = join(td, "test_path") touch(test_path) assert isfile(test_path) _try_open(test_path) _make_read_only(test_path) assert not _can_write_file(test_path, "welcome to the ministry of silly walks") assert not METHOD_NAME(test_path) make_executable(test_path)
null
75
""" Copyright (c) 2021, NVIDIA CORPORATION. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import tensorflow as tf import sparse_operation_kit as sok from models import SOKEmbedding import os, glob class EarlyStopper: def __init__(self): self._stop = False def set_stop(self, message): self._stop = True self._stop_reason = message @property def stop_reason(self): return self._stop_reason def should_stop(self): return self._stop class WarmUpAndPolyDecay(tf.keras.optimizers.schedules.LearningRateSchedule): """Learning rate callable for the embeddings. Linear warmup on [0, warmup_steps] then Constant on [warmup_steps, decay_start_steps] And polynomial decay on [decay_start_steps, decay_start_steps + decay_steps]. """ def __init__( self, batch_size: int, decay_exp: float = 2.0, learning_rate: float = 40.0, warmup_steps: int = 8000, decay_steps: int = 12000, decay_start_steps: int = 10000, ): super(WarmUpAndPolyDecay, self).__init__() self.batch_size = batch_size self.decay_exp = decay_exp self.learning_rate = learning_rate self.warmup_steps = warmup_steps self.decay_steps = decay_steps self.decay_start_steps = decay_start_steps def __call__(self, step): decay_exp = self.decay_exp learning_rate = self.learning_rate warmup_steps = self.warmup_steps decay_steps = self.decay_steps decay_start_steps = self.decay_start_steps scal = self.batch_size / 2048 adj_lr = learning_rate * scal if warmup_steps == 0: return adj_lr warmup_lr = step / warmup_steps * adj_lr global_step = tf.cast(step, tf.float32) decay_steps = tf.cast(decay_steps, tf.float32) decay_start_step = tf.cast(decay_start_steps, tf.float32) warmup_lr = tf.cast(warmup_lr, tf.float32) steps_since_decay_start = global_step - decay_start_step already_decayed_steps = tf.minimum(steps_since_decay_start, decay_steps) decay_lr = adj_lr * ((decay_steps - already_decayed_steps) / decay_steps) ** decay_exp decay_lr = tf.maximum(0.0001, decay_lr) lr = tf.where( global_step < warmup_steps, warmup_lr, tf.where( tf.logical_and(decay_steps > 0, global_step > decay_start_step), decay_lr, adj_lr ), ) lr = tf.maximum(0.01, lr) return lr def get_config(self): return { "batch_size": self.batch_size, "decay_exp": self.decay_exp, "learning_rate": self.learning_rate, "warmup_steps": self.warmup_steps, "decay_steps": self.decay_steps, "decay_start_steps": self.decay_start_steps, } def get_optimizer(optimizer=None): if not optimizer: return tf.keras.optimizers.Adam() else: return tf.keras.optimizers.get(optimizer) def get_lr_callable( global_batch_size, decay_exp, learning_rate, warmup_steps, decay_steps, decay_start_steps ): return WarmUpAndPolyDecay( batch_size=global_batch_size, decay_exp=decay_exp, learning_rate=learning_rate, warmup_steps=warmup_steps, decay_steps=decay_steps, decay_start_steps=decay_start_steps, ) class NullScope(object): def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): return False class NullStrategy(object): def scope(self): return NullScope() def run(self, func, *args, **kwargs): return func(*args, **kwargs) def gather(self, tensor, axis): import horovod.tensorflow as hvd return hvd.allgather(tensor) def shard_filenames(file_pattern, num_pipelines, pipeline_id): matching_files = glob.glob(file_pattern) matching_files.sort() nums_per_shard = len(matching_files) // num_pipelines return matching_files[pipeline_id * nums_per_shard : (pipeline_id + 1) * nums_per_shard] def get_distribute_dataset(dataset, strategy, distribute_dataset=True): if isinstance(strategy, NullStrategy) or not distribute_dataset: return dataset() else: return strategy.distribute_datasets_from_function( lambda input_context: dataset(input_context), options=tf.distribute.InputOptions() ) def split_embedding_variables_from_others(model): if isinstance(model.embedding_layer, SOKEmbedding): return sok.split_embedding_variable_from_others(model.trainable_variables) else: dense_vars = [] for layer in model.layers: if layer != model.embedding_layer: dense_vars.extend(layer.trainable_variables) return model.embedding_layer.trainable_variables, dense_vars def all_reduce(tensors, combiner="sum", comm_options=None): if tf.distribute.has_strategy(): replica_ctx = tf.distribute.get_replica_context() return replica_ctx.all_reduce(combiner, tensors, options=comm_options) else: import horovod.tensorflow as hvd return [hvd.allreduce(tensor) for tensor in tensors] def all_gather(tensors, axis=0, comm_options=None): if tf.distribute.has_strategy(): replica_ctx = tf.distribute.get_replica_context() return replica_ctx.all_gather(tensors, axis=axis, options=comm_options) else: import horovod.tensorflow as hvd return [hvd.allgather(tensor) for tensor in tensors] def METHOD_NAME(optimizer, variables, grads, using_sok, aggregate_gradients=False): if using_sok: with sok.OptimizerScope(variables): optimizer.METHOD_NAME(zip(grads, variables), experimental_aggregate_gradients=False) else: optimizer.METHOD_NAME( zip(grads, variables), experimental_aggregate_gradients=aggregate_gradients ) def broadcast_variables(variables): if tf.distribute.has_strategy(): return else: import horovod.tensorflow as hvd hvd.broadcast_variables(variables, root_rank=0) def show_logs(logs, strategy, elapsed_time, steps_sec, metrics_threshold, stopper): for key, value in logs.items(): if hasattr(value, "values"): logs[key] = value.values[0] if hasattr(value, "numpy"): logs[key] = value.numpy() def no_print(): return def print_logs(): print("-" * 23, logs["global_step"], "-" * 23) del logs["global_step"] for key, value in logs.items(): print(f"{key}: {logs[key]}") print("elapsed_time:", elapsed_time) print("steps/sec:", steps_sec) print("-" * 50) if isinstance(strategy, NullStrategy): import horovod.tensorflow as hvd if hvd.local_rank() != 0: no_print() else: print_logs() elif os.getenv("OMPI_COMM_WORLD_RANK"): rank = os.getenv("OMPI_COMM_WORLD_RANK") if int(rank) != 0: no_print() else: print_logs() else: print_logs() for key, value in metrics_threshold.items(): if logs[key] >= value: stopper.set_stop( f"Metric {key}: {logs[key]} meets its " f"threshold {value}, stop training." ) break
null
76
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkmse.endpoint import endpoint_data class UpdateCircuitBreakerRuleRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'mse', '2019-05-31', 'UpdateCircuitBreakerRule','mse') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Threshold(self): # Float return self.get_query_params().get('Threshold') def set_Threshold(self, Threshold): # Float self.add_query_param('Threshold', Threshold) def METHOD_NAME(self): # Integer return self.get_query_params().get('RetryTimeoutMs') def set_RetryTimeoutMs(self, RetryTimeoutMs): # Integer self.add_query_param('RetryTimeoutMs', RetryTimeoutMs) def get_AppName(self): # String return self.get_query_params().get('AppName') def set_AppName(self, AppName): # String self.add_query_param('AppName', AppName) def get_Enable(self): # Boolean return self.get_query_params().get('Enable') def set_Enable(self, Enable): # Boolean self.add_query_param('Enable', Enable) def get_MinRequestAmount(self): # Integer return self.get_query_params().get('MinRequestAmount') def set_MinRequestAmount(self, MinRequestAmount): # Integer self.add_query_param('MinRequestAmount', MinRequestAmount) def get_MaxAllowedRtMs(self): # Integer return self.get_query_params().get('MaxAllowedRtMs') def set_MaxAllowedRtMs(self, MaxAllowedRtMs): # Integer self.add_query_param('MaxAllowedRtMs', MaxAllowedRtMs) def get_RuleId(self): # Long return self.get_query_params().get('RuleId') def set_RuleId(self, RuleId): # Long self.add_query_param('RuleId', RuleId) def get_HalfOpenBaseAmountPerStep(self): # Integer return self.get_query_params().get('HalfOpenBaseAmountPerStep') def set_HalfOpenBaseAmountPerStep(self, HalfOpenBaseAmountPerStep): # Integer self.add_query_param('HalfOpenBaseAmountPerStep', HalfOpenBaseAmountPerStep) def get_StatIntervalMs(self): # Integer return self.get_query_params().get('StatIntervalMs') def set_StatIntervalMs(self, StatIntervalMs): # Integer self.add_query_param('StatIntervalMs', StatIntervalMs) def get_AppId(self): # String return self.get_query_params().get('AppId') def set_AppId(self, AppId): # String self.add_query_param('AppId', AppId) def get_Namespace(self): # String return self.get_query_params().get('Namespace') def set_Namespace(self, Namespace): # String self.add_query_param('Namespace', Namespace) def get_HalfOpenRecoveryStepNum(self): # Integer return self.get_query_params().get('HalfOpenRecoveryStepNum') def set_HalfOpenRecoveryStepNum(self, HalfOpenRecoveryStepNum): # Integer self.add_query_param('HalfOpenRecoveryStepNum', HalfOpenRecoveryStepNum) def get_AcceptLanguage(self): # String return self.get_query_params().get('AcceptLanguage') def set_AcceptLanguage(self, AcceptLanguage): # String self.add_query_param('AcceptLanguage', AcceptLanguage) def get_Strategy(self): # Integer return self.get_query_params().get('Strategy') def set_Strategy(self, Strategy): # Integer self.add_query_param('Strategy', Strategy)
null
77
from __future__ import print_function import IMP import IMP.test import IMP.core import IMP.algebra import IMP.atom linvelkey = IMP.FloatsKey('linvel') class Tests(IMP.test.TestCase): """Test molecular dynamics optimizer states""" def setup_particles(self, coords, copies=1): m = IMP.Model() ps = [] for i in range(copies): for c in coords: p = IMP.Particle(m) x = IMP.core.XYZ.setup_particle(p, c[0]) x.set_coordinates_are_optimized(True) IMP.atom.Mass.setup_particle(p, 1.0) p.add_attribute(linvelkey, c[1]) ps.append(p) return m, ps def test_remove_rigid_translation(self): """Ensure that rigid translation is removed""" m, ps = self.setup_particles([[IMP.algebra.Vector3D(0, 0, 0), IMP.algebra.Vector3D(10, 0, 0)], [IMP.algebra.Vector3D(10, 0, 0), IMP.algebra.Vector3D(-20, 0, 0)]]) s = IMP.atom.RemoveRigidMotionOptimizerState(m, ps) s.set_period(1) s.remove_rigid_motion() self.assertEqual(ps[0].get_value(linvelkey)[0], 15.) self.assertEqual(ps[1].get_value(linvelkey)[0], -15.) for p in ps: self.assertEqual(p.get_value(linvelkey)[1], 0.) self.assertEqual(p.get_value(linvelkey)[2], 0.) def METHOD_NAME(self): """Ensure that rigid rotation is removed""" # Create 4 points at the vertices of a tetrahedron centered at origin xs = [IMP.algebra.Vector3D(x) for x in [(-10, -10, -10), (10, 10, 10), (10, -10, -10), (-10, 10, 10)]] # Add velocities that would spin it about an axis through the origin # that it not aligned with the x,y,or z axes torque = IMP.algebra.Vector3D(5, 8, 10) vs = [IMP.algebra.get_vector_product(x, torque) for x in xs] m, ps = self.setup_particles(zip(xs, vs)) s = IMP.atom.RemoveRigidMotionOptimizerState(m, ps) s.set_period(1) s.remove_rigid_motion() # We started with no net linear momentum, so removing the angular # momentum should cause the system to become stationary for p in ps: vx, vy, vz = p.get_value(linvelkey) self.assertAlmostEqual(vx, 0., delta=1e-6) self.assertAlmostEqual(vy, 0., delta=1e-6) self.assertAlmostEqual(vz, 0., delta=1e-6) def test_remove_rigid_one_particle(self): """Ensure that rigid removal works with a 1-particle system""" m, ps = self.setup_particles([[IMP.algebra.Vector3D(0, 0, 0), IMP.algebra.Vector3D(10, 0, 0)]]) s = IMP.atom.RemoveRigidMotionOptimizerState(m, ps) s.set_period(1) self.assertEqual(s.get_period(), 1) s.remove_rigid_motion() vx, vy, vz = ps[0].get_value(linvelkey) self.assertEqual(vx, 0.) self.assertEqual(vy, 0.) self.assertEqual(vz, 0.) def test_berendsen_thermostat(self): """Test Berendsen thermostat""" # With a shorter coupling time, fewer steps should be needed # to reach the set temperature for (coupling, steps) in [(8.0, 16), (6.0, 10)]: m, ps = self.setup_particles([[IMP.algebra.Vector3D(0, 0, 0), IMP.algebra.Vector3D(0.1, 0, 0)]]) scaler = IMP.atom.BerendsenThermostatOptimizerState( ps, 298.0, coupling) md = IMP.atom.MolecularDynamics(m) md.set_maximum_time_step(4.0) md.set_scoring_function([]) md.optimize(0) # ick md.add_optimizer_state(scaler) ts = [] for i in range(20): ts.append(md.get_kinetic_temperature(md.get_kinetic_energy())) scaler.rescale_velocities() # Temperature should decrease from start to set temp print(ts) self.assertAlmostEqual(ts[0], 4009.0, delta=0.2) self.assertGreater(ts[steps - 1], 298.1) # Make sure that once set temperature is reached, it is maintained for i in range(steps, 20): self.assertAlmostEqual(ts[i], 298.0, delta=0.1) def test_langevin_thermostat(self): """Test Langevin thermostat""" # Need many particles due to random forces m, ps = self.setup_particles([[IMP.algebra.Vector3D(0, 0, 0), IMP.algebra.Vector3D(0.1, 0, 0)]], copies=50) scaler = IMP.atom.LangevinThermostatOptimizerState( m, ps, 298.0, 0.1) md = IMP.atom.MolecularDynamics(m) md.set_maximum_time_step(4.0) md.add_optimizer_state(scaler) md.set_scoring_function([]) md.optimize(0) ts = [] for i in range(140): ts.append(md.get_kinetic_temperature(md.get_kinetic_energy())) scaler.rescale_velocities() # After a while, temperature should have stabilized at set value equilibrium_temp = sum(ts[40:140]) / 100.0 self.assertAlmostEqual(equilibrium_temp, 298.0, delta=20.0) if __name__ == '__main__': IMP.test.main()
null
78
from argparse import ArgumentParser, Namespace from pathlib import Path from textwrap import dedent from pyrokinetics import Pyro description = "Convert a gyrokinetics input file to a different code." def add_arguments(parser: ArgumentParser) -> None: parser.add_argument( "target", type=str, help=dedent( f"""\ The target gyrokinetics code. Options include {', '.join(Pyro().supported_gk_inputs)}. """ ), ) parser.add_argument( "input_file", type=Path, help="The gyrokinetics config file you wish to convert.", ) parser.add_argument( "--input_type", type=str, help="The code type of the input file. If not provided, this will be inferred.", ) parser.add_argument( "--geometry", "-g", type=str, help=dedent( """\ The type of flux surface geometry to convert to. Options currently include Miller (all), MillerTurnbull (GENE) and MXH (CGYRO, TGLF). """ ), ) parser.add_argument( "--equilibrium", "--eq", "-e", type=Path, help=dedent( f"""\ Path to a plasma equilibrium file, which is used to overwrite the flux surface in 'input_file'. Users should also provide 'psi' to select which flux surface to use from the equilibrium. The supported equilibrium types are {', '.join(Pyro().supported_equilibrium_types)}. """ ), ) parser.add_argument( "--equilibrium_type", "--eq_type", type=str, help="The type of equilibrium file. If not provided, this is inferred.", ) parser.add_argument( "--kinetics", "-k", type=Path, help=dedent( f"""\ Path to a plasma kinetics file, which is used to overwrite the local species data in 'input_file'. Users should also provide 'psi' and 'a_minor' to select which flux surface to use, or provide 'psi' and 'equilibrium'. The supported kinetcs types are {', '.join(Pyro().supported_kinetics_types)}. """ ), ) parser.add_argument( "--kinetics_type", "--k_type", type=str, help="The type of kinetics file. If not provided, this is inferred.", ) parser.add_argument( "--psi", "-p", type=float, help=dedent( """\ The normalised poloidal flux function, used to index which flux surface to draw equilibrium/kinetics data from. Should be in the range [0,1], with 0 being the magnetic axis, and 1 being the last closed flux surface. """ ), ) parser.add_argument( "--a_minor", "-a", type=float, help=dedent( """\ The width of the last closed flux surface, in meters. Used to select a flux surface when providing kinetics data but no equilibrium. Otherwise, this argument is ignored. """ ), ) parser.add_argument( "--output", "-o", type=Path, help="Name of the new gyrokinetics config file.", ) parser.add_argument( "--template", "-t", type=Path, help="Template file to use for the new gyrokinetics config file.", ) def METHOD_NAME(args: Namespace) -> None: # Handle illegal combinations of optional args if args.equilibrium is not None and args.psi is None: raise ValueError("If providing an equilibrium file, must also provide psi") if args.kinetics is not None and args.psi is None: raise ValueError("If providing a kinetics file, must also provide psi") if args.kinetics is not None and args.equilibrium is None and args.a_minor is None: raise ValueError( "If providing a kinetics file without an equilibrium, " "must also provide a_minor" ) # Create a pyro object with just gk info pyro = Pyro(gk_file=args.input_file, gk_code=args.input_type) # Modify local geometry if args.equilibrium is not None: pyro.load_global_eq(eq_file=args.equilibrium, eq_type=args.equilibrium_type) pyro.load_local_geometry(psi_n=args.psi) # Modify local species if args.kinetics is not None: pyro.load_global_kinetics( kinetics_file=args.kinetics, kinetics_type=args.kinetics_type, ) pyro.load_local_species( psi_n=args.psi, a_minor=(args.a_minor if args.equilibrium is None else None), ) # Convert local geometry type if args.geometry is not None: pyro.switch_local_geometry(local_geometry=args.geometry) # Convert and write filename = f"input.{args.target}".lower() if args.output is None else args.output pyro.write_gk_file(filename, gk_code=args.target, template_file=args.template)
null
79
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkga.endpoint import endpoint_data class CreateEndpointGroupRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ga', '2019-11-20', 'CreateEndpointGroup','gaplus') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_PortOverridess(self): # RepeatList return self.get_query_params().get('PortOverrides') def set_PortOverridess(self, PortOverrides): # RepeatList for depth1 in range(len(PortOverrides)): if PortOverrides[depth1].get('ListenerPort') is not None: self.add_query_param('PortOverrides.' + str(depth1 + 1) + '.ListenerPort', PortOverrides[depth1].get('ListenerPort')) if PortOverrides[depth1].get('EndpointPort') is not None: self.add_query_param('PortOverrides.' + str(depth1 + 1) + '.EndpointPort', PortOverrides[depth1].get('EndpointPort')) def get_HealthCheckEnabled(self): # Boolean return self.get_query_params().get('HealthCheckEnabled') def set_HealthCheckEnabled(self, HealthCheckEnabled): # Boolean self.add_query_param('HealthCheckEnabled', HealthCheckEnabled) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_HealthCheckIntervalSeconds(self): # Integer return self.get_query_params().get('HealthCheckIntervalSeconds') def METHOD_NAME(self, HealthCheckIntervalSeconds): # Integer self.add_query_param('HealthCheckIntervalSeconds', HealthCheckIntervalSeconds) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_HealthCheckProtocol(self): # String return self.get_query_params().get('HealthCheckProtocol') def set_HealthCheckProtocol(self, HealthCheckProtocol): # String self.add_query_param('HealthCheckProtocol', HealthCheckProtocol) def get_EndpointRequestProtocol(self): # String return self.get_query_params().get('EndpointRequestProtocol') def set_EndpointRequestProtocol(self, EndpointRequestProtocol): # String self.add_query_param('EndpointRequestProtocol', EndpointRequestProtocol) def get_ListenerId(self): # String return self.get_query_params().get('ListenerId') def set_ListenerId(self, ListenerId): # String self.add_query_param('ListenerId', ListenerId) def get_HealthCheckPath(self): # String return self.get_query_params().get('HealthCheckPath') def set_HealthCheckPath(self, HealthCheckPath): # String self.add_query_param('HealthCheckPath', HealthCheckPath) def get_EndpointConfigurationss(self): # RepeatList return self.get_query_params().get('EndpointConfigurations') def set_EndpointConfigurationss(self, EndpointConfigurations): # RepeatList for depth1 in range(len(EndpointConfigurations)): if EndpointConfigurations[depth1].get('Type') is not None: self.add_query_param('EndpointConfigurations.' + str(depth1 + 1) + '.Type', EndpointConfigurations[depth1].get('Type')) if EndpointConfigurations[depth1].get('EnableClientIPPreservation') is not None: self.add_query_param('EndpointConfigurations.' + str(depth1 + 1) + '.EnableClientIPPreservation', EndpointConfigurations[depth1].get('EnableClientIPPreservation')) if EndpointConfigurations[depth1].get('Weight') is not None: self.add_query_param('EndpointConfigurations.' + str(depth1 + 1) + '.Weight', EndpointConfigurations[depth1].get('Weight')) if EndpointConfigurations[depth1].get('EnableProxyProtocol') is not None: self.add_query_param('EndpointConfigurations.' + str(depth1 + 1) + '.EnableProxyProtocol', EndpointConfigurations[depth1].get('EnableProxyProtocol')) if EndpointConfigurations[depth1].get('Endpoint') is not None: self.add_query_param('EndpointConfigurations.' + str(depth1 + 1) + '.Endpoint', EndpointConfigurations[depth1].get('Endpoint')) def get_EndpointGroupType(self): # String return self.get_query_params().get('EndpointGroupType') def set_EndpointGroupType(self, EndpointGroupType): # String self.add_query_param('EndpointGroupType', EndpointGroupType) def get_AcceleratorId(self): # String return self.get_query_params().get('AcceleratorId') def set_AcceleratorId(self, AcceleratorId): # String self.add_query_param('AcceleratorId', AcceleratorId) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) def get_TrafficPercentage(self): # Integer return self.get_query_params().get('TrafficPercentage') def set_TrafficPercentage(self, TrafficPercentage): # Integer self.add_query_param('TrafficPercentage', TrafficPercentage) def get_HealthCheckPort(self): # Integer return self.get_query_params().get('HealthCheckPort') def set_HealthCheckPort(self, HealthCheckPort): # Integer self.add_query_param('HealthCheckPort', HealthCheckPort) def get_ThresholdCount(self): # Integer return self.get_query_params().get('ThresholdCount') def set_ThresholdCount(self, ThresholdCount): # Integer self.add_query_param('ThresholdCount', ThresholdCount) def get_EndpointGroupRegion(self): # String return self.get_query_params().get('EndpointGroupRegion') def set_EndpointGroupRegion(self, EndpointGroupRegion): # String self.add_query_param('EndpointGroupRegion', EndpointGroupRegion) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name)
null
80
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class GetTaskListFilterRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'devops-rdc', '2020-03-03', 'GetTaskListFilter') self.set_method('POST') def get_InvolveMembers(self): # String return self.get_body_params().get('InvolveMembers') def set_InvolveMembers(self, InvolveMembers): # String self.add_body_params('InvolveMembers', InvolveMembers) def get_ExecutorId(self): # String return self.get_body_params().get('ExecutorId') def set_ExecutorId(self, ExecutorId): # String self.add_body_params('ExecutorId', ExecutorId) def get_OrderCondition(self): # String return self.get_body_params().get('OrderCondition') def set_OrderCondition(self, OrderCondition): # String self.add_body_params('OrderCondition', OrderCondition) def get_SprintId(self): # String return self.get_body_params().get('SprintId') def set_SprintId(self, SprintId): # String self.add_body_params('SprintId', SprintId) def get_Extra(self): # String return self.get_body_params().get('Extra') def set_Extra(self, Extra): # String self.add_body_params('Extra', Extra) def get_PageSize(self): # Integer return self.get_body_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_body_params('PageSize', PageSize) def get_ScenarioFieldConfigId(self): # String return self.get_body_params().get('ScenarioFieldConfigId') def set_ScenarioFieldConfigId(self, ScenarioFieldConfigId): # String self.add_body_params('ScenarioFieldConfigId', ScenarioFieldConfigId) def get_IsDone(self): # Boolean return self.get_body_params().get('IsDone') def set_IsDone(self, IsDone): # Boolean self.add_body_params('IsDone', IsDone) def get_ObjectType(self): # String return self.get_body_params().get('ObjectType') def set_ObjectType(self, ObjectType): # String self.add_body_params('ObjectType', ObjectType) def get_ProjectId(self): # String return self.get_body_params().get('ProjectId') def set_ProjectId(self, ProjectId): # String self.add_body_params('ProjectId', ProjectId) def get_PageToken(self): # String return self.get_body_params().get('PageToken') def set_PageToken(self, PageToken): # String self.add_body_params('PageToken', PageToken) def METHOD_NAME(self): # String return self.get_body_params().get('Order') def set_Order(self, Order): # String self.add_body_params('Order', Order) def get_TagId(self): # String return self.get_body_params().get('TagId') def set_TagId(self, TagId): # String self.add_body_params('TagId', TagId) def get_TaskFlowStatusId(self): # String return self.get_body_params().get('TaskFlowStatusId') def set_TaskFlowStatusId(self, TaskFlowStatusId): # String self.add_body_params('TaskFlowStatusId', TaskFlowStatusId) def get_DueDateStart(self): # String return self.get_body_params().get('DueDateStart') def set_DueDateStart(self, DueDateStart): # String self.add_body_params('DueDateStart', DueDateStart) def get_CreatorId(self): # String return self.get_body_params().get('CreatorId') def set_CreatorId(self, CreatorId): # String self.add_body_params('CreatorId', CreatorId) def get_Priority(self): # String return self.get_body_params().get('Priority') def set_Priority(self, Priority): # String self.add_body_params('Priority', Priority) def get_DueDateEnd(self): # String return self.get_body_params().get('DueDateEnd') def set_DueDateEnd(self, DueDateEnd): # String self.add_body_params('DueDateEnd', DueDateEnd) def get_OrgId(self): # String return self.get_body_params().get('OrgId') def set_OrgId(self, OrgId): # String self.add_body_params('OrgId', OrgId) def get_Name(self): # String return self.get_body_params().get('Name') def set_Name(self, Name): # String self.add_body_params('Name', Name)
null
81
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkdataworks_public.endpoint import endpoint_data class CreateQualityRuleRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'dataworks-public', '2020-05-18', 'CreateQualityRule') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Trend(self): # String return self.get_body_params().get('Trend') def set_Trend(self, Trend): # String self.add_body_params('Trend', Trend) def get_BlockType(self): # Integer return self.get_body_params().get('BlockType') def set_BlockType(self, BlockType): # Integer self.add_body_params('BlockType', BlockType) def get_PropertyType(self): # String return self.get_body_params().get('PropertyType') def set_PropertyType(self, PropertyType): # String self.add_body_params('PropertyType', PropertyType) def get_EntityId(self): # Long return self.get_body_params().get('EntityId') def set_EntityId(self, EntityId): # Long self.add_body_params('EntityId', EntityId) def get_RuleName(self): # String return self.get_body_params().get('RuleName') def set_RuleName(self, RuleName): # String self.add_body_params('RuleName', RuleName) def get_Checker(self): # Integer return self.get_body_params().get('Checker') def set_Checker(self, Checker): # Integer self.add_body_params('Checker', Checker) def get_Operator(self): # String return self.get_body_params().get('Operator') def set_Operator(self, Operator): # String self.add_body_params('Operator', Operator) def get_Property(self): # String return self.get_body_params().get('Property') def set_Property(self, Property): # String self.add_body_params('Property', Property) def get_WarningThreshold(self): # String return self.get_body_params().get('WarningThreshold') def set_WarningThreshold(self, WarningThreshold): # String self.add_body_params('WarningThreshold', WarningThreshold) def get_ProjectId(self): # Long return self.get_body_params().get('ProjectId') def set_ProjectId(self, ProjectId): # Long self.add_body_params('ProjectId', ProjectId) def get_MethodName(self): # String return self.get_body_params().get('MethodName') def set_MethodName(self, MethodName): # String self.add_body_params('MethodName', MethodName) def get_ProjectName(self): # String return self.get_body_params().get('ProjectName') def set_ProjectName(self, ProjectName): # String self.add_body_params('ProjectName', ProjectName) def get_RuleType(self): # Integer return self.get_body_params().get('RuleType') def set_RuleType(self, RuleType): # Integer self.add_body_params('RuleType', RuleType) def get_TemplateId(self): # Integer return self.get_body_params().get('TemplateId') def set_TemplateId(self, TemplateId): # Integer self.add_body_params('TemplateId', TemplateId) def get_ExpectValue(self): # String return self.get_body_params().get('ExpectValue') def METHOD_NAME(self, ExpectValue): # String self.add_body_params('ExpectValue', ExpectValue) def get_WhereCondition(self): # String return self.get_body_params().get('WhereCondition') def set_WhereCondition(self, WhereCondition): # String self.add_body_params('WhereCondition', WhereCondition) def get_CriticalThreshold(self): # String return self.get_body_params().get('CriticalThreshold') def set_CriticalThreshold(self, CriticalThreshold): # String self.add_body_params('CriticalThreshold', CriticalThreshold) def get_Comment(self): # String return self.get_body_params().get('Comment') def set_Comment(self, Comment): # String self.add_body_params('Comment', Comment) def get_PredictType(self): # Integer return self.get_body_params().get('PredictType') def set_PredictType(self, PredictType): # Integer self.add_body_params('PredictType', PredictType)
null
82
import datetime import pytest from dateutil.parser import parse from pages.experiment_timeline_and_population import TimelineAndPopulationPage @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_proposed_start_date_fills_correctly(selenium, base_url, fill_overview): """Test proposed start date fills.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.proposed_start_date == "" date = f"{datetime.datetime.now()}" new_date = parse(date) today = f"{new_date.date()}" timeline_pop_form.proposed_start_date = today assert timeline_pop_form.proposed_start_date == today @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def METHOD_NAME( selenium, base_url, fill_overview ): """Test proposed experiment duration fills.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.proposed_experiment_duration == "" duration = "25" timeline_pop_form.proposed_experiment_duration = duration assert timeline_pop_form.proposed_experiment_duration == duration @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_proposed_enrollment_duration_updates_correctly( selenium, base_url, fill_overview ): """Test proposed enrolled duration updates.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.proposed_enrollment_duration == "" duration = "50" timeline_pop_form.proposed_enrollment_duration = duration assert timeline_pop_form.proposed_enrollment_duration == duration @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_population_percentage_updates_correctly(selenium, base_url, fill_overview): """Test Population percentage updates.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.population_percentage == "0.0000" percentage = "37.0" timeline_pop_form.population_percentage = percentage assert timeline_pop_form.population_percentage == percentage @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_firefox_channel_updates_correctly(selenium, base_url, fill_overview): """Test selecting a Firefox Channel.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.firefox_channel == "Firefox Channel" channel = "Nightly" timeline_pop_form.firefox_channel = channel assert timeline_pop_form.firefox_channel == channel @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_firefox_min_version_updates_correctly(selenium, base_url, fill_overview): """Test setting a Firefox min version.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.firefox_min_version == "Versions" version = "75.0" timeline_pop_form.firefox_min_version = version assert timeline_pop_form.firefox_min_version == version @pytest.mark.skip(reason="superceded by e2e tests") @pytest.mark.nondestructive def test_firefox_max_version_updates_correctly(selenium, base_url, fill_overview): """Test setting a Firefox max version.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.firefox_max_version == "Versions" version = "78.0" timeline_pop_form.firefox_max_version = version assert timeline_pop_form.firefox_max_version == version @pytest.mark.skip @pytest.mark.nondestructive def test_platform_selection_updates_correctly(selenium, base_url, fill_overview): """Test platform selection updates.""" timeline_pop_form = TimelineAndPopulationPage( selenium, base_url, experiment_url=f"{fill_overview.url}" ).open() assert timeline_pop_form.platform == "All Platforms" channel = "All Linux" timeline_pop_form.platform = channel assert timeline_pop_form.platform == channel
null
83
""" This type stub file was generated by pyright. """ import threading from collections import deque from time import time from typing import Any from sentry_sdk._types import MYPY """ A fork of Python 3.6's stdlib queue with Lock swapped out for RLock to avoid a deadlock while garbage collecting. See https://codewithoutrules.com/2017/08/16/concurrency-python/ https://bugs.python.org/issue14976 https://github.com/sqlalchemy/sqlalchemy/blob/4eb747b61f0c1b1c25bdee3856d7195d10a0c227/lib/sqlalchemy/queue.py#L1 We also vendor the code to evade eventlet's broken monkeypatching, see https://github.com/getsentry/sentry-python/pull/484 """ if MYPY: ... __all__ = ["EmptyError", "FullError", "Queue"] class EmptyError(Exception): "Exception raised by Queue.get(block=0)/get_nowait()." ... class FullError(Exception): "Exception raised by Queue.put(block=0)/put_nowait()." ... class Queue: """Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. """ def __init__(self, maxsize=...) -> None: ... def task_done(self): # -> None: """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. """ ... def join(self): # -> None: """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. """ ... def METHOD_NAME(self): # -> int: """Return the approximate size of the queue (not reliable!).""" ... def empty(self): # -> bool: """Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. """ ... def full(self): # -> bool: """Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used. """ ... def put(self, item, block=..., timeout=...): # -> None: """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the FullError exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the FullError exception ('timeout' is ignored in that case). """ ... def get(self, block=..., timeout=...): # -> Any: """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the EmptyError exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the EmptyError exception ('timeout' is ignored in that case). """ ... def put_nowait(self, item): # -> None: """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the FullError exception. """ ... def get_nowait(self): # -> Any: """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the EmptyError exception. """ ...
null
84
from django.contrib.auth.models import User from django.utils import timezone import pytest from dashboard.models import Passport, PassportStamp from passport_score.gr15_providers import providers from passport_score.models import GR15TrustScore from passport_score.utils import handle_submitted_passport, load_passport_stamps from test_plus.test import TestCase NUM_USERS = 2 CURRENT_PASSWORD = "mimamamemima" dids = [f"did:for:user:{i}" for i in range(NUM_USERS)] passports = [ {"stamps": [{"provider": "Provider1"}]}, {"stamps": [{"provider": "Provider2"}]}, ] @pytest.mark.django_db class TestHandleSubmittedPassport(TestCase): """Test loading stamps for APU calculation.""" def setUp(self): self.users = [ User.objects.create(password=CURRENT_PASSWORD, username=f"user_{i}") for i in range(NUM_USERS) ] self.passports = [ Passport.objects.create( user=user, did=user.username, passport={"type": user.username} ) for user in self.users ] self.user1 = self.users[0] self.user2 = self.users[1] self.did1 = dids[0] self.did2 = dids[1] self.passport1 = passports[0] self.passport2 = passports[1] def test_handle_valid_passport(self): """Test handling 2 valid submissions""" handle_submitted_passport(self.user1.id, self.did1, self.passport1) # Both passport submissions are correct we expect no entry in GR15TrustScore for now assert GR15TrustScore.objects.count() == 0 assert Passport.objects.count() == 2 assert Passport.objects.filter(user_id=self.user1.id).count() == 1 assert Passport.objects.filter(user_id=self.user2.id).count() == 1 def test_handle_duplicate_did(self): """ Test handling 2 submissions with the same did - the first user is marked as sybil. - the first users passport is deleted (including all his stamps) - the first user gets: - is_sybil -> True - last_apu_score -> 0 - trust_bonus -> 0 """ handle_submitted_passport(self.user1.id, self.did1, self.passport1) passport1 = Passport.objects.get(user_id=self.user1.id) for provider in ["Google", "Facebook", "POAP"]: PassportStamp( passport=passport1, user=passport1.user, stamp_id=f"stamp_{passport1.user_id}_{provider}", stamp_provider=provider, ).save() # Ensure stamps where saved assert PassportStamp.objects.filter(user_id=self.user1.id).count() == 3 handle_submitted_passport(self.user2.id, self.did1, self.passport1) # Because of duplicate did, we expect user_1 user to have been flagged as sybil assert GR15TrustScore.objects.count() == 1 user1_gr15_trust_score = GR15TrustScore.objects.get(user_id=self.user1.id) assert ( user1_gr15_trust_score.notes[0]["note"] == f"Marking as sybil. Duplicate did: {self.did1}" ) assert user1_gr15_trust_score.is_sybil assert user1_gr15_trust_score.last_apu_score == 0 assert user1_gr15_trust_score.trust_bonus == 0 # Also check that the 1st users passport was deleted assert Passport.objects.count() == 1 assert Passport.objects.filter(user_id=self.user1.id).count() == 0 assert PassportStamp.objects.filter(user_id=self.user1.id).count() == 0 assert Passport.objects.filter(user_id=self.user2.id).count() == 1 def METHOD_NAME(self): """ Test te case when user changes did: - first passport should be deleted - all stamps for 1st passport should be deleted """ handle_submitted_passport(self.user1.id, self.did1, self.passport1) passport1 = Passport.objects.get(user_id=self.user1.id) for provider in ["Google", "Facebook", "POAP"]: PassportStamp( passport=passport1, user=passport1.user, stamp_id=f"stamp_{passport1.user_id}_{provider}", stamp_provider=provider, ).save() # Ensure passport & stamps where saved assert PassportStamp.objects.filter(user_id=self.user1.id).count() == 3 assert Passport.objects.filter(did=self.did1).count() == 1 # Now change the did for the user handle_submitted_passport(self.user1.id, self.did2, self.passport2) # First passport should have been deleted ... assert Passport.objects.filter(pk=passport1.pk).count() == 0 # Stamps should have been deleted assert PassportStamp.objects.count() == 0 # Ensure new passport was saved assert Passport.objects.filter(did=self.did2).count() == 1 # Both passport submissions are correct we expect no entry in GR15TrustScore for now assert GR15TrustScore.objects.count() == 0
null
85
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class UpdatePrivateAccessPolicyRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'csas', '2023-01-20', 'UpdatePrivateAccessPolicy') self.set_method('POST') def get_Description(self): # String return self.get_body_params().get('Description') def set_Description(self, Description): # String self.add_body_params('Description', Description) def get_PolicyId(self): # String return self.get_body_params().get('PolicyId') def set_PolicyId(self, PolicyId): # String self.add_body_params('PolicyId', PolicyId) def get_CustomUserAttributes(self): # Array return self.get_body_params().get('CustomUserAttributes') def set_CustomUserAttributes(self, CustomUserAttributes): # Array for index1, value1 in enumerate(CustomUserAttributes): if value1.get('UserGroupType') is not None: self.add_body_params('CustomUserAttributes.' + str(index1 + 1) + '.UserGroupType', value1.get('UserGroupType')) if value1.get('IdpId') is not None: self.add_body_params('CustomUserAttributes.' + str(index1 + 1) + '.IdpId', value1.get('IdpId')) if value1.get('Value') is not None: self.add_body_params('CustomUserAttributes.' + str(index1 + 1) + '.Value', value1.get('Value')) if value1.get('Relation') is not None: self.add_body_params('CustomUserAttributes.' + str(index1 + 1) + '.Relation', value1.get('Relation')) def get_TagIds(self): # Array return self.get_body_params().get('TagIds') def set_TagIds(self, TagIds): # Array for index1, value1 in enumerate(TagIds): self.add_body_params('TagIds.' + str(index1 + 1), value1) def get_UserGroupIds(self): # Array return self.get_body_params().get('UserGroupIds') def set_UserGroupIds(self, UserGroupIds): # Array for index1, value1 in enumerate(UserGroupIds): self.add_body_params('UserGroupIds.' + str(index1 + 1), value1) def get_PolicyAction(self): # String return self.get_body_params().get('PolicyAction') def set_PolicyAction(self, PolicyAction): # String self.add_body_params('PolicyAction', PolicyAction) def get_Priority(self): # Integer return self.get_body_params().get('Priority') def set_Priority(self, Priority): # Integer self.add_body_params('Priority', Priority) def get_ApplicationIds(self): # Array return self.get_body_params().get('ApplicationIds') def METHOD_NAME(self, ApplicationIds): # Array for index1, value1 in enumerate(ApplicationIds): self.add_body_params('ApplicationIds.' + str(index1 + 1), value1) def get_UserGroupMode(self): # String return self.get_body_params().get('UserGroupMode') def set_UserGroupMode(self, UserGroupMode): # String self.add_body_params('UserGroupMode', UserGroupMode) def get_ModifyType(self): # String return self.get_body_params().get('ModifyType') def set_ModifyType(self, ModifyType): # String self.add_body_params('ModifyType', ModifyType) def get_ApplicationType(self): # String return self.get_body_params().get('ApplicationType') def set_ApplicationType(self, ApplicationType): # String self.add_body_params('ApplicationType', ApplicationType) def get_Status(self): # String return self.get_body_params().get('Status') def set_Status(self, Status): # String self.add_body_params('Status', Status)
null
86
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkclickhouse.endpoint import endpoint_data class ModifyRDSToClickhouseDbRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'clickhouse', '2019-11-11', 'ModifyRDSToClickhouseDb') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_RdsVpcId(self): # String return self.get_query_params().get('RdsVpcId') def set_RdsVpcId(self, RdsVpcId): # String self.add_query_param('RdsVpcId', RdsVpcId) def get_CkPassword(self): # String return self.get_query_params().get('CkPassword') def set_CkPassword(self, CkPassword): # String self.add_query_param('CkPassword', CkPassword) def get_RdsSynTables(self): # String return self.get_query_params().get('RdsSynTables') def set_RdsSynTables(self, RdsSynTables): # String self.add_query_param('RdsSynTables', RdsSynTables) def get_RdsPassword(self): # String return self.get_query_params().get('RdsPassword') def set_RdsPassword(self, RdsPassword): # String self.add_query_param('RdsPassword', RdsPassword) def get_CkUserName(self): # String return self.get_query_params().get('CkUserName') def set_CkUserName(self, CkUserName): # String self.add_query_param('CkUserName', CkUserName) def get_RdsSynDb(self): # String return self.get_query_params().get('RdsSynDb') def set_RdsSynDb(self, RdsSynDb): # String self.add_query_param('RdsSynDb', RdsSynDb) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_DbClusterId(self): # String return self.get_query_params().get('DbClusterId') def set_DbClusterId(self, DbClusterId): # String self.add_query_param('DbClusterId', DbClusterId) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_RdsId(self): # String return self.get_query_params().get('RdsId') def set_RdsId(self, RdsId): # String self.add_query_param('RdsId', RdsId) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_ClickhousePort(self): # Long return self.get_query_params().get('ClickhousePort') def set_ClickhousePort(self, ClickhousePort): # Long self.add_query_param('ClickhousePort', ClickhousePort) def get_LimitUpper(self): # Long return self.get_query_params().get('LimitUpper') def set_LimitUpper(self, LimitUpper): # Long self.add_query_param('LimitUpper', LimitUpper) def get_RdsPort(self): # Long return self.get_query_params().get('RdsPort') def set_RdsPort(self, RdsPort): # Long self.add_query_param('RdsPort', RdsPort) def get_SkipUnsupported(self): # Boolean return self.get_query_params().get('SkipUnsupported') def set_SkipUnsupported(self, SkipUnsupported): # Boolean self.add_query_param('SkipUnsupported', SkipUnsupported) def get_RdsUserName(self): # String return self.get_query_params().get('RdsUserName') def METHOD_NAME(self, RdsUserName): # String self.add_query_param('RdsUserName', RdsUserName)
null
87
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkvpc.endpoint import endpoint_data class ListFullNatEntriesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'ListFullNatEntries','vpc') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_NetworkInterfaceIdss(self): # RepeatList return self.get_query_params().get('NetworkInterfaceIds') def set_NetworkInterfaceIdss(self, NetworkInterfaceIds): # RepeatList for depth1 in range(len(NetworkInterfaceIds)): self.add_query_param('NetworkInterfaceIds.' + str(depth1 + 1), NetworkInterfaceIds[depth1]) def get_FullNatEntryId(self): # String return self.get_query_params().get('FullNatEntryId') def set_FullNatEntryId(self, FullNatEntryId): # String self.add_query_param('FullNatEntryId', FullNatEntryId) def get_FullNatTableId(self): # String return self.get_query_params().get('FullNatTableId') def set_FullNatTableId(self, FullNatTableId): # String self.add_query_param('FullNatTableId', FullNatTableId) def get_NextToken(self): # String return self.get_query_params().get('NextToken') def set_NextToken(self, NextToken): # String self.add_query_param('NextToken', NextToken) def get_FullNatEntryNamess(self): # RepeatList return self.get_query_params().get('FullNatEntryNames') def set_FullNatEntryNamess(self, FullNatEntryNames): # RepeatList for depth1 in range(len(FullNatEntryNames)): self.add_query_param('FullNatEntryNames.' + str(depth1 + 1), FullNatEntryNames[depth1]) def get_NatGatewayId(self): # String return self.get_query_params().get('NatGatewayId') def set_NatGatewayId(self, NatGatewayId): # String self.add_query_param('NatGatewayId', NatGatewayId) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_IpProtocol(self): # String return self.get_query_params().get('IpProtocol') def METHOD_NAME(self, IpProtocol): # String self.add_query_param('IpProtocol', IpProtocol) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_MaxResults(self): # Long return self.get_query_params().get('MaxResults') def set_MaxResults(self, MaxResults): # Long self.add_query_param('MaxResults', MaxResults)
null
88
# Copyright 2017-2023 Posit Software, PBC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import io import json import logging import socket from werkzeug import routing from werkzeug import serving from werkzeug import exceptions from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.wrappers import Request, Response log = logging.getLogger("guild") HTTPException = exceptions.HTTPException NotFound = exceptions.NotFound BadRequest = exceptions.BadRequest class QuietRequestHandler(serving.WSGIRequestHandler): def log(self, type, message, *args): if type != 'info': super().log(type, message, *args) class StaticBase: def __init__(self, exports): self._app = SharedDataMiddleware(self._not_found, exports) def handle(self, _req): return self._app @staticmethod def _not_found(_env, _start_resp): raise NotFound() class StaticDir(StaticBase): def __init__(self, dir): super().__init__({"/": dir}) def handle_index(self, _req): def app(env, start_resp): env["PATH_INFO"] = "/index.html" return self._app(env, start_resp) return app class RedirectMiddleware: def __init__(self, map, app): self.map = map self.app = app def __call__(self, env, start_resp): path = env.get("PATH_INFO") env["PATH_INFO"] = self.map.get(path, path) return self.app(env, start_resp) def make_server(host, port, app, logging=True): if host is None: raise RuntimeError("host cannot be None") if port is None: raise RuntimeError("port cannot be None") if logging: request_handler = serving.WSGIRequestHandler else: request_handler = QuietRequestHandler try: return serving.make_server( host, port, app, threaded=True, request_handler=request_handler, ) except socket.error as e: if host: raise log.debug( "error starting server on %s:%s (%s), trying IPv6 default host '::'", host, port, e ) return serving.make_server("::", port, app, threaded=True) def json_resp(data, status=200, headers=None): return Response( json.dumps(data), status=status, content_type="application/json", headers=headers or [], ) def Rule(path, handler, *args): return routing.Rule(path, endpoint=(handler, args)) def Map(rules): return routing.Map([Rule(path, handler, *args) for path, handler, args, in rules]) def dispatch(routes, env, start_resp): urls = routes.bind_to_environ(env) try: (handler, args), kw = urls.match() except HTTPException as e: return e(env, start_resp) else: args = (Request(env),) + args kw = _del_underscore_vars(kw) try: return handler(*args, **kw)(env, start_resp) except HTTPException as e: return e(env, start_resp) def _del_underscore_vars(kw): return {k: kw[k] for k in kw if k[0] != "_"} def App(routes, error_handler=None): def app(env, start_resp): try: return dispatch(routes, env, start_resp) except Exception as e: if error_handler: return error_handler(e)(env, start_resp) raise return app def request_get(app, url): resp = {} def start_resp(status, _headers): resp["status"] = status resp["body"] = app(_request_env("GET", url), start_resp) return resp def _request_env(method, url, body=None, content_type=None): from urllib.parse import urlparse req = urlparse(url) env = { "wsgi.url_scheme": "http", "REQUEST_METHOD": method, "PATH_INFO": req.path, "QUERY_STRING": req.query, } if body is not None: env["wsgi.input"] = io.BytesIO(body.encode()) env["CONTENT_LENGTH"] = str(len(body)) if content_type: env["CONTENT_TYPE"] = content_type return env def METHOD_NAME(app, url, body, content_type=None): # TODO body and content type resp = {} def start_resp(status, _headers): resp["status"] = status resp["body"] = app(_request_env("POST", url, body, content_type), start_resp) return resp
null
89
# coding=utf-8 # Copyright 2023 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Lazy imports for heavy dependencies.""" import functools import importlib from typing import Any, Callable, TypeVar from tensorflow_datasets.core.utils import py_utils as utils _Fn = TypeVar("_Fn") def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError as e: err_msg = ( "Failed importing {name}. This likely means that the dataset " "requires additional dependencies that have to be " "manually installed (usually with `pip install {name}`). See " "setup.py extras_require." ).format(name=module_name) utils.reraise(e, suffix=err_msg) class LazyImporter(object): """Lazy importer for heavy dependencies. Some datasets require heavy dependencies for data generation. To allow for the default installation to remain lean, those heavy dependencies are lazily imported here. """ @utils.classproperty @classmethod def apache_beam(cls): return _try_import("apache_beam") @utils.classproperty @classmethod def bs4(cls): return _try_import("bs4") @utils.classproperty @classmethod def crepe(cls): return _try_import("crepe") @utils.classproperty @classmethod def cv2(cls): return _try_import("cv2") @utils.classproperty @classmethod def datasets(cls): return _try_import("datasets") @utils.classproperty @classmethod def envlogger(cls): return _try_import("envlogger.reader") @utils.classproperty @classmethod def gcsfs_store(cls): return _try_import("gcsfs").GCSFileSystem(token='anon').get_mapper @utils.classproperty @classmethod def gcld3(cls): return _try_import("gcld3") # pylint: disable=unreachable @utils.classproperty @classmethod def h5py(cls): return _try_import("h5py") @utils.classproperty @classmethod def jax(cls): return _try_import("jax") @utils.classproperty @classmethod def langdetect(cls): return _try_import("langdetect") @utils.classproperty @classmethod def librosa(cls): return _try_import("librosa") @utils.classproperty @classmethod def lxml(cls): return _try_import("lxml") @utils.classproperty @classmethod def matplotlib(cls): _try_import("matplotlib.pyplot") return _try_import("matplotlib") @utils.classproperty @classmethod def mwparserfromhell(cls): return _try_import("mwparserfromhell") @utils.classproperty @classmethod def mwxml(cls): return _try_import("mwxml") @utils.classproperty @classmethod def networkx(cls): return _try_import("networkx") @utils.classproperty @classmethod def nltk(cls): return _try_import("nltk") @utils.classproperty @classmethod def pandas(cls): return _try_import("pandas") @utils.classproperty @classmethod def PIL_Image(cls): # pylint: disable=invalid-name # TiffImagePlugin need to be activated explicitly on some systems # https://github.com/python-pillow/Pillow/blob/5.4.x/src/PIL/Image.py#L407 _try_import("PIL.TiffImagePlugin") return _try_import("PIL.Image") @utils.classproperty @classmethod def PIL_ImageDraw(cls): # pylint: disable=invalid-name return _try_import("PIL.ImageDraw") @utils.classproperty @classmethod def pretty_midi(cls): return _try_import("pretty_midi") @utils.classproperty @classmethod def pycocotools(cls): return _try_import("pycocotools.mask") @utils.classproperty @classmethod def pydub(cls): return _try_import("pydub") @utils.classproperty @classmethod def scipy(cls): _try_import("scipy.io") _try_import("scipy.io.wavfile") _try_import("scipy.ndimage") return _try_import("scipy") @utils.classproperty @classmethod def skimage(cls): _try_import("skimage.color") _try_import("skimage.filters") try: _try_import("skimage.external.tifffile") except ImportError: pass return _try_import("skimage") @utils.classproperty @classmethod def tifffile(cls): return _try_import("tifffile") @utils.classproperty @classmethod def tensorflow_data_validation(cls): return _try_import("tensorflow_data_validation") @utils.classproperty @classmethod def tensorflow_io(cls): return _try_import("tensorflow_io") @utils.classproperty @classmethod def tldextract(cls): return _try_import("tldextract") @utils.classproperty @classmethod def os(cls): """For testing purposes only.""" return _try_import("os") @utils.classproperty @classmethod def test_foo(cls): """For testing purposes only.""" return _try_import("test_foo") @utils.classproperty @classmethod def zarr(cls): return _try_import("zarr") @utils.classproperty @classmethod def conllu(cls): return _try_import("conllu") @utils.classproperty @classmethod def huggingface_hub(cls): return _try_import("huggingface_hub") lazy_imports = LazyImporter # pylint: disable=invalid-name def beam_ptransform_fn(fn: Callable[..., Any]) -> Callable[..., Any]: """Lazy version of `@beam.ptransform_fn`.""" lazy_decorated_fn = None @functools.wraps(fn) def METHOD_NAME(*args, **kwargs): nonlocal lazy_decorated_fn # Actually decorate the function only the first time it is called if lazy_decorated_fn is None: lazy_decorated_fn = lazy_imports.apache_beam.ptransform_fn(fn) return lazy_decorated_fn(*args, **kwargs) return METHOD_NAME
null
90
########################################################################## # # Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import unittest import IECore class TestObject( unittest.TestCase ) : def setUp( self ) : self.typeNames = [ "FloatTypedData", "FloatVectorData", "V3fVectorData" ] def testDataTypesDefinition( self ) : """ Function that checks if all the Data classes from IECore were defined on __dataTypesConversion dict. It raises an exception if there's any problem. """ import IECore def test(c): try: return issubclass(c, IECore.Data) and not (c is IECore.Data) except: return False dataClasses = filter(test, map(lambda x: getattr(IECore, x), dir(IECore))) notDefinedClasses = set(dataClasses).difference(IECore.getDataDerivedTypes()) if len(notDefinedClasses) > 0: raise Exception( "The following classes were not defined on the conversion dictionaire: " + ", ".join( map(str, notDefinedClasses) ) + ".\nPlease, add them on DataTraits.py" ) def testObjectCreateAndCast( self ): """ Tests if all Object derived classes can be created using the factory function and if they can be casted to Object pointers. PS: Data derived objects should be casted down to Data. Because Data is casted to Object. """ import IECore def objectDerived(c): try: return issubclass(c, IECore.Object) and not IECore.Object.isAbstractType(c.__name__) except: return False group = IECore.CompoundObject() objectClasses = filter(objectDerived, map(lambda x: getattr(IECore, x), dir(IECore))) notCreated = [] notCasted = [] for c in objectClasses: tId = IECore.Object.typeIdFromTypeName( c.__name__ ) try: obj = IECore.Object.create(tId) except: notCreated.append(c) else: try: group["object"] = obj except: notCasted.append(c) errors = "" if len( notCreated ) : errors += "The following classes could not be created from Object.create() function: " + str( notCreated ) + "\n" if len( notCasted ): errors += "The following classes could not be casted to ObjectPtr:" + str( notCasted ) if len( errors ): raise Exception( errors ) def testDynamicDowncasting( self ): """ Tests if python can downcast a ObjectPtr to a proper derived Object instance. The downcast usually works, but when the object is used on a function that requires a derived class, then it didn't match. This problem was solved with the INTRUSIVE_PTR_PATCH used on the bindings. This does not test every class on IECore, but should... """ o = IECore.CompoundObject() o["first"] = IECore.IntData( 1 ) t = IECore.CompoundData( { "first": o["first"] } ) def testTypeIdToNameMapping( self ) : for tId in IECore.TypeId.values.values() : if tId==IECore.TypeId.Invalid : continue if IECore.Object.isType( tId ) : self.assertEqual( tId, IECore.Object.typeIdFromTypeName( IECore.Object.typeNameFromTypeId( tId ) ) ) def testCreate( self ) : for tId in IECore.TypeId.values.values() : if tId==IECore.TypeId.Invalid : continue if IECore.Object.isType( tId ) and not IECore.Object.isAbstractType( tId ) : o = IECore.Object.create( tId ) self.assertEqual( o.typeId(), tId ) self.assertEqual( o.typeName(), IECore.Object.typeNameFromTypeId( tId ) ) oo = IECore.Object.create( IECore.Object.typeNameFromTypeId( tId ) ) self.assertEqual( oo.typeId(), tId ) def testCopy( self ) : for tId in IECore.TypeId.values.values() : if tId==IECore.TypeId.Invalid : continue if IECore.Object.isType( tId ) and not IECore.Object.isAbstractType( tId ) : o = IECore.Object.create( tId ) oo = o.copy() self.assertEqual( o, oo ) def testCopyFrom( self ) : i = IECore.IntData( 1 ) ii = IECore.IntData( 2 ) self.assertNotEqual( i, ii ) ii.copyFrom( i ) self.assertEqual( i, ii ) f = IECore.FloatData( 1 ) self.assertNotEqual( i, f ) self.assertRaises( RuntimeError, IECore.curry( ii.copyFrom, f ) ) b = IECore.BlindDataHolder() b.blindData()["floatData"] = IECore.FloatData( 1.0 ) b.blindData()["intData"] = IECore.IntData( -5 ) bb = IECore.BlindDataHolder() self.assertNotEqual( b, bb ) bb.copyFrom( b ) self.assertEqual( b, bb ) def METHOD_NAME( self ) : allHashes = set() objectsCreated = 0 for t in IECore.TypeId.names : o = None with IECore.IgnoredExceptions( RuntimeError ) : o = IECore.Object.create( t ) if o is not None : objectsCreated += 1 allHashes.add( str( o.hash() ) ) h = IECore.MurmurHash() o.hash( h ) self.assertEqual( h, o.hash() ) self.assertEqual( len( allHashes ), objectsCreated ) if __name__ == "__main__": unittest.main()
null
91
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkclickhouse.endpoint import endpoint_data class CreateRDSToClickhouseDbRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'clickhouse', '2019-11-11', 'CreateRDSToClickhouseDb') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_SynDbTables(self): # String return self.get_query_params().get('SynDbTables') def set_SynDbTables(self, SynDbTables): # String self.add_query_param('SynDbTables', SynDbTables) def get_RdsVpcId(self): # String return self.get_query_params().get('RdsVpcId') def set_RdsVpcId(self, RdsVpcId): # String self.add_query_param('RdsVpcId', RdsVpcId) def get_CkPassword(self): # String return self.get_query_params().get('CkPassword') def set_CkPassword(self, CkPassword): # String self.add_query_param('CkPassword', CkPassword) def get_RdsPassword(self): # String return self.get_query_params().get('RdsPassword') def set_RdsPassword(self, RdsPassword): # String self.add_query_param('RdsPassword', RdsPassword) def get_CkUserName(self): # String return self.get_query_params().get('CkUserName') def set_CkUserName(self, CkUserName): # String self.add_query_param('CkUserName', CkUserName) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_DbClusterId(self): # String return self.get_query_params().get('DbClusterId') def set_DbClusterId(self, DbClusterId): # String self.add_query_param('DbClusterId', DbClusterId) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_RdsId(self): # String return self.get_query_params().get('RdsId') def set_RdsId(self, RdsId): # String self.add_query_param('RdsId', RdsId) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_ClickhousePort(self): # Long return self.get_query_params().get('ClickhousePort') def set_ClickhousePort(self, ClickhousePort): # Long self.add_query_param('ClickhousePort', ClickhousePort) def get_LimitUpper(self): # Long return self.get_query_params().get('LimitUpper') def set_LimitUpper(self, LimitUpper): # Long self.add_query_param('LimitUpper', LimitUpper) def get_RdsPort(self): # Long return self.get_query_params().get('RdsPort') def set_RdsPort(self, RdsPort): # Long self.add_query_param('RdsPort', RdsPort) def get_SkipUnsupported(self): # Boolean return self.get_query_params().get('SkipUnsupported') def set_SkipUnsupported(self, SkipUnsupported): # Boolean self.add_query_param('SkipUnsupported', SkipUnsupported) def METHOD_NAME(self): # String return self.get_query_params().get('RdsVpcUrl') def set_RdsVpcUrl(self, RdsVpcUrl): # String self.add_query_param('RdsVpcUrl', RdsVpcUrl) def get_RdsUserName(self): # String return self.get_query_params().get('RdsUserName') def set_RdsUserName(self, RdsUserName): # String self.add_query_param('RdsUserName', RdsUserName)
null
92
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksmc.endpoint import endpoint_data class ModifyReplicationJobAttributeRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'smc', '2019-06-01', 'ModifyReplicationJobAttribute','smc') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_TargetType(self): return self.get_query_params().get('TargetType') def set_TargetType(self,TargetType): self.add_query_param('TargetType',TargetType) def get_Description(self): return self.get_query_params().get('Description') def set_Description(self,Description): self.add_query_param('Description',Description) def get_Frequency(self): return self.get_query_params().get('Frequency') def set_Frequency(self,Frequency): self.add_query_param('Frequency',Frequency) def get_JobId(self): return self.get_query_params().get('JobId') def set_JobId(self,JobId): self.add_query_param('JobId',JobId) def get_ImageName(self): return self.get_query_params().get('ImageName') def set_ImageName(self,ImageName): self.add_query_param('ImageName',ImageName) def METHOD_NAME(self): return self.get_query_params().get('SystemDiskSize') def set_SystemDiskSize(self,SystemDiskSize): self.add_query_param('SystemDiskSize',SystemDiskSize) def get_InstanceType(self): return self.get_query_params().get('InstanceType') def set_InstanceType(self,InstanceType): self.add_query_param('InstanceType',InstanceType) def get_ContainerRepository(self): return self.get_query_params().get('ContainerRepository') def set_ContainerRepository(self,ContainerRepository): self.add_query_param('ContainerRepository',ContainerRepository) def get_ContainerTag(self): return self.get_query_params().get('ContainerTag') def set_ContainerTag(self,ContainerTag): self.add_query_param('ContainerTag',ContainerTag) def get_ContainerNamespace(self): return self.get_query_params().get('ContainerNamespace') def set_ContainerNamespace(self,ContainerNamespace): self.add_query_param('ContainerNamespace',ContainerNamespace) def get_LaunchTemplateId(self): return self.get_query_params().get('LaunchTemplateId') def set_LaunchTemplateId(self,LaunchTemplateId): self.add_query_param('LaunchTemplateId',LaunchTemplateId) def get_ResourceOwnerAccount(self): return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self,ResourceOwnerAccount): self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount) def get_SystemDiskParts(self): return self.get_query_params().get('SystemDiskPart') def set_SystemDiskParts(self, SystemDiskParts): for depth1 in range(len(SystemDiskParts)): if SystemDiskParts[depth1].get('SizeBytes') is not None: self.add_query_param('SystemDiskPart.' + str(depth1 + 1) + '.SizeBytes', SystemDiskParts[depth1].get('SizeBytes')) if SystemDiskParts[depth1].get('Block') is not None: self.add_query_param('SystemDiskPart.' + str(depth1 + 1) + '.Block', SystemDiskParts[depth1].get('Block')) if SystemDiskParts[depth1].get('Device') is not None: self.add_query_param('SystemDiskPart.' + str(depth1 + 1) + '.Device', SystemDiskParts[depth1].get('Device')) def get_ValidTime(self): return self.get_query_params().get('ValidTime') def set_ValidTime(self,ValidTime): self.add_query_param('ValidTime',ValidTime) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_DataDisks(self): return self.get_query_params().get('DataDisk') def set_DataDisks(self, DataDisks): for depth1 in range(len(DataDisks)): if DataDisks[depth1].get('Size') is not None: self.add_query_param('DataDisk.' + str(depth1 + 1) + '.Size', DataDisks[depth1].get('Size')) if DataDisks[depth1].get('Part') is not None: for depth2 in range(len(DataDisks[depth1].get('Part'))): if DataDisks[depth1].get('Part')[depth2].get('SizeBytes') is not None: self.add_query_param('DataDisk.' + str(depth1 + 1) + '.Part.' + str(depth2 + 1) + '.SizeBytes', DataDisks[depth1].get('Part')[depth2].get('SizeBytes')) if DataDisks[depth1].get('Part')[depth2].get('Block') is not None: self.add_query_param('DataDisk.' + str(depth1 + 1) + '.Part.' + str(depth2 + 1) + '.Block', DataDisks[depth1].get('Part')[depth2].get('Block')) if DataDisks[depth1].get('Part')[depth2].get('Device') is not None: self.add_query_param('DataDisk.' + str(depth1 + 1) + '.Part.' + str(depth2 + 1) + '.Device', DataDisks[depth1].get('Part')[depth2].get('Device')) if DataDisks[depth1].get('Index') is not None: self.add_query_param('DataDisk.' + str(depth1 + 1) + '.Index', DataDisks[depth1].get('Index')) def get_LaunchTemplateVersion(self): return self.get_query_params().get('LaunchTemplateVersion') def set_LaunchTemplateVersion(self,LaunchTemplateVersion): self.add_query_param('LaunchTemplateVersion',LaunchTemplateVersion) def get_ScheduledStartTime(self): return self.get_query_params().get('ScheduledStartTime') def set_ScheduledStartTime(self,ScheduledStartTime): self.add_query_param('ScheduledStartTime',ScheduledStartTime) def get_InstanceId(self): return self.get_query_params().get('InstanceId') def set_InstanceId(self,InstanceId): self.add_query_param('InstanceId',InstanceId) def get_InstanceRamRole(self): return self.get_query_params().get('InstanceRamRole') def set_InstanceRamRole(self,InstanceRamRole): self.add_query_param('InstanceRamRole',InstanceRamRole) def get_Name(self): return self.get_query_params().get('Name') def set_Name(self,Name): self.add_query_param('Name',Name) def get_MaxNumberOfImageToKeep(self): return self.get_query_params().get('MaxNumberOfImageToKeep') def set_MaxNumberOfImageToKeep(self,MaxNumberOfImageToKeep): self.add_query_param('MaxNumberOfImageToKeep',MaxNumberOfImageToKeep
null
93
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkcomputenest.endpoint import endpoint_data class CreateServiceInstanceRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'ComputeNest', '2021-06-01', 'CreateServiceInstance','computenest') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Commodity(self): # Struct return self.get_query_params().get('Commodity') def set_Commodity(self, Commodity): # Struct if Commodity.get('PayPeriod') is not None: self.add_query_param('Commodity.PayPeriod', Commodity.get('PayPeriod')) if Commodity.get('PayPeriodUnit') is not None: self.add_query_param('Commodity.PayPeriodUnit', Commodity.get('PayPeriodUnit')) def get_ContactGroup(self): # String return self.get_query_params().get('ContactGroup') def set_ContactGroup(self, ContactGroup): # String self.add_query_param('ContactGroup', ContactGroup) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_SpecificationCode(self): # String return self.get_query_params().get('SpecificationCode') def set_SpecificationCode(self, SpecificationCode): # String self.add_query_param('SpecificationCode', SpecificationCode) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_EnableInstanceOps(self): # Boolean return self.get_query_params().get('EnableInstanceOps') def set_EnableInstanceOps(self, EnableInstanceOps): # Boolean self.add_query_param('EnableInstanceOps', EnableInstanceOps) def get_TemplateName(self): # String return self.get_query_params().get('TemplateName') def set_TemplateName(self, TemplateName): # String self.add_query_param('TemplateName', TemplateName) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) def get_DryRun(self): # Boolean return self.get_query_params().get('DryRun') def set_DryRun(self, DryRun): # Boolean self.add_query_param('DryRun', DryRun) def get_EnableUserPrometheus(self): # Boolean return self.get_query_params().get('EnableUserPrometheus') def set_EnableUserPrometheus(self, EnableUserPrometheus): # Boolean self.add_query_param('EnableUserPrometheus', EnableUserPrometheus) def get_SpecificationName(self): # String return self.get_query_params().get('SpecificationName') def set_SpecificationName(self, SpecificationName): # String self.add_query_param('SpecificationName', SpecificationName) def get_TrialType(self): # String return self.get_query_params().get('TrialType') def set_TrialType(self, TrialType): # String self.add_query_param('TrialType', TrialType) def get_Name(self): # String return self.get_query_params().get('Name') def set_Name(self, Name): # String self.add_query_param('Name', Name) def get_ServiceVersion(self): # String return self.get_query_params().get('ServiceVersion') def set_ServiceVersion(self, ServiceVersion): # String self.add_query_param('ServiceVersion', ServiceVersion) def get_ServiceId(self): # String return self.get_query_params().get('ServiceId') def set_ServiceId(self, ServiceId): # String self.add_query_param('ServiceId', ServiceId) def get_Parameters(self): # String return self.get_query_params().get('Parameters') def METHOD_NAME(self, Parameters): # String self.add_query_param('Parameters', Parameters) def get_PayType(self): # Long return self.get_query_params().get('PayType') def set_PayType(self, PayType): # Long self.add_query_param('PayType', PayType) def get_OperationMetadata(self): # Struct return self.get_query_params().get('OperationMetadata') def set_OperationMetadata(self, OperationMetadata): # Struct if OperationMetadata.get('EndTime') is not None: self.add_query_param('OperationMetadata.EndTime', OperationMetadata.get('EndTime')) if OperationMetadata.get('Resources') is not None: self.add_query_param('OperationMetadata.Resources', OperationMetadata.get('Resources')) if OperationMetadata.get('StartTime') is not None: self.add_query_param('OperationMetadata.StartTime', OperationMetadata.get('StartTime')) if OperationMetadata.get('ExtraInfo') is not None: self.add_query_param('OperationMetadata.ExtraInfo', OperationMetadata.get('ExtraInfo')) if OperationMetadata.get('ServiceInstanceId') is not None: self.add_query_param('OperationMetadata.ServiceInstanceId', OperationMetadata.get('ServiceInstanceId'))
null
94
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkecs.endpoint import endpoint_data class ImportImageRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'ImportImage','ecs') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DiskDeviceMappings(self): # RepeatList return self.get_query_params().get('DiskDeviceMapping') def set_DiskDeviceMappings(self, DiskDeviceMapping): # RepeatList for depth1 in range(len(DiskDeviceMapping)): if DiskDeviceMapping[depth1].get('OSSBucket') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.OSSBucket', DiskDeviceMapping[depth1].get('OSSBucket')) if DiskDeviceMapping[depth1].get('DiskImSize') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.DiskImSize', DiskDeviceMapping[depth1].get('DiskImSize')) if DiskDeviceMapping[depth1].get('Format') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.Format', DiskDeviceMapping[depth1].get('Format')) if DiskDeviceMapping[depth1].get('Device') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.Device', DiskDeviceMapping[depth1].get('Device')) if DiskDeviceMapping[depth1].get('OSSObject') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.OSSObject', DiskDeviceMapping[depth1].get('OSSObject')) if DiskDeviceMapping[depth1].get('DiskImageSize') is not None: self.add_query_param('DiskDeviceMapping.' + str(depth1 + 1) + '.DiskImageSize', DiskDeviceMapping[depth1].get('DiskImageSize')) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_Description(self): # String return self.get_query_params().get('Description') def set_Description(self, Description): # String self.add_query_param('Description', Description) def get_Platform(self): # String return self.get_query_params().get('Platform') def set_Platform(self, Platform): # String self.add_query_param('Platform', Platform) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_BootMode(self): # String return self.get_query_params().get('BootMode') def set_BootMode(self, BootMode): # String self.add_query_param('BootMode', BootMode) def get_ImageName(self): # String return self.get_query_params().get('ImageName') def set_ImageName(self, ImageName): # String self.add_query_param('ImageName', ImageName) def get_Tags(self): # RepeatList return self.get_query_params().get('Tag') def set_Tags(self, Tag): # RepeatList for depth1 in range(len(Tag)): if Tag[depth1].get('Value') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Value', Tag[depth1].get('Value')) if Tag[depth1].get('Key') is not None: self.add_query_param('Tag.' + str(depth1 + 1) + '.Key', Tag[depth1].get('Key')) def get_Architecture(self): # String return self.get_query_params().get('Architecture') def set_Architecture(self, Architecture): # String self.add_query_param('Architecture', Architecture) def get_LicenseType(self): # String return self.get_query_params().get('LicenseType') def METHOD_NAME(self, LicenseType): # String self.add_query_param('LicenseType', LicenseType) def get_DetectionStrategy(self): # String return self.get_query_params().get('DetectionStrategy') def set_DetectionStrategy(self, DetectionStrategy): # String self.add_query_param('DetectionStrategy', DetectionStrategy) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_RoleName(self): # String return self.get_query_params().get('RoleName') def set_RoleName(self, RoleName): # String self.add_query_param('RoleName', RoleName) def get_OSType(self): # String return self.get_query_params().get('OSType') def set_OSType(self, OSType): # String self.add_query_param('OSType', OSType) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId)
null
95
# -*- coding: utf-8 -*- ''' Copyright (C) 2021 Gitcoin Core This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' from __future__ import unicode_literals from django.contrib import admin from django.utils.safestring import mark_safe from .models import ( AccountDeletionRequest, Alumni, EmailEvent, EmailInventory, EmailSubscriber, EmailSupressionList, GithubEvent, GithubOrgToTwitterHandleMapping, ImageDropZone, Job, Keyword, LeaderboardRank, ManualStat, MarketingCallback, Match, RoundupEmail, SlackPresence, SlackUser, Stat, UpcomingDate, ) class RoundupEmailAdmin(admin.ModelAdmin): ordering = ['-id'] list_display = ['created_on', '__str__'] def response_change(self, request, obj): if "_send_roundup_email_myself" in request.POST: from marketing.tasks import weekly_roundup weekly_roundup.delay(request.user.profile.email) self.message_user(request, "Roundup Email Queued!") if "_send_roundup_email_everyone" in request.POST: from marketing.tasks import send_all_weekly_roundup send_all_weekly_roundup.delay() self.message_user(request, "Roundup Email Queued!") return super().response_change(request, obj) class GeneralAdmin(admin.ModelAdmin): ordering = ['-id'] list_display = ['created_on', '__str__'] class UpcomingDateAdmin(admin.ModelAdmin): ordering = ['-date'] list_display = ['created_on', 'date', '__str__'] class LeaderboardRankAdmin(admin.ModelAdmin): ordering = ['-id'] list_display = ['created_on', '__str__'] raw_id_fields = ['profile'] class EmailEventAdmin(admin.ModelAdmin): search_fields = ['email', 'event' ] ordering = ['-id'] class GithubEventAdmin(admin.ModelAdmin): raw_id_fields = ['profile'] ordering = ['-id'] class SlackPresenceAdmin(admin.ModelAdmin): raw_id_fields = ['slackuser'] ordering = ['-id'] class MatchAdmin(admin.ModelAdmin): raw_id_fields = ['bounty'] ordering = ['-id'] class AlumniAdmin(GeneralAdmin): """Define the Alumni admin layout.""" raw_id_fields = ['profile'] search_fields = ['organization', ] list_display = ['get_profile_username', 'get_profile_email', 'organization', 'created_on', ] readonly_fields = ['created_on', 'modified_on', ] def get_queryset(self, request): """Override the get_queryset method to include FK lookups.""" return super(AlumniAdmin, self).get_queryset(request).select_related('profile') def get_profile_email(self, obj): """Get the profile email address.""" return obj.profile.email get_profile_email.admin_order_field = 'email' get_profile_email.short_description = 'Profile Email' def METHOD_NAME(self, obj): """Get the profile username.""" if hasattr(obj, 'profile') and obj.profile.username: return mark_safe( f'<a href=/_administrationmarketing/alumni/{obj.pk}/change/>{obj.profile.username}</a>' ) elif obj.github_username: return obj.github_username return 'N/A' METHOD_NAME.admin_order_field = 'username' METHOD_NAME.short_description = 'Profile Username' class EmailSubscriberAdmin(admin.ModelAdmin): raw_id_fields = ['profile'] ordering = ['-id'] search_fields = ['email', 'source', 'keywords'] list_display = ['email', 'created_on', 'source'] class SlackUserAdmin(admin.ModelAdmin): ordering = ['-times_seen'] search_fields = ['email', 'username'] list_display = ['email', 'username', 'times_seen', 'pct_seen', 'membership_length_in_days', 'last_seen'] def pct_seen(self, instance): return "{}%".format(round(100 * (instance.times_seen / (instance.times_seen + instance.times_unseen)))) def membership_length_in_days(self, instance): try: return (instance.last_seen - instance.created_on).days except Exception: return 'Unknown' class ImageDropZoneAdmin(admin.ModelAdmin): ordering = ['-id'] list_display = ['pk', 'name', 'image'] admin.site.register(MarketingCallback, GeneralAdmin) admin.site.register(AccountDeletionRequest, GeneralAdmin) admin.site.register(EmailSupressionList, GeneralAdmin) admin.site.register(EmailInventory, GeneralAdmin) admin.site.register(Alumni, AlumniAdmin) admin.site.register(GithubEvent, GithubEventAdmin) admin.site.register(Match, MatchAdmin) admin.site.register(Job, GeneralAdmin) admin.site.register(ManualStat, GeneralAdmin) admin.site.register(UpcomingDate, UpcomingDateAdmin) admin.site.register(Stat, GeneralAdmin) admin.site.register(Keyword, GeneralAdmin) admin.site.register(EmailEvent, EmailEventAdmin) admin.site.register(EmailSubscriber, EmailSubscriberAdmin) admin.site.register(LeaderboardRank, LeaderboardRankAdmin) admin.site.register(SlackUser, SlackUserAdmin) admin.site.register(SlackPresence, SlackPresenceAdmin) admin.site.register(GithubOrgToTwitterHandleMapping, GeneralAdmin) admin.site.register(RoundupEmail, RoundupEmailAdmin) admin.site.register(ImageDropZone, ImageDropZoneAdmin)
null
96
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkoos.endpoint import endpoint_data class ListTemplatesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'oos', '2019-06-01', 'ListTemplates','oos') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceGroupId(self): # String return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self, ResourceGroupId): # String self.add_query_param('ResourceGroupId', ResourceGroupId) def get_CreatedDateBefore(self): # String return self.get_query_params().get('CreatedDateBefore') def set_CreatedDateBefore(self, CreatedDateBefore): # String self.add_query_param('CreatedDateBefore', CreatedDateBefore) def get_CreatedBy(self): # String return self.get_query_params().get('CreatedBy') def set_CreatedBy(self, CreatedBy): # String self.add_query_param('CreatedBy', CreatedBy) def METHOD_NAME(self): # String return self.get_query_params().get('NextToken') def set_NextToken(self, NextToken): # String self.add_query_param('NextToken', NextToken) def get_TemplateType(self): # String return self.get_query_params().get('TemplateType') def set_TemplateType(self, TemplateType): # String self.add_query_param('TemplateType', TemplateType) def get_TemplateName(self): # String return self.get_query_params().get('TemplateName') def set_TemplateName(self, TemplateName): # String self.add_query_param('TemplateName', TemplateName) def get_SortOrder(self): # String return self.get_query_params().get('SortOrder') def set_SortOrder(self, SortOrder): # String self.add_query_param('SortOrder', SortOrder) def get_ShareType(self): # String return self.get_query_params().get('ShareType') def set_ShareType(self, ShareType): # String self.add_query_param('ShareType', ShareType) def get_HasTrigger(self): # Boolean return self.get_query_params().get('HasTrigger') def set_HasTrigger(self, HasTrigger): # Boolean self.add_query_param('HasTrigger', HasTrigger) def get_CreatedDateAfter(self): # String return self.get_query_params().get('CreatedDateAfter') def set_CreatedDateAfter(self, CreatedDateAfter): # String self.add_query_param('CreatedDateAfter', CreatedDateAfter) def get_Tags(self): # Json return self.get_query_params().get('Tags') def set_Tags(self, Tags): # Json self.add_query_param('Tags', Tags) def get_MaxResults(self): # Integer return self.get_query_params().get('MaxResults') def set_MaxResults(self, MaxResults): # Integer self.add_query_param('MaxResults', MaxResults) def get_TemplateFormat(self): # String return self.get_query_params().get('TemplateFormat') def set_TemplateFormat(self, TemplateFormat): # String self.add_query_param('TemplateFormat', TemplateFormat) def get_SortField(self): # String return self.get_query_params().get('SortField') def set_SortField(self, SortField): # String self.add_query_param('SortField', SortField) def get_Category(self): # String return self.get_query_params().get('Category') def set_Category(self, Category): # String self.add_query_param('Category', Category)
null
97
# coding=utf-8 # Copyright 2023 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Locomotion dataset.""" import numpy as np import tensorflow_datasets.public_api as tfds from tensorflow_datasets.rlds import rlds_base _DESCRIPTION = """ The datasets were created with a SAC agent trained on the environment reward of MuJoCo locomotion tasks. These datasets are used in [What Matters for Adversarial Imitation Learning? Orsini et al. 2021](https://arxiv.org/pdf/2106.00672.pdf). The datasets follow the [RLDS format](https://github.com/google-research/rlds) to represent steps and episodes.s """ _CITATION = """ @article{orsini2021matters, title={What Matters for Adversarial Imitation Learning?}, author={Orsini, Manu and Raichuk, Anton and Hussenot, L{\'e}onard and Vincent, Damien and Dadashi, Robert and Girgin, Sertan and Geist, Matthieu and Bachem, Olivier and Pietquin, Olivier and Andrychowicz, Marcin}, journal={International Conference in Machine Learning}, year={2021} } """ _HOMEPAGE = 'https://github.com/google-research/rlds' class Locomotion(tfds.core.GeneratorBasedBuilder): """DatasetBuilder for locomotion dataset.""" VERSION = tfds.core.Version('1.0.0') RELEASE_NOTES = { '1.0.0': 'Initial release.', } _DATA_PATHS = { 'ant_sac_1M_single_policy_stochastic': 'https://storage.googleapis.com/rlds_external_data_release/ant_sac_1M_single_policy_stochastic.tar.gz', 'walker2d_sac_1M_single_policy_stochastic': 'https://storage.googleapis.com/rlds_external_data_release/walker2d_sac_1M_single_policy_stochastic.tar.gz', 'humanoid_sac_15M_single_policy_stochastic': 'https://storage.googleapis.com/rlds_external_data_release/humanoid_sac_15M_single_policy_stochastic.tar.gz', 'hopper_sac_1M_single_policy_stochastic': 'https://storage.googleapis.com/rlds_external_data_release/hopper_sac_1M_single_policy_stochastic.tar.gz', 'halfcheetah_sac_1M_single_policy_stochastic': 'https://storage.googleapis.com/rlds_external_data_release/halfcheetah_sac_1M_single_policy_stochastic.tar.gz', } BUILDER_CONFIGS = [ rlds_base.DatasetConfig( name='ant_sac_1M_single_policy_stochastic', observation_info=tfds.features.Tensor(shape=(111,), dtype=np.float32), action_info=tfds.features.Tensor(shape=(8,), dtype=np.float32), reward_info=np.float32, discount_info=np.float32, citation=_CITATION, homepage=_HOMEPAGE, overall_description=_DESCRIPTION, description=( 'Dataset generated by a SAC agent trained for 1M steps for Ant.' ), supervised_keys=None, # pytype: disable=wrong-arg-types # gen-stub-imports ), rlds_base.DatasetConfig( name='hopper_sac_1M_single_policy_stochastic', observation_info=tfds.features.Tensor(shape=(11,), dtype=np.float32), action_info=tfds.features.Tensor(shape=(3,), dtype=np.float32), reward_info=np.float32, discount_info=np.float32, citation=_CITATION, homepage=_HOMEPAGE, overall_description=_DESCRIPTION, description=( 'Dataset generated by a SAC agent trained for 1M steps for' ' Hopper.' ), supervised_keys=None, # pytype: disable=wrong-arg-types # gen-stub-imports ), rlds_base.DatasetConfig( name='halfcheetah_sac_1M_single_policy_stochastic', observation_info=tfds.features.Tensor(shape=(17,), dtype=np.float32), action_info=tfds.features.Tensor(shape=(6,), dtype=np.float32), reward_info=np.float32, discount_info=np.float32, citation=_CITATION, homepage=_HOMEPAGE, overall_description=_DESCRIPTION, description=( 'Dataset generated by a SAC agent trained for 1M steps for' ' HalfCheetah.' ), supervised_keys=None, # pytype: disable=wrong-arg-types # gen-stub-imports ), rlds_base.DatasetConfig( name='walker2d_sac_1M_single_policy_stochastic', observation_info=tfds.features.Tensor(shape=(17,), dtype=np.float32), action_info=tfds.features.Tensor(shape=(6,), dtype=np.float32), reward_info=np.float32, discount_info=np.float32, citation=_CITATION, homepage=_HOMEPAGE, overall_description=_DESCRIPTION, description=( 'Dataset generated by a SAC agent trained for 1M steps for' ' Walker2d.' ), supervised_keys=None, # pytype: disable=wrong-arg-types # gen-stub-imports ), rlds_base.DatasetConfig( name='humanoid_sac_15M_single_policy_stochastic', observation_info=tfds.features.Tensor(shape=(376,), dtype=np.float32), action_info=tfds.features.Tensor(shape=(17,), dtype=np.float32), reward_info=np.float32, discount_info=np.float32, citation=_CITATION, homepage=_HOMEPAGE, overall_description=_DESCRIPTION, description=( 'Dataset generated by a SAC agent trained for 15M steps for' ' Humanoid.' ), supervised_keys=None, # pytype: disable=wrong-arg-types # gen-stub-imports ), ] def METHOD_NAME(self) -> tfds.core.DatasetInfo: """Returns the dataset metadata.""" return rlds_base.build_info(self.builder_config, self) def _split_generators(self, dl_manager: tfds.download.DownloadManager): """Returns SplitGenerators.""" path = dl_manager.download_and_extract( { 'file_path': self._DATA_PATHS[self.builder_config.name], } ) return { 'train': self._generate_examples(path), } def _generate_examples(self, path): """Yields examples.""" file_path = path['file_path'] return rlds_base.generate_examples(file_path)
null
98
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from gen_proto.sdv.databroker.v1 import broker_pb2 as sdv_dot_databroker_dot_v1_dot_broker__pb2 class BrokerStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetDatapoints = channel.unary_unary( '/sdv.databroker.v1.Broker/GetDatapoints', request_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsRequest.SerializeToString, response_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsReply.FromString, ) self.Subscribe = channel.unary_stream( '/sdv.databroker.v1.Broker/Subscribe', request_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeRequest.SerializeToString, response_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeReply.FromString, ) self.GetMetadata = channel.unary_unary( '/sdv.databroker.v1.Broker/GetMetadata', request_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataRequest.SerializeToString, response_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataReply.FromString, ) class BrokerServicer(object): """Missing associated documentation comment in .proto file.""" def GetDatapoints(self, request, context): """Request a set of datapoints (values) Returns a list of requested data points. InvalidArgument is returned if the request is malformed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Subscribe(self, request, context): """Subscribe to a set of data points or conditional expressions using the Data Broker Query Syntax (described in QUERY.md) Returns a stream of replies. InvalidArgument is returned if the request is malformed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetMetadata(self, request, context): """Request the metadata of a set of datapoints Returns metadata of the requested data points that exist. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def METHOD_NAME(servicer, server): rpc_method_handlers = { 'GetDatapoints': grpc.unary_unary_rpc_method_handler( servicer.GetDatapoints, request_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsRequest.FromString, response_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsReply.SerializeToString, ), 'Subscribe': grpc.unary_stream_rpc_method_handler( servicer.Subscribe, request_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeRequest.FromString, response_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeReply.SerializeToString, ), 'GetMetadata': grpc.unary_unary_rpc_method_handler( servicer.GetMetadata, request_deserializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataRequest.FromString, response_serializer=sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'sdv.databroker.v1.Broker', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Broker(object): """Missing associated documentation comment in .proto file.""" @staticmethod def GetDatapoints(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/sdv.databroker.v1.Broker/GetDatapoints', sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsRequest.SerializeToString, sdv_dot_databroker_dot_v1_dot_broker__pb2.GetDatapointsReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def Subscribe(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/sdv.databroker.v1.Broker/Subscribe', sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeRequest.SerializeToString, sdv_dot_databroker_dot_v1_dot_broker__pb2.SubscribeReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def GetMetadata(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/sdv.databroker.v1.Broker/GetMetadata', sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataRequest.SerializeToString, sdv_dot_databroker_dot_v1_dot_broker__pb2.GetMetadataReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
null
99
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class UpdateMaterialRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Trademark', '2018-07-24', 'UpdateMaterial','trademark') def get_ContactEmail(self): return self.get_query_params().get('ContactEmail') def set_ContactEmail(self,ContactEmail): self.add_query_param('ContactEmail',ContactEmail) def get_ContactAddress(self): return self.get_query_params().get('ContactAddress') def set_ContactAddress(self,ContactAddress): self.add_query_param('ContactAddress',ContactAddress) def get_EAddress(self): return self.get_query_params().get('EAddress') def set_EAddress(self,EAddress): self.add_query_param('EAddress',EAddress) def get_LegalNoticeOssKey(self): return self.get_query_params().get('LegalNoticeOssKey') def set_LegalNoticeOssKey(self,LegalNoticeOssKey): self.add_query_param('LegalNoticeOssKey',LegalNoticeOssKey) def get_Address(self): return self.get_query_params().get('Address') def set_Address(self,Address): self.add_query_param('Address',Address) def get_Town(self): return self.get_query_params().get('Town') def set_Town(self,Town): self.add_query_param('Town',Town) def get_ContactNumber(self): return self.get_query_params().get('ContactNumber') def set_ContactNumber(self,ContactNumber): self.add_query_param('ContactNumber',ContactNumber) def get_City(self): return self.get_query_params().get('City') def set_City(self,City): self.add_query_param('City',City) def get_IdCardOssKey(self): return self.get_query_params().get('IdCardOssKey') def set_IdCardOssKey(self,IdCardOssKey): self.add_query_param('IdCardOssKey',IdCardOssKey) def get_ContactName(self): return self.get_query_params().get('ContactName') def set_ContactName(self,ContactName): self.add_query_param('ContactName',ContactName) def get_PassportOssKey(self): return self.get_query_params().get('PassportOssKey') def set_PassportOssKey(self,PassportOssKey): self.add_query_param('PassportOssKey',PassportOssKey) def get_ContactZipcode(self): return self.get_query_params().get('ContactZipcode') def set_ContactZipcode(self,ContactZipcode): self.add_query_param('ContactZipcode',ContactZipcode) def get_EName(self): return self.get_query_params().get('EName') def METHOD_NAME(self,EName): self.add_query_param('EName',EName) def get_Province(self): return self.get_query_params().get('Province') def set_Province(self,Province): self.add_query_param('Province',Province) def get_BusinessLicenceOssKey(self): return self.get_query_params().get('BusinessLicenceOssKey') def set_BusinessLicenceOssKey(self,BusinessLicenceOssKey): self.add_query_param('BusinessLicenceOssKey',BusinessLicenceOssKey) def get_Name(self): return self.get_query_params().get('Name') def set_Name(self,Name): self.add_query_param('Name',Name) def get_Id(self): return self.get_query_params().get('Id') def set_Id(self,Id): self.add_query_param('Id',Id) def get_CardNumber(self): return self.get_query_params().get('CardNumber') def set_CardNumber(self,CardNumber): self.add_query_param('CardNumber',CardNumber) def get_LoaId(self): return self.get_query_params().get('LoaId') def set_LoaId(self,LoaId): self.add_query_param('LoaId',LoaId) def get_LoaOssKey(self): return self.get_query_params().get('LoaOssKey') def set_LoaOssKey(self,LoaOssKey): self.add_query_param('LoaOssKey',LoaOssKey
null