code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Flatten(Layer): <NEW_LINE> <INDENT> def __init__(self, trainable=True, input_shape=None, input_dtype=None, batch_size=None, name=None): <NEW_LINE> <INDENT> super(Flatten, self).__init__(trainable, name, input_shape=input_shape, input_dtype=input_dtype, batch_size=batch_size) <NEW_LINE> <DEDENT> def _call(self, x): <NEW_LINE> <INDENT> return tf.reshape(x, [-1, tf_prod(tf.shape(x)[1:])]) <NEW_LINE> <DEDENT> def _get_output_shape(self, input_shape): <NEW_LINE> <INDENT> if not all(input_shape[1:]): <NEW_LINE> <INDENT> raise Exception('The shape of the input to Flatten is not fully defined' ' (got {}. Make sure to pass a complete input_shape' ' or "batch_input_shape" argument to the first' ' layer in your model.'.format(input_shape[1:])) <NEW_LINE> <DEDENT> return input_shape[0], np.prod(input_shape[1:]) | Flattens the input. Does not affect the batch size.
Example
-------
```python
model = Sequential()
model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32)))
# now: model.output_shape == (None, 64, 32, 32)
model.add(Flatten())
# now: model.output_shape == (None, 65536)
``` | 62598fc723849d37ff8513ce |
class HelloViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class =serializers.HelloSerializer <NEW_LINE> def list(self,request): <NEW_LINE> <INDENT> a_viewset=[ 'Uses action(list, create,retrive, update,portial_update)', 'Automatically maps to URLS using Routers', 'Provides more functionality with less code', ] <NEW_LINE> return Response({'message':'Hello!' ,'a_viewset':a_viewset}) <NEW_LINE> <DEDENT> def create(self,request): <NEW_LINE> <INDENT> serializer =self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.validated_data.get('name') <NEW_LINE> message =f'Hello {name}!' <NEW_LINE> return Response({'message':message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> <DEDENT> def retrieve(self,requst,pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'GET'}) <NEW_LINE> <DEDENT> def update(self,requst,pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'PUT'}) <NEW_LINE> <DEDENT> def partial_update(self,requst,pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'PATCH'}) <NEW_LINE> <DEDENT> def destroy(self,requst,pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'DELETE'}) | Test API ViewSet | 62598fc755399d3f05626835 |
class CourseInstructorFactory(DjangoModelFactory): <NEW_LINE> <INDENT> first_name = factory.Faker("name") <NEW_LINE> last_name = factory.Faker("name") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = CourseInstructor | Factory for course instructors | 62598fc74527f215b58ea1ec |
@method_decorator(login_required, name='dispatch') <NEW_LINE> class ClienteListView(ListView): <NEW_LINE> <INDENT> model = Cliente | docstring for PhotoListView | 62598fc75fcc89381b2662db |
class Square(): <NEW_LINE> <INDENT> def __init__(self, side_length): <NEW_LINE> <INDENT> self.__side_length = side_length <NEW_LINE> self.__side_width = (int) <NEW_LINE> self.__center = [int,int] <NEW_LINE> self.__color = ("") <NEW_LINE> self.name = ("") <NEW_LINE> <DEDENT> ''' Destructor ''' <NEW_LINE> def __del__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> ''' Getter ''' <NEW_LINE> def get_side_length(self): <NEW_LINE> <INDENT> return self.__side_length <NEW_LINE> <DEDENT> def get_center(self): <NEW_LINE> <INDENT> return self.__get_center <NEW_LINE> <DEDENT> def get_color(self): <NEW_LINE> <INDENT> return self.__color <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> ''' Setter ''' <NEW_LINE> def set_side_length(self, side_length): <NEW_LINE> <INDENT> self.__side_length = side_length <NEW_LINE> <DEDENT> def set_center(self, center): <NEW_LINE> <INDENT> self.__center = center <NEW_LINE> <DEDENT> def set_color(self, color): <NEW_LINE> <INDENT> self.__color = color <NEW_LINE> <DEDENT> def set_name(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> ''' Public Method ''' <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return self.__side_length**2 | Constructor | 62598fc7099cdd3c63675570 |
class ResortListSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> name = serializers.ReadOnlyField(source='resort_name') <NEW_LINE> latitude = serializers.ReadOnlyField(source='resort_location_latitude') <NEW_LINE> longitude = serializers.ReadOnlyField(source='resort_location_longitude') <NEW_LINE> websiteUrl = serializers.ReadOnlyField(source='resort_website_url') <NEW_LINE> altitude = serializers.ReadOnlyField(source='resort_altitude') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Resort <NEW_LINE> fields = ( 'id', 'name', 'latitude', 'longitude', 'resort_address_line1', 'resort_address_line2', 'resort_address_city', 'resort_address_state', 'resort_address_zip_code', 'websiteUrl', 'altitude', ) | Create serialized Resort objects to serve from the API. This returns the minimal detail
expected for listing resort search results. | 62598fc7956e5f7376df580c |
class UseNode(object): <NEW_LINE> <INDENT> __slots__ = ['value','hkey','older','newer', 'sideEffects', 'size', 'strongref', '__weakref__'] <NEW_LINE> def __init__(self, value, hkey, older=None, newer=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.hkey = hkey <NEW_LINE> self.older = older <NEW_LINE> self.newer = newer <NEW_LINE> self.sideEffects = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.size) + ','+ str(self.hkey) + ',' + str(self.value) | For linked list kept in most-recent .. least-recent *use* order | 62598fc7a05bb46b3848ab88 |
class Meta: <NEW_LINE> <INDENT> verbose_name = 'Post' <NEW_LINE> verbose_name_plural = 'Posts' | Meta definition for Post. | 62598fc7a8370b77170f06f8 |
class Options: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.parse(sys.argv) <NEW_LINE> <DEDENT> def get_vncserver(self) -> command_mod.Command: <NEW_LINE> <INDENT> return self._vncserver <NEW_LINE> <DEDENT> def _config(self) -> None: <NEW_LINE> <INDENT> if not os.path.isfile( os.path.join(os.environ['HOME'], '.vnc', 'passwd')): <NEW_LINE> <INDENT> raise SystemExit( f'{sys.argv[0]}: ".vnc/passwd" does not exist. ' 'Run "vncpasswd".', ) <NEW_LINE> <DEDENT> os.chdir(os.environ['HOME']) <NEW_LINE> xstartup = os.path.join(os.environ['HOME'], '.vnc', 'xstartup') <NEW_LINE> if not os.path.isfile(xstartup): <NEW_LINE> <INDENT> answer = input( "Would you like to use GNOME(g), KDE(k) or XFCE(x)? " ) <NEW_LINE> try: <NEW_LINE> <INDENT> with open( xstartup, 'w', encoding='utf-8', newline='\n', ) as ofile: <NEW_LINE> <INDENT> print("#!/usr/bin/env bash", file=ofile) <NEW_LINE> print("unset DBUS_SESSION_BUS_ADDRESS", file=ofile) <NEW_LINE> print("unset SESSION_MANAGER", file=ofile) <NEW_LINE> if answer[0].lower() == 'g': <NEW_LINE> <INDENT> print("dbus-launch gnome-session", file=ofile) <NEW_LINE> <DEDENT> elif answer[0].lower() == 'k': <NEW_LINE> <INDENT> print("dbus-launch startkde", file=ofile) <NEW_LINE> <DEDENT> elif answer[0].lower() == 'x': <NEW_LINE> <INDENT> print("dbus-launch startxfce4", file=ofile) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except OSError as exception: <NEW_LINE> <INDENT> raise SystemExit( f'{sys.argv[0]}: Cannot create ".vnc/xstartup" file.', ) from exception <NEW_LINE> <DEDENT> os.chmod(xstartup, int('755', 8) & ~self._umask) <NEW_LINE> <DEDENT> directory = os.path.dirname(self._vncserver.get_file()) <NEW_LINE> if ( 'PATH' in os.environ and directory not in os.environ['PATH'].split(os.pathsep) ): <NEW_LINE> <INDENT> os.environ['PATH'] = directory + os.pathsep + os.environ['PATH'] <NEW_LINE> <DEDENT> <DEDENT> def parse(self, args: List[str]) -> None: <NEW_LINE> <INDENT> self._vncserver = command_mod.Command( 'tigervncserver', pathextra=['/usr/bin'], errors='stop' ) <NEW_LINE> self._vncserver.set_args([ '-geometry', '1280x720', '-depth', '24', '-localhost', '-SecurityTypes', 'X509Vnc,TLSVnc', ] + args[1:]) <NEW_LINE> self._umask = os.umask(int('077', 8)) <NEW_LINE> os.umask(self._umask) <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> self._config() | Options class | 62598fc77d847024c075c6da |
class UnsupportedS3ArnError(BotoCoreError): <NEW_LINE> <INDENT> fmt = ( 'S3 ARN {arn} provided to "Bucket" parameter is invalid. Only ' 'ARNs for S3 access-points are supported.' ) | Error when S3 arn provided to Bucket parameter is not supported | 62598fc763b5f9789fe85492 |
class User(Base): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> name = db.Column(db.String, nullable=False) <NEW_LINE> email = db.Column(db.String, nullable=False, unique=True) <NEW_LINE> _password_hash = db.Column(db.String) <NEW_LINE> @password <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return 'Password: Write Only' <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, password): <NEW_LINE> <INDENT> self._password_hash = bcrypt.generate_password_hash( password, 4 ).decode('utf-8') <NEW_LINE> <DEDENT> def verify_password(self, password): <NEW_LINE> <INDENT> return bcrypt.check_password_hash(self._password_hash, password) | User Model | 62598fc73346ee7daa3377d7 |
class IsOwnerOrReadOnly(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return rules.test_rule('can_read_datasource', request.user, obj) <NEW_LINE> <DEDENT> return obj.owner == request.user | Custom permission to only allow owners of an object to edit it. | 62598fc70fa83653e46f5204 |
class TestArticle(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.test_article = Article('', '', '', '', '', '', '') <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.test_article, Article)) | tests that article class is functional | 62598fc7f9cc0f698b1c5461 |
class Types: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> for i in p_data.types: <NEW_LINE> <INDENT> setattr(self, i, PokeType(i, **p_data.types[i])) <NEW_LINE> <DEDENT> for i in p_data.sub_types: <NEW_LINE> <INDENT> setattr(self, i, PokeSubType(i)) | Class to organize PokeTypes
ARGS:
p_data: p_data module | 62598fc7091ae35668704f47 |
class UserCodeGroupViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = UserCodeGroup.objects.all() <NEW_LINE> serializer_class = UserCodeGroupSerializer <NEW_LINE> parser_classes = (MultiPartParser, FormParser,) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> lookup_field = 'id' | API endpoint that allows users to be viewed or edited.
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions. | 62598fc73d592f4c4edbb1d0 |
class DonateDeviotCommand(sublime_plugin.WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> sublime.run_command('open_url', {'url': 'https://goo.gl/K0EpFU'}) | Show the Deviot github site.
Extends: sublime_plugin.WindowCommand | 62598fc77b180e01f3e491df |
class CreateArtificialDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, X_Mat, Y_Vec): <NEW_LINE> <INDENT> self.X_Mat = X_Mat <NEW_LINE> self.Y_Vec = Y_Vec <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.X_Mat.size()[0] <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> return [self.X_Mat[idx], self.Y_Vec[idx]] | Face Landmarks dataset. | 62598fc7956e5f7376df580d |
class TestCartesianToCylindrical(unittest.TestCase): <NEW_LINE> <INDENT> def test_cartesian_to_cylindrical(self): <NEW_LINE> <INDENT> np.testing.assert_almost_equal( cartesian_to_cylindrical(np.array([3, 1, 6])), np.array([3.16227766, 0.32175055, 6.00000000]), decimal=7, ) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical(np.array([-1, 9, 16])), np.array([9.05538514, 1.68145355, 16.00000000]), decimal=7, ) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical(np.array([6.3434, -0.9345, 18.5675])), np.array([6.41186508, -0.14626640, 18.56750000]), decimal=7, ) <NEW_LINE> <DEDENT> def test_n_dimensional_cartesian_to_cylindrical(self): <NEW_LINE> <INDENT> a_i = np.array([3, 1, 6]) <NEW_LINE> a_o = cartesian_to_cylindrical(a_i) <NEW_LINE> a_i = np.tile(a_i, (6, 1)) <NEW_LINE> a_o = np.tile(a_o, (6, 1)) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical(a_i), a_o, decimal=7 ) <NEW_LINE> a_i = np.reshape(a_i, (2, 3, 3)) <NEW_LINE> a_o = np.reshape(a_o, (2, 3, 3)) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical(a_i), a_o, decimal=7 ) <NEW_LINE> <DEDENT> @ignore_numpy_errors <NEW_LINE> def test_nan_cartesian_to_cylindrical(self): <NEW_LINE> <INDENT> cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] <NEW_LINE> cases = set(permutations(cases * 3, r=3)) <NEW_LINE> for case in cases: <NEW_LINE> <INDENT> a_i = np.array(case) <NEW_LINE> cartesian_to_cylindrical(a_i) | Define :func:`colour.algebra.coordinates.transformations.cartesian_to_cylindrical` definition unit tests methods. | 62598fc72c8b7c6e89bd3ae3 |
class TaxonomyAttributeSinglecodeValue(TaxonomyAttributeValue): <NEW_LINE> <INDENT> def __init__(self, attribute): <NEW_LINE> <INDENT> TaxonomyAttributeValue.__init__(self, attribute) <NEW_LINE> self.__code = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> raise NotImplementedError("taxonomy specific implementation is required") <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return self.__code == None <NEW_LINE> <DEDENT> @property <NEW_LINE> def code(self): <NEW_LINE> <INDENT> return self.__code <NEW_LINE> <DEDENT> def add_value(self, code): <NEW_LINE> <INDENT> self.__code = code <NEW_LINE> self.__is_empty = False | This class represent a valid taxonomy value that is composed
of a valid code | 62598fc7a05bb46b3848ab8a |
class tagRECT(obj.CType): <NEW_LINE> <INDENT> def get_tup(self): <NEW_LINE> <INDENT> return (self.left, self.top, self.right, self.bottom) | A class for window rects | 62598fc75fdd1c0f98e5e2ac |
class BlessingsStringFormatter(logbook.StringFormatter): <NEW_LINE> <INDENT> def __init__(self, format_string=None, colorizers=tuple()): <NEW_LINE> <INDENT> self.colorizers = colorizers <NEW_LINE> self.terminal = blessings.Terminal() <NEW_LINE> self.md5_cache = {} <NEW_LINE> if not format_string: <NEW_LINE> <INDENT> format_string = DEFAULT_FORMAT_STRING <NEW_LINE> <DEDENT> format_string += '{t.normal}' <NEW_LINE> super(BlessingsStringFormatter, self).__init__(format_string) <NEW_LINE> <DEDENT> def format_record(self, record, handler): <NEW_LINE> <INDENT> record = self.prepare_record(record) <NEW_LINE> kwargs = { 'record': record, 'handler': handler, 't': self.terminal, 'level_color': self.level_color(record), 'colorized_channel': self.colorize_channel(record.channel), } <NEW_LINE> try: <NEW_LINE> <INDENT> return self._formatter.format(**kwargs) <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> fmt = self._formatter.decode('ascii', 'replace') <NEW_LINE> return fmt.format(**kwargs) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> fmt = self._formatter.encode('ascii', 'replace') <NEW_LINE> return fmt.format(**kwargs) <NEW_LINE> <DEDENT> <DEDENT> def level_color(self, rc): <NEW_LINE> <INDENT> ret = '' <NEW_LINE> if rc.level_name in ('ERROR', 'CRITICAL'): <NEW_LINE> <INDENT> ret = self.terminal.red + self.terminal.bold <NEW_LINE> <DEDENT> if rc.level_name == 'WARNING': <NEW_LINE> <INDENT> ret = self.terminal.yellow + self.terminal.bold <NEW_LINE> <DEDENT> if rc.level_name == 'DEBUG': <NEW_LINE> <INDENT> ret = self.terminal.white <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def colorize_channel(self, channel): <NEW_LINE> <INDENT> sep = self.terminal.black + SEPARATOR <NEW_LINE> return sep.join(map(self.colorize, channel.split(SEPARATOR))) <NEW_LINE> <DEDENT> def colorize(self, string): <NEW_LINE> <INDENT> colorized = self.md5_cache.get(string) <NEW_LINE> if not colorized: <NEW_LINE> <INDENT> target = COUNTER_RXP.sub('', string) <NEW_LINE> md5 = hashlib.md5(target.encode()).hexdigest() <NEW_LINE> index = self.get_color(md5) <NEW_LINE> colorized = self.terminal.color(index) + string <NEW_LINE> self.md5_cache.update({string: colorized}) <NEW_LINE> <DEDENT> return colorized <NEW_LINE> <DEDENT> def get_color(self, md5): <NEW_LINE> <INDENT> return COLORS[int(md5, 16) % COLOR_LEN] <NEW_LINE> <DEDENT> def prepare_record(self, rc): <NEW_LINE> <INDENT> for colorizer in self.colorizers: <NEW_LINE> <INDENT> done, message = colorizer.colorize(rc.message) <NEW_LINE> rc.message = message <NEW_LINE> if done and colorizer.aborting is True: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return rc | StringFormatter subclass that gives access to blessings.Terminal().
This class adds the `t` object in the formatting string, which is an
instance of blessings.Terminal(). It also provides helper functions to
colorize the log level and log channel. | 62598fc7a8370b77170f06fa |
class MuteManager(BaseModelManager[Mute]): <NEW_LINE> <INDENT> MODEL_CLASS = Mute <NEW_LINE> def mute(self, expiration: datetime) -> Result[None]: <NEW_LINE> <INDENT> return self._execute_command('mute', {'expiration': int(expiration.timestamp())}) <NEW_LINE> <DEDENT> def can_mute(self) -> Result[bool]: <NEW_LINE> <INDENT> return self._execute_command('canMute') <NEW_LINE> <DEDENT> def unmute(self) -> Result[None]: <NEW_LINE> <INDENT> return self._execute_command('unmute') | Mute manager. It allows manage chat mute. | 62598fc7fbf16365ca7943d7 |
class ParameterStringDirectory(ParameterString): <NEW_LINE> <INDENT> pass | This is parameter whose contents are the name of a directory. | 62598fc750812a4eaa620d74 |
class Queue(HashHelper): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.items = [] <NEW_LINE> super(Queue, self).__init__() <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.items == [] <NEW_LINE> <DEDENT> def insert(self, item): <NEW_LINE> <INDENT> self.items.insert(0, item) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> return self.items.pop() <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.items) | A queue class | 62598fc73346ee7daa3377d8 |
class LineNumber(QWidget): <NEW_LINE> <INDENT> def __init__(self, editor): <NEW_LINE> <INDENT> QWidget.__init__(self, editor) <NEW_LINE> self.editor = editor <NEW_LINE> self.editor.blockCountChanged.connect(self.updateAreaWidth) <NEW_LINE> self.editor.updateRequest.connect(self.updateLineNumber) <NEW_LINE> self._flaged_lines = [] <NEW_LINE> self.updateAreaWidth() <NEW_LINE> <DEDENT> def resizeEvent(self, event): <NEW_LINE> <INDENT> cr = QRect(self.editor.contentsRect()) <NEW_LINE> self.setGeometry(QRect(cr.left(), cr.top(), self.areaWidth(), cr.height())) <NEW_LINE> <DEDENT> def updateLineNumber(self, rect, num): <NEW_LINE> <INDENT> if num: <NEW_LINE> <INDENT> self.scroll(0, num) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.update(0, rect.y(), self.width(), rect.height()) <NEW_LINE> <DEDENT> if rect.contains(self.editor.viewport().rect()): <NEW_LINE> <INDENT> self.updateAreaWidth() <NEW_LINE> <DEDENT> <DEDENT> def updateAreaWidth(self, width = 0): <NEW_LINE> <INDENT> self.editor.setViewportMargins(self.areaWidth(), 0, 0, 0) <NEW_LINE> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> return QSize(self.areaWidth(), 0) <NEW_LINE> <DEDENT> def areaWidth(self): <NEW_LINE> <INDENT> digits = 3 <NEW_LINE> max_ = max(1, self.editor.blockCount()) <NEW_LINE> while max_ >= 1000: <NEW_LINE> <INDENT> max_ /= 1000 <NEW_LINE> digits += 1 <NEW_LINE> <DEDENT> return 26 + self.editor.fontMetrics().width(QChar('9')) * digits <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> painter = QPainter(self) <NEW_LINE> painter.fillRect(event.rect(), Qt.lightGray) <NEW_LINE> painter.setPen(Qt.black) <NEW_LINE> block = QTextBlock(self.editor.firstVisibleBlock()) <NEW_LINE> blockNumber = block.blockNumber() <NEW_LINE> top = int(self.editor.blockBoundingGeometry(block).translated(self.editor.contentOffset()).top()) <NEW_LINE> bottom = top + int(self.editor.blockBoundingRect(block).height()) <NEW_LINE> while block.isValid() and (top <= event.rect().bottom()): <NEW_LINE> <INDENT> if block.isVisible() and (bottom >= event.rect().top()): <NEW_LINE> <INDENT> number = QString.number(blockNumber + 1) <NEW_LINE> painter.drawText(0, top, self.width() - 4, self.editor.fontMetrics().height(), Qt.AlignRight, number) <NEW_LINE> if blockNumber + 1 in self._flaged_lines: <NEW_LINE> <INDENT> painter.drawPixmap(0, top, QPixmap(':/icons/warning.png')) <NEW_LINE> <DEDENT> <DEDENT> block = block.next() <NEW_LINE> top = bottom <NEW_LINE> bottom = top + int(self.editor.blockBoundingRect(block).height()) <NEW_LINE> blockNumber += 1 | Line Number widget for RstTextEdit component | 62598fc7377c676e912f6f05 |
class Tree(object): <NEW_LINE> <INDENT> def __init__(self, base_pipeline): <NEW_LINE> <INDENT> self.base_pipeline = base_pipeline <NEW_LINE> self.logger = logging.getLogger(__name__+'.Tree') <NEW_LINE> self.logger.info('This will be deprecated!') <NEW_LINE> self.failing = [] <NEW_LINE> self.stopped = [] <NEW_LINE> self.centrality = {} <NEW_LINE> self.ancestors = {} <NEW_LINE> self.ancestor_groups = {} <NEW_LINE> self.pipelines = {} <NEW_LINE> <DEDENT> def add_pipeline(self, pipeline): <NEW_LINE> <INDENT> assert pipeline.name not in self.pipelines <NEW_LINE> self.pipelines[pipeline.name] = pipeline <NEW_LINE> if pipeline.is_stopped(): <NEW_LINE> <INDENT> self.stopped.append(pipeline.name) <NEW_LINE> <DEDENT> if pipeline.is_failing(): <NEW_LINE> <INDENT> self.failing.append(pipeline.name) <NEW_LINE> <DEDENT> <DEDENT> def get_pipeline_blockers(self, pipeline_name): <NEW_LINE> <INDENT> assert pipeline_name in self.pipelines.keys() <NEW_LINE> blockers = [] <NEW_LINE> for ancestor_name in self.ancestors[pipeline_name]: <NEW_LINE> <INDENT> if self.centrality[ancestor_name] is 0: continue <NEW_LINE> ancestor = self.pipelines[ancestor_name] <NEW_LINE> if ancestor.is_stopped() or ancestor.is_failing(): <NEW_LINE> <INDENT> blockers.append(ancestor) <NEW_LINE> <DEDENT> <DEDENT> return(blockers) <NEW_LINE> <DEDENT> def get_status_from_base(self, pipeline_name=None): <NEW_LINE> <INDENT> if pipeline_name is None: <NEW_LINE> <INDENT> pipeline_name = self.base_pipeline <NEW_LINE> <DEDENT> pipeline = self.pipelines[pipeline_name] <NEW_LINE> base_status = pipeline.get_status() <NEW_LINE> base_status['ancestor_groups'] = self.ancestor_groups[pipeline.name] <NEW_LINE> info = { 'base_name': pipeline_name, 'base_status': base_status, 'blocking': {}, 'schema_version': '1.1.0', } <NEW_LINE> blockers = self.get_pipeline_blockers(pipeline_name) <NEW_LINE> for ancestor in blockers: <NEW_LINE> <INDENT> status = ancestor.get_status() <NEW_LINE> status['ancestor_groups'] = self.ancestor_groups[ancestor.name] <NEW_LINE> info['blocking'][ancestor.name] = status <NEW_LINE> <DEDENT> human_status = 'passing' <NEW_LINE> if len(info['blocking']) > 0: <NEW_LINE> <INDENT> human_status = 'blocked' <NEW_LINE> <DEDENT> if pipeline.is_failing(): <NEW_LINE> <INDENT> human_status = 'failing' <NEW_LINE> <DEDENT> info['status'] = human_status <NEW_LINE> return info <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> string = '' <NEW_LINE> string += 'ancestors: %s\n'% pprint.pformat( self.ancestors) <NEW_LINE> string += 'centrality: %s\n'% pprint.pformat( self.centrality) <NEW_LINE> string += 'failing: %s\n'% pprint.pformat( self.failing) <NEW_LINE> string += 'stopped: %s\n'% pprint.pformat( self.stopped) <NEW_LINE> string += 'ancestor_groups: %s\n'% pprint.pformat( self.ancestor_groups) <NEW_LINE> return(string) | This object contains a tree of pipelines, expanding out from a
base pipeline. | 62598fc7f9cc0f698b1c5462 |
class HTTPClient(object): <NEW_LINE> <INDENT> def __init__(self, endpoint_url, cert=None, key=None, cacert=None): <NEW_LINE> <INDENT> self.VERSION = 'v1' <NEW_LINE> self.endpoint_url = endpoint_url <NEW_LINE> self.cert = None <NEW_LINE> if cert is not None and key is not None: <NEW_LINE> <INDENT> self.cert = (cert, key) <NEW_LINE> <DEDENT> self.cacert = cacert <NEW_LINE> <DEDENT> def urljoin(self, path): <NEW_LINE> <INDENT> data = list(urlparse.urlsplit(self.endpoint_url)) <NEW_LINE> pieces = [self.VERSION] + path.split('/') <NEW_LINE> path = '/'.join(s.strip('/') for s in pieces) <NEW_LINE> data[2] = path <NEW_LINE> return urlparse.urlunsplit(data) <NEW_LINE> <DEDENT> def _get(self, path, params=None): <NEW_LINE> <INDENT> url = self.urljoin(path) <NEW_LINE> return requests.get(url, params=params, cert=self.cert, verify=self.cacert) <NEW_LINE> <DEDENT> def _post(self, path, body): <NEW_LINE> <INDENT> url = self.urljoin(path) <NEW_LINE> return requests.post(url, data=body, cert=self.cert, verify=self.cacert) <NEW_LINE> <DEDENT> def _delete(self, path): <NEW_LINE> <INDENT> url = self.urljoin(path) <NEW_LINE> return requests.delete(url, cert=self.cert, verify=self.cacert) | Wrapper class for HTTP methods. | 62598fc7fff4ab517ebcdb08 |
class ParamTable(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._params = {} <NEW_LINE> <DEDENT> def add(self, param: Param): <NEW_LINE> <INDENT> if not isinstance(param, Param): <NEW_LINE> <INDENT> raise TypeError("Only accepts a Param instance.") <NEW_LINE> <DEDENT> if param.name in self._params: <NEW_LINE> <INDENT> msg = f"Parameter named {param.name} already exists.\n" f"To re-assign parameter {param.name} value, " f"use `params[\"{param.name}\"] = value` instead." <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> self._params[param.name] = param <NEW_LINE> <DEDENT> def get(self, key) -> Param: <NEW_LINE> <INDENT> return self._params[key] <NEW_LINE> <DEDENT> def set(self, key, param: Param): <NEW_LINE> <INDENT> if not isinstance(param, Param): <NEW_LINE> <INDENT> raise ValueError("Only accepts a Param instance.") <NEW_LINE> <DEDENT> self._params[key] = param <NEW_LINE> <DEDENT> @property <NEW_LINE> def hyper_space(self) -> dict: <NEW_LINE> <INDENT> full_space = {} <NEW_LINE> for param in self: <NEW_LINE> <INDENT> if param.hyper_space is not None: <NEW_LINE> <INDENT> param_space = param.hyper_space <NEW_LINE> if isinstance(param_space, hyper_spaces.HyperoptProxy): <NEW_LINE> <INDENT> param_space = param_space.convert(param.name) <NEW_LINE> <DEDENT> full_space[param.name] = param_space <NEW_LINE> <DEDENT> <DEDENT> return full_space <NEW_LINE> <DEDENT> def to_frame(self) -> pd.DataFrame: <NEW_LINE> <INDENT> df = pd.DataFrame(data={ 'Name': [p.name for p in self], 'Description': [p.desc for p in self], 'Value': [p.value for p in self], 'Hyper-Space': [p.hyper_space for p in self] }, columns=['Name', 'Description', 'Value', 'Hyper-Space']) <NEW_LINE> return df <NEW_LINE> <DEDENT> def __getitem__(self, key: str) -> typing.Any: <NEW_LINE> <INDENT> return self._params[key].value <NEW_LINE> <DEDENT> def __setitem__(self, key: str, value: typing.Any): <NEW_LINE> <INDENT> self._params[key].value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '\n'.join(param.name.ljust(30) + str(param.value) for param in self._params.values()) <NEW_LINE> <DEDENT> def __iter__(self) -> typing.Iterator: <NEW_LINE> <INDENT> yield from self._params.values() <NEW_LINE> <DEDENT> def completed(self, exclude: typing.Optional[list] = None) -> bool: <NEW_LINE> <INDENT> return all(param for param in self if param.name not in exclude) <NEW_LINE> <DEDENT> def keys(self) -> collections.abc.KeysView: <NEW_LINE> <INDENT> return self._params.keys() <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self._params <NEW_LINE> <DEDENT> def update(self, other: dict): <NEW_LINE> <INDENT> for key in other: <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> self[key] = other[key] | Parameter table class.
Example:
>>> params = ParamTable()
>>> params.add(Param('ham', 'Parma Ham'))
>>> params.add(Param('egg', 'Over Easy'))
>>> params['ham']
'Parma Ham'
>>> params['egg']
'Over Easy'
>>> print(params)
ham Parma Ham
egg Over Easy
>>> params.add(Param('egg', 'Sunny side Up'))
Traceback (most recent call last):
...
ValueError: Parameter named egg already exists.
To re-assign parameter egg value, use `params["egg"] = value` instead. | 62598fc771ff763f4b5e7a9f |
class TestWSAEVENT(ObjectBaseTestCase): <NEW_LINE> <INDENT> OBJECT_CLASS = WSAEVENT <NEW_LINE> def cast_from_value(self, int_data): <NEW_LINE> <INDENT> ffi, _ = dist.load() <NEW_LINE> cdata = ffi.new(self.OBJECT_CLASS.C_TYPE) <NEW_LINE> cdata[0] = ffi.cast(self.OBJECT_CLASS.__name__, int_data) <NEW_LINE> return self.OBJECT_CLASS(cdata[0]) | Tests for :class:`pywincffi.wintypes.WSAEVENT` | 62598fc7656771135c489990 |
class Douglas2013TestCaseSD010Q200K020(Douglas2013TestCaseSD001Q200K005): <NEW_LINE> <INDENT> GSIM_CLASS = dst.DouglasEtAl2013StochasticSD010Q200K020 <NEW_LINE> MEAN_FILE = 'DOUG2013/DOUGLAS_2013_STOCHASTIC_MEAN_SD010Q0200K020.csv' <NEW_LINE> STD_FILE = 'DOUG2013/DOUGLAS_2013_STOCHASTIC_STD_SD010Q0200K020.csv' <NEW_LINE> INTER_FILE = 'DOUG2013/DOUGLAS_2013_STOCHASTIC_INTER_SD010Q0200K020.csv' <NEW_LINE> INTRA_FILE = 'DOUG2013/DOUGLAS_2013_STOCHASTIC_INTRA_SD010Q0200K020.csv' | Tests the Douglas et al (2013) stochastic GMPE.
SD = 010 Q = 200 K = 0.020 | 62598fc77c178a314d78d7c0 |
class TUI(UI): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.outputDst = TerminalOutput() <NEW_LINE> self.inputSrc = TerminalInput() <NEW_LINE> <DEDENT> def get_str(self) -> str: <NEW_LINE> <INDENT> return self.inputSrc.get() <NEW_LINE> <DEDENT> def get_num(self, any=False) -> Union[int, float]: <NEW_LINE> <INDENT> input_str = self.get_str() <NEW_LINE> try: <NEW_LINE> <INDENT> if float(input_str): <NEW_LINE> <INDENT> if int(float(input_str)): <NEW_LINE> <INDENT> return int(float(input_str)) <NEW_LINE> <DEDENT> return float(input_str) <NEW_LINE> <DEDENT> elif input_str == "0": <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if any is True: <NEW_LINE> <INDENT> return input_str <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def output(self, string: str) -> None: <NEW_LINE> <INDENT> self.outputDst.put(string) <NEW_LINE> <DEDENT> def prompt(self, prompt: Prompt): <NEW_LINE> <INDENT> self.output(prompt.message) <NEW_LINE> response = None <NEW_LINE> if prompt.type == Any: <NEW_LINE> <INDENT> response = self.get_num(any=True) <NEW_LINE> try: <NEW_LINE> <INDENT> response = int(response) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif prompt.type == str: <NEW_LINE> <INDENT> response = self.get_str() <NEW_LINE> <DEDENT> elif prompt.type in [int, float]: <NEW_LINE> <INDENT> response = self.get_num() <NEW_LINE> <DEDENT> return response | Implements a user interface (UI) in a terminal setting. | 62598fc74a966d76dd5ef1f6 |
class TestV1LaunchSecurity(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1LaunchSecurity(self): <NEW_LINE> <INDENT> pass | V1LaunchSecurity unit test stubs | 62598fc7ab23a570cc2d4efe |
class Quadrant(object): <NEW_LINE> <INDENT> def __init__(self, x, f): <NEW_LINE> <INDENT> self.x = np.asarray(x) <NEW_LINE> self.f = np.asarray(f) <NEW_LINE> self.n = float(sum(self.x)) <NEW_LINE> self.m = float(sum(self.f)) <NEW_LINE> self.k = len(self.x) <NEW_LINE> self.var = self.variance() <NEW_LINE> self.mean = sum(self.x * self.f) / self.m <NEW_LINE> self.chi_square = None <NEW_LINE> self.test_statistic() <NEW_LINE> self.test_stat = self.chi_square <NEW_LINE> <DEDENT> def variance(self): <NEW_LINE> <INDENT> var = (sum([self.f[i]*self.x[i]**2 for i in range(self.k)]) - (sum([(self.f[i]*self.x[i]) for i in range(self.k)])**2 / self.m)) / (self.m - 1.0) <NEW_LINE> return var <NEW_LINE> <DEDENT> def test_statistic(self): <NEW_LINE> <INDENT> self.chi_square = (self.var / self.mean) * (self.m - 1.0) | Determine whether a random (Poisson) process has generated a
point pattern.
Requirements
------------
1. Randaom sample of points from a population.
2. Sample points are independently selected.
Null Hypthothesis
-----------------
VMR = 1 (point pattern is random)
Test Statistic
--------------
Chi-Square = VMR*(m - 1)
where
VMR = Variance / Mean
m = NumberOfCells
Notes:
What is df in this case? The total number of points or
the number of cells? | 62598fc75fdd1c0f98e5e2ae |
class TestAuthorizeRequest: <NEW_LINE> <INDENT> def test_calculated_length(self): <NEW_LINE> <INDENT> payload = AuthorizeRequest(key=12345678) <NEW_LINE> assert payload.calculated_length() == 5 <NEW_LINE> <DEDENT> def test_from_knx(self): <NEW_LINE> <INDENT> payload = AuthorizeRequest() <NEW_LINE> payload.from_knx(bytes([0x03, 0xD1, 0x00, 0x00, 0xBC, 0x61, 0x4E])) <NEW_LINE> assert payload == AuthorizeRequest(key=12345678) <NEW_LINE> <DEDENT> def test_to_knx(self): <NEW_LINE> <INDENT> payload = AuthorizeRequest(key=12345678) <NEW_LINE> assert payload.to_knx() == bytes([0x03, 0xD1, 0x00, 0x00, 0xBC, 0x61, 0x4E]) <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> payload = AuthorizeRequest(key=12345678) <NEW_LINE> assert str(payload) == '<AuthorizeRequest key="12345678" />' | Test class for AuthorizeRequest objects. | 62598fc7d8ef3951e32c7fec |
class ModelDocument(Document, ToSonDocumentMixin): <NEW_LINE> <INDENT> __metaclass__ = ModelDocumentMetaclass <NEW_LINE> my_metaclass = None <NEW_LINE> meta = { 'abstract': True, 'queryset_class': ModelQuerySet, } <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.label: <NEW_LINE> <INDENT> return u'%s ("%s")' % (self.id, self.label) <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return unicode(self.id) | A base class for all models.
This uses Flask-MongoEngine as a base, to provide extra convenience methods. | 62598fc7851cf427c66b85d6 |
class OccurrenceReplacer(object): <NEW_LINE> <INDENT> def __init__(self, persisted_occurrences): <NEW_LINE> <INDENT> lookup = [((occ.event, occ.original_start, occ.original_end), occ) for occ in persisted_occurrences] <NEW_LINE> self.lookup = dict(lookup) <NEW_LINE> <DEDENT> def get_occurrence(self, occ): <NEW_LINE> <INDENT> return self.lookup.pop( (occ.event, occ.original_start, occ.original_end), occ) <NEW_LINE> <DEDENT> def has_occurrence(self, occ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (occ.event, occ.original_start, occ.original_end) in self.lookup <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> if not self.lookup: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('A problem with checking if a persisted occurence exists has occured!') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_additional_occurrences(self, start, end): <NEW_LINE> <INDENT> return [occ for _, occ in list(self.lookup.items()) if (occ.start < end and occ.end >= start and not occ.cancelled)] | When getting a list of occurrences, the last thing that needs to be done
before passing it forward is to make sure all of the occurrences that
have been stored in the datebase replace, in the list you are returning,
the generated ones that are equivalent. This class makes this easier. | 62598fc7ad47b63b2c5a7b7b |
class Board: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.places = {} <NEW_LINE> self.white_pieces = [] <NEW_LINE> self.black_pieces = [] <NEW_LINE> self.reset_board() <NEW_LINE> <DEDENT> def reset_board(self): <NEW_LINE> <INDENT> self.places.clear() <NEW_LINE> self.white_pieces.clear() <NEW_LINE> self.black_pieces.clear() <NEW_LINE> self.white_pieces.extend([Rook('White'), Knight('White'), Bishop('White'), Queen('White'), King('White'), Bishop('White'), Knight('White'), Rook('White')]) <NEW_LINE> self.black_pieces.extend([Rook('Black'), Knight('Black'), Bishop('Black'), Queen('Black'), King('Black'), Bishop('Black'), Knight('Black'), Rook('Black')]) <NEW_LINE> row, color, pieces = 1, 'White', self.white_pieces <NEW_LINE> while row <= 8: <NEW_LINE> <INDENT> piece = 0 <NEW_LINE> for column in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']: <NEW_LINE> <INDENT> self.places['{0}{1}'.format(column, row)] = Place(column, row, pieces[piece]) <NEW_LINE> piece += 1 <NEW_LINE> <DEDENT> row, color, pieces = row + 7, 'Black', self.black_pieces <NEW_LINE> <DEDENT> self.white_pieces.extend([Pawn('White'), Pawn('White'), Pawn('White'), Pawn('White'), Pawn('White'), Pawn('White'), Pawn('White'), Pawn('White')]) <NEW_LINE> self.black_pieces.extend([Pawn('Black'), Pawn('Black'), Pawn('Black'), Pawn('Black'), Pawn('Black'), Pawn('Black'), Pawn('Black'), Pawn('Black')]) <NEW_LINE> row, color, pieces = 2, 'White', self.white_pieces <NEW_LINE> while row <= 7: <NEW_LINE> <INDENT> piece = 8 <NEW_LINE> for column in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']: <NEW_LINE> <INDENT> self.places['{0}{1}'.format(column, row)] = Place(column, row, pieces[piece]) <NEW_LINE> piece += 1 <NEW_LINE> <DEDENT> row, color, pieces = row + 5, 'Black', self.black_pieces <NEW_LINE> <DEDENT> for p in self.white_pieces + self.black_pieces: <NEW_LINE> <INDENT> p.board = self <NEW_LINE> <DEDENT> for row in range(3, 7): <NEW_LINE> <INDENT> for column in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']: <NEW_LINE> <INDENT> self.places['{0}{1}'.format(column, row)] = Place(column, row) <NEW_LINE> <DEDENT> <DEDENT> for p in self.places.values(): <NEW_LINE> <INDENT> p.board = self | Board abstraction that contains a dictionary of 64 place objects along with 2 lists that contain
all white and black pieces that haven't been captured | 62598fc7ab23a570cc2d4eff |
class ChatSession(asynchat.async_chat): <NEW_LINE> <INDENT> def __init__(self, server, sock): <NEW_LINE> <INDENT> asynchat.async_chat.__init__(self, sock) <NEW_LINE> self.server = server <NEW_LINE> self.set_terminator('\r\n'.encode('utf-8')) <NEW_LINE> self.data = [] <NEW_LINE> self.usr_name = '' <NEW_LINE> self.entered_rooms = {} <NEW_LINE> self.room_judger = RoomJudger() <NEW_LINE> self.enter(self.server.hall) <NEW_LINE> self.AESKey_is_init = False <NEW_LINE> self.RSAinstance = RSAmessage() <NEW_LINE> self.AESinstance = AESmessage('') <NEW_LINE> send_dict = dict(type='init', msg='RSApubKey', Key=str(self.RSAinstance.pubKey, encoding='utf-8')) <NEW_LINE> send_json = json.dumps(send_dict) <NEW_LINE> self.SecurityPush((send_json + '\r\n').encode('utf-8')) <NEW_LINE> <DEDENT> def enter(self, room): <NEW_LINE> <INDENT> if room.room_name in self.entered_rooms: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.entered_rooms[room.room_name] = room <NEW_LINE> self.entered_rooms[room.room_name].add_session(self) <NEW_LINE> <DEDENT> def collect_incoming_data(self, data): <NEW_LINE> <INDENT> if self.AESKey_is_init: <NEW_LINE> <INDENT> if data == '\r\n'.encode('utf-8'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = self.AESinstance.AESDecrypt(data) <NEW_LINE> self.data.append(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data.append(data.decode('utf-8')) <NEW_LINE> <DEDENT> <DEDENT> def found_terminator(self): <NEW_LINE> <INDENT> line = ''.join(self.data) <NEW_LINE> self.data = [] <NEW_LINE> room_name = self.room_judger.get_room_name(line) <NEW_LINE> try: <NEW_LINE> <INDENT> self.entered_rooms[room_name].handle(self, line) <NEW_LINE> <DEDENT> except EndSession: <NEW_LINE> <INDENT> self.handle_close() <NEW_LINE> <DEDENT> <DEDENT> def handle_close(self): <NEW_LINE> <INDENT> asynchat.async_chat.handle_close(self) <NEW_LINE> <DEDENT> def SecurityPush(self, sendbuffer): <NEW_LINE> <INDENT> if self.AESKey_is_init: <NEW_LINE> <INDENT> sendbuffer = self.AESinstance.AESEncript(str(sendbuffer, encoding='utf-8')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.push(sendbuffer) | 处理与单个用户的通信会话,将socket变为异步的
这个会话类型用于chat-style (command/response) protocols
因此文件协议需要另外的设计 | 62598fc7d8ef3951e32c7fed |
class testDA_visualize(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> np.random.seed(0) <NEW_LINE> N = 150 <NEW_LINE> p = 2 <NEW_LINE> n_classes = 3 <NEW_LINE> X, y_cls = datasets.make_classification(n_samples=N, n_features=p, n_informative=p, n_redundant=0, n_clusters_per_class=1, n_classes=n_classes, weights=[0.3, 0.5]) <NEW_LINE> cls.N, cls.p, cls.n_classes = N, p, n_classes <NEW_LINE> cls.X, cls.y_cls = X, y_cls <NEW_LINE> return <NEW_LINE> <DEDENT> def test000_ML(self): <NEW_LINE> <INDENT> X, y_cls = self.X, self.y_cls <NEW_LINE> DA = DiscriminantAnalysis() <NEW_LINE> DA.fit(X, y_cls, method=MAXIMUM_LIKELIHOOD) <NEW_LINE> visualize_3class(X, y_cls, DA, title="ML Decision Boundaries", save_file="./figures/ML_boundaries.png") <NEW_LINE> return <NEW_LINE> <DEDENT> def test004_ML_diag(self): <NEW_LINE> <INDENT> X, y_cls = self.X, self.y_cls <NEW_LINE> DA = DiscriminantAnalysis(diag_cov=True) <NEW_LINE> DA.fit(X, y_cls, method=MAXIMUM_LIKELIHOOD) <NEW_LINE> visualize_3class(X, y_cls, DA, title="ML Decision Boundaries", save_file="./figures/ML_diag_cov.png") <NEW_LINE> return <NEW_LINE> <DEDENT> def test001_MAP(self): <NEW_LINE> <INDENT> X, y_cls = self.X, self.y_cls <NEW_LINE> DA = DiscriminantAnalysis() <NEW_LINE> DA.fit(X, y_cls, method=BAYES_MAP) <NEW_LINE> visualize_3class(X, y_cls, DA, title="MAP Decision Boundaries", save_file="./figures/MAP_boundaries.png") <NEW_LINE> return <NEW_LINE> <DEDENT> def test002_MEAN(self): <NEW_LINE> <INDENT> X, y_cls = self.X, self.y_cls <NEW_LINE> DA = DiscriminantAnalysis() <NEW_LINE> DA.fit(X, y_cls, method=BAYES_MEAN) <NEW_LINE> visualize_3class(X, y_cls, DA, title="Posterior Mean Decision Boundaries", save_file="./figures/MEAN_boundaries.png") <NEW_LINE> return <NEW_LINE> <DEDENT> def test003_FULL(self): <NEW_LINE> <INDENT> X, y_cls = self.X, self.y_cls <NEW_LINE> DA = DiscriminantAnalysis() <NEW_LINE> DA.fit(X, y_cls, method=BAYES_FULL) <NEW_LINE> visualize_3class(X, y_cls, DA, title="Full Bayes Decision Boundaries", save_file="./figures/FULL_boundaries.png") <NEW_LINE> return | Some 2D classification visualizations | 62598fc750812a4eaa620d76 |
class TestMetaClasses: <NEW_LINE> <INDENT> def test_no_config_path(self): <NEW_LINE> <INDENT> class DummyApplication(p_cli.ProsperApplication): <NEW_LINE> <INDENT> PROGNAME = 'DUMMY' <NEW_LINE> VERSION = '0.0.0' <NEW_LINE> here_path = HERE <NEW_LINE> def main(self): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> <DEDENT> with pytest.raises(NotImplementedError): <NEW_LINE> <INDENT> dummy = DummyApplication() <NEW_LINE> <DEDENT> <DEDENT> def test_config_path_happypath(self): <NEW_LINE> <INDENT> class DummyApplication(p_cli.ProsperApplication): <NEW_LINE> <INDENT> PROGNAME = 'DUMMY' <NEW_LINE> VERSION = '0.0.0' <NEW_LINE> here_path = HERE <NEW_LINE> config_path = LOCAL_CONFIG_PATH <NEW_LINE> def main(self): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> <DEDENT> dummy = DummyApplication(__file__) <NEW_LINE> <DEDENT> def test_app_properties_logger_verbose(self): <NEW_LINE> <INDENT> class DummyVerboseApplication(p_cli.ProsperApplication): <NEW_LINE> <INDENT> PROGNAME = 'DUMMYVERBOSE' <NEW_LINE> VERSION = '0.0.0' <NEW_LINE> here_path = HERE <NEW_LINE> config_path = LOCAL_CONFIG_PATH <NEW_LINE> def main(self): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> <DEDENT> dummy_v = DummyVerboseApplication(__file__) <NEW_LINE> dummy_v.verbose = True <NEW_LINE> assert dummy_v._logger is None <NEW_LINE> assert isinstance(dummy_v.logger, logging.Logger) <NEW_LINE> handler_types = [type(handler) for handler in dummy_v.logger.handlers] <NEW_LINE> assert logging.StreamHandler in handler_types <NEW_LINE> assert p_logging.HackyDiscordHandler not in handler_types <NEW_LINE> assert p_logging.HackySlackHandler not in handler_types <NEW_LINE> assert p_logging.HackyHipChatHandler not in handler_types <NEW_LINE> <DEDENT> def test_app_properties_logger_normal(self): <NEW_LINE> <INDENT> class DummyApplication(p_cli.ProsperApplication): <NEW_LINE> <INDENT> PROGNAME = 'DUMMY' <NEW_LINE> VERSION = '0.0.0' <NEW_LINE> here_path = HERE <NEW_LINE> config_path = LOCAL_CONFIG_PATH <NEW_LINE> def main(self): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> <DEDENT> dummy = DummyApplication(__file__) <NEW_LINE> assert dummy._logger is None <NEW_LINE> assert isinstance(dummy.logger, logging.Logger) <NEW_LINE> handler_types = [type(handler) for handler in dummy.logger.handlers] <NEW_LINE> assert p_logging.HackyDiscordHandler in handler_types <NEW_LINE> assert p_logging.HackySlackHandler in handler_types <NEW_LINE> assert logging.StreamHandler not in handler_types <NEW_LINE> <DEDENT> def test_app_properties_config(self): <NEW_LINE> <INDENT> class DummyApplication(p_cli.ProsperApplication): <NEW_LINE> <INDENT> PROGNAME = 'DUMMY' <NEW_LINE> VERSION = '0.0.0' <NEW_LINE> here_path = HERE <NEW_LINE> config_path = LOCAL_CONFIG_PATH <NEW_LINE> def main(self): <NEW_LINE> <INDENT> return 'yes' <NEW_LINE> <DEDENT> <DEDENT> dummy = DummyApplication(__file__) <NEW_LINE> assert isinstance(dummy.config, p_config.ProsperConfig) | validate expected errors from abc | 62598fc760cbc95b06364661 |
class DashboardPageExtended(DashboardPage): <NEW_LINE> <INDENT> url = LOGIN_BASE_URL + '/home' <NEW_LINE> def is_browser_on_page(self): <NEW_LINE> <INDENT> return self.q(css='.courses.courses-tab.active').visible <NEW_LINE> <DEDENT> def select_course(self, course_title): <NEW_LINE> <INDENT> query = self.q(xpath=f'//h3[contains(text(), "{course_title}")]').first <NEW_LINE> if course_title in query.text: <NEW_LINE> <INDENT> query.click() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise BrokenPromise('Course title not found') <NEW_LINE> <DEDENT> <DEDENT> def click_logout_button(self): <NEW_LINE> <INDENT> self.wait_for_element_visibility( '.account-username', 'Username drop down visibility' ) <NEW_LINE> self.q(css='.account-username').click() <NEW_LINE> self.wait_for_element_visibility( '.title.is-selected', 'Sign out button visibility' ) <NEW_LINE> self.q(css='.action-signout').click() <NEW_LINE> <DEDENT> def click_view_live_button(self): <NEW_LINE> <INDENT> disable_animations(self) <NEW_LINE> course_info = get_course_info() <NEW_LINE> course_key = get_course_key({ 'course_org': course_info['org'], 'course_num': course_info['number'], 'course_run': course_info['run'] }) <NEW_LINE> self.browser.execute_script( "document.querySelectorAll('[data-course-key = \"" "{}\"] .view-button')[0].click();".format(str(course_key))) <NEW_LINE> self.browser.switch_to_window(self.browser.window_handles[-1]) <NEW_LINE> <DEDENT> def click_terms_of_service(self): <NEW_LINE> <INDENT> self.q( css='a[href="' + LMS_REDIRECT_URL + '/edx-terms-service"]' ).click() <NEW_LINE> <DEDENT> def click_privacy_policy(self): <NEW_LINE> <INDENT> self.q( css='a[href="' + LMS_REDIRECT_URL + '/edx-privacy-policy"]' ).click() | This class is an extended class of Studio Dashboard Page,
where we add methods that are different or not used in DashboardPage | 62598fc70fa83653e46f520a |
class CanFdIsoMode(enum.Enum): <NEW_LINE> <INDENT> ISO = _cconsts.NX_CAN_FD_MODE_ISO <NEW_LINE> NON_ISO = _cconsts.NX_CAN_FD_MODE_NON_ISO <NEW_LINE> ISO_LEGACY = _cconsts.NX_CAN_FD_MODE_ISO_LEGACY | CAN FD ISO MODE.
Values:
ISO:
ISO CAN FD standard (ISO standard 11898-1:2015)
In ISO CAN FD mode, for every transmitted frame, you can specify in
the database or frame header whether a frame must be sent in CAN
2.0, CAN FD, or CAN FD+BRS mode. In the frame type field of the
frame header, received frames indicate whether they have been sent
with CAN 2.0, CAN FD, or CAN FD+BRS. You cannot use the
Interface:CAN:Transmit I/O Mode property in ISO CAN FD mode, as the
frame defines the transmit mode.
NON_ISO:
non-ISO CAN FD standard (Bosch CAN FD 1.0 specification)
In Non-ISO CAN FD mode, CAN data frames are received at CAN
data typed frames, which is either CAN 2.0, CAN FD, or CAN FD+BRS,
but you cannot distinguish the standard in which the frame has been
transmitted.
ISO_LEGACY:
You also can set the mode to Legacy ISO mode. In this mode,
the behavior is the same as in Non-ISO CAN FD mode
(Interface:CAN:Transmit I/O Mode is working, and received frames
have the CAN data type). But the interface is working in ISO CAN FD
mode, so you can communicate with other ISO CAN FD devices. Use this
mode only for compatibility with existing applications. | 62598fc73346ee7daa3377da |
class TestError(Error): <NEW_LINE> <INDENT> params = 'items' <NEW_LINE> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return ''.join('\n\n* ' + item for item in self.env['items']) | Some error. | 62598fc7f9cc0f698b1c5464 |
class FileWrapper(FileLikeWrapper): <NEW_LINE> <INDENT> @deprecated_str_to_path(1, "source") <NEW_LINE> def __init__( self, source: PathOrFile, mode: ModeArg = "w", compression: CompressionArg = False, name: Union[str, PurePath] = None, close_fileobj: bool = True, memory_mapped: bool = False, **kwargs, ) -> None: <NEW_LINE> <INDENT> if isinstance(source, Path): <NEW_LINE> <INDENT> self._path = source <NEW_LINE> source_fileobj = xopen(source, mode=mode, compression=compression, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source_fileobj = cast(FileLike, source) <NEW_LINE> if name is None and hasattr(source_fileobj, "name"): <NEW_LINE> <INDENT> name = str(getattr(source_fileobj, "name")) <NEW_LINE> <DEDENT> self._path = Path(name) if name else None <NEW_LINE> <DEDENT> if hasattr(source_fileobj, "mode"): <NEW_LINE> <INDENT> mode = getattr(source_fileobj, "mode") <NEW_LINE> <DEDENT> elif mode: <NEW_LINE> <INDENT> mode = str(mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception(f"cannot determine mode of file {source}") <NEW_LINE> <DEDENT> super().__init__( source_fileobj, compression=compression, close_fileobj=close_fileobj ) <NEW_LINE> self._name = str(name) <NEW_LINE> self._mode = mode <NEW_LINE> self.memory_mapped = memory_mapped <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> if hasattr(self, "_name"): <NEW_LINE> <INDENT> return getattr(self, "_name") <NEW_LINE> <DEDENT> return super().name <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self) -> PurePath: <NEW_LINE> <INDENT> return getattr(self, "_path", None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def mode(self) -> str: <NEW_LINE> <INDENT> return self._mode | Wrapper around a file object.
Args:
source: Path or file object.
mode: File open mode.
compression: Compression type.
name: Use an alternative name for the file.
kwargs: Additional arguments to pass to xopen. | 62598fc74c3428357761a5e1 |
class MetaModel(object): <NEW_LINE> <INDENT> train_score = { 'r2_score': { 'name': 'r2_score', 'function': make_scorer( r2_score, greater_is_better=True)}, 'mae': { 'name': 'mean_absolute_error', 'function': make_scorer( mean_absolute_error, greater_is_better=False)}, 'hae': { 'name': 'harmonic_ average_error', 'function': make_scorer( scores.harmonic_averages_error, greater_is_better=False)}, 'mse': { 'name': 'mean_squared_error', 'function': make_scorer( mean_squared_error, greater_is_better=False)}} <NEW_LINE> def __init__(self, input_names=None, response_names=None, preprocessors=None, trainer_score='r2_score', **kwargs): <NEW_LINE> <INDENT> if input_names is None: <NEW_LINE> <INDENT> input_names = [] <NEW_LINE> <DEDENT> if response_names is None: <NEW_LINE> <INDENT> response_names = [] <NEW_LINE> <DEDENT> if preprocessors is None: <NEW_LINE> <INDENT> preprocessors = [] <NEW_LINE> <DEDENT> self.kwargs = kwargs <NEW_LINE> self.regression_pipeline = None <NEW_LINE> self.processing_steps = preprocessors <NEW_LINE> self.input_names = input_names <NEW_LINE> self.response_names = response_names <NEW_LINE> self.score = self.train_score[trainer_score] <NEW_LINE> <DEDENT> def fit(self, x_train, y_train): <NEW_LINE> <INDENT> raise Exception('Not implemented') <NEW_LINE> <DEDENT> def predict(self, X): <NEW_LINE> <INDENT> val = self.regression_pipeline.predict(X) <NEW_LINE> return pandas.DataFrame(val, columns=self.response_names) <NEW_LINE> <DEDENT> def _update_pipeline_and_fit(self, x_train, y_train, steps): <NEW_LINE> <INDENT> processing_steps = copy.copy(self.processing_steps) <NEW_LINE> for step in steps: <NEW_LINE> <INDENT> processing_steps.append(step) <NEW_LINE> <DEDENT> pipeline = make_pipeline(*processing_steps) <NEW_LINE> self.regression_pipeline = pipeline.fit(x_train, y_train) <NEW_LINE> if hasattr(pipeline._final_estimator, 'best_params_'): <NEW_LINE> <INDENT> print('best params: ', pipeline._final_estimator.best_params_) <NEW_LINE> <DEDENT> <DEDENT> def create_model_parameter_dict(self, key_value): <NEW_LINE> <INDENT> return {arg.key: arg.value for arg in key_value} <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s [%s]' % (self.__class__.__name__, str(self.__dict__)) | This class serves as a superclass for all approximation models and
provides a common interface to be used by the Trainer and outside
of this module. It manages a chain of preprocessing steps and
provides the methods :meth:`fit` and :meth:`predict` to fit the
concrete model to the given training data and to predict output
values given the respective inputs.
:param kwargs: arbitrary keyword arguments that will be passed to
*this.model* when it is fitted to the training data. | 62598fc7656771135c489994 |
class Mesh(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.positions = bytes() <NEW_LINE> self.normals = bytes() <NEW_LINE> self.uvs = bytes() <NEW_LINE> self.numVerts = 0 <NEW_LINE> self.numIdx = 0 <NEW_LINE> self.idxBuff = bytes() <NEW_LINE> self.matNum = -1 <NEW_LINE> self.matName = "" <NEW_LINE> self.meshName = "" <NEW_LINE> self.faceGroups = [] | A generic mesh object, for convenience | 62598fc73d592f4c4edbb1d6 |
class AccountOverview(generic.TemplateView): <NEW_LINE> <INDENT> template_name = 'profiles/account-overview.html' <NEW_LINE> def get_context_data(self,**kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['email'] = 'contact@mail.com' <NEW_LINE> return context | render customer profile details and support data | 62598fc7283ffb24f3cf3baa |
class Station(SurrogatePK, Model, CRUDMixin): <NEW_LINE> <INDENT> __tablename__ = 'stations' <NEW_LINE> name = Column(db.String(80), unique=True, nullable=False) <NEW_LINE> lat = Column(db.Float) <NEW_LINE> lon = Column(db.Float) <NEW_LINE> altitude = Column(db.Float) <NEW_LINE> def __init__(self, name, **kwargs): <NEW_LINE> <INDENT> db.Model.__init__(self, name=name, **kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Station({name})>'.format(name=self.name) | A weather station.
name: name of the station
lat: latitude of the station, float, degrees
lon: longitude of the station, float, degrees | 62598fc77cff6e4e811b5d4b |
class TestKmipClient(testtools.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestKmipClient, self).setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestKmipClient, self).tearDown() <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> DummyKmipClient() <NEW_LINE> <DEDENT> def test_create(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.create('algoritm', 'length') <NEW_LINE> <DEDENT> def test_create_key_pair(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.create_key_pair('algoritm', 'length') <NEW_LINE> <DEDENT> def test_register(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.register('secret') <NEW_LINE> <DEDENT> def test_locate(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.locate('maximum_items', 'storage_status_mask', 'object_group_member', 'attributes') <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.get('uid') <NEW_LINE> <DEDENT> def test_get_attribute_list(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.get_attribute_list('uid') <NEW_LINE> <DEDENT> def test_activate(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.activate('uid') <NEW_LINE> <DEDENT> def test_revoke(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.revoke('reason', 'uid', 'message', 'date') <NEW_LINE> <DEDENT> def test_destroy(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.destroy('uid') <NEW_LINE> <DEDENT> def test_encrypt(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.encrypt('data', 'uid', 'crypto_params', 'iv') <NEW_LINE> <DEDENT> def test_mac(self): <NEW_LINE> <INDENT> dummy = DummyKmipClient() <NEW_LINE> dummy.mac('data', 'uid', 'algorithm') | Test suite for KmipClient.
Since KmipClient is an ABC abstract class, all tests are run against a
dummy subclass defined above, DummyKmipClient. | 62598fc74a966d76dd5ef1fa |
class ReservoirLinear(Reservoir): <NEW_LINE> <INDENT> def __init__(self, graph, system, environment): <NEW_LINE> <INDENT> super().__init__(graph, system, environment) <NEW_LINE> <DEDENT> def evaporation(self, state): <NEW_LINE> <INDENT> loc_e_t = 0.1 * state <NEW_LINE> return loc_e_t | Class that encodes a mnp reservoir scenario
:param graph: computation graph
:type graph: tf.Graph
:param reserv_dict: specific parameters of the problem
:type reserv_dict: dict | 62598fc7ec188e330fdf8bba |
class BankAccount: <NEW_LINE> <INDENT> def __init__(self, blz, account_number, pin, endpoint_url): <NEW_LINE> <INDENT> self.blz = blz <NEW_LINE> self.account_number = account_number <NEW_LINE> self.pin = pin <NEW_LINE> self.endpoint_url = endpoint_url <NEW_LINE> logging.basicConfig(level=logging.ERROR) <NEW_LINE> self.f = FinTS3PinTanClient(self.blz, self.account_number, self.pin, self.endpoint_url) <NEW_LINE> self.accounts = self.f.get_sepa_accounts() <NEW_LINE> <DEDENT> def get_balance(self): <NEW_LINE> <INDENT> returnList = [] <NEW_LINE> for account in self.accounts: <NEW_LINE> <INDENT> balance = self.f.get_balance(account).amount.amount + 42 <NEW_LINE> returnList.append(BalanceItem(account.iban, balance )) <NEW_LINE> <DEDENT> return returnList | This class represents a bank account object | 62598fc72c8b7c6e89bd3ae9 |
class Admin(User): <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age, location): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.name = first_name + ' ' + last_name <NEW_LINE> self.age = age <NEW_LINE> self.location = location <NEW_LINE> self.login_attempts = 1 <NEW_LINE> self.privileges = Privileges() | 定义一个管理员类名为Admin,继承User类 | 62598fc7be7bc26dc9251fee |
class FileCache(Cache): <NEW_LINE> <INDENT> fnprefix = 'suds' <NEW_LINE> fnsuffix = 'http' <NEW_LINE> units = ('months', 'weeks', 'days', 'hours', 'minutes', 'seconds') <NEW_LINE> def __init__(self, location=None, **duration): <NEW_LINE> <INDENT> if location is None: <NEW_LINE> <INDENT> location = os.path.join(tmp(), 'suds') <NEW_LINE> <DEDENT> self.location = location <NEW_LINE> self.duration = (None, 0) <NEW_LINE> self.setduration(**duration) <NEW_LINE> <DEDENT> def setduration(self, **duration): <NEW_LINE> <INDENT> if len(duration) == 1: <NEW_LINE> <INDENT> arg = duration.items()[0] <NEW_LINE> if not arg[0] in self.units: <NEW_LINE> <INDENT> raise Exception('must be: %s' % str(self.units)) <NEW_LINE> <DEDENT> self.duration = arg <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def setlocation(self, location): <NEW_LINE> <INDENT> self.location = location <NEW_LINE> <DEDENT> def mktmp(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.isdir(self.location): <NEW_LINE> <INDENT> os.makedirs(self.location) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> log.debug(self.location, exc_info=1) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def put(self, url, fp): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fn = self.__fn(url) <NEW_LINE> f = self.open(fn, 'w') <NEW_LINE> f.write(fp.read()) <NEW_LINE> f.close() <NEW_LINE> return open(fn) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> log.debug(url, exc_info=1) <NEW_LINE> return fp <NEW_LINE> <DEDENT> <DEDENT> def get(self, url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fn = self.__fn(url) <NEW_LINE> self.validate(fn) <NEW_LINE> return self.open(fn) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def validate(self, fn): <NEW_LINE> <INDENT> if self.duration[1] < 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> created = dt.fromtimestamp(os.path.getctime(fn)) <NEW_LINE> d = {self.duration[0] : self.duration[1]} <NEW_LINE> expired = created+timedelta(**d) <NEW_LINE> if expired < dt.now(): <NEW_LINE> <INDENT> log.debug('%s expired, deleted', fn) <NEW_LINE> os.remove(fn) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> for fn in os.listdir(self.location): <NEW_LINE> <INDENT> if os.path.isdir(fn): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if fn.startswith(self.fnprefix) and fn.endswith(self.fnsuffix): <NEW_LINE> <INDENT> log.debug('deleted: %s', fn) <NEW_LINE> os.remove(os.path.join(self.location, fn)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def open(self, fn, *args): <NEW_LINE> <INDENT> self.mktmp() <NEW_LINE> return open(fn, *args) <NEW_LINE> <DEDENT> def __fn(self, url): <NEW_LINE> <INDENT> if self.__ignored(url): <NEW_LINE> <INDENT> raise Exception('URL %s, ignored' % url) <NEW_LINE> <DEDENT> fn = '%s-%s.%s' % (self.fnprefix, abs(hash(url)), self.fnsuffix) <NEW_LINE> return os.path.join(self.location, fn) <NEW_LINE> <DEDENT> def __ignored(self, url): <NEW_LINE> <INDENT> protocol = urlparse(url)[0] <NEW_LINE> return protocol in ('file',) | A file-based URL cache.
@cvar fnprefix: The file name prefix.
@type fnprefix: str
@cvar fnsuffix: The file name suffix.
@type fnsuffix: str
@ivar duration: The cached file duration which defines how
long the file will be cached.
@type duration: (unit, value)
@ivar location: The directory for the cached files.
@type location: str | 62598fc7091ae35668704f4e |
class TestShouldClean(unittest.TestCase): <NEW_LINE> <INDENT> _temp_folder = '' <NEW_LINE> _old_clean_file = '' <NEW_LINE> _dirty_file = '' <NEW_LINE> _new_clean_file = '' <NEW_LINE> @classmethod <NEW_LINE> def create_temp_file(cls): <NEW_LINE> <INDENT> if cls._temp_folder == '': <NEW_LINE> <INDENT> cls._temp_folder = tempfile.mkdtemp() <NEW_LINE> <DEDENT> file_handle, file_name = tempfile.mkstemp(dir=cls._temp_folder) <NEW_LINE> os.fsync(file_handle) <NEW_LINE> os.close(file_handle) <NEW_LINE> return file_name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> old_date = datetime.datetime(year=2019, month=9, day=1, hour=6, minute=0, second=0) <NEW_LINE> old_time = time.mktime(old_date.timetuple()) <NEW_LINE> dirty_date = datetime.datetime(year=2019, month=9, day=1, hour=6, minute=0, second=1) <NEW_LINE> dirty_time = time.mktime(dirty_date.timetuple()) <NEW_LINE> new_date = datetime.datetime(year=2019, month=9, day=1, hour=6, minute=0, second=2) <NEW_LINE> new_time = time.mktime(new_date.timetuple()) <NEW_LINE> cls._old_clean_file = cls.create_temp_file() <NEW_LINE> os.utime(cls._old_clean_file, (old_time, old_time)) <NEW_LINE> cls._dirty_file = cls.create_temp_file() <NEW_LINE> os.utime(cls._dirty_file, (dirty_time, dirty_time)) <NEW_LINE> cls._new_clean_file = cls.create_temp_file() <NEW_LINE> os.utime(cls._new_clean_file, (new_time, new_time)) <NEW_LINE> <DEDENT> def test_should_clean_no_clean_file(self): <NEW_LINE> <INDENT> assert clean_files.should_clean('dirty', 'clean') is True <NEW_LINE> <DEDENT> def test_should_clean_no_dirty_file(self): <NEW_LINE> <INDENT> with pytest.raises(EnvironmentError): <NEW_LINE> <INDENT> clean_files.should_clean('dirty', self._old_clean_file) <NEW_LINE> <DEDENT> <DEDENT> def test_should_clean_old_clean_file(self): <NEW_LINE> <INDENT> assert clean_files.should_clean(self._dirty_file, self._old_clean_file) is True <NEW_LINE> <DEDENT> def test_should_clean_new_clean_file(self): <NEW_LINE> <INDENT> assert clean_files.should_clean(self._dirty_file, self._new_clean_file) is False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> if cls._temp_folder != '': <NEW_LINE> <INDENT> os.unlink(cls._old_clean_file) <NEW_LINE> os.unlink(cls._dirty_file) <NEW_LINE> os.unlink(cls._new_clean_file) | These tests validate the should_clean method | 62598fc7f9cc0f698b1c5465 |
class VoucherManager(object): <NEW_LINE> <INDENT> def __init__(self, type): <NEW_LINE> <INDENT> super(VoucherManager, self).__init__() <NEW_LINE> self._type = type <NEW_LINE> <DEDENT> def saveVoucherInfo(self, voucherNo, customerName, voucherDate, remarks, paymentType, chequeNo, amount, cancelReason): <NEW_LINE> <INDENT> voucher = _database.Voucher.create( voucherNo=str(voucherNo), customerName=customerName, voucherDate=voucherDate, remarks=str(remarks), paymentType=str(paymentType), chequeNo=str(chequeNo if chequeNo.lower() != 'nan' else ''), amount=str(amount), type=self._type, cancelReason=str(cancelReason) ) <NEW_LINE> voucher.save() <NEW_LINE> <DEDENT> def fetchAllVoucherInfo(self): <NEW_LINE> <INDENT> return _database.Voucher.select().where(_database.Voucher.type==self._type) <NEW_LINE> <DEDENT> def fetchAllVoucherNo(self): <NEW_LINE> <INDENT> return [voucherInfo.voucherNo for voucherInfo in _database.Voucher.select().where(_database.Voucher.type==self._type)] <NEW_LINE> <DEDENT> def getVoucherInfo(self, voucherNo): <NEW_LINE> <INDENT> return _database.Voucher.select().where((_database.Voucher.type==self._type) and (_database.Voucher.voucherNo == voucherNo))[0] <NEW_LINE> <DEDENT> def deleteVoucherInfo(self, voucherNo=None): <NEW_LINE> <INDENT> if voucherNo: <NEW_LINE> <INDENT> voucherInfo = self.getVoucherInfo(voucherNo) <NEW_LINE> voucherInfo.delete_instance() <NEW_LINE> return <NEW_LINE> <DEDENT> for voucherInfo in self.fetchAllVoucherInfo(): <NEW_LINE> <INDENT> voucherInfo.delete_instance() | Manager class for Voucher Database | 62598fc73617ad0b5ee0646d |
class CachetAPI: <NEW_LINE> <INDENT> def __init__(self, endpoint): <NEW_LINE> <INDENT> self.endpoint = endpoint <NEW_LINE> self._loaded = False <NEW_LINE> self._components = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def components(self): <NEW_LINE> <INDENT> if not self._loaded: <NEW_LINE> <INDENT> request = cachet.Components(endpoint=self.endpoint) <NEW_LINE> response = json.loads(request.get()) <NEW_LINE> components = tuple(response['data']) <NEW_LINE> logging.info('retrieved status of %d components from Cachet', len(components)) <NEW_LINE> for component in components: <NEW_LINE> <INDENT> for key in list(component.keys()): <NEW_LINE> <INDENT> if key not in COMPONENT_DATA: <NEW_LINE> <INDENT> del component[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._components = components <NEW_LINE> self._loaded = True <NEW_LINE> <DEDENT> return self._components <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def find_matching_component(component, components_list): <NEW_LINE> <INDENT> matches = list(filter(lambda list_comp: list_comp['id'] == component['id'], components_list)) <NEW_LINE> if not matches: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> matches.sort(key=lambda comp: comp[LAST_UPDATE_FIELD], reverse=True) <NEW_LINE> return matches[0] <NEW_LINE> <DEDENT> <DEDENT> def updated_components(self, saved_components): <NEW_LINE> <INDENT> for component in self.components: <NEW_LINE> <INDENT> match_component = self.find_matching_component(component=component, components_list=saved_components) <NEW_LINE> if not match_component: <NEW_LINE> <INDENT> logging.debug('no saved status for component %d, considering its status updated', component['id']) <NEW_LINE> yield component <NEW_LINE> <DEDENT> elif component['status'] != match_component['status']: <NEW_LINE> <INDENT> logging.debug('component %d status has changed', component['id']) <NEW_LINE> yield component | Provide interface to get Cachet components which status differs from a given list | 62598fc7ad47b63b2c5a7b7f |
class ApplicationManagerStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.RegisterApplication = channel.unary_unary( '/handler.ApplicationManager/RegisterApplication', request_serializer=ApplicationIdentifier.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.GetApplication = channel.unary_unary( '/handler.ApplicationManager/GetApplication', request_serializer=ApplicationIdentifier.SerializeToString, response_deserializer=Application.FromString, ) <NEW_LINE> self.SetApplication = channel.unary_unary( '/handler.ApplicationManager/SetApplication', request_serializer=Application.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.DeleteApplication = channel.unary_unary( '/handler.ApplicationManager/DeleteApplication', request_serializer=ApplicationIdentifier.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.GetDevice = channel.unary_unary( '/handler.ApplicationManager/GetDevice', request_serializer=DeviceIdentifier.SerializeToString, response_deserializer=Device.FromString, ) <NEW_LINE> self.SetDevice = channel.unary_unary( '/handler.ApplicationManager/SetDevice', request_serializer=Device.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.DeleteDevice = channel.unary_unary( '/handler.ApplicationManager/DeleteDevice', request_serializer=DeviceIdentifier.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.GetDevicesForApplication = channel.unary_unary( '/handler.ApplicationManager/GetDevicesForApplication', request_serializer=ApplicationIdentifier.SerializeToString, response_deserializer=DeviceList.FromString, ) <NEW_LINE> self.DryDownlink = channel.unary_unary( '/handler.ApplicationManager/DryDownlink', request_serializer=DryDownlinkMessage.SerializeToString, response_deserializer=DryDownlinkResult.FromString, ) <NEW_LINE> self.DryUplink = channel.unary_unary( '/handler.ApplicationManager/DryUplink', request_serializer=DryUplinkMessage.SerializeToString, response_deserializer=DryUplinkResult.FromString, ) <NEW_LINE> self.SimulateUplink = channel.unary_unary( '/handler.ApplicationManager/SimulateUplink', request_serializer=SimulatedUplinkMessage.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) | ApplicationManager manages application and device registrations on the Handler
To protect our quality of service, you can make up to 5000 calls to the
ApplicationManager API per hour. Once you go over the rate limit, you will
receive an error response. | 62598fc72c8b7c6e89bd3aeb |
class RunSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> calorimeter = serializers.PrimaryKeyRelatedField(queryset=Calorimeter.objects.all(), validators=[]) <NEW_LINE> data_point_count = serializers.SerializerMethodField('count_data_points') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Run <NEW_LINE> fields = ('id', 'name', 'creation_time', 'start_time', 'finish_time', 'stabilized_at_start', 'is_ready', 'is_running', 'is_finished', 'email', 'start_temp', 'target_temp', 'ramp_rate', 'calorimeter', 'data_point_count', ) <NEW_LINE> <DEDENT> def count_data_points(self, instance): <NEW_LINE> <INDENT> return instance.datapoint_set.count() | JSON representation of a calorimetry job. | 62598fc760cbc95b06364665 |
class GateParser: <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> self.current_play = None <NEW_LINE> self.previous_task = None <NEW_LINE> self.remove_play = args.remove_play <NEW_LINE> self.roles_only = args.roles_only <NEW_LINE> self.results = args.number <NEW_LINE> self.stats = {} <NEW_LINE> self.r = requests.get(args.url[0], stream=True).iter_lines() <NEW_LINE> for line in self.r: <NEW_LINE> <INDENT> self.process_line(line) <NEW_LINE> <DEDENT> self.calculate_duration() <NEW_LINE> <DEDENT> def process_line(self, raw_line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> timestamp, line = raw_line.split(" | ", 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if line.startswith("TASK ") or line.startswith('RUNNING HANDLER '): <NEW_LINE> <INDENT> self.handle_task(timestamp, line) <NEW_LINE> return True <NEW_LINE> <DEDENT> if line.startswith("PLAY RECAP") or '[Zuul] Job timed out' in line: <NEW_LINE> <INDENT> if self.previous_task is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> self.stats[self.previous_task].append(parse(timestamp)) <NEW_LINE> self.previous_task = None <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def handle_task(self, timestamp, line): <NEW_LINE> <INDENT> match = re.search(r"(TASK|RUNNING HANDLER) \[(.*)\] \**", line) <NEW_LINE> task_name = match.groups()[1] <NEW_LINE> if self.remove_play: <NEW_LINE> <INDENT> if ':' in task_name: <NEW_LINE> <INDENT> task_name = task_name.split(' : ')[1] <NEW_LINE> <DEDENT> <DEDENT> if self.roles_only: <NEW_LINE> <INDENT> if ':' in task_name: <NEW_LINE> <INDENT> task_name = task_name.split(' : ')[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> task_name = "Base playbook (not from role)" <NEW_LINE> <DEDENT> <DEDENT> timestamp = parse(timestamp) <NEW_LINE> if task_name in self.stats.keys(): <NEW_LINE> <INDENT> self.stats[task_name].append(timestamp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stats[task_name] = [timestamp] <NEW_LINE> <DEDENT> if self.previous_task is not None: <NEW_LINE> <INDENT> self.stats[self.previous_task].append(timestamp) <NEW_LINE> <DEDENT> self.previous_task = task_name <NEW_LINE> <DEDENT> def calculate_duration(self): <NEW_LINE> <INDENT> for task_name, timestamps in self.stats.items(): <NEW_LINE> <INDENT> total_time = 0 <NEW_LINE> if len(timestamps) % 2 != 0: <NEW_LINE> <INDENT> self.stats[task_name] = 0 <NEW_LINE> continue <NEW_LINE> <DEDENT> timestamp_pairs = [timestamps[x:x + 2] for x in range(0, len(timestamps), 2)] <NEW_LINE> for pair in timestamp_pairs: <NEW_LINE> <INDENT> total_time += (pair[1] - pair[0]).total_seconds() <NEW_LINE> <DEDENT> self.stats[task_name] = total_time <NEW_LINE> <DEDENT> <DEDENT> def display_output(self): <NEW_LINE> <INDENT> all_time = pretty_time(sum(self.stats.values())) <NEW_LINE> print("---------- TOTAL TIME {} ".format(all_time).ljust(80, '-')) <NEW_LINE> sorted_stats = sorted( self.stats.items(), key=operator.itemgetter(1), reverse=True) <NEW_LINE> for task_name, total_time in sorted_stats[:self.results]: <NEW_LINE> <INDENT> print("{} - {}".format(pretty_time(total_time), task_name)) | Class for parsing timing data from OpenStack-Ansible job runs. | 62598fc70fa83653e46f520e |
class BahdanauAttentionV2(_BaseAttentionMechanismV2): <NEW_LINE> <INDENT> def __init__(self, units, normalize=False, probability_fn="softmax", dtype=None, name="BahdanauAttention", **kwargs): <NEW_LINE> <INDENT> self.probability_fn_name = probability_fn <NEW_LINE> probability_fn = self._process_probability_fn(self.probability_fn_name) <NEW_LINE> wrapped_probability_fn = lambda score, _: probability_fn(score) <NEW_LINE> if dtype is None: <NEW_LINE> <INDENT> dtype = dtypes.float32 <NEW_LINE> <DEDENT> query_layer = kwargs.pop("query_layer", None) <NEW_LINE> if not query_layer: <NEW_LINE> <INDENT> query_layer = layers.Dense( units, name="query_layer", use_bias=False, dtype=dtype) <NEW_LINE> <DEDENT> memory_layer = kwargs.pop("memory_layer", None) <NEW_LINE> if not memory_layer: <NEW_LINE> <INDENT> memory_layer = layers.Dense( units, name="memory_layer", use_bias=False, dtype=dtype) <NEW_LINE> <DEDENT> super(BahdanauAttentionV2, self).__init__( query_layer=query_layer, memory_layer=memory_layer, probability_fn=wrapped_probability_fn, name=name, dtype=dtype, **kwargs) <NEW_LINE> self.units = units <NEW_LINE> self.normalize = normalize <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> super(BahdanauAttentionV2, self).build(input_shape) <NEW_LINE> self.attention_v = self.add_weight( "attention_v", [self.units], dtype=self.dtype) <NEW_LINE> if self.normalize: <NEW_LINE> <INDENT> self.attention_g = self.add_weight( "attention_g", initializer=init_ops.constant_initializer( math.sqrt((1. / self.units))), shape=()) <NEW_LINE> self.attention_b = self.add_weight( "attention_b", shape=[self.units], initializer=init_ops.zeros_initializer()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.attention_g = None <NEW_LINE> self.attention_b = None <NEW_LINE> <DEDENT> self.built = True <NEW_LINE> <DEDENT> def calculate_attention(self, query, state): <NEW_LINE> <INDENT> processed_query = self.query_layer(query) if self.query_layer else query <NEW_LINE> score = _bahdanau_score(processed_query, self.keys, self.attention_v, attention_g=self.attention_g, attention_b=self.attention_b) <NEW_LINE> alignments = self.probability_fn(score, state) <NEW_LINE> next_state = alignments <NEW_LINE> return alignments, next_state <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = { "units": self.units, "normalize": self.normalize, "probability_fn": self.probability_fn_name, } <NEW_LINE> base_config = super(BahdanauAttentionV2, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items())) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_config(cls, config, custom_objects=None): <NEW_LINE> <INDENT> config = _BaseAttentionMechanismV2.deserialize_inner_layer_from_config( config, custom_objects=custom_objects) <NEW_LINE> return cls(**config) | Implements Bahdanau-style (additive) attention.
This attention has two forms. The first is Bahdanau attention,
as described in:
Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio.
"Neural Machine Translation by Jointly Learning to Align and Translate."
ICLR 2015. https://arxiv.org/abs/1409.0473
The second is the normalized form. This form is inspired by the
weight normalization article:
Tim Salimans, Diederik P. Kingma.
"Weight Normalization: A Simple Reparameterization to Accelerate
Training of Deep Neural Networks."
https://arxiv.org/abs/1602.07868
To enable the second form, construct the object with parameter
`normalize=True`. | 62598fc766673b3332c306fe |
class OrderForSellerSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = OrderForSeller <NEW_LINE> fields = '__all__' | OrderForSeller serializer | 62598fc755399d3f05626841 |
class BaseSet(BaseCollection): <NEW_LINE> <INDENT> def add_all(self, a): <NEW_LINE> <INDENT> for x in a: <NEW_LINE> <INDENT> self.add(x) <NEW_LINE> <DEDENT> <DEDENT> def __in__(self, x): <NEW_LINE> <INDENT> return self.find(x) != None <NEW_LINE> <DEDENT> def __eq__(self, a): <NEW_LINE> <INDENT> if len(a) != len(self): return False <NEW_LINE> for x in self: <NEW_LINE> <INDENT> if not x in a: return False <NEW_LINE> <DEDENT> for x in a: <NEW_LINE> <INDENT> if not x in self: return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def __ne__(self, a): <NEW_LINE> <INDENT> return not self == a | Base class for Set implementations | 62598fc74428ac0f6e65884e |
class BannedIPs(Base): <NEW_LINE> <INDENT> __tablename__ = 'bannedips' <NEW_LINE> id = Column(Integer, autoincrement=True, primary_key=True) <NEW_LINE> date = Column(DateTime) <NEW_LINE> ipaddr = Column(Integer, ForeignKey('ipaddr.id')) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<BannedIP: {}>'.format(self.date.strftime('%d-%m-%Y %H:%M:%S')) | The Banned IPs table, holds details about IP addresses that have been
banned by fail2ban. Details are the date it was banned and a link back
to the IP address table row for this IP address. | 62598fc7a219f33f346c6b30 |
class LegacyTestCompleteAborted(Base): <NEW_LINE> <INDENT> expected_title = "ci.pipeline.complete" <NEW_LINE> expected_subti = 'Commit "591b0d2f" of package rpms/vim was aborted on the Atomic CI pipeline on branch f26' <NEW_LINE> expected_link = "https://jenkins-continuous-infra.apps.ci.centos.org/job/ci-pipeline-f26/91/" <NEW_LINE> expected_icon = "https://ci.centos.org/static/ec6de755/images/" "headshot.png" <NEW_LINE> expected_secondary_icon = 'https://seccdn.libravatar.org/avatar/' '0a3d99117b8b56a071b50877c98db3dccbae292f188ef1a1c5b77f66d60c57fa' '?s=64&d=retro' <NEW_LINE> expected_packages = set([]) <NEW_LINE> expected_usernames = set(['fedora-atomic']) <NEW_LINE> expected_objects = set( ['rpms/vim/' '591b0d2fc67a45e4ad13bdc3e312d5554852426a/' 'f26/complete']) <NEW_LINE> msg = { "i": 1, "timestamp": 1501741048, "msg_id": "2017-b420134c-0e39-4f70-8e5f-0975d7019e4b", "crypto": "x509", "topic": "org.centos.prod.ci.pipeline.complete", "msg": { "CI_TYPE": "custom", "build_id": "91", "username": "fedora-atomic", "rev": "591b0d2fc67a45e4ad13bdc3e312d5554852426a", "message-content": "", "build_url": "https://jenkins-continuous-infra.apps.ci.centos.org/job/ci-pipeline-f26/91/", "namespace": "rpms", "CI_NAME": "ci-pipeline-f26", "repo": "vim", "topic": "org.centos.prod.ci.pipeline.complete", "status": "ABORTED", "test_guidance": "''", "branch": "f26", "package_url": "http://artifacts.ci.centos.org/fedora-atomic/f26/repo/vim_repo/", "ref": "fedora/f26/x86_64/atomic-host" } } | These messages were published when an older version of the CI
pipeline announced having aborted a run of the pipeline on a
package. | 62598fc760cbc95b06364667 |
class MolDefBuilder: <NEW_LINE> <INDENT> def __init__(self, spec: Spec) -> None: <NEW_LINE> <INDENT> self.spec = spec <NEW_LINE> self.name = str(spec.to_non_struct_spec()) <NEW_LINE> self.site_defs = {} <NEW_LINE> <DEDENT> def build(self) -> MolDef: <NEW_LINE> <INDENT> return MolDef(self.name, self.site_defs) <NEW_LINE> <DEDENT> def add_site(self, site: Spec) -> None: <NEW_LINE> <INDENT> if site_name(site) not in self.site_defs: <NEW_LINE> <INDENT> self.site_defs[site_name(site)] = [] <NEW_LINE> <DEDENT> <DEDENT> def add_mod(self, site: Spec, mod: StateModifier) -> None: <NEW_LINE> <INDENT> self.site_defs[site_name(site)].append(str(mod.value)) | MolDefBuilder is used to iteratively collect the different states a molecule can have. | 62598fc7fff4ab517ebcdb12 |
class ShellBinaryCrashTest(base_test.BaseTestClass): <NEW_LINE> <INDENT> EXIT_CODE_CRASH = 133 <NEW_LINE> EXIT_CODE_SEGFAULT = 139 <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> self.run_as_vts_self_test = False <NEW_LINE> self.dut = self.android_devices[0] <NEW_LINE> <DEDENT> def testCrashBinary(self): <NEW_LINE> <INDENT> self.dut.shell.InvokeTerminal("my_shell1") <NEW_LINE> target = "/data/local/tmp/vts_test_binary_crash_app" <NEW_LINE> results = self.dut.shell.my_shell1.Execute( ["chmod 755 %s" % target, target]) <NEW_LINE> logging.info(str(results[const.STDOUT])) <NEW_LINE> asserts.assertEqual(len(results[const.STDOUT]), 2) <NEW_LINE> asserts.assertEqual(results[const.STDOUT][1].strip(), "") <NEW_LINE> asserts.assertEqual(results[const.EXIT_CODE][1], self.EXIT_CODE_CRASH) <NEW_LINE> self.CheckShellDriver("my_shell1") <NEW_LINE> self.CheckShellDriver("my_shell2") <NEW_LINE> <DEDENT> def testSegmentFaultBinary(self): <NEW_LINE> <INDENT> self.dut.shell.InvokeTerminal("my_shell1") <NEW_LINE> target = "/data/local/tmp/vts_test_binary_seg_fault" <NEW_LINE> results = self.dut.shell.my_shell1.Execute( ["chmod 755 %s" % target, target]) <NEW_LINE> logging.info(str(results[const.STDOUT])) <NEW_LINE> asserts.assertEqual(len(results[const.STDOUT]), 2) <NEW_LINE> asserts.assertEqual(results[const.STDOUT][1].strip(), "") <NEW_LINE> asserts.assertEqual(results[const.EXIT_CODE][1], self.EXIT_CODE_SEGFAULT) <NEW_LINE> self.CheckShellDriver("my_shell1") <NEW_LINE> self.CheckShellDriver("my_shell2") <NEW_LINE> <DEDENT> def CheckShellDriver(self, shell_name): <NEW_LINE> <INDENT> self.dut.shell.InvokeTerminal(shell_name) <NEW_LINE> results = getattr(self.dut.shell, shell_name).Execute("which ls") <NEW_LINE> logging.info(str(results[const.STDOUT])) <NEW_LINE> asserts.assertEqual(len(results[const.STDOUT]), 1) <NEW_LINE> asserts.assertEqual(results[const.STDOUT][0].strip(), "/system/bin/ls") <NEW_LINE> asserts.assertEqual(results[const.EXIT_CODE][0], 0) | A binary crash test case for the shell driver. | 62598fc7283ffb24f3cf3baf |
class BaseDatabaseTest(tempest.test.BaseTestCase): <NEW_LINE> <INDENT> _interface = 'json' <NEW_LINE> @classmethod <NEW_LINE> def resource_setup(cls): <NEW_LINE> <INDENT> super(BaseDatabaseTest, cls).resource_setup() <NEW_LINE> if not CONF.service_available.trove: <NEW_LINE> <INDENT> skip_msg = ("%s skipped as trove is not available" % cls.__name__) <NEW_LINE> raise cls.skipException(skip_msg) <NEW_LINE> <DEDENT> cls.catalog_type = CONF.database.catalog_type <NEW_LINE> cls.db_flavor_ref = CONF.database.db_flavor_ref <NEW_LINE> cls.db_current_version = CONF.database.db_current_version <NEW_LINE> os = cls.get_client_manager() <NEW_LINE> cls.os = os <NEW_LINE> cls.database_flavors_client = cls.os.database_flavors_client <NEW_LINE> cls.os_flavors_client = cls.os.flavors_client <NEW_LINE> cls.database_limits_client = cls.os.database_limits_client <NEW_LINE> cls.database_versions_client = cls.os.database_versions_client | Base test case class for all Database API tests. | 62598fc74527f215b58ea1fa |
class MathPower(MultiItem): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> MultiItem.__init__(self) <NEW_LINE> self.style = 'math-var', 1 <NEW_LINE> <DEDENT> def resizePDF(self, pdf, x = 0, y = 0): <NEW_LINE> <INDENT> if len(self.items) < 2 or not self.items[0] or not self.items[1]: <NEW_LINE> <INDENT> raise Exception('MathPower must have two items.') <NEW_LINE> <DEDENT> self.rect = Rect(x,y,x,y) <NEW_LINE> dx = pdf.get_string_width(' ') * self.style[1] <NEW_LINE> base = self.items[0] <NEW_LINE> if hasattr(base,'style'): <NEW_LINE> <INDENT> setFontPDF(pdf, base.style, self.styles) <NEW_LINE> <DEDENT> base.resizePDF(pdf,x,y) <NEW_LINE> index = self.items[1] <NEW_LINE> index.scaleFont(0.8) <NEW_LINE> if hasattr(index,'style'): <NEW_LINE> <INDENT> setFontPDF(pdf, index.style, self.styles) <NEW_LINE> <DEDENT> index.resizePDF(pdf, base.rect.x1() + dx, y - base.rect.height() * 0.4) <NEW_LINE> self.rect.unite(base.rect) <NEW_LINE> self.rect.unite(index.rect) <NEW_LINE> self.refit() | Container for inline maths | 62598fc73d592f4c4edbb1dc |
class DownSampling2dLayer(Layer): <NEW_LINE> <INDENT> def __init__( self, prev_layer, size, is_scale=True, method=0, align_corners=False, name='downsample2d_layer', ): <NEW_LINE> <INDENT> Layer.__init__(self, prev_layer=prev_layer, name=name) <NEW_LINE> self.inputs = prev_layer.outputs <NEW_LINE> if len(self.inputs.get_shape()) == 3: <NEW_LINE> <INDENT> if is_scale: <NEW_LINE> <INDENT> size_h = size[0] * int(self.inputs.get_shape()[0]) <NEW_LINE> size_w = size[1] * int(self.inputs.get_shape()[1]) <NEW_LINE> size = [int(size_h), int(size_w)] <NEW_LINE> <DEDENT> <DEDENT> elif len(self.inputs.get_shape()) == 4: <NEW_LINE> <INDENT> if is_scale: <NEW_LINE> <INDENT> size_h = size[0] * int(self.inputs.get_shape()[1]) <NEW_LINE> size_w = size[1] * int(self.inputs.get_shape()[2]) <NEW_LINE> size = [int(size_h), int(size_w)] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Donot support shape %s" % self.inputs.get_shape()) <NEW_LINE> <DEDENT> logging.info("DownSampling2dLayer %s: is_scale:%s size:%s method:%d, align_corners:%s" % (name, is_scale, size, method, align_corners)) <NEW_LINE> with tf.variable_scope(name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.outputs = tf.image.resize_images(self.inputs, size=size, method=method, align_corners=align_corners) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.outputs = tf.image.resize_images(self.inputs, new_height=size[0], new_width=size[1], method=method, align_corners=align_corners) <NEW_LINE> <DEDENT> <DEDENT> self.all_layers.append(self.outputs) | The :class:`DownSampling2dLayer` class is down-sampling 2D layer, see `tf.image.resize_images <https://www.tensorflow.org/versions/master/api_docs/python/image/resizing#resize_images>`__.
Parameters
----------
layer : :class:`Layer`
Previous layer with 4-D Tensor in the shape of (batch, height, width, channels) or 3-D Tensor in the shape of (height, width, channels).
size : tuple of int/float
(height, width) scale factor or new size of height and width.
is_scale : boolean
If True (default), the `size` is the scale factor; otherwise, the `size` are numbers of pixels of height and width.
method : int
The resize method selected through the index. Defaults index is 0 which is ResizeMethod.BILINEAR.
- Index 0 is ResizeMethod.BILINEAR, Bilinear interpolation.
- Index 1 is ResizeMethod.NEAREST_NEIGHBOR, Nearest neighbor interpolation.
- Index 2 is ResizeMethod.BICUBIC, Bicubic interpolation.
- Index 3 ResizeMethod.AREA, Area interpolation.
align_corners : boolean
If True, exactly align all 4 corners of the input and output. Default is False.
name : str
A unique layer name. | 62598fc7a05bb46b3848ab96 |
class GUIDToUUID(StdLibConverter): <NEW_LINE> <INDENT> _takes_stream = True <NEW_LINE> _takes_ctype = True <NEW_LINE> @classmethod <NEW_LINE> def from_stream(cls, stream, offset=None, byte_order=LITTLE_ENDIAN): <NEW_LINE> <INDENT> if offset is not None: <NEW_LINE> <INDENT> stream.seek(offset, SEEK_SET) <NEW_LINE> <DEDENT> data = stream.read(16) <NEW_LINE> if byte_order == LITTLE_ENDIAN: <NEW_LINE> <INDENT> return UUID(bytes_le=data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return UUID(bytes=data) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_ctype(cls, ctype): <NEW_LINE> <INDENT> return cls.from_guid( ctype.data1, ctype.data2, ctype.data3, ctype.data4 ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_guid(cls, data1, data2, data3, data4): <NEW_LINE> <INDENT> node = (data4[2] << 40) | (data4[3] << 32) | (data4[4] << 24) <NEW_LINE> node = node | (data4[5] << 16) | (data4[6] << 8) | data4[7] <NEW_LINE> return UUID(fields=(data1, data2, data3, data4[0], data4[1], node)) | Converts a GUID to a ``UUID``. | 62598fc7a8370b77170f0706 |
class RectangularExtrusion( Extrusion ): <NEW_LINE> <INDENT> pass | An extrusion of a Square | 62598fc797e22403b383b230 |
class Jin(): <NEW_LINE> <INDENT> style = '' | An empty class solely with the purpose of being an object which can
be instantiated. | 62598fc75fc7496912d48410 |
class CircularString(object): <NEW_LINE> <INDENT> def __init__(self, string): <NEW_LINE> <INDENT> self._string = string <NEW_LINE> self._circular = Circular(string) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> c = self.__class__.__name__ <NEW_LINE> return '{}({})'.format(c, self._string) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return ''.join(list(self._circular[key])) | >>> cs = CircularString('0123456789')
>>> cs[-1:12]
'9012345678901' | 62598fc7851cf427c66b85e0 |
class ModalCustomAttribute(object): <NEW_LINE> <INDENT> MODAL_TITLE = (By.CSS_SELECTOR, '.modal-header h2') <NEW_LINE> ATTRIBUTE_TITLE = (By.CSS_SELECTOR, '.modal-body div:nth-child(1)>label') <NEW_LINE> INLINE_HELP = (By.CSS_SELECTOR, '.modal-body div:nth-child(2)>label') <NEW_LINE> ATTRIBUTE_TYPE = (By.CSS_SELECTOR, '.modal-header h2') <NEW_LINE> PLACEHOLDER = (By.CSS_SELECTOR, '.modal-header h2') <NEW_LINE> MANDATORY = (By.CSS_SELECTOR, '.modal-header h2') <NEW_LINE> UI_ATTRIBUTE_TITLE = (By.CSS_SELECTOR, '.modal-body [name="title"]') <NEW_LINE> UI_INLINE_HELP = (By.CSS_SELECTOR, '.modal-body [name="helptext"]') <NEW_LINE> UI_PLACEHOLDER = (By.CSS_SELECTOR, '.modal-body [name="placeholder"]') <NEW_LINE> UI_POSSIBLE_VALUES = (By.CSS_SELECTOR, '.modal-body ' '[name="multi_choice_options"]') <NEW_LINE> CHECKBOX_MANDATORY = (By.CSS_SELECTOR, '.modal-body [type="checkbox"]') <NEW_LINE> BUTTON_ADD_ANOTHER = ( By.CSS_SELECTOR, '.confirm-buttons [data-toggle="modal-submit-addmore"]') <NEW_LINE> BUTTON_SAVE_AND_CLOSE = ( By.CSS_SELECTOR, '.modal-footer .confirm-buttons [data-toggle="modal-submit"]') <NEW_LINE> ATTRIBUTE_TYPE_SELECTOR = (By.CSS_SELECTOR, "dropdown select") <NEW_LINE> ATTRIBUTE_TYPE_OPTIONS = (By.CSS_SELECTOR, "dropdown select option") | Locators for a generic custom attributes modal in admin dashboard | 62598fc79f28863672818a12 |
class DummyFTP(threading.Thread): <NEW_LINE> <INDENT> def set_params( self, addr=None, port=None, folder=None, user=None, password=None ): <NEW_LINE> <INDENT> self.addr = 'localhost' if not addr else addr <NEW_LINE> self.port = '22122' if not port else port <NEW_LINE> self.folder = os.path.join(os.curdir) if not folder else folder <NEW_LINE> self.user = os.getenv('USER') if not user else user <NEW_LINE> self.password = '' if not password else password <NEW_LINE> self.server = DummyFTP.ftp_server( addr, port, folder, user, password ) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.server.serve_forever() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print("Cannot run DummyFTP: you should call 'set_params' prior to running the FTP server") <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.join() <NEW_LINE> self.server.stop() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ftp_server(addr, port, folder, user, password): <NEW_LINE> <INDENT> handler = FTPHandler <NEW_LINE> handler.authorizer = DummyAuthorizer() <NEW_LINE> handler.authorizer.add_user(user , password ,folder, perm='elradfmw') <NEW_LINE> handler.abstracted_fs = UnixFilesystem <NEW_LINE> server = ThreadedFTPServer( (addr, port), handler ) <NEW_LINE> return server | DummyFTP server | 62598fc77c178a314d78d7cc |
class FormulaResult(models.Model): <NEW_LINE> <INDENT> symbol = models.CharField(max_length=20) <NEW_LINE> formula = models.ForeignKey(Formula) <NEW_LINE> date = models.DateField() <NEW_LINE> arguments = models.TextField(max_length=500) <NEW_LINE> length = models.IntegerField() <NEW_LINE> unique_together = (('symbol', 'formula', 'date'),) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '{date} < {symbol} > {formula}'.format( date=self.date, symbol=self.symbol, formula=self.formula.path ) | An algorithm contain different of variables test | 62598fc75fcc89381b2662e3 |
class FileExporter(StringExporter): <NEW_LINE> <INDENT> def __init__(self, handle, *, columns=80, headers=True, comments=True, variations=True): <NEW_LINE> <INDENT> super(FileExporter, self).__init__(columns=columns, headers=headers, comments=comments, variations=variations) <NEW_LINE> self.handle = handle <NEW_LINE> <DEDENT> def flush_current_line(self): <NEW_LINE> <INDENT> if self.current_line: <NEW_LINE> <INDENT> self.handle.write(self.current_line.rstrip()) <NEW_LINE> self.handle.write("\n") <NEW_LINE> <DEDENT> self.current_line = "" <NEW_LINE> <DEDENT> def write_line(self, line=""): <NEW_LINE> <INDENT> self.flush_current_line() <NEW_LINE> self.handle.write(line.rstrip()) <NEW_LINE> self.handle.write("\n") <NEW_LINE> <DEDENT> def result(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<FileExporter at {}>".format(hex(id(self))) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() | Acts like a :class:`~chess.pgn.StringExporter`, but games are written
directly into a text file.
There will always be a blank line after each game. Handling encodings is up
to the caller.
>>> import chess.pgn
>>>
>>> game = chess.pgn.Game()
>>>
>>> new_pgn = open("/dev/null", "w", encoding="utf-8")
>>> exporter = chess.pgn.FileExporter(new_pgn)
>>> game.accept(exporter) | 62598fc77cff6e4e811b5d53 |
class QuestionForm(forms.ModelForm): <NEW_LINE> <INDENT> summary = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1})) <NEW_LINE> description = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1})) <NEW_LINE> points = forms.FloatField() <NEW_LINE> test = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1}), required=False) <NEW_LINE> options = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1}), required=False) <NEW_LINE> language = forms.CharField(max_length=20, widget=forms.Select (choices=languages)) <NEW_LINE> type = forms.CharField(max_length=8, widget=forms.Select (choices=question_types)) <NEW_LINE> active = forms.BooleanField(required=False) <NEW_LINE> tags = TagField(widget=TagAutocomplete(), required=False) <NEW_LINE> snippet = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1}), required=False) <NEW_LINE> ref_code_path = forms.CharField(widget=forms.Textarea (attrs={'cols': 40, 'rows': 1}), required=False) <NEW_LINE> def save(self, commit=True): <NEW_LINE> <INDENT> summary = self.cleaned_data.get("summary") <NEW_LINE> description = self.cleaned_data.get("description") <NEW_LINE> points = self.cleaned_data.get("points") <NEW_LINE> test = self.cleaned_data.get("test") <NEW_LINE> options = self.cleaned_data.get("options") <NEW_LINE> language = self.cleaned_data.get("language") <NEW_LINE> type = self.cleaned_data.get("type") <NEW_LINE> active = self.cleaned_data.get("active") <NEW_LINE> snippet = self.cleaned_data.get("snippet") <NEW_LINE> new_question = Question() <NEW_LINE> new_question.summary = summary <NEW_LINE> new_question.description = description <NEW_LINE> new_question.points = points <NEW_LINE> new_question.test = test <NEW_LINE> new_question.options = options <NEW_LINE> new_question.language = language <NEW_LINE> new_question.type = type <NEW_LINE> new_question.active = active <NEW_LINE> new_question.snippet = snippet <NEW_LINE> new_question = super(QuestionForm, self).save(commit=False) <NEW_LINE> if commit: <NEW_LINE> <INDENT> new_question.save() <NEW_LINE> <DEDENT> return new_question <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Question | Creates a form to add or edit a Question.
It has the related fields and functions required. | 62598fc7956e5f7376df5814 |
class IECSServices(IResource, IMonitorable): <NEW_LINE> <INDENT> cluster = PacoReference( title='Cluster', required=True, str_ok=False, schema_constraint='IECSCluster' ) <NEW_LINE> disable_services = zope.schema.Bool( title="Disable all services and stop all tasks", default=False, required=False, ) <NEW_LINE> setting_groups = zope.schema.Object( title="Setting Groups", description="", schema=IECSSettingsGroups, required=False ) <NEW_LINE> task_definitions = zope.schema.Object( title="Task Definitions", description="", schema=IECSTaskDefinitions, required=True, ) <NEW_LINE> services = zope.schema.Object( title="Service", description="", schema=IECSServicesContainer, required=True, ) <NEW_LINE> service_discovery_namespace_name = zope.schema.TextLine( title="Service Discovery Namespace", description="", required=False, default='', ) <NEW_LINE> secrets_manager_access = zope.schema.List( title="List Secrets Manager secret Paco references", description="", value_type=PacoReference( title="SecretsManagerSecret", schema_constraint='ISecretsManagerSecret', ), required=False ) | The ``ECSServices`` resource type creates one or more ECS Services and their TaskDefinitions
that can run in an `ECSCluster`_.
Services can launch tasks with a `launch_type` of `Fargate` or `EC2`. Capacity Providers allows
tasks to scale a cluster up/down instead. If using Capacity Providers, use the `capacity_provider`
field for the ECSService, or set a default Capacity Provider for the whole `ECSCluster`. If a Service
is intended to use a Capacity Provider, then `launch_type` should NOT be set.
.. code-block:: yaml
:caption: example ECSServices configuration YAML
type: ECSServices
title: "My ECS Services"
enabled: true
order: 40
cluster: paco.ref netenv.mynet.applications.myapp.groups.ecs.resources.cluster
service_discovery_namespace_name: 'private-name'
secrets_manager_access:
- paco.ref netenv.mynet.secrets_manager.store.database.mydb
task_definitions:
frontend:
container_definitions:
frontend:
cpu: 256
essential: true
image: paco.ref netenv.mynet.applications.myapp.groups.ecr.resources.frontend
image_tag: latest
memory: 150 # in MiB
logging:
driver: awslogs
expire_events_after_days: 90
port_mappings:
- container_port: 80
host_port: 0
protocol: tcp
secrets:
- name: DATABASE_PASSWORD
value_from: paco.ref netenv.mynet.secrets_manager.store.database.mydb
environment:
- name: POSTGRES_HOSTNAME
value: paco.ref netenv.mynet.applications.myapp.groups.database.resources.postgresql.endpoint.address
demoservice:
container_definitions:
demoservice:
cpu: 256
essential: true
image: paco.ref netenv.mynet.applications.myapp.groups.ecr.resources.demoservice
image_tag: latest
memory: 100 # in MiB
logging:
driver: awslogs
expire_events_after_days: 90
port_mappings:
- container_port: 80
host_port: 0
protocol: tcp
services:
frontend:
desired_count: 0
task_definition: frontend
deployment_controller: ecs
hostname: frontend.myapp
load_balancers:
- container_name: frontend
container_port: 80
target_group: paco.ref netenv.mynet.applications.myapp.groups.lb.resources.external.target_groups.frontend
demoservice:
desired_count: 0
task_definition: demoservice
deployment_controller: ecs
load_balancers:
- container_name: demoservice
container_port: 80
target_group: paco.ref netenv.mynet.applications.myapp.groups.lb.resources.internal.target_groups.demoservice
| 62598fc763b5f9789fe854a2 |
class ExtendedTabBar(QFrame): <NEW_LINE> <INDENT> RoundedNorth = QTabBar.RoundedNorth <NEW_LINE> RoundedSouth = QTabBar.RoundedSouth <NEW_LINE> RoundedWest = QTabBar.RoundedWest <NEW_LINE> RoundedEast = QTabBar.RoundedEast <NEW_LINE> TriangularNorth = QTabBar.TriangularNorth <NEW_LINE> TriangularSouth = QTabBar.TriangularSouth <NEW_LINE> TriangularWest = QTabBar.TriangularWest <NEW_LINE> TriangularEast = QTabBar.TriangularEast <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ExtendedTabBar, self).__init__() <NEW_LINE> self._tab_bar = _NoMinimumWidthTabBar() <NEW_LINE> self._left_toolbar = QToolBar() <NEW_LINE> self._floating_toolbar = QToolBar() <NEW_LINE> self._right_toolbar = QToolBar() <NEW_LINE> self._main_layout = QBoxLayout(QBoxLayout.LeftToRight) <NEW_LINE> self._main_layout.setContentsMargins(0, 0, 0, 0) <NEW_LINE> self._main_layout.setSpacing(0) <NEW_LINE> self._main_layout.addWidget(self._left_toolbar) <NEW_LINE> self._main_layout.addWidget(self._tab_bar) <NEW_LINE> self._main_layout.addWidget(self._floating_toolbar) <NEW_LINE> self._main_layout.addStretch() <NEW_LINE> self._main_layout.addWidget(self._right_toolbar) <NEW_LINE> self.setLayout(self._main_layout) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self.__dict__.get(name, getattr(self._tab_bar, name)) <NEW_LINE> <DEDENT> def minimumSizeHint(self): <NEW_LINE> <INDENT> margins = self._main_layout.contentsMargins() <NEW_LINE> minimum_size_hint = self._tab_bar.minimumSizeHint() <NEW_LINE> if self.shape() in { QTabBar.RoundedNorth, QTabBar.RoundedSouth, QTabBar.TriangularNorth, QTabBar.TriangularSouth}: <NEW_LINE> <INDENT> return minimum_size_hint + QSize(0, margins.top() + margins.bottom()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return minimum_size_hint + QSize(margins.left() + margins.right(), 0) <NEW_LINE> <DEDENT> <DEDENT> def setShape(self, shape): <NEW_LINE> <INDENT> self._tab_bar.setShape(shape) <NEW_LINE> if shape in { QTabBar.RoundedNorth, QTabBar.RoundedSouth, QTabBar.TriangularNorth, QTabBar.TriangularSouth}: <NEW_LINE> <INDENT> direction = QBoxLayout.LeftToRight <NEW_LINE> orientation = Qt.Horizontal <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> direction = QBoxLayout.TopToBottom <NEW_LINE> orientation = Qt.Vertical <NEW_LINE> <DEDENT> self._main_layout.setDirection(direction) <NEW_LINE> self._left_toolbar.setOrientation(orientation) <NEW_LINE> self._floating_toolbar.setOrientation(orientation) <NEW_LINE> self._right_toolbar.setOrientation(orientation) <NEW_LINE> <DEDENT> @property <NEW_LINE> def left_toolbar(self): <NEW_LINE> <INDENT> return self._left_toolbar <NEW_LINE> <DEDENT> @property <NEW_LINE> def floating_toolbar(self): <NEW_LINE> <INDENT> return self._floating_toolbar <NEW_LINE> <DEDENT> @property <NEW_LINE> def right_toolbar(self): <NEW_LINE> <INDENT> return self._right_toolbar | A tab bar that has QToolBars to the left, right, and floating at the end of the tabs.
Note that although this class inherits from QFrame, __getattr__() trickery is used to "inherit"
the attributes of an internal object that inherits from QTabBar. This is done because it allows
the actual tab bar object to be placed in a layout with other widgets, while allowing this class
to be treated as the tab bar itself. | 62598fc7a05bb46b3848ab98 |
class NewFunction02(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) <NEW_LINE> self.global_optimum = [[-9.94114736324, -9.99997128772]] <NEW_LINE> self.fglob = -0.199409030092 <NEW_LINE> <DEDENT> def fun(self, x, *args): <NEW_LINE> <INDENT> self.nfev += 1 <NEW_LINE> return ((abs(sin(sqrt(abs(x[0] ** 2 + x[1]))))) ** 0.5 + 0.01 * (x[0] + x[1])) | NewFunction02 objective function.
This class defines the NewFunction02 global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{NewFunction02}}(x) = \left | {\sin\left(\sqrt{\lvert{x_{1}^{2}
+ x_{2}}\rvert}\right)} \right |^{0.5} + (x_{1} + x_{2})/100
with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = -0.19933159253` for
:math:`x = [-9.94103375, -9.99771235]`
.. [1] Mishra, S. Global Optimization by Differential Evolution and
Particle Swarm Methods: Evaluation on Some Benchmark Functions.
Munich Personal RePEc Archive, 2006, 1005
TODO Line 368
TODO WARNING, minimum value is estimated from running many optimisations and
choosing the best. | 62598fc760cbc95b0636466b |
class Node: <NEW_LINE> <INDENT> __slots__ = ('name', 'node_type', 'parent', 'depth', 'children', 'marked', 'alias') <NEW_LINE> def __init__(self, name, node_type, parent): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.node_type = node_type <NEW_LINE> self.parent = parent <NEW_LINE> if not self.parent and self.node_type is not NodeType.ROOT: <NEW_LINE> <INDENT> raise Exception("Only node with type ROOT are allowed to have no parent") <NEW_LINE> <DEDENT> self.depth = 0 <NEW_LINE> if self.node_type is NodeType.ROOT: <NEW_LINE> <INDENT> self.depth = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.depth = self.parent.depth + 1 <NEW_LINE> <DEDENT> self.children = {} <NEW_LINE> self.marked = False <NEW_LINE> self.alias = "" <NEW_LINE> <DEDENT> def add_child(self, child_node): <NEW_LINE> <INDENT> self.children.update({child_node.name: child_node}) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.unmark() <NEW_LINE> for child in self.children.values(): <NEW_LINE> <INDENT> child.clear() <NEW_LINE> <DEDENT> <DEDENT> def has_ancestor(self, ancestor_node, max_distance=128): <NEW_LINE> <INDENT> current_node = self <NEW_LINE> distance = 0 <NEW_LINE> while distance < max_distance: <NEW_LINE> <INDENT> if current_node.parent is ancestor_node: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif not current_node.parent: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> current_node = current_node.parent <NEW_LINE> distance += 1 <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def has_child(self, name): <NEW_LINE> <INDENT> return name in self.children.keys() <NEW_LINE> <DEDENT> def get_child(self, name): <NEW_LINE> <INDENT> return self.children[name] <NEW_LINE> <DEDENT> def get_fqon(self): <NEW_LINE> <INDENT> current_node = self <NEW_LINE> fqon = [] <NEW_LINE> while current_node.node_type is not NodeType.ROOT: <NEW_LINE> <INDENT> fqon.insert(0, current_node.name) <NEW_LINE> current_node = current_node.parent <NEW_LINE> <DEDENT> return tuple(fqon) <NEW_LINE> <DEDENT> def mark(self): <NEW_LINE> <INDENT> self.marked = True <NEW_LINE> <DEDENT> def unmark(self): <NEW_LINE> <INDENT> self.marked = False <NEW_LINE> <DEDENT> def set_alias(self, alias): <NEW_LINE> <INDENT> self.alias = alias | Node in the import tree. This can be a directory, a file
or an object. | 62598fc7f9cc0f698b1c5469 |
class StaticIconFile(StaticFile): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(StaticIconFile, self).__init__(*args, **kwargs) <NEW_LINE> self.is_icon = True | A wrapper for static icons that is compatible to the FieldFile class, i.e.
you can use instances of this class in templates just like you use the value
of FileFields (e.g. `{{ my_static_file.url }}`) | 62598fc79f28863672818a13 |
class ProgressBarDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_icon_png(self): <NEW_LINE> <INDENT> path = ':/plugins/ProgressBar/icon.png' <NEW_LINE> icon = QIcon(path) <NEW_LINE> self.assertFalse(icon.isNull()) | Test rerources work. | 62598fc726068e7796d4cc8a |
class Reset(object): <NEW_LINE> <INDENT> url = "https://iforgot.apple.com/password/verify/appleid" <NEW_LINE> def __init__(self, apple_id, count=10, headless=False): <NEW_LINE> <INDENT> self.apple_id = apple_id <NEW_LINE> self.count = count <NEW_LINE> self.headless = headless <NEW_LINE> if self.headless == True: <NEW_LINE> <INDENT> self.use_requests() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.use_selenium() <NEW_LINE> <DEDENT> <DEDENT> def use_selenium(self): <NEW_LINE> <INDENT> count_down = 0 <NEW_LINE> driver = webdriver.Firefox() <NEW_LINE> driver.get(self.url) <NEW_LINE> while count_down < self.count: <NEW_LINE> <INDENT> elem = driver.find_element_by_xpath("//input[@id='appleid']") <NEW_LINE> elem.send_keys(self.apple_id) <NEW_LINE> elem.send_keys(Keys.RETURN) <NEW_LINE> sleep(2) <NEW_LINE> elem2 = driver.find_element_by_id("action") <NEW_LINE> elem2.click() <NEW_LINE> sleep(2) <NEW_LINE> elem3 = driver.find_element_by_id("action") <NEW_LINE> elem3.click() <NEW_LINE> sleep(2) <NEW_LINE> elem4 = driver.find_element_by_class_name("done") <NEW_LINE> elem4.click() <NEW_LINE> count_down += 1 <NEW_LINE> print ("Attempt %d done" % count_down) <NEW_LINE> sleep(2) <NEW_LINE> <DEDENT> sleep(2) <NEW_LINE> driver.quit() <NEW_LINE> <DEDENT> def use_requests(self): <NEW_LINE> <INDENT> pass | Request a password reset for Apple ID from Apple multiple times. | 62598fc7fbf16365ca7943e7 |
class H5TelstateSensorGetter(RecordSensorGetter): <NEW_LINE> <INDENT> def __init__(self, data, name=None): <NEW_LINE> <INDENT> super().__init__(data, name) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> timestamp = np.asarray(self._data['timestamp']) <NEW_LINE> values = [_h5_telstate_unpack(s) for s in self._data['value']] <NEW_LINE> dtype = infer_dtype(values) <NEW_LINE> if dtype == np.object: <NEW_LINE> <INDENT> values = [ComparableArrayWrapper(value) for value in values] <NEW_LINE> <DEDENT> return SensorData(self.name, timestamp, to_str(np.asarray(values))) | Raw (uninterpolated) sensor data in HDF5 TelescopeState recarray form.
This wraps the telstate sensors stored in recent HDF5 files. It differs
in two ways from the normal HDF5 sensors: no 'status' field and values
encoded by katsdptelstate.
TODO: This is a temporary fix to get at missing sensors in telstate and
should be replaced by a proper wrapping of any telstate object.
Object-valued sensors (including sensors with ndarrays as values) will have
its values wrapped by :class:`ComparableArrayWrapper`.
Parameters
----------
data : recarray-like, with fields ('timestamp', 'value')
Uninterpolated sensor data as structured array or equivalent (such as
an :class:`h5py.Dataset`)
name : string or None, optional
Sensor name (assumed to be data.name by default, if it exists) | 62598fc755399d3f05626849 |
class CheckCmimToken(): <NEW_LINE> <INDENT> def __init__(self,dicdata): <NEW_LINE> <INDENT> self.dicdata=dicdata <NEW_LINE> self.config=pfAPI.getConfig(self.dicdata) <NEW_LINE> self.headers=self.config['headers'] <NEW_LINE> <DEDENT> def send_request(self, thirdPartyToken,corporationSerial="001"): <NEW_LINE> <INDENT> self.cmimToken=thirdPartyToken <NEW_LINE> self.config['url']=self.config['url'].replace("{cmimToken}",thirdPartyToken) <NEW_LINE> self.config['url']=self.config['url'].replace("{corporationSerial}",corporationSerial) <NEW_LINE> r=pfAPI.sendRequests(self.config['method'],self.config['url'],headers=self.headers,auth=self.config['auth']) <NEW_LINE> return r <NEW_LINE> <DEDENT> def get_message(self,r): <NEW_LINE> <INDENT> res=json.loads(r.text) <NEW_LINE> return res['messages'] <NEW_LINE> <DEDENT> def get_messageCode(self,r): <NEW_LINE> <INDENT> res=json.loads(r.text) <NEW_LINE> return res['messageCode'] <NEW_LINE> <DEDENT> def get_status(self,r): <NEW_LINE> <INDENT> res=json.loads(r.text) <NEW_LINE> return res['status'] <NEW_LINE> <DEDENT> def get_statusCode(self, r): <NEW_LINE> <INDENT> res = json.loads(r.text) <NEW_LINE> return res['statusCode'] <NEW_LINE> <DEDENT> def get_content(self,r): <NEW_LINE> <INDENT> res=json.loads(r.text) <NEW_LINE> return res['content'] <NEW_LINE> <DEDENT> def verify_success_return(self, r): <NEW_LINE> <INDENT> statusCode=r.status_code <NEW_LINE> message=self.get_message(r)[0] <NEW_LINE> status=self.get_status(r) <NEW_LINE> result = bool(status == "0000_0") and bool(statusCode == 200) and bool(message == '执行成功') <NEW_LINE> return result | 用户登录
Method:Get
URL:https://<base url>/user/v0/checkcmimToken?{checkcmimToken}
参数: 空 | 62598fc74c3428357761a5ed |
class SCXMLPropertiesContainer(b.SCXMLBase): <NEW_LINE> <INDENT> clsid= '' <NEW_LINE> progid= '' <NEW_LINE> def __init__(self,cId,clsid,progid): <NEW_LINE> <INDENT> super(SCXMLPropertiesContainer,self).__init__(cId,'') <NEW_LINE> self.clsid= clsid <NEW_LINE> self.progid= progid <NEW_LINE> <DEDENT> def populateXMLElement(self, element): <NEW_LINE> <INDENT> super(SCXMLPropertiesContainer,self).populateXMLElement(element) <NEW_LINE> element.set("clsid",self.clsid) <NEW_LINE> if(self.progid!=''): <NEW_LINE> <INDENT> element.set("progid",self.progid) | SCIA XML properties container. | 62598fc7656771135c4899a0 |
class CredentialInstance(InstanceResource): <NEW_LINE> <INDENT> class PushService(object): <NEW_LINE> <INDENT> GCM = "gcm" <NEW_LINE> APN = "apn" <NEW_LINE> FCM = "fcm" <NEW_LINE> <DEDENT> def __init__(self, version, payload, sid=None): <NEW_LINE> <INDENT> super(CredentialInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload['sid'], 'account_sid': payload['account_sid'], 'friendly_name': payload['friendly_name'], 'type': payload['type'], 'sandbox': payload['sandbox'], 'date_created': deserialize.iso8601_datetime(payload['date_created']), 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), 'url': payload['url'], } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = CredentialContext(self._version, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._properties['friendly_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._properties['type'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def sandbox(self): <NEW_LINE> <INDENT> return self._properties['sandbox'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def update(self, friendly_name=values.unset, certificate=values.unset, private_key=values.unset, sandbox=values.unset, api_key=values.unset, secret=values.unset): <NEW_LINE> <INDENT> return self._proxy.update( friendly_name=friendly_name, certificate=certificate, private_key=private_key, sandbox=sandbox, api_key=api_key, secret=secret, ) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Notify.V1.CredentialInstance {}>'.format(context) | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 62598fc77cff6e4e811b5d57 |
class IPv6UDPDst(MatchTest): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> match = ofp.match([ ofp.oxm.eth_type(0x86dd), ofp.oxm.ip_proto(17), ofp.oxm.udp_dst(53), ]) <NEW_LINE> matching = { "udp dport=53": simple_udpv6_packet(udp_dport=53), } <NEW_LINE> nonmatching = { "udp dport=52": simple_udpv6_packet(udp_dport=52), "tcp dport=53": simple_tcpv6_packet(tcp_dport=53), } <NEW_LINE> self.verify_match(match, matching, nonmatching) | Match on ipv4 udp destination port | 62598fc77047854f4633f703 |
class WbRepresentation(abc.ABC): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def toWikibase(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abc.abstractmethod <NEW_LINE> def fromWikibase(cls, json): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> assert isinstance(self._items, tuple) <NEW_LINE> assert all(isinstance(item, str) for item in self._items) <NEW_LINE> values = ((attr, getattr(self, attr)) for attr in self._items) <NEW_LINE> attrs = ', '.join('{}={}'.format(attr, value) for attr, value in values) <NEW_LINE> return '{}({})'.format(self.__class__.__name__, attrs) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> return self.toWikibase() == other.toWikibase() <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(frozenset(self.toWikibase().items())) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) | Abstract class for Wikibase representations. | 62598fc760cbc95b0636466f |
class FileWritey(object): <NEW_LINE> <INDENT> def __init__(self, args, filename, binary=False): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.filename = filename <NEW_LINE> self.trad_file = None <NEW_LINE> self.open_str = "wb" if binary else "w" <NEW_LINE> <DEDENT> def copy_to_bucket(self): <NEW_LINE> <INDENT> if 'google.cloud' in sys.modules and self.args.bucket is not None and self.args.gcs_dir is not None: <NEW_LINE> <INDENT> client = storage.Client() <NEW_LINE> bucket = client.get_bucket(self.args.bucket) <NEW_LINE> blob2 = bucket.blob(os.path.join(self.args.gcs_dir, self.filename)) <NEW_LINE> blob2.upload_from_filename(filename=os.path.join(self.args.output_dir, self.filename)) <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> os.makedirs(self.args.output_dir, exist_ok=True) <NEW_LINE> self.trad_file = open(os.path.join(self.args.output_dir, self.filename), self.open_str) <NEW_LINE> return self.trad_file <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.trad_file.close() <NEW_LINE> self.copy_to_bucket() | Tries to write on traditional filesystem and Google Cloud storage | 62598fc7091ae35668704f5a |
class BzrGitError(brz_errors.BzrError): <NEW_LINE> <INDENT> pass | The base-level exception for bzr-git errors. | 62598fc7d486a94d0ba2c303 |
class HighlightsConfigureInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Switch = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Switch = params.get("Switch") | 智能精彩片段任务控制参数
| 62598fc7bf627c535bcb17dc |
class DeleteEpisode(LoginRequiredMixin, RedirectView): <NEW_LINE> <INDENT> def get_redirect_url(self, *args, **kwargs): <NEW_LINE> <INDENT> return f'/#/patient/{self.kwargs["patient_pk"]}' <NEW_LINE> <DEDENT> def post(self, *args, **kwargs): <NEW_LINE> <INDENT> episode = get_object_or_404(Episode, pk=kwargs["episode_pk"]) <NEW_LINE> patient = episode.patient <NEW_LINE> category_name = episode.category_name <NEW_LINE> if category_name == episode_categories.DentalCareEpisodeCategory.display_name: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> new = episode.category.NEW <NEW_LINE> if episode.stage == episode.category.SUBMITTED: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> episode.delete() <NEW_LINE> patient.episode_set.get_or_create( category_name=category_name, stage=new ) <NEW_LINE> return super().post(*args, **kwargs) | This view is for when an episode has been opened in error
it deletes and redirects to the patient detail page.
Note the way Odonto functions is that a patient
always has a new episode. So after it has deleted
it creates an episode of the same category with
the stage of new if it does not already exist | 62598fc77b180e01f3e491e9 |
class TemplateSystem(object): <NEW_LINE> <INDENT> name = "dummy templates" <NEW_LINE> def set_directories(self, directories, cache_folder): <NEW_LINE> <INDENT> raise Exception("Implement Me First") <NEW_LINE> <DEDENT> def template_deps(self, template_name): <NEW_LINE> <INDENT> raise Exception("Implement Me First") <NEW_LINE> <DEDENT> def render_template(name, output_name, context): <NEW_LINE> <INDENT> raise Exception("Implement Me First") | Plugins of this type wrap templating systems. | 62598fc7956e5f7376df5817 |
class UserCreationForm(forms.ModelForm): <NEW_LINE> <INDENT> error_messages = { 'password_mismatch': "Пароли не совпадают.", } <NEW_LINE> password1 = forms.CharField( label="Пароль", strip=False, widget=forms.PasswordInput, ) <NEW_LINE> password2 = forms.CharField( label="Повторите", widget=forms.PasswordInput, strip=False, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('email',) <NEW_LINE> field_classes = {'email': forms.EmailField} <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get("password1") <NEW_LINE> password2 = self.cleaned_data.get("password2") <NEW_LINE> if password1 and password2 and password1 != password2: <NEW_LINE> <INDENT> raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) <NEW_LINE> <DEDENT> return password2 <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super().save(commit=False) <NEW_LINE> user.set_password(self.cleaned_data["password1"]) <NEW_LINE> if commit: <NEW_LINE> <INDENT> user.save() <NEW_LINE> <DEDENT> return user | A form that creates a user, with no privileges, from the given email and
password. | 62598fc7ec188e330fdf8bc8 |
class CompositeMatcher(gluon.HybridBlock): <NEW_LINE> <INDENT> def __init__(self, matchers): <NEW_LINE> <INDENT> super(CompositeMatcher, self).__init__() <NEW_LINE> assert len(matchers) > 0, "At least one matcher required." <NEW_LINE> for matcher in matchers: <NEW_LINE> <INDENT> assert isinstance(matcher, (gluon.Block, gluon.HybridBlock)) <NEW_LINE> <DEDENT> self._matchers = nn.HybridSequential() <NEW_LINE> for m in matchers: <NEW_LINE> <INDENT> self._matchers.add(m) <NEW_LINE> <DEDENT> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> matches = [matcher(x) for matcher in self._matchers] <NEW_LINE> return self._compose_matches(F, matches) <NEW_LINE> <DEDENT> def _compose_matches(self, F, matches): <NEW_LINE> <INDENT> result = matches[0] <NEW_LINE> for match in matches[1:]: <NEW_LINE> <INDENT> result = F.where(result > -0.5, result, match) <NEW_LINE> <DEDENT> return result | A Matcher that combines multiple strategies.
Parameters
----------
matchers : list of Matcher
Matcher is a Block/HybridBlock used to match two groups of boxes | 62598fc771ff763f4b5e7ab3 |
class PortfolioFeed(gdata.GDataFeed): <NEW_LINE> <INDENT> _tag = 'feed' <NEW_LINE> _namespace = atom.ATOM_NAMESPACE <NEW_LINE> _children = gdata.GDataFeed._children.copy() <NEW_LINE> _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PortfolioEntry]) | A feed that lists all of the user's portfolios.
A portfolio is a collection of positions that the user holds in various
securities, plus metadata. The PortfolioFeed lists all of the user's
portfolios as a list of PortfolioEntries. | 62598fc77c178a314d78d7d4 |
class Discrete3DFunction(TabulatedFunction): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> for _s in [TabulatedFunction]: <NEW_LINE> <INDENT> __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) <NEW_LINE> <DEDENT> __setattr__ = lambda self, name, value: _swig_setattr(self, Discrete3DFunction, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> for _s in [TabulatedFunction]: <NEW_LINE> <INDENT> __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) <NEW_LINE> <DEDENT> __getattr__ = lambda self, name: _swig_getattr(self, Discrete3DFunction, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, xsize, ysize, zsize, values): <NEW_LINE> <INDENT> this = _openmm.new_Discrete3DFunction(xsize, ysize, zsize, values) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> def getFunctionParameters(self): <NEW_LINE> <INDENT> return _openmm.Discrete3DFunction_getFunctionParameters(self) <NEW_LINE> <DEDENT> def setFunctionParameters(self, xsize, ysize, zsize, values): <NEW_LINE> <INDENT> return _openmm.Discrete3DFunction_setFunctionParameters(self, xsize, ysize, zsize, values) <NEW_LINE> <DEDENT> def Copy(self): <NEW_LINE> <INDENT> return _openmm.Discrete3DFunction_Copy(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _openmm.delete_Discrete3DFunction <NEW_LINE> __del__ = lambda self: None | This is a TabulatedFunction that computes a discrete three dimensional function f(x,y,z). To evaluate it, x, y, and z are each rounded to the nearest integer and the table element with those indices is returned. If any index is outside the range [0, size), the result is undefined. | 62598fc7adb09d7d5dc0a8af |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.