code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Session(Base): <NEW_LINE> <INDENT> __tablename__ = 'sessions' <NEW_LINE> id = Column(UUID, primary_key=True, nullable=False, default=uuid.uuid4) <NEW_LINE> authenticated = Column(Boolean, default=False, nullable=False) <NEW_LINE> groups = Column(JSONEncodedValue) <NEW_LINE> last_request_at = Column(DateTime, nullable=False, default=datetime.datetime.now()) <NEW_LINE> last_request_uri = Column(Text, nullable=False) <NEW_LINE> profile = Column(JSONEncodedValue) <NEW_LINE> remote_ip = Column(IPAddress, nullable=False) <NEW_LINE> started_at = Column(DateTime, nullable=False, default=datetime.datetime.now()) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Session %s (%s)>' % (self.id, self.remote_ip)
Define the mapper for carrying session data
62599049d53ae8145f91981d
class GetAudioView(MethodView): <NEW_LINE> <INDENT> def get(self, audioFileType, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if audioFileType == "song": <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> songs = Song.objects.all() <NEW_LINE> return make_response(json.loads(json_util.dumps(songs.to_json())), 200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = AudioController.get_song(id) <NEW_LINE> return make_response(json.loads(json_util.dumps(response)), 200) <NEW_LINE> <DEDENT> <DEDENT> elif audioFileType == "podcast": <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> podcasts = Podcast.objects.all() <NEW_LINE> return make_response(json.loads(json_util.dumps(podcasts.to_json())), 200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = AudioController.get_podcast(id) <NEW_LINE> return make_response(json.loads(json_util.dumps(response)), 200) <NEW_LINE> <DEDENT> <DEDENT> elif audioFileType == "audiobook": <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> audiobooks = AudioBook.objects.all() <NEW_LINE> return make_response(json.loads(json_util.dumps(audiobooks.to_json())), 200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = AudioController.get_audiobook(id) <NEW_LINE> return make_response(json.loads(json_util.dumps(response)), 200) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return make_response(jsonify({"error": "Bad Request"}), 400) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return make_response(jsonify({"error": "Internal Server Error"}), 500)
Returns an audio(podcast, song or audiobook) based on audioFileType and id
625990498da39b475be045ae
class TestBasic2(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.a = 1 <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del self.a <NEW_LINE> <DEDENT> def test_basic1(self): <NEW_LINE> <INDENT> self.assertNotEqual(self.a, 2) <NEW_LINE> <DEDENT> def test_basic2(self): <NEW_LINE> <INDENT> assert self.a != 2 <NEW_LINE> <DEDENT> def test_fail(self): <NEW_LINE> <INDENT> assert self.a == 2
Show setup and teardown
625990498e05c05ec3f6f839
class PoolSenseEntity(CoordinatorEntity): <NEW_LINE> <INDENT> _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} <NEW_LINE> def __init__(self, coordinator, email, description: EntityDescription): <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self.entity_description = description <NEW_LINE> self._attr_name = f"PoolSense {description.name}" <NEW_LINE> self._attr_unique_id = f"{email}-{description.key}"
Implements a common class elements representing the PoolSense component.
6259904916aa5153ce4018ab
class PayoffSimple: <NEW_LINE> <INDENT> def __init__(self, strike, expiry, type, size): <NEW_LINE> <INDENT> if not isinstance(expiry, date): raise TypeError ("bad option expiration: must be represented as a 'datetime.date'") <NEW_LINE> if type.upper() not in ["C", "P"]: raise ValueError("bad option type: must be 'C' / 'P'") <NEW_LINE> self.strike = strike <NEW_LINE> self.expiry = expiry <NEW_LINE> self.type = type.upper() <NEW_LINE> self.size = size <NEW_LINE> <DEDENT> def intrinsic_value(self, spot): <NEW_LINE> <INDENT> if self.type == 'C': return self.size * (spot - self.strike) if spot > self.strike else 0.0 <NEW_LINE> if self.type == 'P': return self.size * (self.strike - spot) if spot < self.strike else 0.0 <NEW_LINE> <DEDENT> def intrinsic_values(self, spots): <NEW_LINE> <INDENT> strikes = self.strike * np.ones(spots.shape) <NEW_LINE> zeroes = np.zeros(spots.shape) <NEW_LINE> if self.type == 'C': return self.size * np.maximum(spots - strikes, zeroes) <NEW_LINE> if self.type == 'P': return self.size * np.maximum(strikes - spots, zeroes) <NEW_LINE> <DEDENT> def expiration_delta(self, spot): <NEW_LINE> <INDENT> if self.type == 'C': return +1 * self.size if spot > self.strike else 0.0 <NEW_LINE> if self.type == 'P': return -1 * self.size if spot < self.strike else 0.0 <NEW_LINE> <DEDENT> def expiration_deltas(self, spots): <NEW_LINE> <INDENT> K = self.strike <NEW_LINE> S = spots.flatten() <NEW_LINE> deltas = np.ones_like(S) <NEW_LINE> for i in range(len(S)): <NEW_LINE> <INDENT> if self.type == 'C': deltas[i] = +1 * self.size if S[i] > K else 0.0 <NEW_LINE> if self.type == 'P': deltas[i] = -1 * self.size if S[i] < K else 0.0 <NEW_LINE> <DEDENT> return deltas.reshape(spots.shape) <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return PayoffSimple(self.strike, self.expiry, self.type, -self.size)
The payoff of a Put or Call option.
62599049379a373c97d9a3e8
class AddPrintableRingOperator46(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "addongen.add_printable_ring_operator46" <NEW_LINE> bl_label = "Add 18.89mm (9)" <NEW_LINE> bl_options = {'REGISTER'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> basicRingFor3DPrint('ring', 64, 18.89) <NEW_LINE> return {'FINISHED'}
Add 18.89mm (US 9 | British R 3/4 | French - | German 19 | Japanese 18 | Swiss -)
62599049d4950a0f3b111821
class UpdatedLabelsIn(): <NEW_LINE> <INDENT> def __init__(self, types: List['TypeLabel'], categories: List['Category']) -> None: <NEW_LINE> <INDENT> self.types = types <NEW_LINE> self.categories = categories <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsIn': <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'types' in _dict: <NEW_LINE> <INDENT> args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'Required property \'types\' not present in UpdatedLabelsIn JSON' ) <NEW_LINE> <DEDENT> if 'categories' in _dict: <NEW_LINE> <INDENT> args['categories'] = [ Category.from_dict(x) for x in _dict.get('categories') ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'Required property \'categories\' not present in UpdatedLabelsIn JSON' ) <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> return cls.from_dict(_dict) <NEW_LINE> <DEDENT> def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'types') and self.types is not None: <NEW_LINE> <INDENT> _dict['types'] = [x.to_dict() for x in self.types] <NEW_LINE> <DEDENT> if hasattr(self, 'categories') and self.categories is not None: <NEW_LINE> <INDENT> _dict['categories'] = [x.to_dict() for x in self.categories] <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return self.to_dict() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other: 'UpdatedLabelsIn') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other: 'UpdatedLabelsIn') -> bool: <NEW_LINE> <INDENT> return not self == other
The updated labeling from the input document, accounting for the submitted feedback. :attr List[TypeLabel] types: Description of the action specified by the element and whom it affects. :attr List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element.
625990496e29344779b01a00
class Improved_Hold(Advantage): <NEW_LINE> <INDENT> advantage_cost_type = Cost_Type.NO_RANK <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__("Improved Hold") <NEW_LINE> self.init_no()
Your grab attacks are particularly difficult to escape. Opponents you grab suffer a –5 circumstance penalty on checks to escape.
625990496fece00bbacccd76
class OfflineComputedGrade(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, db_index=True) <NEW_LINE> course_id = CourseKeyField(max_length=255, db_index=True) <NEW_LINE> created = models.DateTimeField(auto_now_add=True, null=True, db_index=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True, db_index=True) <NEW_LINE> gradeset = models.TextField(null=True, blank=True) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> unique_together = (('user', 'course_id'), ) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "[OfflineComputedGrade] %s: %s (%s) = %s" % (self.user, self.course_id, self.created, self.gradeset)
Table of grades computed offline for a given user and course.
62599049a79ad1619776b43f
@dataclass(frozen=True) <NEW_LINE> class ZtNetworkPermissions: <NEW_LINE> <INDENT> read: bool <NEW_LINE> authorize: bool <NEW_LINE> modify: bool <NEW_LINE> delete: bool
Zerotier network permissions.
6259904923849d37ff85247c
class SubIntake(Subsystem): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("Intake") <NEW_LINE> self._victor = VictorSPX(robotmap.talon_intake) <NEW_LINE> self.set_state(StateIntake.HALT) <NEW_LINE> <DEDENT> def set_victor(self, spd_target: float, mode: ControlMode = ControlMode.PercentOutput): <NEW_LINE> <INDENT> self._victor.set(mode, -spd_target) <NEW_LINE> <DEDENT> def set_state(self, state_target: StateIntake): <NEW_LINE> <INDENT> if state_target is not None and self.get_state() is not state_target: <NEW_LINE> <INDENT> self.set_victor(state_target.value, mode=ControlMode.PercentOutput) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def get_state(self) -> StateIntake: <NEW_LINE> <INDENT> for name, value in StateIntake.__members__.items(): <NEW_LINE> <INDENT> if self._victor.getMotorOutputPercent() == value.value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> raise LookupError("Could not retrieve Intake state!") <NEW_LINE> <DEDENT> def initDefaultCommand(self): <NEW_LINE> <INDENT> from commands.intake.intake_joystick import IntakeJoystick <NEW_LINE> self.setDefaultCommand(IntakeJoystick())
Subsystem used to intake and eject cargo
6259904973bcbd0ca4bcb64d
@slots_extender(('msg_id',)) <NEW_LINE> class AbstractMessage(six.with_metaclass(ABCMeta, BasicStruct)): <NEW_LINE> <INDENT> pass
Basic message class. Holds the common data for resource management messages. Attributes: msg_id (number): sending side unique message identifier.
625990498e71fb1e983bce84
class ListParameterWidget(GenericParameterWidget): <NEW_LINE> <INDENT> def __init__(self, parameter, parent=None): <NEW_LINE> <INDENT> super(ListParameterWidget, self).__init__(parameter, parent) <NEW_LINE> self._input = QListWidget() <NEW_LINE> self._input.setSelectionMode(QAbstractItemView.MultiSelection) <NEW_LINE> if self._parameter.maximum_item_count != self._parameter.minimum_item_count: <NEW_LINE> <INDENT> tool_tip = 'Select between %d and %d items' % ( self._parameter.minimum_item_count, self._parameter.maximum_item_count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tool_tip = 'Select exactly %d items' % ( self._parameter.maximum_item_count) <NEW_LINE> <DEDENT> self._input.setToolTip(tool_tip) <NEW_LINE> for opt in self._parameter.options_list: <NEW_LINE> <INDENT> item = QListWidgetItem() <NEW_LINE> item.setFlags(item.flags() | Qt.ItemIsEditable) <NEW_LINE> item.setText(str(opt)) <NEW_LINE> self._input.addItem(item) <NEW_LINE> if opt in self._parameter.value: <NEW_LINE> <INDENT> item.setSelected(True) <NEW_LINE> <DEDENT> <DEDENT> self.inner_input_layout.addWidget(self._input) <NEW_LINE> self.input_layout.setParent(None) <NEW_LINE> self.help_layout.setParent(None) <NEW_LINE> self.label.setParent(None) <NEW_LINE> self.inner_input_layout.setParent(None) <NEW_LINE> self.input_layout = QVBoxLayout() <NEW_LINE> self.input_layout.setSpacing(0) <NEW_LINE> self.input_layout.addWidget(self.label) <NEW_LINE> self.input_layout.addLayout(self.inner_input_layout) <NEW_LINE> self.main_layout.addLayout(self.input_layout) <NEW_LINE> self.main_layout.addLayout(self.help_layout) <NEW_LINE> <DEDENT> def raise_invalid_type_exception(self): <NEW_LINE> <INDENT> message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) <NEW_LINE> err = ValueError(message) <NEW_LINE> return err <NEW_LINE> <DEDENT> def get_parameter(self): <NEW_LINE> <INDENT> selected_value = [] <NEW_LINE> for opt in self._input.selectedItems(): <NEW_LINE> <INDENT> index = self._input.indexFromItem(opt) <NEW_LINE> selected_value.append(self._parameter.options_list[index.row()]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._parameter.value = selected_value <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> err = self.raise_invalid_type_exception() <NEW_LINE> raise err <NEW_LINE> <DEDENT> return self._parameter
Widget class for List parameter.
62599049379a373c97d9a3ea
class AQTSamplerLocalSimulator(AQTSampler): <NEW_LINE> <INDENT> def __init__(self, remote_host: str = '', access_token: str = '', simulate_ideal: bool = False): <NEW_LINE> <INDENT> self.remote_host = remote_host <NEW_LINE> self.access_token = access_token <NEW_LINE> self.simulate_ideal = simulate_ideal <NEW_LINE> <DEDENT> def _send_json( self, *, json_str: str, id_str: Union[str, uuid.UUID], repetitions: int = 1, num_qubits: int = 1, ) -> np.ndarray: <NEW_LINE> <INDENT> sim = AQTSimulator(num_qubits=num_qubits, simulate_ideal=self.simulate_ideal) <NEW_LINE> sim.generate_circuit_from_list(json_str) <NEW_LINE> data = sim.simulate_samples(repetitions) <NEW_LINE> return data.measurements['m']
Sampler using the AQT simulator on the local machine. Can be used as a replacement for the AQTSampler When the attribute simulate_ideal is set to True, an ideal circuit is sampled If not, the error model defined in aqt_simulator_test.py is used Example for running the ideal sampler: sampler = AQTSamplerLocalSimulator() sampler.simulate_ideal=True
6259904930dc7b76659a0bf2
class HelpTemplate(HasStrictTraits): <NEW_LINE> <INDENT> item_html = Str(ItemHTML) <NEW_LINE> group_html = Str(GroupHTML) <NEW_LINE> item_help = Str(ItemHelp) <NEW_LINE> group_help = Str(GroupHelp) <NEW_LINE> no_group_help = Str('')
Contains HTML templates for displaying help.
6259904915baa72349463351
class ActionLogEventAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ["function_name", "user", "second_arg", "third_arg", "was_successful", "message", "vessel_count", "date_started", "completion_time"] <NEW_LINE> list_filter = ["function_name", "user", "third_arg", "was_successful", "vessel_count", "date_started"] <NEW_LINE> search_fields = ["function_name", "user"] <NEW_LINE> ordering = ["-date_started"]
Customized admin view of the ActionLogEvent model.
625990498a43f66fc4bf3555
class PostView(object): <NEW_LINE> <INDENT> def __init__(self, arg): <NEW_LINE> <INDENT> super(PostView, self).__init__() <NEW_LINE> self.arg = arg
docstring for PostView
625990493eb6a72ae038ba1b
class FlaskDocument(db.Document): <NEW_LINE> <INDENT> meta = { 'abstract': True, } <NEW_LINE> @classmethod <NEW_LINE> def all_subclasses(cls): <NEW_LINE> <INDENT> return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in s.all_subclasses()]
Abstract base class. You should inherit all your models from this to save time down the road. Chances are you will want all your models to share a set of functions or to override others (like changing save behavior)
62599049ec188e330fdf9c5d
class Temperatura(object): <NEW_LINE> <INDENT> C = 1 <NEW_LINE> F = 2 <NEW_LINE> K = 3 <NEW_LINE> def converter(self, valor, tipo, destino): <NEW_LINE> <INDENT> if tipo == self.C: <NEW_LINE> <INDENT> valor = self.celsius_para(valor, destino) <NEW_LINE> <DEDENT> elif tipo == self.F: <NEW_LINE> <INDENT> valor = self.fahrenheit_para(valor, destino) <NEW_LINE> <DEDENT> elif tipo == self.K: <NEW_LINE> <INDENT> valor = self.kelvin_para(valor, destino) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError("Argumentos invalidos") <NEW_LINE> <DEDENT> return valor <NEW_LINE> <DEDENT> def celsius_para(self, valor, destino): <NEW_LINE> <INDENT> C = valor <NEW_LINE> if destino == self.F: <NEW_LINE> <INDENT> F = C*1.8 + 32 <NEW_LINE> valor = F <NEW_LINE> <DEDENT> elif destino == self.K: <NEW_LINE> <INDENT> K = C + 273.15 <NEW_LINE> valor = K <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError("Argumentos invalidos") <NEW_LINE> <DEDENT> return valor <NEW_LINE> <DEDENT> def fahrenheit_para(self, valor, destino): <NEW_LINE> <INDENT> F = valor <NEW_LINE> C = (F - 32)/1.8 <NEW_LINE> if destino == self.C: <NEW_LINE> <INDENT> valor = C <NEW_LINE> <DEDENT> elif destino == self.K: <NEW_LINE> <INDENT> K = C + 273.15 <NEW_LINE> valor = K <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError("Argumentos invalidos") <NEW_LINE> <DEDENT> return valor <NEW_LINE> <DEDENT> def kelvin_para(self, valor, destino): <NEW_LINE> <INDENT> K = valor <NEW_LINE> C = K - 273.15 <NEW_LINE> if destino == self.C: <NEW_LINE> <INDENT> valor = C <NEW_LINE> <DEDENT> elif destino == self.F: <NEW_LINE> <INDENT> F = C*1.8 + 32 <NEW_LINE> valor = F <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError("Argumentos invalidos") <NEW_LINE> <DEDENT> return valor
Métrica de temperatura (C, F, K) para conversão.
62599049d7e4931a7ef3d437
class ChooseMTModelDialog(QDialog, Ui_Dialog): <NEW_LINE> <INDENT> def __init__(self, parent=None, datamodel=None): <NEW_LINE> <INDENT> QDialog.__init__(self, parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.model = QSqlQueryModel() <NEW_LINE> self.selTableView.setModel(self.model) <NEW_LINE> self.database = datamodel.getQSqlDatabase() <NEW_LINE> self.updateModel() <NEW_LINE> self.selTableView.hideColumn(0) <NEW_LINE> self.selTableView.hideColumn(5) <NEW_LINE> self.selTableView.hideColumn(6) <NEW_LINE> QObject.connect( datamodel, SIGNAL("modelInstalled()"), self.on_datamodel_modelInstalled) <NEW_LINE> <DEDENT> def updateModel(self): <NEW_LINE> <INDENT> self.model.setQuery( 'SELECT ID, name, srclang, trglang, status, path, mosesini ' 'FROM models ' 'WHERE status = "READY" AND deleted != "True"', self.database) <NEW_LINE> <DEDENT> def on_datamodel_recordUpdated(self, bRecord): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if bRecord: <NEW_LINE> <INDENT> current = self.selTableView.currentIndex() <NEW_LINE> if current and current.row() != -1: <NEW_LINE> <INDENT> self.curSelection = current.row() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.curSelection = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.curSelection is not None: <NEW_LINE> <INDENT> self.selTableView.selectRow(self.curSelection) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print >> sys.stderr, str(e) <NEW_LINE> <DEDENT> <DEDENT> def on_datamodel_modelInstalled(self): <NEW_LINE> <INDENT> self.updateModel() <NEW_LINE> <DEDENT> @pyqtSignature("") <NEW_LINE> def on_buttonBox_accepted(self): <NEW_LINE> <INDENT> current = self.selTableView.currentIndex() <NEW_LINE> if not current: <NEW_LINE> <INDENT> doAlert("Please choose a model to start.") <NEW_LINE> return <NEW_LINE> <DEDENT> record = self.model.record(current.row()) <NEW_LINE> self.ID = record.value("ID").toString() <NEW_LINE> self.modelName = record.value("name").toString() <NEW_LINE> self.srcLang = record.value('srclang').toString() <NEW_LINE> self.trgLang = record.value('trglang').toString() <NEW_LINE> self.path = record.value("path").toString() <NEW_LINE> self.mosesini = record.value("mosesini").toString() <NEW_LINE> self.accept()
Class documentation goes here.
6259904973bcbd0ca4bcb64e
class XMLBuilder(Builder): <NEW_LINE> <INDENT> name = 'xml' <NEW_LINE> format = 'xml' <NEW_LINE> epilog = __('The XML files are in %(outdir)s.') <NEW_LINE> out_suffix = '.xml' <NEW_LINE> allow_parallel = True <NEW_LINE> _writer_class = XMLWriter <NEW_LINE> default_translator_class = XMLTranslator <NEW_LINE> def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_outdated_docs(self): <NEW_LINE> <INDENT> for docname in self.env.found_docs: <NEW_LINE> <INDENT> if docname not in self.env.all_docs: <NEW_LINE> <INDENT> yield docname <NEW_LINE> continue <NEW_LINE> <DEDENT> targetname = path.join(self.outdir, docname + self.out_suffix) <NEW_LINE> try: <NEW_LINE> <INDENT> targetmtime = path.getmtime(targetname) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> targetmtime = 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> srcmtime = path.getmtime(self.env.doc2path(docname)) <NEW_LINE> if srcmtime > targetmtime: <NEW_LINE> <INDENT> yield docname <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_target_uri(self, docname, typ=None): <NEW_LINE> <INDENT> return docname <NEW_LINE> <DEDENT> def prepare_writing(self, docnames): <NEW_LINE> <INDENT> self.writer = self._writer_class(self) <NEW_LINE> <DEDENT> def write_doc(self, docname, doctree): <NEW_LINE> <INDENT> doctree = doctree.deepcopy() <NEW_LINE> for node in doctree.traverse(nodes.Element): <NEW_LINE> <INDENT> for att, value in node.attributes.items(): <NEW_LINE> <INDENT> if isinstance(value, tuple): <NEW_LINE> <INDENT> node.attributes[att] = list(value) <NEW_LINE> <DEDENT> value = node.attributes[att] <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> for i, val in enumerate(value): <NEW_LINE> <INDENT> if isinstance(val, tuple): <NEW_LINE> <INDENT> value[i] = list(val) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> destination = StringOutput(encoding='utf-8') <NEW_LINE> self.writer.write(doctree, destination) <NEW_LINE> outfilename = path.join(self.outdir, os_path(docname) + self.out_suffix) <NEW_LINE> ensuredir(path.dirname(outfilename)) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(outfilename, 'w', encoding='utf-8') as f: <NEW_LINE> <INDENT> f.write(self.writer.output) <NEW_LINE> <DEDENT> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> logger.warning(__("error writing file %s: %s"), outfilename, err) <NEW_LINE> <DEDENT> <DEDENT> def finish(self): <NEW_LINE> <INDENT> pass
Builds Docutils-native XML.
625990496fece00bbacccd78
class FailoverSegmentRecoveryMethod(Enum): <NEW_LINE> <INDENT> AUTO = "auto" <NEW_LINE> RESERVED_HOST = "reserved_host" <NEW_LINE> AUTO_PRIORITY = "auto_priority" <NEW_LINE> RH_PRIORITY = "rh_priority" <NEW_LINE> ALL = (AUTO, RESERVED_HOST, AUTO_PRIORITY, RH_PRIORITY) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(FailoverSegmentRecoveryMethod, self).__init__(valid_values=FailoverSegmentRecoveryMethod.ALL) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def index(cls, value): <NEW_LINE> <INDENT> return cls.ALL.index(value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_index(cls, index): <NEW_LINE> <INDENT> return cls.ALL[index]
Represents possible recovery_methods for failover segment.
62599049d10714528d69f06e
class HostEvents(object): <NEW_LINE> <INDENT> def __init__(self, kernel_name='', kernel_id='', dispatch_id='', dispatch_start=None, dispatch_end=None, create_buf_start=None, create_buf_end=None, write_start=None, write_end=None, ndrange_start=None, ndrange_end=None, read_start=None, read_end=None): <NEW_LINE> <INDENT> self.dispatch_start = dispatch_start <NEW_LINE> self.dispatch_end = dispatch_end <NEW_LINE> self.create_buf_start = create_buf_start <NEW_LINE> self.create_buf_end = create_buf_end <NEW_LINE> self.write_start = write_start <NEW_LINE> self.write_end = write_end <NEW_LINE> self.ndrange_start = ndrange_start <NEW_LINE> self.ndrange_end = ndrange_end <NEW_LINE> self.read_start = read_start <NEW_LINE> self.read_end = read_end <NEW_LINE> self.kernel_name = kernel_name <NEW_LINE> self.kernel_id = kernel_id <NEW_LINE> self.dispatch_id = dispatch_id <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> a = deepcopy(self.__dict__) <NEW_LINE> for i in a: <NEW_LINE> <INDENT> a[i] = str(a[i]) <NEW_LINE> <DEDENT> return str(a) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self)
Class for storing timing information of various events associated with a kernel. :ivar dispatch_start: Start Timestamp for dispatch function :ivar dispatch_end: End Timestamp for dispatch function :ivar create_buf_start: Start Timestamp for Creation of Buffers :ivar create_buf_end: End Timestamp for Creation of Buggers :ivar write_start: Start TimeStamp for Enqueuing Write Buffer Commands on Command Queue :ivar write_end: End Timestamp for Writing of Buffers to Device :ivar ndrange_start: Start TimeStamp for Launching Kernel :ivar ndrange_end: End Timestamp for when kernel execution is finished on device :ivar read_start: Start TimeStamp for Enqueuing Read Buffer Commands on Command Queue :ivar read_end: End TimeStamp for Reading of Buffers from Device to Host :ivar kernel_name: Name of kernel :ivar kernel_id: Unique id for kernel :ivar dispatch_id: Dispatch id for kernel
625990490fa83653e46f629e
class accountCurveGroupForType(accountCurveSingleElement): <NEW_LINE> <INDENT> def __init__(self, acc_curve_for_type_list, asset_columns, capital=None, weighted_flag=False, curve_type="net"): <NEW_LINE> <INDENT> (acc_total, capital) = total_from_list( acc_curve_for_type_list, asset_columns, capital) <NEW_LINE> super().__init__(acc_total, weighted_flag=weighted_flag, capital=capital) <NEW_LINE> setattr(self, "to_list", acc_curve_for_type_list) <NEW_LINE> setattr(self, "asset_columns", asset_columns) <NEW_LINE> setattr(self, "curve_type", curve_type) <NEW_LINE> <DEDENT> def __getitem__(self, colname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ans = self.to_list[self.asset_columns.index(colname)] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise Exception("%s not found in account curve" % colname) <NEW_LINE> <DEDENT> return ans <NEW_LINE> <DEDENT> def to_frame(self): <NEW_LINE> <INDENT> return acc_list_to_pd_frame(self.to_list, self.asset_columns) <NEW_LINE> <DEDENT> def get_stats(self, stat_method, freq="daily", percent=True): <NEW_LINE> <INDENT> return statsDict(self, stat_method, freq, percent) <NEW_LINE> <DEDENT> def time_weights(self): <NEW_LINE> <INDENT> def _len_nonzero(ac_curve): <NEW_LINE> <INDENT> return_df = ac_curve.as_ts() <NEW_LINE> ans = len([x for x in return_df.values if not np.isnan(x)]) <NEW_LINE> return ans <NEW_LINE> <DEDENT> time_weights_dict = dict([(asset_name, _len_nonzero(ac_curve)) for (asset_name, ac_curve) in zip(self.asset_columns, self.to_list)]) <NEW_LINE> total_weight = sum(time_weights_dict.values()) <NEW_LINE> time_weights_dict = dict([(asset_name, weight / total_weight) for (asset_name, weight) in time_weights_dict.items()]) <NEW_LINE> return time_weights_dict
an accountCurveGroup for one cost type (gross, net, costs)
62599049b57a9660fecd2e3d
class Table(object): <NEW_LINE> <INDENT> def __init__(self, rowNames, columnNames, matrix=None): <NEW_LINE> <INDENT> self.rowNames = list(rowNames) <NEW_LINE> self.columnNames = list(columnNames) <NEW_LINE> self.rowIndices = dict([(n, i) for i, n in enumerate(self.rowNames)]) <NEW_LINE> self.columnIndices = dict([(n, i) for i, n in enumerate(self.columnNames)]) <NEW_LINE> self.matrix = numpy.zeros((len(rowNames), len(columnNames))) <NEW_LINE> if matrix is not None: <NEW_LINE> <INDENT> self.matrix[:] = matrix <NEW_LINE> <DEDENT> <DEDENT> def cell(self, rowName, columnName): <NEW_LINE> <INDENT> return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]] <NEW_LINE> <DEDENT> def row(self, rowName): <NEW_LINE> <INDENT> return self.matrix[self.rowIndices[rowName], :] <NEW_LINE> <DEDENT> def column(self, columnName): <NEW_LINE> <INDENT> return self.matrix[:, self.columnIndices[columnName]] <NEW_LINE> <DEDENT> def rows(self): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> for rowName in self.rowNames: <NEW_LINE> <INDENT> row = {columnName: self[rowName, columnName] for columnName in self.columnNames} <NEW_LINE> row["_"] = rowName <NEW_LINE> rows.append(row) <NEW_LINE> <DEDENT> return rows <NEW_LINE> <DEDENT> def __getRowIndex(self, rowName): <NEW_LINE> <INDENT> if rowName is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.rowIndices[rowName] <NEW_LINE> <DEDENT> <DEDENT> def __getColumnIndex(self, columnName): <NEW_LINE> <INDENT> if columnName is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.columnIndices[columnName] <NEW_LINE> <DEDENT> <DEDENT> def __getRowSlice(self, rowName): <NEW_LINE> <INDENT> if rowName is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif isinstance(rowName, slice): <NEW_LINE> <INDENT> return slice( self.__getRowIndex(rowName.start), self.__getRowIndex(rowName.stop), rowName.step ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__getRowIndex(rowName) <NEW_LINE> <DEDENT> <DEDENT> def __getColumnSlice(self, columnName): <NEW_LINE> <INDENT> if columnName is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif isinstance(columnName, slice): <NEW_LINE> <INDENT> return slice( self.__getColumnIndex(columnName.start), self.__getColumnIndex(columnName.stop), columnName.step ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__getColumnIndex(columnName) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> if not isinstance(item, tuple) or len(item) != 2: <NEW_LINE> <INDENT> raise ValueError("2-tuple expected") <NEW_LINE> <DEDENT> return self.matrix[self.__getRowSlice(item[0]), self.__getColumnSlice(item[1])] <NEW_LINE> <DEDENT> def __setitem__(self, item, value): <NEW_LINE> <INDENT> if not isinstance(item, tuple) or len(item) != 2: <NEW_LINE> <INDENT> raise ValueError("2-tuple expected") <NEW_LINE> <DEDENT> self.matrix[self.__getRowSlice(item[0]), self.__getColumnSlice(item[1])] = value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Table(%s)" % self.matrix <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.matrix) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.matrix)
Provides a two-dimensional matrix with named rows and columns.
6259904907f4c71912bb07f4
class ExportTask(Task): <NEW_LINE> <INDENT> def __init__(self, instance, dn=None): <NEW_LINE> <INDENT> self.cn = 'export_' + Task._get_task_date() <NEW_LINE> dn = "cn=%s,%s" % (self.cn, DN_EXPORT_TASK) <NEW_LINE> self._properties = None <NEW_LINE> super(ExportTask, self).__init__(instance, dn) <NEW_LINE> <DEDENT> def export_suffix_to_ldif(self, ldiffile, suffix): <NEW_LINE> <INDENT> _properties = { 'nsFilename': ldiffile, 'nsIncludeSuffix': suffix, 'ttl': TTL_DEFAULT_VAL, } <NEW_LINE> self.create(properties=_properties)
Create the export to ldif task :param instance: The instance :type instance: lib389.DirSrv
62599049d99f1b3c44d06a5c
class CreateClusterEndpointRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ClusterId = None <NEW_LINE> self.SubnetId = None <NEW_LINE> self.IsExtranet = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ClusterId = params.get("ClusterId") <NEW_LINE> self.SubnetId = params.get("SubnetId") <NEW_LINE> self.IsExtranet = params.get("IsExtranet")
CreateClusterEndpoint request structure.
625990498da39b475be045b2
class NodeForm(BetterForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> fieldsets = (('libvirt', {'fields': ('address',), 'legend': _('Libvirt configuration')}), ('resources', {'fields': ('hdd_total', 'cpu_total', 'memory_total'), 'legend': _('Node capacity')}),) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(NodeForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['address'] = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=45)), label=_('Node address'), help_text=_('Node address - IP or DNS name')) <NEW_LINE> self.fields['hdd_total'] = forms.IntegerField(min_value=1, label=_('HDD Total [MB]'), help_text=_(' - total amount of storage for virtual machine images')) <NEW_LINE> self.fields['cpu_total'] = forms.IntegerField(min_value=1, label=_('Cpu Total'), help_text=_(' - total amount of CPU\'s for libvirt')) <NEW_LINE> self.fields['memory_total'] = forms.IntegerField(min_value=1, label=_('Memory Total [MB]'), help_text=_(' - total amount of RAM'))
Class for <b>creating a node</b> form.
62599049e76e3b2f99fd9dcc
class override_settings(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.options = kwargs <NEW_LINE> self.wrapped = settings._wrapped <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.enable() <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.disable() <NEW_LINE> <DEDENT> def __call__(self, test_func): <NEW_LINE> <INDENT> from django.test import TransactionTestCase <NEW_LINE> if isinstance(test_func, type) and issubclass(test_func, TransactionTestCase): <NEW_LINE> <INDENT> original_pre_setup = test_func._pre_setup <NEW_LINE> original_post_teardown = test_func._post_teardown <NEW_LINE> def _pre_setup(innerself): <NEW_LINE> <INDENT> self.enable() <NEW_LINE> original_pre_setup(innerself) <NEW_LINE> <DEDENT> def _post_teardown(innerself): <NEW_LINE> <INDENT> original_post_teardown(innerself) <NEW_LINE> self.disable() <NEW_LINE> <DEDENT> test_func._pre_setup = _pre_setup <NEW_LINE> test_func._post_teardown = _post_teardown <NEW_LINE> return test_func <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> @wraps(test_func) <NEW_LINE> def inner(*args, **kwargs): <NEW_LINE> <INDENT> with self: <NEW_LINE> <INDENT> return test_func(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return inner <NEW_LINE> <DEDENT> def enable(self): <NEW_LINE> <INDENT> override = UserSettingsHolder(settings._wrapped) <NEW_LINE> for key, new_value in self.options.items(): <NEW_LINE> <INDENT> setattr(override, key, new_value) <NEW_LINE> <DEDENT> settings._wrapped = override <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> settings._wrapped = self.wrapped <NEW_LINE> for key in self.options: <NEW_LINE> <INDENT> new_value = getattr(settings, key, None)
Acts as either a decorator, or a context manager. If it's a decorator it takes a function and returns a wrapped function. If it's a contextmanager it's used with the ``with`` statement. In either event entering/exiting are called before and after, respectively, the function/block is executed.
6259904921a7993f00c6732b
class NIH_Segmented(unittest.TestCase): <NEW_LINE> <INDENT> def test_segment(self): <NEW_LINE> <INDENT> self.assertEqual("532690-57e12f-e2b74b-a07c89-2560a2", parse._nih_segmented("53269057e12fe2b74ba07c892560a2")) <NEW_LINE> self.assertEqual("5326-9057-e12f-e2b7-4ba0-7c89-2560-a2", parse._nih_segmented("53269057e12fe2b74ba07c892560a2", 4)) <NEW_LINE> self.assertEqual("532690-5", parse._nih_segmented("5326905")) <NEW_LINE> self.assertEqual("532690", parse._nih_segmented("532690")) <NEW_LINE> self.assertEqual("53269", parse._nih_segmented("53269")) <NEW_LINE> self.assertEqual("", parse._nih_segmented(""))
Test _nih_segmented()
625990494e696a045264e801
class VmSettings(validation.ValidatedDict): <NEW_LINE> <INDENT> KEY_VALIDATOR = validation.Regex('[a-zA-Z_][a-zA-Z0-9_]*') <NEW_LINE> VALUE_VALIDATOR = str <NEW_LINE> @classmethod <NEW_LINE> def Merge(cls, vm_settings_one, vm_settings_two): <NEW_LINE> <INDENT> result_vm_settings = (vm_settings_two or {}).copy() <NEW_LINE> result_vm_settings.update(vm_settings_one or {}) <NEW_LINE> return VmSettings(**result_vm_settings) if result_vm_settings else None
Class for VM settings. The settings are not further validated here. The settings are validated on the server side.
6259904923e79379d538d8c0
class Batch: <NEW_LINE> <INDENT> def __init__(self, src, pos, trg=None, pad=0): <NEW_LINE> <INDENT> self.src = src <NEW_LINE> self.src_mask = (src != pad).unsqueeze(-2) <NEW_LINE> self.trg = trg <NEW_LINE> self.pos = pos <NEW_LINE> self.ntokens = torch.tensor(self.src != pad, dtype=torch.float).data.sum()
Object for holding a batch of data with mask during training.
6259904996565a6dacd2d96a
class OpenFileAction(Action): <NEW_LINE> <INDENT> tooltip = "Open a file for editing" <NEW_LINE> description = "Open a file for editing" <NEW_LINE> def perform(self, event=None): <NEW_LINE> <INDENT> logger.info('OpenFileAction.perform()') <NEW_LINE> pref_script_path = preference_manager.cviewerui.scriptpath <NEW_LINE> dialog = FileDialog(parent=self.window.control, title='Open File', default_directory=pref_script_path) <NEW_LINE> if dialog.open() == OK: <NEW_LINE> <INDENT> self.window.workbench.edit(File(dialog.path), kind=TextEditor)
Open an existing file in the text editor.
625990498a349b6b4368760f
class IActivationModel(Interface): <NEW_LINE> <INDENT> pass
Register utility registration which marks active Activation SQLAlchemy model class.
62599049b5575c28eb7136aa
class BigInputsSortCase(BaseSortCase): <NEW_LINE> <INDENT> def setup(self, n_elems, max_elem): <NEW_LINE> <INDENT> self.n_elems = n_elems <NEW_LINE> self.max_elem = max_elem <NEW_LINE> self.test_input = [] <NEW_LINE> for _ in range(n_elems): <NEW_LINE> <INDENT> self.test_input.append(random.randint(1, max_elem))
Sort case where VERY LARGE inputs are sorted. The length of the input and maximum value of the input is configurable with the method 'setup'. The elements consist of random values up to the maximum input.
6259904924f1403a926862ae
class Clase(ClaseMadre): <NEW_LINE> <INDENT> def __init__(self, valor): <NEW_LINE> <INDENT> self.atributo = valor
Esto es un ejemplo de clase que hereda de ClaseMadre
62599049498bea3a75a58ee2
class SpriteSheet(object): <NEW_LINE> <INDENT> def __init__(self, file_name): <NEW_LINE> <INDENT> self.sprite_sheet = pygame.image.load(file_name).convert() <NEW_LINE> <DEDENT> def get_image(self, x, y, width, height): <NEW_LINE> <INDENT> image = pygame.Surface([width, height]).convert() <NEW_LINE> image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) <NEW_LINE> image.set_colorkey(constants.WHITE) <NEW_LINE> return image
Class used to grab images out of a sprite sheet.
62599049462c4b4f79dbcdc2
class EngagementInstance(InstanceResource): <NEW_LINE> <INDENT> class Status(object): <NEW_LINE> <INDENT> ACTIVE = "active" <NEW_LINE> ENDED = "ended" <NEW_LINE> <DEDENT> def __init__(self, version, payload, flow_sid, sid=None): <NEW_LINE> <INDENT> super(EngagementInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload['sid'], 'account_sid': payload['account_sid'], 'flow_sid': payload['flow_sid'], 'contact_sid': payload['contact_sid'], 'contact_channel_address': payload['contact_channel_address'], 'status': payload['status'], 'context': payload['context'], 'date_created': deserialize.iso8601_datetime(payload['date_created']), 'date_updated': deserialize.iso8601_datetime(payload['date_updated']), 'url': payload['url'], 'links': payload['links'], } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'flow_sid': flow_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = EngagementContext( self._version, flow_sid=self._solution['flow_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def flow_sid(self): <NEW_LINE> <INDENT> return self._properties['flow_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def contact_sid(self): <NEW_LINE> <INDENT> return self._properties['contact_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def contact_channel_address(self): <NEW_LINE> <INDENT> return self._properties['contact_channel_address'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._properties['status'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def context(self): <NEW_LINE> <INDENT> return self._properties['context'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._properties['links'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> @property <NEW_LINE> def steps(self): <NEW_LINE> <INDENT> return self._proxy.steps <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Preview.Studio.EngagementInstance {}>'.format(context)
PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
62599049d99f1b3c44d06a5e
class IntegrationController(object): <NEW_LINE> <INDENT> def __init__(self, working_dir, view=None, img_data=None, mask_data=None, calibration_data=None, spectrum_data=None, phase_data=None): <NEW_LINE> <INDENT> self.working_dir = working_dir <NEW_LINE> if view == None: <NEW_LINE> <INDENT> self.view = IntegrationView() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.view = view <NEW_LINE> <DEDENT> if img_data == None: <NEW_LINE> <INDENT> self.img_data = ImgData() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.img_data = img_data <NEW_LINE> <DEDENT> if mask_data == None: <NEW_LINE> <INDENT> self.mask_data = MaskData() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mask_data = mask_data <NEW_LINE> <DEDENT> if calibration_data == None: <NEW_LINE> <INDENT> self.calibration_data = CalibrationData(self.img_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.calibration_data = calibration_data <NEW_LINE> <DEDENT> if spectrum_data == None: <NEW_LINE> <INDENT> self.spectrum_data = SpectrumData() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.spectrum_data = spectrum_data <NEW_LINE> <DEDENT> if phase_data == None: <NEW_LINE> <INDENT> self.phase_data = PhaseData() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.phase_data = phase_data <NEW_LINE> <DEDENT> self.create_sub_controller() <NEW_LINE> self.view.setWindowState(self.view.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) <NEW_LINE> self.view.activateWindow() <NEW_LINE> self.view.raise_() <NEW_LINE> <DEDENT> def create_sub_controller(self): <NEW_LINE> <INDENT> self.spectrum_controller = IntegrationSpectrumController(self.working_dir, self.view, self.img_data, self.mask_data, self.calibration_data, self.spectrum_data) <NEW_LINE> self.image_controller = IntegrationImageController(self.working_dir, self.view, self.img_data, self.mask_data, self.calibration_data) <NEW_LINE> self.overlay_controller = IntegrationOverlayController(self.working_dir, self.view, self.spectrum_data) <NEW_LINE> self.phase_controller = IntegrationPhaseController(self.working_dir, self.view, self.calibration_data, self.spectrum_data, self.phase_data)
This controller hosts all the Subcontroller of the integration tab.
625990498da39b475be045b4
class CurveFitting(Command): <NEW_LINE> <INDENT> name = 'curve' <NEW_LINE> options = [CommonOption()] <NEW_LINE> short_description = 'ST-FMR fitting for a single sample' <NEW_LINE> long_description = 'Analyze experimental data using ST-FMR method for a single sample' <NEW_LINE> file_list = [] <NEW_LINE> range_type = [] <NEW_LINE> frequency = [] <NEW_LINE> h_res = [] <NEW_LINE> sym = [] <NEW_LINE> asym = [] <NEW_LINE> linewidth = [] <NEW_LINE> slope = [] <NEW_LINE> bias = [] <NEW_LINE> columns = ["range_type", "frequency", "h_res", "sym", "asym", "linewidth", "slope", "bias"] <NEW_LINE> def file_parser(self, foldername): <NEW_LINE> <INDENT> filename = glob.glob(foldername + '/*lvm') <NEW_LINE> if filename == []: <NEW_LINE> <INDENT> return ExitStatus.MISS_USAGE <NEW_LINE> <DEDENT> for i, filename in enumerate(filename): <NEW_LINE> <INDENT> pat = r'[0-9]+\.[0-9]+' <NEW_LINE> num_list = re.findall(pat, filename) <NEW_LINE> fre = float(num_list[0]) <NEW_LINE> self.file_list.append([fre, filename]) <NEW_LINE> <DEDENT> self.file_list.sort(key=lambda x: x[0]) <NEW_LINE> <DEDENT> def curve_fitting(self, fre, filename): <NEW_LINE> <INDENT> df = pd.read_table(filename, names=['MF', 'Vol']) <NEW_LINE> x = df['MF'] <NEW_LINE> y = df['Vol'] <NEW_LINE> for [range_type, fre_slope, fre_bias] in [["positive", 17, -17], ["negative", -17, 17]]: <NEW_LINE> <INDENT> para_ini = [fre_slope * fre + fre_bias, 1.0, 1.0, 5.0, 1.0, 1.0] <NEW_LINE> x_ = x[fitting_range.get(range_type)] <NEW_LINE> y_ = y[fitting_range.get(range_type)] <NEW_LINE> para, _ = sopt.curve_fit( fitfunc_curve, x_, y_, para_ini) <NEW_LINE> self.range_type += [range_type] <NEW_LINE> self.frequency += [fre] <NEW_LINE> self.h_res += [para[0]] <NEW_LINE> self.sym += [para[1]] <NEW_LINE> self.asym += [para[2]] <NEW_LINE> self.linewidth += [para[3]] <NEW_LINE> self.slope += [para[4]] <NEW_LINE> self.bias += [para[5]] <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def run(self, args): <NEW_LINE> <INDENT> foldername = str(args.dir) <NEW_LINE> self.file_parser(foldername) <NEW_LINE> print('Target files:') <NEW_LINE> for fre, filename in self.file_list: <NEW_LINE> <INDENT> print(filename) <NEW_LINE> self.curve_fitting(fre, filename) <NEW_LINE> <DEDENT> df = pd.DataFrame( data={"range_type": self.range_type, "frequency": self.frequency, "h_res": self.h_res, "sym": self.sym, "asym": self.asym, "linewidth": self.linewidth, "slope": self.slope, "bias": self.bias, }, columns=self.columns ) <NEW_LINE> print(df) <NEW_LINE> df.to_csv(foldername + "/" + curve_fitting_file, index=False) <NEW_LINE> return ExitStatus.SUCCESS
Sub command of root
625990498e05c05ec3f6f83c
class ErrorDuringMerge(GitException): <NEW_LINE> <INDENT> pass
When an error occurs during the merge (merge conflict...)
6259904923849d37ff852480
class RNNCell(RNNCellBase): <NEW_LINE> <INDENT> __constants__ = ['input_size', 'hidden_size', 'bias', 'nonlinearity'] <NEW_LINE> nonlinearity: str <NEW_LINE> def __init__(self, input_size: int, hidden_size: int, bias: bool = True, nonlinearity: str = "tanh", device=None, dtype=None) -> None: <NEW_LINE> <INDENT> factory_kwargs = {'device': device, 'dtype': dtype} <NEW_LINE> super(RNNCell, self).__init__(input_size, hidden_size, bias, num_chunks=1, **factory_kwargs) <NEW_LINE> self.nonlinearity = nonlinearity <NEW_LINE> <DEDENT> def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor: <NEW_LINE> <INDENT> if hx is None: <NEW_LINE> <INDENT> hx = torch.zeros(input.size(0), self.hidden_size, dtype=input.dtype, device=input.device) <NEW_LINE> <DEDENT> if self.nonlinearity == "tanh": <NEW_LINE> <INDENT> ret = _VF.rnn_tanh_cell( input, hx, self.weight_ih, self.weight_hh, self.bias_ih, self.bias_hh, ) <NEW_LINE> <DEDENT> elif self.nonlinearity == "relu": <NEW_LINE> <INDENT> ret = _VF.rnn_relu_cell( input, hx, self.weight_ih, self.weight_hh, self.bias_ih, self.bias_hh, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = input <NEW_LINE> raise RuntimeError( "Unknown nonlinearity: {}".format(self.nonlinearity)) <NEW_LINE> <DEDENT> return ret
An Elman RNN cell with tanh or ReLU non-linearity. .. math:: h' = \tanh(W_{ih} x + b_{ih} + W_{hh} h + b_{hh}) If :attr:`nonlinearity` is `'relu'`, then ReLU is used in place of tanh. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'`` Inputs: input, hidden - **input** of shape `(batch, input_size)`: tensor containing input features - **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. Outputs: h' - **h'** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch Shape: - Input1: :math:`(N, H_{in})` tensor containing input features where :math:`H_{in}` = `input_size` - Input2: :math:`(N, H_{out})` tensor containing the initial hidden state for each element in the batch where :math:`H_{out}` = `hidden_size` Defaults to zero if not provided. - Output: :math:`(N, H_{out})` tensor containing the next hidden state for each element in the batch Attributes: weight_ih: the learnable input-hidden weights, of shape `(hidden_size, input_size)` weight_hh: the learnable hidden-hidden weights, of shape `(hidden_size, hidden_size)` bias_ih: the learnable input-hidden bias, of shape `(hidden_size)` bias_hh: the learnable hidden-hidden bias, of shape `(hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` Examples:: >>> rnn = nn.RNNCell(10, 20) >>> input = torch.randn(6, 3, 10) >>> hx = torch.randn(3, 20) >>> output = [] >>> for i in range(6): hx = rnn(input[i], hx) output.append(hx)
625990498e71fb1e983bce88
class Scene(QtGui.QGraphicsScene): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> left = -300 <NEW_LINE> top = -300 <NEW_LINE> width = 600 <NEW_LINE> height = 600 <NEW_LINE> QtGui.QGraphicsScene.__init__(self) <NEW_LINE> self.setSceneRect(left, top, width, height)
Hold information for the scene that is being drawn in the tugalinhas screen
6259904963d6d428bbee3b8d
class InterpolateColorTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.white = Color('white') <NEW_LINE> self.black = Color('black') <NEW_LINE> <DEDENT> def test_invalid_start(self): <NEW_LINE> <INDENT> with self.assertRaises(qtutils.QtValueError): <NEW_LINE> <INDENT> utils.interpolate_color(Color(), self.white, 0) <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_end(self): <NEW_LINE> <INDENT> with self.assertRaises(qtutils.QtValueError): <NEW_LINE> <INDENT> utils.interpolate_color(self.white, Color(), 0) <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_percentage(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> utils.interpolate_color(self.white, self.white, -1) <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> utils.interpolate_color(self.white, self.white, 101) <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_colorspace(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> utils.interpolate_color(self.white, self.black, 10, QColor.Cmyk) <NEW_LINE> <DEDENT> <DEDENT> def test_valid_percentages_rgb(self): <NEW_LINE> <INDENT> white = utils.interpolate_color(self.white, self.black, 0, QColor.Rgb) <NEW_LINE> black = utils.interpolate_color(self.white, self.black, 100, QColor.Rgb) <NEW_LINE> self.assertEqual(Color(white), self.white) <NEW_LINE> self.assertEqual(Color(black), self.black) <NEW_LINE> <DEDENT> def test_valid_percentages_hsv(self): <NEW_LINE> <INDENT> white = utils.interpolate_color(self.white, self.black, 0, QColor.Hsv) <NEW_LINE> black = utils.interpolate_color(self.white, self.black, 100, QColor.Hsv) <NEW_LINE> self.assertEqual(Color(white), self.white) <NEW_LINE> self.assertEqual(Color(black), self.black) <NEW_LINE> <DEDENT> def test_valid_percentages_hsl(self): <NEW_LINE> <INDENT> white = utils.interpolate_color(self.white, self.black, 0, QColor.Hsl) <NEW_LINE> black = utils.interpolate_color(self.white, self.black, 100, QColor.Hsl) <NEW_LINE> self.assertEqual(Color(white), self.white) <NEW_LINE> self.assertEqual(Color(black), self.black) <NEW_LINE> <DEDENT> def test_interpolation_rgb(self): <NEW_LINE> <INDENT> color = utils.interpolate_color(Color(0, 40, 100), Color(0, 20, 200), 50, QColor.Rgb) <NEW_LINE> self.assertEqual(Color(color), Color(0, 30, 150)) <NEW_LINE> <DEDENT> def test_interpolation_hsv(self): <NEW_LINE> <INDENT> start = Color() <NEW_LINE> stop = Color() <NEW_LINE> start.setHsv(0, 40, 100) <NEW_LINE> stop.setHsv(0, 20, 200) <NEW_LINE> color = utils.interpolate_color(start, stop, 50, QColor.Hsv) <NEW_LINE> expected = Color() <NEW_LINE> expected.setHsv(0, 30, 150) <NEW_LINE> self.assertEqual(Color(color), expected) <NEW_LINE> <DEDENT> def test_interpolation_hsl(self): <NEW_LINE> <INDENT> start = Color() <NEW_LINE> stop = Color() <NEW_LINE> start.setHsl(0, 40, 100) <NEW_LINE> stop.setHsl(0, 20, 200) <NEW_LINE> color = utils.interpolate_color(start, stop, 50, QColor.Hsl) <NEW_LINE> expected = Color() <NEW_LINE> expected.setHsl(0, 30, 150) <NEW_LINE> self.assertEqual(Color(color), expected)
Tests for interpolate_color. Attributes: white: The Color white as a valid Color for tests. white: The Color black as a valid Color for tests.
625990494e696a045264e802
class ChatLogger(BasePlugin): <NEW_LINE> <INDENT> name = 'chat_logger' <NEW_LINE> def on_chat_sent(self, data): <NEW_LINE> <INDENT> parsed = chat_sent().parse(data.data) <NEW_LINE> self.logger.info( 'Chat message sent: <%s> %s', self.protocol.player.name, parsed.message.decode('utf-8') )
Plugin which parses player chatter into the log file.
6259904945492302aabfd896
class ExtendedManagerMixin(BaseUtilityMixin): <NEW_LINE> <INDENT> def __getattr__(self, attr, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(self.__class__, attr, *args) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return getattr(self.get_queryset(), attr, *args)
add this mixin to add support for chainable custom methods to your manager
6259904991af0d3eaad3b1e9
class FileChooserDialog(gtk.FileChooserDialog): <NEW_LINE> <INDENT> def __init__(self, title_text, buttons, default_response, action=gtk.FILE_CHOOSER_ACTION_OPEN, select_multiple=False, current_folder=None, on_response_ok=None, on_response_cancel = None): <NEW_LINE> <INDENT> gtk.FileChooserDialog.__init__(self, title=title_text, action=action, buttons=buttons) <NEW_LINE> if default_response: <NEW_LINE> <INDENT> self.set_default_response(default_response) <NEW_LINE> <DEDENT> self.set_select_multiple(select_multiple) <NEW_LINE> if current_folder and ospath.isdir(current_folder): <NEW_LINE> <INDENT> self.set_current_folder(current_folder) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_current_folder(utils.get_documents_path()) <NEW_LINE> <DEDENT> self.response_ok, self.response_cancel = on_response_ok, on_response_cancel <NEW_LINE> <DEDENT> def on_dialog_response(self, dialog, response): <NEW_LINE> <INDENT> if response in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_CLOSE): <NEW_LINE> <INDENT> if self.response_cancel: <NEW_LINE> <INDENT> if isinstance(self.response_cancel, tuple): <NEW_LINE> <INDENT> self.response_cancel[0](dialog, *self.response_cancel[1:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response_cancel(dialog) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.just_destroy(dialog) <NEW_LINE> <DEDENT> <DEDENT> elif response == gtk.RESPONSE_OK: <NEW_LINE> <INDENT> if self.response_ok: <NEW_LINE> <INDENT> if isinstance(self.response_ok, tuple): <NEW_LINE> <INDENT> self.response_ok[0](dialog, *self.response_ok[1:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response_ok(dialog) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.just_destroy(dialog) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def just_destroy(self, widget): <NEW_LINE> <INDENT> self.destroy() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.show_all()
Non-blocking FileChooser Dialog around gtk.FileChooserDialog
62599049e64d504609df9db2
class SelfOrAdminPermissionMixin(UserPassesTestMixin): <NEW_LINE> <INDENT> def test_func(self) -> bool: <NEW_LINE> <INDENT> user = self.get_object() <NEW_LINE> return user == self.request.user or self.request.user.is_superuser
Mixin to require that a user is the linked object or an admin. To be used e.g. for edit permission on user profiles
6259904973bcbd0ca4bcb652
class NamesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_first_last_name(self): <NEW_LINE> <INDENT> formatted_name = get_formatted_name('janis', 'joplin') <NEW_LINE> self.assertEqual(formatted_name, 'Janis Joplin') <NEW_LINE> <DEDENT> def test_first_last_middle_name(self): <NEW_LINE> <INDENT> formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus') <NEW_LINE> self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
test name_function.py
6259904950485f2cf55dc34e
class BaseServiceProperty(core_models.UuidMixin, core_models.NameMixin, models.Model): <NEW_LINE> <INDENT> class Meta(object): <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @lru_cache(maxsize=1) <NEW_LINE> def get_url_name(cls): <NEW_LINE> <INDENT> return '{}-{}'.format(cls._meta.app_label, cls.__name__.lower())
Base service properties like image, flavor, region, which are usually used for Resource provisioning.
625990493cc13d1c6d466afd
@tf_export("distribute.experimental.CollectiveHints") <NEW_LINE> class Hints(object): <NEW_LINE> <INDENT> def __init__(self, bytes_per_pack=0): <NEW_LINE> <INDENT> if bytes_per_pack < 0: <NEW_LINE> <INDENT> raise ValueError("bytes_per_pack must be non-negative") <NEW_LINE> <DEDENT> self.bytes_per_pack = bytes_per_pack
Hints for collective operations like AllReduce. This can be passed to methods like `tf.distribute.get_replica_context().all_reduce()` to optimize collective operation performance. Note that these are only hints, which may or may not change the actual behavior. Some options only apply to certain strategy and are ignored by others. One common optimization is to break gradients all-reduce into multiple packs so that weight updates can overlap with gradient all-reduce. Example: ```python hints = tf.distribute.experimental.CollectiveHints( bytes_per_pack=50 * 1024 * 1024) grads = tf.distribute.get_replica_context().all_reduce( 'sum', grads, experimental_hints=hints) optimizer.apply_gradients(zip(grads, vars), all_reduce_sum_gradients=False) ```
625990490fa83653e46f62a2
class Particle(object): <NEW_LINE> <INDENT> def __init__(self, name, point, mass): <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError('Supply a valid name.') <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> self.mass = mass <NEW_LINE> self.point = point <NEW_LINE> self.potential_energy = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> __repr__ = __str__ <NEW_LINE> @property <NEW_LINE> def mass(self): <NEW_LINE> <INDENT> return self._mass <NEW_LINE> <DEDENT> @mass.setter <NEW_LINE> def mass(self, value): <NEW_LINE> <INDENT> self._mass = sympify(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def point(self): <NEW_LINE> <INDENT> return self._point <NEW_LINE> <DEDENT> @point.setter <NEW_LINE> def point(self, p): <NEW_LINE> <INDENT> if not isinstance(p, Point): <NEW_LINE> <INDENT> raise TypeError("Particle point attribute must be a Point object.") <NEW_LINE> <DEDENT> self._point = p <NEW_LINE> <DEDENT> def linear_momentum(self, frame): <NEW_LINE> <INDENT> return self.mass * self.point.vel(frame) <NEW_LINE> <DEDENT> def angular_momentum(self, point, frame): <NEW_LINE> <INDENT> return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) <NEW_LINE> <DEDENT> def kinetic_energy(self, frame): <NEW_LINE> <INDENT> return (self.mass / sympify(2) * self.point.vel(frame) & self.point.vel(frame)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def potential_energy(self): <NEW_LINE> <INDENT> return self._pe <NEW_LINE> <DEDENT> @potential_energy.setter <NEW_LINE> def potential_energy(self, scalar): <NEW_LINE> <INDENT> self._pe = sympify(scalar)
A particle. Particles have a non-zero mass and lack spatial extension; they take up no space. Values need to be supplied on initialization, but can be changed later. Parameters ========== name : str Name of particle point : Point A physics/mechanics Point which represents the position, velocity, and acceleration of this Particle mass : sympifyable A SymPy expression representing the Particle's mass Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import Symbol >>> po = Point('po') >>> m = Symbol('m') >>> pa = Particle('pa', po, m) >>> # Or you could change these later >>> pa.mass = m >>> pa.point = po
6259904907d97122c4218068
class EncoderDir(nn.Module): <NEW_LINE> <INDENT> def __init__(self, cfg, target_function): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.inference_network = NeuralNetwork(input_size=cfg.data_size, output_size=cfg.latent_size , hidden_size=cfg.latent_size ) <NEW_LINE> self.latent_size = cfg.latent_size <NEW_LINE> self.batch_size =cfg.batch_size <NEW_LINE> self.n_samples = cfg.n_samples <NEW_LINE> self._gamm_alpha = torch.tensor(1.0).float() <NEW_LINE> self.all_beta = torch.ones(self.batch_size,self.latent_size) <NEW_LINE> self.target_function= target_function <NEW_LINE> self.log_p= NormalLogProb() <NEW_LINE> self.cfg=cfg <NEW_LINE> self.softplus = nn.Softplus() <NEW_LINE> self.register_buffer('p_z_loc', torch.zeros(cfg.latent_size)) <NEW_LINE> self.register_buffer('p_z_scale', torch.ones(cfg.latent_size)) <NEW_LINE> self.encoder_score = self.Dirich_KL <NEW_LINE> <DEDENT> def Dirich_KL(self, scale): <NEW_LINE> <INDENT> alpha0=torch.sum(scale,axis=2) <NEW_LINE> kl_term_0 = torch.lgamma(alpha0) -torch.sum(torch.lgamma(scale)) -torch.lgamma(self.alpha0) + torch.sum(torch.lgamma(self.target_alpha)) <NEW_LINE> kl_term_1 = torch.digamma(scale) -self.digamma0 <NEW_LINE> kl_term_11= scale- self.target_alpha <NEW_LINE> anal_kl = kl_term_0 + torch.mul(kl_term_1,kl_term_11) <NEW_LINE> return anal_kl <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = x.type(torch.FloatTensor) <NEW_LINE> scale_arg = self.inference_network(x) <NEW_LINE> scale = self.softplus(scale_arg) <NEW_LINE> all_gama =Gamma(scale,self.all_beta) <NEW_LINE> all_dir= Dirichlet(scale) <NEW_LINE> scores= kl0._kl_dirichlet_dirichlet(all_dir,self.target_function) <NEW_LINE> scores = scores.mean(dim=-1) <NEW_LINE> zrnd = all_gama.sample(sample_shape=(self.n_samples,)) <NEW_LINE> mz = zrnd.mean(dim=0) <NEW_LINE> z_dir = Dirichlet(mz) <NEW_LINE> z_score= kl0._kl_dirichlet_dirichlet(z_dir,self.target_function) <NEW_LINE> z_score = z_score.mean(dim=-1) <NEW_LINE> scores=torch.unsqueeze(scores,dim=-1) <NEW_LINE> z_score = torch.unsqueeze(z_score, dim=-1) <NEW_LINE> return zrnd, scores,z_score
Approximate posterior parameterized by an inference network.
62599049cad5886f8bdc5a61
class SubtractNode(BinOpNode): <NEW_LINE> <INDENT> nodeName = 'Subtract' <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> BinOpNode.__init__(self, name, '__sub__')
Returns A - B. Does not check input types.
62599049d99f1b3c44d06a60
class Cached(object): <NEW_LINE> <INDENT> cache_keys = [] <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> for ckey in self.cache_keys: <NEW_LINE> <INDENT> cache.remove(ckey) <NEW_LINE> <DEDENT> super(Cached, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def get_cache_values(self): <NEW_LINE> <INDENT> return {ckey: cache.get_value(ckey) for ckey in self.cache_keys}
Mixin class to invalidate cache keys on model.save(). Usage:: class MyModel(Cached, models.Model): # models.Model must be last @property def cache_keys(self): return [...] ... (that's it. All cache keys will be removed whenever `MyModel.save()` is called).
62599049711fe17d825e1680
class text_to_say(smach.StateMachine): <NEW_LINE> <INDENT> def __init__(self, text=None, text_cb=None, wait_before_speaking=0, lang='en_US', wait=True): <NEW_LINE> <INDENT> self.say_pub= rospy.Publisher('/sound/goal', SoundActionGoal, latch=True) <NEW_LINE> smach.StateMachine.__init__(self, outcomes=['succeeded', 'preempted', 'aborted'], input_keys=['tts_text', 'tts_wait_before_speaking', 'tts_lang'], output_keys=[]) <NEW_LINE> with self: <NEW_LINE> <INDENT> self.userdata.tts_wait_before_speaking=0 <NEW_LINE> self.userdata.tts_text=None <NEW_LINE> self.userdata.tts_lang=None <NEW_LINE> smach.StateMachine.add('PrepareData', prepareData(text, wait_before_speaking, lang,wait), transitions={'wait':'CreateSayGoal', 'aborted':'aborted', 'preempted':'preempted','no_wait':'create_goal_no_wait'}) <NEW_LINE> smach.StateMachine.add('CreateSayGoal', createSayGoal(), transitions={'succeeded':'RobotSay', 'aborted':'aborted','preempted':'preempted'}) <NEW_LINE> smach.StateMachine.add('RobotSay', SimpleActionState(TTS_TOPIC_NAME, SoundAction, goal_key='tts_speech_goal', input_keys=['standard_error'], output_keys=['standard_error']), transitions={'succeeded':'succeeded', 'aborted':'aborted'}) <NEW_LINE> smach.StateMachine.add('create_goal_no_wait', createSayGoal_noWait(), transitions={'succeeded':'SEND_GOAL', 'aborted':'aborted'}) <NEW_LINE> smach.StateMachine.add('SEND_GOAL', send_goal(self.say_pub), transitions={'succeeded':'succeeded', 'aborted':'aborted','preempted':'preempted'})
To use say you need to indicate the text to be said. By default it waits 0 seconds before speaking and uses en_US language and don't use the nsecs wait option. smach.StateMachine.add( 'SaySM', text_to_say("I'm working"), transitions={'succeeded': 'succeeded', 'aborted': 'aborted'})
6259904945492302aabfd898
class Ping(object): <NEW_LINE> <INDENT> def __init__(self, address): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> ping_cmd = 'ping -c 4 {0}'.format(self.address) <NEW_LINE> out = runsub.cmd(ping_cmd) <NEW_LINE> return out[1]
Get information about the ping (icmp)
62599049dc8b845886d54981
class TimerMsg(RunnerMsg): <NEW_LINE> <INDENT> pass
A message telling your code that a timer triggers. Subclass this and use it as `CallAdmin.timer`'s ``cls`` parameter for easier disambiguation.
6259904945492302aabfd899
@unique <NEW_LINE> class ExchangeName(IntEnum): <NEW_LINE> <INDENT> Default = 0 <NEW_LINE> HuoBi = 1 <NEW_LINE> BitMex = 2 <NEW_LINE> DataIntegration = 3 <NEW_LINE> LocalFile = 4
交易所名称
6259904976d4e153a661dc59
class AddFolderRequestBody(object): <NEW_LINE> <INDENT> swagger_types = { 'path': 'str', 'name': 'str', 'parent_resource': 'str' } <NEW_LINE> attribute_map = { 'path': 'path', 'name': 'name', 'parent_resource': 'parentResource' } <NEW_LINE> def __init__(self, path=None, name=None, parent_resource=None): <NEW_LINE> <INDENT> self._path = None <NEW_LINE> self._name = None <NEW_LINE> self._parent_resource = None <NEW_LINE> self.discriminator = None <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if parent_resource is not None: <NEW_LINE> <INDENT> self.parent_resource = parent_resource <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @path.setter <NEW_LINE> def path(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent_resource(self): <NEW_LINE> <INDENT> return self._parent_resource <NEW_LINE> <DEDENT> @parent_resource.setter <NEW_LINE> def parent_resource(self, parent_resource): <NEW_LINE> <INDENT> self._parent_resource = parent_resource <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <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> if issubclass(AddFolderRequestBody, 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, AddFolderRequestBody): <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
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904923e79379d538d8c4
class AxisType (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'AxisType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/Users/ulbrich/Projects/RobotDesigner/resources/urdf.xsd', 146, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __xyz = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'xyz'), 'xyz', '__AbsentNamespace0_AxisType_xyz', pyxb.binding.datatypes.string, unicode_default='1 0 0') <NEW_LINE> __xyz._DeclarationLocation = pyxb.utils.utility.Location('/Users/ulbrich/Projects/RobotDesigner/resources/urdf.xsd', 147, 4) <NEW_LINE> __xyz._UseLocation = pyxb.utils.utility.Location('/Users/ulbrich/Projects/RobotDesigner/resources/urdf.xsd', 147, 4) <NEW_LINE> xyz = property(__xyz.value, __xyz.set, None, None) <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ __xyz.name() : __xyz })
Complex type AxisType with content type EMPTY
625990498a349b6b43687613
class ElectricCar(Car): <NEW_LINE> <INDENT> def __init__(self, make, model, year): <NEW_LINE> <INDENT> super().__init__(make, model, year) <NEW_LINE> self.battery = Battery()
Represent aspects of a car, specific to electric vehicles.
625990493617ad0b5ee07503
class CourseDiscussionDivisionEnabledTestCase(ModuleStoreTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.course = CourseFactory.create() <NEW_LINE> CourseModeFactory.create(course_id=self.course.id, mode_slug=CourseMode.AUDIT) <NEW_LINE> self.test_cohort = CohortFactory( course_id=self.course.id, name='Test Cohort', users=[] ) <NEW_LINE> <DEDENT> def test_discussion_division_disabled(self): <NEW_LINE> <INDENT> course_discussion_settings = get_course_discussion_settings(self.course.id) <NEW_LINE> assert not utils.course_discussion_division_enabled(course_discussion_settings) <NEW_LINE> assert [] == utils.available_division_schemes(self.course.id) <NEW_LINE> <DEDENT> def test_discussion_division_by_cohort(self): <NEW_LINE> <INDENT> set_discussion_division_settings( self.course.id, enable_cohorts=False, division_scheme=CourseDiscussionSettings.COHORT ) <NEW_LINE> assert not utils.course_discussion_division_enabled(get_course_discussion_settings(self.course.id)) <NEW_LINE> assert [] == utils.available_division_schemes(self.course.id) <NEW_LINE> set_discussion_division_settings( self.course.id, enable_cohorts=True, division_scheme=CourseDiscussionSettings.COHORT ) <NEW_LINE> assert utils.course_discussion_division_enabled(get_course_discussion_settings(self.course.id)) <NEW_LINE> assert [CourseDiscussionSettings.COHORT] == utils.available_division_schemes(self.course.id) <NEW_LINE> <DEDENT> def test_discussion_division_by_enrollment_track(self): <NEW_LINE> <INDENT> set_discussion_division_settings( self.course.id, division_scheme=CourseDiscussionSettings.ENROLLMENT_TRACK ) <NEW_LINE> assert not utils.course_discussion_division_enabled(get_course_discussion_settings(self.course.id)) <NEW_LINE> assert [] == utils.available_division_schemes(self.course.id) <NEW_LINE> CourseModeFactory.create(course_id=self.course.id, mode_slug=CourseMode.VERIFIED) <NEW_LINE> assert utils.course_discussion_division_enabled(get_course_discussion_settings(self.course.id)) <NEW_LINE> assert [CourseDiscussionSettings.ENROLLMENT_TRACK] == utils.available_division_schemes(self.course.id)
Test the course_discussion_division_enabled and available_division_schemes methods.
62599049b5575c28eb7136ac
class PermissionRegistrationConflict(PermissionException): <NEW_LINE> <INDENT> def __init__(self, perm_name, new_view, old_view): <NEW_LINE> <INDENT> message = "Permission %s is already registered " % perm_name <NEW_LINE> message += "with view name %s. Cannot register " % old_view <NEW_LINE> message += "again with view %s." % new_view <NEW_LINE> super(PermissionRegistrationConflict, self).__init__(message)
Raised when a permission is registered with two different views.
6259904924f1403a926862b0
class Genres(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> data = {genre.id: genre.name for genre in Genre.objects.all()} <NEW_LINE> return JsonResponse(data)
View class that return Json encoded list of music genres available
62599049baa26c4b54d50670
class ArcadeOutputService: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clear_screen(self): <NEW_LINE> <INDENT> arcade.start_render() <NEW_LINE> <DEDENT> def draw_actor(self, actor): <NEW_LINE> <INDENT> actor.draw() <NEW_LINE> <DEDENT> def draw_actors(self, actors): <NEW_LINE> <INDENT> for actor in actors: <NEW_LINE> <INDENT> self.draw_actor(actor) <NEW_LINE> <DEDENT> <DEDENT> def flush_buffer(self): <NEW_LINE> <INDENT> pass
Outputs the game state. The responsibility of the class of objects is to draw the game state on the terminal. Stereotype: Service Provider Attributes: _screen (Screen): An Asciimatics screen.
62599049507cdc57c63a6165
class TargetAT(object): <NEW_LINE> <INDENT> def __init__(self, enemy, player_list): <NEW_LINE> <INDENT> self.enemy = enemy <NEW_LINE> self.player_list = player_list <NEW_LINE> <DEDENT> def find_AT_target(self): <NEW_LINE> <INDENT> if self.enemy.AT is None: <NEW_LINE> <INDENT> self.__create_AT() <NEW_LINE> <DEDENT> target = self.enemy.AT.player <NEW_LINE> return target <NEW_LINE> <DEDENT> def __create_AT(self): <NEW_LINE> <INDENT> player = self.__elite_targeting() <NEW_LINE> self.enemy.AT = AggressionToken(self.enemy, player) <NEW_LINE> <DEDENT> def __elite_targeting(self): <NEW_LINE> <INDENT> role = self.enemy.Role_Name <NEW_LINE> if role == 'Champion': <NEW_LINE> <INDENT> valid_target = [] <NEW_LINE> lowest_armor = None <NEW_LINE> for player in self.player_list: <NEW_LINE> <INDENT> if lowest_armor is None: <NEW_LINE> <INDENT> valid_target.append(player) <NEW_LINE> lowest_armor = player.Armor.value <NEW_LINE> <DEDENT> elif lowest_armor > player.Armor.value: <NEW_LINE> <INDENT> valid_target.clear() <NEW_LINE> valid_target.append(player) <NEW_LINE> lowest_armor = player.Armor.value <NEW_LINE> <DEDENT> elif lowest_armor == player.Armor.value: <NEW_LINE> <INDENT> valid_target.append(player) <NEW_LINE> <DEDENT> <DEDENT> if len(valid_target) == 1: <NEW_LINE> <INDENT> return valid_target[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TargetNearest(self.enemy, valid_target).find_nearest_player() <NEW_LINE> <DEDENT> <DEDENT> elif role == 'Caster': <NEW_LINE> <INDENT> valid_target = [] <NEW_LINE> highest_armor = None <NEW_LINE> for player in self.player_list: <NEW_LINE> <INDENT> if highest_armor is None: <NEW_LINE> <INDENT> valid_target.append(player) <NEW_LINE> highest_armor = player.Armor.value <NEW_LINE> <DEDENT> elif highest_armor < player.Armor.value: <NEW_LINE> <INDENT> valid_target.clear() <NEW_LINE> valid_target.append(player) <NEW_LINE> highest_armor = player.Armor.value <NEW_LINE> <DEDENT> elif highest_armor == player.Armor.value: <NEW_LINE> <INDENT> valid_target.append(player) <NEW_LINE> <DEDENT> <DEDENT> if len(valid_target) == 1: <NEW_LINE> <INDENT> return valid_target[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TargetNearest(self.enemy, valid_target).find_nearest_player() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __get_distance(self, enemy, player): <NEW_LINE> <INDENT> x = abs(enemy.Position[0] - player.Position[0]) <NEW_LINE> y = abs(enemy.Position[1] - player.Position[1]) <NEW_LINE> return x + y
Special targeting that only Elites use. Creates an Aggression Token and "gives" it to the Player which fulfills its targeting restriction. If an Elite already has an Aggression Token in effect, it uses it instead of creating a new one.
6259904950485f2cf55dc350
class MixtureMember(object): <NEW_LINE> <INDENT> def __init__(self, distribution, name=''): <NEW_LINE> <INDENT> self.distribution = distribution <NEW_LINE> self.name = name <NEW_LINE> self.parameters = {} <NEW_LINE> <DEDENT> def pdf(self, X): <NEW_LINE> <INDENT> return self.distribution.pdf(X, **self.parameters) <NEW_LINE> <DEDENT> def cdf(self, X): <NEW_LINE> <INDENT> return self.distribution.cdf(X, **self.parameters)
Base class for mixture member.
625990493cc13d1c6d466aff
class LoggerPlus(logging.Logger): <NEW_LINE> <INDENT> def __init__(self, name, level=logging.NOTSET): <NEW_LINE> <INDENT> logging.Logger.__init__(self, name, level) <NEW_LINE> <DEDENT> def pipelinetrace(self, pipeline_part, msg, *args, **kwargs): <NEW_LINE> <INDENT> if pipeline_part in alpha2aleph.cfgini.CFGINI["pipeline.trace"]["yes"]: <NEW_LINE> <INDENT> return logging.Logger.info(self, "["+pipeline_part+"] "+msg, *args, **kwargs) <NEW_LINE> <DEDENT> elif pipeline_part not in alpha2aleph.cfgini.CFGINI["pipeline.trace"]["no"]: <NEW_LINE> <INDENT> raise RuntimeError("Undefined pipeline part '{0}' " "in the configuration file.".format(pipeline_part)) <NEW_LINE> <DEDENT> return None
LoggerPlus class
62599049cad5886f8bdc5a62
class Car(): <NEW_LINE> <INDENT> def __init__(self, make, model, year): <NEW_LINE> <INDENT> self.make = make <NEW_LINE> self.model = model <NEW_LINE> self.year = year <NEW_LINE> self.odometer_reading = 0 <NEW_LINE> <DEDENT> def get_descriptive_name(self): <NEW_LINE> <INDENT> long_name = str(self.year) + ' ' + self.make + ' ' + self.model <NEW_LINE> return long_name.title() <NEW_LINE> <DEDENT> def read_odometer(self): <NEW_LINE> <INDENT> print("This cat has " + str(self.odometer_reading) + " miles on it") <NEW_LINE> <DEDENT> def update_odometer(self, mileage): <NEW_LINE> <INDENT> if mileage >= self.odometer_reading: <NEW_LINE> <INDENT> self.odometer_reading = mileage <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("你不能回调里程表") <NEW_LINE> <DEDENT> <DEDENT> def increment_odometer(self, miles): <NEW_LINE> <INDENT> self.odometer_reading += miles <NEW_LINE> <DEDENT> def fill_gas_tank(self, litre): <NEW_LINE> <INDENT> self.liter = litre <NEW_LINE> print("油箱剩余油量" + str(self.liter) + "L")
给定实参
6259904907f4c71912bb07fa
class AllergicAdopter(Adopter): <NEW_LINE> <INDENT> def __init__(self, name, desired_species, allergic_species): <NEW_LINE> <INDENT> Adopter.__init__(self, name, desired_species) <NEW_LINE> self.allergic_species = allergic_species <NEW_LINE> <DEDENT> def get_score(self, adoption_center): <NEW_LINE> <INDENT> list = set(self.allergic_species).intersection(adoption_center.get_species_count()) <NEW_LINE> <DEDENT> def get_score(self, adoption_center): <NEW_LINE> <INDENT> list = [] <NEW_LINE> list = set(self.allergic_species).intersection(adoption_center.get_species_count()) <NEW_LINE> if len(list) == 0: <NEW_LINE> <INDENT> return Adopter.get_score(self, adoption_center) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.0
An AllergicAdopter is extremely allergic to a one or more species and cannot even be around it a little bit! If the adoption center contains one or more of these animals, they will not go there. Score should be 0 if the center contains any of the animals, or 1x number of desired animals if not
6259904915baa72349463359
class AST1(AST2, AST0): <NEW_LINE> <INDENT> def __new__(cls, *args, **kw): <NEW_LINE> <INDENT> new_args = [AST_adapt(arg) for arg in args] <NEW_LINE> new_kw = {k: AST_adapt(v) for k, v in kw.items()} <NEW_LINE> self = super().__new__(cls, *new_args, **new_kw) <NEW_LINE> raspon = obuhvati(itertools.chain(args, kw.values())) <NEW_LINE> if raspon: self._početak, self._kraj = raspon <NEW_LINE> return self
Tip apstraktnog sintaksnog stabla.
6259904929b78933be26aaa6
class TraitsController(rest.RestController): <NEW_LINE> <INDENT> @requires_admin <NEW_LINE> @wsme_pecan.wsexpose([Trait], wtypes.text, wtypes.text) <NEW_LINE> def get_one(self, event_type, trait_name): <NEW_LINE> <INDENT> LOG.debug(_("Getting traits for %s") % event_type) <NEW_LINE> return [Trait(name=t.name, type=t.get_type_name(), value=t.value) for t in pecan.request.storage_conn .get_traits(event_type, trait_name)] <NEW_LINE> <DEDENT> @requires_admin <NEW_LINE> @wsme_pecan.wsexpose([TraitDescription], wtypes.text) <NEW_LINE> def get_all(self, event_type): <NEW_LINE> <INDENT> get_trait_name = storage.models.Trait.get_name_by_type <NEW_LINE> return [TraitDescription(name=t['name'], type=get_trait_name(t['data_type'])) for t in pecan.request.storage_conn .get_trait_types(event_type)]
Works on Event Traits.
6259904994891a1f408ba0d9
class SoftDeletionUserQuerySet(QuerySet): <NEW_LINE> <INDENT> def delete(self, **kwargs): <NEW_LINE> <INDENT> return super(SoftDeletionUserQuerySet, self).update(deleted_at=timezone.now(), is_active=False, deleted_by = kwargs.pop('user',None)) <NEW_LINE> <DEDENT> def hard_delete(self): <NEW_LINE> <INDENT> return super(SoftDeletionUserQuerySet, self).delete() <NEW_LINE> <DEDENT> def alive(self): <NEW_LINE> <INDENT> return self.filter(deleted_at=None) <NEW_LINE> <DEDENT> def dead(self): <NEW_LINE> <INDENT> return self.exclude(deleted_at=None)
QuerySet que va de la mano con "SoftDeletionUserManager" Toma el mismo comportamiento definido en el Modelo, implementando el marcado en lugar de la eliminación real, para un conjunto de instancias (en lugar de una, como sucede en el Modelo)
6259904923e79379d538d8c6
class FilesystemWatchMixin (object): <NEW_LINE> <INDENT> def monitor_directories(self, *directories, **kwargs): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> force = kwargs.get('force', False) <NEW_LINE> for directory in directories: <NEW_LINE> <INDENT> gfile = Gio.File.new_for_path(directory) <NEW_LINE> if not force and not gfile.query_exists(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None) <NEW_LINE> <DEDENT> except GLib.GError as exc: <NEW_LINE> <INDENT> pretty.print_debug(__name__, "FilesystemWatchMixin", exc) <NEW_LINE> continue <NEW_LINE> <DEDENT> if monitor: <NEW_LINE> <INDENT> monitor.connect("changed", self.__directory_changed) <NEW_LINE> tokens.append(monitor) <NEW_LINE> <DEDENT> <DEDENT> return NonpersistentToken(tokens) <NEW_LINE> <DEDENT> def monitor_include_file(self, gfile): <NEW_LINE> <INDENT> return not (gfile and gfile.get_basename().startswith(".")) <NEW_LINE> <DEDENT> def __directory_changed(self, monitor, file1, file2, evt_type): <NEW_LINE> <INDENT> if (evt_type in (Gio.FileMonitorEvent.CREATED, Gio.FileMonitorEvent.DELETED) and self.monitor_include_file(file1)): <NEW_LINE> <INDENT> self.mark_for_update()
A mixin for Sources watching directories
6259904930c21e258be99bce
class TimedOutError(MessageQueueError): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TimedOutError, self).__init__( "Timed out waiting for the message queue.")
Raised when a message queue operation times out.
6259904924f1403a926862b1
class SmoothenValue: <NEW_LINE> <INDENT> def __init__(self, beta: float = 0.98): <NEW_LINE> <INDENT> self.beta, self.n, self.mov_avg = beta, 0, 0 <NEW_LINE> <DEDENT> def __call__(self, val: float): <NEW_LINE> <INDENT> self.n += 1 <NEW_LINE> self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val <NEW_LINE> smooth = self.mov_avg / (1 - self.beta ** self.n) <NEW_LINE> return smooth
Create a smooth moving average for a value (loss, etc).
62599049ec188e330fdf9c65
class BiCounter(Mapping): <NEW_LINE> <INDENT> def __init__(self, iterable=None): <NEW_LINE> <INDENT> self.item_to_freq = defaultdict(lambda: 0) <NEW_LINE> self.freq_to_items = defaultdict(set) <NEW_LINE> self.largest_count = 0 <NEW_LINE> if iterable is not None: <NEW_LINE> <INDENT> for item in iterable: <NEW_LINE> <INDENT> self.increment(item) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def increment(self, item): <NEW_LINE> <INDENT> freq = self.item_to_freq.get(item, 0) <NEW_LINE> if freq > 0: <NEW_LINE> <INDENT> self.freq_to_items[freq].remove(item) <NEW_LINE> <DEDENT> self.freq_to_items[freq + 1].add(item) <NEW_LINE> self.item_to_freq[item] += 1 <NEW_LINE> if freq == self.largest_count: <NEW_LINE> <INDENT> self.largest_count += 1 <NEW_LINE> <DEDENT> if not self.freq_to_items[freq]: <NEW_LINE> <INDENT> del self.freq_to_items[freq] <NEW_LINE> <DEDENT> <DEDENT> def decrement(self, item): <NEW_LINE> <INDENT> freq = self.item_to_freq.get(item, 0) <NEW_LINE> if not freq: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.freq_to_items[freq].remove(item) <NEW_LINE> if freq > 1: <NEW_LINE> <INDENT> self.freq_to_items[freq - 1].add(item) <NEW_LINE> self.item_to_freq[item] -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del self.item_to_freq[item] <NEW_LINE> <DEDENT> if not self.get_most_common(): <NEW_LINE> <INDENT> self.largest_count -= 1 <NEW_LINE> del self.freq_to_items[freq] <NEW_LINE> <DEDENT> <DEDENT> def get_most_common(self): <NEW_LINE> <INDENT> return self.freq_to_items[self.largest_count] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.item_to_freq) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.item_to_freq) <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return item in self.item_to_freq <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.item_to_freq[item]
Bi-directional counter. Maps items to a count, and maps the counts to a set of items. Examples -------- >>> bc = BiCounter() >>> bc.increment("a") >>> bc.increment("b") >>> bc.increment("c") >>> bc.increment("a") >>> bc.increment("b") >>> bc.get_most_common() {"a", "b"} >>> bc.decrement("b") >>> bc.get_most_common() {"a"} Parameters ---------- iterable : optional iterable to initialise with
62599049498bea3a75a58ee7
class ConfigServerSettingsValidateResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'is_valid': {'key': 'isValid', 'type': 'bool'}, 'details': {'key': 'details', 'type': '[ConfigServerSettingsErrorRecord]'}, } <NEW_LINE> def __init__( self, *, is_valid: Optional[bool] = None, details: Optional[List["ConfigServerSettingsErrorRecord"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ConfigServerSettingsValidateResult, self).__init__(**kwargs) <NEW_LINE> self.is_valid = is_valid <NEW_LINE> self.details = details
Validation result for config server settings. :ivar is_valid: Indicate if the config server settings are valid. :vartype is_valid: bool :ivar details: The detail validation results. :vartype details: list[~azure.mgmt.appplatform.v2020_11_01_preview.models.ConfigServerSettingsErrorRecord]
62599049462c4b4f79dbcdc8
@utils.use_signature(core.TopLevelConcatSpec) <NEW_LINE> class ConcatChart(TopLevelMixin, core.TopLevelConcatSpec): <NEW_LINE> <INDENT> def __init__(self, data=Undefined, concat=(), columns=Undefined, **kwargs): <NEW_LINE> <INDENT> for spec in concat: <NEW_LINE> <INDENT> _check_if_valid_subspec(spec, "ConcatChart") <NEW_LINE> <DEDENT> super(ConcatChart, self).__init__( data=data, concat=list(concat), columns=columns, **kwargs ) <NEW_LINE> self.data, self.concat = _combine_subchart_data(self.data, self.concat) <NEW_LINE> <DEDENT> def __ior__(self, other): <NEW_LINE> <INDENT> _check_if_valid_subspec(other, "ConcatChart") <NEW_LINE> self.concat.append(other) <NEW_LINE> self.data, self.concat = _combine_subchart_data(self.data, self.concat) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> copy = self.copy(deep=["concat"]) <NEW_LINE> copy |= other <NEW_LINE> return copy <NEW_LINE> <DEDENT> def add_parameter(self, *params): <NEW_LINE> <INDENT> if not params or not self.concat: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> copy = self.copy() <NEW_LINE> copy.concat = [chart.add_parameter(*params) for chart in copy.concat] <NEW_LINE> return copy <NEW_LINE> <DEDENT> def add_selection(self, *selections): <NEW_LINE> <INDENT> warnings.warn( """'add_selection' is deprecated. Use 'add_parameter'""", DeprecationWarning, ) <NEW_LINE> return self.add_parameter(*selections)
A chart with horizontally-concatenated facets
62599049a8ecb033258725da
class V1DaemonSetCondition(object): <NEW_LINE> <INDENT> swagger_types = { 'last_transition_time': 'datetime', 'message': 'str', 'reason': 'str', 'status': 'str', 'type': 'str' } <NEW_LINE> attribute_map = { 'last_transition_time': 'lastTransitionTime', 'message': 'message', 'reason': 'reason', 'status': 'status', 'type': 'type' } <NEW_LINE> def __init__(self, last_transition_time=None, message=None, reason=None, status=None, type=None): <NEW_LINE> <INDENT> self._last_transition_time = None <NEW_LINE> self._message = None <NEW_LINE> self._reason = None <NEW_LINE> self._status = None <NEW_LINE> self._type = None <NEW_LINE> self.discriminator = None <NEW_LINE> if last_transition_time is not None: <NEW_LINE> <INDENT> self.last_transition_time = last_transition_time <NEW_LINE> <DEDENT> if message is not None: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> if reason is not None: <NEW_LINE> <INDENT> self.reason = reason <NEW_LINE> <DEDENT> self.status = status <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_transition_time(self): <NEW_LINE> <INDENT> return self._last_transition_time <NEW_LINE> <DEDENT> @last_transition_time.setter <NEW_LINE> def last_transition_time(self, last_transition_time): <NEW_LINE> <INDENT> self._last_transition_time = last_transition_time <NEW_LINE> <DEDENT> @property <NEW_LINE> def message(self): <NEW_LINE> <INDENT> return self._message <NEW_LINE> <DEDENT> @message.setter <NEW_LINE> def message(self, message): <NEW_LINE> <INDENT> self._message = message <NEW_LINE> <DEDENT> @property <NEW_LINE> def reason(self): <NEW_LINE> <INDENT> return self._reason <NEW_LINE> <DEDENT> @reason.setter <NEW_LINE> def reason(self, reason): <NEW_LINE> <INDENT> self._reason = reason <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._status <NEW_LINE> <DEDENT> @status.setter <NEW_LINE> def status(self, status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `status`, must not be `None`") <NEW_LINE> <DEDENT> self._status = status <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> if type is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `type`, must not be `None`") <NEW_LINE> <DEDENT> self._type = type <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in self.swagger_types.items(): <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> 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, V1DaemonSetCondition): <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
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904907d97122c421806b
class Exception(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def ice_name(self): <NEW_LINE> <INDENT> return self.ice_id()[2:] <NEW_LINE> <DEDENT> def ice_id(self): <NEW_LINE> <INDENT> return self._ice_id
The base class for all Ice exceptions.
6259904907d97122c421806c
class TestBillingUpdate(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testBillingUpdate(self): <NEW_LINE> <INDENT> pass
BillingUpdate unit test stubs
6259904a07f4c71912bb07fc
class Batch: <NEW_LINE> <INDENT> def __init__(self, transport_loop): <NEW_LINE> <INDENT> self.messaging_stack = MessagingStack(transport_loop) <NEW_LINE> self.protocol_printer = Printer(prefix=(batch.RESPONSE_PREFIX)) <NEW_LINE> self.command_printer = MessagePrinter(prefix=' Sending: ') <NEW_LINE> self.protocol = Protocol( self.messaging_stack.connection_synchronizer, response_receivers=[self.protocol_printer], command_receivers=[self.command_printer] ) <NEW_LINE> self.response_printer = MessagePrinter(prefix=batch.RESPONSE_PREFIX) <NEW_LINE> self.messaging_stack.register_response_receivers(self.response_printer) <NEW_LINE> self.messaging_stack.register_response_receivers(self.protocol) <NEW_LINE> self.messaging_stack.register_command_senders(self.protocol) <NEW_LINE> self.batch_execution_manager = BatchExecutionManager( self.messaging_stack.arbiter, self.messaging_stack.command_sender, self.test_routine, header=batch.OUTPUT_HEADER, ready_waiter=self.messaging_stack.connection_synchronizer.wait_connected ) <NEW_LINE> self.messaging_stack.register_execution_manager(self.batch_execution_manager) <NEW_LINE> <DEDENT> async def test_routine(self): <NEW_LINE> <INDENT> print('Running test routine...') <NEW_LINE> await asyncio.sleep(1.0) <NEW_LINE> print('RPC-style with completion wait:') <NEW_LINE> await self.protocol.request_complete() <NEW_LINE> await asyncio.sleep(2.0) <NEW_LINE> print(batch.RESPONSE_PREFIX + 'Reset completed!') <NEW_LINE> print('RPC-style with acknowledgement response wait:') <NEW_LINE> await self.protocol.request() <NEW_LINE> print(batch.RESPONSE_PREFIX + 'Reset command acknowledged!') <NEW_LINE> await self.messaging_stack.connection_synchronizer.disconnected.wait() <NEW_LINE> print(batch.RESPONSE_PREFIX + 'Connection lost!') <NEW_LINE> await self.messaging_stack.connection_synchronizer.connected.wait() <NEW_LINE> print(batch.RESPONSE_PREFIX + 'Reset completed!') <NEW_LINE> await asyncio.sleep(2.0) <NEW_LINE> await asyncio.sleep(2.0) <NEW_LINE> print(batch.OUTPUT_FOOTER) <NEW_LINE> print('Quitting...')
Actor-based batch execution.
6259904ad4950a0f3b111827
class FeatureNames(object): <NEW_LINE> <INDENT> STORY = 'story' <NEW_LINE> QUESTION = 'question' <NEW_LINE> ANSWER = 'answer' <NEW_LINE> @classmethod <NEW_LINE> def features(cls): <NEW_LINE> <INDENT> for attr, value in cls.__dict__.items(): <NEW_LINE> <INDENT> if not attr.startswith('__') and not callable(getattr(cls, attr)): <NEW_LINE> <INDENT> yield value
Feature names, i.e keys for storing babi_qa data in TFExamples.
6259904a8a43f66fc4bf355f
class PolkitTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def __init__(self, methodName='runTest'): <NEW_LINE> <INDENT> unittest.TestCase.__init__(self, methodName) <NEW_LINE> self.polkit_pid = None <NEW_LINE> <DEDENT> def start_polkitd(self, allowed_actions, on_bus=None): <NEW_LINE> <INDENT> assert self.polkit_pid is None, 'can only launch one polkitd at a time; write a separate test case or call stop_polkitd()' <NEW_LINE> self.polkit_pid = spawn(allowed_actions, on_bus) <NEW_LINE> self.addCleanup(self.stop_polkitd) <NEW_LINE> <DEDENT> def stop_polkitd(self): <NEW_LINE> <INDENT> assert self.polkit_pid is not None, 'polkitd is not running' <NEW_LINE> os.kill(self.polkit_pid, signal.SIGTERM) <NEW_LINE> os.waitpid(self.polkit_pid, 0) <NEW_LINE> self.polkit_pid = None
Convenient test cases involving polkit. Call start_polkitd() with the list of allowed actions in your test cases. The daemon will be automatically terminated when the test case exits.
6259904adc8b845886d54985
class Flow(JsonObject): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.table_id = kwargs.get('table_id', None) <NEW_LINE> self.priority = kwargs.get('priority', None) <NEW_LINE> self.match = kwargs.get('match', None) <NEW_LINE> self.duration_sec = kwargs.get('duration_sec', None) <NEW_LINE> self.duration_nsec = kwargs.get('duration_nsec', None) <NEW_LINE> self.idle_timeout = kwargs.get('idle_timeout', None) <NEW_LINE> self.hard_timeout = kwargs.get('hard_timeout', None) <NEW_LINE> self.packet_count = kwargs.get('packet_count', None) <NEW_LINE> self.byte_count = kwargs.get('byte_count', None) <NEW_LINE> self.cookie = kwargs.get('cookie', None) <NEW_LINE> self.cookie_mask = kwargs.get('cookie_mask', None) <NEW_LINE> self.buffer_id = kwargs.get('buffer_id', None) <NEW_LINE> self.out_port = kwargs.get('out_port', None) <NEW_LINE> self.flow_mod_cmd = kwargs.get('flow_mod_cmd', None) <NEW_LINE> self.flow_mod_flags = kwargs.get('flow_mod_flags', []) <NEW_LINE> self.instructions = kwargs.get('instructions', []) <NEW_LINE> self.actions = kwargs.get('actions', []) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def factory(cls, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cm = CLASS_MAP[cls.__name__] <NEW_LINE> for key in data: <NEW_LINE> <INDENT> if key == 'match': <NEW_LINE> <INDENT> new_match = {} <NEW_LINE> for d in data[key]: <NEW_LINE> <INDENT> for k in d: <NEW_LINE> <INDENT> new_match[k] = d[k] <NEW_LINE> <DEDENT> <DEDENT> data[key] = JsonObjectFactory.create('Match', new_match) <NEW_LINE> <DEDENT> elif key == 'actions': <NEW_LINE> <INDENT> new_action = {} <NEW_LINE> keys = [] <NEW_LINE> for d in data[key]: <NEW_LINE> <INDENT> keys.extend([(k, v) for k, v in d.items()]) <NEW_LINE> <DEDENT> num_keys = range(len(keys)) <NEW_LINE> duplicates = {} <NEW_LINE> for i in num_keys: <NEW_LINE> <INDENT> key_name = keys[i][0] <NEW_LINE> if key_name in duplicates: <NEW_LINE> <INDENT> duplicates[key_name].append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> duplicates[key_name] = [i] <NEW_LINE> <DEDENT> <DEDENT> for k, v in duplicates.items(): <NEW_LINE> <INDENT> if len(v) > 1: <NEW_LINE> <INDENT> new_action[k] = [keys[i][1] for i in v] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_action[k] = keys[i][1] <NEW_LINE> <DEDENT> <DEDENT> data[key] = JsonObjectFactory.create('Action', new_action) <NEW_LINE> <DEDENT> elif key in cm and isinstance(data[key], list): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for d in data[key]: <NEW_LINE> <INDENT> l.append(JsonObjectFactory.create(cm[key], d)) <NEW_LINE> <DEDENT> data[key] = l <NEW_LINE> <DEDENT> elif key in cm: <NEW_LINE> <INDENT> data[key] = JsonObjectFactory.create(cm[key], data[key]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return cls(**data)
Flow (JsonObject) Una representación pitón del objeto de flujo
6259904a45492302aabfd89d
class MessageDispatcher(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.recipients = {} <NEW_LINE> <DEDENT> def add(self, transport, address=None): <NEW_LINE> <INDENT> if not address: <NEW_LINE> <INDENT> address = str(uuid.uuid1()) <NEW_LINE> <DEDENT> if address in self.recipients: <NEW_LINE> <INDENT> self.recipients[address].add(transport) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.recipients[address] = RecipientManager(transport, address) <NEW_LINE> <DEDENT> return address <NEW_LINE> <DEDENT> def remove(self, transport): <NEW_LINE> <INDENT> recipients = copy.copy(self.recipients) <NEW_LINE> for address, recManager in recipients.iteritems(): <NEW_LINE> <INDENT> recManager.remove(transport) <NEW_LINE> if not len(recManager.transports): <NEW_LINE> <INDENT> del self.recipients[address] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def send(self, address, data_dict): <NEW_LINE> <INDENT> if type(address) == list: <NEW_LINE> <INDENT> recipients = [self.recipients.get(rec) for rec in address] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> recipients = [self.recipients.get(address)] <NEW_LINE> <DEDENT> if recipients: <NEW_LINE> <INDENT> for recipient in recipients: <NEW_LINE> <INDENT> if recipient: <NEW_LINE> <INDENT> recipient.send(json.dumps(data_dict)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def subscribe(self, transport, data): <NEW_LINE> <INDENT> self.add(transport, address=data.get('hx_subscribe')) <NEW_LINE> self.send( data.get('hx_subscribe'), {'message': "%r is listening" % transport} )
MessageDispatcher is a PubSub state machine that routes data packets through an attribute called "recipients". The recipients attribute is a dict structure where the keys are unique addresses and the values are instances of RecipientManager. "address"es (i.e. RecipientManagers) are created and/or subscribed to. Subscribing to an address results in registering a clientswebsocket (i.e. the transport associated to the SockJSResource protocol) within a dict that is internal to the Manager called "transports". RecipientManager's purpose is to expose functions that MessageDispatcher can leverage to execute the PubSub process. N.B. subscribing a client to an address opens that client to all data published to that address. As such it useful to think of addresses as channels. To acheive a private channel an obsure address is required.
6259904ad6c5a102081e34e6
class SwapGate(TwoQubitGate): <NEW_LINE> <INDENT> gate_name = 'SWAP' <NEW_LINE> gate_name_latex = 'SWAP' <NEW_LINE> def get_target_matrix(self, format='sympy'): <NEW_LINE> <INDENT> return matrix_cache.get_matrix('SWAP', format) <NEW_LINE> <DEDENT> def decompose(self, **options): <NEW_LINE> <INDENT> i, j = self.targets[0], self.targets[1] <NEW_LINE> g1 = CNotGate(i, j) <NEW_LINE> g2 = CNotGate(j, i) <NEW_LINE> return g1*g2*g1 <NEW_LINE> <DEDENT> def plot_gate(self, circ_plot, gate_idx): <NEW_LINE> <INDENT> min_wire = int(_min(self.targets)) <NEW_LINE> max_wire = int(_max(self.targets)) <NEW_LINE> circ_plot.control_line(gate_idx, min_wire, max_wire) <NEW_LINE> circ_plot.swap_point(gate_idx, min_wire) <NEW_LINE> circ_plot.swap_point(gate_idx, max_wire) <NEW_LINE> <DEDENT> def _represent_ZGate(self, basis, **options): <NEW_LINE> <INDENT> format = options.get('format', 'sympy') <NEW_LINE> targets = [int(t) for t in self.targets] <NEW_LINE> min_target = _min(targets) <NEW_LINE> max_target = _max(targets) <NEW_LINE> nqubits = options.get('nqubits', self.min_qubits) <NEW_LINE> op01 = matrix_cache.get_matrix('op01', format) <NEW_LINE> op10 = matrix_cache.get_matrix('op10', format) <NEW_LINE> op11 = matrix_cache.get_matrix('op11', format) <NEW_LINE> op00 = matrix_cache.get_matrix('op00', format) <NEW_LINE> eye2 = matrix_cache.get_matrix('eye2', format) <NEW_LINE> result = None <NEW_LINE> for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): <NEW_LINE> <INDENT> product = nqubits*[eye2] <NEW_LINE> product[nqubits - min_target - 1] = i <NEW_LINE> product[nqubits - max_target - 1] = j <NEW_LINE> new_result = matrix_tensor_product(*product) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> result = new_result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = result + new_result <NEW_LINE> <DEDENT> <DEDENT> return result
Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples ========
6259904a94891a1f408ba0da
class GcodeSet(YamlMixin, RstMixin): <NEW_LINE> <INDENT> def __init__(self, yaml_path): <NEW_LINE> <INDENT> data = self._load_yaml(yaml_path) <NEW_LINE> self._gcodes = {} <NEW_LINE> for gcode_txt, d in data.items(): <NEW_LINE> <INDENT> gcode = Gcode(gcode_txt, d['meaning']) <NEW_LINE> self._gcodes[gcode_txt] = gcode <NEW_LINE> <DEDENT> self._sorted_gcodes = None <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._gcodes) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._gcodes.values()) <NEW_LINE> <DEDENT> def __getitem__(self, code): <NEW_LINE> <INDENT> return self._gcodes[code] <NEW_LINE> <DEDENT> def __contains__(self, code): <NEW_LINE> <INDENT> return code in self._gcodes <NEW_LINE> <DEDENT> def _sort(self): <NEW_LINE> <INDENT> if self._sorted_gcodes is None: <NEW_LINE> <INDENT> items = list(self) <NEW_LINE> items.sort(key=lambda item: str(ord(item.gcode[0])*1000) + item.gcode[1:]) <NEW_LINE> self._sorted_gcodes = items <NEW_LINE> <DEDENT> return self._sorted_gcodes <NEW_LINE> <DEDENT> def sorted_iter(self): <NEW_LINE> <INDENT> return iter(self._sort()) <NEW_LINE> <DEDENT> def iter_on_slice(self, start, stop): <NEW_LINE> <INDENT> start_index = None <NEW_LINE> stop_index = None <NEW_LINE> for i, item in enumerate(self._sort()): <NEW_LINE> <INDENT> if item.gcode == start: <NEW_LINE> <INDENT> start_index = i <NEW_LINE> <DEDENT> elif item.gcode == stop: <NEW_LINE> <INDENT> stop_index = i <NEW_LINE> <DEDENT> <DEDENT> if start_index > stop_index: <NEW_LINE> <INDENT> raise ValueError('{} > {}'.format(start, stop)) <NEW_LINE> <DEDENT> return iter(self._sorted_gcodes[start_index:stop_index+1]) <NEW_LINE> <DEDENT> def to_rst(self, path): <NEW_LINE> <INDENT> self._write_rst( path, headers=('G-code', 'Meaning'), columns=('gcode', 'meaning'), )
Class for the table of G-codes.
6259904a71ff763f4b5e8b6f
class BinaryPackage: <NEW_LINE> <INDENT> def __init__(self, package_type, package_path): <NEW_LINE> <INDENT> self.type = package_type <NEW_LINE> self.path = package_path <NEW_LINE> self.metadata = None <NEW_LINE> self.name = None <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> if self.metadata is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._load() <NEW_LINE> if not "name" in self.metadata: <NEW_LINE> <INDENT> raise Exception("Failed to load package. " "Expecting at least a 'name' key " "in package metadata") <NEW_LINE> <DEDENT> self.name = self.metadata["name"] <NEW_LINE> <DEDENT> def get_metadata(self): <NEW_LINE> <INDENT> if self.metadata is not None: <NEW_LINE> <INDENT> return self.metadata <NEW_LINE> <DEDENT> self.load() <NEW_LINE> return self.metadata <NEW_LINE> <DEDENT> def _load(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def extract(self, dest_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> res = "Binary package:\n" <NEW_LINE> res += ' Type: {0}\n'.format(self.type) <NEW_LINE> res += ' Path: {0}\n'.format(self.path) <NEW_LINE> res += ' Metadata:\n' <NEW_LINE> res += pprint.pformat(self.metadata, indent=2) <NEW_LINE> return res
A binary package is the endpoint of a binary package file provided by most of the Linux distribution. It stores metadata read from the binary package itself.
6259904a24f1403a926862b2
class CustomerInformation( BaseSettingsForm ): <NEW_LINE> <INDENT> form_fields = form.Fields(interfaces.IGetPaidManagementCustomerInformation)
get paid management interface
6259904a07d97122c421806e
class BlockV2(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, channels_num, **kwargs): <NEW_LINE> <INDENT> super(BlockV2, self).__init__(**kwargs) <NEW_LINE> self.body1 = nn.HybridSequential(prefix='') <NEW_LINE> self.body1.add(nn.Conv3D(channels=channels_num, kernel_size=(3, 3, 3), strides=(2, 2, 2), padding=(1, 1, 1)), nn.BatchNorm(epsilon=0.0001), nn.Activation('relu'), nn.Conv3D(channels=channels_num, kernel_size=(3, 3, 3), strides=(1, 1, 1), padding=(1, 1, 1))) <NEW_LINE> self.body2 = nn.HybridSequential(prefix='') <NEW_LINE> self.body2.add(nn.Conv3D(channels=channels_num, kernel_size=(3, 3, 3), strides=(2, 2, 2), padding=(1, 1, 1))) <NEW_LINE> <DEDENT> def hybrid_forward(self, F, x, *args, **kwargs): <NEW_LINE> <INDENT> x1 = self.body1(x) <NEW_LINE> x2 = self.body2(x) <NEW_LINE> return x1 + x2
Component of 3D branch.
6259904a6e29344779b01a0c
class BaseDeathPenalty(object): <NEW_LINE> <INDENT> def __init__(self, timeout, exception=JobTimeoutException): <NEW_LINE> <INDENT> self._timeout = timeout <NEW_LINE> self._exception = exception <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.setup_death_penalty() <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cancel_death_penalty() <NEW_LINE> <DEDENT> except BaseTimeoutException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def setup_death_penalty(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def cancel_death_penalty(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Base class to setup job timeouts.
6259904a7cff6e4e811b6e05
class paymentMethodIdProp(SchemaProperty): <NEW_LINE> <INDENT> _prop_schema = 'paymentMethodId' <NEW_LINE> _expected_schema = None <NEW_LINE> _enum = False <NEW_LINE> _format_as = "TextField"
SchemaField for paymentMethodId Usage: Include in SchemaObject SchemaFields as your_django_field = paymentMethodIdProp() schema.org description:An identifier for the method of payment used (e.g. the last 4 digits of the credit card). prop_schema returns just the property without url# format_as is used by app templatetags based upon schema.org datatype
6259904a82261d6c527308ab
class Critter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> print("Появилась на свет новая зверюшка!") <NEW_LINE> <DEDENT> def talk(self): <NEW_LINE> <INDENT> print("Привет. Я зверюшка - экземпляр класса Critter.")
Виртуальный питомец
6259904a711fe17d825e1683
class TestMemberCreateRequestBody(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testMemberCreateRequestBody(self): <NEW_LINE> <INDENT> pass
MemberCreateRequestBody unit test stubs
6259904a73bcbd0ca4bcb659
class MonitoringStation: <NEW_LINE> <INDENT> def __init__(self, station_id, measure_id, label, coord, typical_range, river, town): <NEW_LINE> <INDENT> self.station_id = station_id <NEW_LINE> self.measure_id = measure_id <NEW_LINE> self.name = label <NEW_LINE> if isinstance(label, list): <NEW_LINE> <INDENT> self.name = label[0] <NEW_LINE> <DEDENT> self.coord = coord <NEW_LINE> self.typical_range = typical_range <NEW_LINE> self.river = river <NEW_LINE> self.town = town <NEW_LINE> self.latest_level = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> d = "Station name: {}\n".format(self.name) <NEW_LINE> d += " id: {}\n".format(self.station_id) <NEW_LINE> d += " measure id: {}\n".format(self.measure_id) <NEW_LINE> d += " coordinate: {}\n".format(self.coord) <NEW_LINE> d += " town: {}\n".format(self.town) <NEW_LINE> d += " river: {}\n".format(self.river) <NEW_LINE> d += " typical range: {}".format(self.typical_range) <NEW_LINE> return d <NEW_LINE> <DEDENT> def typical_range_consistent(self): <NEW_LINE> <INDENT> if self.typical_range == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if type(self.typical_range[1]) != float: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif type(self.typical_range[0]) != float: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.typical_range[1] - self.typical_range[0] < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def relative_water_level(self): <NEW_LINE> <INDENT> current_level = self.latest_level <NEW_LINE> if self.typical_range_consistent() == True: <NEW_LINE> <INDENT> if type(self.latest_level)== float: <NEW_LINE> <INDENT> relative_level = (current_level - self.typical_range[0]) / (self.typical_range[1] - self.typical_range[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> relative_level = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> relative_level = None <NEW_LINE> <DEDENT> return relative_level
This class represents a river level monitoring station
6259904a30dc7b76659a0bfe
class VMwareHTTPWriteVmdk(VMwareHTTPFile): <NEW_LINE> <INDENT> def __init__(self, session, host, rp_ref, vm_folder_ref, vm_create_spec, vmdk_size): <NEW_LINE> <INDENT> self._session = session <NEW_LINE> self._vmdk_size = vmdk_size <NEW_LINE> self._progress = 0 <NEW_LINE> lease = session.invoke_api(session.vim, 'ImportVApp', rp_ref, spec=vm_create_spec, folder=vm_folder_ref) <NEW_LINE> session.wait_for_lease_ready(lease) <NEW_LINE> self._lease = lease <NEW_LINE> lease_info = session.invoke_api(vim_util, 'get_object_property', session.vim, lease, 'info') <NEW_LINE> url = self.find_vmdk_url(lease_info, host) <NEW_LINE> if not url: <NEW_LINE> <INDENT> msg = _("Could not retrieve URL from lease.") <NEW_LINE> LOG.exception(msg) <NEW_LINE> raise error_util.VimException(msg) <NEW_LINE> <DEDENT> LOG.info(_("Opening vmdk url: %s for write.") % url) <NEW_LINE> cookies = session.vim.client.options.transport.cookiejar <NEW_LINE> _urlparse = urlparse.urlparse(url) <NEW_LINE> scheme, netloc, path, params, query, fragment = _urlparse <NEW_LINE> if scheme == 'http': <NEW_LINE> <INDENT> conn = httplib.HTTPConnection(netloc) <NEW_LINE> <DEDENT> elif scheme == 'https': <NEW_LINE> <INDENT> conn = httplib.HTTPSConnection(netloc) <NEW_LINE> <DEDENT> if query: <NEW_LINE> <INDENT> path = path + '?' + query <NEW_LINE> <DEDENT> conn.putrequest('PUT', path) <NEW_LINE> conn.putheader('User-Agent', USER_AGENT) <NEW_LINE> conn.putheader('Content-Length', str(vmdk_size)) <NEW_LINE> conn.putheader('Overwrite', 't') <NEW_LINE> conn.putheader('Cookie', self._build_vim_cookie_headers(cookies)) <NEW_LINE> conn.putheader('Content-Type', 'binary/octet-stream') <NEW_LINE> conn.endheaders() <NEW_LINE> self.conn = conn <NEW_LINE> VMwareHTTPFile.__init__(self, conn) <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> self._progress += len(data) <NEW_LINE> LOG.debug("Written %s bytes to vmdk." % self._progress) <NEW_LINE> self.file_handle.send(data) <NEW_LINE> <DEDENT> def update_progress(self): <NEW_LINE> <INDENT> percent = int(float(self._progress) / self._vmdk_size * 100) <NEW_LINE> try: <NEW_LINE> <INDENT> LOG.debug("Updating progress to %s percent." % percent) <NEW_LINE> self._session.invoke_api(self._session.vim, 'HttpNfcLeaseProgress', self._lease, percent=percent) <NEW_LINE> <DEDENT> except error_util.VimException as ex: <NEW_LINE> <INDENT> LOG.exception(ex) <NEW_LINE> raise ex <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> state = self._session.invoke_api(vim_util, 'get_object_property', self._session.vim, self._lease, 'state') <NEW_LINE> if state == 'ready': <NEW_LINE> <INDENT> self._session.invoke_api(self._session.vim, 'HttpNfcLeaseComplete', self._lease) <NEW_LINE> LOG.debug("Lease released.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug("Lease is already in state: %s." % state) <NEW_LINE> <DEDENT> super(VMwareHTTPWriteVmdk, self).close()
Write VMDK over HTTP using VMware HttpNfcLease.
6259904a8e05c05ec3f6f840
class ListRule(ListItemRule): <NEW_LINE> <INDENT> type = 'list' <NEW_LINE> inside = False <NEW_LINE> def condition(self,block): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def action(self, block, handler): <NEW_LINE> <INDENT> if not self.inside and ListItemRule.condition(self,block): <NEW_LINE> <INDENT> handler.start(self.type) <NEW_LINE> self.inside = True <NEW_LINE> <DEDENT> elif self.inside and not ListItemRule.condition(self,block): <NEW_LINE> <INDENT> handler.end(self.type) <NEW_LINE> self.inside = False <NEW_LINE> <DEDENT> return False
A list begins between a block that is not a list item and a subsequent list item. It ends after the last consecutive list item.
6259904ab57a9660fecd2e48