code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FileAlreadyExists(Exception): <NEW_LINE> <INDENT> pass
Raise File already exists exception
6259906aa219f33f346c7ffd
class News_SourceTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_source = News_Source("CBSN","CBSN NEWS","CBSN is the leading free news platform","cbsn.com","business","us", "en") <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.new_source,News_Source)) <NEW_LINE> <DEDENT> def test_to_check_instance_variables(self): <NEW_LINE> <INDENT> self.assertEquals(self.new_source.id,"CBSN") <NEW_LINE> self.assertEquals(self.new_source.name,"CBSN NEWS") <NEW_LINE> self.assertEquals(self.new_source.description,"CBSN is the leading free news platform") <NEW_LINE> self.assertEquals(self.new_source.url,"cbsn.com") <NEW_LINE> self.assertEquals(self.new_source.category,"business") <NEW_LINE> self.assertEquals(self.new_source.country,"en") <NEW_LINE> self.assertEquals(self.new_source.language,"us")
Test Class to test the behaviour of the News class
6259906a3317a56b869bf13e
class WingSect(XMLContainer): <NEW_LINE> <INDENT> XMLTAG = 'Section' <NEW_LINE> driver = Enum(_MS_AR_TR_S, iotype='in', xmltag='Driver', values=(_MS_AR_TR_A, _MS_AR_TR_S, _MS_AR_TR_TC, _MS_AR_TR_RC, _MS_S_TC_RC, _MS_A_TC_RC, _MS_TR_S_A, _MS_AR_A_RC), aliases=('AR-TR-Area', 'AR-TR-Span', 'AR-TR-TC', 'AR-TR-RC', 'Span-TC-RC', 'Area-Tc-RC', 'TR-Span-Area', 'AR-Area-RC'), desc='Scheme used for section design.') <NEW_LINE> ar = Float(iotype='in', xmltag='AR', desc='Aspect ratio.') <NEW_LINE> tr = Float(iotype='in', xmltag='TR', desc='Taper ratio.') <NEW_LINE> area = Float(iotype='in', xmltag='Area', desc='') <NEW_LINE> span = Float(iotype='in', xmltag='Span', desc='') <NEW_LINE> tc = Float(iotype='in', xmltag='TC', desc='Tip chord.') <NEW_LINE> rc = Float(iotype='in', xmltag='RC', desc='Root chord.') <NEW_LINE> sweep = Float(10.0, low=-85., high=85., units='deg', iotype='in', xmltag='Sweep', desc='') <NEW_LINE> sweep_loc = Float(0.0, low=0., high=1., iotype='in', xmltag='SweepLoc', desc='') <NEW_LINE> twist = Float(0.0, low=-45., high=45., units='deg', iotype='in', xmltag='Twist', desc='') <NEW_LINE> twist_loc = Float(0.0, low=0., high=1., iotype='in', xmltag='TwistLoc', desc='') <NEW_LINE> dihedral = Float(0.0, low=-360., high=360., units='deg', iotype='in', xmltag='Dihedral', desc='') <NEW_LINE> dihed_crv1 = Float(0.0, low=0., high=1., iotype='in', xmltag='Dihed_Crv1', desc='') <NEW_LINE> dihed_crv2 = Float(0.0, low=0., high=1., iotype='in', xmltag='Dihed_Crv2', desc='') <NEW_LINE> dihed_crv1_str = Float(0.75, low=0., high=2., iotype='in', xmltag='Dihed_Crv1_Str', desc='') <NEW_LINE> dihed_crv2_str = Float(0.75, low=0., high=2., iotype='in', xmltag='Dihed_Crv2_Str', desc='') <NEW_LINE> dihedRotFlag = Bool(False, iotype='in', xmltag='DihedRotFlag', desc='') <NEW_LINE> smoothBlendFlag = Bool(False, iotype='in', xmltag='SmoothBlendFlag', desc='') <NEW_LINE> num_interp_xsecs = Int(1, iotype='in', xmltag='NumInterpXsecs', desc='') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(WingSect, self).__init__(self.XMLTAG)
XML parameters for one section of a multi-section wing.
6259906a91f36d47f2231a8a
class LazyConnection: <NEW_LINE> <INDENT> def __init__(self, address, family=AF_INET, type=SOCK_STREAM): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.family = family <NEW_LINE> self.type = type <NEW_LINE> self.local = threading.local() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if hasattr(self.local, 'sock'): <NEW_LINE> <INDENT> raise RuntimeError('Already connected') <NEW_LINE> <DEDENT> self.local.sock = socket(self.family, self.type) <NEW_LINE> self.local.sock.connect(self.address) <NEW_LINE> return self.local.sock <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.local.sock.close() <NEW_LINE> del self.local.sock
该类实现了一个上下文管理器,用来创建线程独立的socket连接。
6259906a92d797404e389756
class Cert_Ldaps(Collection): <NEW_LINE> <INDENT> def __init__(self, auth): <NEW_LINE> <INDENT> super(Cert_Ldaps, self).__init__(auth) <NEW_LINE> self._meta_data['allowed_lazy_attributes'] = [Cert_Ldap] <NEW_LINE> self._meta_data['attribute_registry'] = {'tm:auth:cert-ldap:cert-ldapstate': Cert_Ldap}
BIG-IP® ldap server collection
6259906a4428ac0f6e659d29
class ClockDataParser(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def new_split(cls, start, name=None): <NEW_LINE> <INDENT> return backend.new_dict(dict(name=name, start=start, end=None, data=None, duration=None)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def close_split(cls, split, split_end, name=None): <NEW_LINE> <INDENT> duration = split_end - split['start'] <NEW_LINE> split['end'] = split_end <NEW_LINE> split['duration'] = duration <NEW_LINE> split['name'] = name if name is not None else split['name'] <NEW_LINE> split['current'] = False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_split_at_time(cls, clock_data, sought_time, clock_time): <NEW_LINE> <INDENT> actual_time = sought_time + clock_data['start'] <NEW_LINE> for split in clock_data['splits']: <NEW_LINE> <INDENT> LOGGER.debug('Looking for %r in %s', actual_time, DelayFormat(lambda: str(backend.deep_copy(split)))) <NEW_LINE> if actual_time < split['start']: <NEW_LINE> <INDENT> raise ValueError(actual_time) <NEW_LINE> <DEDENT> elif split['end'] is not None: <NEW_LINE> <INDENT> if actual_time < split['end']: <NEW_LINE> <INDENT> return split <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if actual_time < clock_time: <NEW_LINE> <INDENT> return split <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None
Parse things to do with clock data
6259906aa17c0f6771d5d7a3
class SocialLoginCorrectPermissionsMixin(object): <NEW_LINE> <INDENT> def test_get_authstatus(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('sociallogin:status')) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> response_content = response.content <NEW_LINE> if six.PY3: <NEW_LINE> <INDENT> response_content = str(response_content, encoding='utf8') <NEW_LINE> <DEDENT> json_content = json.loads(response_content) <NEW_LINE> self.assertIn('authenticated', json_content) <NEW_LINE> self.assertEqual(json_content['authenticated'], True) <NEW_LINE> self.assertIn('token', json_content) <NEW_LINE> self.assertIn('preferencesInitialized', json_content)
Mixins for user testing the views is logged if the user has the required permissions.
6259906a67a9b606de54769d
@adapter(IFolderish) <NEW_LINE> @implementer(ISliderConfig) <NEW_LINE> class SliderConfigAdapter(object): <NEW_LINE> <INDENT> height = PrefixedFieldProperty(ISliderConfig['height'], STORAGE_PREFIX) <NEW_LINE> interval = PrefixedFieldProperty(ISliderConfig['interval'], STORAGE_PREFIX) <NEW_LINE> wrap = PrefixedFieldProperty(ISliderConfig['wrap'], STORAGE_PREFIX) <NEW_LINE> pause = PrefixedFieldProperty(ISliderConfig['pause'], STORAGE_PREFIX) <NEW_LINE> scale = PrefixedFieldProperty(ISliderConfig['scale'], STORAGE_PREFIX) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context
Adapter for storing config values
6259906a7047854f46340bac
class JsMathPattern(markdown.inlinepatterns.Pattern): <NEW_LINE> <INDENT> def __init__(self, tag, pattern): <NEW_LINE> <INDENT> super(JsMathPattern, self).__init__(pattern) <NEW_LINE> self.math_tag_class = 'math' <NEW_LINE> self.tag = tag <NEW_LINE> <DEDENT> def handleMatch(self, m): <NEW_LINE> <INDENT> node = markdown.util.etree.Element(self.tag) <NEW_LINE> node.set('class', self.math_tag_class) <NEW_LINE> prefix = '\\(' if m.group('prefix') == '$' else m.group('prefix') <NEW_LINE> suffix = '\\)' if m.group('suffix') == '$' else m.group('suffix') <NEW_LINE> node.text = markdown.util.AtomicString(prefix + m.group('math') + suffix) <NEW_LINE> return node
Inline markdown processing of math.
6259906a7b25080760ed88dd
class ProjectsLocationsService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'projects_locations' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(ContainerV1beta1.ProjectsLocationsService, self).__init__(client) <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def GetServerConfig(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('GetServerConfig') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> GetServerConfig.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/locations/{locationsId}/serverConfig', http_method=u'GET', method_id=u'container.projects.locations.getServerConfig', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'projectId', u'version', u'zone'], relative_path=u'v1beta1/{+name}/serverConfig', request_field='', request_type_name=u'ContainerProjectsLocationsGetServerConfigRequest', response_type_name=u'ServerConfig', supports_download=False, )
Service class for the projects_locations resource.
6259906a3539df3088ecda96
class MockUSBServoBoardDevice(usb.core.Device): <NEW_LINE> <INDENT> def __init__(self, serial_number: str, fw_version: int = 2): <NEW_LINE> <INDENT> self.serial = serial_number <NEW_LINE> self.firmware_version = fw_version <NEW_LINE> self._ctx = MockUSBContext() <NEW_LINE> self.timers_initialised = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def serial_number(self) -> str: <NEW_LINE> <INDENT> return self.serial <NEW_LINE> <DEDENT> def ctrl_transfer( self, bmRequestType: int, bRequest: int, wValue: int = 0, wIndex: int = 0, data_or_wLength: Optional[Union[int, bytes]] = None, timeout: Optional[int] = None, ) -> bytes: <NEW_LINE> <INDENT> assert bRequest == 64 <NEW_LINE> if bmRequestType == 0x80: <NEW_LINE> <INDENT> assert isinstance(data_or_wLength, int) <NEW_LINE> return self.read_data(wValue, wIndex, data_or_wLength, timeout) <NEW_LINE> <DEDENT> if bmRequestType == 0x00: <NEW_LINE> <INDENT> assert isinstance(data_or_wLength, bytes) <NEW_LINE> self.write_data(wValue, wIndex, data_or_wLength, timeout) <NEW_LINE> return b"" <NEW_LINE> <DEDENT> raise ValueError("Invalid Request Type for mock device.") <NEW_LINE> <DEDENT> def read_data( self, wValue: int = 0, wIndex: int = 0, wLength: int = 0, timeout: Optional[int] = None, ) -> bytes: <NEW_LINE> <INDENT> assert wValue == 0 <NEW_LINE> if wIndex == 9: <NEW_LINE> <INDENT> return self.read_fw(wLength) <NEW_LINE> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def read_fw(self, wLength: int) -> bytes: <NEW_LINE> <INDENT> assert wLength == 4 <NEW_LINE> return struct.pack("<I", self.firmware_version) <NEW_LINE> <DEDENT> def write_data( self, wValue: int = 0, wIndex: int = 0, data: bytes = b"", timeout: Optional[int] = None, ) -> None: <NEW_LINE> <INDENT> if 0 <= wIndex < 12: <NEW_LINE> <INDENT> return self.write_servo(wValue, data) <NEW_LINE> <DEDENT> if wIndex == 12: <NEW_LINE> <INDENT> assert data == b'' <NEW_LINE> assert wValue == 0 <NEW_LINE> assert not self.timers_initialised <NEW_LINE> self.timers_initialised = True <NEW_LINE> return <NEW_LINE> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def write_servo(self, wValue: int, data: bytes) -> None: <NEW_LINE> <INDENT> assert -100 <= wValue <= 100 <NEW_LINE> assert data == b'' <NEW_LINE> assert self.timers_initialised
This class mocks the behaviour of a USB device for a Servo Board.
6259906abaa26c4b54d50a9f
class World: <NEW_LINE> <INDENT> def __init__(self, game: str): <NEW_LINE> <INDENT> self.tiles, self.current_tile = self.load(game) <NEW_LINE> [tile.discover_tiles(self) for tile in self.tiles] <NEW_LINE> logging.debug(f"Loaded Tiles: {self.tiles}") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def load(game_places: pathlib.Path): <NEW_LINE> <INDENT> tiles = [] <NEW_LINE> start_at = "" <NEW_LINE> if not game_places.exists(): <NEW_LINE> <INDENT> logging.error( f"Game '{game_places.parent.name}' doesn't define a '{game_places.name}'!" ) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> with game_places.open() as csv_file: <NEW_LINE> <INDENT> data = csv.reader(csv_file) <NEW_LINE> for datarow in data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tiles.append(Tile(*datarow)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print( f"Beep! The description of {datarow[0]} does not provide sufficient information." ) <NEW_LINE> print( "A minimal place description has the following 5 entries: name, north_exit, east_exit, south_exit, west_exit" ) <NEW_LINE> print( "Additional entries are considered point of interests or items available for closer examination." ) <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> print( f"Beep! Place '{datarow[0]}' does not seem to be a valid place. It is not connected to any other tile at the moment." ) <NEW_LINE> <DEDENT> if datarow[0].endswith("*"): <NEW_LINE> <INDENT> if start_at == "": <NEW_LINE> <INDENT> start_at = tiles[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError( "Data contains more than one start tile. Start tiles are indicated by a '*' at the end of a place name." ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return tiles, start_at <NEW_LINE> <DEDENT> def move(self, direction: str): <NEW_LINE> <INDENT> if len(direction) == 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> direction = DIRECTIONS[direction] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Beep! {} is not a valid geographic direction!") <NEW_LINE> <DEDENT> <DEDENT> new_tile = self.current_tile.surrounding[direction] <NEW_LINE> if new_tile: <NEW_LINE> <INDENT> self.current_tile = new_tile <NEW_LINE> self.current_tile.visited = True <NEW_LINE> print("You moved to '{}'.".format(self.current_tile.name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Beep! This move is not available!") <NEW_LINE> <DEDENT> <DEDENT> def get_tile(self, name): <NEW_LINE> <INDENT> for tile in self.tiles: <NEW_LINE> <INDENT> if tile.name == name: <NEW_LINE> <INDENT> return tile <NEW_LINE> <DEDENT> <DEDENT> return None
Word-class, that holds information about available tiles and items.
6259906ae5267d203ee6cfb9
class generator(nn.Module): <NEW_LINE> <INDENT> def __init__(self, nz, nc, ngf): <NEW_LINE> <INDENT> super(generator, self).__init__() <NEW_LINE> self.net = nn.Sequential( nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.ReLU(True), nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), nn.Tanh() ) <NEW_LINE> self.to(DEVICE) <NEW_LINE> print_network(self) <NEW_LINE> <DEDENT> def forward(self, z): <NEW_LINE> <INDENT> return nn.parallel.data_parallel(self.net, z)
dc_gan for lsun datasets
6259906a23849d37ff8528ac
class TestTimeSpan(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.start = datetime(2011, 12, 13, 14, 15, 16) <NEW_LINE> cls.end = datetime(2011, 12, 14, 14, 15, 16) <NEW_LINE> <DEDENT> def test_constructor(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan(start=self.start, end=self.end) <NEW_LINE> self.assertEqual(span.start, self.start) <NEW_LINE> self.assertEqual(span.end, self.end) <NEW_LINE> <DEDENT> def test_set_start(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan() <NEW_LINE> span.start = self.start <NEW_LINE> self.assertEqual(span.start, self.start) <NEW_LINE> <DEDENT> def test_set_end(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan(self.start) <NEW_LINE> span.end = self.end <NEW_LINE> self.assertEqual(span.end, self.end) <NEW_LINE> <DEDENT> def test_start_greater_end(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan() <NEW_LINE> span.start = self.start <NEW_LINE> span.end = self.end <NEW_LINE> self.assertEqual(span.end, self.end) <NEW_LINE> self.assertEqual(span.start, self.start) <NEW_LINE> self.assertGreater(span.end, span.start) <NEW_LINE> <DEDENT> def test_start_end_equal(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan() <NEW_LINE> span.start = self.start <NEW_LINE> span.end = self.start <NEW_LINE> self.assertEqual(span.end, self.start) <NEW_LINE> self.assertEqual(span.start, self.start) <NEW_LINE> self.assertEqual(span.end, span.start) <NEW_LINE> <DEDENT> def test_fail_on_end_lesser_start(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan(self.start, self.end) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> span.start = self.end + timedelta(3) <NEW_LINE> <DEDENT> <DEDENT> def test_fail_on_start_null(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan() <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> span.end = self.end <NEW_LINE> <DEDENT> <DEDENT> def test_fail_on_start_greater_end(self): <NEW_LINE> <INDENT> span = doto.model.TimeSpan() <NEW_LINE> span.start = self.end <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> span.end = self.start <NEW_LINE> <DEDENT> <DEDENT> def test_fail_2_start_greater_end(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> doto.model.TimeSpan(self.end, self.start) <NEW_LINE> <DEDENT> <DEDENT> def test_span(self): <NEW_LINE> <INDENT> time_span = doto.model.TimeSpan(start=self.start, end=self.end) <NEW_LINE> self.assertEqual(time_span.time_delta(), timedelta(1)) <NEW_LINE> <DEDENT> def test_repr(self): <NEW_LINE> <INDENT> doto.model.TimeSpan(start=self.start, end=self.end)
Unittest for the TimeSpan class.
6259906ad268445f2663a758
class RedirectAddress(object): <NEW_LINE> <INDENT> def __init__(self, request, address, relative=True, carry_get=False, ignore_get=None): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.address = address <NEW_LINE> self.relative = relative <NEW_LINE> self.carry_get = carry_get <NEW_LINE> self.ignore_get = ignore_get <NEW_LINE> <DEDENT> @property <NEW_LINE> def modified(self): <NEW_LINE> <INDENT> return self.modify(unicode(self.address)) <NEW_LINE> <DEDENT> def modify(self, address): <NEW_LINE> <INDENT> address = self.joined_address(address) <NEW_LINE> address = self.strip_multi_slashes(address) <NEW_LINE> address = self.add_get_params(address) <NEW_LINE> return address <NEW_LINE> <DEDENT> @property <NEW_LINE> def base_url(self): <NEW_LINE> <INDENT> if hasattr(self.request, 'state'): <NEW_LINE> <INDENT> return self.request.state.base_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.request.META.get('SCRIPT_NAME', '') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def params(self): <NEW_LINE> <INDENT> if not self.ignore_get: <NEW_LINE> <INDENT> return self.request.GET <NEW_LINE> <DEDENT> params = {} <NEW_LINE> for key, val in self.request.GET.items(): <NEW_LINE> <INDENT> if key not in self.ignore_get: <NEW_LINE> <INDENT> params[key] = val <NEW_LINE> <DEDENT> <DEDENT> return params <NEW_LINE> <DEDENT> def strip_multi_slashes(self, string): <NEW_LINE> <INDENT> return regexes['multi_slash'].sub('/', string) <NEW_LINE> <DEDENT> def root_url(self, address): <NEW_LINE> <INDENT> return address[0] == '/' <NEW_LINE> <DEDENT> def add_get_params(self, address): <NEW_LINE> <INDENT> if not self.carry_get: <NEW_LINE> <INDENT> return address <NEW_LINE> <DEDENT> params = urlencode(self.params) <NEW_LINE> return "%s?%s" % (address, params) <NEW_LINE> <DEDENT> def joined_address(self, address): <NEW_LINE> <INDENT> if self.root_url(address): <NEW_LINE> <INDENT> address = self.url_join(self.base_url, address) <NEW_LINE> <DEDENT> elif self.relative: <NEW_LINE> <INDENT> address = self.url_join(self.request.path, address) <NEW_LINE> <DEDENT> return address <NEW_LINE> <DEDENT> def url_join(self, a, b): <NEW_LINE> <INDENT> if not a or not b: <NEW_LINE> <INDENT> return '%s%s' % (a, b) <NEW_LINE> <DEDENT> elif b[0] == '/' or a[-1] == '/': <NEW_LINE> <INDENT> return '%s%s' % (a, b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s/%s' % (a, b)
Helper to determine where to redirect to. :param request: Object representing current Django request. :param address: String representing the address to modify into a redirect url :param relative: If we should be redirecting relative to the current page we're on :param carry_get: If we should use the GET parameters from the current request in our redirect :param ignore_get: List of GET parameters that should be ignored if carry_get is True
6259906a7cff6e4e811b7241
class Category(models.Model): <NEW_LINE> <INDENT> lang = models.CharField(max_length=2, choices=LANGUAGES) <NEW_LINE> title = models.CharField(max_length=100) <NEW_LINE> desc = models.TextField() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return _(self.title) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _("Categories")
A Category related to a single language
6259906a66673b3332c31bf5
class AgentSettings(Settings): <NEW_LINE> <INDENT> def __init__(self, lambda_termination=0.05, lambda_proposal=0.05, lambda_utterance=0.001, hidden_state_size=100, vocab_size=11, utterance_len=6, dim_size=100, discount_factor=0.99, learning_rate=0.001, proposal_channel=True, linguistic_channel=False, ): <NEW_LINE> <INDENT> self.lambda_termination = lambda_termination <NEW_LINE> self.lambda_proposal = lambda_proposal <NEW_LINE> self.lambda_utterance = lambda_utterance <NEW_LINE> self.hidden_state_size = hidden_state_size <NEW_LINE> self.vocab_size = vocab_size <NEW_LINE> self.utterance_len = utterance_len <NEW_LINE> self.dim_size = dim_size <NEW_LINE> self.discount_factor = discount_factor <NEW_LINE> self.learning_rate = learning_rate <NEW_LINE> self.proposal_channel = [True, False][proposal_channel in ['False', False]] <NEW_LINE> self.linguistic_channel = [True, False][linguistic_channel in ['False', False]] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Agent ' + super().__str__()
Agent specific settings.
6259906a009cb60464d02d31
class CertificateFingerprintView(generics.ListAPIView): <NEW_LINE> <INDENT> permission_classes = (rest_permissions.AllowAny,) <NEW_LINE> serializer_class = local_serializers.CertificateFingerprintSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> name = self.kwargs['host'] <NEW_LINE> res = local_models.CertificateFingerprintModel.objects.filter(name=name) <NEW_LINE> if not len(res): <NEW_LINE> <INDENT> raise exceptions.NotFound(detail='[{}] is not found'.format(name)) <NEW_LINE> <DEDENT> return res
Provides the server certificate fingerprint
6259906a44b2445a339b755b
class StrandTest(ColorCycle): <NEW_LINE> <INDENT> def init_parameters(self): <NEW_LINE> <INDENT> super().init_parameters() <NEW_LINE> self.set_parameter('num_steps_per_cycle', self.strip.num_leds) <NEW_LINE> <DEDENT> def before_start(self): <NEW_LINE> <INDENT> self.color = 0x000000 <NEW_LINE> <DEDENT> def update(self, current_step: int, current_cycle: int): <NEW_LINE> <INDENT> if current_step == 0: <NEW_LINE> <INDENT> self.color >>= 8 <NEW_LINE> <DEDENT> if self.color == 0: <NEW_LINE> <INDENT> self.color = 0xFF0000 <NEW_LINE> <DEDENT> head = (current_step + 9) % self.p['num_steps_per_cycle'] <NEW_LINE> tail = current_step <NEW_LINE> self.strip.set_pixel_bytes(head, self.color) <NEW_LINE> self.strip.set_pixel_bytes(tail, 0) <NEW_LINE> return True
Displays a classical LED test No parameters necessary
6259906a99cbb53fe68326de
class PasswordEntry(): <NEW_LINE> <INDENT> def __init__(self, master, center=True): <NEW_LINE> <INDENT> self.master = master <NEW_LINE> self.top = tkinter.Toplevel(master=master) <NEW_LINE> self.top.transient(master) <NEW_LINE> self.top.grab_set() <NEW_LINE> self.top.title = 'Password required' <NEW_LINE> tkinter.Label(self.top, text='Email Password is required').pack() <NEW_LINE> self.e = tkinter.Entry(self.top, show='*') <NEW_LINE> self.e.pack(fill=tkinter.X) <NEW_LINE> self.e.bind('<Return>', self.ok) <NEW_LINE> self.e.bind('<Escape>', self.cancel) <NEW_LINE> f = tkinter.Frame(self.top) <NEW_LINE> f.pack(fill=tkinter.X) <NEW_LINE> tkinter.Button(f, text='OK', command=self.ok).pack(side='left', expand=1, fill=tkinter.X) <NEW_LINE> tkinter.Button(f, text='Cancel', command=self.cancel).pack(side='left', expand=1, fill=tkinter.X) <NEW_LINE> self.result = None <NEW_LINE> if center:self.center() <NEW_LINE> <DEDENT> def ok(self, *args): <NEW_LINE> <INDENT> self.result = self.e.get() <NEW_LINE> self.top.destroy() <NEW_LINE> return 'break' <NEW_LINE> <DEDENT> def cancel(self, *args): <NEW_LINE> <INDENT> self.top.destroy() <NEW_LINE> return 'break' <NEW_LINE> <DEDENT> def center(self): <NEW_LINE> <INDENT> self.master.update_idletasks() <NEW_LINE> master_center_x = self.master.winfo_x() + (self.master.winfo_width()/2) <NEW_LINE> master_center_y = self.master.winfo_y() + (self.master.winfo_height()/2) <NEW_LINE> w = self.top.winfo_width() <NEW_LINE> h = self.top.winfo_height() <NEW_LINE> x = int(max(0, master_center_x - w/2)) <NEW_LINE> y = int(max(0, master_center_y - h/2)) <NEW_LINE> self.top.geometry('{}x{}+{}+{}'.format(w, h, x, y))
Creates a tkinter entry box that shows stars instead of password in clear
6259906a38b623060ffaa44e
class PoolScanPnpC(AbstractCallbackScanner): <NEW_LINE> <INDENT> checks = [ ('PoolTagCheck', dict(tag = "PnpC")), ('CheckPoolSize', dict(condition = lambda x: x >= 0x38)), ('CheckPoolType', dict(non_paged = True, paged = True, free = True)), ('CheckPoolIndex', dict(value = 1)), ]
PoolScanner for PnpC (EventCategoryTargetDeviceChange)
6259906a796e427e5384ff6f
class Publisher(object): <NEW_LINE> <INDENT> def __init__(self, registry): <NEW_LINE> <INDENT> self.registry = registry <NEW_LINE> self.directory_publishers = {} <NEW_LINE> <DEDENT> @webob.dec.wsgify <NEW_LINE> def __call__(self, request): <NEW_LINE> <INDENT> first = request.path_info_peek() <NEW_LINE> if first is None: <NEW_LINE> <INDENT> raise webob.exc.HTTPNotFound() <NEW_LINE> <DEDENT> library_name = request.path_info_pop() <NEW_LINE> if library_name == '': <NEW_LINE> <INDENT> raise webob.exc.HTTPNotFound() <NEW_LINE> <DEDENT> potential_version = request.path_info_peek() <NEW_LINE> if potential_version is not None and potential_version.startswith(fanstatic.VERSION_PREFIX): <NEW_LINE> <INDENT> request.path_info_pop() <NEW_LINE> need_caching = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> need_caching = False <NEW_LINE> <DEDENT> if request.path_info == '': <NEW_LINE> <INDENT> raise webob.exc.HTTPNotFound() <NEW_LINE> <DEDENT> directory_publisher = self.directory_publishers.get(library_name) <NEW_LINE> if directory_publisher is None: <NEW_LINE> <INDENT> library = self.registry.get(library_name) <NEW_LINE> if library is None: <NEW_LINE> <INDENT> raise webob.exc.HTTPNotFound() <NEW_LINE> <DEDENT> self.registry.prepare() <NEW_LINE> directory_publisher = self.directory_publishers[library_name] = LibraryPublisher(library) <NEW_LINE> <DEDENT> response = request.get_response(directory_publisher) <NEW_LINE> if need_caching and response.status.startswith('20'): <NEW_LINE> <INDENT> response.cache_control.max_age = FOREVER <NEW_LINE> response.expires = time.time() + FOREVER <NEW_LINE> <DEDENT> return response
Fanstatic publisher WSGI application. This WSGI application serves Fanstatic :py:class:`Library` instances. Libraries are published as ``<library_name>/<optional_version>/path/to/resource.js``. All static resources contained in the libraries will be published to the web. If a step prefixed with ``:version:`` appears in the URL, this will be automatically skipped, and the HTTP response will indicate the resource can be cached forever. This WSGI component is used automatically by the :py:func:`Fanstatic` WSGI framework component, but can also be used independently if you need more control. :param registry: an instance of :py:class:`LibraryRegistry` with those resource libraries that should be published.
6259906a16aa5153ce401cd2
class GameModel(models.Model): <NEW_LINE> <INDENT> title = models.CharField(default='', max_length=255) <NEW_LINE> ini_file = models.FileField(upload_to='ini_files') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title
Model of Game Ini Files.
6259906a7d847024c075dbd3
class BasecampFileConfig(BasecampConfig): <NEW_LINE> <INDENT> DEFAULT_CONFIG_FILE_LOCATIONS = [ "basecamp.conf", constants.DEFAULT_CONFIG_FILE, "/etc/basecamp.conf", ] <NEW_LINE> def __init__(self, client_id=None, client_secret=None, redirect_uri=None, access_token=None, refresh_token=None, account_id=None, filepath=None): <NEW_LINE> <INDENT> super(BasecampFileConfig, self).__init__(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, access_token=access_token, refresh_token=refresh_token, account_id=account_id) <NEW_LINE> self.filepath = filepath <NEW_LINE> <DEDENT> def read(self, filepath=None): <NEW_LINE> <INDENT> if filepath is None: <NEW_LINE> <INDENT> filepath = self.filepath <NEW_LINE> <DEDENT> config = ConfigParser() <NEW_LINE> config.read(filepath) <NEW_LINE> attrs = [k for k in self.FIELDS_TO_PERSIST] <NEW_LINE> for key in attrs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = config.get('BASECAMP', key) <NEW_LINE> setattr(self, key, value) <NEW_LINE> <DEDENT> except NoOptionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.filepath = filepath <NEW_LINE> <DEDENT> def save(self, filepath=None): <NEW_LINE> <INDENT> if filepath is None: <NEW_LINE> <INDENT> filepath = self.filepath <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> os.makedirs(os.path.dirname(filepath), mode=0o770) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> config = ConfigParser() <NEW_LINE> config.add_section('BASECAMP') <NEW_LINE> attrs = [k for k in self.FIELDS_TO_PERSIST] <NEW_LINE> for key in attrs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = getattr(self, key) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> config.set('BASECAMP', key, six.text_type(value)) <NEW_LINE> setattr(self, key, value) <NEW_LINE> <DEDENT> except (NoSectionError, NoOptionError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> with open(filepath, "w") as fileout: <NEW_LINE> <INDENT> config.write(fileout) <NEW_LINE> <DEDENT> self.filepath = filepath <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_filepath(cls, filepath): <NEW_LINE> <INDENT> if not os.path.exists(filepath): <NEW_LINE> <INDENT> raise IOError("Non-existent configuration file '%s'" % filepath) <NEW_LINE> <DEDENT> new_config = cls() <NEW_LINE> new_config.read(filepath) <NEW_LINE> return new_config <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load_from_default_paths(cls): <NEW_LINE> <INDENT> env_defined = os.getenv("BC3_CONFIG_PATH") <NEW_LINE> if env_defined: <NEW_LINE> <INDENT> cls.DEFAULT_CONFIG_FILE_LOCATIONS.insert(0, env_defined) <NEW_LINE> <DEDENT> for config_file in cls.DEFAULT_CONFIG_FILE_LOCATIONS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.from_filepath(config_file) <NEW_LINE> <DEDENT> except (IOError, OSError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> logger.error("%s: %s is invalid.", type(ex).__name__, config_file) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise exc.NoDefaultConfigurationFound()
Stores credentials to a .conf file in INI format.
6259906a5fc7496912d48e64
class HttpCache(object): <NEW_LINE> <INDENT> def __init__(self, ttl): <NEW_LINE> <INDENT> self.base_path = os.path.join(sublime.packages_path(), 'User', 'CoreBuilder.cache') <NEW_LINE> if not os.path.exists(self.base_path): <NEW_LINE> <INDENT> os.mkdir(self.base_path) <NEW_LINE> <DEDENT> self.clear(int(ttl)) <NEW_LINE> <DEDENT> def clear(self, ttl): <NEW_LINE> <INDENT> ttl = int(ttl) <NEW_LINE> for filename in os.listdir(self.base_path): <NEW_LINE> <INDENT> path = os.path.join(self.base_path, filename) <NEW_LINE> if os.path.isdir(path): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> mtime = os.stat(path).st_mtime <NEW_LINE> if mtime < time.time() - ttl: <NEW_LINE> <INDENT> os.unlink(path) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> cache_file = os.path.join(self.base_path, key) <NEW_LINE> if not os.path.exists(cache_file): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> with open_compat(cache_file, 'rb') as f: <NEW_LINE> <INDENT> return read_compat(f) <NEW_LINE> <DEDENT> <DEDENT> def has(self, key): <NEW_LINE> <INDENT> cache_file = os.path.join(self.base_path, key) <NEW_LINE> return os.path.exists(cache_file) <NEW_LINE> <DEDENT> def set(self, key, content): <NEW_LINE> <INDENT> cache_file = os.path.join(self.base_path, key) <NEW_LINE> with open_compat(cache_file, 'wb') as f: <NEW_LINE> <INDENT> f.write(content)
A data store for caching HTTP response data.
6259906add821e528d6da57d
class NonUniqueNameException(Error): <NEW_LINE> <INDENT> pass
Exception when the name is already registered.
6259906ae5267d203ee6cfba
class ResourceNotFound(ResourceError): <NEW_LINE> <INDENT> default_message = "resource '{path}' not found"
Required resource not found.
6259906a5fcc89381b266d53
class NoteFileParserTest(unittest.TestCase): <NEW_LINE> <INDENT> def parse_notes_test(self): <NEW_LINE> <INDENT> notes, durations, volumes = note_file_parser('tests/notefile.txt') <NEW_LINE> self.assertEqual(notes, ['C4', 'D4', 'E4', 'F4', 'G4']) <NEW_LINE> self.assertEqual(durations, [1.0, 1.0, 1.0, 1.0, 1.0]) <NEW_LINE> self.assertEqual(volumes, [0.5, 0.5, 0.5, 0.5, 0.5]) <NEW_LINE> <DEDENT> def raise_error_test(self): <NEW_LINE> <INDENT> self.assertRaises(NoteFileParsingException, note_file_parser, 'tests/notefile_error.txt')
Tests for note parsing from file
6259906a5fdd1c0f98e5f77e
class _GetLoadsTemplateProcessor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.jinja_env = jinja2.Environment( extensions=[jinja_extensions.LoadExtension], ) <NEW_LINE> self.jinja_env.makejank_load_callback = self.load_callback <NEW_LINE> self.loads = [] <NEW_LINE> <DEDENT> def load_callback(self, *args, **kwargs): <NEW_LINE> <INDENT> self.loads.append((args, kwargs)) <NEW_LINE> <DEDENT> def process(self, template_string): <NEW_LINE> <INDENT> self.jinja_env.parse(template_string) <NEW_LINE> return self.loads
Janky version of template_processor.TemplateProcessor
6259906a1b99ca4002290132
class CacheBase(object): <NEW_LINE> <INDENT> def __init__(self,default_timeout = 0): <NEW_LINE> <INDENT> self.default_timeout = default_timeout <NEW_LINE> <DEDENT> def add(self, key, value, timeout=None): <NEW_LINE> <INDENT> self.set(key,value,timeout) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set(self, key, value, timeout=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def delete(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_many(self, keys): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for k in keys: <NEW_LINE> <INDENT> val = self.get(k) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> d[k] = val <NEW_LINE> <DEDENT> <DEDENT> return d <NEW_LINE> <DEDENT> def has_key(self, key): <NEW_LINE> <INDENT> return self.get(key) is not None <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return self.has_key(key)
ducktype a django cache Credits: Django: http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/base.py
6259906aa8370b77170f1bbf
class TransactionAccountDelegate(QStyledItemDelegate): <NEW_LINE> <INDENT> def createEditor(self, parent, option, index): <NEW_LINE> <INDENT> self.accounts = Accounts.all() <NEW_LINE> self.accountNames = [account.name for account in self.accounts] <NEW_LINE> comboBox = QComboBox(parent) <NEW_LINE> comboBox.insertItems(0, self.accountNames) <NEW_LINE> return comboBox <NEW_LINE> <DEDENT> def setEditorData (self, editor, index): <NEW_LINE> <INDENT> data = index.data() <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> editor.setCurrentIndex(self.accountNames.index(data)) <NEW_LINE> <DEDENT> <DEDENT> def setModelData(self, editor, model, index): <NEW_LINE> <INDENT> model.setData(index, editor.currentText())
Transaction Account View Delegate
6259906acb5e8a47e493cd80
class Menu(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=32) <NEW_LINE> url_name = models.CharField(max_length=64) <NEW_LINE> menu_choice=((0,'related'), (1,'direct') ) <NEW_LINE> type=models.SmallIntegerField(choices=menu_choice) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
菜单
6259906a56ac1b37e63038df
class UserDetailAPIView(APIView): <NEW_LINE> <INDENT> permission_classes = [IsAuthenticated] <NEW_LINE> authentication_classes = [JWTAuthentication] <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return Response("ok")
只能登录以后在访问
6259906a21bff66bcd724460
class MonitorMgr(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._monitor_list = [] <NEW_LINE> <DEDENT> def init_monitors(self, monitor_cfgs, context): <NEW_LINE> <INDENT> LOG.debug("monitorMgr config: %s" % monitor_cfgs) <NEW_LINE> for monitor_cfg in monitor_cfgs: <NEW_LINE> <INDENT> monitor_type = monitor_cfg["monitor_type"] <NEW_LINE> monitor_cls = BaseMonitor.get_monitor_cls(monitor_type) <NEW_LINE> monitor_ins = monitor_cls(monitor_cfg, context) <NEW_LINE> if "key" in monitor_cfg: <NEW_LINE> <INDENT> monitor_ins.key = monitor_cfg["key"] <NEW_LINE> <DEDENT> self._monitor_list.append(monitor_ins) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> for obj in self._monitor_list: <NEW_LINE> <INDENT> if obj.key == item: <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("No such monitor instance of key - %s" % item) <NEW_LINE> <DEDENT> def start_monitors(self): <NEW_LINE> <INDENT> for _monotor_instace in self._monitor_list: <NEW_LINE> <INDENT> _monotor_instace.start_monitor() <NEW_LINE> <DEDENT> <DEDENT> def wait_monitors(self): <NEW_LINE> <INDENT> for monitor in self._monitor_list: <NEW_LINE> <INDENT> monitor.wait_monitor() <NEW_LINE> <DEDENT> <DEDENT> def verify_SLA(self): <NEW_LINE> <INDENT> sla_pass = True <NEW_LINE> for monitor in self._monitor_list: <NEW_LINE> <INDENT> sla_pass = sla_pass & monitor.verify_SLA() <NEW_LINE> <DEDENT> return sla_pass
docstring for MonitorMgr
6259906a4f88993c371f111c
class ExchangeRateFetcher: <NEW_LINE> <INDENT> def __init__(self, api_currency_code: str): <NEW_LINE> <INDENT> self.api_currency_code = api_currency_code <NEW_LINE> <DEDENT> def fetch_rate_for_date(self, date) -> float: <NEW_LINE> <INDENT> params = {endpoints.API_REQUEST_SINGLE_DATE: ApiDatesConverter(date).to_string(), endpoints.API_REQUEST_CURRENCY_CODE: self.api_currency_code} <NEW_LINE> xml_body = self.execute_request_and_return_xml(endpoints.API_URL_FOR_DATE, params) <NEW_LINE> for item in xml_body: <NEW_LINE> <INDENT> if item.attrib["ID"] == self.api_currency_code: <NEW_LINE> <INDENT> return float(item.find("Value").text.replace(",", ".")) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def fetch_rate_for_range_of_dates(self, start_date: str, end_date: str) -> dict: <NEW_LINE> <INDENT> params = {endpoints.API_REQUEST_DATE_RANGE_BEGIN: ApiDatesConverter(start_date).to_string(), endpoints.API_REQUEST_DATE_RANGE_END: ApiDatesConverter(end_date).to_string(), endpoints.API_REQUEST_CURRENCY_CODE: self.api_currency_code} <NEW_LINE> xml_body = self.execute_request_and_return_xml(endpoints.API_URL_FOR_DATE_RANGE, params) <NEW_LINE> dates = [self.api_response_to_datetime(item.attrib["Date"]) for item in xml_body] <NEW_LINE> values = [float(item.find("Value").text.replace(",", ".")) for item in xml_body] <NEW_LINE> return dict(zip(dates, values)) <NEW_LINE> <DEDENT> def api_response_to_datetime(self, datestr: str) -> datetime.datetime: <NEW_LINE> <INDENT> d, m, y = (int(n) for n in datestr.split(".")) <NEW_LINE> return datetime.datetime(y, m, d) <NEW_LINE> <DEDENT> def execute_request_and_return_xml(self, url: str, params: dict): <NEW_LINE> <INDENT> response = requests.get(url, params) <NEW_LINE> if response.status_code != requests.codes.ok: <NEW_LINE> <INDENT> raise Exception("Could not connect to cbr.ru and fetch data.") <NEW_LINE> <DEDENT> return ET.fromstring(response.text)
ExchangeRateFetcher must be initialized with correct CBR API currency code to work properly.
6259906af7d966606f7494b8
class RelationshipProfile(osid_managers.OsidProfile, relationship_managers.RelationshipProfile): <NEW_LINE> <INDENT> def __init__(self, interface_name): <NEW_LINE> <INDENT> osid_managers.OsidProfile.__init__(self) <NEW_LINE> <DEDENT> def _get_hierarchy_session(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._provider_manager.get_family_hierarchy_session( Id(authority='RELATIONSHIP', namespace='CATALOG', identifier='FAMILY')) <NEW_LINE> <DEDENT> except Unsupported: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def supports_relationship_lookup(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_relationship_lookup() <NEW_LINE> <DEDENT> def supports_relationship_query(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_relationship_query() <NEW_LINE> <DEDENT> def supports_relationship_admin(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_relationship_admin() <NEW_LINE> <DEDENT> def supports_family_lookup(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_family_lookup() <NEW_LINE> <DEDENT> def supports_family_admin(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_family_admin() <NEW_LINE> <DEDENT> def supports_family_hierarchy(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_family_hierarchy() <NEW_LINE> <DEDENT> def supports_family_hierarchy_design(self): <NEW_LINE> <INDENT> return self._provider_manager.supports_family_hierarchy_design() <NEW_LINE> <DEDENT> def get_relationship_record_types(self): <NEW_LINE> <INDENT> return self._provider_manager.get_relationship_record_types() <NEW_LINE> <DEDENT> relationship_record_types = property(fget=get_relationship_record_types) <NEW_LINE> def get_relationship_search_record_types(self): <NEW_LINE> <INDENT> return self._provider_manager.get_relationship_search_record_types() <NEW_LINE> <DEDENT> relationship_search_record_types = property(fget=get_relationship_search_record_types) <NEW_LINE> def get_family_record_types(self): <NEW_LINE> <INDENT> return self._provider_manager.get_family_record_types() <NEW_LINE> <DEDENT> family_record_types = property(fget=get_family_record_types) <NEW_LINE> def get_family_search_record_types(self): <NEW_LINE> <INDENT> return self._provider_manager.get_family_search_record_types() <NEW_LINE> <DEDENT> family_search_record_types = property(fget=get_family_search_record_types)
Adapts underlying RelationshipProfile methodswith authorization checks.
6259906b009cb60464d02d34
class Server(object): <NEW_LINE> <INDENT> def __init__(self, sock_server, quitcmd, spawncmd, destroycmd, updatecmd, players, idalloc): <NEW_LINE> <INDENT> self.sock_server = sock_server <NEW_LINE> self.quitcmd = quitcmd <NEW_LINE> self.spawncmd = spawncmd <NEW_LINE> self.destroycmd = destroycmd <NEW_LINE> self.updatecmd = updatecmd <NEW_LINE> self.players = players <NEW_LINE> self.idalloc = idalloc <NEW_LINE> <DEDENT> def on_hello(self, address): <NEW_LINE> <INDENT> if address not in self.players: <NEW_LINE> <INDENT> newid = self.idalloc.fetch() <NEW_LINE> boxman = ServerBoxman(newid) <NEW_LINE> for sendto, player in self.players.iteritems(): <NEW_LINE> <INDENT> self.spawncmd.send(ENT_BOXMAN, player, address) <NEW_LINE> self.spawncmd.send(ENT_BOXMAN, boxman, sendto) <NEW_LINE> <DEDENT> self.players[address] = boxman <NEW_LINE> self.spawncmd.send(ENT_PLAYER, boxman, address) <NEW_LINE> logger.debug("Hello:New client:%s", repr(address)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug("Hello:Client already known") <NEW_LINE> <DEDENT> <DEDENT> def on_quit(self, address): <NEW_LINE> <INDENT> if address in self.players: <NEW_LINE> <INDENT> oldid = self.players[address].id <NEW_LINE> self.idalloc.free(oldid) <NEW_LINE> del self.players[address] <NEW_LINE> self.quitcmd.send(address) <NEW_LINE> logger.debug("Quit:Client %s", repr(address)) <NEW_LINE> for address in self.players.iterkeys(): <NEW_LINE> <INDENT> self.destroycmd.send(oldid, address) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug("Quit:Client unknown") <NEW_LINE> <DEDENT> <DEDENT> def on_client(self, movement, address): <NEW_LINE> <INDENT> if address not in self.players: <NEW_LINE> <INDENT> logger.debug("Client:Client unknown") <NEW_LINE> return <NEW_LINE> <DEDENT> self.players[address].set_movement(movement) <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> for player in self.players.itervalues(): <NEW_LINE> <INDENT> player.update(dt) <NEW_LINE> <DEDENT> for address in self.players.iterkeys(): <NEW_LINE> <INDENT> self.updatecmd.send(self.players.values(), address) <NEW_LINE> <DEDENT> self.sock_server.update()
Handle updating entities and socket server
6259906a4a966d76dd5f06ec
class ActiveSubscriptionAPIView(SubscriptionSmartListMixin, ActiveSubscriptionBaseAPIView): <NEW_LINE> <INDENT> serializer_class = ProvidedSubscriptionSerializer <NEW_LINE> filter_backends = (SubscriptionSmartListMixin.filter_backends + (DateRangeFilter,))
Lists active subscriptions Lists all ``Subscription`` to a plan whose provider is ``{organization}`` and which are currently in progress. Optionnaly when an ``ends_at`` query parameter is specified, returns a queryset of ``Subscription`` that were active at ``ends_at``. When a ``start_at`` query parameter is specified, only considers ``Subscription`` that were created after ``start_at``. The queryset can be filtered for at least one field to match a search term (``q``). Query results can be ordered by natural fields (``o``) in either ascending or descending order (``ot``). The API is typically used within an HTML `subscribers page </docs/themes/#dashboard_profile_subscribers>`_ as present in the default theme. **Tags**: metrics, provider, profilemodel **Examples** .. code-block:: http GET /api/metrics/cowork/active/?o=created_at&ot=desc HTTP/1.1 responds .. code-block:: json { "count": 1, "next": null, "previous": null, "results": [ { "created_at": "2016-01-14T23:16:55Z", "ends_at": "2017-01-14T23:16:55Z", "description": null, "organization": { "slug": "xia", "printable_name": "Xia Lee" }, "plan": { "slug": "open-space", "title": "Open Space", "description": "open space desk, High speed internet - Ethernet or WiFi, Unlimited printing, Unlimited scanning, Unlimited fax service (send and receive)", "is_active": true, "setup_amount": 0, "period_amount": 17999, "interval": 4, "app_url": "http://localhost:8020/app" }, "auto_renew": true } ] }
6259906b435de62698e9d605
class States(Enum): <NEW_LINE> <INDENT> S_START = "0" <NEW_LINE> S_ENTER_NAME = "1" <NEW_LINE> S_ENTER_KOFE = "2" <NEW_LINE> S_SET_PAYMENT = "3"
Мы используем БД Vedis, в которой хранимые значения всегда строки, поэтому и тут будем использовать тоже строки (str)
6259906b16aa5153ce401cd4
class DescribeSecurityGroups(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Amazon/EC2/DescribeSecurityGroups') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return DescribeSecurityGroupsInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return DescribeSecurityGroupsResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return DescribeSecurityGroupsChoreographyExecution(session, exec_id, path)
Create a new instance of the DescribeSecurityGroups Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
6259906b56b00c62f0fb40c9
class FromStreamLoaderMixin(LoaderMixin): <NEW_LINE> <INDENT> def load_from_string(self, content, container, **kwargs): <NEW_LINE> <INDENT> return self.load_from_stream(anyconfig.compat.StringIO(content), container, **kwargs) <NEW_LINE> <DEDENT> def load_from_path(self, filepath, container, **kwargs): <NEW_LINE> <INDENT> with self.ropen(filepath) as inp: <NEW_LINE> <INDENT> return self.load_from_stream(inp, container, **kwargs)
Abstract config parser provides a method to load configuration from string content to help implement parser of which backend lacks of such function. Parser classes inherit this class have to override the method :meth:`load_from_stream` at least.
6259906b097d151d1a2c2869
class ReciprocalFit(ScatterFit): <NEW_LINE> <INDENT> def __init__(self, interp): <NEW_LINE> <INDENT> ScatterFit.__init__(self) <NEW_LINE> self._interp = copy.deepcopy(interp) <NEW_LINE> <DEDENT> def fit(self, x, y): <NEW_LINE> <INDENT> y = np.asarray(y) <NEW_LINE> self._interp.fit(x, 1.0 / y) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> return 1.0 / self._interp(x)
Interpolate the reciprocal of data. This allows any ScatterFit object to fit the reciprocal of a data set, without having to invert the data and the results explicitly. Parameters ---------- interp : object ScatterFit object to use on the reciprocal of the data
6259906b5fc7496912d48e65
class HomeView(TemplateView): <NEW_LINE> <INDENT> template_name = 'home.html'
View class for the homepage.
6259906ba8370b77170f1bc0
class QAData(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vocabulary = Vocabulary("./data/vocab_all.txt") <NEW_LINE> self.dec_timesteps=150 <NEW_LINE> self.enc_timesteps=150 <NEW_LINE> self.answers = pickle.load(open("./data/answers.pkl",'rb')) <NEW_LINE> self.training_set = pickle.load(open("./data/train.pkl",'rb')) <NEW_LINE> <DEDENT> def pad(self, data, length): <NEW_LINE> <INDENT> from keras.preprocessing.sequence import pad_sequences <NEW_LINE> return pad_sequences(data, maxlen=length, padding='post', truncating='post', value=0) <NEW_LINE> <DEDENT> def get_training_data(self): <NEW_LINE> <INDENT> questions = [] <NEW_LINE> good_answers = [] <NEW_LINE> for j, qa in enumerate(self.training_set): <NEW_LINE> <INDENT> questions.extend([qa['question']] * len(qa['answers'])) <NEW_LINE> good_answers.extend([self.answers[i] for i in qa['answers']]) <NEW_LINE> <DEDENT> questions = self.pad(questions, self.enc_timesteps) <NEW_LINE> good_answers = self.pad(good_answers, self.dec_timesteps) <NEW_LINE> bad_answers = self.pad(random.sample(list(self.answers.values()), len(good_answers)), self.dec_timesteps) <NEW_LINE> return questions,good_answers,bad_answers <NEW_LINE> <DEDENT> def process_data(self, d): <NEW_LINE> <INDENT> indices = d['good'] + d['bad'] <NEW_LINE> answers = self.pad([self.answers[i] for i in indices], self.dec_timesteps) <NEW_LINE> question = self.pad([d['question']] * len(indices), self.enc_timesteps) <NEW_LINE> return indices,answers,question <NEW_LINE> <DEDENT> def process_test_data(self, question, answers): <NEW_LINE> <INDENT> answer_unpadded = [] <NEW_LINE> for answer in answers: <NEW_LINE> <INDENT> print (answer.split(' ')) <NEW_LINE> answer_unpadded.append([self.vocabulary[word] for word in answer.split(' ')]) <NEW_LINE> <DEDENT> answers = self.pad(answer_unpadded, self.dec_timesteps) <NEW_LINE> question = self.pad([[self.vocabulary[word] for word in question.split(' ')]] * len(answers), self.enc_timesteps) <NEW_LINE> return answers, question
Load the train/predecit/test data
6259906bdd821e528d6da57e
class WSSHTTPServer(SSLMixIn, ThreadingHTTPServer): <NEW_LINE> <INDENT> pass
HTTP server with multi-threading, SSL configuration, and origin tracking. This aggregates all (pertinent) functionality from this package.
6259906bac7a0e7691f73ce2
class PublicIPFilter(logging.Filter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def filter(self, record): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ipv4 = re.findall(r'[0-9]+(?:\.[0-9]+){3}(?!\d*-[a-z0-9]{6})', record.msg) <NEW_LINE> for ip in ipv4: <NEW_LINE> <INDENT> if helpers.is_ip_public(ip): <NEW_LINE> <INDENT> record.msg = record.msg.replace(ip, ip.partition('.')[0] + '.***.***.***') <NEW_LINE> <DEDENT> <DEDENT> args = [] <NEW_LINE> for arg in record.args: <NEW_LINE> <INDENT> ipv4 = re.findall(r'[0-9]+(?:\.[0-9]+){3}(?!\d*-[a-z0-9]{6})', arg) if isinstance(arg, basestring) else [] <NEW_LINE> for ip in ipv4: <NEW_LINE> <INDENT> if helpers.is_ip_public(ip): <NEW_LINE> <INDENT> arg = arg.replace(ip, ip.partition('.')[0] + '.***.***.***') <NEW_LINE> <DEDENT> <DEDENT> args.append(arg) <NEW_LINE> <DEDENT> record.args = tuple(args) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return True
Log filter for public IP addresses
6259906b99cbb53fe68326e1
class Game(object): <NEW_LINE> <INDENT> def __init__(self, table, wheel): <NEW_LINE> <INDENT> self.table = table <NEW_LINE> self.wheel = wheel <NEW_LINE> <DEDENT> def cycle(self, player): <NEW_LINE> <INDENT> def resolve_bets(): <NEW_LINE> <INDENT> for bet in self.table.__iter__(): <NEW_LINE> <INDENT> if bet.outcome in winning_bin: <NEW_LINE> <INDENT> player.win(bet) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> player.lose(bet) <NEW_LINE> <DEDENT> <DEDENT> self.table.bets = [] <NEW_LINE> <DEDENT> if not player.playing(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> player.placeBets() <NEW_LINE> self.table.isValid() <NEW_LINE> winning_bin = self.wheel.next() <NEW_LINE> resolve_bets()
A Game of roulette, allows Players to play rounds.
6259906b5fdd1c0f98e5f780
class Downloader(object): <NEW_LINE> <INDENT> def send_request(self, request): <NEW_LINE> <INDENT> if request.method.upper() == "GET": <NEW_LINE> <INDENT> response = requests.get( url = request.url, headers = request.headers, params = request.params, proxies = request.proxy ) <NEW_LINE> <DEDENT> elif request.method.upper() == "POST": <NEW_LINE> <INDENT> response = requests.post( url = request.url, headers = request.headers, params = request.params, data = request.data, proxies = request.proxy ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("[ERROR]: Not Support method : <{}>".format(request.method)) <NEW_LINE> <DEDENT> logger.info("Downloader response : [{}] <{}>".format(response.status_code, response.url)) <NEW_LINE> return Response( url = response.url, status_code = response.status_code, headers = response.headers, body = response.content, encoding = chardet.detect(response.content)['encoding'] )
框架按设计的下载器组件,通过requests模块发送请求,构建并返回对应的Response对象
6259906b3d592f4c4edbc6db
class GeoBAM: <NEW_LINE> <INDENT> GEOBAM = importr("geoBAMr") <NEW_LINE> def __init__(self, input_data): <NEW_LINE> <INDENT> self.input_data = input_data <NEW_LINE> self.geobam_data = None <NEW_LINE> self.priors = None <NEW_LINE> <DEDENT> def bam_data(self): <NEW_LINE> <INDENT> numpy2ri.activate() <NEW_LINE> nrows_node = self.input_data["width"].shape[0] <NEW_LINE> nrows_reach = self.input_data["slope2"].shape[0] <NEW_LINE> width_matrix = robjects.r['matrix'](self.input_data["width"], nrow = nrows_node) <NEW_LINE> slope_matrix = robjects.r['matrix'](self.input_data["slope2"], nrow = nrows_reach) <NEW_LINE> d_x_a_matrix = robjects.r['matrix'](self.input_data["d_x_area"], nrow = nrows_node) <NEW_LINE> qhat_vector = robjects.FloatVector(self.input_data["Qhat"]) <NEW_LINE> data = self.GEOBAM.bam_data(w = width_matrix, s = slope_matrix, dA = d_x_a_matrix, Qhat = qhat_vector, variant = 'manning_amhg', max_xs = nrows_node) <NEW_LINE> numpy2ri.deactivate() <NEW_LINE> return data <NEW_LINE> <DEDENT> def bam_priors(self, geobam_data): <NEW_LINE> <INDENT> return self.GEOBAM.bam_priors(bamdata = geobam_data)
Class that represents a run of geoBAM to extract priors. Serves as an API to geoBAM functions which are written in R. Attributes ---------- input_data: dictionary dictionary of formatted input data
6259906b71ff763f4b5e8fa1
class EmailSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('id','email') <NEW_LINE> extra_kwargs = { 'email':{ 'required':True } } <NEW_LINE> <DEDENT> from django.core.mail import send_mail <NEW_LINE> def update(self, instance, validated_data): <NEW_LINE> <INDENT> email = validated_data['email'] <NEW_LINE> instance.email = email <NEW_LINE> instance.save() <NEW_LINE> url = instance.generic_verify_url() <NEW_LINE> from celery_tasks.email.tasks import send_verify_mail <NEW_LINE> send_verify_mail.delay(email,url) <NEW_LINE> return instance
邮箱序列化器
6259906b1b99ca4002290133
class SeqRef(ExprRef): <NEW_LINE> <INDENT> def sort(self): <NEW_LINE> <INDENT> return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Concat(self, other) <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return Concat(other, self) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> if _is_int(i): <NEW_LINE> <INDENT> i = IntVal(i, self.ctx) <NEW_LINE> <DEDENT> return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def at(self, i): <NEW_LINE> <INDENT> if _is_int(i): <NEW_LINE> <INDENT> i = IntVal(i, self.ctx) <NEW_LINE> <DEDENT> return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def is_string(self): <NEW_LINE> <INDENT> return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast())) <NEW_LINE> <DEDENT> def is_string_value(self): <NEW_LINE> <INDENT> return Z3_is_string(self.ctx_ref(), self.as_ast()) <NEW_LINE> <DEDENT> def as_string(self): <NEW_LINE> <INDENT> if self.is_string_value(): <NEW_LINE> <INDENT> string_length = ctypes.c_uint() <NEW_LINE> chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length)) <NEW_LINE> return string_at(chars, size=string_length.value).decode("latin-1") <NEW_LINE> <DEDENT> return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
Sequence expression.
6259906bd6c5a102081e3924
class ChangeCoursesStudentForm(forms.ModelForm): <NEW_LINE> <INDENT> courses = forms.ModelMultipleChoiceField(queryset=Course.objects.all(), widget=forms.widgets.CheckboxSelectMultiple()) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Student <NEW_LINE> fields = ['courses'] <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ChangeCoursesStudentForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['courses'].queryset = Course.objects.filter(Q(city=self.instance.school.city) & Q(years__in=[self.instance.year])).order_by('name') <NEW_LINE> self.initial['courses'] = [t.pk for t in self.instance.courses.all()] <NEW_LINE> self.fields['courses'].widget.attrs['class'] = "checkbox" <NEW_LINE> self.fields['courses'].widget.attrs['onclick'] = "was_changed($(this));" <NEW_LINE> <DEDENT> def clean_courses(self): <NEW_LINE> <INDENT> instance = self.instance <NEW_LINE> courses = self.cleaned_data.get('courses').all() <NEW_LINE> for course in courses: <NEW_LINE> <INDENT> if course not in instance.courses.all() and (not course.has_spots or course.prevent_enrollments): <NEW_LINE> <INDENT> raise forms.ValidationError( course.name + " já está lotada!" ) <NEW_LINE> <DEDENT> gen_1 = AllEvents(course=course) <NEW_LINE> for kourse in courses: <NEW_LINE> <INDENT> if kourse != course: <NEW_LINE> <INDENT> gen_2 = AllEvents(course=kourse) <NEW_LINE> if gen_1.compare(gen_2): <NEW_LINE> <INDENT> raise forms.ValidationError( "Você não pode se inscrever ao mesmo tempo em " + course.name + " e " + kourse.name ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return courses <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> instance = forms.ModelForm.save(self, False) <NEW_LINE> old_save_m2m = self.save_m2m <NEW_LINE> def save_m2m(): <NEW_LINE> <INDENT> old_save_m2m() <NEW_LINE> instance.courses.clear() <NEW_LINE> for course in self.cleaned_data['courses']: <NEW_LINE> <INDENT> instance.courses.add(course) <NEW_LINE> <DEDENT> <DEDENT> self.save_m2m = save_m2m <NEW_LINE> if commit: <NEW_LINE> <INDENT> instance.save() <NEW_LINE> self.save_m2m() <NEW_LINE> <DEDENT> return instance
ChangeCoursesStudentForm Base model that allows the user to change their courses
6259906b5166f23b2e244bcd
class BaseExtension(MapperExtension): <NEW_LINE> <INDENT> def before_insert(self, mapper, connection, instance): <NEW_LINE> <INDENT> datetime_now = datetime.datetime.now() <NEW_LINE> instance.created_at = datetime_now <NEW_LINE> if not instance.updated_at: <NEW_LINE> <INDENT> instance.updated_at = datetime_now <NEW_LINE> <DEDENT> <DEDENT> def before_update(self, mapper, connection, instance): <NEW_LINE> <INDENT> instance.updated_at = datetime.datetime.now()
Base entension class for all entity
6259906b1f5feb6acb1643e9
class WrongOptions(Exception): <NEW_LINE> <INDENT> def __init__(self, option): <NEW_LINE> <INDENT> self.option = option <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Option {} is not available".format(self.option)
Exception raised when options are not available
6259906b7c178a314d78e7e9
class VMD(Loader): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> super(VMD, self).__init__(filename) <NEW_LINE> self.atoms = self.constants['atoms'] <NEW_LINE> <DEDENT> def gofr_tcl(self, center, around, s=5000, e=-1, freq=1): <NEW_LINE> <INDENT> i = self.atoms.index(center) + 1 <NEW_LINE> j = self.atoms.index(around) + 1 <NEW_LINE> filename = 'gofr_{}-{}.tcl'.format(center, around) <NEW_LINE> with open(filename, 'w') as f: <NEW_LINE> <INDENT> f.write('set sel1 [atomselect top "type {:d}"]\n'.format(i)) <NEW_LINE> f.write('set sel2 [atomselect top "type {:d}"]\n'.format(j)) <NEW_LINE> f.write('set gr [measure gofr ') <NEW_LINE> f.write('$sel1 $sel2 delta .1 rmax 10 usepbc 1 selupdate 1 ') <NEW_LINE> f.write('first {:d} last {:d} step {:d}]\n'.format(s, e, freq)) <NEW_LINE> f.write('set outfile [open gofr_{}-{}.dat w]\n'.format(center, around)) <NEW_LINE> f.write('set r [lindex $gr 0]\n') <NEW_LINE> f.write('set gr2 [lindex $gr 1]\n') <NEW_LINE> f.write('set igr [lindex $gr 2]\n') <NEW_LINE> f.write('foreach j $r k $gr2 l $igr {\n') <NEW_LINE> f.write(' puts $outfile "$j $k $l"\n') <NEW_LINE> f.write('}\n') <NEW_LINE> f.write('close $outfile\n') <NEW_LINE> <DEDENT> <DEDENT> def load_tcl(self, data, trajectory, pairs, load_t=10000, interval_t=5000): <NEW_LINE> <INDENT> with open('load.tcl', 'w') as f: <NEW_LINE> <INDENT> f.write('topo readlammpsdata {}\n'.format(data)) <NEW_LINE> f.write('mol addfile {}\n'.format(trajectory)) <NEW_LINE> for a, b in pairs: <NEW_LINE> <INDENT> f.write('after {:d} source gofr_{}-{}.tcl\n'.format(load_t, a, b)) <NEW_LINE> load_t += interval_t
control VMD
6259906b66673b3332c31bf9
class NdmpLogs(object): <NEW_LINE> <INDENT> swagger_types = { 'errors': 'list[NodeStatusCpuError]', 'nodes': 'list[NdmpLogsNode]', 'total': 'int' } <NEW_LINE> attribute_map = { 'errors': 'errors', 'nodes': 'nodes', 'total': 'total' } <NEW_LINE> def __init__(self, errors=None, nodes=None, total=None): <NEW_LINE> <INDENT> self._errors = None <NEW_LINE> self._nodes = None <NEW_LINE> self._total = None <NEW_LINE> self.discriminator = None <NEW_LINE> if errors is not None: <NEW_LINE> <INDENT> self.errors = errors <NEW_LINE> <DEDENT> if nodes is not None: <NEW_LINE> <INDENT> self.nodes = nodes <NEW_LINE> <DEDENT> if total is not None: <NEW_LINE> <INDENT> self.total = total <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> return self._errors <NEW_LINE> <DEDENT> @errors.setter <NEW_LINE> def errors(self, errors): <NEW_LINE> <INDENT> self._errors = errors <NEW_LINE> <DEDENT> @property <NEW_LINE> def nodes(self): <NEW_LINE> <INDENT> return self._nodes <NEW_LINE> <DEDENT> @nodes.setter <NEW_LINE> def nodes(self, nodes): <NEW_LINE> <INDENT> self._nodes = nodes <NEW_LINE> <DEDENT> @property <NEW_LINE> def total(self): <NEW_LINE> <INDENT> return self._total <NEW_LINE> <DEDENT> @total.setter <NEW_LINE> def total(self, total): <NEW_LINE> <INDENT> if total is not None and total > 2147483647: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `total`, must be a value less than or equal to `2147483647`") <NEW_LINE> <DEDENT> if total is not None and total < 0: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `total`, must be a value greater than or equal to `0`") <NEW_LINE> <DEDENT> self._total = total <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NdmpLogs): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259906bcb5e8a47e493cd81
class UID: <NEW_LINE> <INDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return "%0.9u" % randint(0, 999999999)
Helper class, used to generate unique ids required by .cproject symbols.
6259906b8a43f66fc4bf398e
class BufferedWriter(_BufferedIOMixin): <NEW_LINE> <INDENT> def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): <NEW_LINE> <INDENT> if not raw.writable(): <NEW_LINE> <INDENT> raise OSError('"raw" argument must be writable.') <NEW_LINE> <DEDENT> _BufferedIOMixin.__init__(self, raw) <NEW_LINE> if buffer_size <= 0: <NEW_LINE> <INDENT> raise ValueError("invalid buffer size") <NEW_LINE> <DEDENT> self.buffer_size = buffer_size <NEW_LINE> self._write_buf = bytearray() <NEW_LINE> self._write_lock = Lock() <NEW_LINE> <DEDENT> def writable(self): <NEW_LINE> <INDENT> return self.raw.writable() <NEW_LINE> <DEDENT> def write(self, b): <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise ValueError("write to closed file") <NEW_LINE> <DEDENT> if isinstance(b, str): <NEW_LINE> <INDENT> raise TypeError("can't write str to binary stream") <NEW_LINE> <DEDENT> with self._write_lock: <NEW_LINE> <INDENT> if len(self._write_buf) > self.buffer_size: <NEW_LINE> <INDENT> self._flush_unlocked() <NEW_LINE> <DEDENT> before = len(self._write_buf) <NEW_LINE> self._write_buf.extend(b) <NEW_LINE> written = len(self._write_buf) - before <NEW_LINE> if len(self._write_buf) > self.buffer_size: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._flush_unlocked() <NEW_LINE> <DEDENT> except BlockingIOError as e: <NEW_LINE> <INDENT> if len(self._write_buf) > self.buffer_size: <NEW_LINE> <INDENT> overage = len(self._write_buf) - self.buffer_size <NEW_LINE> written -= overage <NEW_LINE> self._write_buf = self._write_buf[:self.buffer_size] <NEW_LINE> raise BlockingIOError(e.errno, e.strerror, written) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return written <NEW_LINE> <DEDENT> <DEDENT> def truncate(self, pos=None): <NEW_LINE> <INDENT> with self._write_lock: <NEW_LINE> <INDENT> self._flush_unlocked() <NEW_LINE> if pos is None: <NEW_LINE> <INDENT> pos = self.raw.tell() <NEW_LINE> <DEDENT> return self.raw.truncate(pos) <NEW_LINE> <DEDENT> <DEDENT> def flush(self): <NEW_LINE> <INDENT> with self._write_lock: <NEW_LINE> <INDENT> self._flush_unlocked() <NEW_LINE> <DEDENT> <DEDENT> def _flush_unlocked(self): <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise ValueError("flush on closed file") <NEW_LINE> <DEDENT> while self._write_buf: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> n = self.raw.write(self._write_buf) <NEW_LINE> <DEDENT> except BlockingIOError: <NEW_LINE> <INDENT> raise RuntimeError("self.raw should implement RawIOBase: it " "should not raise BlockingIOError") <NEW_LINE> <DEDENT> if n is None: <NEW_LINE> <INDENT> raise BlockingIOError( errno.EAGAIN, "write could not complete without blocking", 0) <NEW_LINE> <DEDENT> if n > len(self._write_buf) or n < 0: <NEW_LINE> <INDENT> raise OSError("write() returned incorrect number of bytes") <NEW_LINE> <DEDENT> del self._write_buf[:n] <NEW_LINE> <DEDENT> <DEDENT> def tell(self): <NEW_LINE> <INDENT> return _BufferedIOMixin.tell(self) + len(self._write_buf) <NEW_LINE> <DEDENT> def seek(self, pos, whence=0): <NEW_LINE> <INDENT> if whence not in valid_seek_flags: <NEW_LINE> <INDENT> raise ValueError("invalid whence value") <NEW_LINE> <DEDENT> with self._write_lock: <NEW_LINE> <INDENT> self._flush_unlocked() <NEW_LINE> return _BufferedIOMixin.seek(self, pos, whence)
A buffer for a writeable sequential RawIO object. The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE.
6259906ba219f33f346c8003
class FKApplication(models.Model): <NEW_LINE> <INDENT> state = FSMKeyField('testapp.DbState', default='new', on_delete=models.CASCADE) <NEW_LINE> @transition(field=state, source='new', target='draft') <NEW_LINE> def draft(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @transition(field=state, source=['new', 'draft'], target='dept') <NEW_LINE> def to_approvement(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @transition(field=state, source='dept', target='dean') <NEW_LINE> def dept_approved(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @transition(field=state, source='dept', target='new') <NEW_LINE> def dept_rejected(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @transition(field=state, source='dean', target='done') <NEW_LINE> def dean_approved(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @transition(field=state, source='dean', target='dept') <NEW_LINE> def dean_rejected(self): <NEW_LINE> <INDENT> pass
Student application need to be approved by dept chair and dean. Test workflow for FSMKeyField
6259906b4f88993c371f111d
class ImageFolderWithPaths(datasets.ImageFolder): <NEW_LINE> <INDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> original_tuple = super(ImageFolderWithPaths, self).__getitem__(index) <NEW_LINE> path = self.imgs[index][0] <NEW_LINE> tuple_with_path = (original_tuple + (path,)) <NEW_LINE> return tuple_with_path
Custom dataset that includes image file paths. Extends torchvision.datasets.ImageFolder
6259906b4e4d562566373c02
class HTMLResources(): <NEW_LINE> <INDENT> from gradingResource import const <NEW_LINE> const.MAIN_HTML = '/main.html' <NEW_LINE> const.USER_SIGNIN_HTML = '/user_signin.html' <NEW_LINE> const.ID_CHECK_HTML = '/id_check.html' <NEW_LINE> const.EDIT_PERSONAL_HTML = 'edit_personal.html' <NEW_LINE> const.BOARD_HTML = '/article_board.html' <NEW_LINE> const.ARTICLE_NOTICE_HTML = '/article_notice.html' <NEW_LINE> const.ARTICLE_READ_HTML = '/article_read.html' <NEW_LINE> const.ARTICLE_WRITE_HTML = '/article_write.html' <NEW_LINE> const.RANK_HTML = '/rank.html' <NEW_LINE> const.TEAM_HTML = '/team.html' <NEW_LINE> const.TEAM_MAKE_HTML = '/team_make.html' <NEW_LINE> const.TEAM_MANAGE_HTML = '/team_manage.html' <NEW_LINE> const.TEAM_INFORMATION_HTML = '/team_information.html' <NEW_LINE> const.SUBMISSION_RECORD_HTML = '/submission_record.html' <NEW_LINE> const.SUBMISSION_CODE_HTML = '/submission_code.html' <NEW_LINE> const.PROBLEM_HTML = '/problem.html' <NEW_LINE> const.PROBLEM_RECORD_HTML = '/problem_record.html' <NEW_LINE> const.PROBLEM_LIST_HTML = '/problem_list.html' <NEW_LINE> const.SERVER_ADD_CLASS_HTML = '/server_add_class.html' <NEW_LINE> const.SERVER_ADD_USER_HTML = '/server_add_user.html' <NEW_LINE> const.SERVER_MANAGE_CLASS_HTML = '/server_manage_class.html' <NEW_LINE> const.SERVER_MANAGE_COLLEGEDEPARTMENT_HTML = '/server_manage_collegedepartment.html' <NEW_LINE> const.SERVER_MANAGE_PROBLEM_HTML = '/server_manage_problem.html' <NEW_LINE> const.SERVER_MANAGE_SERVICE_HTML = '/server_manage_service.html' <NEW_LINE> const.SERVER_MANAGE_USER_HTML = '/server_manage_user.html' <NEW_LINE> const.UPLOAD_PROBLEM_HTML = '/upload_problem.htmll' <NEW_LINE> const.CLASS_ADD_USER_HTML = '/class_add_user.html' <NEW_LINE> const.CLASS_MANAGE_PROBLEM_HTML = '/class_manage_problem.html' <NEW_LINE> const.CLASS_MANAGE_SERVICE_HTML = '/class_manage_service.html' <NEW_LINE> const.CLASS_MANAGE_USER_HTML = '/class_manage_user.html' <NEW_LINE> const.CLASS_USER_SUBMIT_SUMMARY_HTML = '/class_user_submit_summary.html' <NEW_LINE> const.CLASS_USER_SUBMIT_HTML = '/class_user_submit.html' <NEW_LINE> const.USER_SUBMIT_SUMMARY_HTML = '/user_submit_summary.html'
HTML Resources
6259906b0a50d4780f7069be
class _AlgoType(ProxyType): <NEW_LINE> <INDENT> _typeID = '_AlgorithmType' <NEW_LINE> _typeEnum = 'AlgorithmType' <NEW_LINE> _propGroup = 'SolverAlgorithm' <NEW_LINE> _proxyName = '_algo' <NEW_LINE> @classmethod <NEW_LINE> def setDefaultTypeID(mcs,obj,name=None): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> name = _AlgoPowell.getName() <NEW_LINE> <DEDENT> super(_AlgoType,mcs).setDefaultTypeID(obj,name)
SciPy minimize algorithm meta class
6259906b442bda511e95d956
@attr.s(slots=True, frozen=True) <NEW_LINE> class TimeslotEntry: <NEW_LINE> <INDENT> start = attr.ib(type=str, default=None) <NEW_LINE> stop = attr.ib(type=str, default=None) <NEW_LINE> conditions = attr.ib(type=[ConditionEntry], default=[]) <NEW_LINE> condition_type = attr.ib(type=str, default=None) <NEW_LINE> actions = attr.ib(type=[ActionEntry], default=[])
Timeslot storage Entry.
6259906b92d797404e389759
class OcrmypdfPluginManager(pluggy.PluginManager): <NEW_LINE> <INDENT> def __init__( self, *args, plugins: List[Union[str, Path]], builtins: bool = True, **kwargs, ): <NEW_LINE> <INDENT> self.__init_args = args <NEW_LINE> self.__init_kwargs = kwargs <NEW_LINE> self.__plugins = plugins <NEW_LINE> self.__builtins = builtins <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> self.setup_plugins() <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> state = dict( init_args=self.__init_args, plugins=self.__plugins, builtins=self.__builtins, init_kwargs=self.__init_kwargs, ) <NEW_LINE> return state <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.__init__( *state['init_args'], plugins=state['plugins'], builtins=state['builtins'], **state['init_kwargs'], ) <NEW_LINE> <DEDENT> def setup_plugins(self): <NEW_LINE> <INDENT> self.add_hookspecs(pluginspec) <NEW_LINE> if self.__builtins: <NEW_LINE> <INDENT> for module in sorted( pkgutil.iter_modules(ocrmypdf.builtin_plugins.__path__) ): <NEW_LINE> <INDENT> name = f'ocrmypdf.builtin_plugins.{module.name}' <NEW_LINE> module = importlib.import_module(name) <NEW_LINE> self.register(module) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> from multiprocessing.synchronize import SemLock <NEW_LINE> del SemLock <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> self.register(importlib.import_module('ocrmypdf.extra_plugins.semfree')) <NEW_LINE> <DEDENT> self.load_setuptools_entrypoints('ocrmypdf') <NEW_LINE> for name in self.__plugins: <NEW_LINE> <INDENT> if isinstance(name, Path) or name.endswith('.py'): <NEW_LINE> <INDENT> module_name = Path(name).stem <NEW_LINE> spec = importlib.util.spec_from_file_location(module_name, name) <NEW_LINE> module = importlib.util.module_from_spec(spec) <NEW_LINE> sys.modules[module_name] = module <NEW_LINE> spec.loader.exec_module(module) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> module = importlib.import_module(name) <NEW_LINE> <DEDENT> self.register(module)
pluggy.PluginManager that can fork. Capable of reconstructing itself in child workers. Arguments: setup_func: callback that initializes the plugin manager with all standard plugins
6259906b7d847024c075dbd7
class PipelineResult: <NEW_LINE> <INDENT> def __init__(self, stdout, stderr, returncode): <NEW_LINE> <INDENT> self._stdout = stdout <NEW_LINE> self._stderr = stderr <NEW_LINE> self.returncode = returncode <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return self.returncode == 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _process(raw_data, single_line, as_lines, raw): <NEW_LINE> <INDENT> if single_line + as_lines + raw > 1: <NEW_LINE> <INDENT> raise RuntimeError("Incompatible arguments: only one of `single_line, as_lines, raw` can be true") <NEW_LINE> <DEDENT> if raw: <NEW_LINE> <INDENT> return raw_data <NEW_LINE> <DEDENT> result = concatenate_all_to_string(raw_data) <NEW_LINE> if single_line: <NEW_LINE> <INDENT> lines = [x for x in result.split(linesep) if x] <NEW_LINE> if len(lines) != 1: <NEW_LINE> <INDENT> raise RuntimeError("Not exactly one line: %s" % lines) <NEW_LINE> <DEDENT> result = lines[0] <NEW_LINE> <DEDENT> elif as_lines: <NEW_LINE> <INDENT> result = result.split(linesep) <NEW_LINE> if result[-1] == "": <NEW_LINE> <INDENT> result.pop() <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def stdout(self, single_line=False, as_lines=False, raw=False): <NEW_LINE> <INDENT> return self._process(self._stdout, single_line=single_line, as_lines=as_lines, raw=raw) <NEW_LINE> <DEDENT> def stderr(self, single_line=False, as_lines=False, raw=False): <NEW_LINE> <INDENT> return self._process(self._stderr, single_line=single_line, as_lines=as_lines, raw=raw) <NEW_LINE> <DEDENT> def _combine(self, other, returncode_combiner): <NEW_LINE> <INDENT> return PipelineResult(self._stdout + other._stdout, self._stderr + other._stderr, returncode_combiner(self.returncode, other.returncode)) <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return self._combine(other, lambda x, y: x and y) <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return self._combine(other, lambda x, y: x or y) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return self._combine(other, lambda x, y: y)
Represents the result of executing a pipeline
6259906b01c39578d7f14333
class AuthError(Exception): <NEW_LINE> <INDENT> def __init__(self, error, status_code): <NEW_LINE> <INDENT> self.error = error <NEW_LINE> self.status_code = status_code
A standardized way to communicate auth failure modes.
6259906ba8370b77170f1bc2
class RPCMethods(object): <NEW_LINE> <INDENT> _dotted_whitelist = ['subprocess'] <NEW_LINE> def __init__(self, server): <NEW_LINE> <INDENT> self._server = server <NEW_LINE> self.subprocess = process.Process <NEW_LINE> <DEDENT> def _dispatch(self, method, params): <NEW_LINE> <INDENT> obj = self <NEW_LINE> if '.' in method: <NEW_LINE> <INDENT> name, method = method.split('.') <NEW_LINE> assert name in self._dotted_whitelist <NEW_LINE> obj = getattr(self, name) <NEW_LINE> <DEDENT> return getattr(obj, method)(*params) <NEW_LINE> <DEDENT> def Echo(self, message): <NEW_LINE> <INDENT> logging.info('Echoing %s', message) <NEW_LINE> return 'echo %s' % str(message) <NEW_LINE> <DEDENT> def AbsPath(self, path): <NEW_LINE> <INDENT> return os.path.abspath(path) <NEW_LINE> <DEDENT> def Quit(self): <NEW_LINE> <INDENT> t = threading.Thread(target=self._server.shutdown) <NEW_LINE> t.start() <NEW_LINE> <DEDENT> def GetOutputDir(self): <NEW_LINE> <INDENT> return common_lib.GetOutputDir() <NEW_LINE> <DEDENT> def WriteFile(self, path, text, mode='wb+'): <NEW_LINE> <INDENT> with open(path, mode) as fh: <NEW_LINE> <INDENT> fh.write(text) <NEW_LINE> <DEDENT> <DEDENT> def ReadFile(self, path, mode='rb'): <NEW_LINE> <INDENT> with open(path, mode) as fh: <NEW_LINE> <INDENT> return fh.read() <NEW_LINE> <DEDENT> <DEDENT> def PathJoin(self, *parts): <NEW_LINE> <INDENT> return os.path.join(*parts) <NEW_LINE> <DEDENT> def ListDir(self, path): <NEW_LINE> <INDENT> return os.listdir(path)
Class exposing RPC methods.
6259906bbaa26c4b54d50aa4
class SelectorDIC(ModelSelector): <NEW_LINE> <INDENT> def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> models = [] <NEW_LINE> for num_of_components in range(self.min_n_components, self.max_n_components + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model = self.base_model(num_of_components) <NEW_LINE> model.fit(self.X, self.lengths) <NEW_LINE> score = model.score(self.X) <NEW_LINE> models.append((score, model)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> scores = [score for score, model in models] <NEW_LINE> sum_log_L = sum(scores) <NEW_LINE> best_score = float("-inf") <NEW_LINE> num_models = len(models) <NEW_LINE> best_model = None <NEW_LINE> for log_L, model in models: <NEW_LINE> <INDENT> score = log_L - (sum_log_L - log_L) / (num_models - 1.0) <NEW_LINE> if score > best_score: <NEW_LINE> <INDENT> best_model = model <NEW_LINE> best_score = score <NEW_LINE> <DEDENT> <DEDENT> return best_model
select best model based on Discriminative Information Criterion Biem, Alain. "A model selection criterion for classification: Application to hmm topology optimization." Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))
6259906b26068e7796d4e137
class ClassList(models.Model): <NEW_LINE> <INDENT> name = models.CharField("班级名称", max_length=32) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
班级
6259906b5fdd1c0f98e5f782
class ParserTestCase(integration_tests.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.useFixture(fixtures.EnvironmentVariable('TMPDIR', self.path)) <NEW_LINE> <DEDENT> def call_parser(self, wiki_path, expect_valid, expect_output=True): <NEW_LINE> <INDENT> part_file = os.path.join(self.path, 'parts.yaml') <NEW_LINE> args = ['--index', wiki_path, '--output', part_file] <NEW_LINE> if expect_valid: <NEW_LINE> <INDENT> self.run_snapcraft_parser(args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertRaises( subprocess.CalledProcessError, self.run_snapcraft_parser, args) <NEW_LINE> <DEDENT> self.assertEqual(os.path.exists(part_file), expect_output)
Test bin/snapcraft-parser
6259906b3539df3088ecda9c
class ComponentTests(ossie.utils.testing.ScaComponentTestCase): <NEW_LINE> <INDENT> def testScaBasicBehavior(self): <NEW_LINE> <INDENT> execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) <NEW_LINE> execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) <NEW_LINE> self.launch(execparams) <NEW_LINE> self.assertNotEqual(self.comp, None) <NEW_LINE> self.assertEqual(self.comp.ref._non_existent(), False) <NEW_LINE> self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True) <NEW_LINE> expectedProps = [] <NEW_LINE> expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) <NEW_LINE> expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True)) <NEW_LINE> props = self.comp.query([]) <NEW_LINE> props = dict((x.id, any.from_any(x.value)) for x in props) <NEW_LINE> for expectedProp in expectedProps: <NEW_LINE> <INDENT> self.assertEquals(props.has_key(expectedProp.id), True) <NEW_LINE> <DEDENT> for port in self.scd.get_componentfeatures().get_ports().get_uses(): <NEW_LINE> <INDENT> port_obj = self.comp.getPort(str(port.get_usesname())) <NEW_LINE> self.assertNotEqual(port_obj, None) <NEW_LINE> self.assertEqual(port_obj._non_existent(), False) <NEW_LINE> self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True) <NEW_LINE> <DEDENT> for port in self.scd.get_componentfeatures().get_ports().get_provides(): <NEW_LINE> <INDENT> port_obj = self.comp.getPort(str(port.get_providesname())) <NEW_LINE> self.assertNotEqual(port_obj, None) <NEW_LINE> self.assertEqual(port_obj._non_existent(), False) <NEW_LINE> self.assertEqual(port_obj._is_a(port.get_repid()), True) <NEW_LINE> <DEDENT> self.comp.start() <NEW_LINE> self.comp.stop() <NEW_LINE> self.comp.releaseObject()
Test for all component implementations in lms_dd_equalizer_cc
6259906bd268445f2663a75b
class BoardUnitListe(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._list = [] <NEW_LINE> <DEDENT> def add(self,BU): <NEW_LINE> <INDENT> if BU._name.strip() not in self._list: <NEW_LINE> <INDENT> self._list.append(BU) <NEW_LINE> <DEDENT> <DEDENT> def byName(self, name): <NEW_LINE> <INDENT> for test in self._list: <NEW_LINE> <INDENT> if test._name == name: <NEW_LINE> <INDENT> return test <NEW_LINE> <DEDENT> <DEDENT> return None
Contains all Boardunits/ECUs of a canmatrix in a list
6259906b23849d37ff8528b2
class KamajiError(Exception): <NEW_LINE> <INDENT> default_message = 'Kamaji Error' <NEW_LINE> def __init__(self, message=None, *args, **kwargs): <NEW_LINE> <INDENT> if not message: <NEW_LINE> <INDENT> message = self.default_message <NEW_LINE> <DEDENT> super(KamajiError, self).__init__(message, *args, **kwargs)
The base exception for all Kamaji Errors.
6259906b99cbb53fe68326e4
class Wannabe(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__args = args <NEW_LINE> self.__kwargs = kwargs <NEW_LINE> self.__calls = list() <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__args = args <NEW_LINE> self.__kwargs = kwargs <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name.startswith('_Wannabe__'): <NEW_LINE> <INDENT> return super(Wannabe, self).__getattribute__(name.replace('_Wannabe', '')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h = Wannabe() <NEW_LINE> self.__calls.append((name, h)) <NEW_LINE> return h <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name.startswith('_Wannabe__'): <NEW_LINE> <INDENT> super(Wannabe, self).__setattr__(name.replace('_Wannabe', ''), value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__calls.append(('__setattr__', (name, value))) <NEW_LINE> <DEDENT> <DEDENT> def __become(self, real_object): <NEW_LINE> <INDENT> for c, h in self.__calls: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if c == '__setattr__': <NEW_LINE> <INDENT> setattr(real_object, h[0], h[1]) <NEW_LINE> logging.debug('Executed pending call .%s = %r' % (h[0], h[1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getattr(real_object, c)(*h.__args, **h.__kwargs) <NEW_LINE> logging.debug('Executed pending call .%s(*args = %r, **kwargs = %r)' % (c, h.__args, h.__kwargs)) <NEW_LINE> <DEDENT> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> logging.debug(str(e))
An object that will become another.
6259906b97e22403b383c70a
class MemoryLog(Log): <NEW_LINE> <INDENT> def __init__(self, part_processor: Msg.PartProcessor = None) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._part_processor = part_processor <NEW_LINE> self._content = "" <NEW_LINE> <DEDENT> def __getstate__(self) -> dict: <NEW_LINE> <INDENT> state = super().__getstate__() <NEW_LINE> state["content"] = self._content <NEW_LINE> return state <NEW_LINE> <DEDENT> def __setstate__(self, state: dict) -> None: <NEW_LINE> <INDENT> super().__setstate__(state) <NEW_LINE> self._content = state["content"] <NEW_LINE> <DEDENT> def _write(self, msg: Msg) -> None: <NEW_LINE> <INDENT> self._content += msg.get_string(self._part_processor) <NEW_LINE> <DEDENT> def get_content(self) -> str: <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> return self._content
Log implementation that stores a log in memory.
6259906b44b2445a339b755e
class AppRouteURLKeyError(KeyError): <NEW_LINE> <INDENT> pass
An app route was constructed without required keyword match arguments.
6259906b2c8b7c6e89bd4fe3
class SyncListList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version, service_sid): <NEW_LINE> <INDENT> super(SyncListList, self).__init__(version) <NEW_LINE> self._solution = {'service_sid': service_sid, } <NEW_LINE> self._uri = '/Services/{service_sid}/Lists'.format(**self._solution) <NEW_LINE> <DEDENT> def create(self, unique_name=values.unset, ttl=values.unset, collection_ttl=values.unset): <NEW_LINE> <INDENT> data = values.of({'UniqueName': unique_name, 'Ttl': ttl, 'CollectionTtl': collection_ttl, }) <NEW_LINE> payload = self._version.create(method='POST', uri=self._uri, data=data, ) <NEW_LINE> return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], ) <NEW_LINE> <DEDENT> def stream(self, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_size) <NEW_LINE> page = self.page(page_size=limits['page_size'], ) <NEW_LINE> return self._version.stream(page, limits['limit'], limits['page_limit']) <NEW_LINE> <DEDENT> def list(self, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream(limit=limit, page_size=page_size, )) <NEW_LINE> <DEDENT> def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page(method='GET', uri=self._uri, params=data, ) <NEW_LINE> return SyncListPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get_page(self, target_url): <NEW_LINE> <INDENT> response = self._version.domain.twilio.request( 'GET', target_url, ) <NEW_LINE> return SyncListPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get(self, sid): <NEW_LINE> <INDENT> return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __call__(self, sid): <NEW_LINE> <INDENT> return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Sync.V1.SyncListList>'
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
6259906b8a43f66fc4bf3990
class NumDB(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.prefixes = [] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _merge(results): <NEW_LINE> <INDENT> ml = max(len(x) for x in results) <NEW_LINE> results = [x + (ml - len(x)) * [None] for x in results] <NEW_LINE> for parts in zip(*results): <NEW_LINE> <INDENT> partlist, proplist = list(zip(*(x for x in parts if x))) <NEW_LINE> part = min(partlist, key=len) <NEW_LINE> props = {} <NEW_LINE> for p in proplist: <NEW_LINE> <INDENT> props.update(p) <NEW_LINE> <DEDENT> yield part, props <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _find(number, prefixes): <NEW_LINE> <INDENT> if not number: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> results = [] <NEW_LINE> if prefixes: <NEW_LINE> <INDENT> for length, low, high, props, children in prefixes: <NEW_LINE> <INDENT> if low <= number[:length] <= high and len(number) >= length: <NEW_LINE> <INDENT> results.append([(number[:length], props)] + NumDB._find(number[length:], children)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not results: <NEW_LINE> <INDENT> return [(number, {})] <NEW_LINE> <DEDENT> return list(NumDB._merge(results)) <NEW_LINE> <DEDENT> def info(self, number): <NEW_LINE> <INDENT> return NumDB._find(number, self.prefixes) <NEW_LINE> <DEDENT> def split(self, number): <NEW_LINE> <INDENT> return [part for part, props in self.info(number)]
Number database.
6259906b56ac1b37e63038e1
class FoundationSampleForm(forms.Form): <NEW_LINE> <INDENT> title = forms.CharField(label=ugettext("title"), max_length=255, required=True) <NEW_LINE> content = forms.CharField(label=ugettext("content"), max_length=255, required=True, widget=forms.Textarea) <NEW_LINE> first_name = forms.CharField(label=ugettext("first_name"), max_length=255, required=True) <NEW_LINE> last_name = forms.CharField(label=ugettext("last_name"), max_length=255, required=True) <NEW_LINE> template = forms.CharField(label=ugettext("template"), max_length=255, required=True) <NEW_LINE> order = forms.CharField(label=ugettext("order"), max_length=255, required=True) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.helper = FormHelper() <NEW_LINE> self.helper.form_action = '.' <NEW_LINE> self.helper.layout = foundation_layout.Layout( foundation_layout.Fieldset( ugettext('Simple fieldset'), 'title', 'content', ), foundation_layout.Fieldset( ugettext('Columned in a row'), foundation_layout.Row( foundation_layout.Column('first_name', css_class='six'), foundation_layout.Column('last_name', css_class='six'), ), ), foundation_layout.Fieldset( ugettext('Columned in fluid row'), foundation_layout.RowFluid( foundation_layout.Column('template', css_class='six'), foundation_layout.Column('order', css_class='six'), ), ), foundation_layout.ButtonHolder( foundation_layout.Submit('submit_and_continue', ugettext('Save and continue')), foundation_layout.Submit('submit', ugettext('Save')), ), ) <NEW_LINE> super(FoundationSampleForm, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> return
Sample form
6259906b76e4537e8c3f0d80
class ColourItem: <NEW_LINE> <INDENT> def __init__(self, internal_colour): <NEW_LINE> <INDENT> self.internal_colour = internal_colour <NEW_LINE> self._colours = jef_colours.colour_mappings[internal_colour] <NEW_LINE> <DEDENT> def data(self, thread_type): <NEW_LINE> <INDENT> code = self._colours[thread_type] <NEW_LINE> return code <NEW_LINE> <DEDENT> def hasThread(self, thread_type): <NEW_LINE> <INDENT> return self._colours.has_key(thread_type) <NEW_LINE> <DEDENT> def colour(self, thread_type = None): <NEW_LINE> <INDENT> code = self.data(thread_type) <NEW_LINE> name, colour = jef_colours.known_colours[thread_type][code] <NEW_LINE> return colour <NEW_LINE> <DEDENT> def colours(self): <NEW_LINE> <INDENT> return self._colours <NEW_LINE> <DEDENT> def name(self, thread_type = None): <NEW_LINE> <INDENT> code = self.data(thread_type) <NEW_LINE> name, colour = jef_colours.known_colours[thread_type][code] <NEW_LINE> return name
ColourItem Represents an internal Janome colour and its interpretations in different thread types.
6259906b8e7ae83300eea88c
class ST_parser(FixedWidthParser): <NEW_LINE> <INDENT> page_sequence = FixedWidthField(0, 3) <NEW_LINE> record_type = FixedWidthField(3, 2) <NEW_LINE> election_id = FixedWidthField(5, 4) <NEW_LINE> statistical_text = FixedWidthField(15, 26) <NEW_LINE> statistical_text_cont = FixedWidthField(44, 26)
LAC doesn't appear to be using this in 2016 election.
6259906b4e4d562566373c04
class StepUpdateView(LoginRequiredMixin, UpdateView): <NEW_LINE> <INDENT> model = Step <NEW_LINE> form_class = UpdateStepForm <NEW_LINE> template_name = 'directions_edit.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['recipe_pk'] = self.model.objects.get(pk=self.kwargs['pk']).recipe.pk <NEW_LINE> return context <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> self.success_url = reverse_lazy('recipes:add-directions', kwargs={ 'pk': form.instance.recipe.pk }) <NEW_LINE> messages.add_message(self.request, messages.SUCCESS, f'Direction number {form.instance.step_number} has been updated!') <NEW_LINE> return super().form_valid(form)
Page where user can update an ingredient.
6259906b8e7ae83300eea88d
class TemplateInstanceNode(BXmlNode): <NEW_LINE> <INDENT> def __init__(self, buf, offset, chunk, parent): <NEW_LINE> <INDENT> super(TemplateInstanceNode, self).__init__(buf, offset, chunk, parent) <NEW_LINE> self.declare_field("byte", "token", 0x0) <NEW_LINE> self.declare_field("byte", "unknown0") <NEW_LINE> self.declare_field("dword", "template_id") <NEW_LINE> self.declare_field("dword", "template_offset") <NEW_LINE> self._data_length = 0 <NEW_LINE> if self.is_resident_template(): <NEW_LINE> <INDENT> new_template = self._chunk.add_template(self.template_offset(), parent=self) <NEW_LINE> self._data_length += new_template.length() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "TemplateInstanceNode(buf={!r}, offset={!r}, chunk={!r}, parent={!r})".format( self._buf, self.offset(), self._chunk, self._parent) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "TemplateInstanceNode(offset={}, length={}, token={})".format( hex(self.offset()), hex(self.length()), hex(0x0C)) <NEW_LINE> <DEDENT> def flags(self): <NEW_LINE> <INDENT> return self.token() >> 4 <NEW_LINE> <DEDENT> def is_resident_template(self): <NEW_LINE> <INDENT> return self.template_offset() > self.offset() - self._chunk._offset <NEW_LINE> <DEDENT> def tag_length(self): <NEW_LINE> <INDENT> return 10 <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> return self.tag_length() + self._data_length <NEW_LINE> <DEDENT> def template(self): <NEW_LINE> <INDENT> return self._chunk.templates()[self.template_offset()] <NEW_LINE> <DEDENT> def children(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> @memoize <NEW_LINE> def find_end_of_stream(self): <NEW_LINE> <INDENT> return self.template().find_end_of_stream()
The binary XML node for the system token 0x0C.
6259906b009cb60464d02d37
class GeojsonAPIView(APIView): <NEW_LINE> <INDENT> def get(self, request, *args, **keywords): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> encjson = serialize('geojson', Border.objects.filter(n03_004="中原区"),srid=4326, geometry_field='geom', fields=('n03_004',) ) <NEW_LINE> result = json.loads(encjson) <NEW_LINE> response = Response(result, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> response = Response({}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> response = Response({}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> return response
GeoJsonデータ取得 @return geojson形式
6259906b32920d7e50bc7844
class ProcessThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, type, status, module, command, cwd, callback, shell, env): <NEW_LINE> <INDENT> self.process = None <NEW_LINE> self._code = 2000 <NEW_LINE> self._output = "" <NEW_LINE> self.lock = threading.RLock() <NEW_LINE> self.type = type <NEW_LINE> self.status = status <NEW_LINE> self.module = module <NEW_LINE> self.command = command <NEW_LINE> self.cwd = cwd <NEW_LINE> self.callback = callback <NEW_LINE> self.shell = shell <NEW_LINE> self.env = os.environ.copy() <NEW_LINE> if env: <NEW_LINE> <INDENT> self.env.update(env) <NEW_LINE> <DEDENT> threading.Thread.__init__(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s(%s, %s)>" % (self.__class__.__name__, self.module, self.command) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._output.decode('utf-8') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return self._output.decode('latin-1') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def code(self): <NEW_LINE> <INDENT> return self._code <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logger.debug("Running %s command" % self.type) <NEW_LINE> self.process = Popen(self.command, stdout=PIPE, stderr=STDOUT, bufsize=1, cwd=self.cwd, shell=self.shell, env=self.env) <NEW_LINE> self.catch_output() <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.process.terminate() <NEW_LINE> self.join() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def catch_output(self): <NEW_LINE> <INDENT> while self.isAlive(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fd = select.select([self.process.stdout.fileno()], [], [], 5)[0][0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> fd = None <NEW_LINE> pass <NEW_LINE> <DEDENT> self.process.poll() <NEW_LINE> if self.process.returncode == None: <NEW_LINE> <INDENT> if fd: <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> self._output += os.read(fd, 1) <NEW_LINE> self.lock.release() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if fd: <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> while True: <NEW_LINE> <INDENT> output = os.read(fd, 4096) <NEW_LINE> if output == None or output == "": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self._output += output <NEW_LINE> <DEDENT> self.lock.release() <NEW_LINE> <DEDENT> self._code = self.process.returncode <NEW_LINE> if self.callback: <NEW_LINE> <INDENT> self.callback(self.module, self._code, self._output) <NEW_LINE> <DEDENT> logger.debug("Finished %s command" % self.type) <NEW_LINE> break
Base class for running tasks
6259906b4428ac0f6e659d30
class Cat: <NEW_LINE> <INDENT> def __init__( self, na, brd, vacc, tat, ag ): <NEW_LINE> <INDENT> self.name = na <NEW_LINE> self.breed = brd <NEW_LINE> self.vaccinated = vacc <NEW_LINE> self.age = ag <NEW_LINE> self.tattooed = tat <NEW_LINE> <DEDENT> def isVaccinated( self ): <NEW_LINE> <INDENT> return self.vaccinated <NEW_LINE> <DEDENT> def getAge( self ): <NEW_LINE> <INDENT> return self.age <NEW_LINE> <DEDENT> def getName( self ): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def getBreed(self): <NEW_LINE> <INDENT> return self.breed <NEW_LINE> <DEDENT> def isTattooed(self): <NEW_LINE> <INDENT> return self.tattooed <NEW_LINE> <DEDENT> def __str__( self ): <NEW_LINE> <INDENT> vacc = "vaccinated" <NEW_LINE> if not self.vaccinated: <NEW_LINE> <INDENT> vacc = "not vaccinated" <NEW_LINE> <DEDENT> tat= "not tattooed" <NEW_LINE> if not self.tattooed: <NEW_LINE> <INDENT> tat= "tattooed" <NEW_LINE> <DEDENT> return "{0:20}:==> {1:1}, {2:1}, {3:1}, {4:1} yrs old".format( self.name, self.breed, vacc, tat, self.age )
a class that implements a cat and its information. Name, breed, vaccinated, tattooed, and age.
6259906b67a9b606de5476a1
class TestRelatedCategoricalDataTable(DistributionTestCaseMixins, TestCase): <NEW_LINE> <INDENT> def test_render_single_related_categorical(self): <NEW_LINE> <INDENT> language_ids = self.create_test_languages() <NEW_LINE> language_distribution = self.get_distribution(language_ids) <NEW_LINE> language_name_distribution = self.recover_related_field_distribution(language_distribution, corpus_models.Language, 'name') <NEW_LINE> dataset = self.generate_messages_for_distribution( field_name='language_id', distribution=language_distribution, ) <NEW_LINE> dimension = registry.get_dimension('language') <NEW_LINE> datatable = models.DataTable(dimension) <NEW_LINE> result = datatable.render(dataset.message_set.all()) <NEW_LINE> self.assertDistributionsEqual(result, language_name_distribution, level_key='language', measure_key='value') <NEW_LINE> <DEDENT> def test_render_two_related_categorical(self): <NEW_LINE> <INDENT> language_ids = self.create_test_languages() <NEW_LINE> dataset = self.create_authors_with_values('username', ['username_%d' % d for d in xrange(5)]) <NEW_LINE> author_ids = dataset.person_set.values_list('id', flat=True).distinct() <NEW_LINE> value_pairs = [] <NEW_LINE> for lang in language_ids: <NEW_LINE> <INDENT> for author in author_ids: <NEW_LINE> <INDENT> if lang % 2 == 0 and author % 2 == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> value_pairs.append((lang, author)) <NEW_LINE> <DEDENT> <DEDENT> id_distribution = self.get_distribution(value_pairs) <NEW_LINE> self.generate_messages_for_multi_distribution(('language_id', 'sender_id'), id_distribution, dataset=dataset) <NEW_LINE> value_distribution = self.convert_id_distribution_to_related(id_distribution, (corpus_models.Language, corpus_models.Person), ('name', 'username')) <NEW_LINE> d1 = registry.get_dimension('language') <NEW_LINE> d2 = registry.get_dimension('sender') <NEW_LINE> datatable = models.DataTable(d1, d2) <NEW_LINE> result = datatable.render(dataset.message_set.all()) <NEW_LINE> self.assertMultiDistributionsEqual(result, value_distribution, ('language', 'sender'), measure_key='value')
Tests for categorical dimensions only, on a related table.
6259906b2ae34c7f260ac8e7
class Trip(models.Model): <NEW_LINE> <INDENT> REQUESTED = 'REQUESTED' <NEW_LINE> STARTED = 'STARTED' <NEW_LINE> IN_PROGRESS = 'IN_PROGRESS' <NEW_LINE> COMPLETED = 'COMPLETED' <NEW_LINE> STATUSES = ( (REQUESTED, REQUESTED), (STARTED, STARTED), (IN_PROGRESS, IN_PROGRESS), (COMPLETED, COMPLETED), ) <NEW_LINE> id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> pick_up_address = models.CharField(max_length=255) <NEW_LINE> drop_off_address = models.CharField(max_length=255) <NEW_LINE> rider = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.DO_NOTHING, related_name="trips_as_rider") <NEW_LINE> driver = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.DO_NOTHING, related_name="trips_as_driver") <NEW_LINE> status = models.CharField( max_length=100, choices=STATUSES, default=REQUESTED ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{}".format(self.id) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('trip_detail', kwargs={'trip_id': self.id})
Trip model
6259906b7d847024c075dbd9
class Conv4d(_ConvNd): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, kernel_size, groups=1,bias=True, pre_permuted_filters=True): <NEW_LINE> <INDENT> stride=1 <NEW_LINE> dilation=1 <NEW_LINE> padding = 0 <NEW_LINE> kernel_size = _quadruple(kernel_size) <NEW_LINE> stride = _quadruple(stride) <NEW_LINE> padding = _quadruple(padding) <NEW_LINE> dilation = _quadruple(dilation) <NEW_LINE> super(Conv4d, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, False, _quadruple(0), groups, bias, 'zero') <NEW_LINE> self.pre_permuted_filters=pre_permuted_filters <NEW_LINE> if self.pre_permuted_filters: <NEW_LINE> <INDENT> self.weight.data=self.weight.data.permute(2,0,1,3,4,5).contiguous() <NEW_LINE> <DEDENT> self.use_half=False <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return conv4d(input, self.weight, groups=self.groups,bias=self.bias,permute_filters=not self.pre_permuted_filters,use_half=self.use_half)
Applies a 4D convolution over an input signal composed of several input planes.
6259906b7047854f46340bb4
class ServiceChainInstance(gquota.GBPQuotaBase, model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): <NEW_LINE> <INDENT> __tablename__ = 'sc_instances' <NEW_LINE> name = sa.Column(sa.String(50)) <NEW_LINE> description = sa.Column(sa.String(255)) <NEW_LINE> config_param_values = sa.Column(sa.String(4096)) <NEW_LINE> specs = orm.relationship( InstanceSpecAssociation, backref='instances', cascade='all,delete, delete-orphan', order_by='InstanceSpecAssociation.position', collection_class=ordering_list('position', count_from=1)) <NEW_LINE> provider_ptg_id = sa.Column(sa.String(36), nullable=True) <NEW_LINE> consumer_ptg_id = sa.Column(sa.String(36), nullable=True) <NEW_LINE> management_ptg_id = sa.Column(sa.String(36), nullable=True) <NEW_LINE> classifier_id = sa.Column(sa.String(36), nullable=True)
Service chain instances
6259906bb7558d5895464b30
class ProductMigrationSourceViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = ProductMigrationSource.objects.all().order_by("name") <NEW_LINE> serializer_class = ProductMigrationSourceSerializer <NEW_LINE> lookup_field = 'id' <NEW_LINE> filter_backends = ( filters.DjangoFilterBackend, filters.SearchFilter, ) <NEW_LINE> filter_fields = ('id', 'name') <NEW_LINE> search_fields = ('$name',) <NEW_LINE> permission_classes = (permissions.DjangoModelPermissions,)
API endpoint for the ProductMigrationSource objects
6259906b379a373c97d9a81e
class Block(Base): <NEW_LINE> <INDENT> __tablename__ = 'block' <NEW_LINE> id = Column(String(32), primary_key=True) <NEW_LINE> secondary_id = Column(String(32)) <NEW_LINE> contig = Column(String(5)) <NEW_LINE> start = Column(Integer) <NEW_LINE> end = Column(Integer) <NEW_LINE> strand = Column(String(1)) <NEW_LINE> superblock_id = Column(String(32), ForeignKey('superblock.id')) <NEW_LINE> superblock = relationship( Superblock, backref=backref('blocks', order_by=start)) <NEW_LINE> def __init__(self, block_id=None, contig=None, start=None, end=None, strand=None, superblock_id=None, secondary_id=None): <NEW_LINE> <INDENT> super(Block, self).__init__() <NEW_LINE> self.id = block_id <NEW_LINE> self.contig = contig <NEW_LINE> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.strand = strand <NEW_LINE> self.superblock_id = superblock_id <NEW_LINE> self.secondary_id = secondary_id <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> base_count = 0 <NEW_LINE> for interval in self.intervals: <NEW_LINE> <INDENT> base_count += len(interval) <NEW_LINE> <DEDENT> return base_count
Set of non-overlapping intervals. A :class:`Block` can *only* be related to a single superset. Args: block_id (str): unique block id (e.g. CCDS transcript id) contig (str): contig/chromosome id start (int): 1-based start of the block (first interval) end (int): 1-based end of the block (last interval, no UTR) strand (str): strand +/- superblock_id (str): related superblock id, e.g. HGNC gene symbol secondary_id (str, optional): secondard block id
6259906b7047854f46340bb5
class LocalStorage(Storage): <NEW_LINE> <INDENT> def __init__(self, tarball_dir: str = '/src/contrib'): <NEW_LINE> <INDENT> self.tarball_dir = tarball_dir <NEW_LINE> super(LocalStorage, self).__init__() <NEW_LINE> <DEDENT> def store_tarball(self, category: str, doc_name: str, tmp_tarball_fp: str): <NEW_LINE> <INDENT> logger.info("Storing document: {doc_filename} with category: " "{doc_category} locally.".format(doc_filename=doc_name, doc_category=category)) <NEW_LINE> tarball_category_dir = os.path.join(self.tarball_dir, category) <NEW_LINE> dest_tarball_fp = os.path.join(tarball_category_dir, doc_name + ".tar.gz") <NEW_LINE> if not os.path.exists(tarball_category_dir): <NEW_LINE> <INDENT> os.mkdir(tarball_category_dir) <NEW_LINE> <DEDENT> if os.path.exists(dest_tarball_fp): <NEW_LINE> <INDENT> rmtree(dest_tarball_fp, ignore_errors=True) <NEW_LINE> <DEDENT> copyfile(tmp_tarball_fp, dest_tarball_fp) <NEW_LINE> <DEDENT> def delete_tarball(self, category: str, doc_name: str): <NEW_LINE> <INDENT> tarball_fp = os.path.join(self.tarball_dir, category, doc_name + ".tar.gz") <NEW_LINE> if os.path.exists(tarball_fp): <NEW_LINE> <INDENT> rmtree(tarball_fp, ignore_errors=True) <NEW_LINE> <DEDENT> <DEDENT> def initialize_storage(self): <NEW_LINE> <INDENT> for category_dir_name in os.listdir(self.tarball_dir): <NEW_LINE> <INDENT> category_dir_path = os.path.join(self.tarball_dir, category_dir_name) <NEW_LINE> if os.path.isdir(category_dir_path): <NEW_LINE> <INDENT> for tarball_filename in os.listdir(category_dir_path): <NEW_LINE> <INDENT> tarball_fp = os.path.join(category_dir_path, tarball_filename) <NEW_LINE> self.extract_docs_from_tarball(category=category_dir_name, doc_name=tarball_filename.replace(".tar.gz", ""), tmp_tarball_fp=tarball_fp)
Storage class extension to store document tarballs locally. Args: tarball_dir (str): Directory in which to store incoming tarballs.
6259906b32920d7e50bc7845
class Department(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> name = models.CharField(verbose_name='部门名称', max_length=32)
部门表
6259906badb09d7d5dc0bd69
class RemoveSchemaChange(UpgradeChange): <NEW_LINE> <INDENT> def __init__(self, schema_object: SchemaObject): <NEW_LINE> <INDENT> UpgradeChange.__init__(self, schema_object.order, [], [])
Simple removal of an existing object.
6259906b23849d37ff8528b5
class SudokuSquare: <NEW_LINE> <INDENT> def __init__(self, number=None, offsetX = 0, offsetY = 0, edit="Y", xLoc = 0, yLoc = 0): <NEW_LINE> <INDENT> if number is not None: <NEW_LINE> <INDENT> number = str(number) <NEW_LINE> self.color = (2, 204, 186) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> number = "" <NEW_LINE> self.color = (255, 255, 255) <NEW_LINE> <DEDENT> self.font = pygame.font.SysFont('opensans', 21) <NEW_LINE> self.text = self.font.render(number, 1, (255, 255, 255)) <NEW_LINE> self.textpos = self.text.get_rect() <NEW_LINE> self.textpos = self.textpos.move(offsetX + 17, offsetY + 4) <NEW_LINE> self.edit = edit <NEW_LINE> self.xLoc = xLoc <NEW_LINE> self.yLoc = yLoc <NEW_LINE> self.offsetX = offsetX <NEW_LINE> self.offsetY = offsetY <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> screen = pygame.display.get_surface() <NEW_LINE> AAfilledRoundedRect(screen, (self.offsetX, self.offsetY, 45, 40), self.color) <NEW_LINE> screen.blit(self.text, self.textpos) <NEW_LINE> <DEDENT> def checkCollide(self, collision): <NEW_LINE> <INDENT> if len(collision) == 2: <NEW_LINE> <INDENT> return self.collideRect.collidepoint(collision) <NEW_LINE> <DEDENT> elif len(collision) == 4: <NEW_LINE> <INDENT> return self.collideRect.colliderect(collision) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def highlight(self): <NEW_LINE> <INDENT> self.collide.fill((190, 190, 255)) <NEW_LINE> self.draw() <NEW_LINE> <DEDENT> def unhighlight(self): <NEW_LINE> <INDENT> self.collide.fill((255, 255, 255, 255)) <NEW_LINE> self.draw() <NEW_LINE> <DEDENT> def change(self, number): <NEW_LINE> <INDENT> if number is not None: <NEW_LINE> <INDENT> number = str(number) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> number = "" <NEW_LINE> <DEDENT> if self.edit == "Y": <NEW_LINE> <INDENT> self.text = self.font.render(number, 1, (0, 0, 0)) <NEW_LINE> self.draw() <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> def currentLoc(self): <NEW_LINE> <INDENT> return self.xLoc, self.yLoc
A sudoku square class.
6259906bf548e778e596cd8b
class Squid(HTTPProcess): <NEW_LINE> <INDENT> protocol = 'HTTP' <NEW_LINE> subprotocol = 'HEADER' <NEW_LINE> re_expr = re.compile("^squid/?(?P<version>[\w\.]+)?\s?(\((?P<os>\w*)\))?", re.IGNORECASE) <NEW_LINE> def process(self, data, metadata): <NEW_LINE> <INDENT> server = self.get_header_field(data, 'server') <NEW_LINE> if server: <NEW_LINE> <INDENT> match_obj = self.re_expr.search(server) <NEW_LINE> if match_obj: <NEW_LINE> <INDENT> metadata.service.product = 'Squid' <NEW_LINE> metadata.service.version = match_obj.group('version') <NEW_LINE> metadata.device.os = match_obj.group('os') <NEW_LINE> <DEDENT> <DEDENT> return metadata
http://www.squid-cache.org/
6259906b7c178a314d78e7eb
class SpotifyEpisode(SpotifyBase): <NEW_LINE> <INDENT> @scopes() <NEW_LINE> @send_and_process(single(FullEpisode)) <NEW_LINE> def episode( self, episode_id: str, market: str = None ) -> FullEpisode: <NEW_LINE> <INDENT> return self._get('episodes/' + episode_id, market=market) <NEW_LINE> <DEDENT> @scopes() <NEW_LINE> @chunked('episode_ids', 1, 50, join_lists) <NEW_LINE> @send_and_process(model_list(FullEpisode, 'episodes')) <NEW_LINE> def episodes( self, episode_ids: list, market: str = None ) -> ModelList[FullEpisode]: <NEW_LINE> <INDENT> return self._get('episodes/?ids=' + ','.join(episode_ids), market=market)
Episode API endpoints.
6259906b38b623060ffaa452
class RandomDisplacementBounds(object): <NEW_LINE> <INDENT> def __init__(self, xmin, xmax, stepsize=0.05): <NEW_LINE> <INDENT> self.xmin = xmin <NEW_LINE> self.xmax = xmax <NEW_LINE> self.stepsize = stepsize <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> xnew = x + np.random.uniform(-self.stepsize, self.stepsize, np.shape(x)) <NEW_LINE> if np.all(xnew < self.xmax) and np.all(xnew > self.xmin): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return xnew
random displacement with bounds
6259906b796e427e5384ff77
class Item(object): <NEW_LINE> <INDENT> __slots__ = ("id", "value", "type") <NEW_LINE> def __init__(self, id: str, value: Any) -> None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.value = value <NEW_LINE> self.type = type(value)
A class representing the defined item in a stored dataset. :ivar str id: The ID of the item. :ivar Any value: The item itself. :ivar Type type: The ID type representation.
6259906b8e7ae83300eea88e