code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class LRUCachedFunction(object): <NEW_LINE> <INDENT> def __init__(self, function, cache=None): <NEW_LINE> <INDENT> if cache: <NEW_LINE> <INDENT> self.cache = cache <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cache = LRUCacheDict() <NEW_LINE> <DEDENT> self.function = function <NEW_LINE> self.__name__ = self.function.__name__ <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> key = repr( (args, kwargs) ) + "#" + self.__name__ <NEW_LINE> try: <NEW_LINE> <INDENT> return self.cache[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> value = self.function(*args, **kwargs) <NEW_LINE> self.cache[key] = value <NEW_LINE> return value | >>> def f(x):
... print "Calling f(" + str(x) + ")"
... return x
>>> f = LRUCachedFunction(f, LRUCacheDict(max_size=3, expiration=3) ) | 62599046b830903b9686ee25 |
class WAVEDecoder(Decoder): <NEW_LINE> <INDENT> suffix = '.wav' <NEW_LINE> def __init__(self, extract_metadata=False, extract_image=False): <NEW_LINE> <INDENT> if extract_metadata or extract_image: <NEW_LINE> <INDENT> raise Exception('WAVE files have no native support for metadata or embedded images.') <NEW_LINE> <DEDENT> <DEDENT> def decode(self, infile, outfile, tmp_image=None): <NEW_LINE> <INDENT> self._check_wav_marker(infile) <NEW_LINE> shutil.copyfile(infile, outfile) <NEW_LINE> return {} <NEW_LINE> <DEDENT> def _check_wav_marker(self, infile): <NEW_LINE> <INDENT> with open(infile, 'rb') as f: <NEW_LINE> <INDENT> riff_marker = f.read(4) <NEW_LINE> f.seek(8) <NEW_LINE> wave_marker = f.read(4) <NEW_LINE> if riff_marker != b'RIFF' or wave_marker != b'WAVE': <NEW_LINE> <INDENT> raise Exception('Not a valid WAVE file') | Decoder for WAVE files | 62599046dc8b845886d54910 |
class _ReadUntil(_Awaitable): <NEW_LINE> <INDENT> __slots__ = ['sep', 'max_bytes'] <NEW_LINE> def __init__(self, sep, max_bytes=None): <NEW_LINE> <INDENT> self.sep = sep <NEW_LINE> self.max_bytes = max_bytes <NEW_LINE> <DEDENT> def check_length(self, pos): <NEW_LINE> <INDENT> if self.max_bytes is not None and pos > self.max_bytes: <NEW_LINE> <INDENT> raise ParseError( 'expected {!r}'.format(self.sep) ) | Read until a separator. | 625990468a43f66fc4bf34ea |
class SessionQueryForms(messages.Message): <NEW_LINE> <INDENT> filters = messages.MessageField(SessionQueryForm, 1, repeated=True) | ConferenceQueryForms -- multiple ConferenceQueryForm inbound form message | 6259904630dc7b76659a0b88 |
class SlackAdapterOptions: <NEW_LINE> <INDENT> def __init__( self, slack_verification_token: str, slack_bot_token: str, slack_client_signing_secret: str, ): <NEW_LINE> <INDENT> self.slack_verification_token = slack_verification_token <NEW_LINE> self.slack_bot_token = slack_bot_token <NEW_LINE> self.slack_client_signing_secret = slack_client_signing_secret <NEW_LINE> self.slack_client_id = None <NEW_LINE> self.slack_client_secret = None <NEW_LINE> self.slack_redirect_uri = None <NEW_LINE> self.slack_scopes = [str] <NEW_LINE> <DEDENT> async def get_token_for_team(self, team_id: str) -> str: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> async def get_bot_user_by_team(self, team_id: str) -> str: <NEW_LINE> <INDENT> raise NotImplementedError() | Class for defining implementation of the SlackAdapter Options. | 6259904615baa723494632e8 |
class ExportDeliveryInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'destination': {'required': True}, } <NEW_LINE> _attribute_map = { 'destination': {'key': 'destination', 'type': 'ExportDeliveryDestination'}, } <NEW_LINE> def __init__( self, *, destination: "ExportDeliveryDestination", **kwargs ): <NEW_LINE> <INDENT> super(ExportDeliveryInfo, self).__init__(**kwargs) <NEW_LINE> self.destination = destination | The delivery information associated with a export.
All required parameters must be populated in order to send to Azure.
:param destination: Required. Has destination for the export being delivered.
:type destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination | 62599046b57a9660fecd2dd3 |
class Processor(AwardProcessor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AwardProcessor.__init__(self, 'Rasputin', 'Most Weapon Type Deaths', [PLAYER_COL, Column('Types', Column.NUMBER, Column.DESC)]) <NEW_LINE> self.types = dict() <NEW_LINE> <DEDENT> def on_kill(self, e): <NEW_LINE> <INDENT> if not e.valid_kill: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not e.victim in self.types: <NEW_LINE> <INDENT> self.types[e.victim] = set() <NEW_LINE> <DEDENT> self.types[e.victim].add( e.weapon ) <NEW_LINE> self.results[e.victim] = len( self.types[e.victim] ) | Overview
This processor keeps track of the most weapon type deaths
Implementation
Cache kill events involving a sniper.
Notes
None. | 62599046b5575c28eb713674 |
class section(EmbeddedDocument): <NEW_LINE> <INDENT> secTitle = StringField(min_length=1, max_length=100, required=True, regex='^([A-ZÁÉÍÓÚÑÜ]+)([A-Z a-z 0-9 À-ÿ : \-]*)([A-Za-z0-9À-ÿ]$)') <NEW_LINE> content = StringField(min_length=1, required=True) | EmbeddedDocument Class for Section.
These are going to be the body of the Document Case.
An EmbeddedDocument is a Document Class that is defined inside another document.
This one is going to be defined, and stored inside the DocumentCase Class.
The reason for this technique is that the Section Class has its own schema.
List of attributes:
- secTitle: <String> Section's title.
- content: <String> Section's body. | 62599046435de62698e9d15b |
class ClipCreator(object): <NEW_LINE> <INDENT> def __init__(self, *a, **k): <NEW_LINE> <INDENT> super(ClipCreator, self).__init__(*a, **k) <NEW_LINE> self._grid_quantization = None <NEW_LINE> self._grid_triplet = False <NEW_LINE> <DEDENT> def _get_grid_quantization(self): <NEW_LINE> <INDENT> return self._grid_quantization <NEW_LINE> <DEDENT> def _set_grid_quantization(self, quantization): <NEW_LINE> <INDENT> self._grid_quantization = quantization <NEW_LINE> <DEDENT> grid_quantization = property(_get_grid_quantization, _set_grid_quantization) <NEW_LINE> def _get_grid_triplet(self): <NEW_LINE> <INDENT> return self._grid_triplet <NEW_LINE> <DEDENT> def _set_grid_triplet(self, triplet): <NEW_LINE> <INDENT> self._grid_triplet = triplet <NEW_LINE> <DEDENT> is_grid_triplet = property(_get_grid_triplet, _set_grid_triplet) <NEW_LINE> def create(self, slot, length): <NEW_LINE> <INDENT> if not slot.clip == None: <NEW_LINE> <INDENT> raise AssertionError <NEW_LINE> slot.create_clip(length) <NEW_LINE> slot.clip.view.grid_quantization = self.grid_quantization != None and self.grid_quantization <NEW_LINE> slot.clip.view.grid_is_triplet = self.is_grid_triplet <NEW_LINE> <DEDENT> slot.fire(force_legato=True, launch_quantization=_Q.q_no_q) | Manages clip creation over all components | 6259904691af0d3eaad3b17b |
class Model(metaclass=ModelBase): <NEW_LINE> <INDENT> __abstract__ = True <NEW_LINE> __init__ = base._declarative_constructor <NEW_LINE> @declared_attr <NEW_LINE> def __tablename__(cls): <NEW_LINE> <INDENT> package = _package_of(cls.__module__).lower() <NEW_LINE> name = '%s.%s' % (package, cls.__name__.lower()) <NEW_LINE> name = re.sub(r'([A-Z])', r'_\1', name) <NEW_LINE> name = re.sub(r'\.+', r'_', name) <NEW_LINE> return name <NEW_LINE> <DEDENT> def save(self, session=None, commit=True): <NEW_LINE> <INDENT> if has_identity(self): <NEW_LINE> <INDENT> session = object_session(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if session is None: <NEW_LINE> <INDENT> session = __import__('alchemist.db').db.session <NEW_LINE> <DEDENT> session.add(self) <NEW_LINE> <DEDENT> if commit: <NEW_LINE> <INDENT> session.commit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> session.flush() | Declares the base model.
This provides various helpers, defaults, and utilities for
sqlalchemy-derived models. | 62599046ec188e330fdf9bf3 |
class GraphiteTextServer(ServerProcessor): <NEW_LINE> <INDENT> def __init__( self, only_accept_local, port, run_state, buffer_size, max_request_size, max_connection_idle_time, logger, ): <NEW_LINE> <INDENT> self.__logger = logger <NEW_LINE> self.__parser = LineRequestParser(max_request_size) <NEW_LINE> ServerProcessor.__init__( self, port, localhost_socket=only_accept_local, max_request_size=max_request_size, max_connection_idle_time=max_connection_idle_time, buffer_size=buffer_size, run_state=run_state, ) <NEW_LINE> <DEDENT> def execute_request(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metric, value, orig_timestamp = request.strip().split() <NEW_LINE> metric = six.ensure_text(metric) <NEW_LINE> value = float(value) <NEW_LINE> orig_timestamp = float(orig_timestamp) <NEW_LINE> self.__logger.emit_value( metric, value, extra_fields={"orig_time": orig_timestamp} ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.__logger.warn( "Could not parse incoming metric line from graphite plaintext server, ignoring", error_code="graphite_monitor/badPlainTextLine", ) <NEW_LINE> <DEDENT> <DEDENT> def parse_request(self, request_input, num_available_bytes): <NEW_LINE> <INDENT> return self.__parser.parse_request(request_input, num_available_bytes) <NEW_LINE> <DEDENT> def report_connection_problem(self, exception): <NEW_LINE> <INDENT> self.__logger.exception( "Exception seen while processing Graphite connect on text port, " 'closing connection: "%s"' % six.text_type(exception) ) | Accepts connections on a server socket and handles them using Graphite's plaintext protocol format, emitting
the received metrics to the log. | 6259904696565a6dacd2d935 |
class EventInSpatial(models.Model): <NEW_LINE> <INDENT> spatial = models.IntegerField() <NEW_LINE> event = models.ForeignKey(Event, related_name='event_spatials') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "Event in Spatial" <NEW_LINE> verbose_name_plural = "Event in Spatials" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.spatial) | Represents the 1:m relation between a Event and Spatials | 62599046a4f1c619b294f833 |
class TestSentenceBreak(unittest.TestCase): <NEW_LINE> <INDENT> def test_table_integrity(self): <NEW_LINE> <INDENT> re_key = re.compile(r'^\^?[a-z0-9./]+$') <NEW_LINE> keys1 = set(uniprops.unidata.unicode_sentence_break.keys()) <NEW_LINE> keys2 = set(uniprops.unidata.ascii_sentence_break.keys()) <NEW_LINE> for k in keys1: <NEW_LINE> <INDENT> self.assertTrue(re_key.match(k) is not None) <NEW_LINE> <DEDENT> self.assertEqual(keys1, keys2) <NEW_LINE> for key in keys1: <NEW_LINE> <INDENT> if not key.startswith('^'): <NEW_LINE> <INDENT> self.assertTrue('^' + key in keys1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_sentencebreak(self): <NEW_LINE> <INDENT> for k, v in uniprops.unidata.unicode_sentence_break.items(): <NEW_LINE> <INDENT> result = uniprops.get_unicode_property('sentencebreak', k) <NEW_LINE> self.assertEqual(result, v) <NEW_LINE> <DEDENT> <DEDENT> def test_sentencebreak_ascii(self): <NEW_LINE> <INDENT> for k, v in uniprops.unidata.ascii_sentence_break.items(): <NEW_LINE> <INDENT> result = uniprops.get_unicode_property('sentencebreak', k, mode=uniprops.MODE_NORMAL) <NEW_LINE> self.assertEqual(result, v) <NEW_LINE> <DEDENT> <DEDENT> def test_sentencebreak_binary(self): <NEW_LINE> <INDENT> for k, v in uniprops.unidata.ascii_sentence_break.items(): <NEW_LINE> <INDENT> result = uniprops.get_unicode_property('sentencebreak', k, mode=uniprops.MODE_ASCII) <NEW_LINE> self.assertEqual(result, uniprops.fmt_string(v, True)) <NEW_LINE> <DEDENT> <DEDENT> def test_bad_sentencebreak(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> uniprops.get_unicode_property('sentencebreak', 'bad') <NEW_LINE> <DEDENT> <DEDENT> def test_alias(self): <NEW_LINE> <INDENT> alias = None <NEW_LINE> for k, v in uniprops.unidata.alias.unicode_alias['_'].items(): <NEW_LINE> <INDENT> if v == 'sentencebreak': <NEW_LINE> <INDENT> alias = k <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(alias is not None) <NEW_LINE> for k, v in uniprops.unidata.unicode_sentence_break.items(): <NEW_LINE> <INDENT> result = uniprops.get_unicode_property(alias, k) <NEW_LINE> self.assertEqual(result, v) <NEW_LINE> break <NEW_LINE> <DEDENT> for k, v in uniprops.unidata.alias.unicode_alias['sentencebreak'].items(): <NEW_LINE> <INDENT> result1 = uniprops.get_unicode_property(alias, k) <NEW_LINE> result2 = uniprops.get_unicode_property(alias, v) <NEW_LINE> self.assertEqual(result1, result2) | Test `Sentence Break` access. | 625990463eb6a72ae038b9b2 |
class TestSetFlagEnabledRequest(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 testSetFlagEnabledRequest(self): <NEW_LINE> <INDENT> pass | SetFlagEnabledRequest unit test stubs | 62599046596a897236128f5b |
class PrioretizedReplayBuffer: <NEW_LINE> <INDENT> def __init__(self, buffer_size, batch_size, seed, device, e=1e-4): <NEW_LINE> <INDENT> self.e = e <NEW_LINE> self.device = device <NEW_LINE> self.memory = deque(maxlen=buffer_size) <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done", "priority"]) <NEW_LINE> self.seed = random.seed(seed) <NEW_LINE> <DEDENT> def add(self, state, action, reward, next_state, done, td_error): <NEW_LINE> <INDENT> p = self.e + np.abs(td_error) <NEW_LINE> e = self.experience(state, action, reward, next_state, done, p) <NEW_LINE> self.memory.append(e) <NEW_LINE> <DEDENT> def sample(self): <NEW_LINE> <INDENT> ps = [e.priority for e in self.memory if e is not None] <NEW_LINE> sum_ps = np.sum(ps) <NEW_LINE> experiences = random.choices(self.memory, weights=[e.priority / sum_ps for e in self.memory if e is not None], k = self.batch_size) <NEW_LINE> states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(self.device) <NEW_LINE> dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device) <NEW_LINE> return (states, actions, rewards, next_states, dones) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.memory) | Fixed-size Prioretized Replay buffer to store experience tuples. | 625990460fa83653e46f6234 |
class MultipartContainer(Form): <NEW_LINE> <INDENT> MULTIPART_HEADER = 'multipart/form-data; boundary=%s' <NEW_LINE> def __init__(self, form_params=None): <NEW_LINE> <INDENT> super(MultipartContainer, self).__init__(form_params) <NEW_LINE> self.boundary = get_boundary() <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return 'Multipart/post' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_multipart(headers): <NEW_LINE> <INDENT> conttype, header_name = headers.iget('content-type', '') <NEW_LINE> return conttype.lower().startswith('multipart/form-data') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_postdata(cls, headers, post_data): <NEW_LINE> <INDENT> if not MultipartContainer.is_multipart(headers): <NEW_LINE> <INDENT> raise ValueError('No multipart content-type header.') <NEW_LINE> <DEDENT> environ = {'REQUEST_METHOD': 'POST'} <NEW_LINE> try: <NEW_LINE> <INDENT> fs = cgi.FieldStorage(fp=StringIO.StringIO(post_data), headers=headers.to_dict(), environ=environ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError('Failed to create MultipartContainer.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form_params = FormParameters() <NEW_LINE> for key in fs.list: <NEW_LINE> <INDENT> if key.filename is None: <NEW_LINE> <INDENT> attrs = {'type': INPUT_TYPE_TEXT, 'name': key.name, 'value': key.file.read()} <NEW_LINE> form_params.add_field_by_attrs(attrs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attrs = {'type': INPUT_TYPE_FILE, 'name': key.name, 'value': key.file.read()} <NEW_LINE> form_params.add_field_by_attrs(attrs) <NEW_LINE> form_params.set_file_name(key.name, key.filename) <NEW_LINE> <DEDENT> <DEDENT> return cls(form_params) <NEW_LINE> <DEDENT> <DEDENT> def get_file_name(self, var_name, default=None): <NEW_LINE> <INDENT> return self.form_params.get_file_name(var_name, default=default) <NEW_LINE> <DEDENT> def get_headers(self): <NEW_LINE> <INDENT> return [('Content-Type', self.MULTIPART_HEADER % self.boundary)] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return encode_as_multipart(self, self.boundary) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.items() == other.items() | This class represents a data container for multipart/post
:author: Andres Riancho ([email protected]) | 62599046cad5886f8bdc5a2a |
class Root(object): <NEW_LINE> <INDENT> @cherrypy.expose <NEW_LINE> def index(self): <NEW_LINE> <INDENT> return "Warning!<br/> Core Meltdown Imminent!" | This implements our application class
| 625990468e71fb1e983bce27 |
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return(self.__width) <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return(self.__height) <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> "" <NEW_LINE> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> "" <NEW_LINE> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return(self.__width * self.__height) <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.__width == 0 or self.__height == 0: <NEW_LINE> <INDENT> return(0) <NEW_LINE> <DEDENT> return(self.__width * 2 + self.__height * 2) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> hash_rectangle = "{}".format('\n'.join("#" * self.__width for i in range(0, self.__height))) <NEW_LINE> return hash_rectangle <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return("Rectangle({}, {})".format(self.width, self.height)) | Rectangle class definition | 6259904645492302aabfd82a |
class SqlException(Exception): <NEW_LINE> <INDENT> def __init__(self, arg): <NEW_LINE> <INDENT> self.message = arg | SQL Custom Exception class | 6259904623849d37ff852414 |
class TestArithmeticMixin(unittest.TestCase): <NEW_LINE> <INDENT> def testAdd(self): <NEW_LINE> <INDENT> self.assertEqual(ip.IPv4('192.168.1.1') + 1, ip.IPv4('192.168.1.2')) <NEW_LINE> <DEDENT> def testSub(self): <NEW_LINE> <INDENT> self.assertEqual(ip.IPv4('192.168.1.2') - 1, ip.IPv4('192.168.1.1')) | Test the debmarshal.ip.ArithmeticMixin class. | 6259904626068e7796d4dc9f |
class ReadLayerError(InaSAFEError): <NEW_LINE> <INDENT> suggestion = ( 'Check that the file exists and you have permissions to read it') | When a layer can't be read | 6259904616aa5153ce401846 |
class HTTSOAPAuditReplacePatternsXPath(Base): <NEW_LINE> <INDENT> __tablename__ = 'http_soap_au_rpl_p_xp' <NEW_LINE> __table_args__ = (UniqueConstraint('conn_id', 'pattern_id'), {}) <NEW_LINE> id = Column(Integer, Sequence('htp_sp_ad_rpl_p_xp_seq'), primary_key=True) <NEW_LINE> conn_id = Column(Integer, ForeignKey('http_soap.id', ondelete='CASCADE'), nullable=False) <NEW_LINE> pattern_id = Column(Integer, ForeignKey('msg_xpath.id', ondelete='CASCADE'), nullable=False) <NEW_LINE> cluster_id = Column(Integer, ForeignKey('cluster.id', ondelete='CASCADE'), nullable=False) <NEW_LINE> replace_patterns_xpath = relationship(HTTPSOAP, backref=backref('replace_patterns_xpath', order_by=id, cascade='all, delete, delete-orphan')) <NEW_LINE> pattern = relationship(XPath) | XPath replace patterns for HTTP/SOAP connections.
| 6259904607f4c71912bb078b |
class IllegalValue(PanError, ValueError): <NEW_LINE> <INDENT> pass | Errors from trying to hardware parameters to values not supported by a particular model | 6259904623e79379d538d857 |
class TransformEventProcess(TransformBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TransformEventProcess,self).__init__() <NEW_LINE> <DEDENT> def on_start(self): <NEW_LINE> <INDENT> super(TransformEventProcess,self).on_start() | Transforms which interact with Ion Events. | 62599046b57a9660fecd2dd6 |
class InspectionTool(QgsMapTool): <NEW_LINE> <INDENT> finished = pyqtSignal(QgsVectorLayer, QgsFeature) <NEW_LINE> def __init__(self, canvas, layerfrom, layerto, mapping): <NEW_LINE> <INDENT> QgsMapTool.__init__(self, canvas) <NEW_LINE> self.layerfrom = layerfrom <NEW_LINE> self.layerto = layerto <NEW_LINE> self.fields = mapping <NEW_LINE> self.band = QgsRubberBand(canvas, QGis.Polygon ) <NEW_LINE> self.band.setColor(QColor.fromRgb(255,0,0, 65)) <NEW_LINE> self.band.setWidth(5) <NEW_LINE> self.cursor = QCursor(QPixmap(["16 16 3 1", " c None", ". c #FF0000", "+ c #FFFFFF", " ", " +.+ ", " ++.++ ", " +.....+ ", " +. .+ ", " +. . .+ ", " +. . .+ ", " ++. . .++", " ... ...+... ...", " ++. . .++", " +. . .+ ", " +. . .+ ", " ++. .+ ", " ++.....+ ", " ++.++ ", " +.+ "])) <NEW_LINE> <DEDENT> def clearBand(self): <NEW_LINE> <INDENT> self.band.reset() <NEW_LINE> <DEDENT> def canvasReleaseEvent(self, event): <NEW_LINE> <INDENT> searchRadius = (QgsTolerance.toleranceInMapUnits( 5, self.layerfrom, self.canvas().mapRenderer(), QgsTolerance.Pixels)) <NEW_LINE> point = self.toMapCoordinates(event.pos()) <NEW_LINE> rect = QgsRectangle() <NEW_LINE> rect.setXMinimum(point.x() - searchRadius) <NEW_LINE> rect.setXMaximum(point.x() + searchRadius) <NEW_LINE> rect.setYMinimum(point.y() - searchRadius) <NEW_LINE> rect.setYMaximum(point.y() + searchRadius) <NEW_LINE> rq = QgsFeatureRequest().setFilterRect(rect) <NEW_LINE> try: <NEW_LINE> <INDENT> feature = self.layerto.getFeatures(rq).next() <NEW_LINE> self.band.setToGeometry(feature.geometry(), self.layerto) <NEW_LINE> self.finished.emit(self.layerto, feature) <NEW_LINE> return <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> feature = self.layerfrom.getFeatures(rq).next() <NEW_LINE> self.band.setToGeometry(feature.geometry(), self.layerfrom) <NEW_LINE> fields = self.layerto.pendingFields() <NEW_LINE> newfeature = QgsFeature(fields) <NEW_LINE> newfeature.setGeometry(QgsGeometry(feature.geometry())) <NEW_LINE> for indx in xrange(fields.count()): <NEW_LINE> <INDENT> newfeature[indx] = self.layerto.dataProvider().defaultValue( indx ) <NEW_LINE> <DEDENT> for fieldfrom, fieldto in self.fields.iteritems(): <NEW_LINE> <INDENT> newfeature[fieldto] = feature[fieldfrom] <NEW_LINE> <DEDENT> self.finished.emit(self.layerto, newfeature) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def activate(self): <NEW_LINE> <INDENT> self.canvas().setCursor(self.cursor) <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isZoomTool(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isTransient(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isEditTool(self): <NEW_LINE> <INDENT> return True | Inspection tool which copies the feature to a new layer
and copies selected data from the underlying feature. | 62599046004d5f362081f993 |
class IndexView(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return render(request, 'index.html') | 首页广告 | 6259904650485f2cf55dc2e1 |
class Q(tree.Node): <NEW_LINE> <INDENT> AND = 'AND' <NEW_LINE> OR = 'OR' <NEW_LINE> default = AND <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Q, self).__init__(children=list(args) + list(kwargs.items())) <NEW_LINE> <DEDENT> def _combine(self, other, conn): <NEW_LINE> <INDENT> if not isinstance(other, Q): <NEW_LINE> <INDENT> raise TypeError(other) <NEW_LINE> <DEDENT> obj = type(self)() <NEW_LINE> obj.connector = conn <NEW_LINE> obj.add(self, conn) <NEW_LINE> obj.add(other, conn) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return self._combine(other, self.OR) <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return self._combine(other, self.AND) <NEW_LINE> <DEDENT> def __invert__(self): <NEW_LINE> <INDENT> obj = type(self)() <NEW_LINE> obj.add(self, self.AND) <NEW_LINE> obj.negate() <NEW_LINE> return obj <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> clone = self.__class__._new_instance( children=[], connector=self.connector, negated=self.negated) <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> if hasattr(child, 'clone'): <NEW_LINE> <INDENT> clone.children.append(child.clone()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> clone.children.append(child) <NEW_LINE> <DEDENT> <DEDENT> return clone <NEW_LINE> <DEDENT> def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): <NEW_LINE> <INDENT> clause, joins = query._add_q(self, reuse, allow_joins=allow_joins, split_subq=False) <NEW_LINE> query.promote_joins(joins) <NEW_LINE> return clause <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _refs_aggregate(cls, obj, existing_aggregates): <NEW_LINE> <INDENT> if not isinstance(obj, tree.Node): <NEW_LINE> <INDENT> aggregate, aggregate_lookups = refs_aggregate(obj[0].split(LOOKUP_SEP), existing_aggregates) <NEW_LINE> if not aggregate and hasattr(obj[1], 'refs_aggregate'): <NEW_LINE> <INDENT> return obj[1].refs_aggregate(existing_aggregates) <NEW_LINE> <DEDENT> return aggregate, aggregate_lookups <NEW_LINE> <DEDENT> for c in obj.children: <NEW_LINE> <INDENT> aggregate, aggregate_lookups = cls._refs_aggregate(c, existing_aggregates) <NEW_LINE> if aggregate: <NEW_LINE> <INDENT> return aggregate, aggregate_lookups <NEW_LINE> <DEDENT> <DEDENT> return False, () <NEW_LINE> <DEDENT> def refs_aggregate(self, existing_aggregates): <NEW_LINE> <INDENT> if not existing_aggregates: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._refs_aggregate(self, existing_aggregates) | Encapsulates filters as objects that can then be combined logically (using
`&` and `|`). | 625990461f5feb6acb163f4f |
class ProjectLeadEdit(LoginRequiredMixin, UpdateView): <NEW_LINE> <INDENT> model = QappLead <NEW_LINE> form_class = QappLeadForm <NEW_LINE> template_name = 'SectionA/project_lead_create.html' <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> pkey = kwargs.get('pk') <NEW_LINE> obj = self.model.objects.filter(id=pkey).first() <NEW_LINE> if check_can_edit(obj.qapp, request.user): <NEW_LINE> <INDENT> return render(request, self.template_name, {'object': obj, 'form': self.form_class(instance=obj), 'qapp_id': obj.qapp.id}) <NEW_LINE> <DEDENT> reason = 'You cannot edit this data.' <NEW_LINE> return HttpResponseRedirect( '/detail/%s' % obj.qapp.id, 401, reason) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> pkey = kwargs.get('pk') <NEW_LINE> instance = self.model.objects.filter(id=pkey).first() <NEW_LINE> qapp = instance.qapp <NEW_LINE> if check_can_edit(qapp, request.user): <NEW_LINE> <INDENT> form = self.form_class(request.POST, instance=instance) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> form.save() <NEW_LINE> return HttpResponseRedirect('/detail/%s' % qapp.id) <NEW_LINE> <DEDENT> return render(request, self.template_name, {'form': form}) <NEW_LINE> <DEDENT> reason = 'You cannot edit this data.' <NEW_LINE> return HttpResponseRedirect('/detail/%s' % qapp.id, 401, reason) | Class view for editing project leads. | 6259904630dc7b76659a0b8c |
class LocalCrystal(LocalRunner): <NEW_LINE> <INDENT> def _submit_job(self,inpfn,outfn="stdout",jobname="",loc=""): <NEW_LINE> <INDENT> exe = self.BIN+"crystal < %s"%inpfn <NEW_LINE> prep_commands=["cp %s INPUT"%inpfn] <NEW_LINE> final_commands = ["rm *.pe[0-9]","rm *.pe[0-9][0-9]"] <NEW_LINE> if jobname == "": <NEW_LINE> <INDENT> jobname = outfn <NEW_LINE> <DEDENT> if loc == "": <NEW_LINE> <INDENT> loc = os.getcwd() <NEW_LINE> <DEDENT> qid = self._qsub(exe,prep_commands,final_commands,jobname,outfn,loc) <NEW_LINE> return qid | Fully defined submission class. Defines interaction with specific
program to be run. | 62599046a8ecb0332587256b |
class BigIntegerField(IntegerField): <NEW_LINE> <INDENT> def to_python(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Int64(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return value | A field that always stores and retrieves numbers as bson.int64.Int64. | 6259904623e79379d538d858 |
class MinList(object): <NEW_LINE> <INDENT> def __init__(self, length): <NEW_LINE> <INDENT> self.__length = length <NEW_LINE> self.__minimums = [] <NEW_LINE> <DEDENT> def append(self, value): <NEW_LINE> <INDENT> mins_length = len(self.__minimums) <NEW_LINE> if mins_length < self.__length: <NEW_LINE> <INDENT> self.__minimums.append(value) <NEW_LINE> self.__minimums.sort(reverse=True) <NEW_LINE> return <NEW_LINE> <DEDENT> if value >= self.__minimums[0]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for i in range(mins_length): <NEW_LINE> <INDENT> if value < self.__minimums[i]: <NEW_LINE> <INDENT> self.__minimums[i] = value <NEW_LINE> self.__minimums.sort(reverse=True) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def max(self): <NEW_LINE> <INDENT> if not self.__minimums: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__minimums[0] <NEW_LINE> <DEDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> minimums = Str.collection(self.__minimums) <NEW_LINE> return "MinList:{length:%s, minimums:%s}" % (self.__length, minimums) | classdocs | 62599046be383301e0254b73 |
@keras_export('keras.constraints.MinMaxNorm', 'keras.constraints.min_max_norm') <NEW_LINE> class MinMaxNorm(Constraint): <NEW_LINE> <INDENT> def __init__(self, min_value=0.0, max_value=1.0, rate=1.0, axis=0): <NEW_LINE> <INDENT> self.min_value = min_value <NEW_LINE> self.max_value = max_value <NEW_LINE> self.rate = rate <NEW_LINE> self.axis = axis <NEW_LINE> <DEDENT> @doc_controls.do_not_generate_docs <NEW_LINE> def __call__(self, w): <NEW_LINE> <INDENT> norms = K.sqrt( math_ops.reduce_sum(math_ops.square(w), axis=self.axis, keepdims=True)) <NEW_LINE> desired = ( self.rate * K.clip(norms, self.min_value, self.max_value) + (1 - self.rate) * norms) <NEW_LINE> return w * (desired / (K.epsilon() + norms)) <NEW_LINE> <DEDENT> @doc_controls.do_not_generate_docs <NEW_LINE> def get_config(self): <NEW_LINE> <INDENT> return { 'min_value': self.min_value, 'max_value': self.max_value, 'rate': self.rate, 'axis': self.axis } | MinMaxNorm weight constraint.
Constrains the weights incident to each hidden unit
to have the norm between a lower bound and an upper bound.
Also available via the shortcut function `tf.keras.constraints.min_max_norm`.
Args:
min_value: the minimum norm for the incoming weights.
max_value: the maximum norm for the incoming weights.
rate: rate for enforcing the constraint: weights will be
rescaled to yield
`(1 - rate) * norm + rate * norm.clip(min_value, max_value)`.
Effectively, this means that rate=1.0 stands for strict
enforcement of the constraint, while rate<1.0 means that
weights will be rescaled at each step to slowly move
towards a value inside the desired interval.
axis: integer, axis along which to calculate weight norms.
For instance, in a `Dense` layer the weight matrix
has shape `(input_dim, output_dim)`,
set `axis` to `0` to constrain each weight vector
of length `(input_dim,)`.
In a `Conv2D` layer with `data_format="channels_last"`,
the weight tensor has shape
`(rows, cols, input_depth, output_depth)`,
set `axis` to `[0, 1, 2]`
to constrain the weights of each filter tensor of size
`(rows, cols, input_depth)`. | 625990463617ad0b5ee07496 |
class BrickletPiezoSpeaker(Device): <NEW_LINE> <INDENT> DEVICE_IDENTIFIER = 242 <NEW_LINE> DEVICE_DISPLAY_NAME = 'Piezo Speaker Bricklet' <NEW_LINE> DEVICE_URL_PART = 'piezo_speaker' <NEW_LINE> CALLBACK_BEEP_FINISHED = 4 <NEW_LINE> CALLBACK_MORSE_CODE_FINISHED = 5 <NEW_LINE> FUNCTION_BEEP = 1 <NEW_LINE> FUNCTION_MORSE_CODE = 2 <NEW_LINE> FUNCTION_CALIBRATE = 3 <NEW_LINE> FUNCTION_GET_IDENTITY = 255 <NEW_LINE> BEEP_DURATION_OFF = 0 <NEW_LINE> BEEP_DURATION_INFINITE = 4294967295 <NEW_LINE> def __init__(self, uid, ipcon): <NEW_LINE> <INDENT> Device.__init__(self, uid, ipcon, BrickletPiezoSpeaker.DEVICE_IDENTIFIER, BrickletPiezoSpeaker.DEVICE_DISPLAY_NAME) <NEW_LINE> self.api_version = (2, 0, 0) <NEW_LINE> self.response_expected[BrickletPiezoSpeaker.FUNCTION_BEEP] = BrickletPiezoSpeaker.RESPONSE_EXPECTED_FALSE <NEW_LINE> self.response_expected[BrickletPiezoSpeaker.FUNCTION_MORSE_CODE] = BrickletPiezoSpeaker.RESPONSE_EXPECTED_FALSE <NEW_LINE> self.response_expected[BrickletPiezoSpeaker.FUNCTION_CALIBRATE] = BrickletPiezoSpeaker.RESPONSE_EXPECTED_ALWAYS_TRUE <NEW_LINE> self.response_expected[BrickletPiezoSpeaker.FUNCTION_GET_IDENTITY] = BrickletPiezoSpeaker.RESPONSE_EXPECTED_ALWAYS_TRUE <NEW_LINE> self.callback_formats[BrickletPiezoSpeaker.CALLBACK_BEEP_FINISHED] = (8, '') <NEW_LINE> self.callback_formats[BrickletPiezoSpeaker.CALLBACK_MORSE_CODE_FINISHED] = (8, '') <NEW_LINE> ipcon.add_device(self) <NEW_LINE> <DEDENT> def beep(self, duration, frequency): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> duration = int(duration) <NEW_LINE> frequency = int(frequency) <NEW_LINE> self.ipcon.send_request(self, BrickletPiezoSpeaker.FUNCTION_BEEP, (duration, frequency), 'I H', 0, '') <NEW_LINE> <DEDENT> def morse_code(self, morse, frequency): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> morse = create_string(morse) <NEW_LINE> frequency = int(frequency) <NEW_LINE> self.ipcon.send_request(self, BrickletPiezoSpeaker.FUNCTION_MORSE_CODE, (morse, frequency), '60s H', 0, '') <NEW_LINE> <DEDENT> def calibrate(self): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> return self.ipcon.send_request(self, BrickletPiezoSpeaker.FUNCTION_CALIBRATE, (), '', 9, '!') <NEW_LINE> <DEDENT> def get_identity(self): <NEW_LINE> <INDENT> return GetIdentity(*self.ipcon.send_request(self, BrickletPiezoSpeaker.FUNCTION_GET_IDENTITY, (), '', 33, '8s 8s c 3B 3B H')) <NEW_LINE> <DEDENT> def register_callback(self, callback_id, function): <NEW_LINE> <INDENT> if function is None: <NEW_LINE> <INDENT> self.registered_callbacks.pop(callback_id, None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.registered_callbacks[callback_id] = function | Creates beep with configurable frequency | 62599046435de62698e9d15f |
class map_keyword(parser.keyword): <NEW_LINE> <INDENT> def __init__(self, sString): <NEW_LINE> <INDENT> parser.keyword.__init__(self, sString) | unique_id = port_map_aspect : map_keyword | 62599046d99f1b3c44d069fa |
class ReTweet(Tweet): <NEW_LINE> <INDENT> def as_html(self, template=None): <NEW_LINE> <INDENT> return self._render('ReTweet', template) | ReTweet object based from twitter-api json
| 6259904607f4c71912bb078d |
class ResourceGenerator(object): <NEW_LINE> <INDENT> def __init__(self, organization, package): <NEW_LINE> <INDENT> self.organization = organization <NEW_LINE> self.package = package <NEW_LINE> self.metadata = importlib.import_module('%s.metadata' % package) <NEW_LINE> self.env = Environment( keep_trailing_newline=True, loader=PackageLoader('%s.sphinx' % self.organization, 'templates')) <NEW_LINE> <DEDENT> def conf(self): <NEW_LINE> <INDENT> return self.env.get_template('conf.py.j2').render( metadata=self.metadata, package=self.package) <NEW_LINE> <DEDENT> def makefile(self): <NEW_LINE> <INDENT> return self.env.get_template('Makefile.j2').render( metadata=self.metadata, package=self.package) | Class to generate Sphinx resources.
Args:
organization (str): name of the profile of the organization on GitHub.
package (str): package to be documented.
metadata (Python module): module containing the package metadata.
env (:py:class:`jinja2.Environment`): the Jinja2 environment. | 62599046e76e3b2f99fd9d67 |
class IC_4000(Base_14pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [None, None, None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] <NEW_LINE> self.pins = pinlist_quick(self.pins) <NEW_LINE> self.uses_pincls = True <NEW_LINE> self.setIC({1: {'desc': 'NC'}, 2: {'desc': 'NC'}, 3: {'desc': 'A1: Input 1 of NOR gate 1'}, 4: {'desc': 'B1: Input 2 of NOR gate 1'}, 5: {'desc': 'C1: Input 3 of NOR gate 1'}, 6: {'desc': 'Q1: Output of NOR gate 1'}, 7: {'desc': 'GND'}, 8: {'desc': 'B2: Input of NOT gate'}, 9: {'desc': 'Q2: Output of NOT gate'}, 10: {'desc': 'Q3: Output of NOR gate 2'}, 11: {'desc': 'C3: Input 3 of NOR gate 2'}, 12: {'desc': 'B3: Input 2 of NOR gate 2'}, 13: {'desc': 'A3: Input 1 of NOR gate 2'}, 14: {'desc': 'VCC'} }) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[6] = NOR(self.pins[3].value, self.pins[4].value, self.pins[5].value).output() <NEW_LINE> output[10] = NOR(self.pins[11].value, self.pins[12].value, self.pins[13].value).output() <NEW_LINE> output[9] = NOT(self.pins[8].value).output() <NEW_LINE> if self.pins[7].value == 0 and self.pins[14].value == 1: <NEW_LINE> <INDENT> self.setIC(output) <NEW_LINE> for i in self.outputConnector: <NEW_LINE> <INDENT> self.outputConnector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print ("Ground and VCC pins have not been configured correctly.") | Dual 3 Input NOR gate + one NOT gate IC.
Pin_6 = NOR(Pin_3, Pin_4, Pin_5)
Pin_10 = NOR(Pin_11, Pin_12, Pin_13)
Pin_9 = NOT(Pin_8) | 6259904663b5f9789fe864c7 |
class Proxy(YmvcBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._signaled_attrs = set() <NEW_LINE> <DEDENT> def add_obs_attrs(self, *attributes): <NEW_LINE> <INDENT> self._signaled_attrs.update(set(attributes)) <NEW_LINE> <DEDENT> def remove_obs_attrs(self, *attributes): <NEW_LINE> <INDENT> self._signaled_attrs.difference_update(set(attributes)) <NEW_LINE> <DEDENT> def bind(self, slot, immediate_callback=True): <NEW_LINE> <INDENT> super(Proxy, self).bind(slot) <NEW_LINE> if immediate_callback and slot._signal == attribute_signal(): <NEW_LINE> <INDENT> self.slot_get_attr(slot) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if not hasattr(self, name): <NEW_LINE> <INDENT> return YmvcBase.__setattr__(self, name, value) <NEW_LINE> <DEDENT> if name in self._signaled_attrs: <NEW_LINE> <INDENT> self._setattr_call(name, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return YmvcBase.__setattr__(self, name, value) <NEW_LINE> <DEDENT> <DEDENT> def _setattr_call(self, name, value): <NEW_LINE> <INDENT> YmvcBase.__setattr__(self, name, value) <NEW_LINE> self.notify_attr(name) <NEW_LINE> <DEDENT> def notify_attr(self, name): <NEW_LINE> <INDENT> kwargs = {_SIGNAL: attribute_signal(), name: getattr(self, name)} <NEW_LINE> self._ysignal.emit(**kwargs) <NEW_LINE> <DEDENT> def slot_get_attr(self, slot): <NEW_LINE> <INDENT> name = slot._attributes[0] <NEW_LINE> kwargs = {_SIGNAL: attribute_signal(), name: getattr(self, name)} <NEW_LINE> return self._ysignal.emit_slot(slot, **kwargs) | Contains the data of your application | 62599046d4950a0f3b1117ef |
class SolrTestCase(Sandboxed, ptc.PloneTestCase): <NEW_LINE> <INDENT> layer = layer | base class for integration tests | 62599046711fe17d825e164b |
class DescribeSmpnFnrResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ResponseData = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("ResponseData") is not None: <NEW_LINE> <INDENT> self.ResponseData = FNRResponse() <NEW_LINE> self.ResponseData._deserialize(params.get("ResponseData")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | DescribeSmpnFnr返回参数结构体
| 6259904676d4e153a661dc23 |
class ItemEdit(MethodView): <NEW_LINE> <INDENT> def put(self, _id): <NEW_LINE> <INDENT> if not session.get('check'): <NEW_LINE> <INDENT> return 401 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> req = request.get_json(silent=True) <NEW_LINE> name, price, desc = (req[i] for i in req) <NEW_LINE> item = ItemModel.query.get(_id) <NEW_LINE> <DEDENT> if not item: <NEW_LINE> <INDENT> new_item = ItemModel(name, price, description) <NEW_LINE> db.session.add(new_item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item.name = name <NEW_LINE> item.price = price <NEW_LINE> item.description = description <NEW_LINE> <DEDENT> db.session.commit() <NEW_LINE> return {'msg': f'Item {item.name} was successfully updated.'}, 201 <NEW_LINE> <DEDENT> def delete(self, _id): <NEW_LINE> <INDENT> if not session.get('check'): <NEW_LINE> <INDENT> return 401 <NEW_LINE> <DEDENT> item = ItemModel.query.get(_id) <NEW_LINE> if not item: <NEW_LINE> <INDENT> return 204 <NEW_LINE> <DEDENT> db.session.delete(item) <NEW_LINE> db.session.commit() <NEW_LINE> return {'msg': f'Item {item.name} was successfully deleted.'}, 202 | @desc: handles 'PUT', 'DELETE' requests with id as url parameter.
@route: /api/items/<id> | 62599046097d151d1a2c23c7 |
class Consumer(object): <NEW_LINE> <INDENT> def __init__(self, func=None): <NEW_LINE> <INDENT> super(Consumer, self).__init__() <NEW_LINE> if func is None: <NEW_LINE> <INDENT> func = (lambda s: s.value) <NEW_LINE> <DEDENT> self.func = func <NEW_LINE> self.initial_state = list() <NEW_LINE> self.state = list() <NEW_LINE> self.result = list() <NEW_LINE> self.num_of_paths = None <NEW_LINE> self.grid = None <NEW_LINE> self.seed = None <NEW_LINE> <DEDENT> def initialize(self, grid=None, num_of_paths=None, seed=None): <NEW_LINE> <INDENT> self.num_of_paths = num_of_paths <NEW_LINE> self.grid = grid <NEW_LINE> self.seed = seed <NEW_LINE> self.result = list() <NEW_LINE> self.state = self.initial_state <NEW_LINE> <DEDENT> def initialize_worker(self, process_num=None): <NEW_LINE> <INDENT> self.initialize(self.grid, self.num_of_paths, self.seed) <NEW_LINE> <DEDENT> def initialize_path(self, path_num=None): <NEW_LINE> <INDENT> self.state = copy(self.initial_state) <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def consume(self, state): <NEW_LINE> <INDENT> self.state.append(self.func(state)) <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def finalize_path(self, path_num=None): <NEW_LINE> <INDENT> self.result.append((path_num, self.state)) <NEW_LINE> <DEDENT> def finalize_worker(self, process_num=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> if self.result: <NEW_LINE> <INDENT> self.result = sorted(self.result, key=lambda x: x[0]) <NEW_LINE> p, r = list(map(list, list(zip(*self.result)))) <NEW_LINE> self.result = r <NEW_LINE> <DEDENT> <DEDENT> def put(self): <NEW_LINE> <INDENT> return self.result <NEW_LINE> <DEDENT> def get(self, queue_get): <NEW_LINE> <INDENT> if isinstance(queue_get, (tuple, list)): <NEW_LINE> <INDENT> self.result.extend(queue_get) | base class for simulation consumers | 625990463eb6a72ae038b9b6 |
class JSONResponseMixin(object): <NEW_LINE> <INDENT> def render_to_response(self, context): <NEW_LINE> <INDENT> return self.get_json_response(self.convert_context_to_json(context)) <NEW_LINE> <DEDENT> def get_json_response(self, content, **httpresponse_kwargs): <NEW_LINE> <INDENT> return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) <NEW_LINE> <DEDENT> def convert_context_to_json(self, context): <NEW_LINE> <INDENT> return json.dumps(context) | Classe `mixin` baseada no exemplo em:
https://docs.djangoproject.com/en/dev/topics/class-based-views/ | 625990461f5feb6acb163f51 |
class TabGroup(object): <NEW_LINE> <INDENT> implements(IAthenaTransportable) <NEW_LINE> jsClass = u'Methanal.Widgets.TabGroup' <NEW_LINE> def __init__(self, id, title, tabs): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.title = title <NEW_LINE> self.tabs = [] <NEW_LINE> for tab in tabs: <NEW_LINE> <INDENT> self._manageTab(tab) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s id=%r title=%r tabs=%r>' % ( type(self).__name__, self.id, self.title, self.tabs) <NEW_LINE> <DEDENT> def _manageTab(self, tab): <NEW_LINE> <INDENT> if tab not in self.tabs: <NEW_LINE> <INDENT> self.tabs.append(tab) <NEW_LINE> tab.group = self.id <NEW_LINE> <DEDENT> <DEDENT> def _releaseTab(self, tab): <NEW_LINE> <INDENT> if tab in self.tabs: <NEW_LINE> <INDENT> self.tabs.remove(tab) <NEW_LINE> tab.group = None <NEW_LINE> <DEDENT> <DEDENT> def getTabIDs(self): <NEW_LINE> <INDENT> return [tab.id for tab in self.tabs] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def mergeGroups(cls, old, new): <NEW_LINE> <INDENT> return cls(new.id, new.title, old.tabs + new.tabs) <NEW_LINE> <DEDENT> def getInitialArguments(self): <NEW_LINE> <INDENT> return [self.id, self.title, self.getTabIDs()] | Visually group labels of L{methanal.widgets.Tab}s together.
@type id: C{unicode}
@ivar id: Unique identifier.
@type title: C{unicode}
@ivar title: Title of the group, used by L{methanal.widgets.TabView} when
constructing the tab list.
@type tabs: C{list} of L{methanal.widgets.Tab}
@ivar tabs: Tabs to group together. | 625990460fa83653e46f6238 |
class ProjectFormSimplified(wtf.Form): <NEW_LINE> <INDENT> description = wtforms.TextField( 'Description <span class="error">*</span>', [wtforms.validators.Required()] ) <NEW_LINE> url = wtforms.TextField( 'URL', [wtforms.validators.optional()] ) <NEW_LINE> avatar_email = wtforms.TextField( 'Avatar email', [wtforms.validators.optional()] ) <NEW_LINE> tags = wtforms.TextField( 'Project tags', [wtforms.validators.optional()] ) | Form to edit the description of a project. | 62599046d10714528d69f03b |
class ConsistentHashRing(object): <NEW_LINE> <INDENT> def __init__(self, replicas=100): <NEW_LINE> <INDENT> self.replicas = replicas <NEW_LINE> self._keys = [] <NEW_LINE> self._nodes = {} <NEW_LINE> <DEDENT> def _hash(self, key): <NEW_LINE> <INDENT> return int(hashlib.md5(key.encode('utf-8')).hexdigest(), 16) <NEW_LINE> <DEDENT> def _repl_iterator(self, nodename): <NEW_LINE> <INDENT> return (self._hash("%s:%s" % (nodename, i)) for i in range(self.replicas)) <NEW_LINE> <DEDENT> def __setitem__(self, nodename, node): <NEW_LINE> <INDENT> for hash_ in self._repl_iterator(nodename): <NEW_LINE> <INDENT> if hash_ in self._nodes: <NEW_LINE> <INDENT> raise ValueError("Node name %r is " "already present" % nodename) <NEW_LINE> <DEDENT> self._nodes[hash_] = node <NEW_LINE> bisect.insort(self._keys, hash_) <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, nodename): <NEW_LINE> <INDENT> for hash_ in self._repl_iterator(nodename): <NEW_LINE> <INDENT> del self._nodes[hash_] <NEW_LINE> index = bisect.bisect_left(self._keys, hash_) <NEW_LINE> del self._keys[index] <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> hash_ = self._hash(key) <NEW_LINE> start = bisect.bisect(self._keys, hash_) <NEW_LINE> l = len(self._keys) <NEW_LINE> if start == l: <NEW_LINE> <INDENT> start = 0 <NEW_LINE> <DEDENT> return self._nodes[self._keys[start]] | Implement a consistent hashing ring. | 625990468e71fb1e983bce2b |
class Location(Parameter): <NEW_LINE> <INDENT> def __init__(self, name: str): <NEW_LINE> <INDENT> super(Location, self).__init__(tf.identity, name) | Location parameters live in the real line. | 6259904615baa723494632ee |
class CallUnits(unittest.TestCase): <NEW_LINE> <INDENT> def testCase010(self): <NEW_LINE> <INDENT> arg = tdata + '/b/*/c.p"""[!:]*"""' <NEW_LINE> if RTE & RTE_WIN32: <NEW_LINE> <INDENT> resX = [tdata + '\\b\\*\\c.p[!:]*'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resX = [tdata + '/b/*/c.p[!:]*'] <NEW_LINE> <DEDENT> res = filesysobjects.apppaths.splitapppathx(arg, stripquote=True) <NEW_LINE> self.assertEqual(res, resX) <NEW_LINE> <DEDENT> def testCase020(self): <NEW_LINE> <INDENT> arg = tdata + '/b/*/c.p"""[!;]*"""' <NEW_LINE> if RTE & RTE_WIN32: <NEW_LINE> <INDENT> resX = [tdata + '\\b\\*\\c.p[!;]*'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resX = [tdata + '/b/*/c.p[!;]*'] <NEW_LINE> <DEDENT> res = filesysobjects.apppaths.splitapppathx(arg, stripquote=True) <NEW_LINE> self.assertEqual(res, resX) | Sets the specific data array and required parameters for test case.
| 6259904626238365f5fadeb8 |
class Spheres(DataSet): <NEW_LINE> <INDENT> fancy_name = "Spheres dataset" <NEW_LINE> __slots__ = ['d', 'n_spheres', 'r'] <NEW_LINE> def __init__(self, d=DEFAULT['spheres']['d'], n_spheres=DEFAULT['spheres']['n_spheres'], r=DEFAULT['spheres']['r']): <NEW_LINE> <INDENT> self.d = d <NEW_LINE> self.n_spheres = n_spheres <NEW_LINE> self.r = r <NEW_LINE> <DEDENT> def sample(self, n_samples, noise=0, seed=DEFAULT['spheres']['seed'], ratio_largesphere=DEFAULT['spheres']['ratio_largesphere'], train: bool = True, old_implementation=False): <NEW_LINE> <INDENT> np.random.seed(seed) <NEW_LINE> if old_implementation: <NEW_LINE> <INDENT> seeds = np.random.random_integers(0, high=1000, size=self.n_spheres) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seeds = np.random.randint(0, high=1000, size=(2, self.n_spheres)) <NEW_LINE> if train: <NEW_LINE> <INDENT> seeds = seeds[0][:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seeds = seeds[1][:] <NEW_LINE> <DEDENT> <DEDENT> np.random.seed(42) <NEW_LINE> variance = 10/np.sqrt(self.d) <NEW_LINE> shift_matrix = np.random.normal(0, variance, [self.n_spheres, self.d+1]) <NEW_LINE> spheres = [] <NEW_LINE> n_datapoints = 0 <NEW_LINE> for i in np.arange(self.n_spheres-1): <NEW_LINE> <INDENT> sphere, labels = dsphere(n=n_samples, d=self.d, r=self.r, seed=seeds[i], noise=noise) <NEW_LINE> spheres.append(sphere+shift_matrix[i, :]) <NEW_LINE> n_datapoints += n_samples <NEW_LINE> <DEDENT> n_samples_big = ratio_largesphere*n_samples <NEW_LINE> big, labels = dsphere(n=n_samples_big, d=self.d, r=self.r*5, seed=seeds[-1], noise=noise) <NEW_LINE> spheres.append(big) <NEW_LINE> n_datapoints += n_samples_big <NEW_LINE> dataset = np.concatenate(spheres, axis=0) <NEW_LINE> labels = np.zeros(n_datapoints) <NEW_LINE> label_index = 0 <NEW_LINE> for index, data in enumerate(spheres): <NEW_LINE> <INDENT> n_sphere_samples = data.shape[0] <NEW_LINE> labels[label_index:label_index+n_sphere_samples] = index <NEW_LINE> label_index += n_sphere_samples <NEW_LINE> <DEDENT> return dataset, labels <NEW_LINE> <DEDENT> def sample_manifold(self): <NEW_LINE> <INDENT> raise AttributeError('{} cannot sample from manifold.'.format(self.fancy_name)) | Spheres dataset from TopAE paper
#todo: make proper reference | 62599046be383301e0254b75 |
@pytest.mark.components <NEW_LINE> @pytest.allure.story('Clients') <NEW_LINE> @pytest.allure.feature('POST') <NEW_LINE> class Test_PFE_Components(object): <NEW_LINE> <INDENT> @pytest.allure.link('https://jira.qumu.com/browse/TC-43114') <NEW_LINE> @pytest.mark.Clients <NEW_LINE> @pytest.mark.POST <NEW_LINE> def test_TC_43114_POST_Clients_Width_Lt(self, context): <NEW_LINE> <INDENT> with pytest.allure.step("""Verify that user is able to add source constraint rule with specific rule for parameter 'Width>LT(Less Than) using request POST '/clients/'."""): <NEW_LINE> <INDENT> clientDetails = context.sc.ClientDetails( id='sourceRuleWidthLT', matchingRule={'operator': 'ALL', 'rules': [], 'groups': []}, name='POST: Client with Source Rule Width LT', sourceSelectionRule=[{ 'operator': 'ALL', 'rules': [{ 'expressionType': 'Single', 'contextField': 'widthPx', 'operator': 'LT', 'contextFieldType': 'String', 'matchValue': 600, 'contextFieldKey': None }], 'groups': [] }]) <NEW_LINE> response = check( context.cl.Clients.createEntity( body=clientDetails ) ) | PFE Clients test cases. | 6259904607f4c71912bb078f |
class CheckOperator(BaseOperator): <NEW_LINE> <INDENT> template_fields = ('sql',) <NEW_LINE> template_ext = ('.hql', '.sql',) <NEW_LINE> ui_color = '#fff7e6' <NEW_LINE> @apply_defaults <NEW_LINE> def __init__( self, sql, conn_id=None, *args, **kwargs): <NEW_LINE> <INDENT> super(CheckOperator, self).__init__(*args, **kwargs) <NEW_LINE> self.conn_id = conn_id <NEW_LINE> self.sql = sql <NEW_LINE> <DEDENT> def execute(self, context=None): <NEW_LINE> <INDENT> logging.info('Executing SQL check: ' + self.sql) <NEW_LINE> records = self.get_db_hook().get_first(self.sql) <NEW_LINE> logging.info("Record: " + str(records)) <NEW_LINE> if not records: <NEW_LINE> <INDENT> raise AirflowException("The query returned None") <NEW_LINE> <DEDENT> elif not all([bool(r) for r in records]): <NEW_LINE> <INDENT> exceptstr = "Test failed.\nQuery:\n{q}\nResults:\n{r!s}" <NEW_LINE> raise AirflowException(exceptstr.format(q=self.sql, r=records)) <NEW_LINE> <DEDENT> logging.info("Success.") <NEW_LINE> <DEDENT> def get_db_hook(self): <NEW_LINE> <INDENT> return BaseHook.get_hook(conn_id=self.conn_id) | Performs checks against a db. The ``CheckOperator`` expects
a sql query that will return a single row. Each value on that
first row is evaluated using python ``bool`` casting. If any of the
values return ``False`` the check is failed and errors out.
Note that Python bool casting evals the following as ``False``:
* False
* 0
* Empty string (``""``)
* Empty list (``[]``)
* Empty dictionary or set (``{}``)
Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if
the count ``== 0``. You can craft much more complex query that could,
for instance, check that the table has the same number of rows as
the source table upstream, or that the count of today's partition is
greater than yesterday's partition, or that a set of metrics are less
than 3 standard deviation for the 7 day average.
This operator can be used as a data quality check in your pipeline, and
depending on where you put it in your DAG, you have the choice to
stop the critical path, preventing from
publishing dubious data, or on the side and receive email alerts
without stopping the progress of the DAG.
Note that this is an abstract class and get_db_hook
needs to be defined. Whereas a get_db_hook is hook that gets a
single record from an external source.
:param sql: the sql to be executed
:type sql: string | 6259904630c21e258be99b63 |
class Solution: <NEW_LINE> <INDENT> def longestCommonSubsequence(self, A, B): <NEW_LINE> <INDENT> x = len(A) <NEW_LINE> y = len(B) <NEW_LINE> dp = [[0 for j in range(y+1)] for i in range(x+1)] <NEW_LINE> for i in range(1, x+1): <NEW_LINE> <INDENT> for j in range(1, y+1): <NEW_LINE> <INDENT> if A[i-1] == B[j-1]: <NEW_LINE> <INDENT> dp[i][j] = dp[i-1][j-1] + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp[i][j] = max(dp[i-1][j], dp[i][j-1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dp[x][y] | @param A, B: Two strings.
@return: The length of longest common subsequence of A and B. | 625990464e696a045264e7cf |
class VisitorNodeDispatch(): <NEW_LINE> <INDENT> def __init__(self, tree): <NEW_LINE> <INDENT> self._dispatch(tree) <NEW_LINE> <DEDENT> def node(self, t): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _dispatch(self, t): <NEW_LINE> <INDENT> self.node(t) <NEW_LINE> if (isinstance(t, Expression)): <NEW_LINE> <INDENT> for e in t.params: <NEW_LINE> <INDENT> self._dispatch(e) <NEW_LINE> <DEDENT> <DEDENT> if (isinstance(t, BodyParameterMixin)): <NEW_LINE> <INDENT> for e in t.body: <NEW_LINE> <INDENT> self._dispatch(e) | A visitor which traverses the entire tree.
The nodes are only dispatched t one method. This can be useful for
visiting where only a small number of nodes need to be looked at.
The downside is that most code that uses this visitor must test for
tree type manually.
Params are visited first, then bodies. | 62599046ec188e330fdf9bf9 |
class end(TexCommand): <NEW_LINE> <INDENT> def __init__(self, environment): <NEW_LINE> <INDENT> super().__init__('end', environment) | 'end' tex command wrapper. | 62599046d4950a0f3b1117f0 |
class TLNOutputModuleTest(test_lib.OutputModuleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._output_writer = cli_test_lib.TestOutputWriter() <NEW_LINE> output_mediator = self._CreateOutputMediator() <NEW_LINE> self._output_module = tln.TLNOutputModule( output_mediator, output_writer=self._output_writer) <NEW_LINE> self._event_object = TLNTestEvent() <NEW_LINE> <DEDENT> def testWriteHeader(self): <NEW_LINE> <INDENT> expected_header = b'Time|Source|Host|User|Description\n' <NEW_LINE> self._output_module.WriteHeader() <NEW_LINE> header = self._output_writer.ReadOutput() <NEW_LINE> self.assertEqual(header, expected_header) <NEW_LINE> <DEDENT> def testWriteEventBody(self): <NEW_LINE> <INDENT> formatters_manager.FormattersManager.RegisterFormatter( TLNTestEventFormatter) <NEW_LINE> self._output_module.WriteEventBody(self._event_object) <NEW_LINE> expected_event_body = ( b'1340821021|LOG|ubuntu|root|2012-06-27T18:17:01+00:00; UNKNOWN; ' b'Reporter <CRON> PID: 8442 (pam_unix(cron:session): ' b'session closed for user root)\n') <NEW_LINE> event_body = self._output_writer.ReadOutput() <NEW_LINE> self.assertEqual(event_body, expected_event_body) <NEW_LINE> self.assertEqual(event_body.count(b'|'), 4) <NEW_LINE> formatters_manager.FormattersManager.DeregisterFormatter( TLNTestEventFormatter) | Tests for the TLN output module. | 6259904645492302aabfd82f |
class Config(NamedTuple): <NEW_LINE> <INDENT> localities: Localities <NEW_LINE> events: Events <NEW_LINE> whitelist: Whitelist <NEW_LINE> factors: Factors | The top-level configuration type.
| 625990460a366e3fb87ddd43 |
class RankAllInOrderOfPreference(RankInOrderOfPreference): <NEW_LINE> <INDENT> def validate(self, responses, field): <NEW_LINE> <INDENT> if len(responses) != len(field): <NEW_LINE> <INDENT> raise rfx.WrongNumberOfChoices('all choices in field must be ranked') <NEW_LINE> <DEDENT> super().validate(responses, field) | A response format that requires the user to rank their choices in
order of preference, without weighting. All of the choices must
in the field must be ranked.
The response is expected to be a list of choices, with the more
preferred choices towards the front of the list. | 625990461f5feb6acb163f53 |
class SafeDict(dict): <NEW_LINE> <INDENT> def __missing__(self, key): <NEW_LINE> <INDENT> return '{' + key + '}' | A safe dictionary implementation that does not break down on missing keys | 62599046462c4b4f79dbcd5c |
class PublicUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_create_valid_user_success (self): <NEW_LINE> <INDENT> payload = { 'email' : '[email protected]', 'password' : 'testpass', 'name' : 'Oscar', } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_201_CREATED) <NEW_LINE> user = get_user_model().objects.get(**res.data) <NEW_LINE> self.assertTrue(user.check_password(payload['password'])) <NEW_LINE> self.assertNotIn('password', res.data) <NEW_LINE> <DEDENT> def test_user_exists(self): <NEW_LINE> <INDENT> payload = { 'email' : '[email protected]', 'password' : 'testpass', } <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_password_too_short(self): <NEW_LINE> <INDENT> payload = { 'email' : '[email protected]', 'password' : 'pw', 'name' : 'Oscar', } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exists = get_user_model().objects.filter( email = payload['email'] ).exists() <NEW_LINE> self.assertFalse(user_exists) <NEW_LINE> <DEDENT> def test_create_token_for_user(self): <NEW_LINE> <INDENT> payload = {'email': '[email protected]', 'password': 'testpass'} <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_create_token_invalid_credentials(self): <NEW_LINE> <INDENT> create_user(email = 'test') <NEW_LINE> payload = {'email': '[email protected]', 'password': 'wrong'} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_create_token_no_user(self): <NEW_LINE> <INDENT> payload = {'email': '[email protected]', 'password': 'testpass'} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_create_toke_missing_field(self): <NEW_LINE> <INDENT> payload = {'email': 'one', 'password': ''} <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_retrieve_user_unauthorized(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test the user API (public) | 62599046596a897236128f5e |
class RecloseSequence(IdentifiedObject): <NEW_LINE> <INDENT> def __init__(self, recloseStep=0, recloseDelay=0.0, ProtectedSwitch=None, *args, **kw_args): <NEW_LINE> <INDENT> self.recloseStep = recloseStep <NEW_LINE> self.recloseDelay = recloseDelay <NEW_LINE> self._ProtectedSwitch = None <NEW_LINE> self.ProtectedSwitch = ProtectedSwitch <NEW_LINE> super(RecloseSequence, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["recloseStep", "recloseDelay"] <NEW_LINE> _attr_types = {"recloseStep": int, "recloseDelay": float} <NEW_LINE> _defaults = {"recloseStep": 0, "recloseDelay": 0.0} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["ProtectedSwitch"] <NEW_LINE> _many_refs = [] <NEW_LINE> def getProtectedSwitch(self): <NEW_LINE> <INDENT> return self._ProtectedSwitch <NEW_LINE> <DEDENT> def setProtectedSwitch(self, value): <NEW_LINE> <INDENT> if self._ProtectedSwitch is not None: <NEW_LINE> <INDENT> filtered = [x for x in self.ProtectedSwitch.RecloseSequences if x != self] <NEW_LINE> self._ProtectedSwitch._RecloseSequences = filtered <NEW_LINE> <DEDENT> self._ProtectedSwitch = value <NEW_LINE> if self._ProtectedSwitch is not None: <NEW_LINE> <INDENT> if self not in self._ProtectedSwitch._RecloseSequences: <NEW_LINE> <INDENT> self._ProtectedSwitch._RecloseSequences.append(self) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ProtectedSwitch = property(getProtectedSwitch, setProtectedSwitch) | A reclose sequence (open and close) is defined for each possible reclosure of a breaker.A reclose sequence (open and close) is defined for each possible reclosure of a breaker.
| 6259904615baa723494632f0 |
class BarbicanAdapters(charms_openstack.adapters.OpenStackAPIRelationAdapters): <NEW_LINE> <INDENT> relation_adapters = { 'hsm': HSMAdapter, } <NEW_LINE> def __init__(self, relations): <NEW_LINE> <INDENT> super(BarbicanAdapters, self).__init__( relations, options_instance=BarbicanConfigurationAdapter( port_map=BarbicanCharm.api_ports)) | Adapters class for the Barbican charm.
This plumbs in the BarbicanConfigurationAdapter as the ConfigurationAdapter
to provide additional properties. | 62599046b57a9660fecd2ddb |
class ItemListView(generics.ListAPIView): <NEW_LINE> <INDENT> queryset = Item.objects.all() <NEW_LINE> permission_classes = (PERM_ALLOW_ANY,) <NEW_LINE> serializer_class = ItemSerializer <NEW_LINE> @staticmethod <NEW_LINE> def format_queryset(queryset): <NEW_LINE> <INDENT> new_queryset = [] <NEW_LINE> for bonus in queryset: <NEW_LINE> <INDENT> bonus_class = bonus_factory.get_bonus(bonus.group.tag) <NEW_LINE> bonus_instance = bonus_class(bonus) <NEW_LINE> bonus.fields = bonus_instance.get_fields() <NEW_LINE> new_queryset.append(bonus) <NEW_LINE> <DEDENT> return new_queryset <NEW_LINE> <DEDENT> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> queryset = self.filter_queryset(self.get_queryset()) <NEW_LINE> formatted_queryset = self.format_queryset(queryset) <NEW_LINE> page = self.paginate_queryset(formatted_queryset) <NEW_LINE> if page is not None: <NEW_LINE> <INDENT> serializer = self.get_serializer(page, many=True) <NEW_LINE> return self.get_paginated_response(serializer.data) <NEW_LINE> <DEDENT> serializer = self.get_serializer(formatted_queryset, many=True) <NEW_LINE> return Response(serializer.data) | Widok przedmiotow dostepnych do zakupu | 625990463617ad0b5ee0749a |
class Problem: <NEW_LINE> <INDENT> def __init__(self, directory: str, category: str, name: str, **config): <NEW_LINE> <INDENT> self.directory = directory <NEW_LINE> self.category = category <NEW_LINE> self.name = name <NEW_LINE> self.title = config["title"] <NEW_LINE> self.value = int(config["value"]) <NEW_LINE> self.text = config["text"] <NEW_LINE> self.hint = config["hint"] <NEW_LINE> self.flag = config["flag"].strip() <NEW_LINE> self.id = category + '/' + name <NEW_LINE> self.author = config.get("author") <NEW_LINE> self.files = config.get("files") <NEW_LINE> self.enabled = config.get("enabled", True) <NEW_LINE> self.settings = config.get("deploy", {}) <NEW_LINE> self.replace = {} <NEW_LINE> if self.files: <NEW_LINE> <INDENT> for path in self.files: <NEW_LINE> <INDENT> basename = os.path.basename(path) <NEW_LINE> self.replace[os.path.basename(path)] = "/static/" + os.path.join(category, name, basename).replace(os.sep, "/") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def export(self, url="", static=""): <NEW_LINE> <INDENT> text = self.text <NEW_LINE> for path, to in self.replace.items(): <NEW_LINE> <INDENT> text = re.sub("\\{\\{\s*" + path + "\s*\\}\\}", url.rstrip("/") + to, text) <NEW_LINE> <DEDENT> text = markdown.markdown(text) <NEW_LINE> hint = markdown.markdown(self.hint) <NEW_LINE> if self.files: <NEW_LINE> <INDENT> directory = os.path.join(static, self.category) <NEW_LINE> to = os.path.join(directory, self.name) <NEW_LINE> if not os.path.isdir(to): <NEW_LINE> <INDENT> os.makedirs(to, exist_ok=True) <NEW_LINE> <DEDENT> print("Copying files to {}".format(to)) <NEW_LINE> for file in self.files: <NEW_LINE> <INDENT> shutil.copy(file, to) <NEW_LINE> <DEDENT> <DEDENT> return { "name": self.name, "title": self.title, "text": text, "value": self.value, "hint": hint, "category": self.category, "flag": hashlib.sha512(self.flag.lower().encode()).hexdigest(), "enabled": self.enabled} <NEW_LINE> <DEDENT> def deploy(self): <NEW_LINE> <INDENT> pass | Default problem with an empty deployment method. | 62599046d99f1b3c44d069fe |
class Aaaas(Collection): <NEW_LINE> <INDENT> def __init__(self, wideip): <NEW_LINE> <INDENT> super(Aaaas, self).__init__(wideip) <NEW_LINE> self._meta_data['allowed_lazy_attributes'] = [Aaaa] <NEW_LINE> self._meta_data['attribute_registry'] = {'tm:gtm:wideip:aaaa:aaaastate': Aaaa} | v12.x BIG-IP® AAAA wideip collection | 6259904623849d37ff85241a |
class BonusPositionEstimator(PositionEstimator): <NEW_LINE> <INDENT> NAME = 'Bonus' <NEW_LINE> def __init__(self, medikit_min=250, medikit_max=1500, repair_min=100, repair_max=800, ammo_crate=500, factor=1): <NEW_LINE> <INDENT> self.medikit_min = medikit_min <NEW_LINE> self.medikit_max = medikit_max <NEW_LINE> self.repair_min = repair_min <NEW_LINE> self.repair_max = repair_max <NEW_LINE> self.ammo_crate = ammo_crate <NEW_LINE> self.factor = factor <NEW_LINE> <DEDENT> def value(self, pos): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> closest_bonus = unit_closest_to(pos.x, pos.y)(self.context.world.bonuses) <NEW_LINE> if closest_bonus.type == BonusType.MEDIKIT: <NEW_LINE> <INDENT> bonus_profit = self.medikit_min + sqrt(1 - self.context.health_fraction) * (self.medikit_max - self.medikit_min) <NEW_LINE> <DEDENT> elif closest_bonus.type == BonusType.REPAIR_KIT: <NEW_LINE> <INDENT> bonus_profit = self.repair_min + sqrt(1 - self.context.hull_fraction) * (self.repair_max - self.repair_min) <NEW_LINE> <DEDENT> elif closest_bonus.type == BonusType.AMMO_CRATE: <NEW_LINE> <INDENT> bonus_profit = self.ammo_crate <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bonus_profit = 0 <NEW_LINE> <DEDENT> bonus_summand = max(0, bonus_profit) <NEW_LINE> if closest_bonus.get_distance_to(pos.x, pos.y) > 10: <NEW_LINE> <INDENT> bonus_summand = 0 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> bonus_summand = 0 <NEW_LINE> <DEDENT> return bonus_summand * self.factor | Bonus priority:
+ Need this bonus
(*) - Close to enemy going for it | 6259904607f4c71912bb0791 |
class Canvas(app.Canvas): <NEW_LINE> <INDENT> def __init__(self, data, theta=30.0, phi=90.0, z=6.0): <NEW_LINE> <INDENT> app.Canvas.__init__(self, size=(800, 400), title="plot3d", keys="interactive") <NEW_LINE> program = gloo.Program(vert=vertex, frag=fragment) <NEW_LINE> view = np.eye(4, dtype=np.float32) <NEW_LINE> model = np.eye(4, dtype=np.float32) <NEW_LINE> projection = np.eye(4, dtype=np.float32) <NEW_LINE> program["u_model"] = model <NEW_LINE> program["u_view"] = view <NEW_LINE> program["u_projection"] = projection <NEW_LINE> program["a_position"] = data <NEW_LINE> self.program = program <NEW_LINE> self.theta = theta <NEW_LINE> self.phi = phi <NEW_LINE> self.z = z <NEW_LINE> gloo.set_viewport(0, 0, *self.physical_size) <NEW_LINE> gloo.set_clear_color("white") <NEW_LINE> gloo.set_state("translucent") <NEW_LINE> gloo.set_line_width(2.0) <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def on_resize(self, event): <NEW_LINE> <INDENT> gloo.set_viewport(0, 0, *event.physical_size) <NEW_LINE> ratio = event.physical_size[0] / float(event.physical_size[1]) <NEW_LINE> self.program["u_projection"] = perspective(45.0, ratio, 2.0, 10.0) <NEW_LINE> <DEDENT> def on_draw(self, event): <NEW_LINE> <INDENT> gloo.clear() <NEW_LINE> view = translate((0, 0, -self.z)) <NEW_LINE> model = np.dot(rotate(self.theta, (0, 1, 0)), rotate(self.phi, (0, 0, 1))) <NEW_LINE> self.program["u_model"] = model <NEW_LINE> self.program["u_view"] = view <NEW_LINE> self.program.draw("line_strip") | build canvas | 62599046c432627299fa42b2 |
class ChemActivityByFacilityInputSet(InputSet): <NEW_LINE> <INDENT> def set_FacilityID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'FacilityID', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_RowEnd(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'RowEnd', value) <NEW_LINE> <DEDENT> def set_RowStart(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'RowStart', value) | An InputSet with methods appropriate for specifying the inputs to the ChemActivityByFacility
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62599046e76e3b2f99fd9d6b |
class CoordSystState(soya.CoordSyst, tofu.State): <NEW_LINE> <INDENT> def __init__(self, mobile): <NEW_LINE> <INDENT> self.added_into(mobile.parent) <NEW_LINE> self.matrix = mobile.matrix | CoordSystState
A State that take care of CoordSyst position, rotation and scaling.
CoordSystState extend CoordSyst, and thus have similar method (e.g. set_xyz, rotate_*,
scale, ...) | 6259904694891a1f408ba0a5 |
class PluggableBackend(object): <NEW_LINE> <INDENT> def __init__(self, pivot, **backends): <NEW_LINE> <INDENT> self.__backends = backends <NEW_LINE> self.__pivot = pivot <NEW_LINE> self.__backend = None <NEW_LINE> <DEDENT> def __get_backend(self): <NEW_LINE> <INDENT> if not self.__backend: <NEW_LINE> <INDENT> backend_name = CONF[self.__pivot] <NEW_LINE> if backend_name not in self.__backends: <NEW_LINE> <INDENT> raise Exception('Invalid backend: %s' % backend_name) <NEW_LINE> <DEDENT> backend = self.__backends[backend_name] <NEW_LINE> if isinstance(backend, tuple): <NEW_LINE> <INDENT> name = backend[0] <NEW_LINE> fromlist = backend[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = backend <NEW_LINE> fromlist = backend <NEW_LINE> <DEDENT> self.__backend = __import__(name, None, None, fromlist) <NEW_LINE> LOG.debug('backend %s', self.__backend) <NEW_LINE> <DEDENT> return self.__backend <NEW_LINE> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> backend = self.__get_backend() <NEW_LINE> return getattr(backend, key) | A pluggable backend loaded lazily based on some value. | 6259904645492302aabfd830 |
class FamilyTypeSetIterator(APIObject,IDisposable,IEnumerator): <NEW_LINE> <INDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def MoveNext(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def next(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseManagedResources(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseUnmanagedResources(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Reset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Current=property(lambda self: object(),lambda self,v: None,lambda self: None) | An iterator to a FamilyType set.
FamilyTypeSetIterator() | 62599046711fe17d825e164d |
class ExternalContent(SpiderEventListener): <NEW_LINE> <INDENT> def __init__(self, driver, domain, path_depth=-1): <NEW_LINE> <INDENT> self.domain = urlparse(domain).netloc <NEW_LINE> self.external = [] <NEW_LINE> self.fingerprinted = [] <NEW_LINE> self.driver = driver <NEW_LINE> self.path_depth = path_depth <NEW_LINE> <DEDENT> def on_page_visited(self): <NEW_LINE> <INDENT> page = self.driver.current_url <NEW_LINE> audios = self.driver.find_elements_by_tag_name("audio") <NEW_LINE> self._extract_src(audios, "src") <NEW_LINE> imgs = self.driver.find_elements_by_tag_name("img") <NEW_LINE> self._extract_src(imgs, "src") <NEW_LINE> scripts = self.driver.find_elements_by_tag_name("script") <NEW_LINE> self._extract_src(scripts, "src") <NEW_LINE> links = self.driver.find_elements_by_tag_name("link") <NEW_LINE> self._extract_src(links, "href") <NEW_LINE> try: <NEW_LINE> <INDENT> embeds = self.driver.find_elements_by_tag_name("embed") <NEW_LINE> self._extract_src(embeds, "src") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> iframes = self.driver.find_elements_by_tag_name("iframe") <NEW_LINE> self._extract_src(iframes, "src") <NEW_LINE> objects = self.driver.find_elements_by_tag_name("objects") <NEW_LINE> self._extract_src(objects, "data") <NEW_LINE> sources = self.driver.find_elements_by_tag_name("source") <NEW_LINE> self._extract_src(sources, "src") <NEW_LINE> <DEDENT> def _get_short_path(self, path): <NEW_LINE> <INDENT> if self.path_depth < 0: <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> paths= path.split("/") <NEW_LINE> short_path = paths [:min(self.path_depth, len(paths))] <NEW_LINE> return "/".join(short_path) <NEW_LINE> <DEDENT> def _extract_src(self, els, attr): <NEW_LINE> <INDENT> page = self.driver.current_url <NEW_LINE> page_path = urlparse(page).path <NEW_LINE> for el in els: <NEW_LINE> <INDENT> src = el.get_attribute(attr) <NEW_LINE> if src: <NEW_LINE> <INDENT> parse = urlparse(src) <NEW_LINE> netloc = parse.netloc <NEW_LINE> scheme = parse.scheme <NEW_LINE> if not((scheme,netloc,el.tag_name) in self.external): <NEW_LINE> <INDENT> self.external.append((scheme, netloc,el.tag_name)) <NEW_LINE> logger.debug(str(time.time()) + "," + el.tag_name + "," + scheme + "," + netloc + "," + src + "," + page) | Look for external calls to other domains | 6259904696565a6dacd2d939 |
class BareTrace(object): <NEW_LINE> <INDENT> def __init__(self, name=""): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.normalized_time = False <NEW_LINE> self.class_definitions = {} <NEW_LINE> self.trace_classes = [] <NEW_LINE> self.basetime = 0 <NEW_LINE> <DEDENT> def get_duration(self): <NEW_LINE> <INDENT> durations = [] <NEW_LINE> for trace_class in self.trace_classes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> durations.append(trace_class.data_frame.index[-1]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if len(durations) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if self.normalized_time: <NEW_LINE> <INDENT> return max(durations) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return max(durations) - self.basetime <NEW_LINE> <DEDENT> <DEDENT> def get_filters(self, key=""): <NEW_LINE> <INDENT> filters = [] <NEW_LINE> for cls in self.class_definitions: <NEW_LINE> <INDENT> if re.search(key, cls): <NEW_LINE> <INDENT> filters.append(cls) <NEW_LINE> <DEDENT> <DEDENT> return filters <NEW_LINE> <DEDENT> def normalize_time(self, basetime=None): <NEW_LINE> <INDENT> if basetime is not None: <NEW_LINE> <INDENT> self.basetime = basetime <NEW_LINE> <DEDENT> for trace_class in self.trace_classes: <NEW_LINE> <INDENT> trace_class.normalize_time(self.basetime) <NEW_LINE> <DEDENT> self.normalized_time = True <NEW_LINE> <DEDENT> def add_parsed_event(self, name, dfr, pivot=None): <NEW_LINE> <INDENT> from trappy.base import Base <NEW_LINE> from trappy.dynamic import DynamicTypeFactory, default_init <NEW_LINE> if hasattr(self, name): <NEW_LINE> <INDENT> raise ValueError("event {} already present".format(name)) <NEW_LINE> <DEDENT> kwords = { "__init__": default_init, "unique_word": name + ":", "name": name, } <NEW_LINE> trace_class = DynamicTypeFactory(name, (Base,), kwords) <NEW_LINE> self.class_definitions[name] = trace_class <NEW_LINE> event = trace_class() <NEW_LINE> self.trace_classes.append(event) <NEW_LINE> event.data_frame = dfr <NEW_LINE> if pivot: <NEW_LINE> <INDENT> event.pivot = pivot <NEW_LINE> <DEDENT> setattr(self, name, event) <NEW_LINE> <DEDENT> def finalize_objects(self): <NEW_LINE> <INDENT> for trace_class in self.trace_classes: <NEW_LINE> <INDENT> trace_class.create_dataframe() <NEW_LINE> trace_class.finalize_object() | A wrapper class that holds dataframes for all the events in a trace.
BareTrace doesn't parse any file so it's a class that should
either be (a) subclassed to parse a particular trace (like FTrace)
or (b) be instantiated and the events added with add_parsed_event()
:param name: is a string describing the trace.
:type name: str | 625990466fece00bbacccd15 |
class TestLongestMountainInArray(unittest.TestCase): <NEW_LINE> <INDENT> def test_longest_mountain_in_array(self): <NEW_LINE> <INDENT> s = Solution() <NEW_LINE> self.assertEqual(5, s.longestMountain([2, 1, 4, 7, 3, 2, 5])) <NEW_LINE> self.assertEqual(0, s.longestMountain([2, 2, 2])) <NEW_LINE> self.assertEqual(0, s.longestMountain([])) <NEW_LINE> self.assertEqual(11, s.longestMountain([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0])) <NEW_LINE> self.assertEqual(3, s.longestMountain([0, 2, 1])) | Test q845_longest_mountain_in_array.py | 6259904682261d6c52730875 |
@method_decorator(login_required, name='dispatch') <NEW_LINE> class SongUpdateView(SuccessMessageMixin, UpdateView): <NEW_LINE> <INDENT> form_class = SongForm <NEW_LINE> model = Song <NEW_LINE> template_name = 'songs/add.html' <NEW_LINE> success_url = reverse_lazy("backend:index") <NEW_LINE> success_message = _("Song %(name)s was successfully updated") <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> if len(form.changed_data) > 0: <NEW_LINE> <INDENT> regenerate_pdf(self.object, True) <NEW_LINE> regenerate_prerender(self.object) <NEW_LINE> <DEDENT> return super().form_valid(form) | Updates existing song | 62599046d7e4931a7ef3d3d5 |
class CpuState(Base): <NEW_LINE> <INDENT> __tablename__ = 'cpuState' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> savename = Column(String) <NEW_LINE> gbregisters = Column(PickleType) <NEW_LINE> stack_ptr = Column(Integer) <NEW_LINE> program_ctr = Column(Integer) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<CPU_STATE(savename=%r>" % self.savename | SQLAlchemy base class to save cpustate.
...
Attributes
----------
id : int
primary key for database
savename : string
game save name
gbregisters : pickle
pickled list of the cpu registers A-F
stack_ptr : int
the stack pointer
program_ctr : int
the program counter | 6259904607f4c71912bb0792 |
class Yasb(): <NEW_LINE> <INDENT> def __init__(self, arg): <NEW_LINE> <INDENT> pass | docstring for Yasb | 62599046596a897236128f5f |
class TestActionInteger(JNTTFactory, JNTTFactoryCommon): <NEW_LINE> <INDENT> entry_name='action_integer' | Test the value factory
| 625990463c8af77a43b688ed |
class SurrogatePK(object): <NEW_LINE> <INDENT> __table_args__ = {"extend_existing": True} <NEW_LINE> id = db.Column(UUIDType(binary=False), primary_key=True) | A mixin that adds a surrogate UUID 'primary key' column named ``id`` to
any declarative-mapped class. | 62599046cad5886f8bdc5a2e |
class RetrieveReportInputSet(InputSet): <NEW_LINE> <INDENT> def set_AWSAccessKeyId(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('AWSAccessKeyId', value) <NEW_LINE> <DEDENT> def set_AWSMarketplaceId(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('AWSMarketplaceId', value) <NEW_LINE> <DEDENT> def set_AWSMerchantId(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('AWSMerchantId', value) <NEW_LINE> <DEDENT> def set_AWSSecretKeyId(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('AWSSecretKeyId', value) <NEW_LINE> <DEDENT> def set_EndDate(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('EndDate', value) <NEW_LINE> <DEDENT> def set_Endpoint(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('Endpoint', value) <NEW_LINE> <DEDENT> def set_MWSAuthToken(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('MWSAuthToken', value) <NEW_LINE> <DEDENT> def set_ReportType(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('ReportType', value) <NEW_LINE> <DEDENT> def set_StartDate(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('StartDate', value) <NEW_LINE> <DEDENT> def set_TimeToWait(self, value): <NEW_LINE> <INDENT> super(RetrieveReportInputSet, self)._set_input('TimeToWait', value) | An InputSet with methods appropriate for specifying the inputs to the RetrieveReport
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 6259904621a7993f00c672c9 |
class ReceiveVerb(VerbExtension): <NEW_LINE> <INDENT> def main(self, *, args): <NEW_LINE> <INDENT> print('Waiting for UDP multicast datagram...') <NEW_LINE> try: <NEW_LINE> <INDENT> data, (host, port) = receive() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = data.decode('utf-8') <NEW_LINE> print(f"Received from {host}:{port}: '{data}'") | Receive a single UDP multicast packet. | 62599046287bf620b6272f49 |
class ZWaveNumericSensor(ZwaveSensorBase): <NEW_LINE> <INDENT> @property <NEW_LINE> def native_value(self): <NEW_LINE> <INDENT> return round(self.values.primary.value, 2) <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_unit_of_measurement(self): <NEW_LINE> <INDENT> if self.values.primary.units == "C": <NEW_LINE> <INDENT> return TEMP_CELSIUS <NEW_LINE> <DEDENT> if self.values.primary.units == "F": <NEW_LINE> <INDENT> return TEMP_FAHRENHEIT <NEW_LINE> <DEDENT> return self.values.primary.units | Representation of a Z-Wave sensor. | 6259904623849d37ff85241c |
class Fragment(pygame.sprite.Sprite): <NEW_LINE> <INDENT> number = 0 <NEW_LINE> def __init__(self, pos, layer = 9): <NEW_LINE> <INDENT> self._layer = layer <NEW_LINE> pygame.sprite.Sprite.__init__(self, self.groups) <NEW_LINE> self.pos = [0.0,0.0] <NEW_LINE> self.fragmentmaxspeed = 200 <NEW_LINE> self.number = Fragment.number <NEW_LINE> Fragment.number += 1 <NEW_LINE> <DEDENT> def init2(self): <NEW_LINE> <INDENT> self.image = pygame.Surface((10,10)) <NEW_LINE> self.image.set_colorkey((0,0,0)) <NEW_LINE> self.fragmentradius = random.randint(2,5) <NEW_LINE> pygame.draw.circle(self.image, self.color, (5,5), self.fragmentradius) <NEW_LINE> self.image = self.image.convert_alpha() <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.center = self.pos <NEW_LINE> self.time = 0.0 <NEW_LINE> <DEDENT> def update(self, seconds): <NEW_LINE> <INDENT> self.time += seconds <NEW_LINE> if self.time > self.lifetime: <NEW_LINE> <INDENT> self.kill() <NEW_LINE> <DEDENT> self.pos[0] += self.dx * seconds <NEW_LINE> self.pos[1] += self.dy * seconds <NEW_LINE> self.rect.centerx = round(self.pos[0],0) <NEW_LINE> self.rect.centery = round(self.pos[1],0) | generic Fragment class. | 6259904691af0d3eaad3b185 |
class TestCompareXLSXFiles(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.maxDiff = None <NEW_LINE> filename = 'fit_to_pages03.xlsx' <NEW_LINE> test_dir = 'xlsxwriter/test/comparison/' <NEW_LINE> self.got_filename = test_dir + '_test_' + filename <NEW_LINE> self.exp_filename = test_dir + 'xlsx_files/' + filename <NEW_LINE> self.ignore_files = ['xl/printerSettings/printerSettings1.bin', 'xl/worksheets/_rels/sheet1.xml.rels'] <NEW_LINE> self.ignore_elements = {'[Content_Types].xml': ['<Default Extension="bin"'], 'xl/worksheets/sheet1.xml': ['<pageMargins', '<pageSetup']} <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> filename = self.got_filename <NEW_LINE> workbook = Workbook(filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.fit_to_pages(1, 2) <NEW_LINE> worksheet.set_paper(9) <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> workbook.close() <NEW_LINE> got, exp = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) <NEW_LINE> self.assertEqual(got, exp) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists(self.got_filename): <NEW_LINE> <INDENT> os.remove(self.got_filename) | Test file created by XlsxWriter against a file created by Excel. | 62599046e76e3b2f99fd9d6d |
class jboolean_t(java_fundamental_t): <NEW_LINE> <INDENT> JNAME = 'jboolean' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> java_fundamental_t.__init__(self, jboolean_t.JNAME) | represents jboolean type | 62599046711fe17d825e164e |
class IProjectContainer(Interface): <NEW_LINE> <INDENT> pass | This is really just a marker interface.
mark the folder as project container. | 62599046d6c5a102081e347d |
class Test__Astropy_Table__(): <NEW_LINE> <INDENT> class SimpleTable: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.columns = [[1, 2, 3], [4, 5, 6], [7, 8, 9] * u.m] <NEW_LINE> self.names = ['a', 'b', 'c'] <NEW_LINE> self.meta = OrderedDict([('a', 1), ('b', 2)]) <NEW_LINE> <DEDENT> def __astropy_table__(self, cls, copy, **kwargs): <NEW_LINE> <INDENT> a, b, c = self.columns <NEW_LINE> c.info.name = 'c' <NEW_LINE> cols = [table.Column(a, name='a'), table.MaskedColumn(b, name='b'), c] <NEW_LINE> names = [col.info.name for col in cols] <NEW_LINE> return cls(cols, names=names, copy=copy, meta=kwargs or self.meta) <NEW_LINE> <DEDENT> <DEDENT> def test_simple_1(self): <NEW_LINE> <INDENT> for table_cls in (table.Table, table.QTable): <NEW_LINE> <INDENT> col_c_class = u.Quantity if table_cls is table.QTable else table.MaskedColumn <NEW_LINE> for cpy in (False, True): <NEW_LINE> <INDENT> st = self.SimpleTable() <NEW_LINE> t = table_cls(st, copy=cpy, extra_meta='extra!') <NEW_LINE> assert t.colnames == ['a', 'b', 'c'] <NEW_LINE> assert t.meta == {'extra_meta': 'extra!'} <NEW_LINE> assert np.all(t['a'] == st.columns[0]) <NEW_LINE> assert np.all(t['b'] == st.columns[1]) <NEW_LINE> vals = t['c'].value if table_cls is table.QTable else t['c'] <NEW_LINE> assert np.all(st.columns[2].value == vals) <NEW_LINE> assert isinstance(t['a'], table.MaskedColumn) <NEW_LINE> assert isinstance(t['b'], table.MaskedColumn) <NEW_LINE> assert isinstance(t['c'], col_c_class) <NEW_LINE> assert t['c'].unit is u.m <NEW_LINE> assert type(t) is table_cls <NEW_LINE> t['a'][0] = 10 <NEW_LINE> assert st.columns[0][0] == 1 if cpy else 10 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_simple_2(self): <NEW_LINE> <INDENT> st = self.SimpleTable() <NEW_LINE> dtypes = [np.int32, np.float32, np.float16] <NEW_LINE> names = ['a', 'b', 'c'] <NEW_LINE> t = table.Table(st, dtype=dtypes, names=names, meta=OrderedDict([('c', 3)])) <NEW_LINE> assert t.colnames == names <NEW_LINE> assert all(col.dtype.type is dtype for col, dtype in zip(t.columns.values(), dtypes)) <NEW_LINE> assert t.meta == st.meta <NEW_LINE> <DEDENT> def test_kwargs_exception(self): <NEW_LINE> <INDENT> with pytest.raises(TypeError) as err: <NEW_LINE> <INDENT> table.Table([[1]], extra_meta='extra!') <NEW_LINE> <DEDENT> assert '__init__() got unexpected keyword argument' in str(err) | Test initializing a Table subclass from a table-like object that
implements the __astropy_table__ interface method. | 62599046b830903b9686ee2b |
class Node: <NEW_LINE> <INDENT> def __init__(self, value, coord, H): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.coord = coord <NEW_LINE> self.parent = None <NEW_LINE> self.H = H <NEW_LINE> self.G = float('inf') | To create nodes of a graph
Attributes:
coord (tuple): The (row, col) coordinate
G (int): The cost to reach this node
H (int): The cost to goal node
parent (Node): The parent of this node
value (int): The value at this location in exploration map | 625990460a366e3fb87ddd47 |
class StartConds: <NEW_LINE> <INDENT> def __init__(self, time: float, coords: Coordinates, velo: float, mu: float, theta: float): <NEW_LINE> <INDENT> self.t = time <NEW_LINE> self.coords = copy(coords) <NEW_LINE> self.V = velo <NEW_LINE> self.mu = mu <NEW_LINE> self.Theta = theta <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return StartConds(self.t, self.coords, self.V, self.mu, self.Theta) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"\t Starting conditions:" f"\n\t - starting time, s: {self.t}" f"\n\t - {self.coords}" f"\n\t - velocity, m/s: {self.V}" f"\n\t - relative propellant mass: {self.mu}" f"\n\t - angle of inclination to the horizon, deg: {np.rad2deg(self.Theta)}" | Starting conditions of the rocket's ballistics task. | 62599046dc8b845886d5491c |
class MockJob(progress.Progress): <NEW_LINE> <INDENT> def __init__(self, *args, sleep_time: float = 0.1, **kwargs): <NEW_LINE> <INDENT> self._sleep_time = sleep_time <NEW_LINE> super(MockJob, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def Run(self): <NEW_LINE> <INDENT> n = self.ctx.n or 0 <NEW_LINE> for self.ctx.i in range(self.ctx.i, n + 1): <NEW_LINE> <INDENT> self.ctx.Log(1, "I did a thing") <NEW_LINE> time.sleep(self._sleep_time) | A mock job. | 6259904650485f2cf55dc2e9 |
class BalancingModeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> RATE = 0 <NEW_LINE> UTILIZATION = 1 | Specifies the balancing mode for this backend. For global HTTP(S) load
balancing, the default is UTILIZATION. Valid values are UTILIZATION and
RATE.
Values:
RATE: <no description>
UTILIZATION: <no description> | 625990461f5feb6acb163f57 |
class Player: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.uid = getUid(name) <NEW_LINE> self.last_online = time.mktime(time.gmtime()) <NEW_LINE> self.game_id = None | Player class | 62599046d53ae8145f9197c1 |
class DBManger: <NEW_LINE> <INDENT> host = None <NEW_LINE> port = None <NEW_LINE> client = None <NEW_LINE> db = None <NEW_LINE> def __init__(self, host: str, port: int, db: str): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.client = MongoClient(host=host, port=port) <NEW_LINE> self.db = self.client[db] <NEW_LINE> <DEDENT> def insert(self, col_name: str, doc, check_keys=True): <NEW_LINE> <INDENT> return self.db[col_name].insert(doc, check_keys=check_keys) <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def find_all(self, col_name: str): <NEW_LINE> <INDENT> return self.db[col_name].find() <NEW_LINE> <DEDENT> def find_by_condition(self, col_name: str, condition): <NEW_LINE> <INDENT> return self.db[col_name].find(condition) <NEW_LINE> <DEDENT> def update(self, col_name, query, update, upsert=False, multi=False): <NEW_LINE> <INDENT> self.db[col_name].update(query, update, upsert, multi) | manager the mongodb | 6259904671ff763f4b5e8b05 |
class AccountIdentityInfo(models.Model): <NEW_LINE> <INDENT> account = models.OneToOneField(Client, verbose_name=_('Account'), primary_key=True) <NEW_LINE> passport = models.ForeignKey(Passport, verbose_name=_('Passport')) <NEW_LINE> national_id_card = models.ForeignKey(NationalIDCard, verbose_name=_('National ID Card')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Identity information') <NEW_LINE> verbose_name_plural = _('Identities information') | Identification info of account | 6259904673bcbd0ca4bcb5ee |
class dependency_node: <NEW_LINE> <INDENT> def depends_on(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_fulfilled(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class _AbortApply(Exception): <NEW_LINE> <INDENT> def __init__(self,value): <NEW_LINE> <INDENT> super(dependency_node._AbortApply, self).__init__("apply call has been aborted.") <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> <DEDENT> def apply_dependencies(self,f,*args,op=(lambda x,y: None), init=None): <NEW_LINE> <INDENT> return self._apply_all_inner(self,f,*args,op=op, is_root_node=True,init=init) <NEW_LINE> <DEDENT> def _apply_all_inner(self,root,f,*args, op=(lambda x,y: None), init=None, is_root_node=False): <NEW_LINE> <INDENT> val = init <NEW_LINE> if (not is_root_node and self == root): <NEW_LINE> <INDENT> raise CyclicGraphException("Circular dependencies detected.") <NEW_LINE> <DEDENT> for dep in self.depends_on(): <NEW_LINE> <INDENT> val = dep._apply_all_inner(root,f,*args, op=op, init=val) <NEW_LINE> <DEDENT> if is_root_node: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return op(val, f(self,*args) ) <NEW_LINE> <DEDENT> <DEDENT> def has_dependencies(self): <NEW_LINE> <INDENT> if self.depends_on() is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif len(self.depends_on()) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def dependencies_fulfilled(self): <NEW_LINE> <INDENT> check = lambda c: c.is_fulfilled() <NEW_LINE> def acc_op(x,y): <NEW_LINE> <INDENT> if x and y: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise dependency_node._AbortApply(False) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return self.apply_dependencies(check,op=acc_op, init=True) <NEW_LINE> <DEDENT> except dependency_node._AbortApply as a: <NEW_LINE> <INDENT> return a.value <NEW_LINE> <DEDENT> <DEDENT> def depends_on_recursive(self): <NEW_LINE> <INDENT> depends = lambda s: s.depends_on() <NEW_LINE> union = lambda s,t : s.union(t) <NEW_LINE> return self.apply_dependencies(depends,op=union,init=self.depends_on()) <NEW_LINE> <DEDENT> def build_batches(self): <NEW_LINE> <INDENT> return build_batches(self.depends_on_recursive().union({self})) | A node of an dependency graph that only supports downward traversal
i.e. traversal towards the nodes it depends upon. | 6259904626238365f5fadebe |
class HelpAction(argparse.Action): <NEW_LINE> <INDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> log = logging.getLogger(__name__) <NEW_LINE> app = self.default <NEW_LINE> parser.print_help(app.stdout) <NEW_LINE> app.stdout.write('\nCommands:\n') <NEW_LINE> command_manager = app.command_manager <NEW_LINE> for name, ep in sorted(command_manager): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> factory = ep.load() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> app.stdout.write('Could not load %r\n' % ep) <NEW_LINE> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> cmd = factory(self, None) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> app.stdout.write('Could not instantiate %r: %s\n' % (ep, err)) <NEW_LINE> continue <NEW_LINE> <DEDENT> one_liner = cmd.get_description().split('\n')[0] <NEW_LINE> app.stdout.write(' %-13s %s\n' % (name, one_liner)) <NEW_LINE> <DEDENT> sys.exit(0) | Provide a custom action so the -h and --help options
to the main app will print a list of the commands.
The commands are determined by checking the CommandManager
instance, passed in as the "default" value for the action. | 62599046d4950a0f3b1117f3 |
class Dict(ModelType): <NEW_LINE> <INDENT> @property <NEW_LINE> def default(self): <NEW_LINE> <INDENT> if self._default is None: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._default <NEW_LINE> <DEDENT> <DEDENT> def from_json(self, value): <NEW_LINE> <INDENT> if value is None or isinstance(value, dict): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Value stored in a Dict must be None or a dict.') | A field class for representing a Python dict.
The stored value must be either be None or a dict. | 6259904645492302aabfd834 |
class AlphaBetaAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> Depth = self.depth <NEW_LINE> Alpha = -99999 <NEW_LINE> Beta = 99999 <NEW_LINE> return self.AlphaBetaSearch(Depth, gameState, 0, Alpha, Beta) <NEW_LINE> <DEDENT> def AlphaBetaSearch(self, currentdepth, state, agent, alpha, beta): <NEW_LINE> <INDENT> NumberOfAgents = state.getNumAgents() <NEW_LINE> currentstate = state <NEW_LINE> PacmanAction = None <NEW_LINE> if currentdepth == 0 or currentstate.isWin() or currentstate.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(currentstate) <NEW_LINE> <DEDENT> newdepth = currentdepth <NEW_LINE> NextAgent = agent + 1 <NEW_LINE> if NextAgent >= NumberOfAgents: <NEW_LINE> <INDENT> NextAgent = 0 <NEW_LINE> newdepth = currentdepth - 1 <NEW_LINE> <DEDENT> Actions = currentstate.getLegalActions(agent) <NEW_LINE> if agent == 0 and currentdepth == self.depth: <NEW_LINE> <INDENT> value = -99999 <NEW_LINE> for action in Actions: <NEW_LINE> <INDENT> FutureScore = self.AlphaBetaSearch( newdepth, currentstate.generateSuccessor(agent, action), NextAgent, alpha, beta) <NEW_LINE> if FutureScore > value: <NEW_LINE> <INDENT> value = FutureScore <NEW_LINE> PacmanAction = action <NEW_LINE> <DEDENT> if value > beta: <NEW_LINE> <INDENT> return PacmanAction <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alpha = max(alpha, value) <NEW_LINE> <DEDENT> <DEDENT> return PacmanAction <NEW_LINE> <DEDENT> elif agent == 0: <NEW_LINE> <INDENT> value = -99999 <NEW_LINE> for action in Actions: <NEW_LINE> <INDENT> FutureScore = self.AlphaBetaSearch( newdepth, currentstate.generateSuccessor(agent, action), NextAgent, alpha, beta) <NEW_LINE> if FutureScore > value: <NEW_LINE> <INDENT> value = FutureScore <NEW_LINE> <DEDENT> if value > beta: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> alpha = max(alpha, value) <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = 99999 <NEW_LINE> for action in Actions: <NEW_LINE> <INDENT> FutureScore = self.AlphaBetaSearch( newdepth, currentstate.generateSuccessor(agent, action), NextAgent, alpha, beta) <NEW_LINE> if FutureScore < value: <NEW_LINE> <INDENT> value = FutureScore <NEW_LINE> <DEDENT> if value < alpha: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> beta = min(beta, value) <NEW_LINE> <DEDENT> <DEDENT> return value | Your minimax agent with alpha-beta pruning (question 3) | 62599046711fe17d825e164f |
class arch_mips4(generic_mips): <NEW_LINE> <INDENT> def __init__(self, myspec): <NEW_LINE> <INDENT> generic_mips.__init__(self, myspec) <NEW_LINE> self.settings["CFLAGS"] = "-O2 -march = mips4 -mabi = 32 -mplt -pipe" | Builder class for MIPS IV [Big-endian] | 625990464e696a045264e7d2 |
class Label(Tkinter.Label, CtxMenu.CtxMenuMixin, IsCurrentMixin, SeverityMixin): <NEW_LINE> <INDENT> def __init__ (self, master, formatStr = None, formatFunc = unicode, helpText = None, helpURL = None, isCurrent = True, severity = RO.Constants.sevNormal, **kargs): <NEW_LINE> <INDENT> kargs.setdefault("anchor", "e") <NEW_LINE> kargs.setdefault("justify", "right") <NEW_LINE> Tkinter.Label.__init__(self, master, **kargs) <NEW_LINE> CtxMenu.CtxMenuMixin.__init__(self, helpURL=helpURL) <NEW_LINE> IsCurrentMixin.__init__(self, isCurrent) <NEW_LINE> SeverityMixin.__init__(self, severity) <NEW_LINE> self._formatStr = formatStr <NEW_LINE> if formatStr is not None: <NEW_LINE> <INDENT> formatFunc = self._formatFromStr <NEW_LINE> <DEDENT> self._formatFunc = formatFunc <NEW_LINE> self.helpText = helpText <NEW_LINE> self._value = None <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return (self._value, self._isCurrent) <NEW_LINE> <DEDENT> def getFormatted(self): <NEW_LINE> <INDENT> if self._value is None: <NEW_LINE> <INDENT> return (None, self._isCurrent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self["text"], self._isCurrent) <NEW_LINE> <DEDENT> <DEDENT> def clear(self, isCurrent=1): <NEW_LINE> <INDENT> self.set(value="", isCurrent=isCurrent) <NEW_LINE> <DEDENT> def set(self, value, isCurrent = True, severity = None, **kargs): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> self.setIsCurrent(isCurrent) <NEW_LINE> if severity is not None: <NEW_LINE> <INDENT> self.setSeverity(severity) <NEW_LINE> <DEDENT> self._updateText() <NEW_LINE> <DEDENT> def setNotCurrent(self): <NEW_LINE> <INDENT> self.setIsCurrent(False) <NEW_LINE> <DEDENT> def _formatFromStr(self, value): <NEW_LINE> <INDENT> return self._formatStr % value <NEW_LINE> <DEDENT> def _updateText(self): <NEW_LINE> <INDENT> if self._value is None: <NEW_LINE> <INDENT> self["text"] = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self["text"] = self._formatFunc(self._value) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> sys.stderr.write("format of value %r failed with error: %s\n" % (self._value, e)) <NEW_LINE> self["text"] = "?%r?" % (self._value,) | Base class for labels (display ROWdgs); do not use directly.
Inputs:
- formatStr: formatting string; if omitted, formatFunc is used.
Displayed value is formatStr % value.
- formatFunc: formatting function; ignored if formatStr specified.
Displayed value is formatFunc(value).
- helpText short text for hot help
- helpURL URL for on-line help
- isCurrent is value current?
- severity one of RO.Constants.sevNormal, sevWarning or sevError
- **kargs: all other keyword arguments go to Tkinter.Label;
the defaults are anchor="e", justify="right"
Inherited methods include:
getIsCurrent, setIsCurrent
getSeverity, setSeverity
Note: if display formatting fails (raises an exception)
then "?%r?" % value is displayed. | 62599046b830903b9686ee2c |
class CircleConstraint(Constraint2D): <NEW_LINE> <INDENT> def __init__(self, radius, edges=16): <NEW_LINE> <INDENT> self._radius = radius <NEW_LINE> self._edges = edges <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def _boundary_points(self): <NEW_LINE> <INDENT> n = self._edges <NEW_LINE> radius = self._radius <NEW_LINE> step_angle = 2 * np.pi / n <NEW_LINE> points = [] <NEW_LINE> for i in range(0, n): <NEW_LINE> <INDENT> points.append(_point_on_circle(i * step_angle, radius)) <NEW_LINE> <DEDENT> return points | Constraint describing a circle | 6259904629b78933be26aa74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.