code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class MyIntEnum(IntEnum): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def has_value(cls, value): <NEW_LINE> <INDENT> return (any(value == item.value for item in cls))
Add class method has_value to IntEnum to check whether a certain value exists in an enum.
62598fb8baa26c4b54d4f3ec
class BlockStyle(with_metaclass(ABCMeta, Base)): <NEW_LINE> <INDENT> def __init__(self, background_color=None, separator=None, separator_color=None, **kwargs): <NEW_LINE> <INDENT> super(BlockStyle, self).__init__(**kwargs) <NEW_LINE> self.background_color = background_color <NEW_LINE> self.separator = separator <NEW_LINE> self.separator_color = separator_color
BlockStyle. https://developers.line.biz/en/reference/messaging-api/#block-style
62598fb857b8e32f525081b6
class Account(models.Model): <NEW_LINE> <INDENT> date = models.DateField(null=True, blank=True) <NEW_LINE> krw = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) <NEW_LINE> usd = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) <NEW_LINE> cash = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.date)
계좌
62598fb84527f215b58ea009
class RenderCount(CachedPageRender): <NEW_LINE> <INDENT> def __init__(self, url_hash): <NEW_LINE> <INDENT> self.create_versioned_key(url_hash) <NEW_LINE> self.url_hash = url_hash <NEW_LINE> <DEDENT> def uncached_render(self, handler): <NEW_LINE> <INDENT> logging.info('Rendering count doc %s' % self.url_hash) <NEW_LINE> doc = model.Document.all().filter('url_hash =', self.url_hash).get() <NEW_LINE> assert(doc) <NEW_LINE> record_list = model.WordRecord.all().filter('doc =', doc) <NEW_LINE> path = os.path.join(os.path.dirname(__file__), 'templates/display.html') <NEW_LINE> return template.render(path, {'record_list' : record_list})
Deal with rendering the webpage showing the statistics of a document. Additionally deals with caching.
62598fb871ff763f4b5e78aa
class BaseUsage: <NEW_LINE> <INDENT> def __init__(self, database, user, server, channel): <NEW_LINE> <INDENT> self.database = database <NEW_LINE> self.server = server <NEW_LINE> self.user = user <NEW_LINE> self.channel = channel <NEW_LINE> self.newRecord = True
The base class for usage information.
62598fb84c3428357761a3ee
class WinView(LoginRequiredMixin, TemplateView): <NEW_LINE> <INDENT> template_name = 'wins/win-details.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = TemplateView.get_context_data(self, **kwargs) <NEW_LINE> resp = get_win_details(kwargs['win_id'], self.request) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> context['win'] = resp.json() <NEW_LINE> context['locked'] = locked(context['win']) <NEW_LINE> context['edit_days'] = settings.EDIT_TIMEOUT_DAYS <NEW_LINE> context['win']['date'] = date_parser(context['win']['date']) <NEW_LINE> return context
View details of a Win of logged in User
62598fb8f548e778e596b6d8
class HexKey(DummyKey): <NEW_LINE> <INDENT> KEY_FIELDS = ('value',) <NEW_LINE> __slots__ = KEY_FIELDS <NEW_LINE> CANONICAL_NAMESPACE = 'hex' <NEW_LINE> def _to_string(self): <NEW_LINE> <INDENT> return hex(self.value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_string(cls, serialized): <NEW_LINE> <INDENT> if not serialized.startswith('0x'): <NEW_LINE> <INDENT> raise InvalidKeyError(cls, serialized) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return cls(int(serialized, 16)) <NEW_LINE> <DEDENT> except (ValueError, TypeError) as error: <NEW_LINE> <INDENT> raise InvalidKeyError(cls, serialized) from error
Key type for testing; _from_string takes hex values
62598fb856b00c62f0fb29ed
class CVI_1014(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.svid = 1014 <NEW_LINE> self.language = "PHP" <NEW_LINE> self.author = "LoRexxar/wufeifei" <NEW_LINE> self.vulnerability = "variable shadowing" <NEW_LINE> self.description = "variable shadowing" <NEW_LINE> self.status = True <NEW_LINE> self.match_mode = "function-param-regex" <NEW_LINE> self.match = "import_request_variables|parse_str|mb_parse_str" <NEW_LINE> self.vul_function = None <NEW_LINE> <DEDENT> def main(self, regex_string): <NEW_LINE> <INDENT> pass
rule class
62598fb8aad79263cf42e907
class TestSocialsApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = bombbomb.apis.socials_api.SocialsApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_social_article_properties(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_social_auto_shares(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_social_permissions(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_social_status(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_social_auto_shares(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_social_message(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_social_status(self): <NEW_LINE> <INDENT> pass
SocialsApi unit test stubs
62598fb867a9b606de546104
class Meta: <NEW_LINE> <INDENT> ordering = ["command", "subcommand", "grant_type"]
Meta-attributes of an AccessGrant.
62598fb867a9b606de546105
class Command(BaseCommand): <NEW_LINE> <INDENT> help = ('Pulls strings from the database and appends them to an existing ' '.pot file.') <NEW_LINE> option_list = BaseCommand.option_list + ( make_option('--output-dir', '-o', default=os.path.join(settings.ROOT, 'locale', 'templates', 'LC_MESSAGES'), dest='outputdir', help='The directory where extracted files are located.' '(Default: %default)'), ) <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> apps = settings.DB_LOCALIZE <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise CommandError('DB_LOCALIZE setting is not defined!') <NEW_LINE> <DEDENT> strings = [] <NEW_LINE> for app, models in apps.items(): <NEW_LINE> <INDENT> for model, params in models.items(): <NEW_LINE> <INDENT> model_class = get_model(app, model) <NEW_LINE> for item in model_class.objects.all().values(): <NEW_LINE> <INDENT> for attr in params['attrs']: <NEW_LINE> <INDENT> msg = { 'id': item[attr], 'auto_comments': ['DB: %s.%s.%s' % (app, model, attr)], 'user_comments': params['comments'], } <NEW_LINE> strings.append(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> po_dir = os.path.abspath(options.get('outputdir')) <NEW_LINE> po_filename = os.path.join(po_dir, '%s.pot' % TEXT_DOMAIN) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(po_filename, 'r') as f: <NEW_LINE> <INDENT> catalog = read_po(f) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> catalog = Catalog() <NEW_LINE> <DEDENT> for msg in strings: <NEW_LINE> <INDENT> catalog.add(tweak_message(msg['id']), auto_comments=msg['auto_comments'], user_comments=msg['user_comments']) <NEW_LINE> <DEDENT> with open(po_filename, 'w+') as f: <NEW_LINE> <INDENT> write_po(f, catalog)
Pulls strings from the database and appends them to an existing pot file. The models and attributes to pull are defined by DB_LOCALIZE: DB_LOCALIZE = { 'some_app': { SomeModel': { 'attrs': ['attr_name', 'another_attr'], } }, 'another_app': { AnotherModel': { 'attrs': ['more_attrs'], 'comments': ['Comment that will appear to localizers.'], } }, } Database columns are expected to be CharFields or TextFields.
62598fb88e7ae83300ee91d3
class CPTECControlData: <NEW_LINE> <INDENT> def __init__(self, hass, data, devices): <NEW_LINE> <INDENT> self.devices = devices <NEW_LINE> self.data = data <NEW_LINE> self.hass = hass <NEW_LINE> <DEDENT> async def fetching_data(self, *_): <NEW_LINE> <INDENT> def try_again(err: str): <NEW_LINE> <INDENT> minutes = 1 <NEW_LINE> _LOGGER.error("Retrying in %i minutes: %s", minutes, err) <NEW_LINE> async_call_later(self.hass, minutes*60, self.fetching_data) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with async_timeout.timeout(10, loop=self.hass.loop): <NEW_LINE> <INDENT> await self.data.async_update_current() <NEW_LINE> <DEDENT> <DEDENT> except (Exception) as err: <NEW_LINE> <INDENT> try_again(err) <NEW_LINE> return <NEW_LINE> <DEDENT> await self.updating_devices() <NEW_LINE> async_call_later(self.hass, 60*60, self.fetching_data) <NEW_LINE> <DEDENT> async def updating_devices(self, *_): <NEW_LINE> <INDENT> if not self.data._conditions: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tasks = [] <NEW_LINE> for dev in self.devices: <NEW_LINE> <INDENT> dev.station_id = self.data.station_id <NEW_LINE> dev.last_updated = self.data.get_reading('last_time_updated') <NEW_LINE> new_state = self.data.get_reading(dev.type) <NEW_LINE> if new_state != dev._state: <NEW_LINE> <INDENT> if dev.type == 'weather': <NEW_LINE> <INDENT> with async_timeout.timeout(10, loop=self.hass.loop): <NEW_LINE> <INDENT> dev.url_icon = await self.data.async_get_formated_icon_URL(_isNight= not sun.is_up(self.hass)) <NEW_LINE> <DEDENT> if dev.url_icon is None: <NEW_LINE> <INDENT> _LOGGER.error("ERROR when get url icon: %s", dev.url_icon) <NEW_LINE> <DEDENT> <DEDENT> dev._state = new_state <NEW_LINE> tasks.append(dev.async_update_ha_state()) <NEW_LINE> <DEDENT> <DEDENT> if tasks: <NEW_LINE> <INDENT> await asyncio.wait(tasks, loop=self.hass.loop)
Get the latest data and updates the states.
62598fb856ac1b37e630231f
class SteeringToWheelVelWrapper(gym.ActionWrapper): <NEW_LINE> <INDENT> def __init__(self, env, gain=1.0, trim=0.0, radius=0.0318, k=27.0, limit=1.0 ): <NEW_LINE> <INDENT> gym.ActionWrapper.__init__(self, env) <NEW_LINE> self.gain = gain <NEW_LINE> self.trim = trim <NEW_LINE> self.radius = radius <NEW_LINE> self.k = k <NEW_LINE> self.limit = limit <NEW_LINE> <DEDENT> def action(self, action): <NEW_LINE> <INDENT> vel, angle = action <NEW_LINE> baseline = self.unwrapped.wheel_dist <NEW_LINE> k_r = self.k <NEW_LINE> k_l = self.k <NEW_LINE> k_r_inv = (self.gain + self.trim) / k_r <NEW_LINE> k_l_inv = (self.gain - self.trim) / k_l <NEW_LINE> omega_r = (vel + 0.5 * angle * baseline) / self.radius <NEW_LINE> omega_l = (vel - 0.5 * angle * baseline) / self.radius <NEW_LINE> u_r = omega_r * k_r_inv <NEW_LINE> u_l = omega_l * k_l_inv <NEW_LINE> u_r_limited = max(min(u_r, self.limit), -self.limit) <NEW_LINE> u_l_limited = max(min(u_l, self.limit), -self.limit) <NEW_LINE> vels = np.array([u_l_limited, u_r_limited]) <NEW_LINE> return vels
Converts policy that was trained with [velocity|heading] actions to [wheelvel_left|wheelvel_right] to comply with AIDO evaluation format
62598fb8956e5f7376df5717
class AhiRSR(object): <NEW_LINE> <INDENT> def __init__(self, platform_name, wavespace='wavelength'): <NEW_LINE> <INDENT> self.platform_name = platform_name <NEW_LINE> self.filename = None <NEW_LINE> self.rsr = None <NEW_LINE> options = get_config() <NEW_LINE> self.output_dir = options.get('rsr_dir', './') <NEW_LINE> ahi_options = options[platform_name + '-ahi'] <NEW_LINE> self.filename = ahi_options['path'] <NEW_LINE> LOG.debug("Filenames: " + str(self.filename)) <NEW_LINE> if os.path.exists(self.filename): <NEW_LINE> <INDENT> self._load() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError("Couldn't find an existing file for this band: " + str(self.bandname)) <NEW_LINE> <DEDENT> <DEDENT> def _load(self, filename=None): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> filename = self.filename <NEW_LINE> <DEDENT> wb_ = open_workbook(filename) <NEW_LINE> self.rsr = {} <NEW_LINE> sheet_names = [] <NEW_LINE> for sheet in wb_.sheets(): <NEW_LINE> <INDENT> if sheet.name in ['Title', ]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ch_name = AHI_BAND_NAMES.get( sheet.name.strip(), sheet.name.strip()) <NEW_LINE> sheet_names.append(sheet.name.strip()) <NEW_LINE> self.rsr[ch_name] = {'wavelength': None, 'response': None} <NEW_LINE> wvl = np.array( sheet.col_values(0, start_rowx=5, end_rowx=5453)) <NEW_LINE> resp = np.array( sheet.col_values(2, start_rowx=5, end_rowx=5453)) <NEW_LINE> self.rsr[ch_name]['wavelength'] = wvl <NEW_LINE> self.rsr[ch_name]['response'] = resp
Container for the Himawari AHI relative spectral response data
62598fb856ac1b37e6302320
class TestBuildSequences(unittest.TestCase): <NEW_LINE> <INDENT> def testBuildSequences(self): <NEW_LINE> <INDENT> seqs = buildSequences([]) <NEW_LINE> self.assertEqual([], seqs) <NEW_LINE> seqs = buildSequences(["spam1", "spam3", "spam2"]) <NEW_LINE> self.assertEqual(1, len(seqs)) <NEW_LINE> self.assertEqual(["spam1", "spam2", "spam3"], list(seqs[0])) <NEW_LINE> seqs = buildSequences(["clip1_1", "clip2_1", "clip1_2", "clip2_2"]) <NEW_LINE> self.assertEqual(1, len(seqs)) <NEW_LINE> self.assertEqual(["clip1_1", "clip1_2", "clip2_1", "clip2_2"], list(seqs[0])) <NEW_LINE> seqs = buildSequences(["clip1_1", "clip2_1", "clip1_2", "clip2_2"], numPos=-1) <NEW_LINE> self.assertEqual(2, len(seqs)) <NEW_LINE> self.assertEqual(["clip1_1", "clip1_2"], list(seqs[0])) <NEW_LINE> self.assertEqual(["clip2_1", "clip2_2"], list(seqs[1])) <NEW_LINE> seqs = buildSequences([1,3,2], nameFunc=lambda obj: "obj%d"%obj) <NEW_LINE> self.assertEqual([1,2,3], list(seqs[0].iterObjects())) <NEW_LINE> self.assertEqual(["obj1", "obj2", "obj3"], list(seqs[0].iterNames())) <NEW_LINE> seqs = buildSequences(["dir1/spam1", "dir2/spam1"]) <NEW_LINE> self.assertEqual(1, len(seqs)) <NEW_LINE> self.assertEqual(["dir1/spam1", "dir2/spam1"], list(seqs[0])) <NEW_LINE> seqs = buildSequences(["dir1/spam1", "dir2/spam1"], assumeFiles=True) <NEW_LINE> self.assertEqual(2, len(seqs)) <NEW_LINE> self.assertEqual(["dir1/spam1"], list(seqs[0])) <NEW_LINE> self.assertEqual(["dir2/spam1"], list(seqs[1])) <NEW_LINE> seqs = buildSequences(["/dir1/dir2/spam1", "/dir1/dir2/spam2"], assumeFiles=True) <NEW_LINE> self.assertEqual(1, len(seqs)) <NEW_LINE> self.assertEqual(("/dir1/dir2/spam@", ["1-2"]), seqs[0].sequenceName())
Test the buildSequences() function.
62598fb87d43ff248742749d
class LocationType(TimeStampedModel): <NEW_LINE> <INDENT> label = models.CharField(_('label'), max_length=32, default='') <NEW_LINE> value = models.CharField(_('value'), max_length=32, default='') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('location type') <NEW_LINE> verbose_name_plural = _('location types') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.label
Location type
62598fb85fcc89381b2661e6
class Stylelint(Linter): <NEW_LINE> <INDENT> syntax = ('css', 'css3') <NEW_LINE> cmd = ('node', os.path.dirname(os.path.realpath(__file__)) + '/stylelint_wrapper.js', '@') <NEW_LINE> error_stream = util.STREAM_BOTH <NEW_LINE> config_file = ('--config', '.stylelintrc') <NEW_LINE> tempfile_suffix = 'css' <NEW_LINE> regex = ( r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' )
Provides an interface to stylelint.
62598fb87b180e01f3e490eb
class LatestSieve(IntStrSieve, CacheMixin): <NEW_LINE> <INDENT> name = "latest" <NEW_LINE> def __init__(self, sifter, tagname, *tagnames): <NEW_LINE> <INDENT> super().__init__(sifter, tagname, *tagnames) <NEW_LINE> self.tag_ids = None <NEW_LINE> <DEDENT> def prep(self, session, binfos): <NEW_LINE> <INDENT> tids = self.tag_ids <NEW_LINE> if tids is None: <NEW_LINE> <INDENT> tags = bulk_load_tags(session, self.tokens, err=True) <NEW_LINE> tids = self.tag_ids = unique(t["id"] for t in tags.values()) <NEW_LINE> <DEDENT> for tid in tids: <NEW_LINE> <INDENT> self.latest_build_ids(session, tid, inherit=True) <NEW_LINE> <DEDENT> <DEDENT> def check(self, session, binfo): <NEW_LINE> <INDENT> bid = binfo["id"] <NEW_LINE> for tid in self.tag_ids: <NEW_LINE> <INDENT> latest = self.latest_build_ids(session, tid, inherit=True) <NEW_LINE> if bid in latest: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
usage: ``(latest TAG [TAG...])`` Passes build infos that are the latest build of their package name in any of the tags.
62598fb87cff6e4e811b5b54
class BufferedRWPair(_BufferedIOBase): <NEW_LINE> <INDENT> def close(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def flush(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isatty(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def peek(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read1(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def readable(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def readinto(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def readinto1(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def writable(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def write(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __getstate__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> closed = property(lambda self: object(), lambda self, v: None, lambda self: None)
A buffered reader and writer object together. A buffered reader object and buffered writer object put together to form a sequential IO object that can read and write. This is typically used with a socket or two-way pipe. reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
62598fb87c178a314d78d5d2
class ForwardOpenD1 (ForwardOpen) : <NEW_LINE> <INDENT> def __init__ ( self , I = 3 , with_error = False , maX_step = -1 ) : <NEW_LINE> <INDENT> ForwardOpen.__init__ ( self , 1 , I , with_error = with_error , max_step = max_step )
Forward open rule for the 1st derivative
62598fb8dc8b845886d536ec
class TestSearchResult(unittest.TestCase): <NEW_LINE> <INDENT> def test_update(self): <NEW_LINE> <INDENT> with mock.patch('npyscreen.Textfield.__init__') as mock_init: <NEW_LINE> <INDENT> mock_init.return_value = None <NEW_LINE> search_result = SearchResult(mock.MagicMock()) <NEW_LINE> <DEDENT> mock_parent = search_result.parent = mock.MagicMock() <NEW_LINE> mock_parent.results_list.side_effect = Exception <NEW_LINE> search_result.highlight = False <NEW_LINE> with mock.patch('npyscreen.Textfield.update') as mock_update: <NEW_LINE> <INDENT> search_result.update() <NEW_LINE> self.assertTrue(mock_update.called_once) <NEW_LINE> <DEDENT> mock_parent.reset_mock() <NEW_LINE> search_result.highlight = True <NEW_LINE> mock_parent.results_list.side_effect = None <NEW_LINE> mock_parent.results_list.values = ['a', 'b', 'c'] <NEW_LINE> mock_parent.results_list.cursor_line = 1 <NEW_LINE> with mock.patch('npyscreen.Textfield.update') as mock_update: <NEW_LINE> <INDENT> search_result.update() <NEW_LINE> <DEDENT> self.assertTrue(mock_update.called_once) <NEW_LINE> self.assertFalse(mock_parent.results_list.update.called) <NEW_LINE> mock_parent.reset_mock() <NEW_LINE> mock_parent.parentApp.page = 41 <NEW_LINE> mock_parent.results_list.cursor_line = 2 <NEW_LINE> mock_parent.search_box.search.return_value = list(range(2)) <NEW_LINE> with mock.patch('npyscreen.Textfield.update') as mock_update: <NEW_LINE> <INDENT> search_result.update() <NEW_LINE> <DEDENT> self.assertTrue(mock_update.called_once) <NEW_LINE> self.assertTrue(mock_parent.results_list.update.called) <NEW_LINE> self.assertEqual(42, mock_parent.parentApp.page) <NEW_LINE> self.assertNotEqual(False, mock_parent.parentApp.more) <NEW_LINE> mock_parent.search_box.search.assert_called_once_with(page=42) <NEW_LINE> mock_parent.reset_mock() <NEW_LINE> mock_parent.results_list.values = ['a', 'b', 'c'] <NEW_LINE> mock_parent.search_box.search.return_value = [] <NEW_LINE> mock_parent.parentApp.more = True <NEW_LINE> with mock.patch('npyscreen.Textfield.update') as mock_update: <NEW_LINE> <INDENT> search_result.update() <NEW_LINE> <DEDENT> self.assertTrue(mock_update.called_once) <NEW_LINE> self.assertTrue(mock_parent.results_list.update.called) <NEW_LINE> self.assertEqual(43, mock_parent.parentApp.page) <NEW_LINE> self.assertEqual(False, mock_parent.parentApp.more) <NEW_LINE> mock_parent.search_box.search.assert_called_once_with(page=43)
Verify the SearchResult Component.
62598fb892d797404e388bfd
class TestBigSegmentTarget(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testBigSegmentTarget(self): <NEW_LINE> <INDENT> pass
BigSegmentTarget unit test stubs
62598fb8851cf427c66b83ea
class TestBigqueryCredential(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testBigqueryCredential(self): <NEW_LINE> <INDENT> pass
BigqueryCredential unit test stubs
62598fb8baa26c4b54d4f3ee
class Node: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.wallet = Wallet() <NEW_LINE> self.wallet.create_keys() <NEW_LINE> self.blockchain = Blockchain(self.wallet.public_key) <NEW_LINE> <DEDENT> def get_transaction_value(self): <NEW_LINE> <INDENT> tx_recipient = input('Enter the recipient of the transaction: ') <NEW_LINE> tx_amount = float(input('Your transaction amount please: ')) <NEW_LINE> return tx_recipient, tx_amount <NEW_LINE> <DEDENT> def get_user_choice(self): <NEW_LINE> <INDENT> user_input = input('Your choice: ') <NEW_LINE> return user_input <NEW_LINE> <DEDENT> def print_blockchain_elements(self): <NEW_LINE> <INDENT> for block in self.blockchain.chain: <NEW_LINE> <INDENT> print('Outputting Block') <NEW_LINE> print(block) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('-' * 20) <NEW_LINE> <DEDENT> <DEDENT> def listen_for_input(self): <NEW_LINE> <INDENT> waiting_for_input = True <NEW_LINE> while waiting_for_input: <NEW_LINE> <INDENT> print('Please choose!') <NEW_LINE> print('1: Add a new transaction value') <NEW_LINE> print('2: Mine a new block') <NEW_LINE> print('3: Output the blockchain blocks') <NEW_LINE> print('4: Check transaction validity') <NEW_LINE> print('5: Create wallet') <NEW_LINE> print('6: Load wallet') <NEW_LINE> print('7: Save keys') <NEW_LINE> print('q: Quit\n') <NEW_LINE> user_choice = self.get_user_choice() <NEW_LINE> if user_choice == '1': <NEW_LINE> <INDENT> tx_data = self.get_transaction_value() <NEW_LINE> recipient, amount = tx_data <NEW_LINE> signature = self.wallet.sign_transaction(self.wallet.public_key, recipient, amount) <NEW_LINE> if self.blockchain.add_transaction(recipient, self.wallet.public_key, signature, amount=amount): <NEW_LINE> <INDENT> print('Added transaction!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Transaction failed!') <NEW_LINE> <DEDENT> print(self.blockchain.get_open_transactions()) <NEW_LINE> <DEDENT> elif user_choice == '2': <NEW_LINE> <INDENT> if not self.blockchain.mine_block(): <NEW_LINE> <INDENT> print('Mining failed. Got no wallet?') <NEW_LINE> <DEDENT> <DEDENT> elif user_choice == '3': <NEW_LINE> <INDENT> self.print_blockchain_elements() <NEW_LINE> <DEDENT> elif user_choice == '4': <NEW_LINE> <INDENT> if Verification.verify_transactions(self.blockchain.get_open_transactions(), self.blockchain.get_balance): <NEW_LINE> <INDENT> print('All transactions are valid.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('There are invalid transactions.') <NEW_LINE> <DEDENT> <DEDENT> elif user_choice == '5': <NEW_LINE> <INDENT> self.wallet.create_keys() <NEW_LINE> self.blockchain = Blockchain(self.wallet.public_key) <NEW_LINE> <DEDENT> elif user_choice == '6': <NEW_LINE> <INDENT> self.wallet.load_keys() <NEW_LINE> self.blockchain = Blockchain(self.wallet.public_key) <NEW_LINE> <DEDENT> elif user_choice == '7': <NEW_LINE> <INDENT> self.wallet.save_keys() <NEW_LINE> <DEDENT> elif user_choice == 'q': <NEW_LINE> <INDENT> waiting_for_input = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Input was invalid, please pick a value from the list!') <NEW_LINE> <DEDENT> if not Verification.verify_chain(self.blockchain.chain): <NEW_LINE> <INDENT> self.print_blockchain_elements() <NEW_LINE> print('Invalid blockchain!') <NEW_LINE> break <NEW_LINE> <DEDENT> print("{}'s balance: {:6.2f}".format(self.wallet.public_key, self.blockchain.get_balance())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Exit noted!')
The node which runs the local blockchain instance. Attributes: :id: The id of the node. :blockchain: The blockchain which is run by this node.
62598fb84527f215b58ea00b
class PublishingHouse(DataCruncher): <NEW_LINE> <INDENT> ACCEPT_STAGE = 3 <NEW_LINE> def generate_data(self): <NEW_LINE> <INDENT> if self.scoring_team == 'blue': <NEW_LINE> <INDENT> self.game.blue_score += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.game.red_score += 1 <NEW_LINE> <DEDENT> print("red's score " + str(self.game.red_score)) <NEW_LINE> print("blue's score " + str(self.game.blue_score)) <NEW_LINE> <DEDENT> def interact(self, player): <NEW_LINE> <INDENT> if super(PublishingHouse, self)._interact(player, PublishingHouse.ACCEPT_STAGE): <NEW_LINE> <INDENT> self.scoring_team = player.team
Where the player brings the final paper and scores a point
62598fb855399d3f05626648
class SchematicInputTemplateTest(TemplateTestCase): <NEW_LINE> <INDENT> TEMPLATE_NAME = 'schematicinput.html' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(SchematicInputTemplateTest, self).setUp() <NEW_LINE> self.context = { 'id': '1', 'status': Status('correct'), 'previewer': 'dummy.js', 'value': '101', 'STATIC_URL': '/dummy-static/', 'msg': '', 'initial_value': 'two large batteries', 'width': '100', 'height': '100', 'parts': 'resistors, capacitors, and flowers', 'setup_script': '/dummy-static/js/capa/schematicinput.js', 'analyses': 'fast, slow, and pink', 'submit_analyses': 'maybe', } <NEW_LINE> <DEDENT> def test_aria_label(self): <NEW_LINE> <INDENT> self.assert_label(aria_label=True)
Test mako template for `<schematic>` input
62598fb85fdd1c0f98e5e0c4
class SynapseError(Exception): <NEW_LINE> <INDENT> pass
Generic exception thrown by the client.
62598fb8236d856c2adc94da
class RandomForestAttacker(TrainedAttacker): <NEW_LINE> <INDENT> def train_model(self, input_features, is_training_labels): <NEW_LINE> <INDENT> rf_model = ensemble.RandomForestClassifier() <NEW_LINE> param_grid = { 'n_estimators': [100], 'max_features': ['auto', 'sqrt'], 'max_depth': [5, 10, 20, None], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } <NEW_LINE> n_jobs = -1 <NEW_LINE> model = model_selection.GridSearchCV( rf_model, param_grid=param_grid, cv=3, n_jobs=n_jobs, verbose=0) <NEW_LINE> model.fit(input_features, is_training_labels) <NEW_LINE> self.model = model
Random forest attacker.
62598fb8aad79263cf42e909
class TooManyFlushData(Exception): <NEW_LINE> <INDENT> pass
Raise this exception when there are too many data useless
62598fb8fff4ab517ebcd91d
class ClusterTemplatesGeneratorTestCase(test.ScenarioTestCase): <NEW_LINE> <INDENT> def _gen_tenants(self, count): <NEW_LINE> <INDENT> tenants = {} <NEW_LINE> for id_ in range(count): <NEW_LINE> <INDENT> tenants[str(id_)] = dict(name=str(id_)) <NEW_LINE> <DEDENT> return tenants <NEW_LINE> <DEDENT> @mock.patch("%s.magnum.utils.MagnumScenario." "_create_cluster_template" % SCN, return_value=fakes.FakeClusterTemplate(id="uuid")) <NEW_LINE> def test_setup(self, mock__create_cluster_template): <NEW_LINE> <INDENT> tenants_count = 2 <NEW_LINE> users_per_tenant = 5 <NEW_LINE> tenants = self._gen_tenants(tenants_count) <NEW_LINE> users = [] <NEW_LINE> for ten_id in tenants: <NEW_LINE> <INDENT> for i in range(users_per_tenant): <NEW_LINE> <INDENT> users.append({"id": i, "tenant_id": ten_id, "credential": mock.MagicMock()}) <NEW_LINE> <DEDENT> <DEDENT> self.context.update({ "config": { "users": { "tenants": tenants_count, "users_per_tenant": users_per_tenant, "concurrent": 10, }, "cluster_templates": { "dns_nameserver": "8.8.8.8", "external_network_id": "public", "flavor_id": "m1.small", "docker_volume_size": 5, "coe": "kubernetes", "image_id": "fedora-atomic-latest", "network_driver": "flannel" } }, "users": users, "tenants": tenants }) <NEW_LINE> ct_ctx = cluster_templates.ClusterTemplateGenerator(self.context) <NEW_LINE> ct_ctx.setup() <NEW_LINE> ct_ctx_config = self.context["config"]["cluster_templates"] <NEW_LINE> image_id = ct_ctx_config.get("image_id") <NEW_LINE> external_network_id = ct_ctx_config.get( "external_network_id") <NEW_LINE> dns_nameserver = ct_ctx_config.get("dns_nameserver") <NEW_LINE> flavor_id = ct_ctx_config.get("flavor_id") <NEW_LINE> docker_volume_size = ct_ctx_config.get("docker_volume_size") <NEW_LINE> network_driver = ct_ctx_config.get("network_driver") <NEW_LINE> coe = ct_ctx_config.get("coe") <NEW_LINE> mock_calls = [mock.call(image_id=image_id, external_network_id=external_network_id, dns_nameserver=dns_nameserver, flavor_id=flavor_id, docker_volume_size=docker_volume_size, network_driver=network_driver, coe=coe) for i in range(tenants_count)] <NEW_LINE> mock__create_cluster_template.assert_has_calls(mock_calls) <NEW_LINE> for ten_id in self.context["tenants"].keys(): <NEW_LINE> <INDENT> self.assertIsNotNone( self.context["tenants"][ten_id]["cluster_template"]) <NEW_LINE> <DEDENT> <DEDENT> @mock.patch("%s.magnum.cluster_templates.resource_manager.cleanup" % CTX) <NEW_LINE> def test_cleanup(self, mock_cleanup): <NEW_LINE> <INDENT> self.context.update({ "users": mock.MagicMock() }) <NEW_LINE> ct_ctx = cluster_templates.ClusterTemplateGenerator(self.context) <NEW_LINE> ct_ctx.cleanup() <NEW_LINE> mock_cleanup.assert_called_once_with( names=["magnum.cluster_templates"], users=self.context["users"], superclass=magnum_utils.MagnumScenario, task_id=self.context["owner_id"])
Generate tenants.
62598fb863d6d428bbee28e4
@python_2_unicode_compatible <NEW_LINE> class Suggestion(models.Model): <NEW_LINE> <INDENT> STATE_NEW = 0 <NEW_LINE> STATE_IN_PROGRESS = 1 <NEW_LINE> STATE_COMPLETED = 2 <NEW_LINE> STATE_REJECTED = 3 <NEW_LINE> STATE_SPAM = 4 <NEW_LINE> RESOLVED_STATES = (STATE_COMPLETED, STATE_REJECTED) <NEW_LINE> OPEN_STATES = (STATE_NEW, STATE_IN_PROGRESS) <NEW_LINE> STATE_CHOICES = ( (STATE_NEW, _(u'New')), (STATE_IN_PROGRESS, _(u'In progress')), (STATE_COMPLETED, _(u'Completed')), (STATE_REJECTED, _(u'Rejected')), (STATE_SPAM, _(u'Spam')), ) <NEW_LINE> state = models.IntegerField(choices=STATE_CHOICES, default=STATE_NEW) <NEW_LINE> name = models.CharField( max_length=128, help_text=_(u'Name of video/collection of videos'), unique=True) <NEW_LINE> url = models.URLField( max_length=255, help_text=_(u'Link to video/collection of videos'), unique=True) <NEW_LINE> comment = models.TextField( blank=True, help_text=_(u'Additional information, urls, etc (optional)')) <NEW_LINE> whiteboard = models.CharField( max_length=255, blank=True, default=u'', help_text=_(u'Editor notes for this suggestion.')) <NEW_LINE> resolution = models.CharField( max_length=128, blank=True, default=u'', help_text=_(u'Describe how this suggestion was resolved.')) <NEW_LINE> submitted = models.DateTimeField(auto_now_add=True) <NEW_LINE> resolved = models.DateTimeField(blank=True, null=True) <NEW_LINE> is_reviewed = models.BooleanField(default=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta(object): <NEW_LINE> <INDENT> verbose_name = _(u'suggestion') <NEW_LINE> verbose_name_plural = _(u'suggestions') <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.state in Suggestion.RESOLVED_STATES: <NEW_LINE> <INDENT> self.resolved = datetime.now() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resolved = None <NEW_LINE> <DEDENT> super(Suggestion, self).save(*args, **kwargs)
Represents a suggestion for videos to be added to the site.
62598fb856ac1b37e6302321
class Critic: <NEW_LINE> <INDENT> def __init__(self, state_size, action_size): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.build_model() <NEW_LINE> <DEDENT> def build_model(self): <NEW_LINE> <INDENT> states = layers.Input(shape=(self.state_size,), name='states') <NEW_LINE> actions = layers.Input(shape=(self.action_size,), name='actions') <NEW_LINE> net_states = layers.Dense(units=32, activation='relu')(states) <NEW_LINE> net_states = layers.Dense(units=64, activation='relu')(net_states) <NEW_LINE> net_states = layers.Dropout(0.25)(net_states) <NEW_LINE> net_actions = layers.Dense(units=32, activation='relu')(actions) <NEW_LINE> net_actions = layers.Dense(units=64, activation='relu')(net_actions) <NEW_LINE> net_actions = layers.Dropout(0.25)(net_actions) <NEW_LINE> net = layers.Add()([net_states, net_actions]) <NEW_LINE> net = layers.Activation('relu')(net) <NEW_LINE> net = layers.Dense(128, activation="relu")(net) <NEW_LINE> net = layers.Dropout(0.25)(net) <NEW_LINE> net = layers.Dense(256, activation="relu")(net) <NEW_LINE> net = layers.Dropout(0.25)(net) <NEW_LINE> Q_values = layers.Dense(units=1, name='q_values')(net) <NEW_LINE> self.model = models.Model(inputs=[states, actions], outputs=Q_values) <NEW_LINE> optimizer = optimizers.Adam() <NEW_LINE> self.model.compile(optimizer=optimizer, loss='mse') <NEW_LINE> action_gradients = K.gradients(Q_values, actions) <NEW_LINE> self.get_action_gradients = K.function( inputs=[*self.model.input, K.learning_phase()], outputs=action_gradients)
Critic (Value) Model.
62598fb8283ffb24f3cf39b9
class TestVehicleOwner(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testVehicleOwner(self): <NEW_LINE> <INDENT> pass
VehicleOwner unit test stubs
62598fb897e22403b383b03b
class CleanHunts(cronjobs.SystemCronFlow): <NEW_LINE> <INDENT> frequency = rdfvalue.Duration("7d") <NEW_LINE> lifetime = rdfvalue.Duration("6h") <NEW_LINE> @flow.StateHandler() <NEW_LINE> def Start(self): <NEW_LINE> <INDENT> hunts_ttl = config_lib.CONFIG["DataRetention.hunts_ttl"] <NEW_LINE> if not hunts_ttl: <NEW_LINE> <INDENT> self.Log("TTL not set - nothing to do...") <NEW_LINE> return <NEW_LINE> <DEDENT> exception_label = config_lib.CONFIG[ "DataRetention.hunts_ttl_exception_label"] <NEW_LINE> hunts_root = aff4.FACTORY.Open("aff4:/hunts", token=self.token) <NEW_LINE> hunts_urns = list(hunts_root.ListChildren()) <NEW_LINE> urns_to_delete = [] <NEW_LINE> deadline = rdfvalue.RDFDatetime().Now() - hunts_ttl <NEW_LINE> hunts = aff4.FACTORY.MultiOpen(hunts_urns, aff4_type="GRRHunt", token=self.token) <NEW_LINE> for hunt in hunts: <NEW_LINE> <INDENT> if exception_label in hunt.GetLabelsNames(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> runner = hunt.GetRunner() <NEW_LINE> if runner.context.expires < deadline: <NEW_LINE> <INDENT> urns_to_delete.append(hunt.urn) <NEW_LINE> <DEDENT> <DEDENT> aff4.FACTORY.MultiDelete(urns_to_delete, token=self.token)
Cleaner that deletes old hunts.
62598fb866673b3332c30505
class TestTicketIsClose(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ticket1 = TicketFactory.build(status="new") <NEW_LINE> self.ticket2 = TicketFactory.build(status="accepted") <NEW_LINE> self.ticket3 = TicketFactory.build(status="assigned") <NEW_LINE> self.ticket4 = TicketFactory.build(status="reopened") <NEW_LINE> self.ticket5 = TicketFactory.build(status="closed") <NEW_LINE> self.ticket6 = TicketFactory.build(status="duplicate") <NEW_LINE> self.ticket7 = TicketFactory.build(status="split") <NEW_LINE> <DEDENT> def test_ticket_is_closed(self): <NEW_LINE> <INDENT> self.assertFalse(self.ticket1.is_closed()) <NEW_LINE> self.assertFalse(self.ticket2.is_closed()) <NEW_LINE> self.assertFalse(self.ticket3.is_closed()) <NEW_LINE> self.assertFalse(self.ticket4.is_closed()) <NEW_LINE> self.assertTrue(self.ticket5.is_closed()) <NEW_LINE> self.assertTrue(self.ticket6.is_closed()) <NEW_LINE> self.assertTrue(self.ticket7.is_closed()) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass
Verify that the ticket.is_closed method work as expected (returns true for closed, split, and duplicate, but false otherwise).
62598fb82c8b7c6e89bd38fa
class CreateTestDialog(CreateItemDialog): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(CreateTestDialog, self).__init__(parent) <NEW_LINE> self.setWindowTitle(self.tr('New test')) <NEW_LINE> <DEDENT> def _create_form(self): <NEW_LINE> <INDENT> test_id_label = QtGui.QLabel(self.tr('Name'), self) <NEW_LINE> self._test_id_input = QtGui.QLineEdit(self) <NEW_LINE> description_label = QtGui.QLabel(self.tr('Description'), self) <NEW_LINE> self._description_input = QtGui.QPlainTextEdit(self) <NEW_LINE> self.layout().addRow(test_id_label, self._test_id_input) <NEW_LINE> self.layout().addRow(description_label, self._description_input) <NEW_LINE> <DEDENT> def accept(self): <NEW_LINE> <INDENT> self.data = {'test_id': self._test_id_input.text(), 'description': self._description_input.toPlainText()} <NEW_LINE> super(CreateTestDialog, self).accept()
Dialog window used to create a new test.
62598fb8a05bb46b3848a9a1
class itkHardConnectedComponentImageFilterIUC2IUC2(itkImageToImageFilterAPython.itkImageToImageFilterIUC2IUC2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputImageDimension = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_InputImageDimension <NEW_LINE> ImageDimension = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_ImageDimension <NEW_LINE> SameDimensionCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_SameDimensionCheck <NEW_LINE> IntConvertibleToOutputCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_IntConvertibleToOutputCheck <NEW_LINE> UnsignedShortConvertibleToOutputCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_UnsignedShortConvertibleToOutputCheck <NEW_LINE> OutputEqualityComparableCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_OutputEqualityComparableCheck <NEW_LINE> UnsignedCharConvertibleToOutputCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_UnsignedCharConvertibleToOutputCheck <NEW_LINE> OutputIncrementDecrementOperatorsCheck = _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_OutputIncrementDecrementOperatorsCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetObjectSeed(self, *args): <NEW_LINE> <INDENT> return _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_SetObjectSeed(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkHardConnectedComponentImageFilterPython.delete_itkHardConnectedComponentImageFilterIUC2IUC2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkHardConnectedComponentImageFilterPython.itkHardConnectedComponentImageFilterIUC2IUC2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkHardConnectedComponentImageFilterIUC2IUC2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkHardConnectedComponentImageFilterIUC2IUC2 class
62598fb8796e427e5384e8cb
class Wrapper: <NEW_LINE> <INDENT> def __init__(self, backend): <NEW_LINE> <INDENT> self._backend = backend <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._backend = CLOSED <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, t, v, tb): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self._backend, name)
Used to lend a backend without closing the wrapped backend.
62598fb8dc8b845886d536ee
class ExportDataRelation(ModelSQL): <NEW_LINE> <INDENT> _name = 'test.export_data.relation' <NEW_LINE> _description = __doc__ <NEW_LINE> many2many = fields.Many2One('test.export_data', 'Export Data') <NEW_LINE> target = fields.Many2One('test.export_data.target', 'Target')
Export Data Many2Many
62598fb8851cf427c66b83ec
class GRUGenerator(Generator): <NEW_LINE> <INDENT> def __init__(self, encoder=None, vocab_size=1, embedding_size=32, hidden_size=64): <NEW_LINE> <INDENT> logger.info('Overriding class: Generator -> GRUGenerator.') <NEW_LINE> super(GRUGenerator, self).__init__(name='G_gru') <NEW_LINE> self.encoder = encoder <NEW_LINE> self.embedding = Embedding( vocab_size, embedding_size, name='embedding') <NEW_LINE> self.cell = GRUCell(hidden_size, name='gru') <NEW_LINE> self.rnn = RNN(self.cell, name='rnn_layer', return_sequences=True, stateful=True) <NEW_LINE> self.linear = Dense(vocab_size, name='out') <NEW_LINE> logger.info('Class overrided.') <NEW_LINE> <DEDENT> @property <NEW_LINE> def encoder(self): <NEW_LINE> <INDENT> return self._encoder <NEW_LINE> <DEDENT> @encoder.setter <NEW_LINE> def encoder(self, encoder): <NEW_LINE> <INDENT> self._encoder = encoder <NEW_LINE> <DEDENT> def call(self, x): <NEW_LINE> <INDENT> x = self.embedding(x) <NEW_LINE> x = self.rnn(x) <NEW_LINE> x = self.linear(x) <NEW_LINE> return x
A GRUGenerator class is the one in charge of a Gated Recurrent Unit implementation. References: K. Cho, et al. Learning phrase representations using RNN encoder-decoder for statistical machine translation. Preprint arXiv:1406.1078 (2014).
62598fb860cbc95b06364475
class loginZ_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = LoginResult() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = TalkService.ttypes.TalkException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('loginZ_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - e
62598fb8f9cc0f698b1c5368
@urls.register <NEW_LINE> class DSCPMarkingRules(generic.View): <NEW_LINE> <INDENT> url_regex = ( r'neutron/qos/policies/(?P<policy_id>[^/]+)' + r'/dscp_marking_rules/$') <NEW_LINE> @rest_utils.ajax(data_required=True) <NEW_LINE> def post(self, req, policy_id): <NEW_LINE> <INDENT> dscp_marking_rule = api.neutron.dscp_marking_rule_create( req, policy_id, **req.DATA) <NEW_LINE> return rest_utils.CreatedResponse( '/api/neutron/qospolicies/dscpmarkingrules/%s' % dscp_marking_rule.id, dscp_marking_rule.to_dict() )
API for DSCP Marking Rule create
62598fb87047854f4633f50d
class Player(models.Model): <NEW_LINE> <INDENT> created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='creator_of') <NEW_LINE> is_deleted = models.BooleanField( default=False, verbose_name='player is deleted') <NEW_LINE> deleted_at = models.DateTimeField(verbose_name='player was deleted at') <NEW_LINE> user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) <NEW_LINE> email_communication = models.BooleanField( default=True, verbose_name='Would you like to get awesome news from us?') <NEW_LINE> nickname = models.CharField(max_length=255) <NEW_LINE> games = models.ManyToManyField(Game, blank=True) <NEW_LINE> @cached_property <NEW_LINE> def win_count(self): <NEW_LINE> <INDENT> return self.play_set.filter(winner=self).count() <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def play_count(self): <NEW_LINE> <INDENT> return self.play_set.count() <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def game_count(self): <NEW_LINE> <INDENT> return self.games.count() <NEW_LINE> <DEDENT> @property <NEW_LINE> def winrate(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.win_count / self.play_count <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def winpercent(self): <NEW_LINE> <INDENT> return f'{self.winrate*100}' <NEW_LINE> <DEDENT> def get_most_played_game(self): <NEW_LINE> <INDENT> game_total = self.play_set.values('game').annotate( total=Count('game')).order_by('-total').first() <NEW_LINE> game = Game.objects.get(id=game_total['game']) <NEW_LINE> return game <NEW_LINE> <DEDENT> def get_winpercent(self, game: 'Game' = None, player: 'Player' = None): <NEW_LINE> <INDENT> if game and player: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif game: <NEW_LINE> <INDENT> play_count = self.play_set.filter(game=game).count() <NEW_LINE> win_count = self.play_set.filter(winner=self, game=game).count() <NEW_LINE> return win_count / play_count * 100 <NEW_LINE> <DEDENT> elif player: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.winpercent <NEW_LINE> <DEDENT> <DEDENT> def get_played_agains_count(self): <NEW_LINE> <INDENT> my_plays = self.play_set.all() <NEW_LINE> my_plays_ids = [x.id for x in my_plays] <NEW_LINE> players_with_count = Play.players.through.objects.filter( play_id__in=my_plays_ids).values('player_id').annotate( count=Count('player_id')).all() <NEW_LINE> return players_with_count <NEW_LINE> <DEDENT> def get_most_played_player(self): <NEW_LINE> <INDENT> from .play import Play <NEW_LINE> my_plays = self.play_set.all() <NEW_LINE> my_plays_ids = [x.id for x in my_plays] <NEW_LINE> most_played_player_id = Play.players.through.objects.filter( play_id__in=my_plays_ids).exclude( player_id=self.id).values('player_id').annotate( count=Count('player_id')).order_by('-count').first() <NEW_LINE> opponent = Player.objects.get(id=most_played_player_id['player_id']) <NEW_LINE> return opponent <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.nickname <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'Player({self.nickname})'
Someone who plays games
62598fb89c8ee8231304020f
class UnfollowArtistButton(BaseButton): <NEW_LINE> <INDENT> CALLBACK_NAME = 'unfollow_artist' <NEW_LINE> @classmethod <NEW_LINE> def handle(cls, update: Update, context: CallbackContext): <NEW_LINE> <INDENT> query = update.callback_query <NEW_LINE> followed_artist_id = cls.get_callback_data(query.data) <NEW_LINE> if followed_artist_id: <NEW_LINE> <INDENT> SpotifyAPIClient().delete_followed_artist(followed_artist_id) <NEW_LINE> <DEDENT> context.bot.edit_message_reply_markup( chat_id=query.message.chat_id, message_id=query.message.message_id ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_keyboard_markup(cls, followed_artists): <NEW_LINE> <INDENT> keyboard = [] <NEW_LINE> for followed_artist in followed_artists: <NEW_LINE> <INDENT> keyboard.append([InlineKeyboardButton( followed_artist.get('artist').get('name'), callback_data=f'{cls.CALLBACK_NAME}:{followed_artist.get("id")}' )]) <NEW_LINE> <DEDENT> keyboard.append([InlineKeyboardButton( str('Cancel'), callback_data=f'{cls.CALLBACK_NAME}:' )]) <NEW_LINE> return InlineKeyboardMarkup(keyboard)
Defines the UnfollowArtist Button show when calling /unfollowartists command
62598fb8442bda511e95c592
class CalculatorButtons(Buttons): <NEW_LINE> <INDENT> def __init__(self, frame: Frame, action: Action) -> None: <NEW_LINE> <INDENT> import functools <NEW_LINE> @functools.lru_cache() <NEW_LINE> def buttons() -> Iterator[Button]: <NEW_LINE> <INDENT> yield from ( One(frame, action), Two(frame, action), Three(frame, action), Four(frame, action), Five(frame, action), Six(frame, action), Seven(frame, action), Eight(frame, action), Nine(frame, action), Zero(frame, action), Add(frame, action), Subtract(frame, action), Multiply(frame, action), Clear(frame, action), Equals(frame, action), Divide(frame, action), Dot(frame, action), Module(frame, action), Power(frame, action), Pi(frame, action) ) <NEW_LINE> <DEDENT> self._buttons: Callable[..., Iterator[Button]] = buttons <NEW_LINE> <DEDENT> def render(self) -> None: <NEW_LINE> <INDENT> for button in self._buttons(): <NEW_LINE> <INDENT> button.grid() <NEW_LINE> <DEDENT> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return len(tuple(self._buttons()))
Represent calculator buttons facade.
62598fb8956e5f7376df5719
class WordListView(SuperuserRequiredMixin, CommonContextMixin, ListView): <NEW_LINE> <INDENT> model = Word <NEW_LINE> template_name = 'analysis/word_list.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(WordListView, self).get_context_data(**kwargs) <NEW_LINE> context['table_titles'] = [u'目标', u'油性or干性', u'敏感or耐受', u'色素or非色素', u'易皱or紧致', ''] <NEW_LINE> context['table_fields'] = ['purpose', 'oily_type_display', 'sensitive_type_display', 'pigment_type_display', 'loose_type_display', 'id'] <NEW_LINE> return context
List views for Word
62598fb8ec188e330fdf89c8
class PerformanceView(DetailView): <NEW_LINE> <INDENT> model = Performance <NEW_LINE> slug_field = 'slug' <NEW_LINE> template_name = 'performance.html'
Single Performance
62598fb810dbd63aa1c70cf0
class JournalKeys(object): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> with open(self.filename, "r") as fin: <NEW_LINE> <INDENT> for line in fin: <NEW_LINE> <INDENT> fields = line.replace("\n", "").split("\t") <NEW_LINE> keys = fields[0:-1] <NEW_LINE> yield keys
Iterable: on each iteration, return journal keys in a list, one list for each journal. Process one cleaned journal at a time using generators, never load the entire corpus into RAM. Using an iterable so that memory isn't a concern, and Gensim vocabulary and BOW building tools work well with iterables.
62598fb8e1aae11d1e7ce8c0
class ExcelInputInMultiDict(ExcelInput): <NEW_LINE> <INDENT> def get_file_tuple(self, field_name): <NEW_LINE> <INDENT> raise NotImplementedError("Please implement this function") <NEW_LINE> <DEDENT> def get_params(self, field_name=None, **keywords): <NEW_LINE> <INDENT> file_type, file_handle = self.get_file_tuple(field_name) <NEW_LINE> if file_type is not None and file_handle is not None: <NEW_LINE> <INDENT> keywords = { 'file_type': file_type, 'file_content': file_handle.read() } <NEW_LINE> return keywords <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Invalid parameters")
A generic interface for an upload excel file appearing in a dictionary
62598fb8a8370b77170f0516
class ApplyLRT(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "mesh.apply_linked_meshes" <NEW_LINE> bl_label = "Apply LRT with linked meshes" <NEW_LINE> bl_options = {"REGISTER", "UNDO"} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return (context.view_layer.objects.active is not None and context.view_layer.objects.active.type == 'MESH') <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> applyLRTEx(self, context) <NEW_LINE> return {'FINISHED'}
Apply LRT with linked mesh data
62598fb81f5feb6acb162d57
class UpdateUserImageInputSet(InputSet): <NEW_LINE> <INDENT> def set_Response(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('Response', value) <NEW_LINE> <DEDENT> def set_Email(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('Email', value) <NEW_LINE> <DEDENT> def set_ImageURL(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('ImageURL', value) <NEW_LINE> <DEDENT> def set_Password(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('Password', value) <NEW_LINE> <DEDENT> def set_Server(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('Server', value) <NEW_LINE> <DEDENT> def set_UserID(self, value): <NEW_LINE> <INDENT> super(UpdateUserImageInputSet, self)._set_input('UserID', value)
An InputSet with methods appropriate for specifying the inputs to the UpdateUserImage Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fb801c39578d7f12eb2
class Status(six.with_metaclass(abc.ABCMeta)): <NEW_LINE> <INDENT> pass
Describes the status of an RPC. This is an EXPERIMENTAL API. Attributes: code: A StatusCode object to be sent to the client. details: An ASCII-encodable string to be sent to the client upon termination of the RPC. trailing_metadata: The trailing :term:`metadata` in the RPC.
62598fb8cc40096d6161a275
class GitHubUserProvider(NonCachingProvider): <NEW_LINE> <INDENT> def __init__(self, repo, package_manager): <NEW_LINE> <INDENT> self.repo = repo <NEW_LINE> self.package_manager = package_manager <NEW_LINE> <DEDENT> def match_url(self): <NEW_LINE> <INDENT> return re.search('^https?://github.com/[^/]+/?$', self.repo) != None <NEW_LINE> <DEDENT> def get_packages(self): <NEW_LINE> <INDENT> user_match = re.search('^https?://github.com/([^/]+)/?$', self.repo) <NEW_LINE> user = user_match.group(1) <NEW_LINE> api_url = 'https://api.github.com/users/%s/repos?per_page=100' % user <NEW_LINE> repo_info = self.fetch_json(api_url) <NEW_LINE> if repo_info == False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> packages = {} <NEW_LINE> for package_info in repo_info: <NEW_LINE> <INDENT> commit_api_url = ('https://api.github.com/repos/%s/%s/commits' + '?sha=master&per_page=1') % (user, package_info['name']) <NEW_LINE> commit_info = self.fetch_json(commit_api_url) <NEW_LINE> if commit_info == False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> commit_date = commit_info[0]['commit']['committer']['date'] <NEW_LINE> timestamp = datetime.datetime.strptime(commit_date[0:19], '%Y-%m-%dT%H:%M:%S') <NEW_LINE> utc_timestamp = timestamp.strftime( '%Y.%m.%d.%H.%M.%S') <NEW_LINE> homepage = package_info['homepage'] <NEW_LINE> if not homepage: <NEW_LINE> <INDENT> homepage = package_info['html_url'] <NEW_LINE> <DEDENT> package = { 'name': package_info['name'], 'description': package_info['description'] if package_info['description'] else 'No description provided', 'url': homepage, 'author': package_info['owner']['login'], 'last_modified': timestamp.strftime('%Y-%m-%d %H:%M:%S'), 'downloads': [ { 'version': utc_timestamp, 'url': 'https://nodeload.github.com/' + package_info['owner']['login'] + '/' + package_info['name'] + '/zip/master' } ] } <NEW_LINE> packages[package['name']] = package <NEW_LINE> <DEDENT> return packages <NEW_LINE> <DEDENT> def get_renamed_packages(self): <NEW_LINE> <INDENT> return {}
Allows using a GitHub user/organization as the source for multiple packages :param repo: The public web URL to the GitHub user/org. Should be in the format `https://github.com/user`. :param package_manager: An instance of :class:`PackageManager` used to access the API
62598fb8dc8b845886d536f0
class MinetestServiceView(ServiceView): <NEW_LINE> <INDENT> service_id = managed_services[0] <NEW_LINE> diagnostics_module_name = "minetest" <NEW_LINE> description = description <NEW_LINE> show_status_block = True <NEW_LINE> form_class = MinetestForm <NEW_LINE> def get_initial(self): <NEW_LINE> <INDENT> initial = super().get_initial() <NEW_LINE> initial.update(get_configuration()) <NEW_LINE> return initial <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> data = form.cleaned_data <NEW_LINE> old_config = get_configuration() <NEW_LINE> if old_config['max_players'] != data['max_players'] and data['max_players'] != None: <NEW_LINE> <INDENT> actions.superuser_run( 'minetest', ['configure', '--max_players', str(data['max_players'])]) <NEW_LINE> messages.success(self.request, _('Maximum players configuration updated')) <NEW_LINE> <DEDENT> if old_config['creative_mode'] != data['creative_mode']: <NEW_LINE> <INDENT> value = 'true' if data['creative_mode'] else 'false' <NEW_LINE> actions.superuser_run( 'minetest', ['configure', '--creative_mode', value]) <NEW_LINE> messages.success(self.request, _('Creative mode configuration updated')) <NEW_LINE> <DEDENT> if old_config['enable_pvp'] != data['enable_pvp']: <NEW_LINE> <INDENT> value = 'true' if data['enable_pvp'] else 'false' <NEW_LINE> actions.superuser_run( 'minetest', ['configure', '--enable_pvp', value]) <NEW_LINE> messages.success(self.request, _('PVP configuration updated')) <NEW_LINE> <DEDENT> if old_config['enable_damage'] != data['enable_damage']: <NEW_LINE> <INDENT> value = 'true' if data['enable_damage'] else 'false' <NEW_LINE> actions.superuser_run( 'minetest', ['configure', '--enable_damage', value]) <NEW_LINE> messages.success(self.request, _('Damage configuration updated')) <NEW_LINE> <DEDENT> return super().form_valid(form)
A specialized view for configuring minetest.
62598fb892d797404e388bff
class SinopeDimmer(Light): <NEW_LINE> <INDENT> def __init__(self, sinope_data, device_id, name): <NEW_LINE> <INDENT> self.client_name = name <NEW_LINE> self.client = sinope_data.client <NEW_LINE> self.device_id = device_id <NEW_LINE> self.sinope_data = sinope_data <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.sinope_data.update() <NEW_LINE> self._brightness = brightness_from_percentage(float(self.sinope_data.data[self.device_id]["data"]["intensity"])) <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> return SUPPORT_FLAGS <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.client_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> return self._brightness <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._brightness != 0 <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> if kwargs.get(ATTR_BRIGHTNESS): <NEW_LINE> <INDENT> brightness = brightness_to_percentage(int(kwargs.get(ATTR_BRIGHTNESS))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> brightness = 101; <NEW_LINE> <DEDENT> self.client.set_brightness(self.device_id, brightness) <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> brightness = self._brightness <NEW_LINE> if brightness is None or brightness == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.client.set_brightness(self.device_id, 0) <NEW_LINE> <DEDENT> def mode(self): <NEW_LINE> <INDENT> return self._mode
Implementation of a Sinope Device.
62598fb8379a373c97d9914e
class KeyStoreKey(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create(**kwargs): <NEW_LINE> <INDENT> return KeyStoreKey(**kwargs) <NEW_LINE> <DEDENT> def __init__(self, json=None, **kwargs): <NEW_LINE> <INDENT> if json is None and not kwargs: <NEW_LINE> <INDENT> raise ValueError('No data or kwargs present') <NEW_LINE> <DEDENT> class_name = 'KeyStoreKey' <NEW_LINE> data = json or kwargs <NEW_LINE> data_types = [string_types] <NEW_LINE> self.globalid = client_support.set_property('globalid', data, data_types, False, [], False, False, class_name) <NEW_LINE> data_types = [string_types] <NEW_LINE> self.key = client_support.set_property('key', data, data_types, False, [], False, True, class_name) <NEW_LINE> data_types = [KeyData] <NEW_LINE> self.keydata = client_support.set_property('keydata', data, data_types, False, [], False, True, class_name) <NEW_LINE> data_types = [Label] <NEW_LINE> self.label = client_support.set_property('label', data, data_types, False, [], False, True, class_name) <NEW_LINE> data_types = [string_types] <NEW_LINE> self.username = client_support.set_property('username', data, data_types, False, [], False, False, class_name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.as_json(indent=4) <NEW_LINE> <DEDENT> def as_json(self, indent=0): <NEW_LINE> <INDENT> return client_support.to_json(self, indent=indent) <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return client_support.to_dict(self)
auto-generated. don't touch.
62598fb8f548e778e596b6dd
class BlankRecord(BiffRecord): <NEW_LINE> <INDENT> _REC_ID = 0x0201 <NEW_LINE> def __init__(self, row, col, xf_index): <NEW_LINE> <INDENT> self._rec_data = pack('<3H', row, col, xf_index)
This record represents an empty cell. Record BLANK, BIFF5-BIFF8: Offset Size Contents 0 2 Index to row 2 2 Index to first column (fc) 4 2 indexes to XF record
62598fb83539df3088ecc3e5
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class FloatingIpManager(object): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def list_pools(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def list(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get(self, floating_ip_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def allocate(self, pool=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def release(self, floating_ip_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def associate(self, floating_ip_id, port_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def disassociate(self, floating_ip_id, port_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def list_targets(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_target_id_by_instance(self, instance_id, target_list=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def list_target_id_by_instance(self, instance_id, target_list=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def is_simple_associate_supported(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def is_supported(self): <NEW_LINE> <INDENT> pass
Abstract class to implement Floating IP methods The FloatingIP object returned from methods in this class must contains the following attributes: * id: ID of Floating IP * ip: Floating IP address * pool: ID of Floating IP pool from which the address is allocated * fixed_ip: Fixed IP address of a VIF associated with the address * port_id: ID of a VIF associated with the address (instance_id when Nova floating IP is used) * instance_id: Instance ID of an associated with the Floating IP
62598fb8baa26c4b54d4f3f1
class ReportSpec: <NEW_LINE> <INDENT> specs = [] <NEW_LINE> def register_args(self, parser): <NEW_LINE> <INDENT> raise ValueError("not implemented") <NEW_LINE> <DEDENT> def execute(self, api, destination, args): <NEW_LINE> <INDENT> raise ValueError("not implemented") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def register(cls, report_spec): <NEW_LINE> <INDENT> cls.specs.append(report_spec)
Base class for reports
62598fb891f36d47f2230f45
class ContainersManager: <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> self.waiting_containers = [] <NEW_LINE> self.sent_containers = [] <NEW_LINE> self.const_h = None <NEW_LINE> self.min_length = args.get("min_length", 1) <NEW_LINE> self.max_length = args.get("max_length", 40) <NEW_LINE> self.min_width = args.get("min_width", 1) <NEW_LINE> self.max_width = args.get("max_width", 40) <NEW_LINE> self.min_height = args.get("min_height", 1) <NEW_LINE> self.max_height = args.get("max_height", 40) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n\t".join([f"Waiting containers ({len(self.waiting_containers)})"] + [str(x) for x in self.waiting_containers]) + "\n" + "\n\t".join([f"Sent containers ({len(self.sent_containers)})"] + [str(x) for x in self.sent_containers]) <NEW_LINE> <DEDENT> def add(self, x, min_timestamp): <NEW_LINE> <INDENT> if type(min_timestamp) is not int: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> container = Container.from_string(x) <NEW_LINE> if container is not None: <NEW_LINE> <INDENT> check_ok = container.timestamp >= min_timestamp and self.min_length <= container.length <= self.max_length and self.min_width <= container.width <= self.max_width and self.min_height <= container.height <= self.max_height and container.cid not in [x.cid for x in self.waiting_containers + self.sent_containers] <NEW_LINE> if check_ok: <NEW_LINE> <INDENT> if self.const_h is None: <NEW_LINE> <INDENT> self.const_h = container.height <NEW_LINE> self.waiting_containers.append(container) <NEW_LINE> <DEDENT> elif container.height == self.const_h: <NEW_LINE> <INDENT> self.waiting_containers.append(container) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> container = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> container = None <NEW_LINE> <DEDENT> <DEDENT> return container <NEW_LINE> <DEDENT> def send(self, containers): <NEW_LINE> <INDENT> for container in containers: <NEW_LINE> <INDENT> if container in self.waiting_containers: <NEW_LINE> <INDENT> self.waiting_containers.remove(container) <NEW_LINE> self.sent_containers.append(container) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_containers(self, max_timestamp): <NEW_LINE> <INDENT> containers_list = [] <NEW_LINE> for container in self.waiting_containers: <NEW_LINE> <INDENT> if container.timestamp <= max_timestamp: <NEW_LINE> <INDENT> containers_list.append(container) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return containers_list
Class used for storing a list of containers, checking if a container has correct values, and managing information about which containers are waiting for sending and which ones have been already sent.
62598fb855399d3f0562664c
class Circle(CRideModel): <NEW_LINE> <INDENT> name = models.CharField('circle name', max_length=140) <NEW_LINE> slug_name = models.SlugField(unique=True, max_length=40) <NEW_LINE> about = models.CharField('circle description', max_length=255) <NEW_LINE> picture = models.ImageField(upload_to='circles/pictures', blank=True, null=True) <NEW_LINE> members = models.ManyToManyField( 'users.User', through='circles.Membership', through_fields=('circle', 'user') ) <NEW_LINE> rides_offered = models.PositiveIntegerField(default=0) <NEW_LINE> rides_taken = models.PositiveIntegerField(default=0) <NEW_LINE> verified = models.BooleanField( 'verified circle', default=False, help_text='Verified circles are also known as official communities', ) <NEW_LINE> is_public = models.BooleanField( default=True, help_text='Public circles are listed in the main page so everyone know about their existence.' ) <NEW_LINE> is_limited = models.BooleanField( 'limited', default=False, help_text='Limited circles can grow up to a fixed number of members.' ) <NEW_LINE> members_limit = models.PositiveIntegerField( default=0, help_text='If circle is limited, thes will be the limit on the number of members' ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta(CRideModel.Meta): <NEW_LINE> <INDENT> ordering = ['-rides_taken', '-rides_offered']
Circle model. A circle is a private group where rides are offered and taken by its members. To join a circle a user must receive an unique invitation code from an existing circle member.
62598fb856b00c62f0fb29f3
class ClassificationError1ofK(Error): <NEW_LINE> <INDENT> def getError(self, target, predict): <NEW_LINE> <INDENT> assert target.ndim == 2, "targetLayer need to output a matrix but got %d dimensions" % target.ndim <NEW_LINE> error = T.mean(T.neq(T.argmax(predict, axis=1), T.argmax(target, axis=1))) <NEW_LINE> return error
classification error when the target is a one of k vector
62598fb8442bda511e95c594
class ModelServing(object): <NEW_LINE> <INDENT> def __init__(self, app_name='model_serving', args=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parser = ArgParser.model_serving_parser() <NEW_LINE> self.args = parser.parse_args(args) if args else parser.parse_args() <NEW_LINE> self.threaded = self.args.threaded or False <NEW_LINE> self.conf = self.args.conf or "conf/model-serving.json" <NEW_LINE> self.frontend = ModelServingFrontEnd(app_name, self.conf) <NEW_LINE> log_file = self.args.log_file <NEW_LINE> log_level = self.args.log_level or "INFO" <NEW_LINE> log_rotation_time = self.args.log_rotation_time or "1 H" <NEW_LINE> _set_root_logger(log_file, log_level, log_rotation_time) <NEW_LINE> logger.info('Initialized model serving.') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('Failed to initialize model serving: ' + str(e)) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> <DEDENT> def start_model_serving(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._arg_process() <NEW_LINE> self.frontend.start_frontend(self.host, self.port, self.threaded) <NEW_LINE> logger.info('Service started successfully.') <NEW_LINE> logger.info('Service health endpoint: ' + self.host + ':' + str(self.port) + '/ping') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error('Failed to start model serving host: ' + str(e)) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> <DEDENT> def _arg_process(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.port = self.args.port or 8080 <NEW_LINE> self.host = self.args.host or '127.0.0.1' <NEW_LINE> MetricsManager.start(self.args.metrics_write_to, Lock()) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error('Failed to process arguments: ' + str(e)) <NEW_LINE> exit(1)
Model Serving
62598fb863d6d428bbee28e8
class StructuralSectionUserDefined(StructuralSectionRectangular,IDisposable): <NEW_LINE> <INDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseUnmanagedResources(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self,width,height,centroidHorizontal,centroidVertical,principalAxesAngle,sectionArea,perimeter,nominalWeight,momentOfInertiaStrongAxis,momentOfInertiaWeakAxis,elasticModulusStrongAxis,elasticModulusWeakAxis,plasticModulusStrongAxis,plasticModulusWeakAxis,torsionalMomentOfInertia,torsionalModulus,warpingConstant,shearAreaStrongAxis,shearAreaWeakAxis): <NEW_LINE> <INDENT> pass
Defines parameters for parameterized user defined structural section. StructuralSectionUserDefined(width: float,height: float,centroidHorizontal: float,centroidVertical: float,principalAxesAngle: float,sectionArea: float,perimeter: float,nominalWeight: float,momentOfInertiaStrongAxis: float,momentOfInertiaWeakAxis: float,elasticModulusStrongAxis: float,elasticModulusWeakAxis: float,plasticModulusStrongAxis: float,plasticModulusWeakAxis: float,torsionalMomentOfInertia: float,torsionalModulus: float,warpingConstant: float,shearAreaStrongAxis: float,shearAreaWeakAxis: float)
62598fb899cbb53fe6831011
@skipServerTests <NEW_LINE> class UdpTests(ManyTestCasesWithServerMixin, unittest.TestCase): <NEW_LINE> <INDENT> influxdb_udp_enabled = True <NEW_LINE> influxdb_template_conf = os.path.join(THIS_DIR, 'influxdb.conf.template') <NEW_LINE> def test_write_points_udp(self): <NEW_LINE> <INDENT> cli = InfluxDBClient( 'localhost', self.influxd_inst.http_port, 'root', '', database='db', use_udp=True, udp_port=self.influxd_inst.udp_port ) <NEW_LINE> cli.write_points(dummy_point) <NEW_LINE> time.sleep(3) <NEW_LINE> rsp = self.cli.query('SELECT * FROM cpu_load_short') <NEW_LINE> self.assertEqual( [ {'value': 0.64, 'time': '2009-11-10T23:00:00Z', "host": "server01", "region": "us-west"} ], list(rsp['cpu_load_short']) )
Define a class to test UDP series.
62598fb8283ffb24f3cf39bc
class BinaryClassificationPerformance(): <NEW_LINE> <INDENT> def __init__(self, predictions, labels, desc, probabilities=None): <NEW_LINE> <INDENT> self.probabilities = probabilities <NEW_LINE> self.performance_df = pd.concat([pd.DataFrame(predictions), pd.DataFrame(labels)], axis=1) <NEW_LINE> self.performance_df.columns = ['preds', 'labls'] <NEW_LINE> self.desc = desc <NEW_LINE> self.performance_measures = {} <NEW_LINE> self.image_indices = {} <NEW_LINE> <DEDENT> def compute_measures(self): <NEW_LINE> <INDENT> self.performance_measures['Pos'] = self.performance_df['labls'].sum() <NEW_LINE> self.performance_measures['Neg'] = self.performance_df.shape[0] - self.performance_df['labls'].sum() <NEW_LINE> self.performance_measures['TP'] = ((self.performance_df['preds'] == True) & (self.performance_df['labls'] == True)).sum() <NEW_LINE> self.performance_measures['TN'] = ((self.performance_df['preds'] == False) & (self.performance_df['labls'] == False)).sum() <NEW_LINE> self.performance_measures['FP'] = ((self.performance_df['preds'] == True) & (self.performance_df['labls'] == False)).sum() <NEW_LINE> self.performance_measures['FN'] = ((self.performance_df['preds'] == False) & (self.performance_df['labls'] == True)).sum() <NEW_LINE> self.performance_measures['Accuracy'] = (self.performance_measures['TP'] + self.performance_measures['TN']) / (self.performance_measures['Pos'] + self.performance_measures['Neg']) <NEW_LINE> self.performance_measures['Precision'] = self.performance_measures['TP'] / (self.performance_measures['TP'] + self.performance_measures['FP']) <NEW_LINE> self.performance_measures['Recall'] = self.performance_measures['TP'] / self.performance_measures['Pos'] <NEW_LINE> <DEDENT> def img_indices(self): <NEW_LINE> <INDENT> self.performance_df['tp_ind'] = ((self.performance_df['preds'] == True) & (self.performance_df['labls'] == True)) <NEW_LINE> self.performance_df['fp_ind'] = ((self.performance_df['preds'] == True) & (self.performance_df['labls'] == False)) <NEW_LINE> self.image_indices['TP_indices'] = np.where(self.performance_df['tp_ind']==True)[0].tolist() <NEW_LINE> self.image_indices['FP_indices'] = np.where(self.performance_df['fp_ind']==True)[0].tolist()
Performance measures to evaluate the fit of a binary classification model
62598fb87b180e01f3e490ee
class BroadlinkRMSwitch(BroadlinkSwitch): <NEW_LINE> <INDENT> def __init__(self, device, config): <NEW_LINE> <INDENT> super().__init__( device, config.get(CONF_COMMAND_ON), config.get(CONF_COMMAND_OFF) ) <NEW_LINE> self._attr_name = config[CONF_NAME] <NEW_LINE> <DEDENT> async def _async_send_packet(self, packet): <NEW_LINE> <INDENT> if packet is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> await self._device.async_request(self._device.api.send_data, packet) <NEW_LINE> <DEDENT> except (BroadlinkException, OSError) as err: <NEW_LINE> <INDENT> _LOGGER.error("Failed to send packet: %s", err) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
Representation of a Broadlink RM switch.
62598fb876e4537e8c3ef6e0
class Body3(Model): <NEW_LINE> <INDENT> def __init__(self, ciudad: str=None, cantidad: int=None): <NEW_LINE> <INDENT> self.swagger_types = { 'ciudad': str, 'cantidad': int } <NEW_LINE> self.attribute_map = { 'ciudad': 'Ciudad', 'cantidad': 'Cantidad' } <NEW_LINE> self._ciudad = ciudad <NEW_LINE> self._cantidad = cantidad <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'Body3': <NEW_LINE> <INDENT> return deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ciudad(self) -> str: <NEW_LINE> <INDENT> return self._ciudad <NEW_LINE> <DEDENT> @ciudad.setter <NEW_LINE> def ciudad(self, ciudad: str): <NEW_LINE> <INDENT> self._ciudad = ciudad <NEW_LINE> <DEDENT> @property <NEW_LINE> def cantidad(self) -> int: <NEW_LINE> <INDENT> return self._cantidad <NEW_LINE> <DEDENT> @cantidad.setter <NEW_LINE> def cantidad(self, cantidad: int): <NEW_LINE> <INDENT> self._cantidad = cantidad
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fb81f5feb6acb162d59
class ModeratelyArmored(Feature): <NEW_LINE> <INDENT> name = 'Moderately Armored' <NEW_LINE> source = 'Feats'
You have trained to master the use of medium armor and shields, gaining the following benefits: • Increase your Strength or Dexterity score by 1, to a maximum of 20. • You gain proficiency with medium armor and shields. **Prerequisite**: Proficiency with light armor
62598fb8fff4ab517ebcd922
class FileCheckError(Exception): <NEW_LINE> <INDENT> pass
Exception for file checks errors
62598fb823849d37ff8511ed
class PastAuditionListView(ListView): <NEW_LINE> <INDENT> model = Audition <NEW_LINE> template_name = 'auditions/past_list.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> upcoming = Audition.objects.filter_upcoming() <NEW_LINE> return Audition.objects.exclude( id__in=[audition.id for audition in upcoming] ).order_by('-start_date') <NEW_LINE> <DEDENT> def get_context_data(self, *args, **kwargs): <NEW_LINE> <INDENT> context = super(PastAuditionListView, self).get_context_data( *args, **kwargs) <NEW_LINE> auditions = self.get_queryset() <NEW_LINE> paginator = Paginator(auditions, 24) <NEW_LINE> page = self.request.GET.get('page') <NEW_LINE> try: <NEW_LINE> <INDENT> page = paginator.page(page) <NEW_LINE> <DEDENT> except PageNotAnInteger: <NEW_LINE> <INDENT> page = paginator.page(1) <NEW_LINE> <DEDENT> except EmptyPage: <NEW_LINE> <INDENT> page = paginator.page(paginator.num_pages) <NEW_LINE> <DEDENT> context['page'] = page <NEW_LINE> return context
Display all past Audition objects, paginated
62598fb8baa26c4b54d4f3f3
class PhoneValue(ComplexNullValue): <NEW_LINE> <INDENT> native_type = Phone <NEW_LINE> allow_casts = (str, dict) <NEW_LINE> def _convert(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> phone = value['phone'] <NEW_LINE> code = value['countryShortName'] <NEW_LINE> return Phone(phone=phone, code=code) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ColumnValueError('invalid_phone_data', self.id, 'Unable to convert "{}" to Phone value.'.format(value)) <NEW_LINE> <DEDENT> <DEDENT> def _cast(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> phone, code = value.split(' ', 1) <NEW_LINE> return Phone(phone=phone, code=code) <NEW_LINE> <DEDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> phone = value['phone'] <NEW_LINE> code = value['code'] <NEW_LINE> return Phone(phone=phone, code=code) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ColumnValueError('invalid_phone_data', self.id, 'Unable to convert "{}" to Phone value.'.format(value)) <NEW_LINE> <DEDENT> <DEDENT> def _format(self): <NEW_LINE> <INDENT> if (self.value.phone == None) or (self.value.code == None): <NEW_LINE> <INDENT> return COMPLEX_NULL_VALUE <NEW_LINE> <DEDENT> return {'phone': self.value.phone, 'countryShortName': self.value.code}
A phone column value.
62598fb832920d7e50bc6189
class CRP(Algo): <NEW_LINE> <INDENT> def __init__(self, b=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.b = np.array(b) if b is not None else None <NEW_LINE> <DEDENT> def step(self, x, last_b, history): <NEW_LINE> <INDENT> if self.b is None: <NEW_LINE> <INDENT> self.b = np.ones(len(x)) / len(x) <NEW_LINE> <DEDENT> return self.b <NEW_LINE> <DEDENT> def weights(self, X): <NEW_LINE> <INDENT> if self.b is None: <NEW_LINE> <INDENT> b = X * 0 + 1 <NEW_LINE> b.loc[:, "CASH"] = 0 <NEW_LINE> b = b.div(b.sum(axis=1), axis=0) <NEW_LINE> return b <NEW_LINE> <DEDENT> elif self.b.ndim == 1: <NEW_LINE> <INDENT> return np.repeat([self.b], X.shape[0], axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.b <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def plot_crps(cls, data, show_3d=False): <NEW_LINE> <INDENT> def _crp(data): <NEW_LINE> <INDENT> B = list(tools.simplex_mesh(2, 100)) <NEW_LINE> crps = CRP.run_combination(data, b=B) <NEW_LINE> x = [b[0] for b in B] <NEW_LINE> y = [c.total_wealth for c in crps] <NEW_LINE> return x, y <NEW_LINE> <DEDENT> import ternary <NEW_LINE> data = data.dropna(how="any") <NEW_LINE> data = data / data.iloc[0] <NEW_LINE> dim = data.shape[1] <NEW_LINE> if dim == 2 and not show_3d: <NEW_LINE> <INDENT> fig, axes = plt.subplots(ncols=2, sharey=True) <NEW_LINE> data.plot(ax=axes[0], logy=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data.plot(logy=False) <NEW_LINE> <DEDENT> if show_3d: <NEW_LINE> <INDENT> assert dim == 3, "3D plot works for exactly 3 assets." <NEW_LINE> plt.figure() <NEW_LINE> fun = lambda b: CRP(b).run(data).total_wealth <NEW_LINE> ternary.plot_heatmap(fun, steps=20, boundary=True) <NEW_LINE> <DEDENT> elif dim == 2: <NEW_LINE> <INDENT> x, y = _crp(data) <NEW_LINE> s = pd.Series(y, index=x) <NEW_LINE> s.plot(ax=axes[1], logy=True) <NEW_LINE> plt.title("CRP performance") <NEW_LINE> plt.xlabel("weight of {}".format(data.columns[0])) <NEW_LINE> <DEDENT> elif dim > 2: <NEW_LINE> <INDENT> fig, axes = plt.subplots(ncols=dim - 1, nrows=dim - 1) <NEW_LINE> for i in range(dim - 1): <NEW_LINE> <INDENT> for j in range(i + 1, dim): <NEW_LINE> <INDENT> x, y = _crp(data[[i, j]]) <NEW_LINE> ax = axes[i][j - 1] <NEW_LINE> ax.plot(x, y) <NEW_LINE> ax.set_title("{} & {}".format(data.columns[i], data.columns[j])) <NEW_LINE> ax.set_xlabel("weights of {}".format(data.columns[i]))
Constant rebalanced portfolio = use fixed weights all the time. Uniform weights are commonly used as a benchmark. Reference: T. Cover. Universal Portfolios, 1991. http://www-isl.stanford.edu/~cover/papers/paper93.pdf
62598fb84527f215b58ea011
class MultiplexingHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, info_stream=sys.stdout, err_stream=sys.stderr): <NEW_LINE> <INDENT> super(MultiplexingHandler, self).__init__() <NEW_LINE> self.info_handler = logging.StreamHandler(info_stream) <NEW_LINE> self.err_handler = logging.StreamHandler(err_stream) <NEW_LINE> self.multiplex = True <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> handler = self.err_handler if record.levelno > logging.INFO and self.multiplex else self.info_handler <NEW_LINE> handler.emit(record) <NEW_LINE> try: <NEW_LINE> <INDENT> handler.flush() <NEW_LINE> <DEDENT> except BrokenPipeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def flush(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.err_handler.flush() <NEW_LINE> self.info_handler.flush() <NEW_LINE> <DEDENT> except BrokenPipeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.err_handler.close() <NEW_LINE> self.info_handler.close() <NEW_LINE> <DEDENT> def setFormatter(self, fmt): <NEW_LINE> <INDENT> self.err_handler.setFormatter(fmt) <NEW_LINE> self.info_handler.setFormatter(fmt)
handler to send INFO and below to stdout, everything above to stderr
62598fb84c3428357761a3f6
class Baseline(Model): <NEW_LINE> <INDENT> _validation = { 'sensitivity': {'required': True}, 'low_thresholds': {'required': True}, 'high_thresholds': {'required': True}, } <NEW_LINE> _attribute_map = { 'sensitivity': {'key': 'sensitivity', 'type': 'Sensitivity'}, 'low_thresholds': {'key': 'lowThresholds', 'type': '[float]'}, 'high_thresholds': {'key': 'highThresholds', 'type': '[float]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Baseline, self).__init__(**kwargs) <NEW_LINE> self.sensitivity = kwargs.get('sensitivity', None) <NEW_LINE> self.low_thresholds = kwargs.get('low_thresholds', None) <NEW_LINE> self.high_thresholds = kwargs.get('high_thresholds', None)
The baseline values for a single sensitivity value. All required parameters must be populated in order to send to Azure. :param sensitivity: Required. the sensitivity of the baseline. Possible values include: 'Low', 'Medium', 'High' :type sensitivity: str or ~azure.mgmt.monitor.models.Sensitivity :param low_thresholds: Required. The low thresholds of the baseline. :type low_thresholds: list[float] :param high_thresholds: Required. The high thresholds of the baseline. :type high_thresholds: list[float]
62598fb8a219f33f346c6940
class Quotient(Builtin): <NEW_LINE> <INDENT> attributes = ('Listable', 'NumericFunction') <NEW_LINE> messages = { 'infy': 'Infinite expression `1` encountered.', } <NEW_LINE> def apply(self, m, n, evaluation): <NEW_LINE> <INDENT> py_m = m.get_int_value() <NEW_LINE> py_n = n.get_int_value() <NEW_LINE> if py_n == 0: <NEW_LINE> <INDENT> evaluation.message('Quotient', 'infy', Expression('Quotient', m, n)) <NEW_LINE> return Symbol('ComplexInfinity') <NEW_LINE> <DEDENT> return Integer(py_m // py_n)
<dl> <dt>'Quotient[m, n]' <dd>computes the integer quotient of $m$ and $n$. </dl> >> Quotient[23, 7] = 3 #> Quotient[13, 0] : Infinite expression Quotient[13, 0] encountered. = ComplexInfinity #> Quotient[-17, 7] = -3 #> Quotient[-17, -4] = 4 #> Quotient[19, -4] = -5
62598fb8f9cc0f698b1c536a
class UserProfile(models.Model): <NEW_LINE> <INDENT> site_colour = models.CharField(blank=True, null=True, max_length=255) <NEW_LINE> tag_colour = models.CharField(blank=True, null=True, max_length=255) <NEW_LINE> user = models.ForeignKey(User, unique=True) <NEW_LINE> harvest_user = models.CharField(blank=True, max_length=255) <NEW_LINE> harvest_pass = models.CharField(blank=True, max_length=255) <NEW_LINE> home_address = models.TextField(blank=True, null=True) <NEW_LINE> phone_number = models.BigIntegerField(blank=True, null=True) <NEW_LINE> receive_text_alerts = models.BooleanField(default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.user.username
An extension of the user model, allowing for profile information
62598fb8236d856c2adc94dd
class Transaction(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._actions = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> assert self._actions is None <NEW_LINE> self._actions = [] <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> if traceback: <NEW_LINE> <INDENT> self.rollback() <NEW_LINE> <DEDENT> assert self._actions is not None <NEW_LINE> self._actions = None <NEW_LINE> <DEDENT> def on_rollback(self, name, fn, *args, **kwargs): <NEW_LINE> <INDENT> assert callable(fn) <NEW_LINE> self._actions.append((name, fn, args, kwargs)) <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> log.info('Rolling back transaction') <NEW_LINE> while self._actions: <NEW_LINE> <INDENT> name, fn, args, kwargs = self._actions.pop() <NEW_LINE> log.debug('Running rollback action "{}"'.format(name)) <NEW_LINE> try: <NEW_LINE> <INDENT> fn(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> log.warning( 'Rollback action "{}" failed: {}'.format(name, exception) )
Context manager of an igvm action with rollback support Each successful step register a callback to undo its changes. If the transaction fails, all registered callbacks are invoked in LIFO order.
62598fb8aad79263cf42e90f
class FissionXS(MGXS): <NEW_LINE> <INDENT> def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name=''): <NEW_LINE> <INDENT> super(FissionXS, self).__init__(domain, domain_type, groups, by_nuclide, name) <NEW_LINE> self._rxn_type = 'fission' <NEW_LINE> <DEDENT> @property <NEW_LINE> def tallies(self): <NEW_LINE> <INDENT> if self._tallies is None: <NEW_LINE> <INDENT> scores = ['flux', 'fission'] <NEW_LINE> estimator = 'tracklength' <NEW_LINE> keys = scores <NEW_LINE> group_edges = self.energy_groups.group_edges <NEW_LINE> energy_filter = openmc.Filter('energy', group_edges) <NEW_LINE> filters = [[energy_filter], [energy_filter]] <NEW_LINE> self._create_tallies(scores, filters, keys, estimator) <NEW_LINE> <DEDENT> return self._tallies <NEW_LINE> <DEDENT> def compute_xs(self): <NEW_LINE> <INDENT> self._xs_tally = self.tallies['fission'] / self.tallies['flux'] <NEW_LINE> super(FissionXS, self).compute_xs()
A fission multi-group cross section.
62598fb88e7ae83300ee91db
class MinimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> minmaxdepth = 0 <NEW_LINE> agents = 0 <NEW_LINE> def getAction(self, gameState): <NEW_LINE> <INDENT> self.agents = gameState.getNumAgents() <NEW_LINE> self.minmaxdepth = (self.depth*self.agents)-1 <NEW_LINE> actions = gameState.getLegalActions(0) <NEW_LINE> values = [self.minimaxValue(gameState.generateSuccessor(0, action), 1,1) for action in actions] <NEW_LINE> bestValue = max(values) <NEW_LINE> chosenIndex=0 <NEW_LINE> for index in range(len(values)): <NEW_LINE> <INDENT> if values[index] == bestValue: chosenIndex = index <NEW_LINE> <DEDENT> return actions[chosenIndex] <NEW_LINE> <DEDENT> def minimaxValue(self, gameState, currentDepth,ghost): <NEW_LINE> <INDENT> tmpdepth = currentDepth+1 <NEW_LINE> if(currentDepth > self.minmaxdepth): return self.evaluationFunction(gameState) <NEW_LINE> else: <NEW_LINE> <INDENT> if(ghost >= gameState.getNumAgents()): <NEW_LINE> <INDENT> actions = gameState.getLegalActions(0) <NEW_LINE> bestValue = -9999 <NEW_LINE> terminalState = True <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0,action) <NEW_LINE> if(successor != None): <NEW_LINE> <INDENT> terminalState = False <NEW_LINE> bestValue = max(bestValue,self.minimaxValue(successor, tmpdepth,1)) <NEW_LINE> <DEDENT> <DEDENT> if(terminalState): return self.evaluationFunction(gameState) <NEW_LINE> else: return bestValue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bestValue = 9999 <NEW_LINE> actions = gameState.getLegalActions(ghost) <NEW_LINE> terminalState = True <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(ghost,action) <NEW_LINE> if (successor != None): <NEW_LINE> <INDENT> terminalState = False <NEW_LINE> bestValue = min(bestValue, self.minimaxValue(successor, tmpdepth,ghost+1)) <NEW_LINE> <DEDENT> <DEDENT> if(terminalState): return self.evaluationFunction(gameState) <NEW_LINE> else: return bestValue
Your minimax agent (question 2)
62598fb8283ffb24f3cf39be
class StateError(Exception): <NEW_LINE> <INDENT> pass
Error in the state transitions.
62598fb897e22403b383b041
class CorpusSummary(object): <NEW_LINE> <INDENT> def __init__(self, text, separator=Separator(), level='phone', log=utils.null_logger()): <NEW_LINE> <INDENT> if level not in ('phone', 'syllable'): <NEW_LINE> <INDENT> raise ValueError( 'Unknown level {}, must be hone or syllable'.format(level)) <NEW_LINE> <DEDENT> log.info('reading data at %s level', level) <NEW_LINE> self.separator = separator <NEW_LINE> self.summary = Counter() <NEW_LINE> self.lexicon = Counter() <NEW_LINE> self.phrase_initial = Counter() <NEW_LINE> self.phrase_final = Counter() <NEW_LINE> self.internal_diphones = Counter() <NEW_LINE> self.spanning_diphones = Counter() <NEW_LINE> nremoved = 0 <NEW_LINE> for index, utt in enumerate(text): <NEW_LINE> <INDENT> if utt.strip() == '': <NEW_LINE> <INDENT> log.debug('ignoring empty line %d', index+1) <NEW_LINE> nremoved += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if separator.word not in utt: <NEW_LINE> <INDENT> raise ValueError( 'word separator "{}" not found in train text: line {}' .format(separator.word, index + 1)) <NEW_LINE> <DEDENT> self._read_utterance(utt, level) <NEW_LINE> <DEDENT> <DEDENT> self.diphones = Counter(self.internal_diphones) <NEW_LINE> for k, v in self.spanning_diphones.items(): <NEW_LINE> <INDENT> self.diphones.increment(k, v) <NEW_LINE> <DEDENT> if nremoved > 0: <NEW_LINE> <INDENT> log.info('ignored %d empty lines in train text', nremoved) <NEW_LINE> <DEDENT> log.info('train data summary: %s', self.summary) <NEW_LINE> <DEDENT> def _read_utterance(self, utterance, level): <NEW_LINE> <INDENT> if not utterance: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> words = self.separator.tokenize(utterance, 'word') <NEW_LINE> phones = [self.separator.tokenize(word, level) for word in words] <NEW_LINE> self.summary.increment('nlines') <NEW_LINE> self.summary.increment('nwords', len(words)) <NEW_LINE> self.summary.increment('nphones', sum(len(p) for p in phones)) <NEW_LINE> self.phrase_initial.increment((phones[0][0],)) <NEW_LINE> self.phrase_final.increment((phones[-1][-1],)) <NEW_LINE> for i, word in enumerate(words): <NEW_LINE> <INDENT> self.lexicon.increment(word) <NEW_LINE> for j in range(len(phones[i]) - 1): <NEW_LINE> <INDENT> self.internal_diphones.increment( (phones[i][j], phones[i][j+1])) <NEW_LINE> <DEDENT> if i < len(words) - 1: <NEW_LINE> <INDENT> self.spanning_diphones.increment( (phones[i][-1], phones[i+1][0]))
Compute statistics on a phonemized corpus This is the "training" step of DiBS. It computes some statistics on phones (and diphones) on a tokenized training text. Parameters ---------- text : sequence of str The input text must be tokenized at phone and word levels (syllables boundaries are ignored if any) separator : Separator, optional Token separation in the input text level : 'phone' or 'syllable', optional The token level to train the model on. Default to 'phone'. log : logging.Logger, optional Where to send log messages Attributes ---------- summary : Counter Basic stats on the entire text: 'nlines', 'nwords' and 'nphones' lexicon : Counter Word count on the entire text phrase_initial : Counter The phones at first position in an utterance phrase_final : Counter The phones at last position in an utterance internal_diphones : Counter The count of within word diphones spanning_diphones : Counter The count of across words diphones diphones : Counter The count of all diphones, sum of internal and spanning diphones. Raises ------ ValueError if a line in the `text` does not contain a word separator.
62598fb810dbd63aa1c70cf4
class box_GUI(shape_GUI): <NEW_LINE> <INDENT> def __init__(self, gui, pt1, pt2, layer='gx_objects', subplot=None, name=None, select= True): <NEW_LINE> <INDENT> shape_GUI.__init__(self, gui, pt1, pt2, layer='gx_objects', subplot=subplot, name= name) <NEW_LINE> if select: <NEW_LINE> <INDENT> self.gui.set_selected_object(self, figure= self.gui.plotter.currFig) <NEW_LINE> print("Created box and moved to currently selected object") <NEW_LINE> <DEDENT> self.gui.plotter.add_obj(np.array([[self.x1, self.y1],[self.dx, self.dy]]), mpl.patches.Rectangle, layer=layer, subplot=subplot, style= None, name=self.name, force= True, display= True) <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.extra_events == []: <NEW_LINE> <INDENT> ev_str = '(no event)' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ev_str = '(with event)' <NEW_LINE> <DEDENT> return "box_GUI(%.3f, %.3f, %.3f, %.3f) - '%s' %s" %(self.x1, self.y1, self.x2, self.y2, self.name, ev_str) <NEW_LINE> <DEDENT> def pin_contents(self, traj, coorddict): <NEW_LINE> <INDENT> for var, params in coorddict.items(): <NEW_LINE> <INDENT> pts = traj.sample(tlo= self.x1, thi= self.x1 + self.dx) <NEW_LINE> pts[params['x']] = pts[params['x']] - self.x1 <NEW_LINE> xs = pts[params['x']] <NEW_LINE> ys = pts[var] <NEW_LINE> self.gui.plotter.add_data([xs, ys], layer= params['layer'], name= params['name'], style = params['style'], traj= pts, force= True) <NEW_LINE> <DEDENT> <DEDENT> def order_points(self, x1, x2, y1, y2): <NEW_LINE> <INDENT> if x1 > x2: <NEW_LINE> <INDENT> xt = x1 <NEW_LINE> x1 = x2 <NEW_LINE> x2 = xt <NEW_LINE> <DEDENT> if y1 > y2: <NEW_LINE> <INDENT> yt = y1 <NEW_LINE> y1 = y2 <NEW_LINE> y2 = yt <NEW_LINE> <DEDENT> return [x1, x2, y1, y2]
Box of interest context_object for GUI
62598fb88a43f66fc4bf22b6
class SparvTextCorpus(gensim.corpora.TextCorpus): <NEW_LINE> <INDENT> def __init__(self, stream, prune_at=2000000): <NEW_LINE> <INDENT> self.dictionary = None <NEW_LINE> self.reader = stream <NEW_LINE> self.document_length = [] <NEW_LINE> self.corpus_documents = [] <NEW_LINE> self.prune_at = prune_at <NEW_LINE> super(SparvTextCorpus, self).__init__(input=True) <NEW_LINE> <DEDENT> def init_dictionary(self, dictionary): <NEW_LINE> <INDENT> self.dictionary = gensim.corpora.Dictionary(self.get_texts(), prune_at=self.prune_at) <NEW_LINE> if (len(self.dictionary) > 0): <NEW_LINE> <INDENT> _ = self.dictionary[0] <NEW_LINE> <DEDENT> <DEDENT> def getstream(self): <NEW_LINE> <INDENT> corpus_documents = [] <NEW_LINE> document_length = [] <NEW_LINE> for document_name, document in self.reader: <NEW_LINE> <INDENT> corpus_documents.append(document_name) <NEW_LINE> document_length.append(len(document)) <NEW_LINE> yield document <NEW_LINE> <DEDENT> self.document_length = document_length <NEW_LINE> self.corpus_documents = corpus_documents <NEW_LINE> <DEDENT> def get_texts(self): <NEW_LINE> <INDENT> for document in self.getstream(): <NEW_LINE> <INDENT> yield document <NEW_LINE> <DEDENT> <DEDENT> def get_total_word_count(self): <NEW_LINE> <INDENT> total_word_count = { word_id: 0 for word_id in self.dictionary.keys() } <NEW_LINE> for word_id, word_count in itertools.chain.from_iterable(self): <NEW_LINE> <INDENT> total_word_count[word_id] += word_count <NEW_LINE> <DEDENT> sorted_word_count = sorted(total_word_count, key=lambda w: w[1], reverse=True) <NEW_LINE> return sorted_word_count <NEW_LINE> <DEDENT> def get_corpus_documents(self, attrib_extractors=None): <NEW_LINE> <INDENT> attrib_extractors = attrib_extractors or [] <NEW_LINE> if len(self.corpus_documents) == 0: <NEW_LINE> <INDENT> for _ in self.getstream(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> print(self.corpus_documents) <NEW_LINE> document_ids, document_names = list(zip(*( (document_id, document) for document_id, document in enumerate(self.corpus_documents) ))) <NEW_LINE> data = dict( document_id=document_ids, document=document_names, length=self.document_length ) <NEW_LINE> for (n, f) in attrib_extractors: <NEW_LINE> <INDENT> data[n] = [ f(x) for x in document_names ] <NEW_LINE> <DEDENT> return data
This is a BOW vector corpus based on gensim.corpora.TextCorpus
62598fb8d486a94d0ba2c109
class ServiceResponse(object): <NEW_LINE> <INDENT> def __init__(self, response_data, request_fulfilled, **kwargs): <NEW_LINE> <INDENT> self.extra_headers = {} <NEW_LINE> self.response_data = response_data <NEW_LINE> self.request_fulfilled = request_fulfilled <NEW_LINE> self.extra_params = kwargs <NEW_LINE> <DEDENT> def render_to_http_response(self, service_request): <NEW_LINE> <INDENT> response_format = 'json' <NEW_LINE> if response_format == 'json': <NEW_LINE> <INDENT> return json_response(self.response_data, headers=self.extra_headers, status=self.extra_params.get('status_code', 200)) <NEW_LINE> <DEDENT> raise NotImplementedError("Format is not supported") <NEW_LINE> <DEDENT> def add_header(self, name, value): <NEW_LINE> <INDENT> self.extra_headers[name] = value
The general idea is the same as for ServiceRequest. ServiceResponse is a abstraction for request handling which could be represented as HTTP/other response in different formats. ServiceResponse always contains a result of calling service. It's not a general purpose response, e.g. errors are handled with exceptions.
62598fb87d847024c075c4f8
class HHLayer: <NEW_LINE> <INDENT> def __init__(self, n): <NEW_LINE> <INDENT> self.N = n <NEW_LINE> self.gNa = np.zeros(n) <NEW_LINE> self.gK = np.zeros(n) <NEW_LINE> self.gL = np.zeros(n) <NEW_LINE> self.ENa = np.zeros(n) <NEW_LINE> self.EK = np.zeros(n) <NEW_LINE> self.EL = np.zeros(n) <NEW_LINE> self.C = np.zeros(n) <NEW_LINE> self.Ik = np.zeros(n) <NEW_LINE> self.m = np.zeros(n) <NEW_LINE> self.n = np.zeros(n) <NEW_LINE> self.h = np.zeros(n) <NEW_LINE> self.alpham = np.zeros(n) <NEW_LINE> self.alphan = np.zeros(n) <NEW_LINE> self.alphah = np.zeros(n) <NEW_LINE> self.betam = np.zeros(n) <NEW_LINE> self.betan = np.zeros(n) <NEW_LINE> self.betah = np.zeros(n) <NEW_LINE> self.S = {} <NEW_LINE> self.delay = {} <NEW_LINE> self.factor = {}
Layer of Hodgkin Huxley neurons to be used inside a HHNetwork.
62598fb866656f66f7d5a52e
class AgendaFilter(Filter): <NEW_LINE> <INDENT> grok.implements(IAgendaFilter) <NEW_LINE> meta_type = "Silva Agenda Filter" <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> silvaconf.icon("www/agenda_filter.png") <NEW_LINE> silvaconf.priority(3.4) <NEW_LINE> security.declarePrivate('get_allowed_types') <NEW_LINE> def get_allowed_types(self): <NEW_LINE> <INDENT> return {'requires': [IAgendaItemContentVersion,]}
To enable editors to channel newsitems on a site, all items are passed from NewsFolder to NewsViewer through filters. On a filter you can choose which NewsFolders you want to channel items for and filter the items on several criteria (as well as individually).
62598fb823849d37ff8511ef
@attr.s(auto_attribs=True, frozen=True) <NEW_LINE> class Class(Node): <NEW_LINE> <INDENT> name: Name <NEW_LINE> funcs: Dict[Name, Function] <NEW_LINE> assignments: List[Assign]
A class definition. Example ------- .. code-block:: python class MyClass: x = 2 def return_x(): return x Here :code:`name` is :code:`MyClass`, :code:`funcs["return_x"]` is :code:`def return_x(): return x`, and :code:`assignments[0]` is :code:`x = 2`.
62598fb8377c676e912f6e0d
class LocalResourceAnchor (pyxb.binding.datatypes.ID): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'LocalResourceAnchor') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/20110630/ddex.xsd', 1138, 4) <NEW_LINE> _Documentation = 'A LocalAnchor which acts as a local Identifier of a Resource. This\n LocalAnchor is a string starting with the letter A.'
A LocalAnchor which acts as a local Identifier of a Resource. This LocalAnchor is a string starting with the letter A.
62598fb8aad79263cf42e910
class QuandlSettings(): <NEW_LINE> <INDENT> def __init__(self, rows, column, frequency="weekly", transformation="normalize", order="desc"): <NEW_LINE> <INDENT> self.rows = rows <NEW_LINE> self.column = column <NEW_LINE> self.frequency = frequency <NEW_LINE> self.transformation = transformation <NEW_LINE> self.order = order <NEW_LINE> pass
This class contains settings for the quandl integration package, settings include,
62598fb85fcc89381b2661ea
class Comment(handlers.Handler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> count = self.request.get("count") <NEW_LINE> if (count): <NEW_LINE> <INDENT> count = int(count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = 100 <NEW_LINE> <DEDENT> page = self.request.get("page") <NEW_LINE> if (page): <NEW_LINE> <INDENT> page = int(page) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page = 1 <NEW_LINE> <DEDENT> user = google.appengine.api.users.User(self.request.get("user")) <NEW_LINE> if (user): <NEW_LINE> <INDENT> comments = db.Comment().fetchByUser(user, page, count) <NEW_LINE> if (comments): <NEW_LINE> <INDENT> result = [comment.toDictionary() for comment in comments] <NEW_LINE> <DEDENT> <DEDENT> self.respondWithDictionaryAsJSON({"result": result}) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> pass
Provides web service methods that handle requests to /api/comment.
62598fb85fdd1c0f98e5e0cb
class NetworkF(NetworkBase): <NEW_LINE> <INDENT> def computeobserved(self): <NEW_LINE> <INDENT> self.fsim = self.ntw.simulate_observations(self.npts) <NEW_LINE> nearest = np.nanmin(self.ntw.allneighbordistances(self.fsim, self.pointpattern), axis=1) <NEW_LINE> self.setbounds(nearest) <NEW_LINE> observedx, observedy = ffunction(nearest, self.lowerbound, self.upperbound, nsteps=self.nsteps, npts=self.npts) <NEW_LINE> self.observed = observedy <NEW_LINE> self.xaxis = observedx <NEW_LINE> <DEDENT> def computepermutations(self): <NEW_LINE> <INDENT> for p in xrange(self.permutations): <NEW_LINE> <INDENT> sim = self.ntw.simulate_observations(self.npts, distribution=self.distribution) <NEW_LINE> nearest = np.nanmin(self.ntw.allneighbordistances(sim, self.fsim), axis=1) <NEW_LINE> simx, simy = ffunction(nearest, self.lowerbound, self.upperbound, self.npts, nsteps=self.nsteps) <NEW_LINE> self.sim[p] = simy
Network constrained F Function This requires the capability to compute a distance matrix between two point patterns. In this case one will be observed and one will be simulated
62598fb8bf627c535bcb15e0
class AccountsWidget(forms.MultiWidget): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> widgets = [LabelSelect(label=c[0]) for c in CATEGORY_CHOICES] <NEW_LINE> kwargs['widgets'] = widgets <NEW_LINE> super(AccountsWidget, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> return [0]*len(CATEGORY_CHOICES)
Widget for selecting Account values
62598fb85166f23b2e243519
class FBGlobalLight (FBBox): <NEW_LINE> <INDENT> AmbientColor=property(doc="<b>Read Write Property:</b> Ambient light color. ") <NEW_LINE> FogBegin=property(doc="<b>Read Write Property:</b> Begin fog distance. ") <NEW_LINE> FogColor=property(doc="<b>Read Write Property:</b> Fog color. ") <NEW_LINE> FogDensity=property(doc="<b>Read Write Property:</b> Fog density. ") <NEW_LINE> FogEnable=property(doc="<b>Read Write Property:</b> Enable fog? ") <NEW_LINE> FogEnd=property(doc="<b>Read Write Property:</b> End fog distance. ") <NEW_LINE> FogMode=property(doc="<b>Read Write Property:</b> Fog falloff mode. ") <NEW_LINE> pass
Global light class.
62598fb867a9b606de54610f
class MyTopo( Topo ): <NEW_LINE> <INDENT> def __init__( self ): <NEW_LINE> <INDENT> Topo.__init__( self ) <NEW_LINE> h1 = self.addHost('h1', mac='00:00:00:00:00:01', ip='10.0.0.1') <NEW_LINE> h2 = self.addHost('h2', mac='00:00:00:00:00:02', ip='10.0.0.2') <NEW_LINE> h3 = self.addHost('h3', mac='00:00:00:00:00:03', ip='10.0.0.3') <NEW_LINE> h4 = self.addHost('h4', mac='00:00:00:00:00:04', ip='10.0.0.4') <NEW_LINE> s1 = self.addSwitch('s1') <NEW_LINE> s2 = self.addSwitch('s2') <NEW_LINE> s3 = self.addSwitch('s3') <NEW_LINE> s4 = self.addSwitch('s4') <NEW_LINE> s5 = self.addSwitch('s5') <NEW_LINE> s6 = self.addSwitch('s6') <NEW_LINE> s7 = self.addSwitch('s7') <NEW_LINE> s8 = self.addSwitch('s8') <NEW_LINE> self.addLink(h1, s1) <NEW_LINE> self.addLink(h2, s7) <NEW_LINE> self.addLink(h3, s8) <NEW_LINE> self.addLink(h4, s4) <NEW_LINE> self.addLink(s1, s2) <NEW_LINE> self.addLink(s2, s3) <NEW_LINE> self.addLink(s2, s5) <NEW_LINE> self.addLink(s2, s6) <NEW_LINE> self.addLink(s3, s4) <NEW_LINE> self.addLink(s3, s6) <NEW_LINE> self.addLink(s5, s6) <NEW_LINE> self.addLink(s5, s7) <NEW_LINE> self.addLink(s6, s8)
Simple topology example.
62598fb87d43ff24874274a2
class TestGetContactCampaignStatsOpened(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testGetContactCampaignStatsOpened(self): <NEW_LINE> <INDENT> pass
GetContactCampaignStatsOpened unit test stubs
62598fb897e22403b383b043
class TestDegreeStyle(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDegreeStyle(self): <NEW_LINE> <INDENT> pass
DegreeStyle unit test stubs
62598fb87b180e01f3e490f0
class TestGetUri(unittest.TestCase): <NEW_LINE> <INDENT> def testFileName(self): <NEW_LINE> <INDENT> self.source = samples["sweep.wav"] <NEW_LINE> self.uri = path2uri(os.path.abspath(self.source)) <NEW_LINE> <DEDENT> def testUri(self): <NEW_LINE> <INDENT> self.uri = 'file://already/an/uri/file.wav' <NEW_LINE> self.source = self.uri <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.assertEqual(self.uri, get_uri(self.source))
Test get_uri function
62598fb8ec188e330fdf89ce
class GwyEllipseSelection_cdata(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.point_pairs = [((0., 0.), (1., 1.)), ((2., 2.), (3., 3.))] <NEW_LINE> self.cdata = ffi.cast("double*", ffi.new("double[]", [0., 0., 1., 1., 2., 2., 3., 3.])) <NEW_LINE> self.ellipsesel = GwyEllipseSelection(point_pairs=self.point_pairs) <NEW_LINE> <DEDENT> def test_return_None_if_data_list_is_empty(self): <NEW_LINE> <INDENT> self.ellipsesel.data = [] <NEW_LINE> cdata = self.ellipsesel._cdata <NEW_LINE> self.assertIsNone(cdata) <NEW_LINE> <DEDENT> def test_return_value_if_data_list_is_not_empty(self): <NEW_LINE> <INDENT> cdata = self.ellipsesel._cdata <NEW_LINE> self.assertAlmostEqual(cdata, self.cdata)
Test _cdata property of GwyEllipseSelection class
62598fb866673b3332c3050d
class RWhisker(RPackage): <NEW_LINE> <INDENT> homepage = "http://github.com/edwindj/whisker" <NEW_LINE> url = "https://cran.r-project.org/src/contrib/whisker_0.3-2.tar.gz" <NEW_LINE> list_url = "https://cran.r-project.org/src/contrib/Archive/whisker" <NEW_LINE> version('0.3-2', 'c4b9bf9a22e69ce003fe68663ab5e8e6')
logicless templating, reuse templates in many programming languages including R
62598fb87c178a314d78d5dc