code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FSMField(models.Field): <NEW_LINE> <INDENT> descriptor_class = FSMFieldDescriptor <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.protected = kwargs.pop('protected', False) <NEW_LINE> kwargs.setdefault('max_length', 50) <NEW_LINE> super(FSMField, self).__init__(*args, **kwargs) <NEW_LINE> self.transitions = [] <NEW_LINE> <DEDENT> def contribute_to_class(self, cls, name): <NEW_LINE> <INDENT> super(FSMField, self).contribute_to_class(cls, name) <NEW_LINE> setattr(cls, self.name, self.descriptor_class(self)) <NEW_LINE> if self.transitions: <NEW_LINE> <INDENT> setattr(cls, 'get_available_%s_transitions' % self.name, curry(get_available_FIELD_transitions, self)) <NEW_LINE> <DEDENT> <DEDENT> def get_internal_type(self): <NEW_LINE> <INDENT> return 'CharField'
State Machine support for Django model
62598fbb097d151d1a2c11d0
class PetterssonM500BatMic(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._device = None <NEW_LINE> self._endpoint_out = None <NEW_LINE> self._endpoint_in = None <NEW_LINE> self._init_sound_card() <NEW_LINE> <DEDENT> def start_stream(self): <NEW_LINE> <INDENT> self._send_command('01') <NEW_LINE> <DEDENT> def stop_stream(self): <NEW_LINE> <INDENT> self._send_command('04') <NEW_LINE> <DEDENT> def read_stream(self): <NEW_LINE> <INDENT> return self._endpoint_in.read(0x10000, 2000) <NEW_LINE> <DEDENT> def led_on(self): <NEW_LINE> <INDENT> self._send_command('03') <NEW_LINE> <DEDENT> def led_flash(self): <NEW_LINE> <INDENT> self._send_command('02') <NEW_LINE> <DEDENT> def _init_sound_card(self): <NEW_LINE> <INDENT> self._device = usb.core.find(idVendor=0x287d, idProduct=0x0146) <NEW_LINE> self._device.set_configuration() <NEW_LINE> configuration = self._device.get_active_configuration() <NEW_LINE> interface = configuration[(0,0)] <NEW_LINE> self._endpoint_out = usb.util.find_descriptor(interface, custom_match = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT) <NEW_LINE> self._endpoint_in = usb.util.find_descriptor(interface, custom_match = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN) <NEW_LINE> <DEDENT> def _send_command(self, command): <NEW_LINE> <INDENT> cmd_string = '4261744d6963' <NEW_LINE> cmd_string += command <NEW_LINE> cmd_string += '20a10700' <NEW_LINE> cmd_string += '00400000' <NEW_LINE> cmd_string += '00000000' <NEW_LINE> cmd_string += '00' <NEW_LINE> cmd_string += '00' <NEW_LINE> cmd_string += 'ff' if command in ['02', '03'] else '00' <NEW_LINE> cmd_string += '00000000000000000000' <NEW_LINE> self._endpoint_out.write(cmd_string.decode('hex'), 1000)
Class used for control of the Pettersson M500 USB Ultrasound Microphone. More info at http://batsound.com/ Normally the M500 should be accessed from Windows systems, but this class makes it possible to call it from Linux. Installation instructions for pyusb: https://github.com/walac/pyusb Since pyusb access hardware directly 'udev rules' must be created. During test it is possible to run it as a 'sudo' user. Example for execution of the test case at the end of this file: > sudo python pettersson_m500_batmic.py More info about adding 'udev rules': http://stackoverflow.com/questions/3738173/why-does-pyusb-libusb-require-root-sudo-permissions-on-linux
62598fbb2c8b7c6e89bd3963
class MenuButton(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, pos=0, text="", cmd="", enabled=True, loc=(0, 0)): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.type = 'button' <NEW_LINE> self.color = (255, 255, 255) <NEW_LINE> self.font = pygame.font.Font(current_folder + "/misc/Domestic_Manners.ttf", 20) <NEW_LINE> self.text = text <NEW_LINE> self.pos = pos <NEW_LINE> self.cmd = cmd <NEW_LINE> self.enabled = enabled <NEW_LINE> self.loc = loc <NEW_LINE> self.image_normal = self.font.render(self.text, True, self.color) <NEW_LINE> self.image_pressed = self.font.render(self.text, True, (176, 154, 133)) <NEW_LINE> self.image_disabled = self.font.render(self.text, True, (95, 245, 244)) <NEW_LINE> if self.enabled: <NEW_LINE> <INDENT> self.image = self.image_normal.copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = self.image_disabled.copy() <NEW_LINE> <DEDENT> self.rect = self.image.get_rect() <NEW_LINE> self.surface_backup = self.image.copy() <NEW_LINE> wzglobals.menu_group.add(self) <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> self.image = self.surface_backup.copy() <NEW_LINE> bgrect = wzglobals.background.get_rect() <NEW_LINE> menupos = wzglobals.menu_bg.get_rect() <NEW_LINE> menupos.centery = wzglobals.background.get_rect().centery <NEW_LINE> if self.pos >= 0: <NEW_LINE> <INDENT> self.rect.centerx = bgrect.centerx <NEW_LINE> self.rect.top = menupos.top + 50 + (self.rect.height + 5) * self.pos <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> menupos.centerx = wzglobals.background.get_rect().centerx <NEW_LINE> self.rect.top = menupos.top + self.loc[1] <NEW_LINE> self.rect.left = menupos.left + self.loc[0] <NEW_LINE> <DEDENT> wzglobals.background.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.draw() <NEW_LINE> <DEDENT> def onmouse(self): <NEW_LINE> <INDENT> if self.enabled: <NEW_LINE> <INDENT> self.image = self.image_pressed <NEW_LINE> self.surface_backup = self.image.copy() <NEW_LINE> <DEDENT> <DEDENT> def onmouseout(self): <NEW_LINE> <INDENT> if self.enabled: <NEW_LINE> <INDENT> self.image = self.image_normal <NEW_LINE> self.surface_backup = self.image.copy() <NEW_LINE> <DEDENT> <DEDENT> def onmousedown(self): <NEW_LINE> <INDENT> if self.enabled: <NEW_LINE> <INDENT> exec(self.cmd) <NEW_LINE> self.image = self.image_pressed <NEW_LINE> self.surface_backup = self.image.copy() <NEW_LINE> <DEDENT> <DEDENT> def onmouseup(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def default(self): <NEW_LINE> <INDENT> self.image = self.image_normal <NEW_LINE> self.surface_backup = self.image.copy()
menu item
62598fbb60cbc95b063644dc
class C1aStatistic(Statistic, Asymmetry): <NEW_LINE> <INDENT> def __calculate__(self): <NEW_LINE> <INDENT> SD1a = SD1aStatistic(signal_plus=self.signal_plus, signal_minus=self.signal_minus, buffer=self.buffer).compute() <NEW_LINE> SD1 = SD1Statistic(signal_plus=self.signal_plus, signal_minus=self.signal_minus, buffer=self.buffer).compute() <NEW_LINE> return (SD1a / SD1) ** 2
for accelerations
62598fbb627d3e7fe0e0704f
class ApplicantConfirmationGet(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> applicant = ApplicantForm(VALID_APPLICANT) <NEW_LINE> applicant.save() <NEW_LINE> <DEDENT> def test_no_code(self): <NEW_LINE> <INDENT> response = self.client.get('/AuditiON/applicant_confirmation') <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertEqual(response._headers['location'][1], '/AuditiON/access_denied') <NEW_LINE> <DEDENT> def test_bad_code(self): <NEW_LINE> <INDENT> response = self.client.get('/AuditiON/applicant_confirmation/?code=1234567') <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertEqual(response._headers['location'][1], '/AuditiON/database_problem') <NEW_LINE> <DEDENT> def test_already_confirmed(self): <NEW_LINE> <INDENT> applicant = Applicant.objects.get(instrument='Flute') <NEW_LINE> applicant.confirmation='Accept' <NEW_LINE> applicant.save() <NEW_LINE> url = '/AuditiON/applicant_confirmation/?code=%s' % applicant.code <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertEqual(response._headers['location'][1], '/AuditiON/already_confirmed') <NEW_LINE> <DEDENT> def test_not_confirmed(self): <NEW_LINE> <INDENT> applicant = Applicant.objects.get(instrument='Flute') <NEW_LINE> applicant.confirmation='Unconfirmed' <NEW_LINE> applicant.save() <NEW_LINE> url = '/AuditiON/applicant_confirmation/?code=%s' % applicant.code <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, 'AuditiON/applicant_confirmation.html') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> Applicant.objects.all().delete()
Test all GET use cases for applicant_confirmation
62598fbb4a966d76dd5ef070
class ParameterNameError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, *args): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> super(ParameterNameError, self).__init__(message, *args)
Raise an error when the names of the parameter given by the user do not correspond to the names of the parameters detected in the symbolic expression of the immittance.
62598fbb63d6d428bbee294e
@admin.register(Image) <NEW_LINE> class ImageAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("id", "content_type", "object_id", "content_object") <NEW_LINE> search_fields = ("id", "content_type", "object_id", "content_object")
Admin page of :model:`images.Image`
62598fbb3d592f4c4edbb05b
class TrafficReportTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._ncc = None <NEW_LINE> self._ndr_config_file = None <NEW_LINE> self._created_files = [] <NEW_LINE> tests.util.setup_ndr_client_config(self) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> tests.util.cleanup_files(self) <NEW_LINE> <DEDENT> def check_last_entry(self, last_entry): <NEW_LINE> <INDENT> self.assertEqual(last_entry.protocol, ndr.PortProtocols.TCP) <NEW_LINE> self.assertEqual(last_entry.src_address, ipaddress.ip_address("192.168.2.2")) <NEW_LINE> self.assertEqual(last_entry.src_port, 39274) <NEW_LINE> self.assertEqual(last_entry.src_hostname, "test-outbound.example") <NEW_LINE> self.assertEqual(last_entry.dst_address, ipaddress.ip_address("104.16.111.18")) <NEW_LINE> self.assertEqual(last_entry.dst_port, 443) <NEW_LINE> self.assertEqual(last_entry.dst_hostname, "test-inbound.example") <NEW_LINE> self.assertEqual(last_entry.rx_bytes, 60) <NEW_LINE> self.assertEqual(last_entry.tx_bytes, 54) <NEW_LINE> <DEDENT> def test_deserialization_of_csv_test_data(self): <NEW_LINE> <INDENT> with open(TSHARK_REPORT, 'r') as f: <NEW_LINE> <INDENT> trm = ndr.TrafficReportMessage() <NEW_LINE> trm.parse_csv_file(f) <NEW_LINE> self.assertEqual(len(trm.traffic_entries), 19) <NEW_LINE> <DEDENT> last_entry = trm.traffic_entries.pop() <NEW_LINE> self.check_last_entry(last_entry) <NEW_LINE> <DEDENT> def test_serializing_deserializing_tr_message(self): <NEW_LINE> <INDENT> with open(TSHARK_REPORT, 'r') as f: <NEW_LINE> <INDENT> trm = ndr.TrafficReportMessage() <NEW_LINE> trm.parse_csv_file(f) <NEW_LINE> <DEDENT> trm_dict = trm.to_dict() <NEW_LINE> trm2 = ndr.TrafficReportMessage() <NEW_LINE> trm2.from_dict(trm_dict) <NEW_LINE> self.assertEqual(len(trm2.traffic_entries), 19) <NEW_LINE> last_entry = trm2.traffic_entries.pop() <NEW_LINE> self.check_last_entry(last_entry) <NEW_LINE> <DEDENT> def test_parsing_pcap(self): <NEW_LINE> <INDENT> trm = ndr.TrafficReportMessage(self._ncc) <NEW_LINE> trm.parse_pcap_file(TSHARK_PCAP) <NEW_LINE> self.assertEqual(len(trm.traffic_entries), 19) <NEW_LINE> last_entry = trm.traffic_entries.pop() <NEW_LINE> self.assertIsNone(last_entry.dst_hostname) <NEW_LINE> self.assertIsNone(last_entry.src_hostname) <NEW_LINE> last_entry.src_hostname = "test-outbound.example" <NEW_LINE> last_entry.dst_hostname = "test-inbound.example" <NEW_LINE> self.check_last_entry(last_entry)
Tests handling of snort traffic data reporting
62598fbbcc40096d6161a2a8
class CalculationRule(models.Model): <NEW_LINE> <INDENT> first_year_effective = models.ForeignKey('sis.SchoolYear', help_text='Rule also applies to subsequent years unless a more recent rule exists.') <NEW_LINE> points_possible = models.DecimalField(max_digits=8, decimal_places=2, default=4) <NEW_LINE> decimal_places = models.IntegerField(default=2) <NEW_LINE> def substitute(self, item_or_aggregate, value): <NEW_LINE> <INDENT> calculate_as = value <NEW_LINE> display_as = None <NEW_LINE> for s in self.substitution_set.filter(apply_to_departments=item_or_aggregate.course_section.department, apply_to_categories=item_or_aggregate.category): <NEW_LINE> <INDENT> if s.applies_to(value): <NEW_LINE> <INDENT> if s.calculate_as is not None: <NEW_LINE> <INDENT> calculate_as = s.calculate_as <NEW_LINE> <DEDENT> if s.display_as is not None and len(s.display_as): <NEW_LINE> <INDENT> display_as = s.display_as <NEW_LINE> <DEDENT> return calculate_as, display_as <NEW_LINE> <DEDENT> <DEDENT> return calculate_as, display_as <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'Rule of ' + self.first_year_effective.name
A per-year GPA calculation rule. It should also be applied to future years unless a more current rule exists.
62598fbb56ac1b37e630238b
class ConstantSingleQuotedString(ConstantString): <NEW_LINE> <INDENT> def repr(self): <NEW_LINE> <INDENT> return "ConstantSingleQuotedString('%s')" % (self.value)
String, that needs to be pre-processed
62598fbb57b8e32f525081eb
class Tag(NerdeezModel): <NEW_LINE> <INDENT> title = models.CharField(max_length=400)
bugs can have tags
62598fbb71ff763f4b5e7918
class LogBlockDebugTab(Tab, logblock_tab_class): <NEW_LINE> <INDENT> _blocks_updated_signal = pyqtSignal(object, bool) <NEW_LINE> _disconnected_signal = pyqtSignal(str) <NEW_LINE> def __init__(self, tabWidget, helper, *args): <NEW_LINE> <INDENT> super(LogBlockDebugTab, self).__init__(*args) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.tabName = "Log Blocks Debugging" <NEW_LINE> self.menuName = "Log Blocks Debugging" <NEW_LINE> self._helper = helper <NEW_LINE> self.tabWidget = tabWidget <NEW_LINE> self._helper.cf.log.block_added_cb.add_callback(self._block_added) <NEW_LINE> self._disconnected_signal.connect(self._disconnected) <NEW_LINE> self._helper.cf.disconnected.add_callback( self._disconnected_signal.emit) <NEW_LINE> self._blocks_updated_signal.connect(self._update_tree) <NEW_LINE> self._block_tree.setHeaderLabels( ['Id', 'Name', 'Period (ms)', 'Added', 'Started', 'Error', 'Contents']) <NEW_LINE> self._block_tree.sortItems(0, QtCore.Qt.AscendingOrder) <NEW_LINE> <DEDENT> def _block_added(self, block): <NEW_LINE> <INDENT> block.added_cb.add_callback(self._blocks_updated_signal.emit) <NEW_LINE> block.started_cb.add_callback(self._blocks_updated_signal.emit) <NEW_LINE> <DEDENT> def _update_tree(self, conf, value): <NEW_LINE> <INDENT> self._block_tree.clear() <NEW_LINE> for block in self._helper.cf.log.log_blocks: <NEW_LINE> <INDENT> item = QtWidgets.QTreeWidgetItem() <NEW_LINE> item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) <NEW_LINE> item.setData(0, Qt.DisplayRole, block.id) <NEW_LINE> item.setData(1, Qt.EditRole, block.name) <NEW_LINE> item.setData(2, Qt.DisplayRole, (block.period_in_ms)) <NEW_LINE> item.setData(3, Qt.DisplayRole, block.added) <NEW_LINE> item.setData(4, Qt.EditRole, block.started) <NEW_LINE> item.setData(5, Qt.EditRole, block.err_no) <NEW_LINE> for var in block.variables: <NEW_LINE> <INDENT> subItem = QtWidgets.QTreeWidgetItem() <NEW_LINE> subItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) <NEW_LINE> subItem.setData(6, Qt.EditRole, var.name) <NEW_LINE> item.addChild(subItem) <NEW_LINE> <DEDENT> self._block_tree.addTopLevelItem(item) <NEW_LINE> self._block_tree.expandItem(item) <NEW_LINE> <DEDENT> <DEDENT> def _disconnected(self, link_uri): <NEW_LINE> <INDENT> self._block_tree.clear()
Used to show debug-information about log status.
62598fbbbe383301e025399d
class Data7041(BaseData): <NEW_LINE> <INDENT> hdr_dtype = np.dtype([('SonarID', 'u8'), ('PingNumber', 'u4'), ('MultipingSequence', 'u2'), ('Beams', 'u2'), ('Flags', 'u2'), ('SampleRate', 'f4'), ('Reserved', '4u4')]) <NEW_LINE> def __init__(self, datablock, utctime, read_limit=1): <NEW_LINE> <INDENT> super(Data7041, self).__init__(datablock, read_limit=read_limit) <NEW_LINE> self.time = utctime <NEW_LINE> self.numbeams = self.header[3] <NEW_LINE> self.data = None <NEW_LINE> self.beam_identifiers = None <NEW_LINE> self.read(datablock[self.hdr_sz:]) <NEW_LINE> <DEDENT> def read(self, datablock): <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> self.beam_identifiers = [] <NEW_LINE> flags = self.header[4] <NEW_LINE> if (flags & 256) == 256: <NEW_LINE> <INDENT> beamid = 'f4' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> beamid = 'u2' <NEW_LINE> <DEDENT> cur_pointer = 0 <NEW_LINE> for i in range(self.numbeams): <NEW_LINE> <INDENT> data_fmt = np.dtype(beamid) <NEW_LINE> data_sz = data_fmt.itemsize <NEW_LINE> beaminfo = np.frombuffer(datablock[cur_pointer:cur_pointer + data_sz], data_fmt)[0] <NEW_LINE> cur_pointer += data_sz <NEW_LINE> data_fmt = np.dtype('u4') <NEW_LINE> data_sz = data_fmt.itemsize <NEW_LINE> numsamples = np.frombuffer(datablock[cur_pointer:cur_pointer + data_sz], data_fmt)[0] <NEW_LINE> cur_pointer += data_sz <NEW_LINE> self.beam_identifiers.append(beaminfo) <NEW_LINE> data_fmt = np.dtype(f'{int(numsamples)}{beamid}') <NEW_LINE> data_sz = data_fmt.itemsize <NEW_LINE> beamdata = np.frombuffer(datablock[cur_pointer:cur_pointer + data_sz], data_fmt)[0] <NEW_LINE> cur_pointer += data_sz <NEW_LINE> self.data.append(beamdata)
Compressed Beamformed Intensity Data
62598fbb4a966d76dd5ef072
class AccountingDescriptorTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testGetSucceedOnInstance(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testGetFailOnClass(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testSetFailIfInstance(self): <NEW_LINE> <INDENT> pass
Tests related to the ``AccountingDescriptor`` descriptor
62598fbbe5267d203ee6ba9f
class ExchangeNTLMAuthConnection(ExchangeBaseConnection): <NEW_LINE> <INDENT> def __init__(self, url, username, password, verify_certificate=True, **kwargs): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.verify_certificate = verify_certificate <NEW_LINE> self.handler = None <NEW_LINE> self.session = None <NEW_LINE> self.password_manager = None <NEW_LINE> <DEDENT> def build_password_manager(self): <NEW_LINE> <INDENT> if self.password_manager: <NEW_LINE> <INDENT> return self.password_manager <NEW_LINE> <DEDENT> log.debug(u'Constructing password manager') <NEW_LINE> self.password_manager = HttpNtlmAuth(self.username, self.password) <NEW_LINE> return self.password_manager <NEW_LINE> <DEDENT> def build_session(self): <NEW_LINE> <INDENT> if self.session: <NEW_LINE> <INDENT> return self.session <NEW_LINE> <DEDENT> log.debug(u'Constructing opener') <NEW_LINE> self.password_manager = self.build_password_manager() <NEW_LINE> self.session = requests.Session() <NEW_LINE> self.session.auth = self.password_manager <NEW_LINE> return self.session <NEW_LINE> <DEDENT> def send(self, body, headers=None, retries=2, timeout=30, encoding=u"utf-8"): <NEW_LINE> <INDENT> if not self.session: <NEW_LINE> <INDENT> self.session = self.build_session() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> response = self.session.post(self.url, data=body, headers=headers, verify = self.verify_certificate) <NEW_LINE> response.raise_for_status() <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as err: <NEW_LINE> <INDENT> log.debug(err.response.content) <NEW_LINE> raise FailedExchangeException(u'Unable to connect to Exchange: %s' % err) <NEW_LINE> <DEDENT> log.info(u'Got response: {code}'.format(code=response.status_code)) <NEW_LINE> log.debug(u'Got response headers: {headers}'.format(headers=response.headers)) <NEW_LINE> log.debug(u'Got body: {body}'.format(body=response.text)) <NEW_LINE> return response.text
Connection to Exchange that uses NTLM authentication
62598fbb3317a56b869be61e
class IPages(Interface): <NEW_LINE> <INDENT> pass
Shared interface and schema for Pages
62598fbbdc8b845886d53758
class TestDiscoveryString(unittest.TestCase): <NEW_LINE> <INDENT> def test_valid_discovery_response(self): <NEW_LINE> <INDENT> if is_py3: <NEW_LINE> <INDENT> data = bytearray(b"\xab\x01\xa8\xc0OKTwinkly_A1234B\x00") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = "\xab\x01\xa8\xc0OKTwinkly_A1234B\x00" <NEW_LINE> <DEDENT> decoded = discover.decode_discovery_response(data) <NEW_LINE> assert len(decoded) == 2 <NEW_LINE> part0, part1 = decoded <NEW_LINE> assert part0 == b"192.168.1.171" <NEW_LINE> assert part1 == b"Twinkly_A1234B" <NEW_LINE> <DEDENT> def test_invalid_status_discovery_response(self): <NEW_LINE> <INDENT> if is_py3: <NEW_LINE> <INDENT> data = bytearray(b"\xab\x01\xa8\xc0KOTwinkly_A1234B\x00") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = "\xab\x01\xa8\xc0KOTwinkly_A1234B\x00" <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> discover.decode_discovery_response(data) <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_end_discovery_response(self): <NEW_LINE> <INDENT> if is_py3: <NEW_LINE> <INDENT> data = bytearray(b"\xab\x01\xa8\xc0OKTwinkly_A1234B\x01") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = "\xab\x01\xa8\xc0OKTwinkly_A1234B\x01" <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> discover.decode_discovery_response(data)
Tests for `xled.discovery` module. String input data.
62598fbb4c3428357761a45b
class RegistrationView(BaseRegistrationView): <NEW_LINE> <INDENT> folder = Folder; <NEW_LINE> def register(self, request, **cleaned_data): <NEW_LINE> <INDENT> username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1'] <NEW_LINE> UserModel().objects.create_user(username, email, password) <NEW_LINE> new_user = authenticate(username=username, password=password) <NEW_LINE> login(request, new_user) <NEW_LINE> f = self.folder(); <NEW_LINE> f.author = username; <NEW_LINE> f.name = "ROOT"; <NEW_LINE> f.save(); <NEW_LINE> signals.user_registered.send(sender=self.__class__, user=new_user, request=request) <NEW_LINE> return new_user <NEW_LINE> <DEDENT> def registration_allowed(self, request): <NEW_LINE> <INDENT> return getattr(settings, 'REGISTRATION_OPEN', True) <NEW_LINE> <DEDENT> def get_success_url(self, request, user): <NEW_LINE> <INDENT> return ('registration_complete', (), {})
A registration backend which implements the simplest possible workflow: a user supplies a username, email address and password (the bare minimum for a useful account), and is immediately signed up and logged in).
62598fbbbf627c535bcb1644
class LabListCreateSerializer(serializers.ListSerializer): <NEW_LINE> <INDENT> def to_internal_value(self, data): <NEW_LINE> <INDENT> course = self.context.get("course") <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> data[i]['course'] = course <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def validate(self, data): <NEW_LINE> <INDENT> name_set = [d['name'] for d in data] <NEW_LINE> without_dups = list(set(name_set)) <NEW_LINE> if len(name_set) != len(without_dups): <NEW_LINE> <INDENT> raise serializers.ValidationError({'name': '重複した名前は使用できません.'}) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> course = self.context.get("course") <NEW_LINE> labs = [Lab(**data) for data in validated_data] <NEW_LINE> Lab.objects.bulk_create(labs) <NEW_LINE> return Lab.objects.filter(course_id=course.pk).all()
複数の研究室を一括で作成するシリアライザ
62598fbb796e427e5384e935
class FileExistsError(OSError): <NEW_LINE> <INDENT> pass
| File already exists. | | Method resolution order: | FileExistsError | OSError | Exception | BaseException | object | | Methods defined here: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from OSError: | | __reduce__(...) | Helper for pickle. | | __str__(self, /) | Return str(self). | | ---------------------------------------------------------------------- | Static methods inherited from OSError: | | __new__(*args, **kwargs) from type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from OSError: | | characters_written | | errno | POSIX exception code | | filename | exception filename | | filename2 | second exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
62598fbb099cdd3c636754b2
class WalkieFactory(protocol.Factory): <NEW_LINE> <INDENT> protocol = WalkieServer
Factory Class that Generates WalkieServer Instances
62598fbbd486a94d0ba2c16f
@attr.s(hash=True) <NEW_LINE> class RefResolutionError(Exception): <NEW_LINE> <INDENT> _cause = attr.ib() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self._cause)
A ref could not be resolved.
62598fbba8370b77170f0580
class Process(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> if 'process_id' not in kwargs and 'pid' not in kwargs: <NEW_LINE> <INDENT> raise Exception("Need a process id to initialize a process!") <NEW_LINE> <DEDENT> if 'pid' in kwargs: <NEW_LINE> <INDENT> kwargs['process_id'] = kwargs['pid'] <NEW_LINE> <DEDENT> self.state = 'New' <NEW_LINE> self.io_status_info = [] <NEW_LINE> self.acct = SystemAccounting(kwargs['process_id']) <NEW_LINE> self.mem_required = 0 <NEW_LINE> self.burst_time = 0 <NEW_LINE> self.priority = 0 <NEW_LINE> self.process_id = 0 <NEW_LINE> if 'priority' in kwargs: <NEW_LINE> <INDENT> self.priority = kwargs['priority'] <NEW_LINE> <DEDENT> if 'mem_required' in kwargs: <NEW_LINE> <INDENT> self.mem_required = kwargs['mem_required'] <NEW_LINE> <DEDENT> if 'burst_time' in kwargs: <NEW_LINE> <INDENT> self.burst_time = kwargs['burst_time'] <NEW_LINE> <DEDENT> if 'num_bursts' in kwargs: <NEW_LINE> <INDENT> self.num_bursts = kwargs['num_bursts'] <NEW_LINE> <DEDENT> if 'priority' in kwargs: <NEW_LINE> <INDENT> self.priority = kwargs['priority'] <NEW_LINE> <DEDENT> if 'process_id' in kwargs: <NEW_LINE> <INDENT> self.process_id = kwargs['process_id'] <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, val): <NEW_LINE> <INDENT> if hasattr(self, key): <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> elif hasattr(self.acct, key): <NEW_LINE> <INDENT> setattr(self.acct, key, val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if hasattr(self, key): <NEW_LINE> <INDENT> return getattr(self, key) <NEW_LINE> <DEDENT> elif hasattr(self.acct, key): <NEW_LINE> <INDENT> return getattr(self.acct, key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[process_id: %s, state: %s, io_status_info: %s, mem_required: %s, burst_time: %s, priority: %s]" % (self.process_id, self.state, self.io_status_info, self.mem_required, self.burst_time, self.priority)
Represents a single process. - Classes: Pcb : Process Control Block Included in process class SystemAccounting : Accounting class - Methods: __str__ : Prints a string representation of the object __setitem__: Allows user to use [] to set a value within the object. (e.g. p1['priority'] = 2) __getitem__: Allows user to use [] to get a value from an object. - **Attributes**: - burst_time (int) : CPU Burst time - io_status_info (list) : This includes a list of I/O devices allocated to the process. - mem_required (int) : Total memory required (in blocks) - priority (int) : Priority of process - process_id (int) : Unique identification for each of the process in the operating system. - state (enum) : The current state of the process [New, Ready, Running, Waiting, Terminated]
62598fbbad47b63b2c5a79f5
class OmnisciServerError(Exception): <NEW_LINE> <INDENT> pass
Raised when OmnisciDB server raises a runtime error that RBC knows how to interpret.
62598fbb63b5f9789fe85310
class FileCollection(BaseCollection): <NEW_LINE> <INDENT> model = FileProxy <NEW_LINE> object_id_field = 'path' <NEW_LINE> def __init__(self, data_store): <NEW_LINE> <INDENT> self.data_store = data_store <NEW_LINE> <DEDENT> def get_available_key(self, path): <NEW_LINE> <INDENT> return self.data_store.get_available_key(path)
A collection of file objects referenced through paths
62598fbb60cbc95b063644e0
class ApplicationConfigSection(PythonPackageConfigSection): <NEW_LINE> <INDENT> def __init__(self, template_config): <NEW_LINE> <INDENT> super(ApplicationConfigSection, self).__init__(template_config, "Application") <NEW_LINE> <DEDENT> @property <NEW_LINE> def app_class_name(self): <NEW_LINE> <INDENT> return self._get_property("appClassName", required=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def event_handlers(self): <NEW_LINE> <INDENT> return self._get_list_property("eventHandlers", required=False, default_value=[]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def services(self): <NEW_LINE> <INDENT> return self._get_list_property("services", required=False, default_value=[]) <NEW_LINE> <DEDENT> def _get_install_requires_list(self): <NEW_LINE> <INDENT> return ["dxlbootstrap", "dxlclient"]
Configuration section for the "application"
62598fbb4f6381625f199593
class Function(object): <NEW_LINE> <INDENT> def __init__(self, callable_object): <NEW_LINE> <INDENT> self.function = callable_object <NEW_LINE> for attr in ('__module__', '__name__', '__doc__'): <NEW_LINE> <INDENT> setattr(self, attr, getattr(callable_object, attr, None)) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.function(*args, **kwargs) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return self.__class__(compose(self.function, other)) <NEW_LINE> <DEDENT> def __ror__(self, other): <NEW_LINE> <INDENT> return self.__mul__(other) <NEW_LINE> <DEDENT> def __rmul__(self, other): <NEW_LINE> <INDENT> return self.__class__(compose(other, self.function)) <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return self.__rmul__(other)
The Function Wrapper. Support function composition via ``*`` operator. >>> add_1 = Function(lambda n: n + 1) >>> inc = add_1 * int >>> inc('42') 43 Support function piping via ``|`` operator. >>> inc2 = int | add_1 | add_1 | str >>> inc2('42') '44'
62598fbb3317a56b869be61f
class TestPortlet(unittest.TestCase): <NEW_LINE> <INDENT> layer = FTW_CLOCKPORTLET_INTEGRATION_TESTING <NEW_LINE> def test_portlet_type_registered(self): <NEW_LINE> <INDENT> portlet = getUtility( IPortletType, name='ftw.portlet.clock') <NEW_LINE> self.assertEquals( portlet.addview, 'ftw.portlet.clock') <NEW_LINE> <DEDENT> def test_interfaces(self): <NEW_LINE> <INDENT> portlet = clock.Assignment() <NEW_LINE> self.failUnless( clock.IClockPortlet.providedBy(portlet)) <NEW_LINE> <DEDENT> def test_renderer(self, section=''): <NEW_LINE> <INDENT> context = self.layer['portal'] <NEW_LINE> request = self.layer['request'] <NEW_LINE> view = context.restrictedTraverse('@@plone') <NEW_LINE> manager = getUtility( IPortletManager, name='plone.rightcolumn', context=context) <NEW_LINE> assignment = clock.Assignment() <NEW_LINE> renderer = getMultiAdapter( (context, request, view, manager, assignment), IPortletRenderer) <NEW_LINE> self.assertTrue("portlet sbbclock" in renderer.render()) <NEW_LINE> registry = getUtility(IRegistry) <NEW_LINE> self.assertTrue(registry['ftw.portlet.clock.url'] in renderer.render()) <NEW_LINE> <DEDENT> def test_assignment(self): <NEW_LINE> <INDENT> assignment = clock.Assignment() <NEW_LINE> self.assertEqual( assignment.title, u'SBB Clock')
Test clock portlet
62598fbb7047854f4633f577
class Battery(): <NEW_LINE> <INDENT> def __init__(self, battery_size=70): <NEW_LINE> <INDENT> self.battery_size = battery_size <NEW_LINE> <DEDENT> def describe_battery(self): <NEW_LINE> <INDENT> print("This car has a " + str(self.battery_size) + "-kWh battery.") <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 70: <NEW_LINE> <INDENT> range = 240 <NEW_LINE> <DEDENT> elif self.battery_size == 85: <NEW_LINE> <INDENT> range = 270 <NEW_LINE> <DEDENT> message = "This car can go approximately " + str(range) <NEW_LINE> message += " miles on a full charge." <NEW_LINE> print(message) <NEW_LINE> <DEDENT> def upgrade_battery(self): <NEW_LINE> <INDENT> if self.battery_size != 85: <NEW_LINE> <INDENT> self.battery_size = 85 <NEW_LINE> print("Upgraded the battery to " + self.battery_size + " kWh.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("The battery is already upgraded.")
A simple attempt to model a battery for an electric car.
62598fbbf548e778e596b748
class UnknownCommand(StatueException): <NEW_LINE> <INDENT> def __init__(self, command_name: str) -> None: <NEW_LINE> <INDENT> super().__init__(f'Could not find command named "{command_name}"')
Command isn't recognized.
62598fbb0fa83653e46f5086
@tf_export(v1=['layers.Conv2D']) <NEW_LINE> class Conv2D(keras_layers.Conv2D, base.Layer): <NEW_LINE> <INDENT> def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format='channels_last', dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer=None, bias_initializer=init_ops.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): <NEW_LINE> <INDENT> super(Conv2D, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, trainable=trainable, name=name, **kwargs)
2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function. Set it to None to maintain a linear activation. use_bias: Boolean, whether the layer uses a bias. kernel_initializer: An initializer for the convolution kernel. bias_initializer: An initializer for the bias vector. If None, the default initializer will be used. kernel_regularizer: Optional regularizer for the convolution kernel. bias_regularizer: Optional regularizer for the bias vector. activity_regularizer: Optional regularizer function for the output. kernel_constraint: Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer`. trainable: Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). name: A string, the name of the layer.
62598fbb7d847024c075c55e
class PowerSurge(Feature): <NEW_LINE> <INDENT> name = "Power Surge" <NEW_LINE> source = "Wizard (School of War Magic)"
Starting at 6th level, you can store magical energy within yourself to later empower your damaging spells. In its stored form, this energy is called a power surge. You can store a maximum number of power surges equal to your Intelligence modifier (minimum of one). Whenever you finish a long rest, your number of power surges reset-s to one. Whenever you successfully end a spell with dispel magic or counterspel], you gain one power surge, as you steal magic from the spell you foiled. If you end a short rest with no power surges, you gain one power surge Once per turn when you deal damage to a creature or object with a wizard spell, you can spend one power surge to deal extra force damage to that target. The ex- tra damage equals half your wizard level.
62598fbb7c178a314d78d641
class SelectManager(Manager): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._select_related = kwargs.pop('_select_related', []) <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def get_queryset(self, *args, **kwargs): <NEW_LINE> <INDENT> queryset = super().get_queryset(*args, **kwargs) <NEW_LINE> return queryset.select_related(*self._select_related)
Custom manager to transparently select related items.
62598fbb01c39578d7f12f1d
class TestApp(object): <NEW_LINE> <INDENT> cov = None <NEW_LINE> try: <NEW_LINE> <INDENT> import coverage <NEW_LINE> src_dirs = [ "pythia.journal", "pythia.pyre.applications", "pythia.pyre.components", "pythia.pyre.filesystem", "pythia.pyre.inventory", "pythia.pyre.odb", "pythia.pyre.parsing", "pythia.pyre.schedulers", "pythia.pyre.units", "pythia.pyre.util", "pythia.pyre.xml", ] <NEW_LINE> cov = coverage.Coverage(source=src_dirs) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> if self.cov: <NEW_LINE> <INDENT> self.cov.start() <NEW_LINE> <DEDENT> success = unittest.TextTestRunner(verbosity=2).run(self._suite()).wasSuccessful() <NEW_LINE> if not success: <NEW_LINE> <INDENT> sys.exit(1) <NEW_LINE> <DEDENT> if self.cov: <NEW_LINE> <INDENT> self.cov.stop() <NEW_LINE> self.cov.save() <NEW_LINE> self.cov.report() <NEW_LINE> self.cov.xml_report(outfile="coverage.xml") <NEW_LINE> <DEDENT> <DEDENT> def _suite(self): <NEW_LINE> <INDENT> import pyre.test_units <NEW_LINE> import pyre.test_inventory <NEW_LINE> import pyre.test_schedulers <NEW_LINE> import pyre.test_pyredoc <NEW_LINE> import pyre.test_nemesis <NEW_LINE> import journal.test_channels <NEW_LINE> import journal.test_devices <NEW_LINE> import journal.test_facilities <NEW_LINE> test_cases = [] <NEW_LINE> for mod in [ pyre.test_units, pyre.test_inventory, pyre.test_schedulers, pyre.test_pyredoc, pyre.test_nemesis, journal.test_channels, journal.test_devices, journal.test_facilities, ]: <NEW_LINE> <INDENT> test_cases += mod.test_classes() <NEW_LINE> <DEDENT> suite = unittest.TestSuite() <NEW_LINE> for test_case in test_cases: <NEW_LINE> <INDENT> suite.addTest(unittest.makeSuite(test_case)) <NEW_LINE> <DEDENT> return suite
Application to run tests.
62598fbba8370b77170f0581
class GameState(str, enum.Enum): <NEW_LINE> <INDENT> READY = "READY" <NEW_LINE> ACTIVE = "ACTIVE" <NEW_LINE> WON = "WON" <NEW_LINE> LOST = "LOST" <NEW_LINE> def started(self) -> bool: <NEW_LINE> <INDENT> return self is not self.READY <NEW_LINE> <DEDENT> def finished(self) -> bool: <NEW_LINE> <INDENT> return self in [self.WON, self.LOST]
Enum representing the state of a game.
62598fbb851cf427c66b8458
class InputModule(AbstractInput): <NEW_LINE> <INDENT> def __init__(self, input_dev, testing=False): <NEW_LINE> <INDENT> super(InputModule, self).__init__(input_dev, testing=testing, name=__name__) <NEW_LINE> self.sensor = None <NEW_LINE> if not testing: <NEW_LINE> <INDENT> self.initialize_input() <NEW_LINE> <DEDENT> <DEDENT> def initialize_input(self): <NEW_LINE> <INDENT> import adafruit_si7021 <NEW_LINE> from adafruit_extended_bus import ExtendedI2C <NEW_LINE> self.sensor = adafruit_si7021.SI7021( ExtendedI2C(self.input_dev.i2c_bus), address=int(str(self.input_dev.i2c_location), 16)) <NEW_LINE> <DEDENT> def get_measurement(self): <NEW_LINE> <INDENT> if not self.sensor: <NEW_LINE> <INDENT> self.logger.error("Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info.") <NEW_LINE> return <NEW_LINE> <DEDENT> self.return_dict = copy.deepcopy(measurements_dict) <NEW_LINE> if self.is_enabled(0): <NEW_LINE> <INDENT> self.value_set(0, self.sensor.temperature) <NEW_LINE> <DEDENT> if self.is_enabled(1): <NEW_LINE> <INDENT> self.value_set(1, self.sensor.relative_humidity) <NEW_LINE> <DEDENT> if self.is_enabled(2) and self.is_enabled(0) and self.is_enabled(1): <NEW_LINE> <INDENT> self.value_set(2, calculate_dewpoint(self.value_get(0), self.value_get(1))) <NEW_LINE> <DEDENT> if self.is_enabled(3) and self.is_enabled(0) and self.is_enabled(1): <NEW_LINE> <INDENT> self.value_set(3, calculate_vapor_pressure_deficit(self.value_get(0), self.value_get(1))) <NEW_LINE> <DEDENT> return self.return_dict
A sensor support class that measures.
62598fbbd268445f26639c55
class RunApiGetLotteryRecord(RunApi): <NEW_LINE> <INDENT> def __init__(self, step_name: str = None): <NEW_LINE> <INDENT> super().__init__("getLotteryRecord", step_name) <NEW_LINE> <DEDENT> def request(self): <NEW_LINE> <INDENT> return ( super() .request() .with_json( { "data": { "accountId": "$account_id" } } ) )
Implement api 'getLotteryRecord'. Key-value pairs: - accountId: $account_id (str), required - awardId: $award_id (int), required
62598fbb236d856c2adc9511
class Problem(object): <NEW_LINE> <INDENT> def __init__(self, filename, instance): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.instance = instance <NEW_LINE> self.numberOfJobs = 0 <NEW_LINE> self.numberOfMachines = 0 <NEW_LINE> self.processing_times = None <NEW_LINE> self.operation_numbers_dictionary = None <NEW_LINE> self.dimension = 0 <NEW_LINE> self.machineOrder = None <NEW_LINE> self.due_dates = None <NEW_LINE> self.parse_problem() <NEW_LINE> <DEDENT> def parse_problem(self): <NEW_LINE> <INDENT> with open(self.filename, 'r') as f: <NEW_LINE> <INDENT> problem_line = '/number of jobs, number of machines, time seed, machine seed, upper bound, lower bound :/' <NEW_LINE> lines = list(map(str.strip, f.readlines())) <NEW_LINE> lines[0] = '/' + lines[0] <NEW_LINE> try: <NEW_LINE> <INDENT> proctimes = '/'.join(lines).split(problem_line)[self.instance].split('/machines')[0].split('/')[2:] <NEW_LINE> machines = '/'.join(lines).split(problem_line)[self.instance].split('/machines')[1].split('/')[1:] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> max_instances = len('/'.join(lines).split(problem_line)) - 1 <NEW_LINE> print("\nError: Instance must be within 1 and %d\n" % max_instances) <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> self.processing_times = [list(map(int, line.split())) for line in proctimes] <NEW_LINE> self.numberOfJobs = len(self.processing_times) <NEW_LINE> self.numberOfMachines = len(self.processing_times[0]) <NEW_LINE> self.dimension = self.numberOfJobs * self.numberOfMachines <NEW_LINE> self.operation_numbers_dictionary = {i: (i % self.numberOfMachines, i // self.numberOfMachines) for i in range(self.dimension)} <NEW_LINE> self.machineOrder = [map(int, line.split()) for line in machines] <NEW_LINE> self.sort_problem() <NEW_LINE> <DEDENT> <DEDENT> def sort_problem(self): <NEW_LINE> <INDENT> new_ptimes = np.zeros((self.numberOfJobs, self.numberOfMachines), dtype=np.int16) <NEW_LINE> for i, job in enumerate(self.processing_times): <NEW_LINE> <INDENT> newlist = sorted(zip(self.machineOrder[i], job)) <NEW_LINE> for j, ptime in enumerate(newlist): <NEW_LINE> <INDENT> new_ptimes[i, j] = ptime[1] <NEW_LINE> <DEDENT> <DEDENT> self.due_dates = np.sum(new_ptimes, axis=1) <NEW_LINE> self.processing_times = new_ptimes.flatten()
Reads and parses Open Shop Scheduling Problem
62598fbb7d43ff24874274d5
class LoginRequestEventlet(GenericApiRequest): <NEW_LINE> <INDENT> def __init__(self, client_obj, user, password, client_conn=None, headers=None): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> headers = {} <NEW_LINE> <DEDENT> message = client_obj.render(client_obj.login_msg()) <NEW_LINE> body = message.get('body', None) <NEW_LINE> auth = base64.encodestring('%s:%s' % (user, password)). replace('\n', '') <NEW_LINE> headers.update({'Authorization': "Basic %s" % auth}) <NEW_LINE> super(LoginRequestEventlet, self).__init__( client_obj, message['path'], message['method'], body, headers, auto_login=True, client_conn=client_conn) <NEW_LINE> <DEDENT> def session_cookie(self): <NEW_LINE> <INDENT> if self.successful(): <NEW_LINE> <INDENT> return self.value.getheader("Set-Cookie") <NEW_LINE> <DEDENT> return None
Process a login request.
62598fbb3317a56b869be620
class HostCollection(object): <NEW_LINE> <INDENT> command_base = 'host-collection' <NEW_LINE> @classmethod <NEW_LINE> def add_content_host(cls, options=None): <NEW_LINE> <INDENT> cls.command_sub = 'add-content-host' <NEW_LINE> return cls.execute(cls._construct_command(options)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def remove_content_host(cls, options=None): <NEW_LINE> <INDENT> cls.command_sub = 'remove-content-host' <NEW_LINE> return cls.execute(cls._construct_command(options)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def content_hosts(cls, options=None): <NEW_LINE> <INDENT> cls.command_sub = 'content-hosts' <NEW_LINE> return cls.execute( cls._construct_command(options), output_format='csv')
Manipulates Katello engine's host-collection command.
62598fbb1f5feb6acb162dc3
class StatusCause(_messages.Message): <NEW_LINE> <INDENT> field = _messages.StringField(1) <NEW_LINE> message = _messages.StringField(2) <NEW_LINE> reason = _messages.StringField(3)
StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered. Fields: field: The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. Examples: "name" - the field "name" on the current resource "items[0].name" - the field "name" on the first array entry in "items" +optional message: A human-readable description of the cause of the error. This field may be presented as-is to a reader. +optional reason: A machine-readable description of the cause of the error. If this value is empty there is no information available. +optional
62598fbb3539df3088ecc450
class TestDistributionSettingsView(TestCaseWithFactory): <NEW_LINE> <INDENT> layer = LaunchpadFunctionalLayer <NEW_LINE> def test_only_translation_fields(self): <NEW_LINE> <INDENT> distribution = self.factory.makeDistribution() <NEW_LINE> view = create_initialized_view( distribution, '+configure-translations', rootsite='translations') <NEW_LINE> self.assertContentEqual( ["translations_usage", "translation_focus", "translationgroup", "translationpermission", ], view.field_names) <NEW_LINE> <DEDENT> def test_unprivileged_users(self): <NEW_LINE> <INDENT> unprivileged = self.factory.makePerson() <NEW_LINE> distribution = self.factory.makeDistribution() <NEW_LINE> browser = self.getUserBrowser(user=unprivileged) <NEW_LINE> url = canonical_url(distribution, view_name='+configure-translations', rootsite='translations') <NEW_LINE> self.assertRaises(Unauthorized, browser.open, url) <NEW_LINE> <DEDENT> def test_translation_group_owner(self): <NEW_LINE> <INDENT> group = self.factory.makeTranslationGroup() <NEW_LINE> distribution = self.factory.makeDistribution() <NEW_LINE> with person_logged_in(distribution.owner): <NEW_LINE> <INDENT> distribution.translationgroup = group <NEW_LINE> <DEDENT> browser = self.getUserBrowser(user=group.owner) <NEW_LINE> url = canonical_url(distribution, view_name='+configure-translations', rootsite='translations') <NEW_LINE> browser.open(url) <NEW_LINE> <DEDENT> def test_distribution_owner(self): <NEW_LINE> <INDENT> distribution = self.factory.makeDistribution() <NEW_LINE> browser = self.getUserBrowser(user=distribution.owner) <NEW_LINE> url = canonical_url(distribution, view_name='+configure-translations', rootsite='translations') <NEW_LINE> browser.open(url)
Test distribution settings (+configure-translations) view.
62598fbb56ac1b37e6302391
class ReplacedContext(BaseModel): <NEW_LINE> <INDENT> vocab: Optional[str] <NEW_LINE> syn: Optional[str] <NEW_LINE> orig_text: Optional[List[str]] <NEW_LINE> mod_text: Optional[List[str]] <NEW_LINE> similarity_score: Optional[List[float]]
Info around a replaced vocabulary. Examples: >>> rc = ReplacedContext(vocab = "detrimental", syn = "damaging", orig_text = ["damaging to health"], mod_text = ["detrimental to health"])
62598fbb7b180e01f3e49121
class GameOfRoundsReport(game.GameReport): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GameOfRoundsReport, self).__init__() <NEW_LINE> self.roundsReports = [] <NEW_LINE> <DEDENT> def addRoundReport(self, roundReport): <NEW_LINE> <INDENT> self.roundsReports.append(roundReport) <NEW_LINE> <DEDENT> def summary(self): <NEW_LINE> <INDENT> t = Template( ) <NEW_LINE> gameReport = super(GameOfRoundsReport, self).summary() <NEW_LINE> roundsReports = '\n '.join(round.summary() for round in self.roundsReports) <NEW_LINE> return t.substitute(numberOfRounds=len(self.roundsReports), gameReport=gameReport, roundsReports=roundsReports)
roundsReports
62598fbb8a349b6b436863e0
class CatagtleCustmersSearchView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mp = request.GET.get('user_name') <NEW_LINE> req = MiddlePeople.objects.values('id', 'really_name').filter(really_name__contains=mp) <NEW_LINE> query = list(req) <NEW_LINE> paginator = Paginator(query, 10) <NEW_LINE> page = int(request.GET.get('page')) <NEW_LINE> try: <NEW_LINE> <INDENT> page_value = paginator.page(page) <NEW_LINE> <DEDENT> except EmptyPage: <NEW_LINE> <INDENT> return JsonResponse({'Code': 400, 'Errmsg': 'page数据出错'}) <NEW_LINE> <DEDENT> data_list = [] <NEW_LINE> for i in page_value: <NEW_LINE> <INDENT> json_dict = {} <NEW_LINE> json_dict['id'] = i['id'] <NEW_LINE> b = i['id'] <NEW_LINE> date = ExclusiveCustmer.objects.get(middle_name_id=b) <NEW_LINE> json_dict['id'] = date.id <NEW_LINE> json_dict['really_name'] = i['really_name'] <NEW_LINE> json_dict['user_id'] = date.user_id <NEW_LINE> json_dict['user_id'] = date.user_name <NEW_LINE> json_dict['user_id'] = date.custmer_time <NEW_LINE> json_dict['head_img'] = date.head_img <NEW_LINE> data_list.append(json_dict) <NEW_LINE> <DEDENT> total_page = paginator.num_pages <NEW_LINE> return JsonResponse({"statue": 200, 'data': data_list, 'count': total_page}, safe=False) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> context = {"Result": 'false', 'Msg': {e}} <NEW_LINE> return JsonResponse(context)
专属客户搜索框
62598fbb236d856c2adc9512
class InvalidFacePointsException(ConnectiveGeometryException): <NEW_LINE> <INDENT> pass
InvalidFacePointsException()
62598fbb091ae35668704dc7
class TestValues(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls) -> None: <NEW_LINE> <INDENT> init_testing() <NEW_LINE> <DEDENT> def test_basic(self) -> None: <NEW_LINE> <INDENT> from pineboolib.application.database import pnsqlcursor <NEW_LINE> from pineboolib.application.qsatypes import date <NEW_LINE> cursor = pnsqlcursor.PNSqlCursor("flupdates") <NEW_LINE> cursor.setModeAccess(cursor.Insert) <NEW_LINE> cursor.refreshBuffer() <NEW_LINE> date_ = date.Date() <NEW_LINE> cursor.setValueBuffer("fecha", date_) <NEW_LINE> cursor.setValueBuffer("hora", "00:00:01") <NEW_LINE> cursor.setValueBuffer("nombre", "nombre de prueba") <NEW_LINE> cursor.setValueBuffer("modulesdef", "module_1\nmodule_2\nmodule_3") <NEW_LINE> cursor.setValueBuffer("filesdef", "file_1\nfile_2\nfile_3") <NEW_LINE> cursor.setValueBuffer("shaglobal", "1234567890") <NEW_LINE> cursor.setValueBuffer("auxtxt", "aux_1\naux_2\naux_3") <NEW_LINE> self.assertEqual(cursor.commitBuffer(), True) <NEW_LINE> self.assertEqual(str(cursor.valueBuffer("fecha"))[0:10], str(date_)[0:10]) <NEW_LINE> self.assertEqual(cursor.valueBuffer("hora"), "00:00:01") <NEW_LINE> self.assertEqual(cursor.valueBuffer("nombre"), "nombre de prueba") <NEW_LINE> cursor_2 = pnsqlcursor.PNSqlCursor("fltest3") <NEW_LINE> cursor_2.setModeAccess(cursor_2.Insert) <NEW_LINE> cursor_2.refreshBuffer() <NEW_LINE> cursor_2.setValueBuffer("string_field", "Campo de prueba test_pnsqlcursor_test_basic") <NEW_LINE> self.assertTrue(cursor_2.commitBuffer()) <NEW_LINE> cursor_2.select() <NEW_LINE> self.assertTrue(cursor_2.first()) <NEW_LINE> self.assertTrue(cursor_2.valueBuffer("counter"), "000001") <NEW_LINE> cursor_2.setModeAccess(cursor_2.Del) <NEW_LINE> cursor_2.refreshBuffer() <NEW_LINE> self.assertTrue(cursor_2.commitBuffer()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls) -> None: <NEW_LINE> <INDENT> finish_testing()
Test Values class.
62598fbb63b5f9789fe85314
class SaveMatplotlib(qt.QAction): <NEW_LINE> <INDENT> def __init__(self, title, maskImageWidget): <NEW_LINE> <INDENT> super(SaveMatplotlib, self).__init__(QString(title), maskImageWidget) <NEW_LINE> self.maskImageWidget = maskImageWidget <NEW_LINE> self.triggered[bool].connect(self.onTrigger) <NEW_LINE> self._matplotlibSaveImage = None <NEW_LINE> <DEDENT> def onTrigger(self): <NEW_LINE> <INDENT> imageData = self.maskImageWidget.getImageData() <NEW_LINE> if self._matplotlibSaveImage is None: <NEW_LINE> <INDENT> self._matplotlibSaveImage = QPyMcaMatplotlibSave.SaveImageSetup( None, image=None) <NEW_LINE> <DEDENT> title = "Matplotlib " + self.maskImageWidget.plot.getGraphTitle() <NEW_LINE> self._matplotlibSaveImage.setWindowTitle(title) <NEW_LINE> ddict = self._matplotlibSaveImage.getParameters() <NEW_LINE> colormapDict = self.maskImageWidget.getCurrentColormap() <NEW_LINE> if colormapDict is not None: <NEW_LINE> <INDENT> autoscale = colormapDict['autoscale'] <NEW_LINE> vmin = colormapDict['vmin'] <NEW_LINE> vmax = colormapDict['vmax'] <NEW_LINE> colormapType = colormapDict['normalization'] <NEW_LINE> if colormapType == 'log': <NEW_LINE> <INDENT> colormapType = 'logarithmic' <NEW_LINE> <DEDENT> ddict['linlogcolormap'] = colormapType <NEW_LINE> if not autoscale: <NEW_LINE> <INDENT> ddict['valuemin'] = vmin <NEW_LINE> ddict['valuemax'] = vmax <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ddict['valuemin'] = 0 <NEW_LINE> ddict['valuemax'] = 0 <NEW_LINE> <DEDENT> <DEDENT> origin = self.maskImageWidget._origin <NEW_LINE> delta = self.maskImageWidget._deltaXY <NEW_LINE> ddict['xpixelsize'] = delta[0] <NEW_LINE> ddict['xorigin'] = origin[0] <NEW_LINE> ddict['ypixelsize'] = delta[1] <NEW_LINE> ddict['yorigin'] = origin[1] <NEW_LINE> ddict['xlabel'] = self.maskImageWidget.plot.getGraphXLabel() <NEW_LINE> ddict['ylabel'] = self.maskImageWidget.plot.getGraphYLabel() <NEW_LINE> limits = self.maskImageWidget.plot.getGraphXLimits() <NEW_LINE> ddict['zoomxmin'] = limits[0] <NEW_LINE> ddict['zoomxmax'] = limits[1] <NEW_LINE> limits = self.maskImageWidget.plot.getGraphYLimits() <NEW_LINE> ddict['zoomymin'] = limits[0] <NEW_LINE> ddict['zoomymax'] = limits[1] <NEW_LINE> self._matplotlibSaveImage.setParameters(ddict) <NEW_LINE> self._matplotlibSaveImage.setImageData(imageData) <NEW_LINE> self._matplotlibSaveImage.show() <NEW_LINE> self._matplotlibSaveImage.raise_()
Save current image ho high quality graphics using matplotlib
62598fbb3317a56b869be621
class Eq_46(HardwoodVolumeEquation_WithX): <NEW_LINE> <INDENT> def calc_cvts(self, drc, ht, stems=None): <NEW_LINE> <INDENT> if stems is None: <NEW_LINE> <INDENT> stems = np.ones_like(drc) <NEW_LINE> <DEDENT> cvts = np.where( drc**2 * ht / 1000 <= 2, (-0.043 + 2.3378 * drc**2 * ht / 1000 + 0.8024 * (drc**2 * ht / 1000)**2), 9.586 + 2.3378 * drc**2 * ht / 1000 - 12.839 / (drc**2 * ht / 1000) ) <NEW_LINE> mask = np.logical_and(stems > 1, (drc**2 * ht / 1000) <= 2) <NEW_LINE> cvts[mask] = (0.020 + 1.8972 * drc[mask]**2 * ht[mask] / 1000 + 0.5756 * (drc[mask]**2 * ht[mask] / 1000)**2) <NEW_LINE> mask = np.logical_and(stems > 1, (drc**2 * ht / 1000) > 2) <NEW_LINE> cvts[mask] = (9.586 + 2.3378 * drc[mask]**2 * ht[mask] / 1000 - 12.839 / (drc[mask]**2 * ht[mask] / 1000)) <NEW_LINE> cvts = np.clip(cvts, 0.1, None) <NEW_LINE> cvts[np.logical_or(drc <= 0, ht <= 0)] = 0 <NEW_LINE> return cvts
Mesquite (CHOJNACKY, 1985) Chojnacky D.C., 1985. Pinyon-Juniper Volume Equations for the Central Rocky Mountain States. Res. Note INT-339, USDA, Forest Service, Intermountain Res. Station, Ogden, UT 84401.
62598fbb67a9b606de546173
class Missile(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, position, velocity, angle): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image = pygame.Surface([4, 10], pygame.SRCALPHA) <NEW_LINE> self.image.fill(BLUE) <NEW_LINE> self.image = pygame.transform.rotozoom(self.image, -angle, 1) <NEW_LINE> self.rect = self.image.get_rect(center=position) <NEW_LINE> self.position = vec(position) <NEW_LINE> self.velocity = velocity <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.position += self.velocity <NEW_LINE> self.rect.center = self.position <NEW_LINE> if self.rect.x < 0 or self.rect.x > WIDTH or self.rect.y < 0 or self.rect.y > HEIGHT: <NEW_LINE> <INDENT> self.kill()
This class represents the bullet. A missile launched by the player's ship.
62598fbb3539df3088ecc452
class QuiverConfig(object): <NEW_LINE> <INDENT> def __init__(self, parameterSets, minMapQV=10, minPoaCoverage=3, maxPoaCoverage=11, mutationSeparation=10, mutationNeighborhood=20, maxIterations=40, refineDinucleotideRepeats=True, noEvidenceConsensus="nocall", computeConfidence=True, readStumpinessThreshold=0.1): <NEW_LINE> <INDENT> self.minMapQV = minMapQV <NEW_LINE> self.minPoaCoverage = minPoaCoverage <NEW_LINE> self.maxPoaCoverage = maxPoaCoverage <NEW_LINE> self.mutationSeparation = mutationSeparation <NEW_LINE> self.mutationNeighborhood = mutationNeighborhood <NEW_LINE> self.maxIterations = maxIterations <NEW_LINE> self.refineDinucleotideRepeats = refineDinucleotideRepeats <NEW_LINE> self.noEvidenceConsensus = noEvidenceConsensus <NEW_LINE> self.computeConfidence = computeConfidence <NEW_LINE> self.readStumpinessThreshold = readStumpinessThreshold <NEW_LINE> self.parameterSets = parameterSets <NEW_LINE> qct = cc.QuiverConfigTable() <NEW_LINE> for (chem, pset) in self.parameterSets.items(): <NEW_LINE> <INDENT> if chem == "*": <NEW_LINE> <INDENT> qct.InsertDefault(pset.ccQuiverConfig) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qct.InsertAs(chem, pset.ccQuiverConfig) <NEW_LINE> <DEDENT> <DEDENT> self.ccQuiverConfigTbl = qct <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _defaultQuiverParameters(): <NEW_LINE> <INDENT> return loadQuiverConfig("unknown.NoQVsModel") <NEW_LINE> <DEDENT> def extractMappedRead(self, aln, windowStart): <NEW_LINE> <INDENT> pset = self.parameterSets.get(chemOrUnknown(aln)) or self.parameterSets.get("*") <NEW_LINE> model = pset.model <NEW_LINE> return model.extractMappedRead(aln, windowStart)
Quiver configuration options
62598fbbcc0a2c111447b1b3
class Article(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=40) <NEW_LINE> headline = models.CharField(max_length=100) <NEW_LINE> body = models.TextField() <NEW_LINE> author = models.ForeignKey(User) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('blog:article-detail', kwargs={'pk': self.id})
Model to hold data about articles
62598fbb0fa83653e46f508a
class Row(Index): <NEW_LINE> <INDENT> def __index__(self): <NEW_LINE> <INDENT> return int(self.name) - 1
A one-based, end-inclusive row index for use in slices, eg:: ``[Row(1):Row(2), :]``
62598fbb5fdd1c0f98e5e137
class HassAqualinkSwitch(AqualinkEntity, SwitchEntity): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.dev.label <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self) -> str: <NEW_LINE> <INDENT> if self.name == "Cleaner": <NEW_LINE> <INDENT> return "mdi:robot-vacuum" <NEW_LINE> <DEDENT> if self.name == "Waterfall" or self.name.endswith("Dscnt"): <NEW_LINE> <INDENT> return "mdi:fountain" <NEW_LINE> <DEDENT> if self.name.endswith("Pump") or self.name.endswith("Blower"): <NEW_LINE> <INDENT> return "mdi:fan" <NEW_LINE> <DEDENT> if self.name.endswith("Heater"): <NEW_LINE> <INDENT> return "mdi:radiator" <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self.dev.is_on <NEW_LINE> <DEDENT> @refresh_system <NEW_LINE> async def async_turn_on(self, **kwargs) -> None: <NEW_LINE> <INDENT> await await_or_reraise(self.dev.turn_on()) <NEW_LINE> <DEDENT> @refresh_system <NEW_LINE> async def async_turn_off(self, **kwargs) -> None: <NEW_LINE> <INDENT> await await_or_reraise(self.dev.turn_off())
Representation of a switch.
62598fbb656771135c489815
class CopyrightView(BrowserView): <NEW_LINE> <INDENT> def changeCopyright(self, value): <NEW_LINE> <INDENT> context = self.context <NEW_LINE> message = '' <NEW_LINE> if IClearCopyrightable.providedBy(context): <NEW_LINE> <INDENT> anno = IAnnotations(context) <NEW_LINE> if value == 'True': <NEW_LINE> <INDENT> anno['eduCommons.clearcopyright'] = True <NEW_LINE> message= _(u'Copyright Cleared') <NEW_LINE> <DEDENT> elif value == 'False': <NEW_LINE> <INDENT> anno['eduCommons.clearcopyright'] = False <NEW_LINE> message= _(u'Copyright Revoked') <NEW_LINE> <DEDENT> <DEDENT> return message
Provides view of object with access to annotations in placeless environments
62598fbb66673b3332c30577
class MalibApiBase: <NEW_LINE> <INDENT> def addressIsAllowed(self, addr): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def codeIsValid(self, code): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def log(self, severity, msg): <NEW_LINE> <INDENT> if hasattr(logging,severity): <NEW_LINE> <INDENT> getattr(logging,severity)(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Logger.error("unknown severity: " + msg) <NEW_LINE> <DEDENT> <DEDENT> def localBroadcast(self, event, *args ): <NEW_LINE> <INDENT> pub.sendMessage("localBroadcast", event=event, args=args ) <NEW_LINE> <DEDENT> def multicast(self, addrList, event, *args ): <NEW_LINE> <INDENT> pub.sendMessage("localBroadcast", event=event, args=args ) <NEW_LINE> for addr in addrList: <NEW_LINE> <INDENT> thread.start_new_thread( sendBroadcast, (addr, event, args,) ) <NEW_LINE> <DEDENT> <DEDENT> def sendAgent(self, code, briefcase ): <NEW_LINE> <INDENT> thread.start_new_thread( sendAgent, (code, briefcase,) )
Base class for mobile agents. Provides a facility for registering events, logging and sending mobile agents to other peers.
62598fbbcc40096d6161a2ac
@handler.subscribe(OpenPortEvent, predicate=lambda x: x.port == 8001) <NEW_LINE> class KubeProxy(Discovery): <NEW_LINE> <INDENT> def __init__(self, event): <NEW_LINE> <INDENT> self.event = event <NEW_LINE> self.host = event.host <NEW_LINE> self.port = event.port or 8001 <NEW_LINE> <DEDENT> @property <NEW_LINE> def accesible(self): <NEW_LINE> <INDENT> config = get_config() <NEW_LINE> endpoint = f"http://{self.host}:{self.port}/api/v1" <NEW_LINE> logger.debug("Attempting to discover a proxy service") <NEW_LINE> try: <NEW_LINE> <INDENT> r = requests.get(endpoint, timeout=config.network_timeout) <NEW_LINE> if r.status_code == 200 and "APIResourceList" in r.text: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except requests.Timeout: <NEW_LINE> <INDENT> logger.debug(f"failed to get {endpoint}", exc_info=True) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.accesible: <NEW_LINE> <INDENT> self.publish_event(KubeProxyEvent())
Proxy Discovery Checks for the existence of a an open Proxy service
62598fbb56ac1b37e6302394
class GetMsg(object): <NEW_LINE> <INDENT> def get_info(self, regx, msg): <NEW_LINE> <INDENT> result = re.findall(regx, msg) <NEW_LINE> if result: <NEW_LINE> <INDENT> return result[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def get_text_msg(self, msg): <NEW_LINE> <INDENT> self.content = self.get_info(re_text_content, msg) <NEW_LINE> <DEDENT> def get_img_msg(self, msg): <NEW_LINE> <INDENT> self.pic_url = self.get_info(re_img_url, msg) <NEW_LINE> self.media_id = self.get_info(re_media_id, msg) <NEW_LINE> <DEDENT> def get_location_msg(self, msg): <NEW_LINE> <INDENT> self.location_x = self.get_info(re_locx, msg) <NEW_LINE> self.location_y = self.get_info(re_locy, msg) <NEW_LINE> self.scale = self.get_info(re_scale, msg) <NEW_LINE> self.label = self.get_info(re_label, msg) <NEW_LINE> <DEDENT> def get_link_msg(self, msg): <NEW_LINE> <INDENT> self.title = self.get_info(re_title, msg) <NEW_LINE> self.description = self.get_info(re_description, msg) <NEW_LINE> self.url = self.get_info(re_url, msg) <NEW_LINE> <DEDENT> def get_event_msg(self, msg): <NEW_LINE> <INDENT> self.event = self.get_info(re_event, msg) <NEW_LINE> self.event_key = self.get_info(re_eventkey, msg) <NEW_LINE> <DEDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.to_user_name = self.get_info(re_msg_tuid, msg) <NEW_LINE> self.from_user_name = self.get_info(re_msg_fuid, msg) <NEW_LINE> self.create_time = self.get_info(re_msg_ctime, msg) <NEW_LINE> self.msg_type = self.get_info(re_msg_type, msg) <NEW_LINE> self.msg_id = self.get_info(re_msg_id, msg) <NEW_LINE> msgtype = self.msg_type <NEW_LINE> if msgtype == 'text': <NEW_LINE> <INDENT> self.get_text_msg(msg) <NEW_LINE> <DEDENT> elif msgtype == 'image': <NEW_LINE> <INDENT> self.get_img_msg(msg) <NEW_LINE> <DEDENT> elif msgtype == 'location': <NEW_LINE> <INDENT> self.get_location_msg(msg) <NEW_LINE> <DEDENT> elif msgtype == 'link': <NEW_LINE> <INDENT> self.get_link_msg(msg) <NEW_LINE> <DEDENT> elif msgtype == 'event': <NEW_LINE> <INDENT> self.get_event_msg(msg)
输入一个xml文本字符串对象,生成一个object并返回
62598fbb4f88993c371f05e0
class disconnection_notification_dialog(Gtk.Dialog): <NEW_LINE> <INDENT> def window_attn(self, widget, event): <NEW_LINE> <INDENT> if event.new_window_state | Gdk.WINDOW_STATE_ICONIFIED: <NEW_LINE> <INDENT> widget.set_urgency_hint(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> widget.set_urgency_hint(False) <NEW_LINE> <DEDENT> <DEDENT> def respond(self, dialog, response): <NEW_LINE> <INDENT> if response in (Gtk.ResponseType.CLOSE, Gtk.ResponseType.DELETE_EVENT): <NEW_LINE> <INDENT> dialog.hide() <NEW_LINE> <DEDENT> <DEDENT> def present(self): <NEW_LINE> <INDENT> self.dial_group.hide(self) <NEW_LINE> Gtk.Dialog.present(self) <NEW_LINE> <DEDENT> def __init__(self, dial_group = None, window_group = None, window_title = None, text = None): <NEW_LINE> <INDENT> if window_title is None: <NEW_LINE> <INDENT> window_title = pm.title_extra.strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> window_title += pm.title_extra <NEW_LINE> <DEDENT> Gtk.Dialog.__init__(self, window_title, None, Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)) <NEW_LINE> if window_group is not None: <NEW_LINE> <INDENT> window_group.add_window(self) <NEW_LINE> <DEDENT> self.set_resizable(False) <NEW_LINE> self.set_border_width(6) <NEW_LINE> self.get_child().set_spacing(12) <NEW_LINE> self.connect("close", self.respond) <NEW_LINE> self.connect("response", self.respond) <NEW_LINE> self.connect("window-state-event", self.window_attn) <NEW_LINE> hbox = Gtk.HBox(False, 20) <NEW_LINE> hbox.set_spacing(12) <NEW_LINE> self.get_content_area().pack_start(hbox, True, True, 0) <NEW_LINE> hbox.show() <NEW_LINE> image = Gtk.Image() <NEW_LINE> image.set_alignment(0.5, 0) <NEW_LINE> image.set_from_stock(Gtk.STOCK_DISCONNECT, Gtk.IconSize.DIALOG) <NEW_LINE> hbox.pack_start(image, False, False, 0) <NEW_LINE> image.show() <NEW_LINE> vbox = Gtk.VBox() <NEW_LINE> hbox.pack_start(vbox, True, True, 0) <NEW_LINE> vbox.show() <NEW_LINE> if text is not None: <NEW_LINE> <INDENT> for each in text.splitlines(): <NEW_LINE> <INDENT> label = Gtk.Label(each) <NEW_LINE> label.set_use_markup(True) <NEW_LINE> label.set_alignment(0.0, 0.5) <NEW_LINE> vbox.pack_start(label, False, False, 0) <NEW_LINE> label.show() <NEW_LINE> <DEDENT> <DEDENT> if dial_group is not None: <NEW_LINE> <INDENT> dial_group.add(self) <NEW_LINE> <DEDENT> self.dial_group = dial_group
Used to show a dialog related to the failure of the server connection.
62598fbb4527f215b58ea07b
class RunConfigsTest(DriftBaseTestCase): <NEW_LINE> <INDENT> def test_runconfig_create(self): <NEW_LINE> <INDENT> self.auth_service() <NEW_LINE> data = { "name": make_unique("runconfig name"), "repository": "Test/Test", "ref": "test/test", "build": "HEAD" } <NEW_LINE> r = self.post(self.endpoints["runconfigs"], data=data, expected_status_code=http_client.CREATED) <NEW_LINE> runconfig_url = r.json()["url"] <NEW_LINE> r = self.get(runconfig_url) <NEW_LINE> for k, v in data.items(): <NEW_LINE> <INDENT> self.assertEqual(v, r.json()[k]) <NEW_LINE> <DEDENT> self.post(self.endpoints["runconfigs"], data=data, expected_status_code=http_client.BAD_REQUEST)
Tests for the /machines service endpoints
62598fbb3346ee7daa33771b
class TransportException(Exception): <NEW_LINE> <INDENT> pass
An error due to incomprehensible data received from the transport side
62598fbbad47b63b2c5a79fb
class UserApi: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.get_token_url = app.base_url + "/token/user" <NEW_LINE> self.token_verify_url = app.base_url + "/token/verify" <NEW_LINE> self.user_address_url = app.base_url + "/address" <NEW_LINE> <DEDENT> def get_token_api(self): <NEW_LINE> <INDENT> logging.info("用户-获取Token") <NEW_LINE> data = {"code": app.code} <NEW_LINE> return requests.post(self.get_token_url,json=data,headers=app.headers) <NEW_LINE> <DEDENT> def verify_token_api(self): <NEW_LINE> <INDENT> logging.info("用户-验证token") <NEW_LINE> data = {"token": app.headers.get("token")} <NEW_LINE> return requests.post(self.token_verify_url, json=data, headers=app.headers) <NEW_LINE> <DEDENT> def user_address_api(self): <NEW_LINE> <INDENT> logging.info("用户-用户地址信息") <NEW_LINE> return requests.get(self.user_address_url, headers=app.headers)
用户API接口方法
62598fbb60cbc95b063644e6
class MngFormat(FreeimageMulti): <NEW_LINE> <INDENT> _fif = 6 <NEW_LINE> def _can_save(self, request): <NEW_LINE> <INDENT> return False
An Mng format based on the Freeimage library. Read only. Seems broken.
62598fbb7047854f4633f57d
class NumericFieldSerializer(FieldSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = NumericField <NEW_LINE> depth = 1 <NEW_LINE> fields = ('id', 'status', 'fieldtype', 'name', 'description', 'key', 'required', 'is_displayfield', 'minval', 'maxval') <NEW_LINE> read_only_fields = ('id', 'name', 'key')
Serializer for numeric fields.
62598fbb4527f215b58ea07c
class TestMaxRange(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ranges1 = [(-0.2, 0.5), (0, 1), (-0.37, 1.02), (np.NaN, 0.3)] <NEW_LINE> self.ranges2 = [(np.NaN, np.NaN), (np.NaN, np.NaN)] <NEW_LINE> <DEDENT> def test_max_range1(self): <NEW_LINE> <INDENT> self.assertEqual(max_range(self.ranges1), (-0.37, 1.02)) <NEW_LINE> <DEDENT> def test_max_range2(self): <NEW_LINE> <INDENT> lower, upper = max_range(self.ranges2) <NEW_LINE> self.assertTrue(math.isnan(lower)) <NEW_LINE> self.assertTrue(math.isnan(upper))
Tests for max_range function.
62598fbb63d6d428bbee2958
class SaleOpportunityTestCase(ModuleTestCase): <NEW_LINE> <INDENT> module = 'sale_opportunity'
Test SaleOpportunity module
62598fbb67a9b606de546174
class EventSpinboxFilter(Qt.QObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(EventSpinboxFilter, self).__init__() <NEW_LINE> <DEDENT> def eventFilter(self, *args, **kwargs): <NEW_LINE> <INDENT> event = args[1] <NEW_LINE> eventType = args[1].type() <NEW_LINE> if eventType == Qt.QEvent.KeyPress and (event.key() == QtCore.Qt.Key_Enter or event.key() == QtCore.Qt.Key_Return): <NEW_LINE> <INDENT> args[0].emit(Qt.SIGNAL("valueChanged()")) <NEW_LINE> <DEDENT> return False
Event filter for spinbox Value is changed only when ENTER is pressed
62598fbb26068e7796d4cb02
class RegistrationFormTests(TestCase): <NEW_LINE> <INDENT> def test_registration_form(self): <NEW_LINE> <INDENT> User = get_user_model() <NEW_LINE> User.objects.create_user('alice', 'alice@example.com', 'secret') <NEW_LINE> invalid_data_dicts = [ {'data': {'username': 'foo/bar', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo'}, 'error': ('username', [u"This value may contain only letters, numbers and @/./+/-/_ characters."])}, {'data': {'username': 'alice', 'email': 'alice@example.com', 'password1': 'secret', 'password2': 'secret'}, 'error': ('username', [u"A user with that username already exists."])}, {'data': {'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'bar'}, 'error': ('__all__', [u"The two password fields didn't match."])}, ] <NEW_LINE> for invalid_dict in invalid_data_dicts: <NEW_LINE> <INDENT> form = forms.RegistrationForm(data=invalid_dict['data']) <NEW_LINE> self.failIf(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) <NEW_LINE> <DEDENT> form = forms.RegistrationForm(data={'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo'}) <NEW_LINE> self.failUnless(form.is_valid()) <NEW_LINE> <DEDENT> def test_registration_form_tos(self): <NEW_LINE> <INDENT> form = forms.RegistrationFormTermsOfService(data={'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo'}) <NEW_LINE> self.failIf(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"]) <NEW_LINE> form = forms.RegistrationFormTermsOfService(data={'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo', 'tos': 'on'}) <NEW_LINE> self.failUnless(form.is_valid()) <NEW_LINE> <DEDENT> def test_registration_form_unique_email(self): <NEW_LINE> <INDENT> User = get_user_model() <NEW_LINE> User.objects.create_user('alice', 'alice@example.com', 'secret') <NEW_LINE> form = forms.RegistrationFormUniqueEmail(data={'username': 'foo', 'email': 'alice@example.com', 'password1': 'foo', 'password2': 'foo'}) <NEW_LINE> self.failIf(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."]) <NEW_LINE> form = forms.RegistrationFormUniqueEmail(data={'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo'}) <NEW_LINE> self.failUnless(form.is_valid()) <NEW_LINE> <DEDENT> def test_registration_form_no_free_email(self): <NEW_LINE> <INDENT> base_data = {'username': 'foo', 'password1': 'foo', 'password2': 'foo'} <NEW_LINE> for domain in forms.RegistrationFormNoFreeEmail.bad_domains: <NEW_LINE> <INDENT> invalid_data = base_data.copy() <NEW_LINE> invalid_data['email'] = u"foo@%s" % domain <NEW_LINE> form = forms.RegistrationFormNoFreeEmail(data=invalid_data) <NEW_LINE> self.failIf(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."]) <NEW_LINE> <DEDENT> base_data['email'] = 'foo@example.com' <NEW_LINE> form = forms.RegistrationFormNoFreeEmail(data=base_data) <NEW_LINE> self.failUnless(form.is_valid())
Test the default registration forms.
62598fbb3d592f4c4edbb066
class CosmologyRead(io_registry.UnifiedReadWrite): <NEW_LINE> <INDENT> def __init__(self, instance, cosmo_cls): <NEW_LINE> <INDENT> super().__init__(instance, cosmo_cls, "read") <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> from astropy.cosmology.core import Cosmology <NEW_LINE> if self._cls is not Cosmology: <NEW_LINE> <INDENT> kwargs.setdefault("cosmology", self._cls) <NEW_LINE> valid = (self._cls, self._cls.__qualname__) <NEW_LINE> if kwargs["cosmology"] not in valid: <NEW_LINE> <INDENT> raise ValueError( "keyword argument `cosmology` must be either the class " f"{valid[0]} or its qualified name '{valid[1]}'") <NEW_LINE> <DEDENT> <DEDENT> cosmo = io_registry.read(self._cls, *args, **kwargs) <NEW_LINE> return cosmo
Read and parse data to a `~astropy.cosmology.Cosmology`. This function provides the Cosmology interface to the Astropy unified I/O layer. This allows easily reading a file in supported data formats using syntax such as:: >>> from astropy.cosmology import Cosmology >>> cosmo1 = Cosmology.read('<file name>') When the ``read`` method is called from a subclass the subclass will provide a keyword argument ``cosmology=<class>`` to the registered read method. The method uses this cosmology class, regardless of the class indicated in the file, and sets parameters' default values from the class' signature. Get help on the available readers using the ``help()`` method:: >>> Cosmology.read.help() # Get help reading and list supported formats >>> Cosmology.read.help(format='<format>') # Get detailed help on a format >>> Cosmology.read.list_formats() # Print list of available formats See also: https://docs.astropy.org/en/stable/io/unified.html .. note:: :meth:`~astropy.cosmology.Cosmology.read` and :meth:`~astropy.cosmology.Cosmology.from_format` currently access the same registry. This will be deprecated and formats intended for ``from_format`` should not be used here. Use ``Cosmology.read.help()`` to confirm that the format may be used to read a file. Parameters ---------- *args Positional arguments passed through to data reader. If supplied the first argument is typically the input filename. format : str (optional, keyword-only) File format specifier. **kwargs Keyword arguments passed through to data reader. Returns ------- out : `~astropy.cosmology.Cosmology` subclass instance `~astropy.cosmology.Cosmology` corresponding to file contents. Notes -----
62598fbb283ffb24f3cf3a2b
class CallBackHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> @tornado.gen.coroutine <NEW_LINE> def post(self): <NEW_LINE> <INDENT> req_head = self.request.headers <NEW_LINE> req_body = self.request.body <NEW_LINE> yield receiveQueue.queued_items.put([req_head, req_body]) <NEW_LINE> self.write("OK")
LINEからの通知(コールバック)用ハンドラ
62598fbb71ff763f4b5e7922
class newobject(object): <NEW_LINE> <INDENT> def next(self): <NEW_LINE> <INDENT> if hasattr(self, '__next__'): <NEW_LINE> <INDENT> return type(self).__next__(self) <NEW_LINE> <DEDENT> raise TypeError('newobject is not an iterator') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if hasattr(self, '__str__'): <NEW_LINE> <INDENT> s = type(self).__str__(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = str(self) <NEW_LINE> <DEDENT> if isinstance(s, unicode): <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s.decode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> if hasattr(self, '__bool__'): <NEW_LINE> <INDENT> return type(self).__bool__(self) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def __long__(self): <NEW_LINE> <INDENT> if not hasattr(self, '__int__'): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.__int__() <NEW_LINE> <DEDENT> def __native__(self): <NEW_LINE> <INDENT> return object(self)
A magical object class that provides Python 2 compatibility methods:: next __unicode__ __nonzero__ Subclasses of this class can merely define the Python 3 methods (__next__, __str__, and __bool__). This is a copy/paste of the future.types.newobject class of the future package.
62598fbbf9cc0f698b1c53a2
class GenerateManifests: <NEW_LINE> <INDENT> def __init__(self, df, directory, context): <NEW_LINE> <INDENT> self.df = df <NEW_LINE> self.directory = directory <NEW_LINE> self.context = context <NEW_LINE> self.manifest_dir = os.path.join(directory, "manifests") <NEW_LINE> self.submission_dir = os.path.join(directory, "submissions") <NEW_LINE> <DEDENT> def row_processing(self, row): <NEW_LINE> <INDENT> row = row.dropna() <NEW_LINE> row_meta = row.to_dict() <NEW_LINE> if self.context == 'reads': <NEW_LINE> <INDENT> prefix_field = row_meta.get('uploaded file 1') <NEW_LINE> <DEDENT> elif self.context == 'genome': <NEW_LINE> <INDENT> prefix_field = row_meta.get('fasta') <NEW_LINE> <DEDENT> prefix = os.path.splitext(os.path.splitext(os.path.basename(prefix_field))[0])[0] <NEW_LINE> manifest_file = os.path.join(self.manifest_dir, "Manifest_{}.txt".format(prefix)) <NEW_LINE> return manifest_file <NEW_LINE> <DEDENT> def create_manifest(self, metadata_content): <NEW_LINE> <INDENT> first_col = [] <NEW_LINE> second_col = [] <NEW_LINE> for item in metadata_content.items(): <NEW_LINE> <INDENT> field = item[0] <NEW_LINE> value = item[1] <NEW_LINE> if field in spreadsheet_column_mapping: <NEW_LINE> <INDENT> field = spreadsheet_column_mapping.get(field) <NEW_LINE> <DEDENT> elif field == "insert_size": <NEW_LINE> <INDENT> value = int(value) <NEW_LINE> <DEDENT> elif field == "uploaded file 1" or "uploaded file 2": <NEW_LINE> <INDENT> if ".fastq" in str(value) or ".fq" in str(value): <NEW_LINE> <INDENT> field = "fastq" <NEW_LINE> <DEDENT> elif ".cram" in str(value): <NEW_LINE> <INDENT> field = "cram" <NEW_LINE> <DEDENT> elif ".bam" in str(value): <NEW_LINE> <INDENT> field = "bam" <NEW_LINE> <DEDENT> <DEDENT> field = field.upper() <NEW_LINE> first_col.append(str(field)) <NEW_LINE> second_col.append(str(value)) <NEW_LINE> <DEDENT> manifest_content = {'field': first_col, 'value': second_col} <NEW_LINE> manifest_content = pd.DataFrame.from_dict(manifest_content) <NEW_LINE> return manifest_content <NEW_LINE> <DEDENT> def write_manifests(self, manifest_file, manifest_content): <NEW_LINE> <INDENT> prepare_directories(self.manifest_dir) <NEW_LINE> prepare_directories(self.submission_dir) <NEW_LINE> successful = [] <NEW_LINE> failed = [] <NEW_LINE> try: <NEW_LINE> <INDENT> out = manifest_content.to_csv(manifest_file, sep="\t", index=False, header=False) <NEW_LINE> successful.append(manifest_file) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> failed.append(manifest_file) <NEW_LINE> print('> ERROR during creation of manifest file: '+str(e)) <NEW_LINE> <DEDENT> return successful, failed <NEW_LINE> <DEDENT> def generate_manifests(self): <NEW_LINE> <INDENT> all_successful_files = [] <NEW_LINE> all_failed_files = [] <NEW_LINE> for index, row in self.df.iterrows(): <NEW_LINE> <INDENT> manifest_file = self.row_processing(row) <NEW_LINE> manifest_content = self.create_manifest(row) <NEW_LINE> successful_files, failed_files = self.write_manifests(manifest_file, manifest_content) <NEW_LINE> all_successful_files.append(successful_files) <NEW_LINE> all_failed_files.append(failed_files) <NEW_LINE> <DEDENT> return all_successful_files, all_failed_files
Class object that coordinates the generation of manifest files
62598fbb66673b3332c30579
class ConfigParserWithDefaults(configparser.ConfigParser): <NEW_LINE> <INDENT> def get(self, section, options, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = configparser.ConfigParser.get(self, section, options, **kwargs) <NEW_LINE> <DEDENT> except configparser.NoOptionError: <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def getint(self, section, options, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = configparser.ConfigParser.get(self, section, options, **kwargs) <NEW_LINE> <DEDENT> except configparser.NoOptionError: <NEW_LINE> <INDENT> result = 0 <NEW_LINE> <DEDENT> return int(result)
This is just a wrapper on ConfigParser, that uses default values
62598fbb4f88993c371f05e1
class NCISerial(NeatoCommandInterface): <NEW_LINE> <INDENT> def __init__(self, port="/dev/ttyACM0", baudrate=115200, timeout=0.5): <NEW_LINE> <INDENT> self.ser = serial.Serial() <NEW_LINE> self.ser.port = port <NEW_LINE> self.ser.baudrate = baudrate <NEW_LINE> self.ser.bytesize = serial.EIGHTBITS <NEW_LINE> self.ser.parity = serial.PARITY_NONE <NEW_LINE> self.ser.stopbits = serial.STOPBITS_ONE <NEW_LINE> self.ser.timeout = timeout <NEW_LINE> self.ser.write_timeout = 2 <NEW_LINE> self.isready = False <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.ser.open() <NEW_LINE> self.isready = True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> L.error("[NCISerial] Error open serial port: " + str(e)) <NEW_LINE> self.isready = False <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.isready = False <NEW_LINE> self.ser.close() <NEW_LINE> <DEDENT> def ready(self): <NEW_LINE> <INDENT> if self.isready: <NEW_LINE> <INDENT> return self.ser.isOpen() <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> if self.ready(): <NEW_LINE> <INDENT> self.ser.flushInput() <NEW_LINE> self.ser.flushOutput() <NEW_LINE> self.ser.flush() <NEW_LINE> <DEDENT> <DEDENT> def put(self, line): <NEW_LINE> <INDENT> if self.ready() == False: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> sendcmd = line.strip() + "\n" <NEW_LINE> self.ser.write(sendcmd.encode('ASCII')) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if self.ready() == False: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> retval = "" <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.ser.readline() <NEW_LINE> <DEDENT> except TimeoutError: <NEW_LINE> <INDENT> L.debug('[NCISerial] timeout read') <NEW_LINE> break <NEW_LINE> <DEDENT> if len(response) < 1: <NEW_LINE> <INDENT> L.debug('[NCISerial] read null') <NEW_LINE> break <NEW_LINE> <DEDENT> response = response.decode('ASCII') <NEW_LINE> if len(response) < 1: <NEW_LINE> <INDENT> L.debug('[NCISerial] read null 2') <NEW_LINE> break <NEW_LINE> <DEDENT> response = response.strip() <NEW_LINE> if len(response) == 1: <NEW_LINE> <INDENT> if response[0] == '\x1A': <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> response = response.replace('\x1A', '\n') <NEW_LINE> response = response.replace('\r\n', '\n') <NEW_LINE> retval += response + "\n" <NEW_LINE> <DEDENT> retval = retval.replace('\n\n', '\n') <NEW_LINE> return retval.strip() + "\n\n"
Neato Command Interface for serial ports
62598fbbd268445f26639c58
class MirrorSweepRectangle(StoppableThread): <NEW_LINE> <INDENT> def __init__(self, driver, point_a, point_b, step, wait_time = 0): <NEW_LINE> <INDENT> super(MirrorSweepRectangle, self).__init__() <NEW_LINE> self.driver = driver <NEW_LINE> self.driver.running_sweep = False <NEW_LINE> self.point_a = point_a <NEW_LINE> self.point_b = point_b <NEW_LINE> self.step = step <NEW_LINE> self.wait_time = wait_time <NEW_LINE> <DEDENT> def move(self, x, y): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.stopped(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.driver.MoveAbsoluteX(x) <NEW_LINE> break <NEW_LINE> <DEDENT> except TimeoutError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.stopped(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.driver.MoveAbsoluteY(y) <NEW_LINE> break <NEW_LINE> <DEDENT> except TimeoutError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def calculate_coords_range(self, a, b, step): <NEW_LINE> <INDENT> if a > b: <NEW_LINE> <INDENT> return np.arange(a,b-step,-step) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.arange(a,b+step,step) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.driver.running_sweep = True <NEW_LINE> coords_x = self.calculate_coords_range(self.point_a[0], self.point_b[0], self.step) <NEW_LINE> coords_y = self.calculate_coords_range(self.point_a[1], self.point_b[1], self.step) <NEW_LINE> while True: <NEW_LINE> <INDENT> for x in coords_x: <NEW_LINE> <INDENT> for y in coords_y: <NEW_LINE> <INDENT> self.move(x,y) <NEW_LINE> time.sleep(self.wait_time) <NEW_LINE> if self.stopped(): <NEW_LINE> <INDENT> logging.warning("ZaberTMM info: stopped sweeping") <NEW_LINE> self.driver.running_sweep = False <NEW_LINE> return
Mirror sweep in a separate thread to ensure continous data acquisition simultaneous to sweeping the mirror. Define a rectangle by two opposing corners to sweep through.
62598fbbe1aae11d1e7ce8f9
class _Project(ArchIFC.IfcContext): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> obj.Proxy = self <NEW_LINE> self.setProperties(obj) <NEW_LINE> obj.IfcType = "Project" <NEW_LINE> <DEDENT> def setProperties(self, obj): <NEW_LINE> <INDENT> ArchIFC.IfcContext.setProperties(self, obj) <NEW_LINE> pl = obj.PropertiesList <NEW_LINE> if not hasattr(obj,"Group"): <NEW_LINE> <INDENT> obj.addExtension("App::GroupExtensionPython") <NEW_LINE> <DEDENT> self.Type = "Project" <NEW_LINE> <DEDENT> def onDocumentRestored(self, obj): <NEW_LINE> <INDENT> self.setProperties(obj) <NEW_LINE> <DEDENT> def addObject(self,obj,child): <NEW_LINE> <INDENT> if not child in obj.Group: <NEW_LINE> <INDENT> g = obj.Group <NEW_LINE> g.append(child) <NEW_LINE> obj.Group = g
The project object. Takes a <Part::FeaturePython>, and turns it into a Project. Then takes a list of Arch sites to own as its children. Parameters ---------- obj: <App::DocumentObjectGroupPython> or <App::FeaturePython> The object to turn into a Project.
62598fbbbe7bc26dc9251f30
class Soulution: <NEW_LINE> <INDENT> def GetLeastNumbers(self, tinput, k): <NEW_LINE> <INDENT> tinput.sort() <NEW_LINE> return tinput[:k] if len(tinput) > k else []
输入n个整数,找出其中最小的K个数。 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。输入n个整数,找出其中最小的K个数。 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
62598fbb377c676e912f6e45
class ScheduleAction(Action): <NEW_LINE> <INDENT> def __init__(self, instance, *, condition=None): <NEW_LINE> <INDENT> self.job_id = instance.job_id <NEW_LINE> self.args = instance.args <NEW_LINE> self.condition = condition <NEW_LINE> <DEDENT> async def __call__(self, apsis, run): <NEW_LINE> <INDENT> if self.condition is not None and not self.condition(run): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> args = { n: runs.template_expand(v, run.inst.args) for n, v in self.args.items() } <NEW_LINE> inst = runs.Instance(self.job_id, args) <NEW_LINE> inst = apsis._propagate_args(run.inst.args, inst) <NEW_LINE> log.info(f"action for {run.run_id}: scheduling {inst}") <NEW_LINE> new_run = await apsis.schedule(None, runs.Run(inst)) <NEW_LINE> log.info(f"action for {run.run_id}: scheduled {new_run.run_id}") <NEW_LINE> apsis.run_log.info( run, f"action scheduling {inst} as {new_run.run_id}") <NEW_LINE> apsis.run_log.info( new_run, f"scheduled by action of {run.run_id}") <NEW_LINE> <DEDENT> def to_jso(self): <NEW_LINE> <INDENT> return { **super().to_jso(), "job_id" : self.job_id, "args" : self.args, "condition" : self.condition.to_jso() } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_jso(cls, jso): <NEW_LINE> <INDENT> with check_schema(jso) as pop: <NEW_LINE> <INDENT> job_id = pop("job_id") <NEW_LINE> args = pop("args", default={}) <NEW_LINE> condition = Condition.from_jso(pop("if", default=None)) <NEW_LINE> <DEDENT> return cls(runs.Instance(job_id, args), condition=condition)
Schedules a new run.
62598fbb4f6381625f199597
class GenerativeModel: <NEW_LINE> <INDENT> def __init__(self, config: Config, loss_terms: [LossTerm], dis_a: Model, dis_b: Model, gen_a: Model, gen_b: Model): <NEW_LINE> <INDENT> self.model: Model = None <NEW_LINE> self.config = config <NEW_LINE> self.batch_size = config.batch_size <NEW_LINE> self.dis_a = dis_a <NEW_LINE> self.dis_b = dis_b <NEW_LINE> self.gen_a = gen_a <NEW_LINE> self.gen_b = gen_b <NEW_LINE> self.loss_terms = loss_terms <NEW_LINE> self.loss_names = ['generative_model/'] <NEW_LINE> for term in self.loss_terms: <NEW_LINE> <INDENT> for name in term.names: <NEW_LINE> <INDENT> self.loss_names.append(f'generative_model/{name}') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def compile(self): <NEW_LINE> <INDENT> self.dis_a.trainable = False <NEW_LINE> self.dis_b.trainable = False <NEW_LINE> outputs, losses, weights = [], [], [] <NEW_LINE> real_a = Input(shape=self.config.image_shape) <NEW_LINE> real_b = Input(shape=self.config.image_shape) <NEW_LINE> fake_b = self.gen_a(real_a) <NEW_LINE> fake_a = self.gen_b(real_b) <NEW_LINE> inputs = [real_a, real_b] <NEW_LINE> for term in self.loss_terms: <NEW_LINE> <INDENT> term.compile(self.dis_a, self.dis_b, self.gen_a, self.gen_b, real_a, fake_a, real_b, fake_b) <NEW_LINE> outputs.extend(term.outputs) <NEW_LINE> losses.extend(term.losses) <NEW_LINE> weights.extend(term.weights) <NEW_LINE> <DEDENT> model = Model(inputs, outputs) <NEW_LINE> model.compile(optimizer=self.config.optimizer_g, loss=losses, loss_weights=weights) <NEW_LINE> self.model = model <NEW_LINE> <DEDENT> def train_on_batch(self, real_a, real_b): <NEW_LINE> <INDENT> self.dis_a.trainable = False <NEW_LINE> self.dis_b.trainable = False <NEW_LINE> inputs = [real_a, real_b] <NEW_LINE> outputs = [] <NEW_LINE> for term in self.loss_terms: <NEW_LINE> <INDENT> outputs.extend(term.get_targets(self.batch_size, self.dis_b, self.gen_b)) <NEW_LINE> <DEDENT> g_loss = self.model.train_on_batch(inputs, outputs) <NEW_LINE> return list(zip(self.loss_names, g_loss))
Combines two generators into a single generative model
62598fbb5fcc89381b266221
class InfoCommand(Command): <NEW_LINE> <INDENT> def __init__(self, subparsers, parser): <NEW_LINE> <INDENT> subparser = self.add_parser_compat(subparsers, 'info', help="get static information about a network", epilog=parser.epilog) <NEW_LINE> subparser.add_argument('network', metavar='NETWORK', type=_network_address, help="a network address") <NEW_LINE> subparser.set_defaults(func=self.func) <NEW_LINE> <DEDENT> def func(self, args): <NEW_LINE> <INDENT> net = args.network <NEW_LINE> assert net.version in (4, 6) <NEW_LINE> if net.version == 4: <NEW_LINE> <INDENT> info_addr = [ ('IP address', net.ip), ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info_type = net.info.IPv6[0].allocation <NEW_LINE> <DEDENT> except (AttributeError, IndexError): <NEW_LINE> <INDENT> info_type = "None" <NEW_LINE> <DEDENT> info_addr = [ ('Compact address', net.ip.format(netaddr.ipv6_compact)), ('Expanded address', net.ip.format(netaddr.ipv6_verbose)), ('Address type', info_type), ] <NEW_LINE> <DEDENT> info = info_addr + [ ('Network address', net.cidr), ('Network mask', net.netmask.format(netaddr.ipv6_full)), ('Prefix length', net.prefixlen), ('Host wildcard', net.hostmask.format(netaddr.ipv6_full)), ('Broadcast address', net.broadcast if net.version == 4 else "N/A"), ('Address count', net.size), ('First address', netaddr.IPAddress(net.first, net.version).format(netaddr.ipv6_verbose)), ('Last address', netaddr.IPAddress(net.last, net.version).format(netaddr.ipv6_verbose)), ] <NEW_LINE> padding = max([len(i[0]) for i in info]) <NEW_LINE> for descr, value in info: <NEW_LINE> <INDENT> print("%-*s - %s" % (padding, descr, str(value)))
Get static information about a network. Arguments: NETWORK Example: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers() >>> info = InfoCommand(subparsers, parser) >>> args = parser.parse_args("info 192.0.2.18/24".split()) >>> args.func(args) IP address - 192.0.2.18 Network address - 192.0.2.0/24 Network mask - 255.255.255.0 Prefix length - 24 Host wildcard - 0.0.0.255 Broadcast address - 192.0.2.255 Address count - 256 First address - 192.0.2.0 Last address - 192.0.2.255
62598fbb796e427e5384e93f
class Not_Compiled_Error(Exception): <NEW_LINE> <INDENT> pass
Raised when code that should be compiled is found to be interpreted instead.
62598fbb3d592f4c4edbb068
class no_grad(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.prev = torch.is_grad_enabled() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> torch._C.set_grad_enabled(False) <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> torch.set_grad_enabled(self.prev) <NEW_LINE> return False
Context-manager that disabled gradient calculation. Disabling gradient calculation is useful for inference, when you are sure that you will not call :meth:`Variable.backward()`. It will reduce memory consumption for computations that would otherwise have `requires_grad=True`. In this mode, the result of every computation will have `requires_grad=False`, even when the inputs have `requires_grad=True`. Example:: >>> x = torch.tensor([1], requires_grad=True) >>> with torch.no_grad(): ... y = x * 2 >>> y.requires_grad False
62598fbb0fa83653e46f508e
class Creature: <NEW_LINE> <INDENT> id_count = 0 <NEW_LINE> def __init__(self, x, y, dx, dy, color, radius): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.dx = dx <NEW_LINE> self.dy = dy <NEW_LINE> self.color = color <NEW_LINE> self.radius = radius <NEW_LINE> self.id = Creature.id_count <NEW_LINE> Creature.id_count += 1 <NEW_LINE> <DEDENT> def step(self, world, overlapping): <NEW_LINE> <INDENT> self.x += self.dx <NEW_LINE> self.y += self.dy <NEW_LINE> ddx = random.random() * 0.3 - 0.15 <NEW_LINE> ddy = random.random() * 0.3 - 0.15 <NEW_LINE> if self.x < self.radius: <NEW_LINE> <INDENT> ddx -= self.x - self.radius <NEW_LINE> <DEDENT> elif self.x > world.width - self.radius: <NEW_LINE> <INDENT> ddx += world.width - self.radius - self.x <NEW_LINE> <DEDENT> if self.y < self.radius: <NEW_LINE> <INDENT> ddy -= self.y - self.radius <NEW_LINE> <DEDENT> elif self.y > world.height - self.radius: <NEW_LINE> <INDENT> ddy += world.height - self.radius - self.y <NEW_LINE> <DEDENT> for other in overlapping: <NEW_LINE> <INDENT> dist = self.distance(other.x, other.y) <NEW_LINE> if dist: <NEW_LINE> <INDENT> ddx -= 3 * (other.x - self.x) / dist <NEW_LINE> ddy -= 3 * (other.y - self.y) / dist <NEW_LINE> <DEDENT> <DEDENT> self.dx += ddx <NEW_LINE> self.dy += ddy <NEW_LINE> if abs(self.dx) > 7: <NEW_LINE> <INDENT> self.dx *= 7 / abs(self.dx) <NEW_LINE> <DEDENT> if abs(self.dy) > 7: <NEW_LINE> <INDENT> self.dy *= 7 / abs(self.dy) <NEW_LINE> <DEDENT> <DEDENT> def draw(self, screen): <NEW_LINE> <INDENT> pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.radius)) <NEW_LINE> <DEDENT> def box(self): <NEW_LINE> <INDENT> r2 = self.radius <NEW_LINE> res = [self.x - r2, self.y - r2, self.x + r2, self.y + r2] <NEW_LINE> return res <NEW_LINE> <DEDENT> def distance(self, x1, y1): <NEW_LINE> <INDENT> dx = self.x - x1 <NEW_LINE> dy = self.y - y1 <NEW_LINE> return math.sqrt(dx * dx + dy * dy)
Creature class representing one bouncing ball for now.
62598fbb9c8ee82313040249
class ITermField(Interface): <NEW_LINE> <INDENT> pass
A field using an ITerm as an object value.
62598fbb7c178a314d78d649
class StencylTests(LargeFrameworkTests): <NEW_LINE> <INDENT> TIMEOUT_INSTALL_PROGRESS = 120 <NEW_LINE> TIMEOUT_START = 20 <NEW_LINE> TIMEOUT_STOP = 20 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.installed_path = os.path.join(self.install_base_path, "games", "stencyl") <NEW_LINE> self.desktop_filename = "stencyl.desktop" <NEW_LINE> <DEDENT> def test_default_stencyl_install(self): <NEW_LINE> <INDENT> self.child = spawn_process(self.command('{} games stencyl'.format(UMAKE))) <NEW_LINE> self.expect_and_no_warn("Choose installation path: {}".format(self.installed_path)) <NEW_LINE> self.child.sendline("") <NEW_LINE> self.expect_and_no_warn("Installation done", timeout=self.TIMEOUT_INSTALL_PROGRESS) <NEW_LINE> self.wait_and_close() <NEW_LINE> self.assertTrue(self.launcher_exists_and_is_pinned(self.desktop_filename)) <NEW_LINE> self.assert_exec_exists() <NEW_LINE> self.assert_icon_exists() <NEW_LINE> self.assert_exec_link_exists() <NEW_LINE> use_cwd = self.installed_path <NEW_LINE> if self.in_container: <NEW_LINE> <INDENT> use_cwd = None <NEW_LINE> <DEDENT> proc = subprocess.Popen(self.command_as_list(self.exec_path), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, cwd=use_cwd) <NEW_LINE> self.check_and_kill_process([self.exec_path], wait_before=self.TIMEOUT_START) <NEW_LINE> proc.wait(self.TIMEOUT_STOP) <NEW_LINE> self.child = spawn_process(self.command('{} games stencyl'.format(UMAKE))) <NEW_LINE> self.expect_and_no_warn("Stencyl is already installed.*\[.*\] ") <NEW_LINE> self.child.sendline() <NEW_LINE> self.wait_and_close()
This will test the Stencyl installation
62598fbb656771135c489818
class LoadYaml(TemplatePlugin): <NEW_LINE> <INDENT> aliases = ['loadyaml'] <NEW_LINE> def load_yaml(self, filename): <NEW_LINE> <INDENT> import yaml <NEW_LINE> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> return yaml.safe_load(f.read()) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> return { 'load_yaml' : ("Safely load YAML from a file.", self.load_yaml,) }
Loads YAML from a file.
62598fbb851cf427c66b8460
class TestV1LoadBalancerIngress(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 testV1LoadBalancerIngress(self): <NEW_LINE> <INDENT> pass
V1LoadBalancerIngress unit test stubs
62598fbbd268445f26639c59
class _SubnetworkSpec( collections.namedtuple("_SubnetworkSpec", [ "name", "subnetwork", "builder", "predictions", "loss", "train_op", "eval_metrics", ])): <NEW_LINE> <INDENT> def __new__(cls, name, subnetwork, builder, predictions, loss=None, train_op=None, eval_metrics=None): <NEW_LINE> <INDENT> return super(_SubnetworkSpec, cls).__new__( cls, name=name, subnetwork=subnetwork, builder=builder, predictions=predictions, loss=loss, train_op=train_op, eval_metrics=eval_metrics)
Subnetwork training and evaluation `Tensors` and `Ops`. Args: name: String name of this subnetwork. Should be unique in the graph. subnetwork: The `adanet.subnetwork.Subnetwork` for this spec. builder: The `adanet.subnetwork.Builder` that produced `subnetwork`. predictions: Predictions `Tensor` or dict of `Tensor`. loss: Loss `Tensor` as computed by the `Head`. Must be either scalar, or with shape `[1]`. train_op: Candidate subnetwork's `TrainOpSpec`. eval_metrics: Tuple of (metric_fn, tensors) where metric_fn(tensors) returns the dict of eval metrics keyed by name. The values of the dict are the results of calling a metric function, namely a `(metric_tensor, update_op)` tuple. `metric_tensor` should be evaluated without any impact on state (typically is a pure computation based on variables.). For example, it should not trigger the `update_op` or require any input fetching. Returns: A `_SubnetworkSpec` object.
62598fbb377c676e912f6e46
class _Model(_Register): <NEW_LINE> <INDENT> pass
The model registry; all models are accessed through here for reconstruction.
62598fbb63b5f9789fe8531a
class Queue(object): <NEW_LINE> <INDENT> def __init__(self, name, config=None): <NEW_LINE> <INDENT> specified_config = config or {} <NEW_LINE> self.name = name <NEW_LINE> self._name = 'retaskqueue-' + name <NEW_LINE> self.config = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None, } <NEW_LINE> self.config.update(specified_config) <NEW_LINE> self.rdb = None <NEW_LINE> self.connected = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def length(self): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> raise ConnectionError('Queue is not connected') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> length = self.rdb.llen(self._name) <NEW_LINE> <DEDENT> except redis.exceptions.ConnectionError as err: <NEW_LINE> <INDENT> raise ConnectionError(str(err)) <NEW_LINE> <DEDENT> return length <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> self.rdb = redis.Redis(config['host'], config['port'], config['db'], config['password']) <NEW_LINE> try: <NEW_LINE> <INDENT> info = self.rdb.info() <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> except redis.ConnectionError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def wait(self, wait_time=0): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> raise ConnectionError('Queue is not connected') <NEW_LINE> <DEDENT> data = self.rdb.brpop(self._name, wait_time) <NEW_LINE> if data: <NEW_LINE> <INDENT> task = Task() <NEW_LINE> task.__dict__ = json.loads(data[1]) <NEW_LINE> return task <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def dequeue(self): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> raise ConnectionError('Queue is not connected') <NEW_LINE> <DEDENT> if self.rdb.llen(self._name) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> data = self.rdb.rpop(self._name) <NEW_LINE> if not data: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(data, six.binary_type): <NEW_LINE> <INDENT> data = six.text_type(data, 'utf-8', errors = 'replace') <NEW_LINE> <DEDENT> task = Task() <NEW_LINE> task.__dict__ = json.loads(data) <NEW_LINE> return task <NEW_LINE> <DEDENT> def enqueue(self, task): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> raise ConnectionError('Queue is not connected') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> job = Job(self.rdb) <NEW_LINE> task.urn = job.urn <NEW_LINE> text = json.dumps(task.__dict__) <NEW_LINE> self.rdb.lpush(self._name, text) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return job <NEW_LINE> <DEDENT> def send(self, task, result, expire=60): <NEW_LINE> <INDENT> self.rdb.lpush(task.urn, json.dumps(result)) <NEW_LINE> self.rdb.expire(task.urn, expire) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> return '%s()' % (self.__class__.__name__,) <NEW_LINE> <DEDENT> return '%s(%r)' % (self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def find(self, obj): <NEW_LINE> <INDENT> if not self.connected: <NEW_LINE> <INDENT> raise ConnectionError('Queue is not connected') <NEW_LINE> <DEDENT> data = self.rdb.lrange(self._name, 0, -1) <NEW_LINE> for i, datum in enumerate(data): <NEW_LINE> <INDENT> if datum.find(str(obj)) != -1: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return -1
Returns the ``Queue`` object with the given name. If the user passes optional config dictionary with details for Redis server, it will connect to that instance. By default it connects to the localhost.
62598fbb3617ad0b5ee062f1
class ThemeFilesFinder(BaseFinder): <NEW_LINE> <INDENT> storage_class = ThemeStorage <NEW_LINE> source_dir = 'static' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.themes = [] <NEW_LINE> self.storages = OrderedDict() <NEW_LINE> themes = get_themes() <NEW_LINE> for theme in themes: <NEW_LINE> <INDENT> theme_storage = self.storage_class( os.path.join(theme.path, self.source_dir), prefix=theme.theme_dir_name, ) <NEW_LINE> self.storages[theme.theme_dir_name] = theme_storage <NEW_LINE> if theme.theme_dir_name not in self.themes: <NEW_LINE> <INDENT> self.themes.append(theme.theme_dir_name) <NEW_LINE> <DEDENT> <DEDENT> super(ThemeFilesFinder, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def list(self, ignore_patterns): <NEW_LINE> <INDENT> for storage in six.itervalues(self.storages): <NEW_LINE> <INDENT> if storage.exists(''): <NEW_LINE> <INDENT> for path in utils.get_files(storage, ignore_patterns): <NEW_LINE> <INDENT> yield path, storage <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def find(self, path, all=False): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> theme_dir_name = path.split("/", 1)[0] <NEW_LINE> themes = {t.theme_dir_name: t for t in get_themes()} <NEW_LINE> if theme_dir_name in themes: <NEW_LINE> <INDENT> theme = themes[theme_dir_name] <NEW_LINE> path = "/".join(path.split("/")[1:]) <NEW_LINE> match = self.find_in_theme(theme.theme_dir_name, path) <NEW_LINE> if match: <NEW_LINE> <INDENT> if not all: <NEW_LINE> <INDENT> return match <NEW_LINE> <DEDENT> matches.append(match) <NEW_LINE> <DEDENT> <DEDENT> return matches <NEW_LINE> <DEDENT> def find_in_theme(self, theme, path): <NEW_LINE> <INDENT> storage = self.storages.get(theme, None) <NEW_LINE> if storage: <NEW_LINE> <INDENT> if storage.exists(path): <NEW_LINE> <INDENT> matched_path = storage.path(path) <NEW_LINE> if matched_path: <NEW_LINE> <INDENT> return matched_path
A static files finder that looks in the directory of each theme as specified in the source_dir attribute.
62598fbb4a966d76dd5ef07e
class PythonModuleIndex(Index): <NEW_LINE> <INDENT> name = 'modindex' <NEW_LINE> localname = l_('Python Module Index') <NEW_LINE> shortname = l_('modules') <NEW_LINE> def generate(self, docnames=None): <NEW_LINE> <INDENT> content = {} <NEW_LINE> ignores = self.domain.env.config['modindex_common_prefix'] <NEW_LINE> ignores = sorted(ignores, key=len, reverse=True) <NEW_LINE> modules = sorted(self.domain.data['modules'].iteritems(), key=lambda x: x[0].lower()) <NEW_LINE> prev_modname = '' <NEW_LINE> num_toplevels = 0 <NEW_LINE> for modname, (docname, synopsis, platforms, deprecated) in modules: <NEW_LINE> <INDENT> if docnames and docname not in docnames: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for ignore in ignores: <NEW_LINE> <INDENT> if modname.startswith(ignore): <NEW_LINE> <INDENT> modname = modname[len(ignore):] <NEW_LINE> stripped = ignore <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> stripped = '' <NEW_LINE> <DEDENT> if not modname: <NEW_LINE> <INDENT> modname, stripped = stripped, '' <NEW_LINE> <DEDENT> entries = content.setdefault(modname[0].lower(), []) <NEW_LINE> package = modname.split('.')[0] <NEW_LINE> if package != modname: <NEW_LINE> <INDENT> if prev_modname == package: <NEW_LINE> <INDENT> if entries: <NEW_LINE> <INDENT> entries[-1][1] = 1 <NEW_LINE> <DEDENT> <DEDENT> elif not prev_modname.startswith(package): <NEW_LINE> <INDENT> entries.append([stripped + package, 1, '', '', '', '', '']) <NEW_LINE> <DEDENT> subtype = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_toplevels += 1 <NEW_LINE> subtype = 0 <NEW_LINE> <DEDENT> qualifier = deprecated and _('Deprecated') or '' <NEW_LINE> entries.append([stripped + modname, subtype, docname, 'module-' + stripped + modname, platforms, qualifier, synopsis]) <NEW_LINE> prev_modname = modname <NEW_LINE> <DEDENT> collapse = len(modules) - num_toplevels < num_toplevels <NEW_LINE> content = sorted(content.iteritems()) <NEW_LINE> return content, collapse
Index subclass to provide the Python module index.
62598fbb4527f215b58ea080
class Actor(db.Model): <NEW_LINE> <INDENT> __tablename__ = "actors" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String, nullable=False) <NEW_LINE> age = db.Column(db.Integer, nullable=False) <NEW_LINE> gender = db.Column(db.String, nullable=False) <NEW_LINE> def get_actorname(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def insert(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> db.session.commit() <NEW_LINE> <DEDENT> def format(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, 'age': self.age, 'gender': self.gender }
Actor Model to create actor table in postgres Each Actor must have a name, age, gender
62598fbbf548e778e596b751
class Backend(abc.ABC): <NEW_LINE> <INDENT> def __init__(self, title): <NEW_LINE> <INDENT> self._title = title <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def add_data(self, module_name, datum, step): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def add_histogram(self, module_name, datum, step): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return self._title
Base class for visualiation backends. :class:`~ikkuna.export.subscriber.Subscriber`\ s use this class to dispatch their metrics to have them visualised. Attributes ---------- title : str The figure title
62598fbbbe383301e02539a9
class ContainerTest(unittest_utils.ForsetiTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @mock.patch.object( google.auth, 'default', return_value=(mock.Mock(spec_set=credentials.Credentials), 'test-project')) <NEW_LINE> def setUpClass(cls, mock_google_credential): <NEW_LINE> <INDENT> fake_global_configs = { 'container': {'max_calls': 9, 'period': 1}} <NEW_LINE> cls.container_client = container.ContainerClient( global_configs=fake_global_configs, use_rate_limiter=False) <NEW_LINE> cls.project_id = fake_container.FAKE_PROJECT_ID <NEW_LINE> cls.zone = fake_container.FAKE_ZONE <NEW_LINE> <DEDENT> @mock.patch.object( google.auth, 'default', return_value=(mock.Mock(spec_set=credentials.Credentials), 'test-project')) <NEW_LINE> def test_no_quota(self, mock_google_credential): <NEW_LINE> <INDENT> container_client = container.ContainerClient(global_configs={}) <NEW_LINE> self.assertEqual(None, container_client.repository._rate_limiter) <NEW_LINE> <DEDENT> def test_get_serverconfig_by_zone(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.FAKE_GET_SERVERCONFIG_RESPONSE) <NEW_LINE> result = self.container_client.get_serverconfig( self.project_id, zone=self.zone) <NEW_LINE> self.assertEqual( json.loads(fake_container.FAKE_GET_SERVERCONFIG_RESPONSE), result) <NEW_LINE> <DEDENT> def test_get_serverconfig_by_location(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.FAKE_GET_SERVERCONFIG_RESPONSE) <NEW_LINE> result = self.container_client.get_serverconfig( self.project_id, location=fake_container.FAKE_LOCATION) <NEW_LINE> self.assertEqual( json.loads(fake_container.FAKE_GET_SERVERCONFIG_RESPONSE), result) <NEW_LINE> <DEDENT> def test_get_serverconfig_by_location_and_zone(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.FAKE_GET_SERVERCONFIG_RESPONSE) <NEW_LINE> result = self.container_client.get_serverconfig( self.project_id, zone=self.zone, location=fake_container.FAKE_LOCATION) <NEW_LINE> self.assertEqual( json.loads(fake_container.FAKE_GET_SERVERCONFIG_RESPONSE), result) <NEW_LINE> <DEDENT> def test_get_serverconfig_missing_location_and_zone(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.container_client.get_serverconfig(self.project_id) <NEW_LINE> <DEDENT> <DEDENT> def test_get_serverconfig_error(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.INVALID_ARGUMENT_400, '400') <NEW_LINE> with self.assertRaises(api_errors.ApiExecutionError): <NEW_LINE> <INDENT> self.container_client.get_serverconfig( self.project_id, zone=fake_container.FAKE_BAD_ZONE) <NEW_LINE> <DEDENT> <DEDENT> def test_get_clusters(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.FAKE_GET_CLUSTERS_RESPONSE) <NEW_LINE> results = self.container_client.get_clusters(self.project_id) <NEW_LINE> self.assertEqual(fake_container.EXPECTED_CLUSTER_NAMES, [r.get('name') for r in results]) <NEW_LINE> <DEDENT> def test_get_clusters_error(self): <NEW_LINE> <INDENT> http_mocks.mock_http_response( fake_container.INVALID_ARGUMENT_400, '400') <NEW_LINE> with self.assertRaises(api_errors.ApiExecutionError): <NEW_LINE> <INDENT> self.container_client.get_clusters( self.project_id, zone=fake_container.FAKE_BAD_ZONE)
Test the Container Client.
62598fbb60cbc95b063644ea
class Commands(Enum): <NEW_LINE> <INDENT> DESCRIBE = 'describe' <NEW_LINE> PLACE = 'place' <NEW_LINE> CONSUME = 'consume' <NEW_LINE> CLOSE = 'close' <NEW_LINE> EXTEND = 'extend' <NEW_LINE> TRANSFER = 'transfer' <NEW_LINE> RAW = 'raw' <NEW_LINE> LIST = 'list' <NEW_LINE> CUSTOMIZE = 'customize' <NEW_LINE> PRODUCE = 'produce'
Values COMMAND can take.
62598fbb3d592f4c4edbb06a
class UserValid(_NotifyUser): <NEW_LINE> <INDENT> verb = 'vérifiée' <NEW_LINE> template_name = 'projects/participation_valid.md'
Notify a user their participation was marked as valid.
62598fbb9c8ee8231304024a
class TaeminPluginTest(utils.TaeminTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.plugin = plugin.TaeminPlugin(self.taemin) <NEW_LINE> <DEDENT> @mock.patch("irc.client.ServerConnection.privmsg") <NEW_LINE> def test_privmsg(self, privmsg): <NEW_LINE> <INDENT> self.plugin.privmsg("#bla", "bla") <NEW_LINE> privmsg.assert_called_with("#bla", "bla") <NEW_LINE> privmsg.reset_mock() <NEW_LINE> self.plugin.privmsg("#bla", b"\x00") <NEW_LINE> privmsg.assert_called_with("#bla", "\x00")
test TaeminPlugin class
62598fbb57b8e32f525081f2
class UsersView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> queryset = User.objects.all() <NEW_LINE> renderer_classes = (JSONRenderer, ) <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> lookup_field = 'id'
API for reviewers. Handles GET :returns: All reviewers Handles POST :returns: A JSON with applied data in it.
62598fbb656771135c48981a
class MessengerOverworld(World): <NEW_LINE> <INDENT> def __init__(self, opt, agent): <NEW_LINE> <INDENT> self.agent = agent <NEW_LINE> self.opt = opt <NEW_LINE> self.first_time = True <NEW_LINE> self.episodeDone = False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_world(opt, agents): <NEW_LINE> <INDENT> return MessengerOverworld(opt, agents[0]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def assign_roles(agents): <NEW_LINE> <INDENT> for a in agents: <NEW_LINE> <INDENT> a.disp_id = 'Agent' <NEW_LINE> <DEDENT> <DEDENT> def episode_done(self): <NEW_LINE> <INDENT> return self.episodeDone <NEW_LINE> <DEDENT> def parley(self): <NEW_LINE> <INDENT> if self.first_time: <NEW_LINE> <INDENT> self.agent.observe( { 'id': 'Overworld', 'text': 'Welcome to the overworld for the ParlAI messenger ' 'chatbot demo. Please type "begin" to start.', 'quick_replies': ['begin'], } ) <NEW_LINE> self.first_time = False <NEW_LINE> <DEDENT> a = self.agent.act() <NEW_LINE> if a is not None and a['text'].lower() == 'begin': <NEW_LINE> <INDENT> self.episodeDone = True <NEW_LINE> return 'default' <NEW_LINE> <DEDENT> elif a is not None: <NEW_LINE> <INDENT> self.agent.observe( { 'id': 'Overworld', 'text': 'Invalid option. Please type "begin".', 'quick_replies': ['begin'], } )
World to handle moving agents to their proper places.
62598fbba8370b77170f058c