code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class PetShop: <NEW_LINE> <INDENT> def __init__(self, animal_factory=None): <NEW_LINE> <INDENT> self.pet_factory = animal_factory <NEW_LINE> <DEDENT> def show_pet(self): <NEW_LINE> <INDENT> pet = self.pet_factory.get_pet() <NEW_LINE> print("This is a lovely", pet) <NEW_LINE> print("It says", pet.speak()) <NEW_LINE> print("It eats", self.pet_factory.get_food())
A pet shop
6259904776d4e153a661dc2f
class TFramedTransport: <NEW_LINE> <INDENT> def __init__(self, base): <NEW_LINE> <INDENT> self.__base = base <NEW_LINE> self.__read_buffer = BytesIO() <NEW_LINE> self.__write_buffer = BytesIO() <NEW_LINE> <DEDENT> def read(self, n=-1): <NEW_LINE> <INDENT> if len(self.__read_buffer.getvalue()) == 0: <NEW_LINE> <INDENT> self.read_frame() <NEW_LINE> <DEDENT> return self.__read_buffer.read(n) <NEW_LINE> <DEDENT> async def read_frame(self): <NEW_LINE> <INDENT> buff = await self.__base.readexactly(4) <NEW_LINE> sz, = unpack('!i', buff) <NEW_LINE> self.__read_buffer = BytesIO(await self.__base.readexactly(sz)) <NEW_LINE> <DEDENT> async def readexactly(self, n): <NEW_LINE> <INDENT> now, end = self.__read_buffer.tell(), self.__read_buffer.seek(0, 2) <NEW_LINE> remaining = end - now <NEW_LINE> self.__read_buffer.seek(now) <NEW_LINE> if 0 < remaining < n: <NEW_LINE> <INDENT> raise IOError("Tried to read invalid amount from framed transport") <NEW_LINE> <DEDENT> elif remaining == 0: <NEW_LINE> <INDENT> await self.read_frame() <NEW_LINE> <DEDENT> return self.__read_buffer.read(n) <NEW_LINE> <DEDENT> def write(self, val): <NEW_LINE> <INDENT> self.__write_buffer.write(val) <NEW_LINE> <DEDENT> async def drain(self): <NEW_LINE> <INDENT> wout = self.__write_buffer.getvalue() <NEW_LINE> wsz = len(wout) <NEW_LINE> self.__write_buffer = BytesIO() <NEW_LINE> buf = pack("!i", wsz) + wout <NEW_LINE> self.__base.write(buf) <NEW_LINE> await self.__base.drain() <NEW_LINE> <DEDENT> def at_eof(self): <NEW_LINE> <INDENT> return self.__base.at_eof() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return self.__base.close()
Implement the Twisted framed transport protocol. Since most async servers use this including the python2 twisted bindings, this is likely of interest.
62599047b57a9660fecd2def
class PrimitiveProcedure(Procedure): <NEW_LINE> <INDENT> def __init__(self, fn, use_env=False, name='primitive'): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fn = fn <NEW_LINE> self.use_env = use_env <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '#[{0}]'.format(self.name) <NEW_LINE> <DEDENT> def apply(self, args, env): <NEW_LINE> <INDENT> if not scheme_listp(args): <NEW_LINE> <INDENT> raise SchemeError('arguments are not in a list: {0}'.format(args)) <NEW_LINE> <DEDENT> python_args = [] <NEW_LINE> while args is not nil: <NEW_LINE> <INDENT> python_args.append(args.first) <NEW_LINE> args = args.second <NEW_LINE> <DEDENT> if self.use_env: <NEW_LINE> <INDENT> python_args.append(env) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.fn(*python_args) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise SchemeError("invalid arguments")
A Scheme procedure defined as a Python function.
6259904729b78933be26aa7c
class TestStackList(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.A = Node(1) <NEW_LINE> self.B = Node(2) <NEW_LINE> self.C = Node(3) <NEW_LINE> self._stack = StackList() <NEW_LINE> <DEDENT> def test1(self): <NEW_LINE> <INDENT> self.assertEqual(self._stack.count(), 0) <NEW_LINE> self._stack.push(self.A) <NEW_LINE> self._stack.push(self.B) <NEW_LINE> self._stack.push(self.C) <NEW_LINE> for idx, node in enumerate(self._stack.enumerateStack()): <NEW_LINE> <INDENT> if idx == 0: <NEW_LINE> <INDENT> self.assertEqual(node.value, 3) <NEW_LINE> <DEDENT> elif idx == 1: <NEW_LINE> <INDENT> self.assertEqual(node.value, 2) <NEW_LINE> <DEDENT> elif idx == 2: <NEW_LINE> <INDENT> self.assertEqual(node.value, 1) <NEW_LINE> <DEDENT> <DEDENT> self.assertEqual(self._stack.count(), 3) <NEW_LINE> self.assertEqual(self._stack.peek(), 3) <NEW_LINE> self.assertEqual(self._stack.count(), 3) <NEW_LINE> self.assertEqual(self._stack.pop(), 3) <NEW_LINE> self.assertEqual(self._stack.count(), 2) <NEW_LINE> self.assertEqual(self._stack.pop(), 2) <NEW_LINE> self.assertEqual(self._stack.count(), 1) <NEW_LINE> self.assertEqual(self._stack.pop(), 1) <NEW_LINE> self.assertEqual(self._stack.count(), 0) <NEW_LINE> self.assertRaises(InvalidOperationException, self._stack.pop) <NEW_LINE> <DEDENT> def testClear(self): <NEW_LINE> <INDENT> self._stack.push(self.A) <NEW_LINE> self._stack.push(self.B) <NEW_LINE> self._stack.push(self.C) <NEW_LINE> self._stack.clear() <NEW_LINE> self.assertEqual(self._stack.count(), 0) <NEW_LINE> self.assertRaises(InvalidOperationException, self._stack.pop)
Test the StackList class
62599047dc8b845886d5492e
class Error(Exception): <NEW_LINE> <INDENT> pass
Base class for all redpipe errors
62599047097d151d1a2c23df
class LoaderError(Exception): <NEW_LINE> <INDENT> pass
Loader base error.
62599047462c4b4f79dbcd72
class ExperimentSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Experiment <NEW_LINE> fields = '__all__'
JSON serialized representation of the Experiment Model
6259904771ff763f4b5e8b17
class TestingConfig(Config): <NEW_LINE> <INDENT> TESTING = True <NEW_LINE> SQLALCHEMY_DATABASE_URI = os.getenv('TEST_DATABASE_URI') <NEW_LINE> PRESERVE_CONTEXT_ON_EXCEPTION = False
Testing configurations
6259904773bcbd0ca4bcb600
class Map(object): <NEW_LINE> <INDENT> TILE_SIZE = 256 <NEW_LINE> LEVEL_NUMBER = 20 <NEW_LINE> ZOOM_FACTOR = 2 <NEW_LINE> srs = '+init=epsg:4326' <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> for elem, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, elem, value)
used for carry Map Element attributes
625990478a43f66fc4bf3508
class TestEstoriaApp(TestCase): <NEW_LINE> <INDENT> def test_apps(self): <NEW_LINE> <INDENT> self.assertEqual(EstoriaAppConfig.name, 'estoria_app') <NEW_LINE> self.assertEqual(apps.get_app_config('estoria_app').name, 'estoria_app')
Test apps.py
6259904730dc7b76659a0ba6
class BasicCancel(AMQPMethodPayload): <NEW_LINE> <INDENT> __slots__ = ( u'consumer_tag', u'no_wait', ) <NEW_LINE> NAME = u'basic.cancel' <NEW_LINE> INDEX = (60, 30) <NEW_LINE> BINARY_HEADER = b'\x00\x3C\x00\x1E' <NEW_LINE> SENT_BY_CLIENT, SENT_BY_SERVER = True, True <NEW_LINE> IS_SIZE_STATIC = False <NEW_LINE> IS_CONTENT_STATIC = False <NEW_LINE> FIELDS = [ Field(u'consumer-tag', u'consumer-tag', u'shortstr', reserved=False), Field(u'no-wait', u'no-wait', u'bit', reserved=False), ] <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return 'BasicCancel(%s)' % (', '.join( map(to_repr, [self.consumer_tag, self.no_wait]))) <NEW_LINE> <DEDENT> def __init__(self, consumer_tag, no_wait): <NEW_LINE> <INDENT> self.consumer_tag = consumer_tag <NEW_LINE> self.no_wait = no_wait <NEW_LINE> <DEDENT> def write_arguments(self, buf): <NEW_LINE> <INDENT> buf.write(STRUCT_B.pack(len(self.consumer_tag))) <NEW_LINE> buf.write(self.consumer_tag) <NEW_LINE> buf.write(STRUCT_B.pack((self.no_wait << 0))) <NEW_LINE> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> return 2 + len(self.consumer_tag) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_buffer(cls, buf, start_offset): <NEW_LINE> <INDENT> offset = start_offset <NEW_LINE> s_len, = STRUCT_B.unpack_from(buf, offset) <NEW_LINE> offset += 1 <NEW_LINE> consumer_tag = buf[offset:offset + s_len] <NEW_LINE> offset += s_len <NEW_LINE> _bit, = STRUCT_B.unpack_from(buf, offset) <NEW_LINE> offset += 0 <NEW_LINE> no_wait = bool(_bit >> 0) <NEW_LINE> offset += 1 <NEW_LINE> return cls(consumer_tag, no_wait)
End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. It may also be sent from the server to the client in the event of the consumer being unexpectedly cancelled (i.e. cancelled for any reason other than the server receiving the corresponding basic.cancel from the client). This allows clients to be notified of the loss of consumers due to events such as queue deletion. Note that as it is not a MUST for clients to accept this method from the server, it is advisable for the broker to be able to identify those clients that are capable of accepting the method, through some means of capability negotiation. :type consumer_tag: binary type (max length 255) (consumer-tag in AMQP) :type no_wait: bool (no-wait in AMQP)
625990470fa83653e46f6250
class FionaReader(object): <NEW_LINE> <INDENT> def __init__(self, filename, bbox=None): <NEW_LINE> <INDENT> self._data = [] <NEW_LINE> with fiona.open(filename) as f: <NEW_LINE> <INDENT> if bbox is not None: <NEW_LINE> <INDENT> assert len(bbox) == 4 <NEW_LINE> features = f.filter(bbox=bbox) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> features = f <NEW_LINE> <DEDENT> if hasattr(features, "__geo_interface__"): <NEW_LINE> <INDENT> fs = features.__geo_interface__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fs = features <NEW_LINE> <DEDENT> if isinstance(fs, dict) and fs.get('type') == 'FeatureCollection': <NEW_LINE> <INDENT> features_lst = fs['features'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> features_lst = features <NEW_LINE> <DEDENT> for feature in features_lst: <NEW_LINE> <INDENT> if hasattr(f, "__geo_interface__"): <NEW_LINE> <INDENT> feature = feature.__geo_interface__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> feature = feature <NEW_LINE> <DEDENT> d = {'geometry': sgeom.shape(feature['geometry']) if feature['geometry'] else None} <NEW_LINE> d.update(feature['properties']) <NEW_LINE> self._data.append(d) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._data) <NEW_LINE> <DEDENT> def geometries(self): <NEW_LINE> <INDENT> for item in self._data: <NEW_LINE> <INDENT> yield item['geometry'] <NEW_LINE> <DEDENT> <DEDENT> def records(self): <NEW_LINE> <INDENT> for item in self._data: <NEW_LINE> <INDENT> yield FionaRecord(item['geometry'], {key: value for key, value in item.items() if key != 'geometry'})
Provides an interface for accessing the contents of a shapefile with the fiona library, which has a much faster reader than pyshp. The primary methods used on a Reader instance are :meth:`~Reader.records` and :meth:`~Reader.geometries`.
6259904710dbd63aa1c71f4e
class CopyProcess(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__process = client.CopyProcess() <NEW_LINE> <DEDENT> def add_job(self, source, target, sourcelimit = 1, force = False, posc = False, coerce = False, mkdir = False, thirdparty = 'none', checksummode = 'none', checksumtype = '', checksumpreset = '', dynamicsource = False, chunksize = 4194304, parallelchunks = 8, inittimeout = 600, tpctimeout = 1800): <NEW_LINE> <INDENT> self.__process.add_job(source, target, sourcelimit, force, posc, coerce, mkdir, thirdparty, checksummode, checksumtype, checksumpreset, dynamicsource, chunksize, parallelchunks, inittimeout, tpctimeout) <NEW_LINE> <DEDENT> def prepare(self): <NEW_LINE> <INDENT> status = self.__process.prepare() <NEW_LINE> return XRootDStatus(status) <NEW_LINE> <DEDENT> def run(self, handler=None): <NEW_LINE> <INDENT> status, results = self.__process.run(ProgressHandlerWrapper(handler)) <NEW_LINE> for x in results: <NEW_LINE> <INDENT> if x.has_key('status'): <NEW_LINE> <INDENT> x['status'] = XRootDStatus(x['status']) <NEW_LINE> <DEDENT> <DEDENT> return XRootDStatus(status), results
Add multiple individually-configurable copy jobs to a "copy process" and run them in parallel (yes, in parallel, because ``xrootd`` isn't limited by the `GIL`.
625990473617ad0b5ee074b0
class Form(Base): <NEW_LINE> <INDENT> __tablename__ = 'forms' <NEW_LINE> __mapper_args__ = {'polymorphic_on': 'type'} <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> type = Column(String(16), nullable=False) <NEW_LINE> project_id = Column(Integer, ForeignKey('projects.id')) <NEW_LINE> def __init__(self, project): <NEW_LINE> <INDENT> self.project = project <NEW_LINE> <DEDENT> def has_widgets(self): <NEW_LINE> <INDENT> return len(self.widgets)
A collection of widgets
6259904707d97122c4218016
class FieldGetDbPrepValueMixin(object): <NEW_LINE> <INDENT> get_db_prep_lookup_value_is_iterable = False <NEW_LINE> @classmethod <NEW_LINE> def get_prep_lookup_value(cls, value, output_field): <NEW_LINE> <INDENT> if hasattr(value, '_prepare'): <NEW_LINE> <INDENT> return value._prepare(output_field) <NEW_LINE> <DEDENT> return output_field.get_prep_value(value) <NEW_LINE> <DEDENT> def get_db_prep_lookup(self, value, connection): <NEW_LINE> <INDENT> field = getattr(self.lhs.output_field, 'field', None) <NEW_LINE> get_db_prep_value = getattr(field, 'get_db_prep_value', None) <NEW_LINE> if not get_db_prep_value: <NEW_LINE> <INDENT> get_db_prep_value = self.lhs.output_field.get_db_prep_value <NEW_LINE> <DEDENT> return ( '%s', [get_db_prep_value(v, connection, prepared=True) for v in value] if self.get_db_prep_lookup_value_is_iterable else [get_db_prep_value(value, connection, prepared=True)] )
Some lookups require Field.get_db_prep_value() to be called on their inputs.
62599047d53ae8145f9197d4
class BaseConfig(object): <NEW_LINE> <INDENT> TESTING = False <NEW_LINE> DEBUG = False <NEW_LINE> SECRET_KEY = "justincase"
Common configurations
62599047379a373c97d9a39f
class ChangeRoomForm(forms.ModelForm): <NEW_LINE> <INDENT> labels_file = forms.FileField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = OTreeInstance <NEW_LINE> fields = ['otree_room_name', 'labels_file'] <NEW_LINE> <DEDENT> def clean_labels_file(self): <NEW_LINE> <INDENT> participant_label_file = self.cleaned_data.get('labels_file', False) <NEW_LINE> if participant_label_file.size > 1024: <NEW_LINE> <INDENT> raise forms.ValidationError(error_messages['file_size'], code="invalid file") <NEW_LINE> <DEDENT> if not participant_label_file: <NEW_LINE> <INDENT> raise forms.ValidationError(error_messages['no_labels'], code="invalid file") <NEW_LINE> <DEDENT> return participant_label_file <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> inst = super().save() <NEW_LINE> labels = [] <NEW_LINE> for line in self.cleaned_data.get('labels_file', []): <NEW_LINE> <INDENT> label = line.decode('utf-8').strip() <NEW_LINE> if label: <NEW_LINE> <INDENT> labels.append(label) <NEW_LINE> <DEDENT> <DEDENT> inst.set_participant_labels(labels) <NEW_LINE> return inst
Form for changing room details
6259904763b5f9789fe864e1
class AllTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_zero_hour(self): <NEW_LINE> <INDENT> self.assertEqual( hour_man.hhmmss2sec(0,0,0), 0 ) <NEW_LINE> <DEDENT> def test_random_hour(self): <NEW_LINE> <INDENT> self.assertEqual( hour_man.hhmmss2sec(15,32,11), 55931 ) <NEW_LINE> <DEDENT> def test_max_hour(self): <NEW_LINE> <INDENT> self.assertEqual( hour_man.hhmmss2sec(23,59,59), 86399 ) <NEW_LINE> <DEDENT> def test_hour_range_pos(self): <NEW_LINE> <INDENT> self.assertTrue( hour_man.checkHourRange(0) ) <NEW_LINE> <DEDENT> def test_hour_range_neg(self): <NEW_LINE> <INDENT> self.assertFalse( hour_man.checkHourRange(24) ) <NEW_LINE> <DEDENT> def test_minutes_seconds_range_pos(self): <NEW_LINE> <INDENT> self.assertTrue( hour_man.checkMinutesSecondsRange(37) ) <NEW_LINE> <DEDENT> def test_minutes_seconds_range_neg(self): <NEW_LINE> <INDENT> self.assertFalse( hour_man.checkMinutesSecondsRange(60) )
Test the stand-alone module functions.
62599047b57a9660fecd2df2
class Field(ScopeContext): <NEW_LINE> <INDENT> def __init__(self, type_, default=UNSET, serializer=UNSET): <NEW_LINE> <INDENT> self.type_ = type_ <NEW_LINE> self.default = default <NEW_LINE> self.serializer = serializer <NEW_LINE> <DEDENT> def serialize(self, value): <NEW_LINE> <INDENT> serializer = self.serializer <NEW_LINE> if serializer is not UNSET: <NEW_LINE> <INDENT> with scope_context(serializer, self.name, self.parent): <NEW_LINE> <INDENT> return serializer.dump(value) <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def deserialize(self, value): <NEW_LINE> <INDENT> serializer = self.serializer <NEW_LINE> if serializer is not UNSET: <NEW_LINE> <INDENT> with scope_context(serializer, self.name, self.parent): <NEW_LINE> <INDENT> return serializer.load(value) <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if not isinstance(value, self.type_): <NEW_LINE> <INDENT> raise ValueError(u'{} is no {} type'.format(value, self.type_))
A schema field.
625990471f5feb6acb163f6b
class _MoeUITask(object): <NEW_LINE> <INDENT> def __init__(self, ui, task_name, description, formatter): <NEW_LINE> <INDENT> self._ui = ui <NEW_LINE> self._task_name = task_name <NEW_LINE> self._description = description <NEW_LINE> self._formatter = formatter <NEW_LINE> self._result = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._formatter.PrintBeginning(self._description) <NEW_LINE> self._ui._tasks.append(self._task_name) <NEW_LINE> return self <NEW_LINE> <DEDENT> def SetResult(self, result): <NEW_LINE> <INDENT> if self._result: <NEW_LINE> <INDENT> raise base.Error( "Trying to set result on task %s, but it is already %s" % ( self._task_name, self._result)) <NEW_LINE> <DEDENT> self._result = result <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> if not self._ui._tasks: <NEW_LINE> <INDENT> raise base.Error("Trying to end task %s, but no tasks on the stack" % self._task_name) <NEW_LINE> <DEDENT> if self._ui._tasks[-1] != self._task_name: <NEW_LINE> <INDENT> raise base.Error("Trying to end task %s, but current task is %s" % (self._task_name, self._ui._tasks[-1])) <NEW_LINE> <DEDENT> self._ui._tasks = self._ui._tasks[:-1] <NEW_LINE> self._formatter.PrintEnding(self._description, self._result) <NEW_LINE> return False
_MoeUITask encapsulates a single, transactional task in the UI.
6259904730dc7b76659a0ba8
class ArgumentError(SQLAlchemyError): <NEW_LINE> <INDENT> pass
Raised when an invalid or conflicting function argument is supplied. This error generally corresponds to construction time state errors.
6259904710dbd63aa1c71f50
class RandInt(PyoObject): <NEW_LINE> <INDENT> def __init__(self, max=100, freq=1.0, mul=1, add=0): <NEW_LINE> <INDENT> pyoArgsAssert(self, "OOOO", max, freq, mul, add) <NEW_LINE> PyoObject.__init__(self, mul, add) <NEW_LINE> self._max = max <NEW_LINE> self._freq = freq <NEW_LINE> max, freq, mul, add, lmax = convertArgsToLists(max, freq, mul, add) <NEW_LINE> self._base_objs = [RandInt_base(wrap(max, i), wrap(freq, i), wrap(mul, i), wrap(add, i)) for i in range(lmax)] <NEW_LINE> self._init_play() <NEW_LINE> <DEDENT> def setMax(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "O", x) <NEW_LINE> self._max = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setMax(wrap(x, i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> def setFreq(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "O", x) <NEW_LINE> self._freq = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setFreq(wrap(x, i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> def ctrl(self, map_list=None, title=None, wxnoserver=False): <NEW_LINE> <INDENT> self._map_list = [ SLMap(1.0, 2.0, "lin", "max", self._max), SLMap(0.1, 20.0, "lin", "freq", self._freq), SLMapMul(self._mul), ] <NEW_LINE> PyoObject.ctrl(self, map_list, title, wxnoserver) <NEW_LINE> <DEDENT> @property <NEW_LINE> def max(self): <NEW_LINE> <INDENT> return self._max <NEW_LINE> <DEDENT> @max.setter <NEW_LINE> def max(self, x): <NEW_LINE> <INDENT> self.setMax(x) <NEW_LINE> <DEDENT> @property <NEW_LINE> def freq(self): <NEW_LINE> <INDENT> return self._freq <NEW_LINE> <DEDENT> @freq.setter <NEW_LINE> def freq(self, x): <NEW_LINE> <INDENT> self.setFreq(x)
Periodic pseudo-random integer generator. RandInt generates a pseudo-random integer number between 0 and `max` values at a frequency specified by `freq` parameter. RandInt will hold generated value until the next generation. :Parent: :py:class:`PyoObject` :Args: max: float or PyoObject, optional Maximum value for the random generation. Defaults to 100. freq: float or PyoObject, optional Polling frequency. Defaults to 1. >>> s = Server().boot() >>> s.start() >>> freq = RandInt(max=10, freq=5, mul=100, add=500) >>> jit = Randi(min=0.99, max=1.01, freq=[2.33,3.41]) >>> a = SineLoop(freq*jit, feedback=0.03, mul=.2).out()
6259904707d97122c4218017
class FunctionalForm(Component): <NEW_LINE> <INDENT> def __init__(self, extent, decay, rough, left_component, right_component, name='', reverse=False, microslab_max_thickness=1): <NEW_LINE> <INDENT> super(FunctionalForm, self).__init__(name=name) <NEW_LINE> self.left_component = left_component <NEW_LINE> self.right_component = right_component <NEW_LINE> self.reverse = reverse <NEW_LINE> self.microslab_max_thickness = microslab_max_thickness <NEW_LINE> self.extent = ( possibly_create_parameter(extent, name='%s - functional extent' % name)) <NEW_LINE> self.decay = ( possibly_create_parameter(decay, name='%s - decay length' % name)) <NEW_LINE> self.rough = ( possibly_create_parameter(rough, name='%s - rough' % name)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> p = Parameters(name=self.name) <NEW_LINE> p.extend([self.extent, self.decay, self.rough]) <NEW_LINE> return p <NEW_LINE> <DEDENT> def slabs(self, structure=None): <NEW_LINE> <INDENT> num_slabs = np.ceil(float(self.extent) / self.microslab_max_thickness) <NEW_LINE> slab_thick = float(self.extent / num_slabs) <NEW_LINE> slabs = np.zeros((int(num_slabs), 5)) <NEW_LINE> slabs[:, 0] = slab_thick <NEW_LINE> a = self.left_component.slabs()[-1, 1] <NEW_LINE> b = self.right_component.slabs()[0, 1] <NEW_LINE> dist = np.cumsum(slabs[..., 0]) - 0.5 * slab_thick <NEW_LINE> if self.reverse: <NEW_LINE> <INDENT> slabs[0, 3] = self.rough <NEW_LINE> if a <= b: <NEW_LINE> <INDENT> slabs[:, 1] = np.abs(b - a) * np.exp(-dist / self.decay) + a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slabs[:, 1] = np.abs(b - a) * (1. - np.exp(-dist / self.decay)) + b <NEW_LINE> <DEDENT> slabs[0, 3] = self.rough <NEW_LINE> return slabs[::-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if a >= b: <NEW_LINE> <INDENT> slabs[:, 1] = np.abs(b - a) * np.exp(-dist / self.decay) + b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slabs[:, 1] = np.abs(b - a) * (1. - np.exp(-dist / self.decay)) + a <NEW_LINE> <DEDENT> slabs[0, 3] = self.rough <NEW_LINE> <DEDENT> return slabs
Component describing an analytic SLD profile. An exponential profile is hard coded here. Parameters ---------- extent : Parameter or float The total extent of the functional region decay : Parameter or float Decay length of exponential profile rough : Parameter or float Roughness between this Component and `left_component` left_component : Component Prior Component (used to obtain the SLD of the layer immediately before this one) right_component : Component Following Component (used to obtain the SLD of the layer immediately after this one) name : str Name of component reverse : bool reverses the profile in this component alone microslab_max_thickness : float, optional Thickness of microslicing of spline for reflectivity calculation
6259904707d97122c4218018
class Maciek(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Model definition for Maciek.
625990478da39b475be04566
class StoppableThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(StoppableThread, self).__init__(**kwargs) <NEW_LINE> self._stop_requested = threading.Event() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._stop_requested.set() <NEW_LINE> <DEDENT> def stopped(self): <NEW_LINE> <INDENT> return self._stop_requested.isSet()
Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
6259904745492302aabfd848
class TestTileProcessor(TileProcessor): <NEW_LINE> <INDENT> def setup(self, parameters): <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> <DEDENT> def process(self, file_path, x_index, y_index, z_index, t_index=None): <NEW_LINE> <INDENT> return open(file_path, 'rb')
Example processor for unit tests
62599047c432627299fa42be
class Wait(object): <NEW_LINE> <INDENT> CLASS_NAME = "Native_wait___" <NEW_LINE> def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): <NEW_LINE> <INDENT> self._driver = driver <NEW_LINE> self._timeout = timeout <NEW_LINE> self._poll = poll_frequency <NEW_LINE> if self._poll == 0: <NEW_LINE> <INDENT> self._poll = POLL_FREQUENCY <NEW_LINE> <DEDENT> exceptions = list(IGNORED_EXCEPTIONS) <NEW_LINE> if ignored_exceptions is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exceptions.extend(iter(ignored_exceptions)) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> exceptions.append(ignored_exceptions) <NEW_LINE> <DEDENT> <DEDENT> self._ignored_exceptions = tuple(exceptions) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<{0.__module__}.{0.__name__} (session="{1}")>'.format( type(self), self._driver.session_id) <NEW_LINE> <DEDENT> def until(self, method, message=''): <NEW_LINE> <INDENT> screen = None <NEW_LINE> stacktrace = None <NEW_LINE> end_time = time.time() + self._timeout <NEW_LINE> value = None <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = method(self._driver) <NEW_LINE> if value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> except self._ignored_exceptions as exc: <NEW_LINE> <INDENT> screen = getattr(exc, 'screen', None) <NEW_LINE> stacktrace = getattr(exc, 'stacktrace', None) <NEW_LINE> <DEDENT> time.sleep(self._poll) <NEW_LINE> if time.time() > end_time: <NEW_LINE> <INDENT> logger.exception(self.CLASS_NAME + " cannot find elements after wait-time-out!") <NEW_LINE> try: <NEW_LINE> <INDENT> res = run_all_methods(self._driver) <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> logger.error(self.CLASS_NAME+" occur error when run white list") <NEW_LINE> screen_shot(driver=self._driver, filename=self.CLASS_NAME + ".png") <NEW_LINE> raise NoSuchElementException(message, screen, stacktrace) <NEW_LINE> <DEDENT> value = method(self._driver) <NEW_LINE> if value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif not value and not res: <NEW_LINE> <INDENT> return self.until(method, message='') <NEW_LINE> <DEDENT> elif not value and res: <NEW_LINE> <INDENT> logger.error(self.CLASS_NAME + " cannot find element and don't exist in white list") <NEW_LINE> screen_shot(driver=self._driver, filename=self.CLASS_NAME + ".png") <NEW_LINE> raise NoSuchElementException(message, screen, stacktrace) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def until_not(self, method, message=''): <NEW_LINE> <INDENT> end_time = time.time() + self._timeout <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = method(self._driver) <NEW_LINE> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> except self._ignored_exceptions: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> time.sleep(self._poll) <NEW_LINE> if time.time() > end_time: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> raise TimeoutException(message)
Native find element wait
6259904730c21e258be99b7d
class Permission(db.Model, IdModel, SoftDeleteModel): <NEW_LINE> <INDENT> __tablename__ = 'permission' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> role_id = db.Column(db.Integer, db.ForeignKey('role.id'), index=True) <NEW_LINE> read = db.Column(db.Boolean, default=False) <NEW_LINE> write = db.Column(db.Boolean, default=False) <NEW_LINE> collection_id = db.Column(db.Integer, nullable=False) <NEW_LINE> @classmethod <NEW_LINE> def grant(cls, collection, role, read, write): <NEW_LINE> <INDENT> permission = cls.by_collection_role(collection, role) <NEW_LINE> if permission is None: <NEW_LINE> <INDENT> permission = Permission() <NEW_LINE> permission.role_id = role.id <NEW_LINE> permission.collection_id = collection.id <NEW_LINE> db.session.add(permission) <NEW_LINE> <DEDENT> permission.read = read or write <NEW_LINE> permission.write = write <NEW_LINE> if not permission.read: <NEW_LINE> <INDENT> permission.deleted_at = datetime.utcnow() <NEW_LINE> <DEDENT> db.session.flush() <NEW_LINE> collection.reset_state() <NEW_LINE> return permission <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def by_collection_role(cls, collection, role): <NEW_LINE> <INDENT> q = cls.all() <NEW_LINE> q = q.filter(Permission.role_id == role.id) <NEW_LINE> q = q.filter(Permission.collection_id == collection.id) <NEW_LINE> permission = q.first() <NEW_LINE> return permission <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def delete_by_collection(cls, collection_id, deleted_at=None): <NEW_LINE> <INDENT> if deleted_at is None: <NEW_LINE> <INDENT> deleted_at = datetime.utcnow() <NEW_LINE> <DEDENT> q = db.session.query(cls) <NEW_LINE> q = q.filter(cls.collection_id == collection_id) <NEW_LINE> q.update({cls.deleted_at: deleted_at}, synchronize_session=False)
A set of rights granted to a role on a resource.
6259904794891a1f408ba0b1
class Management(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'course_manager' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "the Management"
deprecated! This class covers no functionality at all and should be removed with the next update. Mind possible cross-dependencies when applying changes.
6259904729b78933be26aa7e
class IntentPolicy(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self, policy_name): <NEW_LINE> <INDENT> super(IntentPolicy, self).__init__() <NEW_LINE> self.policy_name = policy_name <NEW_LINE> <DEDENT> def get_policy_name(self): <NEW_LINE> <INDENT> return self.policy_name <NEW_LINE> <DEDENT> def set_slots(self, slots): <NEW_LINE> <INDENT> self.slots = {} <NEW_LINE> for slot in slots: <NEW_LINE> <INDENT> self.slots[slot.name] = slot <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> for slot in self.slots.values(): <NEW_LINE> <INDENT> slot.clear() <NEW_LINE> <DEDENT> <DEDENT> def get_unfinished_slots(self): <NEW_LINE> <INDENT> return [slot for slot in self.slots.values() if slot.enabling_condition(self.slots) and not slot.is_fully_filled()] <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_info(self, sentence): <NEW_LINE> <INDENT> return self.get_unfinished_slots() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def ask_info(self, unfilled_slots): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def confirm_info(self): <NEW_LINE> <INDENT> return "Please confirm the following information: {}.".format('; '.join([str(slot) for slot in self.slots.values()])) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_confirmation(self, sentence): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def action_with_information(self): <NEW_LINE> <INDENT> pass
Policy to handle an intention of the user.
62599047baa26c4b54d50621
class AlphaBetaAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> def maxFunction(gameState, depth, alpha, beta): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose() or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> maxVal = -float("inf") <NEW_LINE> actions = gameState.getLegalActions(agentIndex = 0) <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> maxVal = max(maxVal, minFunction(gameState.generateSuccessor(0, action),depth, 1, alpha, beta)) <NEW_LINE> if maxVal > beta: <NEW_LINE> <INDENT> return maxVal <NEW_LINE> <DEDENT> alpha = max(alpha, maxVal) <NEW_LINE> <DEDENT> return maxVal <NEW_LINE> <DEDENT> def minFunction(gameState, depth, ghost, alpha, beta): <NEW_LINE> <INDENT> if gameState.isWin() or gameState.isLose() or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> minVal = float("inf") <NEW_LINE> actions = gameState.getLegalActions(agentIndex = ghost) <NEW_LINE> if ghost != gameState.getNumAgents()-1: <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> minVal = min(minVal, minFunction(gameState.generateSuccessor(ghost, action), depth, ghost+1, alpha, beta)) <NEW_LINE> if minVal < alpha: <NEW_LINE> <INDENT> return minVal <NEW_LINE> <DEDENT> beta = min(beta, minVal) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> minVal = min(minVal, maxFunction(gameState.generateSuccessor(gameState.getNumAgents()-1, action), depth-1, alpha, beta)) <NEW_LINE> if minVal < alpha: <NEW_LINE> <INDENT> return minVal <NEW_LINE> <DEDENT> beta = min(beta, minVal) <NEW_LINE> <DEDENT> <DEDENT> return minVal <NEW_LINE> <DEDENT> actions = gameState.getLegalActions() <NEW_LINE> best = Directions.STOP <NEW_LINE> score = -float("inf") <NEW_LINE> maxScore = -float("inf") <NEW_LINE> alpha = -float("inf") <NEW_LINE> beta = float("inf") <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> maxScore = score <NEW_LINE> score = max(score, minFunction(gameState.generateSuccessor(0, action), self.depth, 1, alpha, beta)) <NEW_LINE> if score > maxScore: <NEW_LINE> <INDENT> maxScore = score <NEW_LINE> best = action <NEW_LINE> <DEDENT> if score > beta: <NEW_LINE> <INDENT> return best <NEW_LINE> <DEDENT> alpha = max(alpha, maxScore) <NEW_LINE> <DEDENT> return best <NEW_LINE> util.raiseNotDefined()
Your minimax agent with alpha-beta pruning (question 3)
6259904723e79379d538d875
class MyChevyHub(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, client, hass, hass_config): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._client = client <NEW_LINE> self.hass = hass <NEW_LINE> self.hass_config = hass_config <NEW_LINE> self.cars = [] <NEW_LINE> self.status = None <NEW_LINE> self.ready = False <NEW_LINE> <DEDENT> @Throttle(MIN_TIME_BETWEEN_UPDATES) <NEW_LINE> def update(self): <NEW_LINE> <INDENT> self._client.login() <NEW_LINE> self._client.get_cars() <NEW_LINE> self.cars = self._client.cars <NEW_LINE> if self.ready is not True: <NEW_LINE> <INDENT> discovery.load_platform(self.hass, 'sensor', DOMAIN, {}, self.hass_config) <NEW_LINE> discovery.load_platform(self.hass, 'binary_sensor', DOMAIN, {}, self.hass_config) <NEW_LINE> self.ready = True <NEW_LINE> <DEDENT> self.cars = self._client.update_cars() <NEW_LINE> <DEDENT> def get_car(self, vid): <NEW_LINE> <INDENT> if self.cars: <NEW_LINE> <INDENT> for car in self.cars: <NEW_LINE> <INDENT> if car.vid == vid: <NEW_LINE> <INDENT> return car <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _LOGGER.info("Starting mychevy loop") <NEW_LINE> self.update() <NEW_LINE> self.hass.helpers.dispatcher.dispatcher_send(UPDATE_TOPIC) <NEW_LINE> time.sleep(MIN_TIME_BETWEEN_UPDATES.seconds) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception( "Error updating mychevy data. " "This probably means the OnStar link is down again") <NEW_LINE> self.hass.helpers.dispatcher.dispatcher_send(ERROR_TOPIC) <NEW_LINE> time.sleep(ERROR_SLEEP_TIME.seconds)
MyChevy Hub. Connecting to the mychevy website is done through a selenium webscraping process. That can only run synchronously. In order to prevent blocking of other parts of Home Assistant the architecture launches a polling loop in a thread. When new data is received, sensors are updated, and hass is signaled that there are updates. Sensors are not created until the first update, which will be 60 - 120 seconds after the platform starts.
62599047097d151d1a2c23e3
@admin.register(GlobalSeo) <NEW_LINE> class GlobalSeoAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> fieldsets = ( ('Главная страница', {'fields': ('main_seo_title', 'main_seo_description', 'main_seo_keywords')}), ('Блог', {'fields': ('blog_seo_title', 'blog_seo_description', 'blog_seo_keywords')}), ('Портфолио', {'fields': ('portfolio_seo_title', 'portfolio_description', 'portfolio_seo_keywords')}), ('Контакты', {'fields': ('contact_seo_title', 'contact_seo_description', 'contact_seo_keywords')}), ) <NEW_LINE> def has_add_permission(self, request): <NEW_LINE> <INDENT> return False if self.model.objects.count() > 0 else True
Admin for global SEO settings
625990471f5feb6acb163f6d
class ReplicaAppResource(tardis.tardis_portal.api.ReplicaResource): <NEW_LINE> <INDENT> class Meta(tardis.tardis_portal.api.ReplicaResource.Meta): <NEW_LINE> <INDENT> resource_name = 'replica' <NEW_LINE> authorization = ACLAuthorization() <NEW_LINE> queryset = DataFileObject.objects.all() <NEW_LINE> filtering = { 'verified': ('exact',), 'url': ('exact', 'startswith'), } <NEW_LINE> <DEDENT> def dehydrate(self, bundle): <NEW_LINE> <INDENT> dfo = bundle.obj <NEW_LINE> bundle.data['location'] = dfo.storage_box.name <NEW_LINE> try: <NEW_LINE> <INDENT> file_object_size = getattr( getattr(dfo, 'file_object', None), 'size', None) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> file_object_size = None <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> file_object_size = None <NEW_LINE> <DEDENT> bundle.data['size'] = file_object_size <NEW_LINE> return bundle
Extends MyTardis's API for DFOs, adding in the size as measured by file_object.size
62599047d7e4931a7ef3d3ed
class TestDedupeApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = isi_sdk_8_2_1.api.dedupe_api.DedupeApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_dedupe_summary(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_report(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_reports(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_inline_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_dedupe_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_inline_settings(self): <NEW_LINE> <INDENT> pass
DedupeApi unit test stubs
62599047596a897236128f6b
class ApplicationConfig(BaseWorker.CONFIG_CLASS): <NEW_LINE> <INDENT> transport_name = ConfigText( "The name this application instance will use to create its queues.", required=True, static=True) <NEW_LINE> send_to = ConfigDict( "'send_to' configuration dict.", default={}, static=True)
Base config definition for applications. You should subclass this and add application-specific fields.
6259904726238365f5faded4
class Hunt_Specification( namedtuple('Hunt_Specification', ('J', 'C', 'h', 's', 'Q', 'M', 'H', 'HC'))): <NEW_LINE> <INDENT> pass
Defines the Hunt colour appearance model specification. This specification has field names consistent with the remaining colour appearance models in :mod:`colour.appearance` but diverge from Fairchild (2013) reference. Parameters ---------- J : numeric Correlate of *Lightness* :math:`J`. C : numeric Correlate of *chroma* :math:`C_94`. h : numeric *Hue* angle :math:`h_S` in degrees. s : numeric Correlate of *saturation* :math:`s`. Q : numeric Correlate of *brightness* :math:`Q`. M : numeric Correlate of *colourfulness* :math:`M_94`. H : numeric *Hue* :math:`h` quadrature :math:`H`. HC : numeric *Hue* :math:`h` composition :math:`H_C`.
6259904715baa72349463309
class Solution(object): <NEW_LINE> <INDENT> def countAndSay(self, n): <NEW_LINE> <INDENT> res = '1' <NEW_LINE> for _ in range(n - 1): <NEW_LINE> <INDENT> res = self.helper(res) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def helper(self, n): <NEW_LINE> <INDENT> count, i, res = 1, 0, "" <NEW_LINE> while i < len(n) - 1: <NEW_LINE> <INDENT> if n[i] == n[i + 1]: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res += str(count) + n[i] <NEW_LINE> count = 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> res += str(count) + n[i] <NEW_LINE> return res
理解了题意即懂如何做,题意是依据上一个字符串来推导下一个字符串,第一个字符串是"1",所以第二个就是1个1,即"11", 第三个就是2个1,即"21",第四个就是1个2,1个1,即"1211"; 解法就是遍历需要得到的答案位于第几个,然后针对每一个去求得它的值 Runtime: 24 ms, faster than 64.32% of Python online submissions for Count and Say. Memory Usage: 11.8 MB, less than 5.40% of Python online submissions for Count and Say.
62599047e76e3b2f99fd9d84
class number_of_jobs(Variable): <NEW_LINE> <INDENT> _return_type="int32" <NEW_LINE> def dependencies(self): <NEW_LINE> <INDENT> return [attribute_label("faz", "large_area_id"), attribute_label("faz", "number_of_jobs"), my_attribute_label("large_area_id")] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> faz = dataset_pool.get_dataset('faz') <NEW_LINE> return self.get_dataset().sum_over_ids(faz.get_attribute("large_area_id"), faz.get_attribute("number_of_jobs")) <NEW_LINE> <DEDENT> def post_check(self, values, dataset_pool): <NEW_LINE> <INDENT> size = dataset_pool.get_dataset('faz').get_attribute("number_of_jobs").sum() <NEW_LINE> self.do_check("x >= 0 and x <= " + str(size), values)
Number of jobs in each area
62599047b830903b9686ee37
class BitwiseNegationOperator(UnaryOperator): <NEW_LINE> <INDENT> pass
Represents the '~' bitwise negation operator
625990474e696a045264e7dd
class CmdChannels(MuxCommand): <NEW_LINE> <INDENT> key = "channels" <NEW_LINE> aliases = ["comlist"] <NEW_LINE> help_category = "Comms" <NEW_LINE> locks = "cmd: not pperm(channel_banned)" <NEW_LINE> account_caller = True <NEW_LINE> def func(self): <NEW_LINE> <INDENT> caller = self.caller <NEW_LINE> channels = [chan for chan in ChannelDB.objects.get_all_channels() if chan.access(caller, 'listen')] <NEW_LINE> if not channels: <NEW_LINE> <INDENT> self.msg("No channels available.") <NEW_LINE> return <NEW_LINE> <DEDENT> subs = ChannelDB.objects.get_subscriptions(caller) <NEW_LINE> if self.cmdstring == "comlist": <NEW_LINE> <INDENT> comtable = evtable.EvTable("|wchannel|n", "|wmy aliases|n", "|wdescription|n", align="l", maxwidth=_DEFAULT_WIDTH) <NEW_LINE> for chan in subs: <NEW_LINE> <INDENT> clower = chan.key.lower() <NEW_LINE> nicks = caller.nicks.get(category="channel", return_obj=True) <NEW_LINE> comtable.add_row(*["%s%s" % (chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or ""), "%s" % ",".join(nick.db_key for nick in make_iter(nicks) if nick and nick.value[3].lower() == clower), chan.db.desc]) <NEW_LINE> <DEDENT> self.msg("\n|wChannel subscriptions|n (use |w@channels|n to list all," " |waddcom|n/|wdelcom|n to sub/unsub):|n\n%s" % comtable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> comtable = evtable.EvTable("|wsub|n", "|wchannel|n", "|wmy aliases|n", "|wlocks|n", "|wdescription|n", maxwidth=_DEFAULT_WIDTH) <NEW_LINE> for chan in channels: <NEW_LINE> <INDENT> clower = chan.key.lower() <NEW_LINE> nicks = caller.nicks.get(category="channel", return_obj=True) <NEW_LINE> nicks = nicks or [] <NEW_LINE> if chan not in subs: <NEW_LINE> <INDENT> substatus = "|rNo|n" <NEW_LINE> <DEDENT> elif caller in chan.mutelist: <NEW_LINE> <INDENT> substatus = "|rMuted|n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> substatus = "|gYes|n" <NEW_LINE> <DEDENT> comtable.add_row(*[substatus, "%s%s" % (chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or ""), "%s" % ",".join(nick.db_key for nick in make_iter(nicks) if nick.value[3].lower() == clower), str(chan.locks), chan.db.desc]) <NEW_LINE> <DEDENT> comtable.reformat_column(0, width=9) <NEW_LINE> comtable.reformat_column(3, width=14) <NEW_LINE> self.msg("\n|wAvailable channels|n (use |wcomlist|n,|waddcom|n and |wdelcom|n" " to manage subscriptions):\n%s" % comtable)
list all channels available to you Usage: channels clist comlist Lists all channels available to you, whether you listen to them or not. Use 'comlist' to only view your current channel subscriptions. Use addcom/delcom to join and leave channels
6259904796565a6dacd2d946
class GameObject(metaclass=GameObjectMeta): <NEW_LINE> <INDENT> registry = GameObjectRegistry() <NEW_LINE> load_priority = 0 <NEW_LINE> hooks = [] <NEW_LINE> def __init__(self, id_=None): <NEW_LINE> <INDENT> id_ = id_ or self.registry.make_id() <NEW_LINE> self.id_ = id_ <NEW_LINE> self.registry[id_] = self <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> return { 'cls': type(self).__name__, 'id_': self.id_, } <NEW_LINE> <DEDENT> def load(self, struct): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> del self.registry[self.id_] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def locate(cls): <NEW_LINE> <INDENT> if hasattr(cls, 'name'): <NEW_LINE> <INDENT> name = cls.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = cls.__name__ <NEW_LINE> <DEDENT> return cls.registry.categories[name]
{ cls: class_name, id: id_ or None }
62599047b57a9660fecd2df6
class ConfigurationException(mcxPyBotException): <NEW_LINE> <INDENT> pass
Exception for configuration errors detected on runtime of mcxPyBot.
62599047d53ae8145f9197d9
@parser(Specs.sysctl_conf_initramfs) <NEW_LINE> class SysctlConfInitramfs(CommandParser, LogFileOutput): <NEW_LINE> <INDENT> def parse_content(self, content): <NEW_LINE> <INDENT> valid_lines = [] <NEW_LINE> for line in content: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if line and not (line.startswith('#') or line.startswith(';')): <NEW_LINE> <INDENT> valid_lines.append(line) <NEW_LINE> <DEDENT> <DEDENT> super(SysctlConfInitramfs, self).parse_content(valid_lines)
Shared parser for the output of ``lsinitrd`` applied to kdump initramfs images to view ``sysctl.conf`` and ``sysctl.d`` configurations. For now, the file is treated as raw lines (as a ``LogFileOutput`` parser. This is because the output of the command, applied to multiple files to examine multiple files does not seem to be unambiguously parsable. Since the only plugins requiring the file to date "grep out" certain strings, this approach will suffice. .. note:: Please refer to its super-class :class:`insights.core.LogFileOutput` Sample input:: initramfs:/etc/sysctl.conf ======================================================================== # sysctl settings are defined through files in # /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/. # # Vendors settings live in /usr/lib/sysctl.d/. # To override a whole file, create a new file with the same in # /etc/sysctl.d/ and put new settings there. To override # only specific settings, add a file with a lexically later # name in /etc/sysctl.d/ and put new settings there. # # For more information, see sysctl.conf(5) and sysctl.d(5). fs.inotify.max_user_watches=524288 ======================================================================== initramfs:/etc/sysctl.d/*.conf ======================================================================== ======================================================================== Examples: >>> type(sysctl_initramfs) <class 'insights.parsers.sysctl.SysctlConfInitramfs'> >>> sysctl_initramfs.get('max_user_watches') [{'raw_message': 'fs.inotify.max_user_watches=524288'}]
6259904771ff763f4b5e8b1d
class ContatosViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Contato.objects.all() <NEW_LINE> serializer_class = ContatoSerializer
Exibindo todos os Contatos
6259904773bcbd0ca4bcb606
class Odbc(Publisher): <NEW_LINE> <INDENT> def __init__(self, dsn): <NEW_LINE> <INDENT> Publisher.__init__(self) <NEW_LINE> self._dsn = dsn <NEW_LINE> self._sql = None <NEW_LINE> self._cursor = None <NEW_LINE> self._sql = None <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._sql = odbc.odbc(self._dsn) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._cursor.close() <NEW_LINE> self._cursor = None <NEW_LINE> self._sql.close() <NEW_LINE> self._sql = None <NEW_LINE> <DEDENT> def call(self, method, args): <NEW_LINE> <INDENT> self._cursor = self._sql.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> self._cursor.execute(method, args) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Warning: execute failed: %s" % sys.exc_info()) <NEW_LINE> pass <NEW_LINE> <DEDENT> ret = '' <NEW_LINE> try: <NEW_LINE> <INDENT> row = self._cursor.fetchone() <NEW_LINE> for i in range(len(row)): <NEW_LINE> <INDENT> retType = type(row[i]) <NEW_LINE> if retType is IntType: <NEW_LINE> <INDENT> ret += "\t%d" % row[i] <NEW_LINE> <DEDENT> elif retType is FloatType: <NEW_LINE> <INDENT> ret += "\t%f" % row[i] <NEW_LINE> <DEDENT> elif retType is LongType: <NEW_LINE> <INDENT> ret += "\t%d" % row[i] <NEW_LINE> <DEDENT> elif retType is StringType: <NEW_LINE> <INDENT> ret += "\t%s" % row[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return ret
Publisher for ODBC connections. Generated data sent as a SQL query via execute. Calling receave will return a string of all row data concatenated together with as field separator. Currently this Publisher makes use of the odbc package which is some what broken in that you must create an actual ODBC DSN via the ODBC manager. Check out mxODBC which is not open source for another alterative. Note: Each call to start/stop will create and close the SQL connection and cursor.
6259904710dbd63aa1c71f54
class HttpMessage(object): <NEW_LINE> <INDENT> def __init__(self, version='1.1'): <NEW_LINE> <INDENT> self.version = version <NEW_LINE> self._headers = dict() <NEW_LINE> <DEDENT> @property <NEW_LINE> def headers(self): <NEW_LINE> <INDENT> return self._headers <NEW_LINE> <DEDENT> def header(self, name): <NEW_LINE> <INDENT> nameval = strval(name) <NEW_LINE> header = self._headers.get(nameval, None) <NEW_LINE> if not header: <NEW_LINE> <INDENT> header = HttpHeader(name) <NEW_LINE> self._headers[nameval] = header <NEW_LINE> <DEDENT> return header <NEW_LINE> <DEDENT> def replace_header(self, name): <NEW_LINE> <INDENT> self.remove_header(name) <NEW_LINE> return self.header(name) <NEW_LINE> <DEDENT> def get_header(self, name): <NEW_LINE> <INDENT> return self._headers.get(strval(name), None) <NEW_LINE> <DEDENT> def remove_header(self, name): <NEW_LINE> <INDENT> nameval = strval(name) <NEW_LINE> if nameval in self._headers: <NEW_LINE> <INDENT> del self._headers[nameval] <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Parent class for requests and responses. Many of the elements in the messages share common structures. Attributes: version A bytearray or string value representing the major-minor version of the HttpMessage.
6259904721a7993f00c672e3
class MLPHeb(HebbianNetwork): <NEW_LINE> <INDENT> def __init__(self, config=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> defaults = dict( device="cpu", input_size=784, num_classes=10, hidden_sizes=[100, 100, 100], percent_on_k_winner=[1.0, 1.0, 1.0], boost_strength=[1.4, 1.4, 1.4], boost_strength_factor=[0.7, 0.7, 0.7], batch_norm=False, dropout=False, bias=True, k_inference_factor=1.0, ) <NEW_LINE> assert ( config is None or "use_kwinners" not in config ), "use_kwinners is deprecated" <NEW_LINE> defaults.update(config or {}) <NEW_LINE> self.__dict__.update(defaults) <NEW_LINE> self.device = torch.device(self.device) <NEW_LINE> self.activation_funcs = [] <NEW_LINE> for layer, hidden_size in enumerate(self.hidden_sizes): <NEW_LINE> <INDENT> if self.percent_on_k_winner[layer] < 0.5: <NEW_LINE> <INDENT> self.activation_funcs.append( KWinners( hidden_size, percent_on=self.percent_on_k_winner[layer], boost_strength=self.boost_strength[layer], boost_strength_factor=self.boost_strength_factor[layer], k_inference_factor=self.k_inference_factor, ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.activation_funcs.append(nn.ReLU()) <NEW_LINE> <DEDENT> <DEDENT> layers = [] <NEW_LINE> kwargs = dict(bias=self.bias, batch_norm=self.batch_norm, dropout=self.dropout) <NEW_LINE> layers = [nn.Flatten()] <NEW_LINE> layers.append( DSLinearBlock( self.input_size, self.hidden_sizes[0], activation_func=self.activation_funcs[0], config=config, **kwargs, ) ) <NEW_LINE> for i in range(1, len(self.hidden_sizes)): <NEW_LINE> <INDENT> layers.append( DSLinearBlock( self.hidden_sizes[i - 1], self.hidden_sizes[i], activation_func=self.activation_funcs[i], config=config, **kwargs, ) ) <NEW_LINE> <DEDENT> layers.append( DSLinearBlock( self.hidden_sizes[-1], self.num_classes, bias=self.bias, config=config ) ) <NEW_LINE> self.dynamic_sparse_modules = [layer[0] for layer in layers[1:]] <NEW_LINE> self.classifier = nn.Sequential(*layers) <NEW_LINE> self._track_coactivations = False
Simple 3 hidden layers + output MLP
6259904707f4c71912bb07ac
class FUGUE(FSLCommand): <NEW_LINE> <INDENT> _cmd = 'fugue' <NEW_LINE> input_spec = FUGUEInputSpec <NEW_LINE> output_spec = FUGUEOutputSpec <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(FUGUE, self).__init__(**kwargs) <NEW_LINE> warn( 'This interface has not been fully tested. Please report any failures.') <NEW_LINE> <DEDENT> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self._outputs().get() <NEW_LINE> if self.inputs.forward_warping: <NEW_LINE> <INDENT> out_field = 'warped_file' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_field = 'unwarped_file' <NEW_LINE> <DEDENT> out_file = getattr(self.inputs, out_field) <NEW_LINE> if not isdefined(out_file): <NEW_LINE> <INDENT> if isdefined(self.inputs.in_file): <NEW_LINE> <INDENT> out_file = self._gen_fname(self.inputs.in_file, suffix='_'+out_field[:-5]) <NEW_LINE> <DEDENT> <DEDENT> if isdefined(out_file): <NEW_LINE> <INDENT> outputs[out_field] = os.path.abspath(out_file) <NEW_LINE> <DEDENT> if isdefined(self.inputs.fmap_out_file): <NEW_LINE> <INDENT> outputs['fmap_out_file'] = os.path.abspath( self.inputs.fmap_out_file) <NEW_LINE> <DEDENT> if isdefined(self.inputs.shift_out_file): <NEW_LINE> <INDENT> outputs['shift_out_file'] = os.path.abspath( self.inputs.shift_out_file) <NEW_LINE> <DEDENT> return outputs <NEW_LINE> <DEDENT> def _gen_filename(self, name): <NEW_LINE> <INDENT> if name == 'unwarped_file' and not self.inputs.forward_warping: <NEW_LINE> <INDENT> return self._list_outputs()['unwarped_file'] <NEW_LINE> <DEDENT> if name == 'warped_file' and self.inputs.forward_warping: <NEW_LINE> <INDENT> return self._list_outputs()['warped_file'] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def _parse_inputs(self, skip=None): <NEW_LINE> <INDENT> if skip is None: <NEW_LINE> <INDENT> skip = [] <NEW_LINE> <DEDENT> if not isdefined(self.inputs.save_shift) or not self.inputs.save_shift: <NEW_LINE> <INDENT> skip += ['shift_out_file'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isdefined(self.inputs.shift_out_file): <NEW_LINE> <INDENT> self.inputs.shift_out_file = self._gen_fname( self.inputs.in_file, suffix='_vsm') <NEW_LINE> <DEDENT> <DEDENT> if not isdefined(self.inputs.in_file): <NEW_LINE> <INDENT> skip += ['unwarped_file', 'warped_file'] <NEW_LINE> <DEDENT> elif self.inputs.forward_warping: <NEW_LINE> <INDENT> if not isdefined(self.inputs.warped_file): <NEW_LINE> <INDENT> self.inputs.warped_file = self._gen_fname( self.inputs.in_file, suffix='_warped') <NEW_LINE> <DEDENT> <DEDENT> elif not self.inputs.forward_warping: <NEW_LINE> <INDENT> if not isdefined(self.inputs.unwarped_file): <NEW_LINE> <INDENT> self.inputs.unwarped_file = self._gen_fname( self.inputs.in_file, suffix='_unwarped') <NEW_LINE> <DEDENT> <DEDENT> return super(FUGUE, self)._parse_inputs(skip=skip)
Use FSL FUGUE to unwarp epi's with fieldmaps Examples -------- Please insert examples for use of this command
6259904707d97122c421801c
class ControllerGetResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'more_items_remaining': 'bool', 'total_item_count': 'int', 'continuation_token': 'str', 'items': 'list[Controller]' } <NEW_LINE> attribute_map = { 'more_items_remaining': 'more_items_remaining', 'total_item_count': 'total_item_count', 'continuation_token': 'continuation_token', 'items': 'items' } <NEW_LINE> required_args = { } <NEW_LINE> def __init__( self, more_items_remaining=None, total_item_count=None, continuation_token=None, items=None, ): <NEW_LINE> <INDENT> if more_items_remaining is not None: <NEW_LINE> <INDENT> self.more_items_remaining = more_items_remaining <NEW_LINE> <DEDENT> if total_item_count is not None: <NEW_LINE> <INDENT> self.total_item_count = total_item_count <NEW_LINE> <DEDENT> if continuation_token is not None: <NEW_LINE> <INDENT> self.continuation_token = continuation_token <NEW_LINE> <DEDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key not in self.attribute_map: <NEW_LINE> <INDENT> raise KeyError("Invalid key `{}` for `ControllerGetResponse`".format(key)) <NEW_LINE> <DEDENT> self.__dict__[key] = value <NEW_LINE> <DEDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> value = object.__getattribute__(self, item) <NEW_LINE> if isinstance(value, Property): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if issubclass(ControllerGetResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ControllerGetResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition.
625990478e71fb1e983bce47
class Test_Traversal(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.g = graph.DirectedGraph() <NEW_LINE> self.g.add_node("a") <NEW_LINE> self.g.add_node("b", ["a"]) <NEW_LINE> self.g.add_node("c", ["b"]) <NEW_LINE> self.g.add_node("d", ["b"]) <NEW_LINE> self.g.add_node("e") <NEW_LINE> self.g.add_node("f", ["e"]) <NEW_LINE> self.g.add_node("g") <NEW_LINE> self.g.add_node("h") <NEW_LINE> self.g.add_node("j") <NEW_LINE> self.g.add_node("i", ['h', 'j']) <NEW_LINE> <DEDENT> def test_get_all_dependencies(self): <NEW_LINE> <INDENT> li = self.g.get_all_dependencies("d") <NEW_LINE> self.assertEqual(li, ["b", "a"]) <NEW_LINE> li = self.g.get_all_dependencies("i") <NEW_LINE> self.assertEqual(li, ["h", "j"]) <NEW_LINE> li = self.g.get_all_dependencies("g") <NEW_LINE> self.assertEqual(li, []) <NEW_LINE> <DEDENT> def test_get_all_dependees(self): <NEW_LINE> <INDENT> li = self.g.get_all_dependees("a") <NEW_LINE> self.assertEqual(li, ["b", "c", "d"]) <NEW_LINE> li = self.g.get_all_dependees("e") <NEW_LINE> self.assertEqual(li, ["f"]) <NEW_LINE> <DEDENT> def test_iterator(self): <NEW_LINE> <INDENT> iterator = graph.iter_from_root_to_leaves(self.g) <NEW_LINE> visited = [] <NEW_LINE> for n in iterator: <NEW_LINE> <INDENT> visited.append(n) <NEW_LINE> <DEDENT> self.assertEqual(visited, [self.g.ROOT, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"])
Many tests using the same tree which contains all the cases.
62599047d53ae8145f9197da
class Assessment(UserResource): <NEW_LINE> <INDENT> lead = models.OneToOneField(Lead, default=None, blank=True, null=True) <NEW_LINE> lead_group = models.OneToOneField(LeadGroup, default=None, blank=True, null=True) <NEW_LINE> metadata = JSONField(default=None, blank=True, null=True) <NEW_LINE> methodology = JSONField(default=None, blank=True, null=True) <NEW_LINE> summary = JSONField(default=None, blank=True, null=True) <NEW_LINE> score = JSONField(default=None, blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.lead) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if not self.lead and not self.lead_group: <NEW_LINE> <INDENT> raise ValidationError( 'Neither `lead` nor `lead_group` defined' ) <NEW_LINE> <DEDENT> if self.lead and self.lead_group: <NEW_LINE> <INDENT> raise ValidationError( 'Assessment cannot have both `lead` and `lead_group` defined' ) <NEW_LINE> <DEDENT> return super(Assessment, self).clean() <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.clean() <NEW_LINE> return super(Assessment, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_for(user): <NEW_LINE> <INDENT> return Assessment.objects.filter( models.Q(lead__project__members=user) | models.Q(lead__project__user_groups__members=user) | models.Q(lead_group__project__members=user) | models.Q(lead_group__project__user_groups__members=user) ).distinct() <NEW_LINE> <DEDENT> def can_get(self, user): <NEW_LINE> <INDENT> return ( (self.lead and self.lead.can_get(user)) or (self.lead_group and self.lead_group.can_get(user)) ) <NEW_LINE> <DEDENT> def can_modify(self, user): <NEW_LINE> <INDENT> return ( (self.lead and self.lead.can_modify(user)) or (self.lead_group and self.lead_group.can_modify(user)) )
Assesssment belonging to a lead
62599047d6c5a102081e3496
class BinaryPredicate(Predicate): <NEW_LINE> <INDENT> def __init__(self, label, pairs, kb, producer_pred=None): <NEW_LINE> <INDENT> Predicate.__init__(self, label, kb, producer_pred) <NEW_LINE> if not producer_pred: <NEW_LINE> <INDENT> self.input_var = Predicate._avar() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_var = producer_pred.output_var <NEW_LINE> <DEDENT> self.output_var = Predicate._avar() <NEW_LINE> if producer_pred: <NEW_LINE> <INDENT> prod_out_var = self.producer_predicate.output_var <NEW_LINE> potential_inputs = self.producer_predicate.domain[prod_out_var] <NEW_LINE> inputs = potential_inputs & kb.get_domains(label)[0] <NEW_LINE> outputs = kb.get_empty_domain() <NEW_LINE> for el1 in kb.bits_to_indices(inputs): <NEW_LINE> <INDENT> outputs |= pairs[el1] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> inputs, outputs = kb.get_domains(label) <NEW_LINE> <DEDENT> self.domain = {self.input_var: inputs, self.output_var: outputs}
A binary predicate.
6259904715baa7234946330b
class ShowFirewallRule(neutronv20.ShowCommand): <NEW_LINE> <INDENT> resource = 'firewall_rule' <NEW_LINE> log = logging.getLogger(__name__ + '.ShowFirewallRule')
Show information of a given firewall rule.
6259904745492302aabfd84c
class ITC03010801_InstallHost_Maintenance(BaseTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dm = super(self.__class__, self).setUp() <NEW_LINE> self.host_api = HostAPIs() <NEW_LINE> LogPrint().info('Pre-Test-1: Create Host "%s" in Cluster "%s".' % (self.dm.host_name, ModuleData.cluster_name)) <NEW_LINE> self.assertTrue(smart_create_host(self.dm.host_name, self.dm.xml_host_info)) <NEW_LINE> LogPrint().info("Pre-Test-2: Deactivate host '%s'." % self.dm.host_name) <NEW_LINE> self.host_api.deactiveHost(self.dm.host_name) <NEW_LINE> def is_host_maintenance(): <NEW_LINE> <INDENT> return self.host_api.getHostStatus(self.dm.host_name)=='maintenance' <NEW_LINE> <DEDENT> if wait_until(is_host_maintenance, 120, 5): <NEW_LINE> <INDENT> LogPrint().info("Pre-Test2-PASS: Deactive host '%s'SUCCESS." % self.dm.host_name) <NEW_LINE> self.flag = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LogPrint().error("Pre-Test2-FAIL: Deactive host '%s'FAILED." % self.dm.host_name) <NEW_LINE> self.flag = False <NEW_LINE> <DEDENT> self.assertTrue(self.flag) <NEW_LINE> <DEDENT> def test_InstallHost(self): <NEW_LINE> <INDENT> host_name = self.dm.host_name <NEW_LINE> def is_host_up(): <NEW_LINE> <INDENT> return self.host_api.getHostStatus(host_name)=='up' <NEW_LINE> <DEDENT> def is_host_install(): <NEW_LINE> <INDENT> return self.host_api.getHostStatus(host_name)=='installing' <NEW_LINE> <DEDENT> LogPrint().info("Test: Install host '%s' while in 'Maintenance' state." % host_name) <NEW_LINE> r = self.host_api.installHost(host_name, self.dm.xml_install_option) <NEW_LINE> if r['status_code'] == self.dm.expected_status_code_install_host: <NEW_LINE> <INDENT> if wait_until(is_host_install, 50, 5) and wait_until(is_host_up, 200, 5): <NEW_LINE> <INDENT> LogPrint().info("PASS: Install host '%s' SUCCESS." % host_name) <NEW_LINE> self.flag = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LogPrint().error("FAIL: The state of host '%s' is NOT 'installing' or 'up' when installing host.") <NEW_LINE> self.flag = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> LogPrint().error("FAIL: Returned status code '%s' is INCORRECT after installing host." % r['status_code']) <NEW_LINE> self.flag = False <NEW_LINE> <DEDENT> self.assertTrue(self.flag) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> host_name = self.dm.host_name <NEW_LINE> LogPrint().info("Delete host '%s'." % host_name) <NEW_LINE> self.assertTrue(smart_del_host(host_name, self.dm.xml_host_del_option))
@summary: ITC-03主机管理-01主机操作-08安装-01主机Maintenance状态
62599047379a373c97d9a3a5
class Solution: <NEW_LINE> <INDENT> def searchRange(self, root, k1, k2): <NEW_LINE> <INDENT> res = [] <NEW_LINE> self.helper(res, root, k1, k2) <NEW_LINE> return res <NEW_LINE> <DEDENT> def helper(self, res, root, k1, k2): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if root.val < k1: <NEW_LINE> <INDENT> self.helper(res, root.right, k1, k2) <NEW_LINE> <DEDENT> elif root.val > k2: <NEW_LINE> <INDENT> self.helper(res, root.left, k1, k2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.helper(res, root.left, k1, k2) <NEW_LINE> res.append(root.val) <NEW_LINE> self.helper(res, root.right, k1, k2)
@param root: param root: The root of the binary search tree @param k1: An integer @param k2: An integer @return: return: Return all keys that k1<=key<=k2 in ascending order
62599047711fe17d825e165b
class SubmittedThing (CloneableModelMixin, CacheClearingModel, ModelWithDataBlob, TimeStampedModel): <NEW_LINE> <INDENT> submitter = models.ForeignKey(User, related_name='things', null=True, blank=True) <NEW_LINE> dataset = models.ForeignKey('DataSet', related_name='things', blank=True) <NEW_LINE> visible = models.BooleanField(default=True, blank=True, db_index=True) <NEW_LINE> objects = SubmittedThingManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'sa_api_v2' <NEW_LINE> db_table = 'sa_api_submittedthing' <NEW_LINE> <DEDENT> def index_values(self, indexes=None): <NEW_LINE> <INDENT> if indexes is None: <NEW_LINE> <INDENT> indexes = self.dataset.indexes.all() <NEW_LINE> <DEDENT> if len(indexes) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = json.loads(self.data) <NEW_LINE> for index in indexes: <NEW_LINE> <INDENT> IndexedValue.objects.sync(self, index, data=data) <NEW_LINE> <DEDENT> <DEDENT> def get_clone_save_kwargs(self): <NEW_LINE> <INDENT> return {'silent': True, 'reindex': False, 'clear_cache': False} <NEW_LINE> <DEDENT> def save(self, silent=False, source='', reindex=True, *args, **kwargs): <NEW_LINE> <INDENT> silent = getattr(self, 'silent', silent) <NEW_LINE> source = getattr(self, 'source', source) <NEW_LINE> reindex = getattr(self, 'reindex', reindex) <NEW_LINE> is_new = (self.id == None) <NEW_LINE> ret = super(SubmittedThing, self).save(*args, **kwargs) <NEW_LINE> if reindex: <NEW_LINE> <INDENT> self.index_values() <NEW_LINE> <DEDENT> if not silent: <NEW_LINE> <INDENT> action = Action() <NEW_LINE> action.action = 'create' if is_new else 'update' <NEW_LINE> action.thing = self <NEW_LINE> action.source = source <NEW_LINE> action.save() <NEW_LINE> <DEDENT> return ret
A SubmittedThing generally comes from the end-user. It may be a place, a comment, a vote, etc.
6259904794891a1f408ba0b3
class Escape(ColorMixin, BackGroundColorMixin, ModifiersMixin, object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self._original_string = ''.join( [arg.encode('utf-8') if (not PY3 and isinstance(arg, unicode)) else str(arg) for arg in args] ) <NEW_LINE> self._styled_string = self._original_string <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> styled_string = self._styled_string <NEW_LINE> if isinstance(styled_string, bytes): <NEW_LINE> <INDENT> return styled_string.decode('utf8') <NEW_LINE> <DEDENT> return styled_string <NEW_LINE> <DEDENT> if PY3: <NEW_LINE> <INDENT> __str__ = __unicode__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self._styled_string <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other == self._styled_string <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return self._styled_string + other <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return other + self._styled_string <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._original_string) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return self._styled_string * other
Simple string like class to produce ansi-escaped strings
6259904729b78933be26aa80
class ConsumptionFilter(FilterBase): <NEW_LINE> <INDENT> def __init__( self, csv_path: str, category: str, indicator: str, frequency: TemporalFrequency): <NEW_LINE> <INDENT> super().__init__(csv_path=csv_path) <NEW_LINE> self.category = category <NEW_LINE> self.indicator = indicator <NEW_LINE> self.frequency = frequency <NEW_LINE> <DEDENT> def isValid(self, row: dict) -> bool: <NEW_LINE> <INDENT> if (ESTIMATE_KEY not in row or row[ESTIMATE_KEY] != ESTIMATE_VALUE): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (GEO_KEY not in row or row[GEO_KEY] != GEO_VALUE): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if PRICE_KEY not in row or row[PRICE_KEY] != PRICE_VALUE: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (VALUE_KEY not in row or SCALAR_KEY not in row or DATE_KEY not in row): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def getIndicator(self, _) -> str: <NEW_LINE> <INDENT> return self.indicator <NEW_LINE> <DEDENT> def getCategory(self, _) -> str: <NEW_LINE> <INDENT> return self.category <NEW_LINE> <DEDENT> def getFrequency(self, _) -> TemporalFrequency: <NEW_LINE> <INDENT> return self.frequency <NEW_LINE> <DEDENT> def getValue(self, row) -> int: <NEW_LINE> <INDENT> value = tryint(row[VALUE_KEY]) <NEW_LINE> multiplier = scalar_multiplier(row[SCALAR_KEY]) <NEW_LINE> return value * multiplier
Consumption Filter.
6259904782261d6c52730883
class Discriminator(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_channels=1, n_filters=16): <NEW_LINE> <INDENT> super(Discriminator, self).__init__() <NEW_LINE> ndf = n_filters <NEW_LINE> self.network = nn.Sequential( nn.Conv2d(input_channels, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid() ) <NEW_LINE> <DEDENT> def forward(self, inputs): <NEW_LINE> <INDENT> return self.network(inputs).squeeze()
Discriminator module for the GAN.
62599047d99f1b3c44d06a1b
class DataUpdateCoordinatorMixin: <NEW_LINE> <INDENT> async def async_read_data(self, module_id: str, data_id: str) -> list[str, bool]: <NEW_LINE> <INDENT> client = self._plenticore.client <NEW_LINE> if client is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> val = await client.get_setting_values(module_id, data_id) <NEW_LINE> <DEDENT> except PlenticoreApiException: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> async def async_write_data(self, module_id: str, value: dict[str, str]) -> bool: <NEW_LINE> <INDENT> client = self._plenticore.client <NEW_LINE> if client is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> await client.set_setting_values(module_id, value) <NEW_LINE> <DEDENT> except PlenticoreApiException: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Base implementation for read and write data.
6259904715baa7234946330c
class Assign(object): <NEW_LINE> <INDENT> def __init__(self, left_attribute, right_attribute=None, right=None, **kwargs): <NEW_LINE> <INDENT> if not right_attribute and not right: <NEW_LINE> <INDENT> raise ValueError('require argument: right_attribute or right') <NEW_LINE> <DEDENT> assert left_attribute is not None <NEW_LINE> self.left_attribute = left_attribute <NEW_LINE> self.right_attribute = right_attribute <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def assign(self, from_obj, to_obj): <NEW_LINE> <INDENT> if self.right is not None: <NEW_LINE> <INDENT> right = self.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> right = from_obj.get_data(self.right_attribute) <NEW_LINE> <DEDENT> to_obj.set_data(**{unicode(self.left_attribute): right})
Assigns a new value to an attribute. The source may be either a static value, or another attribute.
6259904721a7993f00c672e5
class SubmissionFlair: <NEW_LINE> <INDENT> def __init__(self, submission: "Submission"): <NEW_LINE> <INDENT> self.submission = submission <NEW_LINE> <DEDENT> def choices(self) -> List[Dict[str, Union[bool, list, str]]]: <NEW_LINE> <INDENT> url = API_PATH["flairselector"].format(subreddit=self.submission.subreddit) <NEW_LINE> return self.submission._reddit.post( url, data={"link": self.submission.fullname} )["choices"] <NEW_LINE> <DEDENT> def select(self, flair_template_id: str, text: Optional[str] = None): <NEW_LINE> <INDENT> data = { "flair_template_id": flair_template_id, "link": self.submission.fullname, "text": text, } <NEW_LINE> url = API_PATH["select_flair"].format(subreddit=self.submission.subreddit) <NEW_LINE> self.submission._reddit.post(url, data=data)
Provide a set of functions pertaining to Submission flair.
62599047d53ae8145f9197dc
class agilentMSOX4022A(agilent4000A): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__.setdefault('_instrument_id', 'MSO-X 4022A') <NEW_LINE> super(agilentMSOX4022A, self).__init__(*args, **kwargs) <NEW_LINE> self._analog_channel_count = 2 <NEW_LINE> self._digital_channel_count = 16 <NEW_LINE> self._channel_count = self._analog_channel_count + self._digital_channel_count <NEW_LINE> self._bandwidth = 200e6 <NEW_LINE> self._init_channels()
Agilent InfiniiVision MSOX4022A IVI oscilloscope driver
62599047d4950a0f3b111800
class Queensland(DstTzInfo): <NEW_LINE> <INDENT> zone = 'Australia/Queensland' <NEW_LINE> _utc_transition_times = [ d(1,1,1,0,0,0), d(1916,12,31,14,1,0), d(1917,3,24,15,0,0), d(1941,12,31,16,0,0), d(1942,3,28,15,0,0), d(1942,9,26,16,0,0), d(1943,3,27,15,0,0), d(1943,10,2,16,0,0), d(1944,3,25,15,0,0), d(1971,10,30,16,0,0), d(1972,2,26,16,0,0), d(1989,10,28,16,0,0), d(1990,3,3,16,0,0), d(1990,10,27,16,0,0), d(1991,3,2,16,0,0), d(1991,10,26,16,0,0), d(1992,2,29,16,0,0), ] <NEW_LINE> _transition_info = [ i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), i(39600,3600,'EST'), i(36000,0,'EST'), ]
Australia/Queensland timezone definition. See datetime.tzinfo for details
62599047b5575c28eb713687
class Config(dict): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Config, self).__init__() <NEW_LINE> <DEDENT> def __getattribute__(self, attr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Config, self).__getattribute__(attr) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return self.get(attr) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> self.__setitem__(attr, value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self, indent=2, sort_keys=True) <NEW_LINE> <DEDENT> def update(self, other, overwrite=True): <NEW_LINE> <INDENT> if not isinstance(other, dict): <NEW_LINE> <INDENT> raise ValueError("Config can only be updated with a dict") <NEW_LINE> <DEDENT> for key, value in other.items(): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> if key not in self: <NEW_LINE> <INDENT> self[key] = Config() <NEW_LINE> <DEDENT> if isinstance(self[key], Config): <NEW_LINE> <INDENT> self[key].update(value, overwrite) <NEW_LINE> <DEDENT> elif overwrite: <NEW_LINE> <INDENT> self[key] = Config() <NEW_LINE> self[key].update(value, overwrite) <NEW_LINE> <DEDENT> <DEDENT> elif key not in self or overwrite: <NEW_LINE> <INDENT> if str(value).lower() == "true": <NEW_LINE> <INDENT> self[key] = True <NEW_LINE> <DEDENT> elif str(value).lower() == "false": <NEW_LINE> <INDENT> self[key] = False <NEW_LINE> <DEDENT> elif value is not None: <NEW_LINE> <INDENT> self[key] = value
Holds all configuration information about the Client
62599047a79ad1619776b3fd
class EventTestMixin(object): <NEW_LINE> <INDENT> def setUp(self, tracker): <NEW_LINE> <INDENT> super(EventTestMixin, self).setUp() <NEW_LINE> self.tracker = tracker <NEW_LINE> patcher = patch(self.tracker) <NEW_LINE> self.mock_tracker = patcher.start() <NEW_LINE> self.addCleanup(patcher.stop) <NEW_LINE> <DEDENT> def assert_no_events_were_emitted(self): <NEW_LINE> <INDENT> self.assertFalse(self.mock_tracker.emit.called) <NEW_LINE> <DEDENT> def assert_event_emitted(self, event_name, **kwargs): <NEW_LINE> <INDENT> self.mock_tracker.emit.assert_any_call( event_name, kwargs ) <NEW_LINE> <DEDENT> def reset_tracker(self): <NEW_LINE> <INDENT> self.mock_tracker.reset_mock()
Generic mixin for verifying that events were emitted during a test.
6259904730c21e258be99b83
class Users(API): <NEW_LINE> <INDENT> def create(self, email, password): <NEW_LINE> <INDENT> data = {'email': email, 'password': password} <NEW_LINE> return self.client.post('/v2/users', data) <NEW_LINE> <DEDENT> def authenticate(self, email, password): <NEW_LINE> <INDENT> data = {'email': email, 'password': password} <NEW_LINE> return self.client.post('/v2/authenticate', data) <NEW_LINE> <DEDENT> def logout(self, access_token): <NEW_LINE> <INDENT> data = {'access_token': access_token} <NEW_LINE> return self.client.post('/v2/logout', data) <NEW_LINE> <DEDENT> def list(self): <NEW_LINE> <INDENT> return self.client.get('/v2/users', {'limit': DEFAULT_LIMIT}) <NEW_LINE> <DEDENT> def retrieve(self, uuid): <NEW_LINE> <INDENT> return self.client.get('/v2/users/%s'%uuid, {}) <NEW_LINE> <DEDENT> def edit(self, uuid, current_password, new_password): <NEW_LINE> <INDENT> data = { 'current_password': current_password, 'new_password': new_password } <NEW_LINE> return self.client.put('/v2/users/%s/password'%uuid, data) <NEW_LINE> <DEDENT> def delete(self, uuid, password): <NEW_LINE> <INDENT> data = {'password': password} <NEW_LINE> return self.client.delete('/v2/users/%s'%uuid, data) <NEW_LINE> <DEDENT> def delete_all(self): <NEW_LINE> <INDENT> return self.client.delete('/v2/users', {})
Users endpoints.
6259904729b78933be26aa81
class FullBeam(Obit.FullBeam): <NEW_LINE> <INDENT> def __init__(self, name="no_name", image=None, err=None) : <NEW_LINE> <INDENT> super(FullBeam, self).__init__() <NEW_LINE> Obit.CreateFullBeam(self.this, name, image, err) <NEW_LINE> self.myClass = myClass <NEW_LINE> <DEDENT> def __del__(self, DeleteFullBeam=_Obit.DeleteFullBeam): <NEW_LINE> <INDENT> if _Obit!=None: <NEW_LINE> <INDENT> DeleteFullBeam(self.this) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self,name,value): <NEW_LINE> <INDENT> if name == "me" : <NEW_LINE> <INDENT> if self.this!=None: <NEW_LINE> <INDENT> Obit.FullBeamUnref(Obit.FullBeam_Get_me(self.this)) <NEW_LINE> <DEDENT> Obit.FullBeam_Set_me(self.this,value) <NEW_LINE> return <NEW_LINE> <DEDENT> self.__dict__[name] = value <NEW_LINE> <DEDENT> def __getattr__(self,name): <NEW_LINE> <INDENT> if not isinstance(self, FullBeam): <NEW_LINE> <INDENT> return "Bogus dude "+str(self.__class__) <NEW_LINE> <DEDENT> if name == "me" : <NEW_LINE> <INDENT> return Obit.FullBeam_Get_me(self.this) <NEW_LINE> <DEDENT> raise AttributeError(name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if not isinstance(self, FullBeam): <NEW_LINE> <INDENT> return "Bogus dude "+str(self.__class__) <NEW_LINE> <DEDENT> return "<C FullBeam instance> " + Obit.FullBeamGetName(self.me) <NEW_LINE> <DEDENT> def Gain (self, dra, ddec, parAng, plane, err): <NEW_LINE> <INDENT> if not PIsA(self): <NEW_LINE> <INDENT> raise TypeError("self MUST be a Python Obit FullBeam") <NEW_LINE> <DEDENT> return Obit.FullBeamValue(self.me, dra, ddec, parAng, plane, err.me) <NEW_LINE> <DEDENT> def FindPlane(self, freq): <NEW_LINE> <INDENT> if not PIsA(self): <NEW_LINE> <INDENT> raise TypeError("self MUST be a Python Obit FullBeam") <NEW_LINE> <DEDENT> return Obit.FullBeamFindPlane(self.me, freq) <NEW_LINE> <DEDENT> def FullBeamIsA (self): <NEW_LINE> <INDENT> return Obit.FullBeamIsA(self.me)!=0
Python Obit FullBeam class This class provides values of the beam shape derived from an image Gains at specified offsets from the beam center at giv3en parallactic angles are interpolated from a Full Beam image. FullBeam Members with python interfaces:
62599047004d5f362081f9a5
class GetMessages(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self, gameid, since): <NEW_LINE> <INDENT> user = auth() <NEW_LINE> if user == None: <NEW_LINE> <INDENT> self.response.out.write(json.dumps({'error': 'No autheticated user'})) <NEW_LINE> return <NEW_LINE> <DEDENT> logging.debug("here") <NEW_LINE> since = int(since)/1000 <NEW_LINE> logging.debug(gameid) <NEW_LINE> q = MyMessage.gql("WHERE gameid = "+gameid) <NEW_LINE> logging.debug(q.count()) <NEW_LINE> results = q.fetch(20) <NEW_LINE> reply = [] <NEW_LINE> for result in results: <NEW_LINE> <INDENT> if time.mktime(result.time.timetuple()) > since: <NEW_LINE> <INDENT> reply.append(result.toDict()) <NEW_LINE> <DEDENT> <DEDENT> logging.debug(reply) <NEW_LINE> self.response.out.write(json.dumps(reply))
Messages are fetched by user using game id
6259904750485f2cf55dc305
class AddView(LoginRequiredMixin, generic.CreateView): <NEW_LINE> <INDENT> model = Issue <NEW_LINE> form_class = IssueCreateForm <NEW_LINE> login_url = 'lanve:signin' <NEW_LINE> success_url = reverse_lazy('lanve:list') <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> messages.success(self.request, 'Your issue was posted successfully') <NEW_LINE> issue = form.save(commit=False) <NEW_LINE> issue.contributor = self.request.user <NEW_LINE> issue.save() <NEW_LINE> response = super().form_valid(form) <NEW_LINE> return response
Create new issues View
62599047462c4b4f79dbcd7c
class setGlobalConfiguration_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.BOOL, 'success', None, None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.BOOL: <NEW_LINE> <INDENT> self.success = iprot.readBool(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('setGlobalConfiguration_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.BOOL, 0) <NEW_LINE> oprot.writeBool(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success
62599047d53ae8145f9197dd
@WordSplitter.register('just_spaces') <NEW_LINE> class JustSpacesWordSplitter(WordSplitter): <NEW_LINE> <INDENT> @overrides <NEW_LINE> def split_words(self, sentence: str) -> List[Token]: <NEW_LINE> <INDENT> return [Token(t) for t in sentence.split()]
A ``WordSplitter`` that assumes you've already done your own tokenization somehow and have separated the tokens by spaces. We just split the input string on whitespace and return the resulting list. We use a somewhat odd name here to avoid coming too close to the more commonly used ``SpacyWordSplitter``. Note that we use ``sentence.split()``, which means that the amount of whitespace between the tokens does not matter. This will never result in spaces being included as tokens.
62599047d99f1b3c44d06a1d
class ComputeDistanceMap(SEMLikeCommandLine): <NEW_LINE> <INDENT> input_spec = ComputeDistanceMapInputSpec <NEW_LINE> output_spec = ComputeDistanceMapOutputSpec <NEW_LINE> _cmd = " ComputeDistanceMap " <NEW_LINE> _outputs_filenames = {'distanceMap':'distanceMap.nii'}
title: ComputeDistanceMap category: Chest Imaging Platform.Toolkit.Processing description: This program computes a distance map from an input binary map. A donwsampling can be applied prior to the distance map computation to improve performance. The resulting distance map will by upsampled by the same amount before writing. version: 0.0.1 license: Slicer contributor: Applied Chest Imaging Laboratory, Brigham and women's hospital acknowledgements: This work is funded by the National Heart, Lung, And Blood Institute of the National Institutes of Health under Award Number R01HL116931. The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health.
625990473c8af77a43b688fc
class SIPpFailure(RuntimeError): <NEW_LINE> <INDENT> pass
SIPp commands failed
62599047507cdc57c63a611c
class TextProcessor: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TextProcessor, self).__init__() <NEW_LINE> self.TAG = "Text Processor" <NEW_LINE> print("Current class:", self.TAG)
TextProcessor creates text bundles in a video from text sources.
6259904776d4e153a661dc35
class POWER_SEQUENCER_OT_split_strips_under_cursor(bpy.types.Operator): <NEW_LINE> <INDENT> doc = { "name": doc_name(__qualname__), "demo": "https://i.imgur.com/ZyEd0jD.gif", "description": doc_description(__doc__), "shortcuts": [({"type": "K", "value": "PRESS"}, {}, "Cut All Strips Under Cursor")], "keymap": "Sequencer", } <NEW_LINE> bl_idname = doc_idname(__qualname__) <NEW_LINE> bl_label = doc["name"] <NEW_LINE> bl_description = doc_brief(doc["description"]) <NEW_LINE> bl_options = {"REGISTER", "UNDO"} <NEW_LINE> side: bpy.props.EnumProperty( items=[("LEFT", "", ""), ("RIGHT", "", "")], name="Side", default="LEFT", options={"HIDDEN"}, ) <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.sequences <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> frame, channel = get_mouse_frame_and_channel(context, event) <NEW_LINE> self.side = "LEFT" if frame < context.scene.frame_current else "RIGHT" <NEW_LINE> return self.execute(context) <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> deselect = True <NEW_LINE> for s in bpy.context.selected_sequences: <NEW_LINE> <INDENT> if s.frame_final_start <= context.scene.frame_current <= s.frame_final_end: <NEW_LINE> <INDENT> deselect = False <NEW_LINE> <DEDENT> <DEDENT> if deselect: <NEW_LINE> <INDENT> bpy.ops.sequencer.select_all(action="DESELECT") <NEW_LINE> <DEDENT> (context.selected_sequences or bpy.ops.power_sequencer.select_strips_under_cursor()) <NEW_LINE> return bpy.ops.sequencer.split(frame=context.scene.frame_current, side=self.side)
Splits all strips under cursor including muted strips, but excluding locked strips. Auto selects sequences under the time cursor when you don't have a selection
62599047b57a9660fecd2dfb
class Slide(Orderable): <NEW_LINE> <INDENT> homepage = models.ForeignKey(HomePage, related_name="slides") <NEW_LINE> image = FileField(verbose_name=_("Image"), upload_to=upload_to("theme.Slide.image", "slider"), format="Image", max_length=255, null=True, blank=True) <NEW_LINE> title = models.CharField(max_length=50, default="Slide")
A slide in a slider connected to a HomePage
62599047b830903b9686ee3a
class MAVLink_state_correction_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_STATE_CORRECTION <NEW_LINE> name = 'STATE_CORRECTION' <NEW_LINE> fieldnames = ['xErr', 'yErr', 'zErr', 'rollErr', 'pitchErr', 'yawErr', 'vxErr', 'vyErr', 'vzErr'] <NEW_LINE> ordered_fieldnames = [ 'xErr', 'yErr', 'zErr', 'rollErr', 'pitchErr', 'yawErr', 'vxErr', 'vyErr', 'vzErr' ] <NEW_LINE> format = '>fffffffff' <NEW_LINE> native_format = bytearray('>fffffffff', 'ascii') <NEW_LINE> orders = [0, 1, 2, 3, 4, 5, 6, 7, 8] <NEW_LINE> lengths = [1, 1, 1, 1, 1, 1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0, 0, 0, 0, 0, 0] <NEW_LINE> crc_extra = 130 <NEW_LINE> def __init__(self, xErr, yErr, zErr, rollErr, pitchErr, yawErr, vxErr, vyErr, vzErr): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_state_correction_message.id, MAVLink_state_correction_message.name) <NEW_LINE> self._fieldnames = MAVLink_state_correction_message.fieldnames <NEW_LINE> self.xErr = xErr <NEW_LINE> self.yErr = yErr <NEW_LINE> self.zErr = zErr <NEW_LINE> self.rollErr = rollErr <NEW_LINE> self.pitchErr = pitchErr <NEW_LINE> self.yawErr = yawErr <NEW_LINE> self.vxErr = vxErr <NEW_LINE> self.vyErr = vyErr <NEW_LINE> self.vzErr = vzErr <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 130, struct.pack('>fffffffff', self.xErr, self.yErr, self.zErr, self.rollErr, self.pitchErr, self.yawErr, self.vxErr, self.vyErr, self.vzErr))
Corrects the systems state by adding an error correction term to the position and velocity, and by rotating the attitude by a correction angle.
62599047097d151d1a2c23eb
class WorkspaceViewerServerPlanar( TrajectoryOptimizationViewer, WorkspaceViewerServer): <NEW_LINE> <INDENT> def __init__(self, workspace, trajectory, use_gl=True, scale=700.): <NEW_LINE> <INDENT> WorkspaceViewerServer.__init__(self, workspace, trajectory) <NEW_LINE> TrajectoryOptimizationViewer.__init__( self, None, draw=False, draw_gradient=True, use_3d=False, use_gl=use_gl) <NEW_LINE> self.init_viewer(workspace, scale=scale) <NEW_LINE> <DEDENT> def initialize_viewer(self, problem, trajectory): <NEW_LINE> <INDENT> self.objective = problem <NEW_LINE> self.draw_robot = False <NEW_LINE> if hasattr(self.objective, 'robot'): <NEW_LINE> <INDENT> self.draw_robot = True <NEW_LINE> self.robot_verticies = self.objective.robot.shape <NEW_LINE> <DEDENT> self.viewer.background_matrix_eval = False <NEW_LINE> self.viewer.save_images = True <NEW_LINE> self.viewer.workspace_id += 1 <NEW_LINE> self.viewer.image_id = 0 <NEW_LINE> self.goal_manifold = False <NEW_LINE> self.reset_objective() <NEW_LINE> self.viewer.draw_ws_obstacles() <NEW_LINE> self.q_init = trajectory.initial_configuration() <NEW_LINE> self.active_shape = (self.objective.n * (self.objective.T + 1), ) <NEW_LINE> self._current_trajectory = trajectory <NEW_LINE> self.update_viewer() <NEW_LINE> self.draw(trajectory) <NEW_LINE> <DEDENT> def draw_path(self, path, radius=.01, color=(0, 0, 1), linewidth=7): <NEW_LINE> <INDENT> for k, q in enumerate(path): <NEW_LINE> <INDENT> self.viewer.draw_ws_circle( radius, origin=q, color=color, filled=True) <NEW_LINE> if k > 0: <NEW_LINE> <INDENT> self.viewer.draw_ws_line( [q, path[k - 1]], color=color, linewidth=linewidth) <NEW_LINE> <DEDENT> <DEDENT> self.viewer.show() <NEW_LINE> <DEDENT> def update_viewer(self): <NEW_LINE> <INDENT> if self.q_goal is not None: <NEW_LINE> <INDENT> self.draw_configuration(self.q_goal, (1, 0, 1)) <NEW_LINE> <DEDENT> if self._current_trajectory is not None: <NEW_LINE> <INDENT> self.draw(self._current_trajectory) <NEW_LINE> if self.goal_manifold: <NEW_LINE> <INDENT> self.viewer.draw_ws_circle( self.objective.goal_manifold.radius, self.objective.goal_manifold.origin, color=(1, 0, 0)) <NEW_LINE> <DEDENT> <DEDENT> if self.callback: <NEW_LINE> <INDENT> self.callback(self.viewer)
Workspace display based on pyglet backend
62599047d53ae8145f9197df
class _DictAccessor (object): <NEW_LINE> <INDENT> def __init__ (self,namespace): <NEW_LINE> <INDENT> object.__setattr__(self,'namespace',namespace); <NEW_LINE> <DEDENT> def __call__ (self,name,default=""): <NEW_LINE> <INDENT> if isinstance(default,str): <NEW_LINE> <INDENT> default = interpolate(default,inspect.currentframe().f_back); <NEW_LINE> <DEDENT> return object.__getattribute__(self,'namespace').get(name,default); <NEW_LINE> <DEDENT> def __getattr__ (self,name,default=""): <NEW_LINE> <INDENT> if isinstance(default,str): <NEW_LINE> <INDENT> default = interpolate(default,inspect.currentframe().f_back); <NEW_LINE> <DEDENT> return object.__getattribute__(self,'namespace').get(name,default); <NEW_LINE> <DEDENT> def __setattr__ (self,name,value): <NEW_LINE> <INDENT> object.__getattribute__(self,'namespace')[name] = value; <NEW_LINE> <DEDENT> def __contains__ (self,name): <NEW_LINE> <INDENT> return name in object.__getattribute__(self,'namespace');
Helper class that maps dicts to attributes
62599047e64d504609df9d90
class VSEQFQuickTagsClear(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = 'vseqf.quicktags_clear' <NEW_LINE> bl_label = 'VSEQF Quick Tags Clear' <NEW_LINE> bl_description = 'Clear all tags on all selected sequences' <NEW_LINE> mode: bpy.props.StringProperty('selected') <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> if self.mode == 'selected': <NEW_LINE> <INDENT> sequences = timeline.current_selected(context) <NEW_LINE> if not sequences: <NEW_LINE> <INDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> bpy.ops.ed.undo_push() <NEW_LINE> for sequence in sequences: <NEW_LINE> <INDENT> sequence.tags.clear() <NEW_LINE> <DEDENT> populate_selected_tags() <NEW_LINE> populate_tags() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sequence = timeline.current_active(context) <NEW_LINE> if not sequence: <NEW_LINE> <INDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> bpy.ops.ed.undo_push() <NEW_LINE> sequence.tags.clear() <NEW_LINE> populate_tags() <NEW_LINE> <DEDENT> return{'FINISHED'}
Clears all tags on the selected and active sequences
6259904710dbd63aa1c71f5a
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.qValuelist = {} <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> if(state, action) not in self.qValuelist: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self.qValuelist[(state, action)] <NEW_LINE> return value <NEW_LINE> <DEDENT> <DEDENT> def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> actions = self.getLegalActions(state) <NEW_LINE> if len(actions) == 0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> maxVal = -9999.9 <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> qval = self.getQValue(state, action) <NEW_LINE> if qval > maxVal: <NEW_LINE> <INDENT> maxVal = qval <NEW_LINE> <DEDENT> <DEDENT> return maxVal <NEW_LINE> <DEDENT> def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> actions = self.getLegalActions(state) <NEW_LINE> if len(actions) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> maxVal = -9999.9 <NEW_LINE> bestAction = None <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> qval = self.getQValue(state, action) <NEW_LINE> if qval > maxVal: <NEW_LINE> <INDENT> bestAction = action <NEW_LINE> maxVal = qval <NEW_LINE> <DEDENT> <DEDENT> return bestAction <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> if len(legalActions) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if flipCoin(self.epsilon): <NEW_LINE> <INDENT> action = random.choice(legalActions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> if(state, action) not in self.qValuelist: <NEW_LINE> <INDENT> self.qValuelist[(state, action)] = 0.0 <NEW_LINE> <DEDENT> qSdashA = self.computeValueFromQValues(nextState) <NEW_LINE> sample = reward + (self.discount*qSdashA) <NEW_LINE> currvalue = self.qValuelist[(state,action)] <NEW_LINE> qsa = currvalue + (self.alpha*(sample - currvalue)) <NEW_LINE> self.qValuelist[(state, action)] = qsa <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.computeValueFromQValues(state)
Q-Learning Agent Functions you should fill in: - computeValueFromQValues - computeActionFromQValues - getQValue - getAction - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62599047435de62698e9d185
class Plugin(DecoderPlugin): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super().__init__('URL', "Thomas Engel", ["urllib"], context) <NEW_LINE> <DEDENT> def run(self, text): <NEW_LINE> <INDENT> import urllib.parse <NEW_LINE> return urllib.parse.unquote(text) <NEW_LINE> <DEDENT> def can_decode_input(self, input): <NEW_LINE> <INDENT> if input and "+" not in input: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.run(input) != input <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return False
Decodes an URL. Example: Input: abcdefghijklmnopqrstuvwxyz \ %0A%5E%C2%B0%21%22%C2%A7%24%25%26/%28%29%3D%3F%C2%B4%60%3C%3E%7C%20%2C.-%3B%3A_%23%2B%27%2A%7E%0A \ 0123456789 Output: abcdefghijklmnopqrstuvwxyz ^°!"§$%&/()=?´`<>| ,.-;:_#+'*~ 0123456789
6259904726068e7796d4dcc7
class Order(Base): <NEW_LINE> <INDENT> __tablename__ = 'order' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> order_num = Column(Integer) <NEW_LINE> day = Column(String) <NEW_LINE> date = Column(String) <NEW_LINE> payment = Column(String) <NEW_LINE> restaurant = Column(String) <NEW_LINE> address = Column(String) <NEW_LINE> customer = Column(String) <NEW_LINE> delivery_time = Column(String) <NEW_LINE> pickup_time = Column(String) <NEW_LINE> time_delivered = Column(String) <NEW_LINE> subtotal = Column(Float) <NEW_LINE> tax = Column(Float) <NEW_LINE> delivery_charge = Column(Float) <NEW_LINE> tip = Column(Float) <NEW_LINE> total = Column(Float)
Database model for Order data
6259904763b5f9789fe864ed
class Answer(): <NEW_LINE> <INDENT> def __init__(self, answer_string='', comment='', is_correct=False): <NEW_LINE> <INDENT> assert answer_string, 'Answer Object has to have a description/entry!' <NEW_LINE> self.answer_string = answer_string <NEW_LINE> self.comment = comment <NEW_LINE> self.is_correct = is_correct <NEW_LINE> <DEDENT> def check_if_correct(self): <NEW_LINE> <INDENT> return self.is_correct <NEW_LINE> <DEDENT> def edit(self, entry, new_value): <NEW_LINE> <INDENT> if entry == 'answer_string': <NEW_LINE> <INDENT> assert (new_value and type(new_value) == str), 'The new entry for the answer_string must be string of len > 0.' <NEW_LINE> self.answer_string = new_value <NEW_LINE> <DEDENT> elif entry == 'comment': <NEW_LINE> <INDENT> assert (new_value and type(new_value) == str), 'The new entry for comments must be string of len > 0.' <NEW_LINE> self.comment = new_value <NEW_LINE> <DEDENT> elif entry == 'is_correct': <NEW_LINE> <INDENT> assert type(new_value) == bool, 'The new value for is_correct must be bool' <NEW_LINE> self.is_correct = new_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('The entry {} is not in possible answer fields [answer_string, comment, is_correct]'.format(entry)) <NEW_LINE> <DEDENT> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = {} <NEW_LINE> config['answer_string'] = self.answer_string <NEW_LINE> config['comment'] = self.comment <NEW_LINE> config['is_correct'] = self.is_correct <NEW_LINE> return config <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.answer_string + '\n'
Impl. of an Answer; check if setting of answer properties is valid; store, if answer has a comment (and handle printing); store, if answer is correct answer
625990473cc13d1c6d466ab7
class RevoluteJoint(Joint): <NEW_LINE> <INDENT> def set_velocity(self, amount): <NEW_LINE> <INDENT> self._set_angular_velocity(amount)
Es un tipo de unión que realiza movimientos de rotación con un grado de libertad.
625990478a349b6b436875cd
class income_and_ln_residential_units(Variable): <NEW_LINE> <INDENT> _return_type="float32" <NEW_LINE> parcel_residential_units = "residential_units" <NEW_LINE> hh_income = "income" <NEW_LINE> def dependencies(self): <NEW_LINE> <INDENT> return ["parcel_ln_residential_units = ln(psrc.parcel.residential_units)", attribute_label("household", self.hh_income)] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> return self.get_dataset().multiply(self.hh_income, "parcel_ln_residential_units")
income * ln_residential_units
625990478a43f66fc4bf3516
class MongoDBCredentials(BaseCredentials): <NEW_LINE> <INDENT> def __init__(self, username=None, password=None, source=None, mechanism=None, ssl_obj=None): <NEW_LINE> <INDENT> self.auth_username = username <NEW_LINE> self.auth_password = password <NEW_LINE> self.auth_source = source <NEW_LINE> self.auth_mechanism = mechanism <NEW_LINE> self.ssl_enabled = False <NEW_LINE> self.auth_ssl = ssl_obj <NEW_LINE> self.check_credentials() <NEW_LINE> <DEDENT> @property <NEW_LINE> def username(self): <NEW_LINE> <INDENT> return self.auth_username <NEW_LINE> <DEDENT> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return self.auth_password <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self.auth_source <NEW_LINE> <DEDENT> @property <NEW_LINE> def mechanism(self): <NEW_LINE> <INDENT> return self.auth_mechanism <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_ssl_enabled(self): <NEW_LINE> <INDENT> return self.ssl_enabled <NEW_LINE> <DEDENT> @property <NEW_LINE> def ssl_detail(self): <NEW_LINE> <INDENT> return self.auth_ssl <NEW_LINE> <DEDENT> def check_credentials(self): <NEW_LINE> <INDENT> if self.ssl_detail: <NEW_LINE> <INDENT> if not isinstance(self.ssl_detail, MongoDBSSLCredentials): <NEW_LINE> <INDENT> raise InvalidCredentials( 'SSL is not an instance of MongoDBSSLCredentials.') <NEW_LINE> <DEDENT> self.ssl_enabled = True
MongoDB Credentials Provider
625990471f5feb6acb163f77
class SwimFishModel: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.fish = Fish((209, 95, 238), 60, 50, 200, 450) <NEW_LINE> self.monsters = [] <NEW_LINE> self.choices = ['images/octopus1_png.png', 'images/crab1.png', 'images/jellyfish.png', 'images/shark.png', 'images/stingray.png']
Encodes the game state
62599047d7e4931a7ef3d3f7
class WordFrequencyExtractor: <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> def fit(self, text): <NEW_LINE> <INDENT> text = ''.join( [c if c in string.ascii_letters or c.isspace() or c in string.digits else '' for c in text]) <NEW_LINE> words = find_word_count(text) <NEW_LINE> most_common = words.most_common() <NEW_LINE> most_common.sort(key=lambda x: (x[1], x[0]), reverse=True) <NEW_LINE> most_common = [key for (key, value) in most_common[0:self.size]] <NEW_LINE> if len(most_common) != self.size: <NEW_LINE> <INDENT> raise RuntimeError( 'Could not find ' + str(self.size) + ' different grams.') <NEW_LINE> <DEDENT> self.words = most_common <NEW_LINE> <DEDENT> def extract(self, text): <NEW_LINE> <INDENT> text = ''.join( [c if c in string.ascii_letters or c.isspace() or c in string.digits else '' for c in text]) <NEW_LINE> return find_word_frequencies(text, self.words) <NEW_LINE> <DEDENT> def chosen_features(self): <NEW_LINE> <INDENT> human_readable = [] <NEW_LINE> for feature in self.words: <NEW_LINE> <INDENT> human_readable.append('word-1-gram "' + feature + '"') <NEW_LINE> <DEDENT> return human_readable
Extract word frequencies from a text. The class is initialized with number of most frequent words to use. After the feature extractor has been created it has to be fitted. To fit it give the text to fit to. The fitting text is used to identify the most common words. When features are then extracted from another text the most common words from the fitting process is the ones frequencies are computed for. Both the fitting text and the extraction text is preprocessed by removing all special characters from them before the words are found. Attributes: size (int): Number of most frequent words to compute frequencies for. words (list): List of most common words in the fitting text.
62599047d10714528d69f04e
class Person: <NEW_LINE> <INDENT> def __init__(self, name, eyecolor, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.eyecolor = eyecolor <NEW_LINE> self.age = age
This class eloborates about the Person
625990473617ad0b5ee074be
class SharedEbs(Ebs): <NEW_LINE> <INDENT> def __init__( self, mount_dir: str, name: str, kms_key_id: str = None, snapshot_id: str = None, volume_id: str = None, raid: Raid = None, deletion_policy: str = None, **kwargs, ): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.kms_key_id = Resource.init_param(kms_key_id) <NEW_LINE> self.mount_dir = Resource.init_param(mount_dir) <NEW_LINE> self.name = Resource.init_param(name) <NEW_LINE> self.shared_storage_type = SharedStorageType.RAID if raid else SharedStorageType.EBS <NEW_LINE> self.snapshot_id = Resource.init_param(snapshot_id) <NEW_LINE> self.volume_id = Resource.init_param(volume_id) <NEW_LINE> self.raid = raid <NEW_LINE> self.deletion_policy = Resource.init_param(deletion_policy, default="Delete") <NEW_LINE> <DEDENT> def _register_validators(self): <NEW_LINE> <INDENT> super()._register_validators() <NEW_LINE> self._register_validator(SharedStorageNameValidator, name=self.name) <NEW_LINE> if self.kms_key_id: <NEW_LINE> <INDENT> self._register_validator(KmsKeyValidator, kms_key_id=self.kms_key_id) <NEW_LINE> self._register_validator(KmsKeyIdEncryptedValidator, kms_key_id=self.kms_key_id, encrypted=self.encrypted) <NEW_LINE> <DEDENT> self._register_validator(SharedEbsVolumeIdValidator, volume_id=self.volume_id) <NEW_LINE> self._register_validator(EbsVolumeSizeSnapshotValidator, snapshot_id=self.snapshot_id, volume_size=self.size)
Represent a shared EBS, inherits from both _SharedStorage and Ebs classes.
6259904721a7993f00c672eb
class SenMLDocument(object): <NEW_LINE> <INDENT> measurement_factory = SenMLMeasurement <NEW_LINE> def __init__(self, measurements=None, *args, base=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.measurements = measurements <NEW_LINE> self.base = base <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, json_data): <NEW_LINE> <INDENT> base = cls.measurement_factory.base_from_json(json_data[0]) <NEW_LINE> measurements = [cls.measurement_factory.from_json(item) for item in json_data] <NEW_LINE> obj = cls(base=base, measurements=measurements) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> first = { 'bver': 5, } <NEW_LINE> if self.base: <NEW_LINE> <INDENT> base = self.base <NEW_LINE> if base.name is not None: <NEW_LINE> <INDENT> first['bn'] = str(base.name) <NEW_LINE> <DEDENT> if base.time is not None: <NEW_LINE> <INDENT> first['bt'] = float(base.time) <NEW_LINE> <DEDENT> if base.unit is not None: <NEW_LINE> <INDENT> first['bu'] = str(base.unit) <NEW_LINE> <DEDENT> if base.value is not None: <NEW_LINE> <INDENT> first['bv'] = float(base.value) <NEW_LINE> <DEDENT> <DEDENT> if self.measurements: <NEW_LINE> <INDENT> first.update(self.measurements[0].to_json()) <NEW_LINE> ret = [first] <NEW_LINE> ret.extend([item.to_json() for item in self.measurements[1:]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = [] <NEW_LINE> <DEDENT> return ret
A collection of SenMLMeasurement data points
62599047cad5886f8bdc5a3f
class OkonomibelopValidator(BaseValidator): <NEW_LINE> <INDENT> def validate_put_fields(self): <NEW_LINE> <INDENT> self.validate_is_positive_integer('belop', 'Beløp', requires_value=False) <NEW_LINE> return self
Validator klasse for Okonomibelop
62599047d53ae8145f9197e2
class SteadyState(Filter): <NEW_LINE> <INDENT> inputs = Types(('values', list, list, (int, float))) <NEW_LINE> outputs = Types(('values', list, list, (int, float))) <NEW_LINE> def __init__(self, k, threshold): <NEW_LINE> <INDENT> super(SteadyState, self).__init__() <NEW_LINE> self.threshold = threshold <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def _run(self, **kwargs): <NEW_LINE> <INDENT> xss = kwargs['values'] <NEW_LINE> for xs in xss: <NEW_LINE> <INDENT> for i in range(0, len(xs) - self.k): <NEW_LINE> <INDENT> if stats.coefficient_of_variation(xs[i:self.k + i]) < self.threshold: <NEW_LINE> <INDENT> self.out['values'].append(xs[i:self.k + i]) <NEW_LINE> break
Determines for each invocation the iteration where steady-state performance is reached and suppose that we want to retain ``k`` measurements per invocation. I.e. once the coefficient of variation of the ``k`` iterations falls below ``threshold`` (typically 0.01 or 0.02). Inputs: - ``values``: 2d list of measurements Outputs: - ``values``: 2d list of steady-state iterations
6259904750485f2cf55dc30a
class Column(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_value(self, n): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_value(self, n, item): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_value(self, item): <NEW_LINE> <INDENT> pass
Class representing a column
6259904723e79379d538d880
class Answer: <NEW_LINE> <INDENT> question = Question() <NEW_LINE> answers = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.question = Question() <NEW_LINE> <DEDENT> def parsejson(self,immutableDict): <NEW_LINE> <INDENT> self.answers = immutableDict.getlist(self.question.id)
This Object will be generated by connecting server based on the json sent in by frontend This Object will be sent to DNA DNA will return a Question Object & A list of data
6259904745492302aabfd854
class TestPageObject(unittest2.TestCase): <NEW_LINE> <INDENT> driver = None <NEW_LINE> def tearDown(self): <NEW_LINE> <INDENT> do_and_ignore(lambda: WTF_WEBDRIVER_MANAGER.close_driver()) <NEW_LINE> <DEDENT> def test_createPage_createsPageFromFactory(self): <NEW_LINE> <INDENT> config_reader = mock() <NEW_LINE> when(config_reader).get( "selenium.take_reference_screenshot", False).thenReturn(False) <NEW_LINE> self.driver = WTF_WEBDRIVER_MANAGER.new_driver( "TestPageObject.test_createPage_createsPageFromFactory") <NEW_LINE> self.driver.get("http://www.google.com") <NEW_LINE> google = SearchPage.create_page( self.driver, config_reader=config_reader) <NEW_LINE> self.assertTrue(type(google) == GoogleSearch) <NEW_LINE> self.driver.get("http://www.yahoo.com") <NEW_LINE> yahoo = SearchPage.create_page( self.driver, config_reader=config_reader) <NEW_LINE> self.assertTrue(type(yahoo) == YahooSearch) <NEW_LINE> <DEDENT> def test_validatePage_GetsCalledDuringInit(self): <NEW_LINE> <INDENT> config_reader = mock(ConfigReader) <NEW_LINE> when(config_reader).get( "selenium.take_reference_screenshot", False).thenReturn(False) <NEW_LINE> driver = mock(WebDriver) <NEW_LINE> when(driver).get("http://www.yahoo.com").thenReturn(None) <NEW_LINE> when(driver).current_url = "http://www.yahoo.com" <NEW_LINE> driver.get("http://www.yahoo.com") <NEW_LINE> try: <NEW_LINE> <INDENT> GoogleTestPageObj(driver, config_reader=config_reader) <NEW_LINE> self.fail("Should of thrown exception.") <NEW_LINE> <DEDENT> except InvalidPageError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.fail( "Should throw an InvalidPageError, thrown was: " + str(type(e))) <NEW_LINE> <DEDENT> when(driver).get("http://www.google.com").thenReturn(None) <NEW_LINE> driver.current_url = "http://www.google.com" <NEW_LINE> element = mock(WebElement) <NEW_LINE> when(driver).find_element_by_name("q").thenReturn(element) <NEW_LINE> driver.get("http://www.google.com") <NEW_LINE> google_page = GoogleTestPageObj(driver, config_reader=config_reader) <NEW_LINE> google_page.enter_query("hello world") <NEW_LINE> driver.close() <NEW_LINE> <DEDENT> def test_handle_validate_not_implemented(self): <NEW_LINE> <INDENT> driver = mock(WebDriver) <NEW_LINE> self.assertRaises(TypeError, ValidateNotImplementedPageObject, driver)
Unit test of the PageObject Class
6259904726068e7796d4dcc9
class GMMConv(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, dim, bias=True): <NEW_LINE> <INDENT> super(GMMConv, self).__init__() <NEW_LINE> self.in_channels = in_channels <NEW_LINE> self.out_channels = out_channels <NEW_LINE> self.dim = dim <NEW_LINE> self.mu = Parameter(in_channels, dim) <NEW_LINE> self.sigma = Parameter(in_channels, dim) <NEW_LINE> self.lin = torch.nn.Linear(in_channels, out_channels, bias=bias) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> size = self.in_channels <NEW_LINE> uniform(size, self.mu) <NEW_LINE> uniform(size, self.cov) <NEW_LINE> reset(self.lin) <NEW_LINE> <DEDENT> def forward(self, x, edge_index, pseudo): <NEW_LINE> <INDENT> edge_index, _ = remove_self_loops(edge_index) <NEW_LINE> edge_index = add_self_loops(edge_index, num_nodes=x.size(0)) <NEW_LINE> x = x.unsqueeze(-1) if x.dim() == 1 else x <NEW_LINE> pseudo = pseudo.unsqueeze(-1) if pseudo.dim() == 1 else pseudo <NEW_LINE> row, col = edge_index <NEW_LINE> F, (E, D) = x.size(0), pseudo.size() <NEW_LINE> gaussian = -0.5 * (pseudo.view(E, 1, D) - self.mu.view(1, F, D))**2 <NEW_LINE> gaussian = torch.exp(gaussian / (1e-14 + self.sigma.view(1, F, D)**2)) <NEW_LINE> gaussian = gaussian.prod(dim=-1) <NEW_LINE> gaussian_mean = scatter_add(gaussian, row, dim=0, dim_size=x.size(0)) <NEW_LINE> gaussian = gaussian / (1e-14 + gaussian_mean[row]).view(E, F) <NEW_LINE> out = scatter_add(x[col] * gaussian, row, dim=0, dim_size=x.size(0)) <NEW_LINE> out = self.lin(out) <NEW_LINE> return out <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}({}, {})'.format(self.__class__.__name__, self.in_channels, self.out_channels)
The gaussian mixture model convolutional operator from the `"Geometric Deep Learning on Graphs and Manifolds using Mixture Model CNNs" <https://arxiv.org/abs/1611.08402>`_ paper .. math:: \mathbf{x}^{\prime}_i = \mathbf{\Theta} \cdot \sum_{j \in \mathcal{N}(i) \cup \{ i \}} w(\mathbf{e}_{i,j}) \odot \mathbf{x}_j, where .. math:: w_m(\mathbf{e}) = \exp \left( -\frac{1}{2} {\left( \mathbf{e} - \mathbf{\mu}_m \right)}^{\top} \Sigma_m^{-1} \left( \mathbf{e} - \mathbf{\mu}_m \right) \right) with trainable mean vector :math:`\mathbf{\mu}_m` and diagonal covariance matrix :math:`\mathbf{\Sigma}_m` for each input channel :math:`m`. Args: in_channels (int): Size of each input sample. out_channels (int): Size of each output sample. dim (int): Pseudo-coordinate dimensionality. bias (bool, optional): If set to :obj:`False`, the layer will not learn an additive bias. (default: :obj:`True`)
6259904724f1403a9268628e