code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Tag(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=20, blank=False, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.id) +":"+self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "Tags" | This is a tag for user submitted post entries. | 6259906fd268445f2663a7a7 |
class ShadowBox(Camera): <NEW_LINE> <INDENT> def __init__(self, fratio=0.5, distorted=False): <NEW_LINE> <INDENT> self.stages = [] <NEW_LINE> D = 12. <NEW_LINE> res = 0.1 <NEW_LINE> transmitter = OpticalSurface(D, res) <NEW_LINE> f = fratio * D <NEW_LINE> if distorted: <NEW_LINE> <INDENT> transmitter.distort_randomly() <NEW_LINE> <DEDENT> detector = OpticalSurface(0.75 * D, 2. * res, square=True) <NEW_LINE> detector.shift(f) <NEW_LINE> detector.x[:,0] += 0.5 * detector.D <NEW_LINE> detector.x[:,1] += 0.5 * detector.D <NEW_LINE> self.stages.append(CameraStage(transmitter, detector)) <NEW_LINE> return None | ## class `ShadowBox`:
A particular kind of `Camera` that is a circular aperture in a
screen! It is illuminated by a perfect plane wave (for now).
# initialization input:
* `fratio`: F ratio of the primary optics (default 4).
* `distorted`: If `True`, apply random distortions. | 6259906f32920d7e50bc78db |
class SoftmaxWithXEntropy(OutputLayer): <NEW_LINE> <INDENT> def __init__(self, n_units, n_in, *args, **kwargs): <NEW_LINE> <INDENT> super(SoftmaxWithXEntropy, self).__init__(n_units, n_in, *args, **kwargs) <NEW_LINE> <DEDENT> def calculate_layer_gradients(self, *args, **kwargs): <NEW_LINE> <INDENT> y = kwargs.get('y', None) <NEW_LINE> dLdZ = self.A-y <NEW_LINE> dZdW = self.A_l_1 <NEW_LINE> dJdW = np.dot(dLdZ, dZdW.T) / dLdZ.shape[1] <NEW_LINE> dJdb = np.sum(dLdZ, axis=1, keepdims=True) / dLdZ.shape[1] <NEW_LINE> dZdA_1 = self.W <NEW_LINE> dLdA_1 = np.dot(dZdA_1.T, dLdZ) <NEW_LINE> return dLdA_1, dJdW, dJdb | Calculating exponentials and logarithmics are computationally expensive. As we can see from the previous 2 parts,
the softmax layer is raising the logit scores to exponential in order to get probability vectors, and then the loss
function is doing the log to calculate the entropy of the loss.
If we combine these 2 stages in one layer, logarithmics and exponentials kind of cancel out each others, and we can
get the same final result with much less computational resources. That’s why in many neural network frameworks and
libraries there is a “softmax-log-loss” function, which is much more optimal than having the 2 functions separated | 6259906f091ae356687064ca |
class GoalKeeper(Tactic): <NEW_LINE> <INDENT> def __init__(self, p_info_manager, p_player_id, p_is_yellow=False): <NEW_LINE> <INDENT> Tactic.__init__(self, p_info_manager) <NEW_LINE> assert isinstance(p_player_id, int) <NEW_LINE> assert PLAYER_PER_TEAM >= p_player_id >= 0 <NEW_LINE> assert isinstance(p_is_yellow, bool) <NEW_LINE> self.player_id = p_player_id <NEW_LINE> self.is_yellow = p_is_yellow <NEW_LINE> self.current_state = self.protect_goal <NEW_LINE> self.next_state = self.protect_goal <NEW_LINE> self.status_flag = tactic_constants.WIP <NEW_LINE> <DEDENT> def protect_goal(self): <NEW_LINE> <INDENT> if not isInsideGoalArea(self.info_manager.get_ball_position(), self.is_yellow): <NEW_LINE> <INDENT> self.next_state = self.protect_goal <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if player_can_grab_ball(self.info_manager, self.player_id): <NEW_LINE> <INDENT> self.next_state = self.grab_ball <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.next_state = self.go_behind_ball <NEW_LINE> <DEDENT> <DEDENT> self.target = Pose(self.info_manager.get_ball_position()) <NEW_LINE> return ProtectGoal(self.info_manager, self.player_id, self.is_yellow, p_minimum_distance=300) <NEW_LINE> <DEDENT> def go_behind_ball(self): <NEW_LINE> <INDENT> ball_position = self.info_manager.get_ball_position() <NEW_LINE> if player_can_grab_ball(self.info_manager, self.player_id): <NEW_LINE> <INDENT> self.next_state = self.grab_ball <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.next_state = self.go_behind_ball <NEW_LINE> <DEDENT> return GoBehind(self.info_manager, self.player_id, ball_position, Position(0, 0), DISTANCE_BEHIND) <NEW_LINE> <DEDENT> def grab_ball(self): <NEW_LINE> <INDENT> if player_grabbed_ball(self.info_manager, self.player_id): <NEW_LINE> <INDENT> self.next_state = self.halt <NEW_LINE> self.status_flag = tactic_constants.SUCCESS <NEW_LINE> <DEDENT> elif player_can_grab_ball(self.info_manager, self.player_id): <NEW_LINE> <INDENT> self.next_state = self.grab_ball <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.next_state = self.go_behind_ball <NEW_LINE> <DEDENT> return GrabBall(self.info_manager, self.player_id) | Tactique du gardien de but standard. Le gardien doit se placer entre la balle et le but, tout en restant à
l'intérieur de son demi-cercle. Si la balle entre dans son demi-cercle, le gardien tente d'aller en prendre
possession. Il s'agit d'une version simple, mais fonctionelle du gardien. Peut être améliorer.
méthodes:
exec(self) : Exécute une Action selon l'état courant
attributs:
info_manager: référence à la façade InfoManager
player_id : Identifiant du gardien de but
current_state : L'état courant de la tactique
next_state : L'état suivant de la tactique
status_flag : L'indicateur de progression de la tactique
is_yellow : un booléen indiquant si le gardien est dans l'équipe des jaunes, ce qui détermine quel but est
protégé. Les jaunes protègent le but de droite et les bleus, le but de gauche. | 6259906f63b5f9789fe869f8 |
class RandomCrop(object): <NEW_LINE> <INDENT> def __init__(self, size, padding=0): <NEW_LINE> <INDENT> if isinstance(size, numbers.Number): <NEW_LINE> <INDENT> self.size = (int(size), int(size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> self.padding = padding <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_params(img, output_size): <NEW_LINE> <INDENT> w, h = img.size <NEW_LINE> th, tw = output_size <NEW_LINE> if w == tw and h == th: <NEW_LINE> <INDENT> return 0, 0, h, w <NEW_LINE> <DEDENT> i = random.randint(0, h - th) <NEW_LINE> j = random.randint(0, w - tw) <NEW_LINE> return i, j, th, tw <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> if self.padding > 0: <NEW_LINE> <INDENT> img = F.pad(img, self.padding) <NEW_LINE> <DEDENT> i, j, h, w = self.get_params(img, self.size) <NEW_LINE> return F.crop(img, i, j, h, w) | Crop the given PIL Image at a random location.
Args:
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made.
padding (int or sequence, optional): Optional padding on each border
of the image. Default is 0, i.e no padding. If a sequence of length
4 is provided, it is used to pad left, top, right, bottom borders
respectively. | 6259906fec188e330fdfa137 |
class TestDestinyDefinitionsDestinyActivityModifierReferenceDefinition(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 testDestinyDefinitionsDestinyActivityModifierReferenceDefinition(self): <NEW_LINE> <INDENT> pass | DestinyDefinitionsDestinyActivityModifierReferenceDefinition unit test stubs | 6259906f32920d7e50bc78dc |
class Mahasiswa(object): <NEW_LINE> <INDENT> def __init__(self, nama, nim, kota,us): <NEW_LINE> <INDENT> self.nama = nama <NEW_LINE> self.NIM = nim <NEW_LINE> self.kotaTinggal = kota <NEW_LINE> self.uangSaku = us <NEW_LINE> self.listKuliah = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = self.nama + ',NIM '+ str(self.nim) + '. Tinggal di ' + self.kotaTinggal + '. Uang saku Rp ' + str(self.uangSaku) + ' tiap bulannya.' <NEW_LINE> return s <NEW_LINE> <DEDENT> def ambilNama(self): <NEW_LINE> <INDENT> return self.nama <NEW_LINE> <DEDENT> def ambilNIM(self): <NEW_LINE> <INDENT> return self.NIM <NEW_LINE> <DEDENT> def ambilUangSaku(self): <NEW_LINE> <INDENT> return self.uangSaku <NEW_LINE> <DEDENT> def makan(self,s): <NEW_LINE> <INDENT> print("Saya baru saja makan",s," Sambil velajar.") <NEW_LINE> self.keadaan= "kenyang" <NEW_LINE> <DEDENT> def ambilKuliah(self, kuliah): <NEW_LINE> <INDENT> self.listKuliah.append(kuliah) <NEW_LINE> return self.listKuliah <NEW_LINE> <DEDENT> def hapusKuliah(self, delete): <NEW_LINE> <INDENT> self.listKuliah.remove(delete) | Class mahasiswa dengan berbagai metode | 6259906fadb09d7d5dc0be00 |
class TkMenu(tk.Menu, TkWidgetSimple): <NEW_LINE> <INDENT> def __init__(self, master, *args, **kw): <NEW_LINE> <INDENT> tk.Menu.__init__(self, master) <NEW_LINE> TkWidgetSimple.__init__(self, master, *args, **kw) | Extends tk.Menu and TkWidgetSimple.
This Object is an Extension of the Tkinter Menu Widget which is
needed to make it possible to build a GUI with XML Definitions. | 6259906f01c39578d7f1437f |
class UniqueSettingsTests(TestCase): <NEW_LINE> <INDENT> settings_module = settings <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self._installed_apps = self.settings_module.INSTALLED_APPS <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.settings_module.INSTALLED_APPS = self._installed_apps <NEW_LINE> <DEDENT> def test_unique(self): <NEW_LINE> <INDENT> with self.assertRaises(ImproperlyConfigured): <NEW_LINE> <INDENT> self.settings_module.INSTALLED_APPS = ("myApp1", "myApp1", "myApp2", "myApp3") | Tests for the INSTALLED_APPS setting. | 6259906f097d151d1a2c2906 |
class HealthStatus(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.HealthScore = None <NEW_LINE> self.HealthLevel = None <NEW_LINE> self.ScoreLost = None <NEW_LINE> self.ScoreDetails = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.HealthScore = params.get("HealthScore") <NEW_LINE> self.HealthLevel = params.get("HealthLevel") <NEW_LINE> self.ScoreLost = params.get("ScoreLost") <NEW_LINE> if params.get("ScoreDetails") is not None: <NEW_LINE> <INDENT> self.ScoreDetails = [] <NEW_LINE> for item in params.get("ScoreDetails"): <NEW_LINE> <INDENT> obj = ScoreDetail() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.ScoreDetails.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 实例健康详情。
| 6259906f97e22403b383c798 |
class TestUntranslatedValidator(unittest.TestCase): <NEW_LINE> <INDENT> def test_pass(self): <NEW_LINE> <INDENT> entry = POEntry(msgid="Source", msgstr="Translation") <NEW_LINE> status = Status() <NEW_LINE> status.step(entry) <NEW_LINE> self.assertTrue(untranslated_validator(status)) <NEW_LINE> <DEDENT> def test_fail_missing(self): <NEW_LINE> <INDENT> entry = POEntry(msgid="Source", msgstr="") <NEW_LINE> status = Status() <NEW_LINE> status.step(entry) <NEW_LINE> self.assertFalse(untranslated_validator(status)) <NEW_LINE> <DEDENT> def test_fail_fuzzy(self): <NEW_LINE> <INDENT> entry = POEntry(msgid="Source", msgstr="Translation", flags=['fuzzy']) <NEW_LINE> status = Status() <NEW_LINE> status.step(entry) <NEW_LINE> self.assertFalse(untranslated_validator(status)) <NEW_LINE> <DEDENT> def test_fail_obsolete(self): <NEW_LINE> <INDENT> entry = POEntry(msgid="Source", msgstr="Translation", obsolete=True) <NEW_LINE> status = Status() <NEW_LINE> status.step(entry) <NEW_LINE> self.assertFalse(untranslated_validator(status)) | Test `untranslated_validator`. | 6259906f4527f215b58eb5ea |
class __action_space__: <NEW_LINE> <INDENT> def __init__(self, base): <NEW_LINE> <INDENT> self.__base__ = base <NEW_LINE> self.shape = len(self.__base__.__possible_choices__) <NEW_LINE> <DEDENT> def sample(self): <NEW_LINE> <INDENT> return random.choice(self.__base__.__current_direction__[:-1]) | to see more information about __action_space__ class,
see the env-class docstring about its action_space-class
Note:
This sub-class is snchronized with the parent-env-class | 6259906f4e4d562566373c9c |
class User(Base): <NEW_LINE> <INDENT> __tablename__ = 'user' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(250), nullable=False) <NEW_LINE> email = Column(String(250), nullable=False) <NEW_LINE> picture = Column(String(250)) | User class that creates the user, and stores their login data
Attributes:
name (str): user's name
email (str): user's email
picture (img): user's profile picture | 6259906f56b00c62f0fb4163 |
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.height = height <NEW_LINE> self.width = width <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value | Defines class Rectangle | 6259906f71ff763f4b5e903d |
class DummyMixedDictEnv(gym.Env): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.observation_space = spaces.Dict( { "obs1": spaces.Box(low=-20.0, high=20.0, shape=(4,), dtype=np.float32), "obs2": spaces.Discrete(1), "obs3": spaces.Box(low=-20.0, high=20.0, shape=(4,), dtype=np.float32), } ) <NEW_LINE> self.action_space = spaces.Box(low=-1, high=1, shape=(3,), dtype=np.float32) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return self.observation_space.sample() <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> obs = self.observation_space.sample() <NEW_LINE> done = np.random.rand() > 0.8 <NEW_LINE> return obs, 0.0, done, {} | Dummy mixed gym env for testing purposes | 6259906fa8370b77170f1c5e |
class CalcLifeCell(Elaboratable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.input = Signal(9) <NEW_LINE> self.output = Signal() <NEW_LINE> <DEDENT> def elaborate(self, platform): <NEW_LINE> <INDENT> m = Module() <NEW_LINE> total = Signal(4) <NEW_LINE> i = [self.input[n] for n in range(9)] <NEW_LINE> m.d.comb += [ total.eq(sum(i)), self.output.eq((total == 3) | (i[4] & (total == 4))) ] <NEW_LINE> return m | An evaluator for a single cell | 6259906f99fddb7c1ca63a1d |
class Monster: <NEW_LINE> <INDENT> def __init__(self, x, y, hp): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.hp = hp <NEW_LINE> <DEDENT> def move(self, tuple): <NEW_LINE> <INDENT> self.x = tuple[0] <NEW_LINE> self.y = tuple[1] <NEW_LINE> <DEDENT> def attack(self, player): <NEW_LINE> <INDENT> player.hp -= 1 | Creates a Monster
| 6259906f8e7ae83300eea926 |
class TestRemoteValueSceneNumber: <NEW_LINE> <INDENT> def test_to_knx(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx) <NEW_LINE> assert remote_value.to_knx(11) == DPTArray((0x0A,)) <NEW_LINE> <DEDENT> def test_from_knx(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx) <NEW_LINE> assert remote_value.from_knx(DPTArray((0x0A,))) == 11 <NEW_LINE> <DEDENT> def test_to_knx_error(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx) <NEW_LINE> with pytest.raises(ConversionError): <NEW_LINE> <INDENT> remote_value.to_knx(100) <NEW_LINE> <DEDENT> with pytest.raises(ConversionError): <NEW_LINE> <INDENT> remote_value.to_knx("100") <NEW_LINE> <DEDENT> <DEDENT> async def test_set(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx, group_address=GroupAddress("1/2/3")) <NEW_LINE> await remote_value.set(11) <NEW_LINE> assert xknx.telegrams.qsize() == 1 <NEW_LINE> telegram = xknx.telegrams.get_nowait() <NEW_LINE> assert telegram == Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((0x0A,))), ) <NEW_LINE> await remote_value.set(12) <NEW_LINE> assert xknx.telegrams.qsize() == 1 <NEW_LINE> telegram = xknx.telegrams.get_nowait() <NEW_LINE> assert telegram == Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((0x0B,))), ) <NEW_LINE> <DEDENT> async def test_process(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx, group_address=GroupAddress("1/2/3")) <NEW_LINE> telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((0x0A,))), ) <NEW_LINE> await remote_value.process(telegram) <NEW_LINE> assert remote_value.value == 11 <NEW_LINE> <DEDENT> async def test_to_process_error(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> remote_value = RemoteValueSceneNumber(xknx, group_address=GroupAddress("1/2/3")) <NEW_LINE> telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1)), ) <NEW_LINE> assert await remote_value.process(telegram) is False <NEW_LINE> telegram = Telegram( destination_address=GroupAddress("1/2/3"), payload=GroupValueWrite(DPTArray((0x64, 0x65))), ) <NEW_LINE> assert await remote_value.process(telegram) is False <NEW_LINE> assert remote_value.value is None | Test class for RemoteValueSceneNumber objects. | 6259906f435de62698e9d69c |
class Conflict(HTTPException): <NEW_LINE> <INDENT> code = 409 <NEW_LINE> description = ( 'A conflict happened while processing the request. The resource ' 'might have been modified while the request was being processed.' ) | *409* `Conflict`
Raise to signal that a request cannot be completed because it conflicts
with the current state on the server.
.. versionadded:: 0.7 | 6259906fe5267d203ee6d008 |
class MemoryMessageStoreFactory(MessageStoreFactory): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.base_dict = {} <NEW_LINE> <DEDENT> def get_store(self, store_id): <NEW_LINE> <INDENT> return MemoryMessageStore(self.base_dict, store_id) | Return a Memory message store. All message are lost at pypeman stop. | 6259906fa17c0f6771d5d7f5 |
class PrintIntTask(BaseTask): <NEW_LINE> <INDENT> def __init__(self, base, fixed_string): <NEW_LINE> <INDENT> super(type(self), self).__init__() <NEW_LINE> self.base = base <NEW_LINE> self.eos = 0 <NEW_LINE> self.fixed_string = [13,12,13,14] <NEW_LINE> self.input_type = IOType.integer <NEW_LINE> self.output_type = IOType.integer <NEW_LINE> <DEDENT> def make_io_set(self): <NEW_LINE> <INDENT> return [(list(), list(self.fixed_string))] | Print integer coding task.
Code needs to output a fixed single value (given as a hyperparameter to the
task constructor). Program input is ignored. | 6259906fcc0a2c111447c71c |
class SQALink(MooseMarkdownCommon, Pattern): <NEW_LINE> <INDENT> RE = r'(?<!`)\[(?P<text>.*?)\]\((?P<filename>.*?)(?:\s+(?P<settings>.*?))?\)' <NEW_LINE> @staticmethod <NEW_LINE> def defaultSettings(): <NEW_LINE> <INDENT> settings = MooseMarkdownCommon.defaultSettings() <NEW_LINE> settings['status'] = (False, "When True status badge(s) are created that display the " "status of the linked page.") <NEW_LINE> return settings <NEW_LINE> <DEDENT> def __init__(self, markdown_instance=None, **kwargs): <NEW_LINE> <INDENT> MooseMarkdownCommon.__init__(self, **kwargs) <NEW_LINE> Pattern.__init__(self, self.RE, markdown_instance) <NEW_LINE> <DEDENT> def handleMatch(self, match): <NEW_LINE> <INDENT> if not match.group('settings'): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> settings = self.getSettings(match.group('settings')) <NEW_LINE> filename = match.group('filename') <NEW_LINE> text = match.group('text') <NEW_LINE> el = etree.Element('a') <NEW_LINE> el.set('href', match.group('filename')) <NEW_LINE> if settings['status']: <NEW_LINE> <INDENT> span = etree.SubElement(el, 'span') <NEW_LINE> span.text = text <NEW_LINE> _, found = self.markdown.getFilename(filename) <NEW_LINE> if found: <NEW_LINE> <INDENT> el.append(SQAPageStatus.createStatusElement(found, self.markdown.current)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> el.text = text <NEW_LINE> <DEDENT> return el | Creates markdown link syntax that accept key, value pairs. | 6259906f167d2b6e312b81da |
class TestA(object): <NEW_LINE> <INDENT> pass | Base test class. | 6259906fd486a94d0ba2d855 |
class EventHubListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[EventHubResource]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(EventHubListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | The result of the List EventHubs operation.
:param value: Result of the List EventHubs operation.
:type value: list[~azure.mgmt.eventhub.v2015_08_01.models.EventHubResource]
:param next_link: Link to the next set of results. Not empty if Value contains incomplete list
of EventHubs.
:type next_link: str | 6259906f3539df3088ecdb33 |
class NullTerminatedInput(object): <NEW_LINE> <INDENT> sizehint = 8 * 1024 <NEW_LINE> ifile = None <NEW_LINE> buff = '' <NEW_LINE> def __init__(self, ifile: TextIO=sys.stdin): <NEW_LINE> <INDENT> self.ifile = ifile <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def readlines(self): <NEW_LINE> <INDENT> lines = list() <NEW_LINE> for line in self: <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> <DEDENT> return lines <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> busplitpt = self.buff.find(NULLCHAR) <NEW_LINE> if busplitpt >= 0: <NEW_LINE> <INDENT> nextstr = self.buff[:busplitpt] <NEW_LINE> self.buff = self.buff[busplitpt + 1:] <NEW_LINE> return nextstr <NEW_LINE> <DEDENT> my_bytes = '' <NEW_LINE> bysplitpt = -1 <NEW_LINE> while bysplitpt < 0: <NEW_LINE> <INDENT> my_bytes = self.ifile.read(self.sizehint) <NEW_LINE> if len(my_bytes) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.buff += my_bytes <NEW_LINE> bysplitpt = my_bytes.find(NULLCHAR) <NEW_LINE> <DEDENT> if len(my_bytes) == 0: <NEW_LINE> <INDENT> if len(self.buff) == 0: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.buff <NEW_LINE> <DEDENT> <DEDENT> prevbufflen = len(self.buff) - len(my_bytes) <NEW_LINE> nextstr = self.buff[:prevbufflen + bysplitpt] <NEW_LINE> self.buff = self.buff[prevbufflen + bysplitpt + 1:] <NEW_LINE> return nextstr | An iterator over null-terminated lines (terminated by ' ') in
a file. File must be opened before construction and should be
closed by the caller afterward. | 6259906faad79263cf43004d |
class SpecificHumidityStandardNameAdd(AttributeAdd): <NEW_LINE> <INDENT> def __init__(self, filename, directory): <NEW_LINE> <INDENT> super().__init__(filename, directory) <NEW_LINE> self.attribute_name = 'standard_name' <NEW_LINE> self.attribute_visibility = self.variable_name <NEW_LINE> self.attribute_type = 'c' <NEW_LINE> <DEDENT> def _calculate_new_value(self): <NEW_LINE> <INDENT> self.new_value = 'specific_humidity' | Add a variable attribute `standard_name` with a value of
`specific_humidity`. This is done
in overwrite mode and so will work irrespective of whether there is an
existing standard_name attribute. | 6259906f55399d3f05627db7 |
class BootstrapEstimator(object): <NEW_LINE> <INDENT> def __init__(self, wrapped, n_bootstrap_samples=1000): <NEW_LINE> <INDENT> self._instances = [clone(wrapped, safe=False) for _ in range(n_bootstrap_samples)] <NEW_LINE> self._n_bootstrap_samples = n_bootstrap_samples <NEW_LINE> <DEDENT> def fit(self, *args, **named_args): <NEW_LINE> <INDENT> n_samples = np.shape(args[0] if args else named_args[(*named_args,)[0]])[0] <NEW_LINE> indices = np.random.choice(n_samples, size=(self._n_bootstrap_samples, n_samples), replace=True) <NEW_LINE> for obj, inds in zip(self._instances, indices): <NEW_LINE> <INDENT> obj.fit(*[arg[inds] for arg in args], **{arg: named_args[arg][inds] for arg in named_args}) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> def proxy(make_call, name, summary): <NEW_LINE> <INDENT> def summarize_with(f): <NEW_LINE> <INDENT> return summary(np.array([f(obj, name) for obj in self._instances])) <NEW_LINE> <DEDENT> if make_call: <NEW_LINE> <INDENT> def call(*args, **kwargs): <NEW_LINE> <INDENT> return summarize_with(lambda obj, name: getattr(obj, name)(*args, **kwargs)) <NEW_LINE> <DEDENT> return call <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return summarize_with(lambda obj, name: getattr(obj, name)) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return proxy(callable(getattr(self._instances[0], name)), name, lambda arr: np.mean(arr, axis=0)) <NEW_LINE> <DEDENT> except AttributeError as err: <NEW_LINE> <INDENT> if name.endswith("_interval"): <NEW_LINE> <INDENT> name = name[: - len("_interval")] <NEW_LINE> def call_with_bounds(can_call, lower, upper): <NEW_LINE> <INDENT> return proxy(can_call, name, lambda arr: (np.percentile(arr, lower, axis=0), np.percentile(arr, upper, axis=0))) <NEW_LINE> <DEDENT> can_call = callable(getattr(self._instances[0], name)) <NEW_LINE> if can_call: <NEW_LINE> <INDENT> def call(*args, lower=5, upper=95, **kwargs): <NEW_LINE> <INDENT> return call_with_bounds(can_call, lower, upper)(*args, **kwargs) <NEW_LINE> <DEDENT> return call <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def call(lower=5, upper=95): <NEW_LINE> <INDENT> return call_with_bounds(can_call, lower, upper) <NEW_LINE> <DEDENT> return call <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise err | Estimator that uses bootstrap sampling to wrap an existing estimator.
This estimator provides a `fit` method with the same signature as the wrapped estimator.
The bootstrap estimator will also wrap all other methods and attributes of the wrapped estimator,
but return the average of the sampled calculations (this will fail for non-numeric outputs).
It will also provide a wrapper method suffixed with `_interval` for each method or attribute of
the wrapped estimator that takes two additional optional keyword arguments `lower` and `upper` specifiying
the percentiles of the interval, and which uses `np.percentile` to return the corresponding lower
and upper bounds based on the sampled calculations. For example, if the underlying estimator supports
an `effect` method with signature `(X,T) -> Y`, this class will provide a method `effect_interval`
with pseudo-signature `(lower=5, upper=95, X, T) -> (Y, Y)` (where `lower` and `upper` cannot be
supplied as positional arguments).
Parameters
----------
wrapped : object
The basis for the clones used for estimation.
This object must support a `fit` method which takes numpy arrays with consistent first dimensions
as arguments.
n_bootstrap_samples : int
How many draws to perform. | 6259906f796e427e5385000f |
class PathObject(BaseObject): <NEW_LINE> <INDENT> def __init__(self, x, y, p, rgb, parent): <NEW_LINE> <INDENT> super(PathObject, self).__init__(parent) <NEW_LINE> qDebug("PathObject Constructor()") <NEW_LINE> self.init(x, y, p, rgb, Qt.SolidLine) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> qDebug("PathObject Destructor()") <NEW_LINE> <DEDENT> def init(self, x, y, p, rgb, lineType): <NEW_LINE> <INDENT> self.setData(OBJ_TYPE, self.type()) <NEW_LINE> self.setData(OBJ_NAME, OBJ_NAME_PATH) <NEW_LINE> self.setFlag(QGraphicsItem.ItemIsSelectable, True) <NEW_LINE> self.updatePath(p) <NEW_LINE> self.setObjectPos(x, y) <NEW_LINE> self.setObjectColor(rgb) <NEW_LINE> self.setObjectLineType(lineType) <NEW_LINE> self.setObjectLineWeight(0.35) <NEW_LINE> self.setPen(self.objectPen()) <NEW_LINE> <DEDENT> def updatePath(self, p): <NEW_LINE> <INDENT> normalPath = p <NEW_LINE> reversePath = normalPath.toReversed() <NEW_LINE> reversePath.connectPath(normalPath) <NEW_LINE> self.setObjectPath(reversePath) <NEW_LINE> <DEDENT> def paint(self, painter, option, widget): <NEW_LINE> <INDENT> objScene = self.scene() <NEW_LINE> if not objScene: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> paintPen = self.pen() <NEW_LINE> painter.setPen(paintPen) <NEW_LINE> self.updateRubber(painter) <NEW_LINE> if option.state & QStyle.State_Selected: <NEW_LINE> <INDENT> paintPen.setStyle(Qt.DashLine) <NEW_LINE> <DEDENT> if objScene.property(ENABLE_LWT).toBool(): <NEW_LINE> <INDENT> paintPen = self.lineWeightPen() <NEW_LINE> <DEDENT> painter.setPen(paintPen) <NEW_LINE> painter.drawPath(self.objectPath()) <NEW_LINE> <DEDENT> def updateRubber(self, painter): <NEW_LINE> <INDENT> pass <NEW_LINE> pass <NEW_LINE> <DEDENT> def vulcanize(self): <NEW_LINE> <INDENT> qDebug("PathObject vulcanize()") <NEW_LINE> self.updateRubber() <NEW_LINE> self.setObjectRubberMode(OBJ_RUBBER_OFF) <NEW_LINE> if not normalPath.elementCount(): <NEW_LINE> <INDENT> QMessageBox.critical(0, QObject.tr("Empty Path Error"), QObject.tr("The path added contains no points. The command that created this object has flawed logic.")) <NEW_LINE> <DEDENT> <DEDENT> def mouseSnapPoint(self, mousePoint): <NEW_LINE> <INDENT> return self.scenePos() <NEW_LINE> <DEDENT> def allGripPoints(self): <NEW_LINE> <INDENT> gripPoints = list(self.scenePos()) <NEW_LINE> return gripPoints <NEW_LINE> <DEDENT> def gripEdit(self, before, after): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def objectCopyPath(self): <NEW_LINE> <INDENT> return normalPath <NEW_LINE> <DEDENT> def objectSavePath(self): <NEW_LINE> <INDENT> s = self.scale() <NEW_LINE> trans = QTransform() <NEW_LINE> trans.rotate(self.rotation()) <NEW_LINE> trans.scale(s, s) <NEW_LINE> return trans.map(normalPath) | Subclass of `BaseObject`_
TOWRITE | 6259906fac7a0e7691f73d7f |
class RSSError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value) | Base class for all rss.py errors | 6259906f1f037a2d8b9e54b6 |
class UpdateSubmodules(Command): <NEW_LINE> <INDENT> description = "Update git submodules" <NEW_LINE> user_options = [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> failure = False <NEW_LINE> try: <NEW_LINE> <INDENT> self.spawn('git submodule init'.split()) <NEW_LINE> self.spawn('git submodule update --recursive'.split()) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> failure = e <NEW_LINE> print(e) <NEW_LINE> <DEDENT> if not check_submodule_status(repo_root) == 'clean': <NEW_LINE> <INDENT> print("submodules could not be checked out") <NEW_LINE> sys.exit(1) | Update git submodules
| 6259906f4527f215b58eb5eb |
class MockJSONEncoder(JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> return "9" | Mock JSON encoder. | 6259906f4e4d562566373c9e |
class RWLock(object): <NEW_LINE> <INDENT> def __init__(self, max_readers=1, io_loop=None): <NEW_LINE> <INDENT> self._max_readers = max_readers <NEW_LINE> self._block = BoundedSemaphore(value=max_readers, io_loop=io_loop) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<%s _block=%s>" % ( self.__class__.__name__, self._block) <NEW_LINE> <DEDENT> def acquire_read(self, deadline=None): <NEW_LINE> <INDENT> return self._block.acquire(deadline) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def acquire_write(self, deadline=None): <NEW_LINE> <INDENT> futures = [self._block.acquire(deadline) for _ in xrange(self._max_readers)] <NEW_LINE> try: <NEW_LINE> <INDENT> managers = yield tornado_multi_future(futures, quiet_exceptions=Timeout) <NEW_LINE> <DEDENT> except Timeout: <NEW_LINE> <INDENT> for f in futures: <NEW_LINE> <INDENT> f.exception() <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> raise gen.Return(_ContextManagerList(managers)) <NEW_LINE> <DEDENT> def release_read(self): <NEW_LINE> <INDENT> if self._block.counter == self._max_readers: <NEW_LINE> <INDENT> raise RuntimeError('release unlocked lock') <NEW_LINE> <DEDENT> self._block.release() <NEW_LINE> <DEDENT> def release_write(self): <NEW_LINE> <INDENT> if not self.locked(): <NEW_LINE> <INDENT> raise RuntimeError('release unlocked lock') <NEW_LINE> <DEDENT> for i in xrange(self._max_readers): <NEW_LINE> <INDENT> self._block.release() <NEW_LINE> <DEDENT> <DEDENT> def locked(self): <NEW_LINE> <INDENT> return self._block.locked() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> raise RuntimeError( "Use RWLock like 'with (yield lock)', not like" " 'with lock'") <NEW_LINE> <DEDENT> __exit__ = __enter__ | A reader-writer lock for coroutines.
It is created unlocked. When unlocked, :meth:`acquire_write` always changes
the state to locked. When unlocked, :meth:`acquire_read` can changed the
state to locked, if :meth:`acquire_read` was called max_readers times. When
the state is locked, yielding :meth:`acquire_read`/meth:`acquire_write`
waits until a call to :meth:`release_write` in case of locking on write, or
:meth:`release_read` in case of locking on read.
The :meth:`release_read` method should only be called in the locked-on-read
state; an attempt to release an unlocked lock raises RuntimeError.
The :meth:`release_write` method should only be called in the locked on
write state; an attempt to release an unlocked lock raises RuntimeError.
When more than one coroutine is waiting for the lock, the first one
registered is awakened by :meth:`release_read`/:meth:`release_write`.
:meth:`acquire_read`/:meth:`acquire_write` support the context manager
protocol:
>>> from tornado import gen
>>> import toro
>>> lock = toro.RWLock(max_readers=10)
>>>
>>> @gen.coroutine
... def f():
... with (yield lock.acquire_read()):
... assert not lock.locked()
...
... with (yield lock.acquire_write()):
... assert lock.locked()
...
... assert not lock.locked()
:Parameters:
- `max_readers`: Optional max readers value, default 1.
- `io_loop`: Optional custom IOLoop. | 6259906ff548e778e596ce24 |
class AppAlertDismissAjaxView(SODARBaseAjaxView): <NEW_LINE> <INDENT> permission_required = 'appalerts.view_alerts' <NEW_LINE> def post(self, request, **kwargs): <NEW_LINE> <INDENT> if not request.user or request.user.is_anonymous: <NEW_LINE> <INDENT> return Response({'detail': 'Anonymous access denied'}, status=401) <NEW_LINE> <DEDENT> alerts = AppAlert.objects.filter(user=request.user, active=True) <NEW_LINE> if kwargs.get('appalert'): <NEW_LINE> <INDENT> alerts = alerts.filter(sodar_uuid=kwargs['appalert']) <NEW_LINE> <DEDENT> if not alerts: <NEW_LINE> <INDENT> return Response({'detail': 'Not found'}, status=404) <NEW_LINE> <DEDENT> for alert in alerts: <NEW_LINE> <INDENT> alert.active = False <NEW_LINE> alert.save() <NEW_LINE> <DEDENT> return Response({'detail': 'OK'}, status=200) | View to handle app alert dismissal in UI | 6259906f56ac1b37e630392e |
class AssetContentRecord(osid_records.OsidRecord): <NEW_LINE> <INDENT> pass | A record for an ``AssetContent``.
The methods specified by the record type are available through the
underlying object. | 6259906f627d3e7fe0e0871f |
class Euclidean(core.BaseWeight): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def names(cls): <NEW_LINE> <INDENT> return "euclidean", "euc", "ordinary" <NEW_LINE> <DEDENT> def __init__(self, to_num=None): <NEW_LINE> <INDENT> self.to_num = to_num_default if to_num is None else to_num <NEW_LINE> <DEDENT> def weight(self, hap0, hap1): <NEW_LINE> <INDENT> s = 0.0 <NEW_LINE> for name in set(hap0.keys() + hap1.keys()): <NEW_LINE> <INDENT> v0 = self.to_num(hap0.get(name, "")) <NEW_LINE> v1 = self.to_num(hap1.get(name, "")) <NEW_LINE> s += (v1 - v0) ** 2 <NEW_LINE> <DEDENT> return np.sqrt(s) | Calculates "ordinary" distance/weight between two haplotypes given by
the Pythagorean formula.
Every attribute value is converted to a number by a ``to_num`` function.
The default behavior of ``to_num`` is a sumatory of base64 ord value of
every attribute value. Example:
.. code-block:: python
def to_num(attr):
value = 0
for c in str(attr).encode("base64"):
value += ord(c)
return value
to_num("h") # 294
For more info about euclidean distance:
http://en.wikipedia.org/wiki/Euclidean_distance | 6259906f8da39b475be04a85 |
class ExportAssetsRequest(_messages.Message): <NEW_LINE> <INDENT> class ContentTypeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> CONTENT_TYPE_UNSPECIFIED = 0 <NEW_LINE> RESOURCE = 1 <NEW_LINE> IAM_POLICY = 2 <NEW_LINE> <DEDENT> assetTypes = _messages.StringField(1, repeated=True) <NEW_LINE> contentType = _messages.EnumField('ContentTypeValueValuesEnum', 2) <NEW_LINE> outputConfig = _messages.MessageField('OutputConfig', 3) <NEW_LINE> readTime = _messages.StringField(4) | Export asset request.
Enums:
ContentTypeValueValuesEnum: Asset content type. If not specified, no
content but the asset name will be returned.
Fields:
assetTypes: A list of asset types of which to take a snapshot for. For
example: "compute.googleapis.com/Disk". If specified, only matching
assets will be returned. See [Introduction to Cloud Asset
Inventory](https://cloud.google.com/resource-manager/docs/cloud-asset-
inventory/overview) for all supported asset types.
contentType: Asset content type. If not specified, no content but the
asset name will be returned.
outputConfig: Required. Output configuration indicating where the results
will be output to. All results will be in newline delimited JSON format.
readTime: Timestamp to take an asset snapshot. This can only be set to a
timestamp between 2018-10-02 UTC (inclusive) and the current time. If
not specified, the current time will be used. Due to delays in resource
data collection and indexing, there is a volatile window during which
running the same query may get different results. | 6259906fa05bb46b3848bd78 |
class Sentence(AbstractSentence): <NEW_LINE> <INDENT> homework_sheet = models.ForeignKey("HomeworkSheet", related_name="sentences"); <NEW_LINE> def get_mixed(self): <NEW_LINE> <INDENT> splited = self.sentence_text[:-1].split() <NEW_LINE> shuffle(splited) <NEW_LINE> return " ".join(splited) + self.sentence_text[-1] | Original sentence model.
For sentences written by teacher. | 6259906fa8370b77170f1c60 |
class get_twitter(): <NEW_LINE> <INDENT> def __init__(self,query,item,namesave): <NEW_LINE> <INDENT> self.df_traing = pd.DataFrame() <NEW_LINE> self.query = query <NEW_LINE> self.namesave = namesave <NEW_LINE> self.item = item <NEW_LINE> <DEDENT> def __help__(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __version__(): <NEW_LINE> <INDENT> print("1.1.12") <NEW_LINE> <DEDENT> def authenticate_twitter_app(self): <NEW_LINE> <INDENT> key = farhadkey() <NEW_LINE> consumer_key = key["CONSUMER_KEY"] <NEW_LINE> consumer_secret = key["CONSUMER_SECRET"] <NEW_LINE> access_token = key["ACCESS_TOKEN"] <NEW_LINE> access_secret = key["ACCESS_SECRET"] <NEW_LINE> auth = tweepy.OAuthHandler(consumer_key, consumer_secret) <NEW_LINE> auth.set_access_token(access_token, access_secret) <NEW_LINE> self.api = tweepy.API(auth) <NEW_LINE> <DEDENT> def get_by_query_until(self): <NEW_LINE> <INDENT> data_name = [] <NEW_LINE> data_screen_name =[] <NEW_LINE> data_location = [] <NEW_LINE> data_text =[] <NEW_LINE> data_created_at= [] <NEW_LINE> data_geo = [] <NEW_LINE> data_source =[] <NEW_LINE> data_idtwitter =[] <NEW_LINE> end_date = datetime.datetime.now() <NEW_LINE> for number,status in enumerate(tweepy.Cursor(self.api.search, q=self.query, result_type="recent", lan='en' ).items(self.item)): <NEW_LINE> <INDENT> data_name.append(status.user.name) <NEW_LINE> data_screen_name.append(status.user.screen_name) <NEW_LINE> data_location.append(status.user.location) <NEW_LINE> data_text.append(status.text) <NEW_LINE> data_created_at.append(status.user.created_at) <NEW_LINE> data_geo.append(status.coordinates) <NEW_LINE> data_source.append(status.source) <NEW_LINE> run = ("[Number of Tweets have been gotten:"+str(number+1)+"]["+str('collected tweets')+']') <NEW_LINE> sys.stdout.write('\r'+ run) <NEW_LINE> <DEDENT> self.df_traing['name'] = data_name <NEW_LINE> self.df_traing['screen_name'] = data_screen_name <NEW_LINE> self.df_traing['text'] = data_text <NEW_LINE> self.df_traing['created_at'] = data_created_at <NEW_LINE> self.df_traing['geo'] = data_geo <NEW_LINE> self.df_traing['source'] = data_source <NEW_LINE> self.df_traing['data_location'] = data_location <NEW_LINE> self.df_traing.to_csv(self.namesave,index=False) <NEW_LINE> print("*** DONE!(I am cool) ***") <NEW_LINE> return self.df_traing | use Twiiter API (by tweepy api) | 6259906fdd821e528d6da5cd |
class BouncingBall: <NEW_LINE> <INDENT> def __init__(self, canvas, center, radius, color, direction, speed): <NEW_LINE> <INDENT> x, y = center <NEW_LINE> x1 = x - radius <NEW_LINE> y1 = y - radius <NEW_LINE> x2 = x + radius <NEW_LINE> y2 = y + radius <NEW_LINE> self.handle = canvas.create_oval(x1, y1, x2, y2, fill=color, outline=color) <NEW_LINE> global ballList <NEW_LINE> ballList.append(self.handle) <NEW_LINE> self.canvas = canvas <NEW_LINE> self.xmax = int(canvas.cget('width')) - 1 <NEW_LINE> self.ymax = int(canvas.cget('height')) - 1 <NEW_LINE> self.center = center <NEW_LINE> self.radius = radius <NEW_LINE> self.color = color <NEW_LINE> if direction < 0.0 or direction > 360.0: <NEW_LINE> <INDENT> raise ValueError('Invalid direction; must be in range [0.0, 360.0]') <NEW_LINE> <DEDENT> dir_radians = direction * math.pi / 180.0 <NEW_LINE> self.dirx = math.cos(dir_radians) <NEW_LINE> self.diry = -math.sin(dir_radians) <NEW_LINE> if speed < 0.0: <NEW_LINE> <INDENT> raise ValueError('Invalid speed; must be positive') <NEW_LINE> <DEDENT> self.speed = speed <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> vx = self.speed * self.dirx <NEW_LINE> vy = self.speed * self.diry <NEW_LINE> dx = self.displacement(self.center[0], vx, self.xmax) <NEW_LINE> dy = self.displacement(self.center[1], vy, self.ymax) <NEW_LINE> if dx != vx: <NEW_LINE> <INDENT> self.dirx *= -1 <NEW_LINE> <DEDENT> if dy != vy: <NEW_LINE> <INDENT> self.diry *= -1 <NEW_LINE> <DEDENT> (x, y) = self.center <NEW_LINE> x += dx <NEW_LINE> y += dy <NEW_LINE> self.center = (x, y) <NEW_LINE> canvas.delete(self.handle) <NEW_LINE> ballList.remove(self.handle) <NEW_LINE> self.handle = canvas.create_oval(x + self.radius, y + self.radius, x - self.radius, y - self.radius, fill=self.color, outline=self.color) <NEW_LINE> ballList.append(self.handle) <NEW_LINE> <DEDENT> def displacement(self, c, d, cmax): <NEW_LINE> <INDENT> if(c + self.radius + d) > cmax: <NEW_LINE> <INDENT> dist_away = cmax - (c + self.radius) <NEW_LINE> return dist_away - (d - dist_away) <NEW_LINE> <DEDENT> elif(c - self.radius + d) < 0: <NEW_LINE> <INDENT> dist_away = 0 + (c - self.radius) <NEW_LINE> return dist_away + (d + dist_away) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return d <NEW_LINE> <DEDENT> <DEDENT> def scale_speed(self, scale): <NEW_LINE> <INDENT> self.speed *= scale <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> self.canvas.delete(self.handle) | Objects of this class represent balls which bounce on a canvas. | 6259906f99fddb7c1ca63a1e |
class Register(Resource): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> email = request.form['email'] <NEW_LINE> password = request.form['password'] <NEW_LINE> if not email or not password: <NEW_LINE> <INDENT> response = jsonify({'message': 'Provide both email and password'}) <NEW_LINE> response.status_code = 400 <NEW_LINE> return response <NEW_LINE> <DEDENT> user = User(email, password) <NEW_LINE> db.session.add(user) <NEW_LINE> try: <NEW_LINE> <INDENT> db.session.commit() <NEW_LINE> response = jsonify({'message': 'Registered Successfully'}) <NEW_LINE> response.status_code = 200 <NEW_LINE> return response <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> response = jsonify({'message': 'Email address already in use'}) <NEW_LINE> response.status_code = 400 <NEW_LINE> return response | Register user | 6259906f5fc7496912d48eb4 |
class LoginHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> if not self.current_user: <NEW_LINE> <INDENT> self.render("admin_login.html") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect("/Index") <NEW_LINE> <DEDENT> <DEDENT> async def post(self): <NEW_LINE> <INDENT> data = tornado.escape.json_decode(self.request.body) <NEW_LINE> username = data["username"] <NEW_LINE> password = data['password'] <NEW_LINE> document = await db.admin.find_one({"username":username}) <NEW_LINE> if document != None: <NEW_LINE> <INDENT> stored_password = document['password'] <NEW_LINE> salt = document['salt'].encode() <NEW_LINE> password = bcrypt.hashpw(password.encode(), salt) <NEW_LINE> if stored_password == password.decode(): <NEW_LINE> <INDENT> self.set_secure_cookie("Admin", username) <NEW_LINE> self.set_cookie("Checked", "No") <NEW_LINE> response = {"LoggedIn": "True"} <NEW_LINE> self.write(json.dumps(response)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = {"LoggedIn": "False"} <NEW_LINE> self.write(json.dumps(response)) | Login Page | 6259906f3317a56b869bf190 |
class LookupError(Error): <NEW_LINE> <INDENT> pass | An error occurred during a lookup query.
| 6259906ff548e778e596ce25 |
class BeginTransactionRequest(_messages.Message): <NEW_LINE> <INDENT> options = _messages.MessageField('TransactionOptions', 1) | The request for Firestore.BeginTransaction.
Fields:
options: The options for the transaction. Defaults to a read-write
transaction. | 6259906f4f88993c371f116c |
class _IsolatedEnvVenvPip(IsolatedEnv): <NEW_LINE> <INDENT> def __init__(self, path, python_executable, scripts_dir): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> self._python_executable = python_executable <NEW_LINE> self._scripts_dir = scripts_dir <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @property <NEW_LINE> def executable(self): <NEW_LINE> <INDENT> return self._python_executable <NEW_LINE> <DEDENT> @property <NEW_LINE> def scripts_dir(self): <NEW_LINE> <INDENT> return self._scripts_dir <NEW_LINE> <DEDENT> def install(self, requirements): <NEW_LINE> <INDENT> if not requirements: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with tempfile.NamedTemporaryFile('w+', prefix='build-reqs-', suffix='.txt', delete=False) as req_file: <NEW_LINE> <INDENT> req_file.write(os.linesep.join(requirements)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> cmd = [ self.executable, '-{}m'.format('E' if sys.version_info[0] == 2 else 'I'), 'pip', 'install', '--use-pep517', '--no-warn-script-location', '-r', os.path.abspath(req_file.name), ] <NEW_LINE> subprocess.check_call(cmd) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.unlink(req_file.name) | Isolated build environment context manager
Non-standard paths injected directly to sys.path will still be passed to the environment. | 6259906f7d847024c075dc71 |
class AnanlysisEmployeeEveryday(LoginRequiredMixin,View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> getParams = request.GET <NEW_LINE> filter_date = getParams.get('filter_date', '') <NEW_LINE> employee_name= getParams.get('employee_name', '') <NEW_LINE> if not employee_name: <NEW_LINE> <INDENT> employee_name=u'空姓名' <NEW_LINE> <DEDENT> department_name = request.user.department.department_name <NEW_LINE> plain_sql=filter_dev_event_sql(filter_date=filter_date,employee_name=employee_name,project_id='',project_name='',department_name='',user_id='') <NEW_LINE> group_sql = u'select event_date,event_type_name,ROUND(sum(duration_time/3600)::numeric,2) as date_diff from ({0}) as child group by event_date,event_type_name order by event_date,event_type_name '.format(plain_sql) <NEW_LINE> row = fetch_data(group_sql) <NEW_LINE> event_date_list=list({i['event_date'].strftime("%Y-%m-%d") for i in row}) <NEW_LINE> event_type_name_list=list({i['event_type_name'] for i in row}) <NEW_LINE> event_date_list.sort() <NEW_LINE> result={} <NEW_LINE> for event_date in event_date_list: <NEW_LINE> <INDENT> result[event_date]={} <NEW_LINE> for type_name in event_type_name_list: <NEW_LINE> <INDENT> result[event_date][type_name]=0 <NEW_LINE> for value in row: <NEW_LINE> <INDENT> if value.get('event_date').strftime("%Y-%m-%d")==event_date and value.get('event_type_name')==type_name: <NEW_LINE> <INDENT> result[event_date][type_name]=value.get('date_diff',0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> date_list=[] <NEW_LINE> time_count_list={} <NEW_LINE> for event_date in event_date_list: <NEW_LINE> <INDENT> date_list.append(event_date) <NEW_LINE> for type_name in event_type_name_list: <NEW_LINE> <INDENT> if time_count_list.get(type_name): <NEW_LINE> <INDENT> time_count_list[type_name].append(result[event_date].get(type_name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time_count_list[type_name]=[result[event_date].get(type_name)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> content = dict_to_json({'date_list':date_list,'time_count_list':time_count_list}) <NEW_LINE> response = my_response(code=0, msg=u"查询成功", content=content) <NEW_LINE> return response | 查询特定职员每日工作情况 | 6259906fe76e3b2f99fda29b |
class CreateRouteTableResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RouteTable = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("RouteTable") is not None: <NEW_LINE> <INDENT> self.RouteTable = RouteTable() <NEW_LINE> self.RouteTable._deserialize(params.get("RouteTable")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | CreateRouteTable返回参数结构体
| 6259906fd486a94d0ba2d857 |
@implementer(IToolConf) <NEW_LINE> class ToolConf(baseConf): <NEW_LINE> <INDENT> def __init__(self, copyFrom=None, **values): <NEW_LINE> <INDENT> self.id = "" <NEW_LINE> self.name = "" <NEW_LINE> self.context = "" <NEW_LINE> self.apply = None <NEW_LINE> self.data = [] <NEW_LINE> self.values = {} <NEW_LINE> self.views = [] <NEW_LINE> self.modules = [] <NEW_LINE> self.mimetype = "" <NEW_LINE> self.hidden = False <NEW_LINE> self.description = "" <NEW_LINE> baseConf.__init__(self, copyFrom, **values) <NEW_LINE> <DEDENT> def __call__(self, context): <NEW_LINE> <INDENT> return self, context <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%(id)s (%(name)s) implemented by %(context)s" % self <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> report = [] <NEW_LINE> if not self.id: <NEW_LINE> <INDENT> report.append((ConfigurationError, " ToolConf.id is empty", self)) <NEW_LINE> <DEDENT> o = TryResolveName(self.context) <NEW_LINE> if not o: <NEW_LINE> <INDENT> report.append((ImportError, " for ToolConf.context", self)) <NEW_LINE> <DEDENT> if not isinstance(self.data, (list, tuple)): <NEW_LINE> <INDENT> report.append((TypeError, " ToolConf.data error: Not a list", self)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for m in self.data: <NEW_LINE> <INDENT> if hasattr(m, "test"): <NEW_LINE> <INDENT> report += m.test() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not isinstance(self.views, (list, tuple)): <NEW_LINE> <INDENT> report.append((TypeError, " ToolConf.views error: Not a list", self)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for m in self.views: <NEW_LINE> <INDENT> if hasattr(m, "test"): <NEW_LINE> <INDENT> report += m.test() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for m in self.modules: <NEW_LINE> <INDENT> if isinstance(m, str): <NEW_LINE> <INDENT> o = TryResolveName(m) <NEW_LINE> if not o: <NEW_LINE> <INDENT> report.append((ImportError, " ToolConf.modules import: "+m, self)) <NEW_LINE> <DEDENT> <DEDENT> if hasattr(m, "test"): <NEW_LINE> <INDENT> report += m.test() <NEW_LINE> <DEDENT> <DEDENT> return report | Tool configuration
Values ::
*id : Unique tool id as ascii string. Used to register and lookup the tool.
*context : Dotted python name or class reference used as factory.
*apply : List of interfaces the tool is registered for.
data : Tool data defined as nive.definitions.FieldConf list.
values : Values to override data.default on execution.
views : List of nive.definitions.ViewConf definitions.
mimetype : Mimetype of tool return stream
hidden : Hide in user interface.
name : Display name
events : Register for one or multiple Application events.
Register each event as e.g. Conf(event="run", callback=function).
modules : Additional module configurations to be included.
description : Description
Call ToolConf().test() to verify configuration values.
Interface: IToolConf | 6259906f01c39578d7f14381 |
class CalibrationClient(Client): <NEW_LINE> <INDENT> def __init__(self, calibrationID=None, workerID=None, **kwargs): <NEW_LINE> <INDENT> super(CalibrationClient, self).__init__(**kwargs) <NEW_LINE> self.setServer('Calibration/Calibration') <NEW_LINE> self.calibrationID = calibrationID <NEW_LINE> self.workerID = workerID <NEW_LINE> self.currentStep = -1 <NEW_LINE> self.currentPhase = CalibrationPhase.ECalDigi <NEW_LINE> self.currentStage = 1 <NEW_LINE> self.parameterSet = None <NEW_LINE> self.log = LOG <NEW_LINE> self.ops = Operations() <NEW_LINE> self.maximumReportTries = self.ops.getValue('Calibration/MaximumReportTries', 10) <NEW_LINE> <DEDENT> def getInputDataDict(self, calibrationID=None, workerID=None): <NEW_LINE> <INDENT> if calibrationID is None and self.calibrationID is None: <NEW_LINE> <INDENT> return S_ERROR("Specify calibrationID") <NEW_LINE> <DEDENT> if workerID is None and self.workerID is None: <NEW_LINE> <INDENT> return S_ERROR("Specify workerID") <NEW_LINE> <DEDENT> calibIDToUse = calibrationID if calibrationID is not None else self.calibrationID <NEW_LINE> workerIDToUse = workerID if workerID is not None else self.workerID <NEW_LINE> return self._getRPC().getInputDataDict(calibIDToUse, workerIDToUse) <NEW_LINE> <DEDENT> def requestNewParameters(self): <NEW_LINE> <INDENT> res = self.getNewParameters(self.calibrationID, self.currentStep) <NEW_LINE> if res['OK']: <NEW_LINE> <INDENT> returnValue = res['Value'] <NEW_LINE> if returnValue is not None: <NEW_LINE> <INDENT> self.currentPhase = returnValue['currentPhase'] <NEW_LINE> self.currentStage = returnValue['currentStage'] <NEW_LINE> self.currentStep = returnValue['currentStep'] <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> def requestNewPhotonLikelihood(self): <NEW_LINE> <INDENT> res = self.getNewPhotonLikelihood(self.calibrationID) <NEW_LINE> if res['OK']: <NEW_LINE> <INDENT> return res['Value'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def reportResult(self, outFileName): <NEW_LINE> <INDENT> attempt = 0 <NEW_LINE> resultString = binaryFileToString(outFileName) <NEW_LINE> while attempt < self.maximumReportTries: <NEW_LINE> <INDENT> res = self.submitResult(self.calibrationID, self.currentStage, self.currentPhase, self.currentStep, self.workerID, resultString) <NEW_LINE> if res['OK']: <NEW_LINE> <INDENT> return S_OK() <NEW_LINE> <DEDENT> self.log.warn("Failed to submit result, try", "%s: %s " % (attempt, res['Message'])) <NEW_LINE> attempt += 1 <NEW_LINE> <DEDENT> return S_ERROR('Could not report result back to CalibrationService.') <NEW_LINE> <DEDENT> def createCalibration(self, inputFiles, numberOfEventsPerFile, calibSettingsDict): <NEW_LINE> <INDENT> res = self._getRPC().createCalibration(inputFiles, numberOfEventsPerFile, calibSettingsDict) <NEW_LINE> if not res['OK']: <NEW_LINE> <INDENT> LOG.error('Error while executing createCalibration! Error message: ', res['Message']) <NEW_LINE> <DEDENT> return res | Provide an interface for user and worker nodes to talk to Calibration service.
Contains interfaces to fetch the necessary data from the service to worker node and to report the results back. | 6259906f7047854f46340c51 |
class TestCalendarUpdate(Base): <NEW_LINE> <INDENT> expected_title = "fedocal.calendar.update" <NEW_LINE> expected_subti = 'ralph updated the "awesome" calendar' <NEW_LINE> expected_link = "https://apps.fedoraproject.org/calendar/awesome/" <NEW_LINE> expected_icon = ("https://apps.fedoraproject.org/calendar/" "static/calendar.png") <NEW_LINE> expected_secondary_icon = ( "https://seccdn.libravatar.org/avatar/" "9c9f7784935381befc302fe3c814f9136e7a33953d0318761669b8643f4df55c" "?s=64&d=retro") <NEW_LINE> expected_packages = set([]) <NEW_LINE> expected_usernames = set(['ralph']) <NEW_LINE> expected_objects = set(['awesome/update']) <NEW_LINE> msg = { "username": "threebean", "i": 1, "timestamp": 1379638157.759283, "msg_id": "2013-96f9ca0e-c7c6-43f0-9de7-7a268c7f1cef", "topic": "org.fedoraproject.dev.fedocal.calendar.update", "msg": { "calendar": { "calendar_editor_group": "sysadmin-main", "calendar_name": "awesome", "calendar_description": "cool deal", "calendar_admin_group": "sysadmin-badges", "calendar_contact": "[email protected]", "calendar_status": "Enabled" }, "agent": "ralph" } } | These messages are published when someone updates a whole calendar from
`fedocal <https://apps.fedoraproject.org/calendar>`_. | 6259906ffff4ab517ebcf0b4 |
class SafeChildWatcher(BaseChildWatcher): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._callbacks = {} <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._callbacks.clear() <NEW_LINE> super().close() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, a, b, c): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_child_handler(self, pid, callback, *args): <NEW_LINE> <INDENT> self._callbacks[pid] = callback, args <NEW_LINE> self._do_waitpid(pid) <NEW_LINE> <DEDENT> def remove_child_handler(self, pid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self._callbacks[pid] <NEW_LINE> return True <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def _do_waitpid_all(self): <NEW_LINE> <INDENT> for pid in list(self._callbacks): <NEW_LINE> <INDENT> self._do_waitpid(pid) <NEW_LINE> <DEDENT> <DEDENT> def _do_waitpid(self, expected_pid): <NEW_LINE> <INDENT> assert expected_pid > 0 <NEW_LINE> try: <NEW_LINE> <INDENT> pid, status = os.waitpid(expected_pid, os.WNOHANG) <NEW_LINE> <DEDENT> except ChildProcessError: <NEW_LINE> <INDENT> pid = expected_pid <NEW_LINE> returncode = 255 <NEW_LINE> logger.warning( "Unknown child process pid %d, will report returncode 255", pid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if pid == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> returncode = self._compute_returncode(status) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> callback, args = self._callbacks.pop(pid) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> callback(pid, returncode, *args) | 'Safe' child watcher implementation.
This implementation avoids disrupting other code spawning processes by
polling explicitly each process in the SIGCHLD handler instead of calling
os.waitpid(-1).
This is a safe solution but it has a significant overhead when handling a
big number of children (O(n) each time SIGCHLD is raised) | 6259906fbe8e80087fbc0928 |
class WeblateLoginView(LoginView): <NEW_LINE> <INDENT> form_class = LoginForm <NEW_LINE> template_name = "accounts/login.html" <NEW_LINE> redirect_authenticated_user = True <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> auth_backends = list(load_backends(social_django.utils.BACKENDS).keys()) <NEW_LINE> context["login_backends"] = [x for x in auth_backends if x != "email"] <NEW_LINE> context["can_reset"] = "email" in auth_backends <NEW_LINE> context["title"] = _("Sign in") <NEW_LINE> return context <NEW_LINE> <DEDENT> @method_decorator(never_cache) <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> return redirect_profile() <NEW_LINE> <DEDENT> auth_backends = list(load_backends(social_django.utils.BACKENDS).keys()) <NEW_LINE> if len(auth_backends) == 1 and auth_backends[0] != "email": <NEW_LINE> <INDENT> return redirect_single(request, auth_backends[0]) <NEW_LINE> <DEDENT> return super().dispatch(request, *args, **kwargs) | Login handler, just a wrapper around standard Django login. | 6259906fa05bb46b3848bd79 |
class RaftStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.RequestVote = channel.unary_unary( '/Raft/RequestVote', request_serializer=raft__pb2.VoteRequest.SerializeToString, response_deserializer=raft__pb2.Ack.FromString, ) <NEW_LINE> self.AppendEntries = channel.unary_unary( '/Raft/AppendEntries', request_serializer=raft__pb2.Entries.SerializeToString, response_deserializer=raft__pb2.Ack.FromString, ) <NEW_LINE> self.ReceivePropose = channel.unary_unary( '/Raft/ReceivePropose', request_serializer=raft__pb2.Proposal.SerializeToString, response_deserializer=raft__pb2.Ack.FromString, ) | Raft gRPC implementation
| 6259906fa8370b77170f1c62 |
class ScaledMean(Mean, ScaledFunction): <NEW_LINE> <INDENT> @_dispatch <NEW_LINE> def __call__(self, x): <NEW_LINE> <INDENT> return B.multiply(self.scale, self[0](x)) | Scaled mean. | 6259906f5fdd1c0f98e5f820 |
class WindowManager(ScreenManager): <NEW_LINE> <INDENT> pass | Navigation Router | 6259906f009cb60464d02dd1 |
class Vehiculo(models.Model): <NEW_LINE> <INDENT> TIPO_USUARIO = ( (u'1', u'Gerente'), (u'2', u'Tesorero'), (u'3', u'Cliente'), (u'4', u'Conductor'), ) <NEW_LINE> id = models.UUIDField(primary_key=True, default=uuid4, editable=False) <NEW_LINE> documento_identidad=models.IntegerField() <NEW_LINE> foto_vehiculo=models.ImageField(upload_to='photo') <NEW_LINE> conductor =models.ForeignKey(User, on_delete=models.CASCADE,) <NEW_LINE> marca=models.CharField(max_length=50) <NEW_LINE> modelo = models.CharField(max_length=50) <NEW_LINE> año = models.CharField(max_length=4) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "DatosPersonal" <NEW_LINE> verbose_name_plural = "DatosPersonales" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.documento_identidad | docs | 6259906f0a50d4780f706a0e |
class UUIDEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, UUID4): <NEW_LINE> <INDENT> return str(obj) <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, obj) | UUID Encoder | 6259906f4f6381625f19a0f5 |
class SubstringEmbeddableGenerator(AbstractEmbeddableGenerator): <NEW_LINE> <INDENT> def __init__(self, substringGenerator, name=None): <NEW_LINE> <INDENT> self.substringGenerator = substringGenerator <NEW_LINE> super(SubstringEmbeddableGenerator, self).__init__(name) <NEW_LINE> <DEDENT> def generateEmbeddable(self): <NEW_LINE> <INDENT> substring, substringDescription = self.substringGenerator.generateSubstring() <NEW_LINE> return StringEmbeddable(substring, substringDescription) <NEW_LINE> <DEDENT> def getJsonableObject(self): <NEW_LINE> <INDENT> return OrderedDict([("class", "SubstringEmbeddableGenerator"), ("substringGenerator", self.substringGenerator.getJsonableObject())]) | Generates a :class:`.StringEmbeddable`
Calls ``substringGenerator``, wraps the result in
a :class:`.StringEmbeddable` and returns it.
Arguments:
substringGenerator: instance of :class:`.AbstractSubstringGenerator` | 6259906f92d797404e3897a8 |
class BaseConfig: <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> TESTING = False <NEW_LINE> SECRET_KEY = "PB3aGvTmCkzaLGRAxDc3aMayKTPTDd5usT8gw4pCmKOk5AlJjh12pTrnNgQyOHCH" <NEW_LINE> DEBUG_TB_ENABLED = False <NEW_LINE> DEBUG_TB_INTERCEPT_REDIRECTS = False | Base configuration | 6259906f2ae34c7f260ac984 |
class Background(Effect): <NEW_LINE> <INDENT> def __init__(self, screen, bg=0, **kwargs): <NEW_LINE> <INDENT> super(Background, self).__init__(screen, **kwargs) <NEW_LINE> self._bg = bg <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _update(self, frame_no): <NEW_LINE> <INDENT> for y in range(self._screen.height): <NEW_LINE> <INDENT> self._screen.print_at(" " * self._screen.width, 0, y, bg=self._bg) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def frame_update_count(self): <NEW_LINE> <INDENT> return 1000000 <NEW_LINE> <DEDENT> @property <NEW_LINE> def stop_frame(self): <NEW_LINE> <INDENT> return self._stop_frame | Effect to be used as a Desktop background. This sets the background to the specified
colour. | 6259906f460517430c432ca4 |
class NetworkServer(NetworkPlayer): <NEW_LINE> <INDENT> def __init__(self,name="玩家1",parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.name = name <NEW_LINE> self.ser_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> try: <NEW_LINE> <INDENT> self.ser_socket.bind(("0.0.0.0", 30018)) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> print("监听失败",e) <NEW_LINE> QMessageBox.information(self,"消息","端口已经被占用,请重试") <NEW_LINE> <DEDENT> self.ser_socket.listen(8) <NEW_LINE> th = threading.Thread(target=self.start_listen) <NEW_LINE> th.start() <NEW_LINE> <DEDENT> def start_listen(self): <NEW_LINE> <INDENT> print("start listening ") <NEW_LINE> while self.is_connect: <NEW_LINE> <INDENT> sock, addr = self.ser_socket.accept() <NEW_LINE> self.tcp_socket = sock <NEW_LINE> self.tcp_socket.sendall( ( json.dumps( {"msg": "name", "data": self.name} ) + " END" ).encode() ) <NEW_LINE> self.recv_data(self.tcp_socket) | 运行服务端游戏界面 | 6259906f1f5feb6acb16448c |
class CycleCallback(Callback): <NEW_LINE> <INDENT> def __init__(self, optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, init_iter=0, init_lr=0, interpolate='linear'): <NEW_LINE> <INDENT> self.max_lr = max_lr <NEW_LINE> self.min_lr = min_lr <NEW_LINE> self.cycles = cycles <NEW_LINE> self.cycle_len = cycle_len <NEW_LINE> self.cycle_mult = cycle_mult <NEW_LINE> self.init_iter = init_iter <NEW_LINE> self.init_lr = init_lr <NEW_LINE> if cycle_mult > 1: <NEW_LINE> <INDENT> self.epochs = self.cycle_len * (self.cycle_mult ** self.cycles - 1) // (self.cycle_mult - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.epochs = self.cycle_mult * self.cycles <NEW_LINE> <DEDENT> self.optimizer = optimizer <NEW_LINE> self.interpolate = interpolate <NEW_LINE> self.cycle_dict, self.cycle_lengths, self.cycle_starts = self._init_cycle_dict() <NEW_LINE> <DEDENT> def _init_cycle_dict(self): <NEW_LINE> <INDENT> dict_arr = np.zeros(self.epochs, dtype=int) <NEW_LINE> length_arr = np.zeros(self.epochs, dtype=int) <NEW_LINE> start_arr = np.zeros(self.epochs, dtype=int) <NEW_LINE> c_len = self.cycle_len <NEW_LINE> idx = 0 <NEW_LINE> for i in range(self.cycles): <NEW_LINE> <INDENT> current_start = idx <NEW_LINE> for j in range(c_len): <NEW_LINE> <INDENT> dict_arr[idx] = i <NEW_LINE> length_arr[idx] = c_len <NEW_LINE> start_arr[idx] = current_start <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> c_len *= self.cycle_mult <NEW_LINE> <DEDENT> return dict_arr, length_arr, start_arr <NEW_LINE> <DEDENT> def on_batch_begin(self, batch_info: BatchInfo): <NEW_LINE> <INDENT> cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1] <NEW_LINE> cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1] <NEW_LINE> numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number <NEW_LINE> denominator = cycle_length * batch_info.batches_per_epoch <NEW_LINE> interpolation_number = numerator / denominator <NEW_LINE> if cycle_start == 0 and numerator < self.init_iter: <NEW_LINE> <INDENT> lr = self.init_lr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(self.max_lr, list): <NEW_LINE> <INDENT> lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate) <NEW_LINE> <DEDENT> <DEDENT> self.set_lr(lr) <NEW_LINE> <DEDENT> def set_lr(self, lr): <NEW_LINE> <INDENT> if isinstance(lr, list): <NEW_LINE> <INDENT> for group_lr, param_group in zip(lr, self.optimizer.param_groups): <NEW_LINE> <INDENT> param_group['lr'] = group_lr <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for param_group in self.optimizer.param_groups: <NEW_LINE> <INDENT> param_group['lr'] = lr | A callback that manages setting the proper learning rate | 6259906f38b623060ffaa4a1 |
class Unbaser(object): <NEW_LINE> <INDENT> ALPHABET = { 56: '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz', 59: '0123456789abcdefghijklmnopqrstuvwABCDEFGHIJKLMNOPQRSTUVWXYZ', 64: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/', 95: (' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ' '[\]^_`abcdefghijklmnopqrstuvwxyz{|}~') } <NEW_LINE> def __init__(self, base): <NEW_LINE> <INDENT> self.base = base <NEW_LINE> if 2 <= base <= 36: <NEW_LINE> <INDENT> self.unbase = lambda string: int(string, base) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.ALPHABET = self.ALPHABET[base] if base in self.ALPHABET else self.ALPHABET[64][0:base] <NEW_LINE> self.dictionary = dict((cipher, index) for index, cipher in enumerate(self.ALPHABET)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise TypeError('Unsupported base encoding.') <NEW_LINE> <DEDENT> self.unbase = self._dictunbaser <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, string): <NEW_LINE> <INDENT> return self.unbase(string) <NEW_LINE> <DEDENT> def _dictunbaser(self, string): <NEW_LINE> <INDENT> ret = 0 <NEW_LINE> for index, cipher in enumerate(string[::-1]): <NEW_LINE> <INDENT> ret += (self.base ** index) * self.dictionary[cipher] <NEW_LINE> <DEDENT> return ret | Functor for a given base. Will efficiently convert
strings to natural numbers. | 6259906f167d2b6e312b81dc |
class Device(models.Model): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.uuid <NEW_LINE> <DEDENT> uuid = models.CharField( db_index=True, max_length=64, unique=True, default=uuid.uuid4, editable=False, ) <NEW_LINE> user = models.OneToOneField( User, related_name="Hiccup_Device", on_delete=models.CASCADE, unique=True, ) <NEW_LINE> imei = models.CharField(max_length=32, null=True, blank=True) <NEW_LINE> board_date = models.DateTimeField(null=True, blank=True) <NEW_LINE> chipset = models.CharField(max_length=200, null=True, blank=True) <NEW_LINE> tags = TaggableManager(blank=True) <NEW_LINE> last_heartbeat = models.DateTimeField(null=True, blank=True) <NEW_LINE> token = models.CharField(max_length=200, null=True, blank=True) <NEW_LINE> next_per_crashreport_key = models.PositiveIntegerField(default=1) <NEW_LINE> next_per_heartbeat_key = models.PositiveIntegerField(default=1) <NEW_LINE> @transaction.atomic <NEW_LINE> def get_crashreport_key(self): <NEW_LINE> <INDENT> device = Device.objects.select_for_update().get(id=self.id) <NEW_LINE> ret = device.next_per_crashreport_key <NEW_LINE> device.next_per_crashreport_key += 1 <NEW_LINE> device.save() <NEW_LINE> return ret <NEW_LINE> <DEDENT> @transaction.atomic <NEW_LINE> def get_heartbeat_key(self): <NEW_LINE> <INDENT> device = Device.objects.select_for_update().get(id=self.id) <NEW_LINE> ret = device.next_per_heartbeat_key <NEW_LINE> device.next_per_heartbeat_key += 1 <NEW_LINE> device.save() <NEW_LINE> return ret | A device representing a phone that has been registered on Hiccup. | 6259906f56b00c62f0fb4169 |
class UsualDiaryOneSubject: <NEW_LINE> <INDENT> def __init__(self, name: str, subject_type: str, time: str, homework: str, marks: str) -> None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = subject_type <NEW_LINE> self.time = time <NEW_LINE> self.homework = homework <NEW_LINE> self.marks = marks <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return f'{self.name}, Type: {self.type}, Time: {self.time}, Homework: {self.homework}, Marks: {self.marks}' | Class representing one subject in user diary
Arguments
---------
name: str
Name of the subject
type: str
Type of the lesson (intramural, extramural)
time: str
Time of the lesson (8:00 - 8:45)
homework: str
Homework for this lesson
marks: str
Marks for that lesson
Returns
-------
None | 6259906f1f037a2d8b9e54b8 |
class NuclearPleomorphism(OneFieldPerReport): <NEW_LINE> <INDENT> __version__ = 'NuclearPleomorphism1.0' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(NuclearPleomorphism, self).__init__() <NEW_LINE> self.field_name = 'NuclearPleomorphism' <NEW_LINE> self.regex = r'Nuclear Pleomorphism:[\s]+([123\-]+)[\s]+point' <NEW_LINE> self.confidence = .75 <NEW_LINE> self.match_style = 'first' <NEW_LINE> self.table = gb.PATHOLOGY_TABLE <NEW_LINE> self.value_type = 'match' <NEW_LINE> self.good_section = r'SUMMARY CANCER|DIAGNOSIS' | find the invasive nuclear pleomorphism in the templated pathology report | 6259906f71ff763f4b5e9043 |
class LinkedList: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__root = None <NEW_LINE> <DEDENT> def get_root(self): <NEW_LINE> <INDENT> return self.__root <NEW_LINE> <DEDENT> def add_to_list(self, node): <NEW_LINE> <INDENT> if self.__root: <NEW_LINE> <INDENT> node.set_next(self.__root) <NEW_LINE> <DEDENT> self.__root = node <NEW_LINE> <DEDENT> def print_list(self): <NEW_LINE> <INDENT> marker = self.__root <NEW_LINE> while marker: <NEW_LINE> <INDENT> marker.print_details() <NEW_LINE> marker = marker.get_next() <NEW_LINE> <DEDENT> <DEDENT> def find(self, name): <NEW_LINE> <INDENT> marker = self.__root <NEW_LINE> while marker: <NEW_LINE> <INDENT> if marker.name == name: <NEW_LINE> <INDENT> return marker <NEW_LINE> <DEDENT> marker = marker.get_next() <NEW_LINE> <DEDENT> raise LookupError(f"Name {name} not found") | This class is the one you should be modifying!
Don't change the name of the class or any of the methods.
Implement those methods that current raise a NotImplementedError | 6259906f44b2445a339b75ac |
class MustDoHistory(models.Model): <NEW_LINE> <INDENT> date = models.DateField() <NEW_LINE> category_link = models.ForeignKey('MustDoCategories', related_name='history') <NEW_LINE> done = models.BooleanField(default=False) | the combination of start date and schedule will populate this field. | 6259906ff548e778e596ce28 |
class QueryView(View): <NEW_LINE> <INDENT> def get(self, request, task_id): <NEW_LINE> <INDENT> result_object = AsyncResult(task_id) <NEW_LINE> response = { 'status': result_object.state } <NEW_LINE> if result_object.successful(): <NEW_LINE> <INDENT> response['output'] = result_object.result <NEW_LINE> <DEDENT> return JsonResponse(response) | Given a task id, queries the status of the associated task. | 6259906f627d3e7fe0e08723 |
class Actions(ActionsBase): <NEW_LINE> <INDENT> def configure(self,**args): <NEW_LINE> <INDENT> self.jp_instance.hrd.applyOnFile( path="/opt/elasticsearch/config/elasticsearch.yml", additionalArgs={}) <NEW_LINE> return True | process for install
-------------------
step1: prepare actions
step2: check_requirements action
step3: download files & copy on right location (hrd info is used)
step4: configure action
step5: check_uptime_local to see if process stops (uses timeout $process.stop.timeout)
step5b: if check uptime was true will do stop action and retry the check_uptime_local check
step5c: if check uptime was true even after stop will do halt action and retry the check_uptime_local check
step6: use the info in the hrd to start the application
step7: do check_uptime_local to see if process starts
step7b: do monitor_local to see if package healthy installed & running
step7c: do monitor_remote to see if package healthy installed & running, but this time test is done from central location | 6259906fbe8e80087fbc092a |
class WalmartModel(models.Model): <NEW_LINE> <INDENT> upc = models.CharField(unique=True,max_length=50) <NEW_LINE> salePrice = models.DecimalField(decimal_places=2,max_digits=12) <NEW_LINE> name = models.CharField(max_length=10000) <NEW_LINE> brandName = models.CharField(max_length=10000) <NEW_LINE> modelNumber = models.CharField(max_length=10000) <NEW_LINE> largeImage = models.CharField(max_length=10000) <NEW_LINE> stock = models.CharField(max_length=60) <NEW_LINE> freeShippingOver50Dollars = models.BooleanField() <NEW_LINE> date_modified = models.DateTimeField() | Collection walmart data | 6259906fa219f33f346c80a5 |
class IndexPageTest(TestCase): <NEW_LINE> <INDENT> def test_index_page_renders_index_template(self): <NEW_LINE> <INDENT> response = self.client.get('/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, 'index.html') | 测试index登录首页 | 6259906f3317a56b869bf192 |
class OptionDialog(dialogs.FancyPopup): <NEW_LINE> <INDENT> def __init__(self, parent, playback): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> layout = QtWidgets.QVBoxLayout(self) <NEW_LINE> hLayout = QtWidgets.QHBoxLayout() <NEW_LINE> layout.addLayout(hLayout) <NEW_LINE> hLayout.addWidget(QtWidgets.QLabel(self.tr("Backend:"))) <NEW_LINE> backendChooser = profilesgui.ProfileComboBox(profiles.category('playback'), default=playback.backend) <NEW_LINE> backendChooser.profileChosen.connect(playback.setBackend) <NEW_LINE> hLayout.addWidget(backendChooser) <NEW_LINE> hLayout.addStretch() <NEW_LINE> layout.addStretch() | Dialog for the option button in the playlist's (dock widget) title bar. | 6259906f7c178a314d78e839 |
class capture_output(object): <NEW_LINE> <INDENT> stdout = True <NEW_LINE> stderr = True <NEW_LINE> display = True <NEW_LINE> def __init__(self, stdout=True, stderr=True, display=True): <NEW_LINE> <INDENT> self.stdout = stdout <NEW_LINE> self.stderr = stderr <NEW_LINE> self.display = display <NEW_LINE> self.shell = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> from IPython.core.getipython import get_ipython <NEW_LINE> from IPython.core.displaypub import CapturingDisplayPublisher <NEW_LINE> from IPython.core.displayhook import CapturingDisplayHook <NEW_LINE> self.sys_stdout = sys.stdout <NEW_LINE> self.sys_stderr = sys.stderr <NEW_LINE> if self.display: <NEW_LINE> <INDENT> self.shell = get_ipython() <NEW_LINE> if self.shell is None: <NEW_LINE> <INDENT> self.save_display_pub = None <NEW_LINE> self.display = False <NEW_LINE> <DEDENT> <DEDENT> stdout = stderr = outputs = None <NEW_LINE> if self.stdout: <NEW_LINE> <INDENT> stdout = sys.stdout = StringIO() <NEW_LINE> <DEDENT> if self.stderr: <NEW_LINE> <INDENT> stderr = sys.stderr = StringIO() <NEW_LINE> <DEDENT> if self.display: <NEW_LINE> <INDENT> self.save_display_pub = self.shell.display_pub <NEW_LINE> self.shell.display_pub = CapturingDisplayPublisher() <NEW_LINE> outputs = self.shell.display_pub.outputs <NEW_LINE> self.save_display_hook = sys.displayhook <NEW_LINE> sys.displayhook = CapturingDisplayHook(shell=self.shell, outputs=outputs) <NEW_LINE> <DEDENT> return CapturedIO(stdout, stderr, outputs) <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> sys.stdout = self.sys_stdout <NEW_LINE> sys.stderr = self.sys_stderr <NEW_LINE> if self.display and self.shell: <NEW_LINE> <INDENT> self.shell.display_pub = self.save_display_pub <NEW_LINE> sys.displayhook = self.save_display_hook | context manager for capturing stdout/err | 6259906f4428ac0f6e659dd0 |
class Rds(): <NEW_LINE> <INDENT> def __init__(self, host, port, db): <NEW_LINE> <INDENT> self.rds = Redis(host = host, port = port, db = db) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getLocal(): <NEW_LINE> <INDENT> obj = Rds('127.0.0.1', 6379, 1) <NEW_LINE> return obj.rds <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getRds(): <NEW_LINE> <INDENT> env = C.get('env') <NEW_LINE> host = C.get('rds_host_' + env) <NEW_LINE> db = C.get('rds_db_' + env) <NEW_LINE> obj = Rds(host, 6379, db) <NEW_LINE> return obj.rds <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getSender(): <NEW_LINE> <INDENT> return Rds.getRds() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getService(): <NEW_LINE> <INDENT> rds = Rds.getRds() <NEW_LINE> return rds.pubsub() | Redis封装 | 6259906f2ae34c7f260ac986 |
class StatefulServiceReplicaHealthState(ReplicaHealthState): <NEW_LINE> <INDENT> _validation = { 'service_kind': {'required': True}, } <NEW_LINE> _attribute_map = { 'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'}, 'partition_id': {'key': 'PartitionId', 'type': 'str'}, 'service_kind': {'key': 'ServiceKind', 'type': 'str'}, 'replica_id': {'key': 'ReplicaId', 'type': 'str'}, } <NEW_LINE> def __init__(self, aggregated_health_state=None, partition_id=None, replica_id=None): <NEW_LINE> <INDENT> super(StatefulServiceReplicaHealthState, self).__init__(aggregated_health_state=aggregated_health_state, partition_id=partition_id) <NEW_LINE> self.replica_id = replica_id <NEW_LINE> self.service_kind = 'Stateful' | Represents the health state of the stateful service replica, which contains
the replica id and the aggregated health state.
:param aggregated_health_state: Possible values include: 'Invalid', 'Ok',
'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str or :class:`enum
<azure.servicefabric.models.enum>`
:param partition_id:
:type partition_id: str
:param service_kind: Polymorphic Discriminator
:type service_kind: str
:param replica_id:
:type replica_id: str | 6259906f9c8ee82313040dd6 |
class SquareXianchangyaoCases(TestCase): <NEW_LINE> <INDENT> def tearDown(self): <NEW_LINE> <INDENT> self.reset.clearData() <NEW_LINE> self.driver.quit() <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.logger = Logger() <NEW_LINE> self.driver = AppiumDriver(None, None, IDC.platformName, IDC.platformVersion, IDC.deviceName, IDC.driverUrl, IDC.bundleId, IDC.udid).getDriver() <NEW_LINE> self.reset = ClearAppData(self.driver) <NEW_LINE> self.reset.clearData() <NEW_LINE> testPrepare = TestPrepare(testcase = self , driver = self.driver , logger = self.logger) <NEW_LINE> testPrepare.prepare(False) <NEW_LINE> <DEDENT> def test_case(self): <NEW_LINE> <INDENT> dashboardPage = DashboardPage(self, self.driver, self.logger) <NEW_LINE> squarePage = SquareModulePage(self, self.driver, self.logger) <NEW_LINE> xianchangyao = XianchangyaoPage(self, self.driver, self.logger) <NEW_LINE> dashboardPage.validSelf() <NEW_LINE> dashboardPage.clickOnSquareModule() <NEW_LINE> squarePage.validSelf() <NEW_LINE> squarePage.clickOnXianchangyao() <NEW_LINE> xianchangyao.validSelf() <NEW_LINE> xianchangyao.clickOnShakingImage() <NEW_LINE> xianchangyao.waitBySeconds(10) <NEW_LINE> xianchangyao.validShakingResult() | 作者 刘涛
广场现场摇 | 625990703539df3088ecdb39 |
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User, on_delete=models.CASCADE) <NEW_LINE> dob = models.DateField(blank=True, null=True) <NEW_LINE> nickname = models.CharField(max_length=30, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'UserProfile' | A Profile Model for creating and updating User profile | 625990707047854f46340c55 |
class Command(CeleryCommand): <NEW_LINE> <INDENT> help = "celery control utility" <NEW_LINE> keep_base_opts = False <NEW_LINE> def run_from_argv(self, argv): <NEW_LINE> <INDENT> util = celeryctl(app=app) <NEW_LINE> util.execute_from_commandline(self.handle_default_options(argv)[1:]) | Run the celery control utility. | 625990701f037a2d8b9e54b9 |
class DirectedEdgeStar(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._outEdges = [] <NEW_LINE> self._sorted = False <NEW_LINE> <DEDENT> def sortEdges(self): <NEW_LINE> <INDENT> if not self._sorted: <NEW_LINE> <INDENT> self._outEdges = sorted(self._outEdges, key=lambda de: de.angle) <NEW_LINE> self._sorted = True <NEW_LINE> <DEDENT> <DEDENT> def add(self, de): <NEW_LINE> <INDENT> self._outEdges.append(de) <NEW_LINE> self._sorted = False <NEW_LINE> <DEDENT> def remove(self, de): <NEW_LINE> <INDENT> for i, outEdge in enumerate(self._outEdges): <NEW_LINE> <INDENT> if outEdge is de: <NEW_LINE> <INDENT> self._outEdges.pop(i) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def degree(self): <NEW_LINE> <INDENT> return len(self._outEdges) <NEW_LINE> <DEDENT> @property <NEW_LINE> def coord(self): <NEW_LINE> <INDENT> if len(self._outEdges) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._outEdges[0].coord <NEW_LINE> <DEDENT> @property <NEW_LINE> def edges(self): <NEW_LINE> <INDENT> self.sortEdges() <NEW_LINE> return self._outEdges <NEW_LINE> <DEDENT> def getIndex(self, i): <NEW_LINE> <INDENT> if type(i).__name__ == 'int': <NEW_LINE> <INDENT> maxi = len(self._outEdges) <NEW_LINE> modi = i % maxi <NEW_LINE> if modi < 0: <NEW_LINE> <INDENT> modi += maxi <NEW_LINE> <DEDENT> return modi <NEW_LINE> <DEDENT> elif type(i).__name__ == 'DirectedEdge': <NEW_LINE> <INDENT> self.sortEdges() <NEW_LINE> return self._outEdges.index(i) <NEW_LINE> <DEDENT> <DEDENT> def getNextEdge(self, dirEdge): <NEW_LINE> <INDENT> i = self.getIndex(dirEdge) <NEW_LINE> return self._outEdges[self.getIndex(i + 1)] | * A sorted collection of DirectedEdge which leave a Node in a PlanarGraph. | 62599070fff4ab517ebcf0b8 |
class ThreadWithExceptions(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ThreadWithExceptions, self).__init__(*args, **kwargs) <NEW_LINE> self.exception = None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.RunWithExceptions() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.exception = ('Exception occured in thread %s:\n%s' % (self.ident, traceback.format_exc())) <NEW_LINE> <DEDENT> <DEDENT> def RunWithExceptions(self): <NEW_LINE> <INDENT> super(ThreadWithExceptions, self).run() <NEW_LINE> <DEDENT> def join(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ThreadWithExceptions, self).join(*args, **kwargs) <NEW_LINE> if self.exception: <NEW_LINE> <INDENT> raise errors.VmUtil.ThreadException(self.exception) | Extension of threading.Thread that propagates exceptions on join. | 6259907097e22403b383c7a1 |
class PrivateIngredientsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> self.user = get_user_model().objects.create_user( '[email protected]', 'testpass' ) <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_ingredient_list(self): <NEW_LINE> <INDENT> Ingredient.objects.create(user=self.user, name='Kale') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Salt') <NEW_LINE> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> ingredients = Ingredient.objects.all().order_by('-name') <NEW_LINE> serializer = IngredientSerializer(ingredients, many=True) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, serializer.data) <NEW_LINE> <DEDENT> def test_ingredients_limited_to_user(self): <NEW_LINE> <INDENT> user2 = get_user_model().objects.create_user( '[email protected]', 'testpass' ) <NEW_LINE> Ingredient.objects.create(user=user2, name='Vinegar') <NEW_LINE> ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') <NEW_LINE> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(res.data), 1) <NEW_LINE> self.assertEqual(res.data[0]['name'], ingredient.name) <NEW_LINE> <DEDENT> def test_create_ingredient_successful(self): <NEW_LINE> <INDENT> payload = {'name': 'Cabbage'} <NEW_LINE> self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> exists = Ingredient.objects.filter( user=self.user, name=payload['name'], ).exists() <NEW_LINE> self.assertTrue(exists) <NEW_LINE> <DEDENT> def test_create_ingredient_invalid(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> res = self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_retrieve_ingredients_assigned_to_recipes(self): <NEW_LINE> <INDENT> ingredient1 = Ingredient.objects.create( user=self.user, name='Apples' ) <NEW_LINE> ingredient2 = Ingredient.objects.create( user=self.user, name='Turkey' ) <NEW_LINE> recipe = Recipe.objects.create( title='Apple crumble', time_minutes=5, price=10, user=self.user ) <NEW_LINE> recipe.ingredients.add(ingredient1) <NEW_LINE> res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1}) <NEW_LINE> serializer1 = IngredientSerializer(ingredient1) <NEW_LINE> serializer2 = IngredientSerializer(ingredient2) <NEW_LINE> self.assertIn(serializer1.data, res.data) <NEW_LINE> self.assertNotIn(serializer2.data, res.data) <NEW_LINE> <DEDENT> def test_retrieve_ingredients_assigned_unique(self): <NEW_LINE> <INDENT> ingredient = Ingredient.objects.create(user=self.user, name='Eggs') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Cheese') <NEW_LINE> recipe1 = Recipe.objects.create( title='Eggs benedict', time_minutes=30, price=12.00, user=self.user ) <NEW_LINE> recipe1.ingredients.add(ingredient) <NEW_LINE> recipe2 = Recipe.objects.create( title='Coriander eggs on toast', time_minutes=20, price=5.00, user=self.user ) <NEW_LINE> recipe2.ingredients.add(ingredient) <NEW_LINE> res = self.client.get(INGREDIENTS_URL, {'assigned_only': 1}) <NEW_LINE> self.assertEqual(len(res.data), 1) | Test the private ingredients API | 62599070e1aae11d1e7cf45b |
class CalculatorType(Enum): <NEW_LINE> <INDENT> MATLAB, OCTAVE, REMOTE = range(3) | Enum used to specify the type of NATLAB client to build | 62599070dd821e528d6da5d0 |
class TempDirectoryPath(str): <NEW_LINE> <INDENT> def __enter__(self) -> "TempDirectoryPath": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__( self, _exc: Optional[Type[BaseException]], _value: Optional[Exception], _tb: Optional[TracebackType], ) -> bool: <NEW_LINE> <INDENT> if os.path.exists(self): <NEW_LINE> <INDENT> shutil.rmtree(self) | Represents a path to an temporary directory. When used as a context
manager, it erases the contents of the directory on exit. | 625990703317a56b869bf193 |
class Lexical(restService): <NEW_LINE> <INDENT> def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None, do_error=False): <NEW_LINE> <INDENT> if basePath is None: <NEW_LINE> <INDENT> basePath = BASEPATH <NEW_LINE> <DEDENT> self._basePath = basePath <NEW_LINE> self._verbose = verbose <NEW_LINE> super().__init__(cache=cache, safe_cache=safe_cache, key=key, do_error=do_error) <NEW_LINE> <DEDENT> def getChunks(self, text, output='application/json'): <NEW_LINE> <INDENT> kwargs = {'text': text} <NEW_LINE> kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()} <NEW_LINE> param_rest = self._make_rest(None, **kwargs) <NEW_LINE> url = self._basePath + ('/lexical/chunks').format(**kwargs) <NEW_LINE> requests_params = kwargs <NEW_LINE> output = self._get('GET', url, requests_params, output) <NEW_LINE> return output if output else [] <NEW_LINE> <DEDENT> def getEntities(self, text, output='application/json'): <NEW_LINE> <INDENT> kwargs = {'text': text} <NEW_LINE> kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()} <NEW_LINE> param_rest = self._make_rest(None, **kwargs) <NEW_LINE> url = self._basePath + ('/lexical/entities').format(**kwargs) <NEW_LINE> requests_params = kwargs <NEW_LINE> output = self._get('GET', url, requests_params, output) <NEW_LINE> return output if output else [] <NEW_LINE> <DEDENT> def getPos(self, text, output='application/json'): <NEW_LINE> <INDENT> kwargs = {'text': text} <NEW_LINE> kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()} <NEW_LINE> param_rest = self._make_rest(None, **kwargs) <NEW_LINE> url = self._basePath + ('/lexical/pos').format(**kwargs) <NEW_LINE> requests_params = kwargs <NEW_LINE> output = self._get('GET', url, requests_params, output) <NEW_LINE> return output if output else [] <NEW_LINE> <DEDENT> def getSentences(self, text, output='application/json'): <NEW_LINE> <INDENT> kwargs = {'text': text} <NEW_LINE> kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()} <NEW_LINE> param_rest = self._make_rest(None, **kwargs) <NEW_LINE> url = self._basePath + ('/lexical/sentences').format(**kwargs) <NEW_LINE> requests_params = kwargs <NEW_LINE> output = self._get('GET', url, requests_params, output) <NEW_LINE> return output if output else [] | Lexical services | 625990704f88993c371f116f |
class ReluLayer(Layer): <NEW_LINE> <INDENT> def fprop(self, inputs): <NEW_LINE> <INDENT> return np.maximum(0., inputs) <NEW_LINE> <DEDENT> def bprop(self, inputs, outputs, grads_wrt_outputs): <NEW_LINE> <INDENT> return (outputs > 0.) * grads_wrt_outputs <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'ReluLayer' | Layer implementing an element-wise rectified linear transformation. | 62599070d268445f2663a7ac |
class OpenLatchImpl(AbstractCommandImpl[OpenLatchParams, OpenLatchResult]): <NEW_LINE> <INDENT> def __init__( self, state_view: StateView, hardware_api: HardwareControlAPI, **unused_dependencies: object, ) -> None: <NEW_LINE> <INDENT> self._state_view = state_view <NEW_LINE> self._hardware_api = hardware_api <NEW_LINE> <DEDENT> async def execute(self, params: OpenLatchParams) -> OpenLatchResult: <NEW_LINE> <INDENT> hs_module_view = self._state_view.modules.get_heater_shaker_module_view( module_id=params.moduleId ) <NEW_LINE> hs_hardware_module = hs_module_view.find_hardware( attached_modules=self._hardware_api.attached_modules ) <NEW_LINE> if hs_hardware_module is not None: <NEW_LINE> <INDENT> await hs_hardware_module.open_labware_latch() <NEW_LINE> <DEDENT> return OpenLatchResult() | Execution implementation of a Heater-Shaker's open latch command. | 625990702ae34c7f260ac988 |
class equilibrium(osv.osv): <NEW_LINE> <INDENT> _name = 'interview.equilibrium' <NEW_LINE> def _perform_equilibrium(self, cr, uid, ids, fields_name, arg, context=None): <NEW_LINE> <INDENT> res = {} <NEW_LINE> result = "" <NEW_LINE> for i in ids: <NEW_LINE> <INDENT> A = [int(x) for x in self.browse(cr, uid, ids)[0].list.split(',')] <NEW_LINE> minDiff = sys.maxint <NEW_LINE> diff = minDiff <NEW_LINE> for j in range(1, len(A)): <NEW_LINE> <INDENT> first = A[:j] <NEW_LINE> second = A[j:] <NEW_LINE> diff = abs(sum(first) - sum(second)) <NEW_LINE> if diff < minDiff: <NEW_LINE> <INDENT> minDiff = diff <NEW_LINE> <DEDENT> <DEDENT> res[i] = minDiff <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> _columns = { 'name': fields.char("Name",size=128,required=True), 'list': fields.char("List",size=128,required=True), 'result': fields.function(_perform_equilibrium, type="integer", method=True, store=True, string="Result") } | A equilibrium model | 6259907038b623060ffaa4a3 |
class LogModel(QtWidgets.QFileSystemModel): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(LogModel, self).__init__() <NEW_LINE> <DEDENT> def columnCount(self, parent = QtCore.QModelIndex()): <NEW_LINE> <INDENT> return super(LogModel, self).columnCount()+1 <NEW_LINE> <DEDENT> def data(self, index, role): <NEW_LINE> <INDENT> if index.column() == self.columnCount() - 1: <NEW_LINE> <INDENT> if role == Qt.DisplayRole: <NEW_LINE> <INDENT> filePath = self.filePath(index) <NEW_LINE> if os.path.isfile(filePath): <NEW_LINE> <INDENT> with open(filePath) as json_data: <NEW_LINE> <INDENT> fileContents = json.load(json_data) <NEW_LINE> <DEDENT> return fileContents["recipeName"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = self.filePath(index) <NEW_LINE> position = path.rfind("/") <NEW_LINE> return path[position+1:] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return super(LogModel, self).data(index, role) | A Subclass of QFileSystemModel to add a column. | 6259907076e4537e8c3f0e23 |
class AuthenticationForm(forms.Form): <NEW_LINE> <INDENT> email = forms.EmailField( label=_("Email address"), max_length=254, widget=forms.EmailInput(attrs={'autofocus': True}), ) <NEW_LINE> password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) <NEW_LINE> error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } <NEW_LINE> def __init__(self, request=None, *args, **kwargs): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.user_cache = None <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> self.username_field = UserModel._meta.get_field( UserModel.USERNAME_FIELD) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> email = self.cleaned_data.get('email') <NEW_LINE> password = self.cleaned_data.get('password') <NEW_LINE> if email and password: <NEW_LINE> <INDENT> self.user_cache = authenticate( self.request, email=email, password=password) <NEW_LINE> if self.user_cache is None: <NEW_LINE> <INDENT> if django.VERSION < (2, 1): <NEW_LINE> <INDENT> raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) <NEW_LINE> <DEDENT> raise self.get_invalid_login_error() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.confirm_login_allowed(self.user_cache) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data <NEW_LINE> <DEDENT> def confirm_login_allowed(self, user): <NEW_LINE> <INDENT> if not user.is_active: <NEW_LINE> <INDENT> raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) <NEW_LINE> <DEDENT> <DEDENT> if django.VERSION < (2, 1): <NEW_LINE> <INDENT> def get_user_id(self): <NEW_LINE> <INDENT> if self.user_cache: <NEW_LINE> <INDENT> return self.user_cache.id <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_user(self): <NEW_LINE> <INDENT> return self.user_cache <NEW_LINE> <DEDENT> if django.VERSION >= (2, 1): <NEW_LINE> <INDENT> def get_invalid_login_error(self): <NEW_LINE> <INDENT> return forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) | Base class for authenticating users. Extend this to get a form that accepts
email/password logins. | 62599070796e427e53850017 |
class DbTest(BaseTest): <NEW_LINE> <INDENT> def test_select_db(self): <NEW_LINE> <INDENT> bloom = pyreBloom.pyreBloom(self.KEY, self.CAPACITY, self.ERROR_RATE, db=1) <NEW_LINE> samples = sample_strings(20, 100) <NEW_LINE> self.bloom.extend(samples) <NEW_LINE> self.assertEqual(len(bloom.contains(samples)), 0) | Make sure we can select a database | 62599070aad79263cf430055 |
class UnschedulableNodeError(RuntimeError): <NEW_LINE> <INDENT> log = True <NEW_LINE> fault_code = fault_code_counter.next() | Raise if an action isn't valid on a node marked "unscheduled" | 6259907044b2445a339b75ae |
class PlatformReport(models.Model): <NEW_LINE> <INDENT> date = models.DateField("Дата", default=datetime.now) <NEW_LINE> platform_id = models.IntegerField(verbose_name="Площадка") <NEW_LINE> video_id = models.CharField(verbose_name="Видео", max_length=32) <NEW_LINE> video_views = models.PositiveIntegerField("Количество показов видео", default=0, db_index=True) <NEW_LINE> adv_views = models.PositiveIntegerField("Количество показов рекламы", default=0, db_index=True) <NEW_LINE> income = models.DecimalField("Заработок", max_digits=12, decimal_places=4, default=Decimal("0.0000"), db_index=True) <NEW_LINE> approved = models.BooleanField("Отчет утвержден", default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "reports_platformreport" <NEW_LINE> verbose_name = "Отчет по площадке" <NEW_LINE> verbose_name_plural = "Отчеты по площадкам" <NEW_LINE> unique_together = ("date", "platform_id", "video_id") <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '[%s] pid=%s vid=%s' % (self.date, self.platform_id, self.video_id) | Данные отчетов по площадка.
| 62599070e1aae11d1e7cf45c |
class TFOptimizer(Optimizer, trackable.Trackable): <NEW_LINE> <INDENT> def __init__(self, optimizer, iterations=None): <NEW_LINE> <INDENT> self.optimizer = optimizer <NEW_LINE> self._track_trackable(optimizer, name='optimizer') <NEW_LINE> if iterations is None: <NEW_LINE> <INDENT> with K.name_scope(self.__class__.__name__): <NEW_LINE> <INDENT> self.iterations = K.variable(0, dtype='int64', name='iterations') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.iterations = iterations <NEW_LINE> <DEDENT> self._track_trackable(self.iterations, name='global_step') <NEW_LINE> <DEDENT> def _clip_gradients(self, grads): <NEW_LINE> <INDENT> return grads <NEW_LINE> <DEDENT> def apply_gradients(self, grads): <NEW_LINE> <INDENT> self.optimizer.apply_gradients(grads, global_step=self.iterations) <NEW_LINE> <DEDENT> def get_grads(self, loss, params): <NEW_LINE> <INDENT> return self.optimizer.compute_gradients(loss, params) <NEW_LINE> <DEDENT> def get_updates(self, loss, params): <NEW_LINE> <INDENT> if distribution_strategy_context.has_strategy(): <NEW_LINE> <INDENT> self.updates = [] <NEW_LINE> if not params: <NEW_LINE> <INDENT> grads = self.optimizer.compute_gradients(loss) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> grads = self.optimizer.compute_gradients(loss, params) <NEW_LINE> <DEDENT> global_step = training_util.get_global_step() <NEW_LINE> opt_update = self.optimizer.apply_gradients(grads, global_step) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not params: <NEW_LINE> <INDENT> self.updates = [state_ops.assign_add(self.iterations, 1)] <NEW_LINE> return self.updates <NEW_LINE> <DEDENT> self.updates = [] <NEW_LINE> grads = self.optimizer.compute_gradients(loss, params) <NEW_LINE> opt_update = self.optimizer.apply_gradients( grads, global_step=self.iterations) <NEW_LINE> <DEDENT> self.updates.append(opt_update) <NEW_LINE> return self.updates <NEW_LINE> <DEDENT> @property <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def from_config(self, config): <NEW_LINE> <INDENT> raise NotImplementedError | Wrapper class for native TensorFlow optimizers. | 625990703d592f4c4edbc780 |
class ProxyWorkerFinder(WorkerFinder): <NEW_LINE> <INDENT> def __init__(self, uuid, proxy, topics): <NEW_LINE> <INDENT> super(ProxyWorkerFinder, self).__init__() <NEW_LINE> self._proxy = proxy <NEW_LINE> self._topics = topics <NEW_LINE> self._workers = {} <NEW_LINE> self._uuid = uuid <NEW_LINE> self._proxy.dispatcher.type_handlers.update({ pr.NOTIFY: [ self._process_response, functools.partial(pr.Notify.validate, response=True), ], }) <NEW_LINE> self._counter = itertools.count() <NEW_LINE> <DEDENT> def _next_worker(self, topic, tasks, temporary=False): <NEW_LINE> <INDENT> if not temporary: <NEW_LINE> <INDENT> return TopicWorker(topic, tasks, identity=six.next(self._counter)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TopicWorker(topic, tasks) <NEW_LINE> <DEDENT> <DEDENT> @periodic.periodic(pr.NOTIFY_PERIOD) <NEW_LINE> def beat(self): <NEW_LINE> <INDENT> self._proxy.publish(pr.Notify(), self._topics, reply_to=self._uuid) <NEW_LINE> <DEDENT> def _total_workers(self): <NEW_LINE> <INDENT> return len(self._workers) <NEW_LINE> <DEDENT> def _add(self, topic, tasks): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> worker = self._workers[topic] <NEW_LINE> if worker == self._next_worker(topic, tasks, temporary=True): <NEW_LINE> <INDENT> return (worker, False) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> worker = self._next_worker(topic, tasks) <NEW_LINE> self._workers[topic] = worker <NEW_LINE> return (worker, True) <NEW_LINE> <DEDENT> def _process_response(self, response, message): <NEW_LINE> <INDENT> LOG.debug("Started processing notify message '%s'", ku.DelayedPretty(message)) <NEW_LINE> topic = response['topic'] <NEW_LINE> tasks = response['tasks'] <NEW_LINE> with self._cond: <NEW_LINE> <INDENT> worker, new_or_updated = self._add(topic, tasks) <NEW_LINE> if new_or_updated: <NEW_LINE> <INDENT> LOG.debug("Received notification about worker '%s' (%s" " total workers are currently known)", worker, self._total_workers()) <NEW_LINE> self._cond.notify_all() <NEW_LINE> <DEDENT> <DEDENT> if self.on_worker is not None and new_or_updated: <NEW_LINE> <INDENT> self.on_worker(worker) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> with self._cond: <NEW_LINE> <INDENT> self._workers.clear() <NEW_LINE> self._cond.notify_all() <NEW_LINE> <DEDENT> <DEDENT> def get_worker_for_task(self, task): <NEW_LINE> <INDENT> available_workers = [] <NEW_LINE> with self._cond: <NEW_LINE> <INDENT> for worker in six.itervalues(self._workers): <NEW_LINE> <INDENT> if worker.performs(task): <NEW_LINE> <INDENT> available_workers.append(worker) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if available_workers: <NEW_LINE> <INDENT> return self._match_worker(task, available_workers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Requests and receives responses about workers topic+task details. | 62599070a219f33f346c80a9 |
class CuttlefishCommonPkgInstaller(base_task_runner.BaseTaskRunner): <NEW_LINE> <INDENT> WELCOME_MESSAGE_TITLE = "Install cuttlefish-common packages on the host" <NEW_LINE> WELCOME_MESSAGE = ("This step will walk you through the cuttlefish-common " "packages installation for your host.") <NEW_LINE> def ShouldRun(self): <NEW_LINE> <INDENT> if not utils.IsSupportedPlatform(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not setup_common.PackageInstalled(_CUTTLEFISH_COMMOM_PKG): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _Run(self): <NEW_LINE> <INDENT> cf_common_path = os.path.join(tempfile.mkdtemp(), _CF_COMMOM_FOLDER) <NEW_LINE> logger.debug("cuttlefish-common path: %s", cf_common_path) <NEW_LINE> cmd = "\n".join(sub_cmd.format(git_folder=cf_common_path) for sub_cmd in _INSTALL_CUTTLEFISH_COMMOM_CMD) <NEW_LINE> if not utils.GetUserAnswerYes("\nStart to install cuttlefish-common :\n%s" "\nPress 'y' to continue or anything " "else to do it myself and run acloud " "again[y/N]: " % cmd): <NEW_LINE> <INDENT> sys.exit(constants.EXIT_BY_USER) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> setup_common.CheckCmdOutput(cmd, shell=True) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> shutil.rmtree(os.path.dirname(cf_common_path)) <NEW_LINE> <DEDENT> logger.info("Cuttlefish-common package installed now.") | Subtask base runner class for installing cuttlefish-common. | 625990708e7ae83300eea930 |
class Apparmor(Plugin, UbuntuPlugin): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.add_copy_specs([ "/etc/apparmor" ]) | Apparmor related information
| 6259907099cbb53fe6832789 |
class ReflexAgent(Agent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [self.evaluationFunction(gameState, action) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> "Add more of your code here if you want to" <NEW_LINE> return legalMoves[chosenIndex] <NEW_LINE> <DEDENT> def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> oldFood = currentGameState.getFood() <NEW_LINE> FoodList = oldFood.asList() <NEW_LINE> PacToFoodDisList = [] <NEW_LINE> for FoodPos in FoodList: <NEW_LINE> <INDENT> PacToFoodDis = manhattanDistance(FoodPos, newPos) <NEW_LINE> PacToFoodDisList.append(PacToFoodDis) <NEW_LINE> <DEDENT> PacToNearestFoodDis = min(PacToFoodDisList) <NEW_LINE> newGhostPos = currentGameState.getGhostPositions() <NEW_LINE> PacToGhostDistList = [] <NEW_LINE> for GhostPos in newGhostPos: <NEW_LINE> <INDENT> PacToGhostDis = manhattanDistance(GhostPos, newPos) <NEW_LINE> PacToGhostDistList.append(PacToGhostDis) <NEW_LINE> <DEDENT> PacToNearestGhostDis = min(PacToGhostDistList) <NEW_LINE> if successorGameState.isWin(): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if successorGameState.isLose(): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if PacToNearestFoodDis == 0: <NEW_LINE> <INDENT> return PacToNearestGhostDis <NEW_LINE> <DEDENT> evalue = 1.0 / PacToNearestFoodDis - 1.0 / PacToNearestGhostDis <NEW_LINE> return evalue | A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers. | 62599070435de62698e9d6a5 |
class WhooshBookmarks(object): <NEW_LINE> <INDENT> def __init__(self, db): <NEW_LINE> <INDENT> self.bookmarks_collection = db.bookmarks_col <NEW_LINE> self.webpages_collection = db.webpages_col <NEW_LINE> self.indexdir = "index" <NEW_LINE> self.indexname = "bookmarks" <NEW_LINE> self.schema = self.get_schema() <NEW_LINE> if not os.path.exists(self.indexdir): <NEW_LINE> <INDENT> os.mkdir(self.indexdir) <NEW_LINE> create_in(self.indexdir, self.schema, indexname=self.indexname) <NEW_LINE> <DEDENT> self.ix = open_dir(self.indexdir, indexname=self.indexname) <NEW_LINE> <DEDENT> def get_schema(self): <NEW_LINE> <INDENT> return Schema( nid=ID(unique=True, stored=True), url=ID(unique=True, stored=True), title=TEXT(phrase=False), tags=KEYWORD(lowercase=True, commas=True, scorable=True), note=TEXT(analyzer=analyzer), content=TEXT(stored=True, analyzer=analyzer) ) <NEW_LINE> <DEDENT> def rebuild_index(self): <NEW_LINE> <INDENT> ix = create_in(self.indexdir, self.schema, indexname=self.indexname) <NEW_LINE> writer = ix.writer() <NEW_LINE> for bookmark in self.bookmarks_collection.find(timeout=False): <NEW_LINE> <INDENT> webpage = self.webpages_collection.find_one({'_id': bookmark['webpage']}) <NEW_LINE> if webpage: <NEW_LINE> <INDENT> writer.update_document( nid=str(bookmark['_id']), url=bookmark['url'], title=bookmark['title'], tags=bookmark['tags'], note=bookmark['note'], content=webpage['content'] ) <NEW_LINE> <DEDENT> <DEDENT> writer.commit() <NEW_LINE> <DEDENT> def commit(self, writer): <NEW_LINE> <INDENT> writer.commit() <NEW_LINE> return True <NEW_LINE> <DEDENT> def update(self, bookmark, webpage, writer=None): <NEW_LINE> <INDENT> if writer is None: <NEW_LINE> <INDENT> writer = self.ix.writer() <NEW_LINE> <DEDENT> writer.update_document( nid=str(bookmark['_id']), url=bookmark['url'], title=bookmark['title'], tags=bookmark['tags'], note=bookmark['note'], content=webpage['content'] ) <NEW_LINE> writer.commit() <NEW_LINE> <DEDENT> def parse_query(self, query): <NEW_LINE> <INDENT> parser = qparser.MultifieldParser( ["url", "title", "tags", "note", "content"], self.ix.schema) <NEW_LINE> return parser.parse(query) <NEW_LINE> <DEDENT> def search(self, query, page): <NEW_LINE> <INDENT> results = [] <NEW_LINE> with self.ix.searcher() as searcher: <NEW_LINE> <INDENT> result_page = searcher.search_page( self.parse_query(query), page, pagelen=PAGE_SIZE) <NEW_LINE> for result in result_page: <NEW_LINE> <INDENT> results.append(dict(result)) <NEW_LINE> <DEDENT> <DEDENT> return {'results': results, 'total': result_page.total} <NEW_LINE> <DEDENT> def delele_by_url(self, url): <NEW_LINE> <INDENT> writer = self.ix.writer() <NEW_LINE> result = writer.delete_by_term('url', url) <NEW_LINE> writer.commit() <NEW_LINE> return result <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.ix.close() | Object utilising Whoosh (http://woosh.ca/) to create a search index of all
crawled rss feeds, parse queries and search the index for related mentions. | 6259907067a9b606de5476f3 |
class GridFSStorage(FileStorage): <NEW_LINE> <INDENT> def __init__(self, mongouri, collection='filedepot'): <NEW_LINE> <INDENT> self._cli = MongoClient(mongouri) <NEW_LINE> self._db = self._cli.get_default_database() <NEW_LINE> self._gridfs = gridfs.GridFS(self._db, collection=collection) <NEW_LINE> <DEDENT> def get(self, file_or_id): <NEW_LINE> <INDENT> fileid = self.fileid(file_or_id) <NEW_LINE> try: <NEW_LINE> <INDENT> gridout = self._gridfs.get(_check_file_id(fileid)) <NEW_LINE> <DEDENT> except gridfs.errors.NoFile: <NEW_LINE> <INDENT> raise IOError('File %s not existing' % fileid) <NEW_LINE> <DEDENT> return GridFSStoredFile(fileid, gridout) <NEW_LINE> <DEDENT> def create(self, content, filename=None, content_type=None): <NEW_LINE> <INDENT> content, filename, content_type = self.fileinfo(content, filename, content_type) <NEW_LINE> new_file_id = self._gridfs.put(content, filename=filename or 'unknown', content_type=content_type, last_modified=utils.timestamp()) <NEW_LINE> return str(new_file_id) <NEW_LINE> <DEDENT> def replace(self, file_or_id, content, filename=None, content_type=None): <NEW_LINE> <INDENT> fileid = self.fileid(file_or_id) <NEW_LINE> fileid = _check_file_id(fileid) <NEW_LINE> content, filename, content_type = self.fileinfo(content, filename, content_type) <NEW_LINE> if filename is None: <NEW_LINE> <INDENT> f = self.get(fileid) <NEW_LINE> filename = f.filename <NEW_LINE> content_type = f.content_type <NEW_LINE> <DEDENT> self._gridfs.delete(fileid) <NEW_LINE> new_file_id = self._gridfs.put(content, _id=fileid, filename=filename or 'unknown', content_type=content_type, last_modified=utils.timestamp()) <NEW_LINE> return str(new_file_id) <NEW_LINE> <DEDENT> def delete(self, file_or_id): <NEW_LINE> <INDENT> fileid = self.fileid(file_or_id) <NEW_LINE> fileid = _check_file_id(fileid) <NEW_LINE> self._gridfs.delete(fileid) <NEW_LINE> <DEDENT> def exists(self, file_or_id): <NEW_LINE> <INDENT> fileid = self.fileid(file_or_id) <NEW_LINE> fileid = _check_file_id(fileid) <NEW_LINE> return self._gridfs.exists(fileid) | :class:`depot.io.interfaces.FileStorage` implementation that stores files on MongoDB.
All the files are stored using GridFS to the database pointed by the ``mongouri`` parameter into
the collection named ``collection``. | 625990704a966d76dd5f078a |
class Rectangle: <NEW_LINE> <INDENT> number_of_instances = 0 <NEW_LINE> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.height = height <NEW_LINE> self.width = width <NEW_LINE> self.__class__.number_of_instances += 1 <NEW_LINE> <DEDENT> def __testInput(self, prop, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("{} must be an integer".format(prop)) <NEW_LINE> <DEDENT> elif value < 0: <NEW_LINE> <INDENT> raise ValueError("{} must be >= 0".format(prop)) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self._Rectangle__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if self.__testInput("width", value): <NEW_LINE> <INDENT> self._Rectangle__width = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self._Rectangle__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if self.__testInput("height", value): <NEW_LINE> <INDENT> self._Rectangle__height = value <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.width * self.height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.width + self.height) * 2 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join(["#" * self.width] * self.height) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> className = self.__class__.__name__ <NEW_LINE> return "{}({}, {})".format(className, self.width, self.height) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.__class__.number_of_instances -= 1 <NEW_LINE> print("Bye rectangle...") | class Rectangle that defines a rectangle | 625990708e7ae83300eea931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.