code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ChromeWindow(wx.Window): <NEW_LINE> <INDENT> def __init__(self, parent, url="", useTimer=True, timerMillis=DEFAULT_TIMER_MILLIS, browserSettings=None, size=(-1, -1), *args, **kwargs): <NEW_LINE> <INDENT> wx.Window.__init__(self, parent, id=wx.ID_ANY, size=size, *args, **kwargs) <NEW_LINE> self.timer = wx.Timer() <NEW_LINE> if platform.system() in ["Linux", "Darwin"]: <NEW_LINE> <INDENT> if url.startswith("/"): <NEW_LINE> <INDENT> url = "file://" + url <NEW_LINE> <DEDENT> <DEDENT> self.url = url <NEW_LINE> windowInfo = cefpython.WindowInfo() <NEW_LINE> if platform.system() == "Windows": <NEW_LINE> <INDENT> windowInfo.SetAsChild(self.GetHandle()) <NEW_LINE> <DEDENT> elif platform.system() == "Linux": <NEW_LINE> <INDENT> windowInfo.SetAsChild(self.GetGtkWidget()) <NEW_LINE> <DEDENT> elif platform.system() == "Darwin": <NEW_LINE> <INDENT> (width, height) = self.GetClientSizeTuple() <NEW_LINE> windowInfo.SetAsChild(self.GetHandle(), [0, 0, width, height]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Unsupported OS") <NEW_LINE> <DEDENT> if not browserSettings: <NEW_LINE> <INDENT> browserSettings = {} <NEW_LINE> <DEDENT> self.browser = cefpython.CreateBrowserSync(windowInfo, browserSettings=browserSettings, navigateUrl=url) <NEW_LINE> if platform.system() == "Windows": <NEW_LINE> <INDENT> self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) <NEW_LINE> self.Bind(wx.EVT_SIZE, self.OnSize) <NEW_LINE> <DEDENT> self._useTimer = useTimer <NEW_LINE> if useTimer: <NEW_LINE> <INDENT> CreateMessageLoopTimer(self, timerMillis) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Debug("WARNING: Using EVT_IDLE for CEF message loop processing" " is not recommended") <NEW_LINE> self.Bind(wx.EVT_IDLE, self.OnIdle) <NEW_LINE> <DEDENT> self.Bind(wx.EVT_CLOSE, self.OnClose) <NEW_LINE> <DEDENT> def OnClose(self, event): <NEW_LINE> <INDENT> if not self._useTimer: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.Unbind(wx.EVT_IDLE) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.browser.ParentWindowWillClose() <NEW_LINE> <DEDENT> def OnIdle(self, event): <NEW_LINE> <INDENT> cefpython.MessageLoopWork() <NEW_LINE> event.Skip() <NEW_LINE> <DEDENT> def OnSetFocus(self, event): <NEW_LINE> <INDENT> cefpython.WindowUtils.OnSetFocus(self.GetHandle(), 0, 0, 0) <NEW_LINE> event.Skip() <NEW_LINE> <DEDENT> def OnSize(self, event): <NEW_LINE> <INDENT> cefpython.WindowUtils.OnSize(self.GetHandle(), 0, 0, 0) <NEW_LINE> event.Skip() <NEW_LINE> <DEDENT> def GetBrowser(self): <NEW_LINE> <INDENT> return self.browser <NEW_LINE> <DEDENT> def LoadUrl(self, url, onLoadStart=None, onLoadEnd=None): <NEW_LINE> <INDENT> if onLoadStart or onLoadEnd: <NEW_LINE> <INDENT> self.GetBrowser().SetClientHandler( CallbackClientHandler(onLoadStart, onLoadEnd)) <NEW_LINE> <DEDENT> browser = self.GetBrowser() <NEW_LINE> if cefpython.g_debug: <NEW_LINE> <INDENT> Debug("LoadUrl() self: %s" % self) <NEW_LINE> Debug("browser: %s" % browser) <NEW_LINE> Debug("browser id: %s" % browser.GetIdentifier()) <NEW_LINE> Debug("mainframe: %s" % browser.GetMainFrame()) <NEW_LINE> Debug("mainframe id: %s" % browser.GetMainFrame().GetIdentifier()) <NEW_LINE> <DEDENT> self.GetBrowser().GetMainFrame().LoadUrl(url) | Standalone CEF component. The class provides facilites for interacting
with wx message loop | 6259907b4c3428357761bcc6 |
class CompaniesListTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> Company.objects.create(name='Sofware Solutions') <NEW_LINE> <DEDENT> def test_list_one_company_on_list(self): <NEW_LINE> <INDENT> companies = [] <NEW_LINE> companies = Company.objects.all() <NEW_LINE> self.assertTrue(0 < len(companies)) <NEW_LINE> <DEDENT> def test_list_1000_companies_on_list(self): <NEW_LINE> <INDENT> companies = [] <NEW_LINE> for c in range(0, 1000): <NEW_LINE> <INDENT> Company.objects.create(name='Mocke Company {}'.format(c)) <NEW_LINE> <DEDENT> companies = Company.objects.all()[0:1000] <NEW_LINE> self.assertTrue(0 < len(companies)) <NEW_LINE> self.assertEqual(1000, len(companies)) <NEW_LINE> self.assertTrue('Mocke Company 10' in [item.name for item in companies]) | Unittest for list companies | 6259907bf548e778e596cf9e |
class StoreLocation(models.Model): <NEW_LINE> <INDENT> store = models.ForeignKey(Store) <NEW_LINE> street = models.CharField(max_length=255) <NEW_LINE> city = models.CharField(max_length=64) <NEW_LINE> state = models.CharField(max_length=2) <NEW_LINE> zip_code = models.CharField(max_length=5, null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s\n%s, %s, %s' % (self.street, self.city, self.state, self.zip_code) | Each store can have multiple location. so we have
this module to rapresent this locations. | 6259907b5fdd1c0f98e5f98c |
class For(Basic): <NEW_LINE> <INDENT> def __new__(cls, target, iter, body): <NEW_LINE> <INDENT> target = _sympify(target) <NEW_LINE> if not iterable(iter): <NEW_LINE> <INDENT> raise TypeError("iter must be an iterable") <NEW_LINE> <DEDENT> if isinstance(iter, list): <NEW_LINE> <INDENT> iter = tuple(iter) <NEW_LINE> <DEDENT> iter = _sympify(iter) <NEW_LINE> if not isinstance(body, CodeBlock): <NEW_LINE> <INDENT> if not iterable(body): <NEW_LINE> <INDENT> raise TypeError("body must be an iterable or CodeBlock") <NEW_LINE> <DEDENT> body = CodeBlock(*(_sympify(i) for i in body)) <NEW_LINE> <DEDENT> return Basic.__new__(cls, target, iter, body) <NEW_LINE> <DEDENT> @property <NEW_LINE> def target(self): <NEW_LINE> <INDENT> return self._args[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def iterable(self): <NEW_LINE> <INDENT> return self._args[1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def body(self): <NEW_LINE> <INDENT> return self._args[2] | Represents a 'for-loop' in the code.
Expressions are of the form:
"for target in iter:
body..."
Parameters
----------
target : symbol
iter : iterable
body : sympy expr
Examples
--------
>>> from sympy import symbols, Range
>>> from sympy.codegen.ast import aug_assign, For
>>> x, n = symbols('x n')
>>> For(n, Range(10), [aug_assign(x, '+', n)])
For(n, Range(0, 10, 1), CodeBlock(AddAugmentedAssignment(x, n))) | 6259907b1f5feb6acb164604 |
class AvailableServiceSkuPaged(Paged): <NEW_LINE> <INDENT> _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[AvailableServiceSku]'} } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AvailableServiceSkuPaged, self).__init__(*args, **kwargs) | A paging container for iterating over a list of :class:`AvailableServiceSku <azure.mgmt.datamigration.models.AvailableServiceSku>` object | 6259907bec188e330fdfa2b5 |
@parser(Specs.ceph_osd_log) <NEW_LINE> class CephOsdLog(LogFileOutput): <NEW_LINE> <INDENT> time_format = '%Y-%m-%d %H:%M:%S.%f' | Provide access to Ceph OSD logs using the LogFileOutput parser class.
.. note::
Please refer to the super-class :class:`insights.core.LogFileOutput` | 6259907b60cbc95b06365a74 |
class _BaseCommandManager(dict): <NEW_LINE> <INDENT> _use_args = True <NEW_LINE> _callback_manager = None <NEW_LINE> def register_commands(self, names, callback, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(names, str): <NEW_LINE> <INDENT> names = [names] <NEW_LINE> <DEDENT> if not type(names) in (list, tuple): <NEW_LINE> <INDENT> raise TypeError( '{0} commands must be passed as a list, tuple, or string,' ' not "{1}"'.format(type(self).__name__, type(names).__name__)) <NEW_LINE> <DEDENT> if not self._callback_manager is None: <NEW_LINE> <INDENT> callback = self._callback_manager(callback, *args, **kwargs) <NEW_LINE> <DEDENT> for name in names: <NEW_LINE> <INDENT> if not name in self: <NEW_LINE> <INDENT> if self._use_args: <NEW_LINE> <INDENT> command = self._get_command(name, *args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command = self._get_command(name) <NEW_LINE> <DEDENT> self[name] = _CallbackList(command) <NEW_LINE> <DEDENT> self[name].append(callback) <NEW_LINE> <DEDENT> <DEDENT> def unregister_commands(self, names, callback): <NEW_LINE> <INDENT> if isinstance(names, str): <NEW_LINE> <INDENT> names = [names] <NEW_LINE> <DEDENT> if not type(names) in (list, tuple): <NEW_LINE> <INDENT> raise TypeError( '{0} commands must be passed as a list, tuple, or string,' ' not "{1}"'.format(type(self).__name__, type(names).__name__)) <NEW_LINE> <DEDENT> for name in names: <NEW_LINE> <INDENT> if not name in self: <NEW_LINE> <INDENT> raise KeyError('Command "{0}" not registered'.format(name)) <NEW_LINE> <DEDENT> if not self._callback_manager is None: <NEW_LINE> <INDENT> for registered_callback in self[name]: <NEW_LINE> <INDENT> if registered_callback.callback == callback: <NEW_LINE> <INDENT> callback = registered_callback <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self[name].remove(callback) <NEW_LINE> if not self[name]: <NEW_LINE> <INDENT> self[name].command.remove_callback(self[name]) <NEW_LINE> del self[name] | Class used to (un)register commands | 6259907be1aae11d1e7cf517 |
class CatchLogStub(object): <NEW_LINE> <INDENT> @pytest.yield_fixture <NEW_LINE> def caplog(self): <NEW_LINE> <INDENT> yield | Provides a no-op 'caplog' fixture fallback. | 6259907b5fc7496912d48f71 |
class ICustomNavigation(IViewletManager): <NEW_LINE> <INDENT> pass | Custom Viewlet Manager for Navigation.
| 6259907b283ffb24f3cf52ae |
class HiddenInputs(HiddenInput): <NEW_LINE> <INDENT> item_widget = HiddenInput() <NEW_LINE> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> items = field._value() or [] <NEW_LINE> return HTMLString('\n'.join(self.item_widget(field, value=item) for item in items)) | Render hidden inputs for list elements. | 6259907ba8370b77170f1ddc |
class DefaultLicense(Dict[str, Any]): <NEW_LINE> <INDENT> domain_content: bool = False <NEW_LINE> domain_data: bool = False <NEW_LINE> domain_software: bool = False <NEW_LINE> family: str = '' <NEW_LINE> is_generic: bool = False <NEW_LINE> od_conformance: str = 'not reviewed' <NEW_LINE> osd_conformance: str = 'not reviewed' <NEW_LINE> maintainer: str = '' <NEW_LINE> status: str = 'active' <NEW_LINE> url: str = '' <NEW_LINE> id: str = '' <NEW_LINE> @property <NEW_LINE> def title(self) -> str: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> _keys: list[str] = ['domain_content', 'id', 'domain_data', 'domain_software', 'family', 'is_generic', 'od_conformance', 'osd_conformance', 'maintainer', 'status', 'url', 'title'] <NEW_LINE> def __getitem__(self, key: str) -> Any: <NEW_LINE> <INDENT> if key in self._keys: <NEW_LINE> <INDENT> value = getattr(self, key) <NEW_LINE> if isinstance(value, str): <NEW_LINE> <INDENT> return str(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> <DEDENT> def copy(self) -> dict[str, Any]: <NEW_LINE> <INDENT> out: dict[str, Any] = {} <NEW_LINE> for key in self._keys: <NEW_LINE> <INDENT> out[key] = str(getattr(self, key)) <NEW_LINE> <DEDENT> return out | The license was a dict but this did not allow translation of the
title. This is a slightly changed dict that allows us to have the title
as a property and so translated. | 6259907b796e427e53850188 |
class OpEnsembleMargin(Operator): <NEW_LINE> <INDENT> Input = InputSlot() <NEW_LINE> Output = OutputSlot() <NEW_LINE> def setupOutputs(self): <NEW_LINE> <INDENT> self.Output.meta.assignFrom(self.Input.meta) <NEW_LINE> taggedShape = self.Input.meta.getTaggedShape() <NEW_LINE> taggedShape["c"] = 1 <NEW_LINE> self.Output.meta.shape = tuple(taggedShape.values()) <NEW_LINE> <DEDENT> def execute(self, slot, subindex, roi, result): <NEW_LINE> <INDENT> if self.Input.meta.getTaggedShape()["c"] <= 1: <NEW_LINE> <INDENT> result[:] = 0 <NEW_LINE> return <NEW_LINE> <DEDENT> roi = copy.copy(roi) <NEW_LINE> taggedShape = self.Input.meta.getTaggedShape() <NEW_LINE> chanAxis = self.Input.meta.axistags.index("c") <NEW_LINE> roi.start[chanAxis] = 0 <NEW_LINE> roi.stop[chanAxis] = taggedShape["c"] <NEW_LINE> pmap = self.Input.get(roi).wait() <NEW_LINE> pmap.sort(axis=self.Input.meta.axistags.index("c")) <NEW_LINE> pmap = pmap.view(vigra.VigraArray) <NEW_LINE> pmap.axistags = self.Input.meta.axistags <NEW_LINE> res = pmap.bindAxis("c", -1) - pmap.bindAxis("c", -2) <NEW_LINE> res = res.withAxes(*list(taggedShape.keys())).view(numpy.ndarray) <NEW_LINE> result[...] = 1 - res <NEW_LINE> return result <NEW_LINE> <DEDENT> def propagateDirty(self, inputSlot, subindex, roi): <NEW_LINE> <INDENT> roi = roi.copy() <NEW_LINE> chanAxis = self.Input.meta.axistags.index("c") <NEW_LINE> roi.start[chanAxis] = 0 <NEW_LINE> roi.stop[chanAxis] = 1 <NEW_LINE> self.Output.setDirty(roi) | Produces a pixelwise measure of the uncertainty of the pixelwise predictions.
Uncertainty is negatively proportional to the difference between the
highest two probabilities at every pixel. | 6259907b7047854f46340dc8 |
class ImageFile(): <NEW_LINE> <INDENT> def __init__(self, num=None, size=None, dest=None): <NEW_LINE> <INDENT> self.num = num <NEW_LINE> self.size = size <NEW_LINE> self.dest = dest <NEW_LINE> <DEDENT> def createimage(self): <NEW_LINE> <INDENT> for i in range(self.num): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = 'dd if=/dev/zero of=%s/file.%s bs=1024 count=%s' % (self.dest, i, self.size) <NEW_LINE> Popen(cmd, shell=True, stdout=PIPE) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> sys.stderr.write(err) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def controller(self): <NEW_LINE> <INDENT> p = optparse.OptionParser(description='Launches Many dd', prog='Many dd', version='0.1', usage='%prog [options] dest') <NEW_LINE> p.add_option('-n', '--number', help='set many dd', type=int) <NEW_LINE> p.add_option('-s', '--size', help='size of image in bytes', type=int) <NEW_LINE> p.set_defaults(number=10, size=10240) <NEW_LINE> options, arguments = p.parse_args() <NEW_LINE> if len(arguments) == 1: <NEW_LINE> <INDENT> self.dest = arguments[0] <NEW_LINE> self.size = options.size <NEW_LINE> self.num = options.number <NEW_LINE> self.createimage() | Created Image Files Using dd | 6259907b63b5f9789fe86b75 |
class OSFBasicAuthentication(BasicAuthentication): <NEW_LINE> <INDENT> def authenticate(self, request): <NEW_LINE> <INDENT> user_auth_tuple = super(OSFBasicAuthentication, self).authenticate(request) <NEW_LINE> if user_auth_tuple is not None: <NEW_LINE> <INDENT> self.authenticate_twofactor_credentials(user_auth_tuple[0], request) <NEW_LINE> <DEDENT> return user_auth_tuple <NEW_LINE> <DEDENT> def authenticate_credentials(self, userid, password): <NEW_LINE> <INDENT> user = get_user(email=userid, password=password) <NEW_LINE> if userid and not user: <NEW_LINE> <INDENT> raise exceptions.AuthenticationFailed(_('Invalid username/password.')) <NEW_LINE> <DEDENT> elif userid is None and password is None: <NEW_LINE> <INDENT> raise exceptions.NotAuthenticated() <NEW_LINE> <DEDENT> check_user(user) <NEW_LINE> return user, None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def authenticate_twofactor_credentials(user, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> two_factor = TwoFactorUserSettings.objects.get(owner_id=user.pk) <NEW_LINE> <DEDENT> except TwoFactorUserSettings.DoesNotExist: <NEW_LINE> <INDENT> two_factor = None <NEW_LINE> <DEDENT> if two_factor and two_factor.is_confirmed: <NEW_LINE> <INDENT> otp = request.META.get('HTTP_X_OSF_OTP') <NEW_LINE> if otp is None: <NEW_LINE> <INDENT> raise TwoFactorRequiredError() <NEW_LINE> <DEDENT> if not two_factor.verify_code(otp): <NEW_LINE> <INDENT> raise exceptions.AuthenticationFailed(_('Invalid two-factor authentication OTP code.')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def authenticate_header(self, request): <NEW_LINE> <INDENT> return 'Documentation realm="{}"'.format(self.www_authenticate_realm) | Custom DRF authentication class for API call with email, password, and two-factor if necessary. | 6259907b009cb60464d02f4d |
class DecimalType(BaseType): <NEW_LINE> <INDENT> primitive_type = str <NEW_LINE> native_type = decimal.Decimal <NEW_LINE> MESSAGES = { 'number_coerce': _("Number '{0}' failed to convert to a decimal."), 'number_min': _("Value should be greater than or equal to {0}."), 'number_max': _("Value should be less than or equal to {0}."), } <NEW_LINE> def __init__(self, min_value=None, max_value=None, **kwargs): <NEW_LINE> <INDENT> self.min_value, self.max_value = min_value, max_value <NEW_LINE> super(DecimalType, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def _mock(self, context=None): <NEW_LINE> <INDENT> return get_value_in(self.min_value, self.max_value) <NEW_LINE> <DEDENT> def to_primitive(self, value, context=None): <NEW_LINE> <INDENT> return str(value) <NEW_LINE> <DEDENT> def to_native(self, value, context=None): <NEW_LINE> <INDENT> if not isinstance(value, decimal.Decimal): <NEW_LINE> <INDENT> if not isinstance(value, string_type): <NEW_LINE> <INDENT> value = str(value) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = decimal.Decimal(value) <NEW_LINE> <DEDENT> except (TypeError, decimal.InvalidOperation): <NEW_LINE> <INDENT> raise ConversionError(self.messages['number_coerce'].format(value)) <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def validate_range(self, value, context=None): <NEW_LINE> <INDENT> if self.min_value is not None and value < self.min_value: <NEW_LINE> <INDENT> error_msg = self.messages['number_min'].format(self.min_value) <NEW_LINE> raise ValidationError(error_msg) <NEW_LINE> <DEDENT> if self.max_value is not None and value > self.max_value: <NEW_LINE> <INDENT> error_msg = self.messages['number_max'].format(self.max_value) <NEW_LINE> raise ValidationError(error_msg) <NEW_LINE> <DEDENT> return value | A fixed-point decimal number field.
| 6259907b91f36d47f2231b96 |
class ownedFromProp(SchemaProperty): <NEW_LINE> <INDENT> _prop_schema = 'ownedFrom' <NEW_LINE> _expected_schema = None <NEW_LINE> _enum = False <NEW_LINE> _format_as = "DateTimeField" | SchemaField for ownedFrom
Usage: Include in SchemaObject SchemaFields as your_django_field = ownedFromProp()
schema.org description:The date and time of obtaining the product.
prop_schema returns just the property without url#
format_as is used by app templatetags based upon schema.org datatype | 6259907be1aae11d1e7cf518 |
@dataclasses.dataclass <NEW_LINE> class SelfSupervisedOutput: <NEW_LINE> <INDENT> frames: Union[np.ndarray, torch.FloatTensor] <NEW_LINE> feats: Union[np.ndarray, torch.FloatTensor] <NEW_LINE> embs: Union[np.ndarray, torch.FloatTensor] <NEW_LINE> def squeeze(self, dim): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k, v in dataclasses.asdict(self).items(): <NEW_LINE> <INDENT> kwargs[k] = v.squeeze(dim) <NEW_LINE> <DEDENT> return self.__class__(**kwargs) <NEW_LINE> <DEDENT> def cpu(self): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k, v in dataclasses.asdict(self).items(): <NEW_LINE> <INDENT> kwargs[k] = v.cpu() <NEW_LINE> <DEDENT> return self.__class__(**kwargs) <NEW_LINE> <DEDENT> def numpy(self): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k, v in dataclasses.asdict(self).items(): <NEW_LINE> <INDENT> if k != "frames": <NEW_LINE> <INDENT> kwargs[k] = v.cpu().detach().numpy() <NEW_LINE> <DEDENT> <DEDENT> kwargs["frames"] = self.frames.permute(0, 2, 3, 1).cpu().detach().numpy() <NEW_LINE> return self.__class__(**kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def merge( cls, output_list): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for k in dataclasses.asdict(output_list[0]).keys(): <NEW_LINE> <INDENT> kwargs[k] = torch.cat([getattr(o, k) for o in output_list], dim=1) <NEW_LINE> <DEDENT> return cls(**kwargs) | The output of a self-supervised model. | 6259907bbe7bc26dc9252b5d |
class DummyScreen(display.Display): <NEW_LINE> <INDENT> def __init__(self, width=64, height=32): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> self.canvas = pygame.Surface((width, height)) <NEW_LINE> self._display = pygame.display.set_mode( (width * SCALING, height * SCALING)) <NEW_LINE> pygame.display.set_caption('infopanel test screen') <NEW_LINE> self.clock = pygame.time.Clock() <NEW_LINE> self._brightness = 50 <NEW_LINE> self.font = pygame.font.SysFont("courier", 9) <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.canvas.get_width() <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.canvas.get_height() <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> return self._brightness <NEW_LINE> <DEDENT> @brightness.setter <NEW_LINE> def brightness(self, value): <NEW_LINE> <INDENT> self._brightness = value <NEW_LINE> <DEDENT> def text(self, font, x, y, red, green, blue, text): <NEW_LINE> <INDENT> val = self.font.render(text, 0, (red, green, blue)) <NEW_LINE> width, _height = self.font.size(text) <NEW_LINE> self.canvas.blit(val, (x, y - self.font.get_height())) <NEW_LINE> return width <NEW_LINE> <DEDENT> def set_pixel(self, x, y, red, green, blue): <NEW_LINE> <INDENT> self.canvas.fill((red, green, blue), (x, y, 1, 1)) <NEW_LINE> <DEDENT> def set_image(self, image, x=0, y=0): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> myimage = pygame.image.load("myimage.bmp") <NEW_LINE> imagerect = myimage.get_rect() <NEW_LINE> self.canvas.blit(myimage, imagerect) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.canvas.fill((0, 0, 0)) <NEW_LINE> <DEDENT> def buffer(self): <NEW_LINE> <INDENT> pygame.transform.scale( self.canvas, (self.width * SCALING, self.height * SCALING), self._display) <NEW_LINE> pygame.display.flip() | A dummy screen for testing purposes. | 6259907b7d847024c075dded |
class Player(object): <NEW_LINE> <INDENT> def __init__(self, player_name, player_color): <NEW_LINE> <INDENT> self.adversary = None <NEW_LINE> self.name = player_name <NEW_LINE> self.color = player_color <NEW_LINE> self.points = 0 <NEW_LINE> <DEDENT> def get_adversary(self): <NEW_LINE> <INDENT> return self.adversary <NEW_LINE> <DEDENT> def set_adversary(self, adversary): <NEW_LINE> <INDENT> if self.adversary is None: <NEW_LINE> <INDENT> self.adversary = adversary <NEW_LINE> <DEDENT> return self.adversary <NEW_LINE> <DEDENT> def play(self, grid): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> pos = input("What is the position " + self.name + " want to conquer : ") <NEW_LINE> pos = pos.split(" ") <NEW_LINE> try: <NEW_LINE> <INDENT> pos_x = int(pos[0]) <NEW_LINE> pos_y = int(pos[1]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('you must type "x y" where x and y is the pos you want to play') <NEW_LINE> continue <NEW_LINE> <DEDENT> if grid.add_a_pawn(self, pos_x, pos_y): <NEW_LINE> <INDENT> break | Takes 4 arguments :
The name of the player
The color he chooses
The number of points he has
The name of the adversary
Takes two method :
get_adversary()
set_adversary() | 6259907b7b180e01f3e49d6d |
class BlogAnswer(models.Model): <NEW_LINE> <INDENT> block_diagram_blog_question = models.OneToOneField( BlockDiagramBlogQuestion, related_name='blog_answer', on_delete=models.CASCADE, primary_key=True, ) <NEW_LINE> answer = models.TextField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.answer) | Answer from the user. | 6259907b3346ee7daa338369 |
class MailInboundException(Exception): <NEW_LINE> <INDENT> def __init__(self, exitcode, errormsg): <NEW_LINE> <INDENT> self.exitcode = exitcode <NEW_LINE> self.errormsg = errormsg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s:%s' % (self.exitcode, self.errormsg) | An exception indicating an error occured while processing
an inbound mail. | 6259907b3539df3088ecdca8 |
class ProductionConfig(Config): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> level = logging.WARNING <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/ihome01' | 创建线上环境下的配置类 | 6259907b23849d37ff852ac9 |
class CouponTierItemDiscount(object): <NEW_LINE> <INDENT> swagger_types = { 'discount_amount': 'float', 'items': 'list[str]' } <NEW_LINE> attribute_map = { 'discount_amount': 'discount_amount', 'items': 'items' } <NEW_LINE> def __init__(self, discount_amount=None, items=None): <NEW_LINE> <INDENT> self._discount_amount = None <NEW_LINE> self._items = None <NEW_LINE> self.discriminator = None <NEW_LINE> if discount_amount is not None: <NEW_LINE> <INDENT> self.discount_amount = discount_amount <NEW_LINE> <DEDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def discount_amount(self): <NEW_LINE> <INDENT> return self._discount_amount <NEW_LINE> <DEDENT> @discount_amount.setter <NEW_LINE> def discount_amount(self, discount_amount): <NEW_LINE> <INDENT> self._discount_amount = discount_amount <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(CouponTierItemDiscount, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CouponTierItemDiscount): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907b01c39578d7f1443d |
class NimbusConfig(Config): <NEW_LINE> <INDENT> def setup_contextualization(self): <NEW_LINE> <INDENT> self.validate_contextualization() <NEW_LINE> self.metadata_service_url_file = self.ini.get("DEFAULT", "metadata_service_url_file") <NEW_LINE> with open(self.metadata_service_url_file, 'r') as fd: <NEW_LINE> <INDENT> url = fd.read().strip() <NEW_LINE> <DEDENT> self.metadata_service = url <NEW_LINE> self.instance_userdata_url = '%s/current/user-data' % url | Class for Nimbus pilot config | 6259907b3317a56b869bf24e |
class GridSpecFromSubplotSpec(GridSpecBase): <NEW_LINE> <INDENT> def __init__(self, nrows, ncols, subplot_spec, wspace=None, hspace=None, height_ratios=None, width_ratios=None): <NEW_LINE> <INDENT> self._wspace = wspace <NEW_LINE> self._hspace = hspace <NEW_LINE> self._subplot_spec = subplot_spec <NEW_LINE> self.figure = self._subplot_spec.get_gridspec().figure <NEW_LINE> super().__init__(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) <NEW_LINE> subspeclb = subplot_spec.get_gridspec()._layoutgrid <NEW_LINE> if subspeclb is None: <NEW_LINE> <INDENT> self._layoutgrid = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._toplayoutgrid = layoutgrid.LayoutGrid( parent=subspeclb, name=subspeclb.name + '.top' + layoutgrid.seq_id(), nrows=1, ncols=1, parent_pos=(subplot_spec.rowspan, subplot_spec.colspan)) <NEW_LINE> self._layoutgrid = layoutgrid.LayoutGrid( parent=self._toplayoutgrid, name=(self._toplayoutgrid.name + '.gridspec' + layoutgrid.seq_id()), nrows=nrows, ncols=ncols, width_ratios=width_ratios, height_ratios=height_ratios) <NEW_LINE> <DEDENT> <DEDENT> def get_subplot_params(self, figure=None): <NEW_LINE> <INDENT> hspace = (self._hspace if self._hspace is not None else figure.subplotpars.hspace if figure is not None else rcParams["figure.subplot.hspace"]) <NEW_LINE> wspace = (self._wspace if self._wspace is not None else figure.subplotpars.wspace if figure is not None else rcParams["figure.subplot.wspace"]) <NEW_LINE> figbox = self._subplot_spec.get_position(figure) <NEW_LINE> left, bottom, right, top = figbox.extents <NEW_LINE> return mpl.figure.SubplotParams(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace) <NEW_LINE> <DEDENT> def get_topmost_subplotspec(self): <NEW_LINE> <INDENT> return self._subplot_spec.get_topmost_subplotspec() | GridSpec whose subplot layout parameters are inherited from the
location specified by a given SubplotSpec. | 6259907b32920d7e50bc7a53 |
class UserRegistrationForm(UserCreationForm): <NEW_LINE> <INDENT> password1 = forms.CharField( label="Password", widget=forms.PasswordInput) <NEW_LINE> password2 = forms.CharField( label="Password Confirmation", widget=forms.PasswordInput) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['email', 'username', 'password1', 'password2'] | Forms for registering a user | 6259907b283ffb24f3cf52b1 |
class InvItemVirtualFields: <NEW_LINE> <INDENT> extra_fields = ["quantity", "pack_value", ] <NEW_LINE> def total_value(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = self.inv_inv_item.quantity * self.inv_inv_item.pack_value <NEW_LINE> <DEDENT> except (AttributeError,TypeError): <NEW_LINE> <INDENT> return current.messages.NONE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> <DEDENT> def item_code(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.inv_inv_item.item_id.code <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return current.messages.NONE <NEW_LINE> <DEDENT> <DEDENT> def item_category(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.inv_inv_item.item_id.item_category_id.name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return current.messages.NONE | Virtual fields as dimension classes for reports | 6259907bbf627c535bcb2ee1 |
class AsyncSmallMsgDef(AbstractSmallMsgDef): <NEW_LINE> <INDENT> CORRELATION_ID_FLAG = 0x01 <NEW_LINE> CORRELATION_ID_BYTES_FLAG = 0x02 <NEW_LINE> def readExternal(self, obj, context): <NEW_LINE> <INDENT> AbstractSmallMsgDef.readExternal(self, obj, context) <NEW_LINE> flags = self._readFlags(context) <NEW_LINE> for i, flag in enumerate(flags): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> if flag & self.CORRELATION_ID_FLAG: <NEW_LINE> <INDENT> obj.correlationId = decode(context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj.correlationId = None <NEW_LINE> <DEDENT> if flag & self.CORRELATION_ID_BYTES_FLAG: <NEW_LINE> <INDENT> correlationIdBytes = decode(context) <NEW_LINE> obj.correlationId = self._readUid(correlationIdBytes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not hasattr(obj, 'correlationId'): <NEW_LINE> <INDENT> obj.correlationId = None | Decodes messages that were encoded using ISmallMessage. | 6259907b283ffb24f3cf52b2 |
class Track(): <NEW_LINE> <INDENT> def __init__(self, name:str="", note:List[Note]=[]): <NEW_LINE> <INDENT> if(note==[]): <NEW_LINE> <INDENT> note=[] <NEW_LINE> <DEDENT> self.name=name <NEW_LINE> self.note=note <NEW_LINE> <DEDENT> pass | 音轨类
name:音轨名,str
singer:歌手编号,str
note:音符列表,List[Svipnote]
volume:音量,float,[0,2]
balance:左右声道平衡,float,[-1,1]
mute:静音,bool
solo:独奏,bool
reverb:混响类型,int | 6259907b796e427e5385018c |
class FeatureExtractor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True): <NEW_LINE> <INDENT> super(FeatureExtractor, self).__init__() <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.num_layers = num_layers <NEW_LINE> self.num_embeddings, self.embedding_dim = pretrained_mtx.shape <NEW_LINE> self.token2idx_dict = token2idx_dict <NEW_LINE> self.embedding = nn.Embedding.from_pretrained(torch.from_numpy(pretrained_mtx).float(), freeze=freeze_embedding) <NEW_LINE> self.lstm = nn.LSTM(self.embedding_dim, self.hidden_size, num_layers=self.num_layers, batch_first=True) <NEW_LINE> <DEDENT> def forward(self, graph, device): <NEW_LINE> <INDENT> seqs = [] <NEW_LINE> for node_index in list(graph.nodes()): <NEW_LINE> <INDENT> list_tokenized_words = word_tokenize(graph.nodes[node_index]["context"]) <NEW_LINE> seqs.append(list_tokenized_words) <NEW_LINE> <DEDENT> for seqs_list in seqs: <NEW_LINE> <INDENT> if seqs_list == []: <NEW_LINE> <INDENT> seqs_list.append("Empty") <NEW_LINE> <DEDENT> <DEDENT> vectorized_seqs = [[self.token2idx_dict[tok] for tok in seq if tok in self.token2idx_dict.keys()] for seq in seqs] <NEW_LINE> seq_lengths = torch.LongTensor(list(map(len, vectorized_seqs))).to(device) <NEW_LINE> seq_tensor = torch.zeros((len(vectorized_seqs), seq_lengths.max())).long().to(device) <NEW_LINE> for idx, (seq, seqlen) in enumerate(zip(vectorized_seqs, seq_lengths)): <NEW_LINE> <INDENT> seq_tensor[idx, :seqlen] = torch.LongTensor(seq).to(device) <NEW_LINE> <DEDENT> seq_lengths, perm_idx = seq_lengths.sort(0, descending=True) <NEW_LINE> seq_tensor = seq_tensor[perm_idx] <NEW_LINE> embedded_seq_tensor = self.embedding(seq_tensor) <NEW_LINE> packed_input = pack_padded_sequence(embedded_seq_tensor, seq_lengths.cpu().numpy(), batch_first=True) <NEW_LINE> _, (ht, _) = self.lstm(packed_input) <NEW_LINE> dgl_graph = dgl.DGLGraph() <NEW_LINE> dgl_graph.add_nodes(len(list(graph.nodes()))) <NEW_LINE> src = [] <NEW_LINE> dst = [] <NEW_LINE> for edge in list(graph.edges()): <NEW_LINE> <INDENT> src.append(edge[0]) <NEW_LINE> dst.append(edge[1]) <NEW_LINE> <DEDENT> dgl_graph.add_edges(src, dst) <NEW_LINE> feat_init = torch.zeros(ht.squeeze(0).size()) <NEW_LINE> dgl_graph.ndata['feat'] = feat_init <NEW_LINE> dgl_graph.nodes[perm_idx].data['feat'] = ht.squeeze(0).cpu() <NEW_LINE> return dgl_graph | Feature extracter for each node in the graph. | 6259907b99fddb7c1ca63ae0 |
class VitalNullPointerException (VitalBaseException): <NEW_LINE> <INDENT> pass | When an error occurs due to use of a NULL pointer | 6259907b63b5f9789fe86b79 |
class User(BaseModel): <NEW_LINE> <INDENT> email = "" <NEW_LINE> password = "" <NEW_LINE> first_name = "" <NEW_LINE> last_name = "" | User reprisentation str info | 6259907b97e22403b383c913 |
class BaseBrowserPlugin(_AttributeManipulator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> _AttributeManipulator.__init__(self) <NEW_LINE> self.overrides = self._load_list("is_override") <NEW_LINE> self.extensions = self._load_list("is_extension") <NEW_LINE> self.property_extensions = self._load_list("is_property_extension") <NEW_LINE> self.handlers = [] <NEW_LINE> self.addheaders = [] | A :class:`lib.browser.Browser` plugin is defined as a set of patches to
be applied to a Browser object. This class defines a base for browser
plugins. | 6259907b3317a56b869bf24f |
class Record(object): <NEW_LINE> <INDENT> def __init__(self, tuple, ats, dts): <NEW_LINE> <INDENT> self.tuple = tuple <NEW_LINE> self.ats = ats <NEW_LINE> self.dts = dts | Represents a structure that is inserted into the hash table.
It is composed by a tuple, ats (arrival timestamp) and
dts (departure timestamp). | 6259907bfff4ab517ebcf22b |
class AccountMonitor(BasicMonitor): <NEW_LINE> <INDENT> def __init__(self, main_engine, event_engine, parent=None): <NEW_LINE> <INDENT> super(AccountMonitor, self).__init__(main_engine, event_engine, parent) <NEW_LINE> d = OrderedDict() <NEW_LINE> d['accountID'] = {'chinese': u'账户', 'cellType': BasicCell} <NEW_LINE> d['preBalance'] = {'chinese': u'昨结', 'cellType': BasicCell} <NEW_LINE> d['balance'] = {'chinese': u'净值', 'cellType': BasicCell} <NEW_LINE> d['available'] = {'chinese': u'可用', 'cellType': BasicCell} <NEW_LINE> d['commission'] = {'chinese': u'手续费', 'cellType': BasicCell} <NEW_LINE> d['margin'] = {'chinese': u'保证金', 'cellType': BasicCell} <NEW_LINE> d['closeProfit'] = {'chinese': u'平仓盈亏', 'cellType': BasicCell} <NEW_LINE> d['positionProfit'] = {'chinese': u'持仓盈亏', 'cellType': BasicCell} <NEW_LINE> d['gatewayName'] = {'chinese': u'接口', 'cellType': BasicCell} <NEW_LINE> self.setHeaderDict(d) <NEW_LINE> self.setDataKey('vtAccountID') <NEW_LINE> self.setEventType(EVENT_ACCOUNT) <NEW_LINE> self.setFont(BASIC_FONT) <NEW_LINE> self.initTable() <NEW_LINE> self.registerEvent() | 账户监控 | 6259907b71ff763f4b5e91bf |
class Iomega(omegaExpr): <NEW_LINE> <INDENT> quantity = 'Current spectrum' <NEW_LINE> units = 'A/rad/s' <NEW_LINE> def __init__(self, val): <NEW_LINE> <INDENT> super(Iomega, self).__init__(val) <NEW_LINE> self._fourier_conjugate_class = It | omega-domain current (units A/rad/s) | 6259907b1b99ca400229023f |
class _TestPageviews(_TestHarness): <NEW_LINE> <INDENT> _gwriter_mode = None <NEW_LINE> data__test_pageview__html = None <NEW_LINE> data__test_pageview_alt__html = None <NEW_LINE> def test_render_page(self): <NEW_LINE> <INDENT> as_html = self.request.g_analytics_writer.render() <NEW_LINE> self.assertEqual(as_html, self.data__test_pageview__html) <NEW_LINE> <DEDENT> def test_render_pageview_alt(self): <NEW_LINE> <INDENT> self.request.g_analytics_writer.set_custom_variable(1, "section", "account") <NEW_LINE> self.request.g_analytics_writer.set_custom_variable(2, "pagetype", "-") <NEW_LINE> self.request.g_analytics_writer.set_custom_variable( 5, "is_known_user", "1", 1 ) <NEW_LINE> self.request.g_analytics_writer.set_custom_variable(2, "pagetype", "home") <NEW_LINE> as_html = self.request.g_analytics_writer.render() <NEW_LINE> self.assertEqual(as_html, self.data__test_pageview_alt__html) | core class for tests.
subclass this with data and a configred _gwriter_mode | 6259907b56ac1b37e63039ec |
class InlineResponse2005(object): <NEW_LINE> <INDENT> openapi_types = { 'items': 'list[VoltageChange]' } <NEW_LINE> attribute_map = { 'items': '_items' } <NEW_LINE> def __init__(self, items=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._items = None <NEW_LINE> self.discriminator = None <NEW_LINE> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse2005): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse2005): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259907bbf627c535bcb2ee3 |
class HuaweiDeviceHandler(DefaultDeviceHandler): <NEW_LINE> <INDENT> _EXEMPT_ERRORS = [] <NEW_LINE> def __init__(self, device_params): <NEW_LINE> <INDENT> super(HuaweiDeviceHandler, self).__init__(device_params) <NEW_LINE> <DEDENT> def add_additional_operations(self): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> dict["cli"] = CLI <NEW_LINE> dict["action"] = Action <NEW_LINE> return dict <NEW_LINE> <DEDENT> def get_capabilities(self): <NEW_LINE> <INDENT> c = super(HuaweiDeviceHandler, self).get_capabilities() <NEW_LINE> c.append('http://www.huawei.com/netconf/capability/execute-cli/1.0') <NEW_LINE> c.append('http://www.huawei.com/netconf/capability/action/1.0') <NEW_LINE> c.append('http://www.huawei.com/netconf/capability/active/1.0') <NEW_LINE> c.append('http://www.huawei.com/netconf/capability/discard-commit/1.0') <NEW_LINE> c.append('urn:ietf:params:netconf:capability:notification:1.0') <NEW_LINE> return c <NEW_LINE> <DEDENT> def get_xml_base_namespace_dict(self): <NEW_LINE> <INDENT> return {None: BASE_NS_1_0} <NEW_LINE> <DEDENT> def get_xml_extra_prefix_kwargs(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> d.update(self.get_xml_base_namespace_dict()) <NEW_LINE> return {"nsmap": d} <NEW_LINE> <DEDENT> def perform_qualify_check(self): <NEW_LINE> <INDENT> return False | Huawei handler for device specific information.
In the device_params dictionary, which is passed to __init__, you can specify
the parameter "ssh_subsystem_name". That allows you to configure the preferred
SSH subsystem name that should be tried on your Huawei switch. If connecting with
that name fails, or you didn't specify that name, the other known subsystem names
will be tried. However, if you specify it then this name will be tried first. | 6259907ba8370b77170f1de2 |
class Roles(models.Model): <NEW_LINE> <INDENT> role_name = models.CharField(max_length=20) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'Roles' <NEW_LINE> managed = False <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '%s' % self.role_name | Django model for Roles table. | 6259907b9c8ee82313040e91 |
class AdvertEventHandler: <NEW_LINE> <INDENT> def __init__(self, pkt): <NEW_LINE> <INDENT> self.pkt = pkt <NEW_LINE> self.adv_data = None <NEW_LINE> self.rssi = None <NEW_LINE> self.manufacturer_data = None <NEW_LINE> self.service_data = None <NEW_LINE> self.eddystone_url = None <NEW_LINE> self.eddystone_uid = None <NEW_LINE> self.ibeacon = None <NEW_LINE> self.alt_beacon = None <NEW_LINE> self.evt = AdvertEvent(pkt) <NEW_LINE> if not self.evt.payload: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.rssi = self.evt.rssi <NEW_LINE> self.adv_payload = self.evt.payload <NEW_LINE> self.adv_data = AdvertData(self.adv_payload) <NEW_LINE> if self.adv_data and self.adv_data.manufacturer_data: <NEW_LINE> <INDENT> self.manufacturer_data = ManufacturerData(self.adv_data.manufacturer_data) <NEW_LINE> if self.manufacturer_data.is_ibeacon: <NEW_LINE> <INDENT> self.ibeacon = iBeacon(self.manufacturer_data.data) <NEW_LINE> <DEDENT> elif self.manufacturer_data.is_alt_beacon: <NEW_LINE> <INDENT> self.alt_beacon = AltBeacon(self.manufacturer_data.data) <NEW_LINE> <DEDENT> <DEDENT> elif self.adv_data and self.adv_data.service_data: <NEW_LINE> <INDENT> self.service_data = ServiceData(self.adv_data.service_data) <NEW_LINE> self.eddystone_beacon = Eddystone(self.service_data.service_data) <NEW_LINE> if self.eddystone_beacon.is_eddystone_url: <NEW_LINE> <INDENT> self.eddystone_url = EddystoneUrl(self.eddystone_beacon.data) <NEW_LINE> <DEDENT> elif self.eddystone_beacon.is_eddystone_uid: <NEW_LINE> <INDENT> self.eddystone_uid = EddystoneUid(self.eddystone_beacon.data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self.evt.mac_addr.__str__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def advert_flags(self): <NEW_LINE> <INDENT> return self.adv_data.adv_flags <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'<AdvertEventHandler({format_bytearray(self.pkt)})>' | Class to unpack BLE advert event | 6259907b8a349b6b43687c70 |
class AbstractSubject(object): <NEW_LINE> <INDENT> def register(self, listener): <NEW_LINE> <INDENT> raise NotImplementedError("Must subclass me") <NEW_LINE> <DEDENT> def unregister(self, listener): <NEW_LINE> <INDENT> raise NotImplementedError("Must subclass me") <NEW_LINE> <DEDENT> def notify_listeners(self, event): <NEW_LINE> <INDENT> raise NotImplementedError("Must subclass me") | Abstract Subject | 6259907bdc8b845886d54fcf |
class Channel(six.with_metaclass(abc.ABCMeta)): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def subscribe(self, callback, try_to_connect=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def unsubscribe(self, callback): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def unary_unary(self, method, request_serializer=None, response_deserializer=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def unary_stream(self, method, request_serializer=None, response_deserializer=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def stream_unary(self, method, request_serializer=None, response_deserializer=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def stream_stream(self, method, request_serializer=None, response_deserializer=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def close(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> raise NotImplementedError() | Affords RPC invocation via generic methods on client-side.
Channel objects implement the Context Manager type, although they need not
support being entered and exited multiple times. | 6259907b3346ee7daa33836b |
@dataclass(frozen=True) <NEW_LINE> class ASTpathelem: <NEW_LINE> <INDENT> node: ast.AST <NEW_LINE> attr: str <NEW_LINE> index: Optional[int] = None <NEW_LINE> @property <NEW_LINE> def field(self): <NEW_LINE> <INDENT> return getattr(self.node, self.attr) <NEW_LINE> <DEDENT> def field_is_body(self): <NEW_LINE> <INDENT> return self.attr in ("body", "orelse", "finalbody") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = self.node.__class__.__name__ <NEW_LINE> if hasattr(self.node, "lineno"): <NEW_LINE> <INDENT> s += f"(#{self.node.lineno})" <NEW_LINE> <DEDENT> s += f".{self.attr}" <NEW_LINE> if self.index is not None: <NEW_LINE> <INDENT> s += f"[{self.index}]" <NEW_LINE> <DEDENT> return s | An element of AST path. | 6259907b7d43ff248742811f |
class CustomComponents(): <NEW_LINE> <INDENT> def __init__(self, hass, conf_hide_sensor, conf_component_urls): <NEW_LINE> <INDENT> _LOGGER.debug('CustomComponents - __init__') <NEW_LINE> from pyupdate.ha_custom.custom_components import ( CustomComponents as Components) <NEW_LINE> self.hass = hass <NEW_LINE> self.ha_conf_dir = str(hass.config.path()) <NEW_LINE> self.hidden = conf_hide_sensor <NEW_LINE> self.pyupdate = Components(self.ha_conf_dir, conf_component_urls) <NEW_LINE> <DEDENT> async def extra_init(self): <NEW_LINE> <INDENT> _LOGGER.debug('CustomComponents - extra_init') <NEW_LINE> await self.cache_versions() <NEW_LINE> <DEDENT> async def cache_versions(self, now=None): <NEW_LINE> <INDENT> _LOGGER.debug('CustomComponents - cache_versions') <NEW_LINE> information = await self.pyupdate.get_sensor_data(True) <NEW_LINE> state = int(information[1]) <NEW_LINE> attributes = information[0] <NEW_LINE> attributes['hidden'] = self.hidden <NEW_LINE> self.hass.states.async_set( 'sensor.custom_component_tracker', state, attributes) <NEW_LINE> <DEDENT> async def update_all(self): <NEW_LINE> <INDENT> _LOGGER.debug('CustomComponents - update_all') <NEW_LINE> await self.pyupdate.update_all() <NEW_LINE> information = await self.pyupdate.get_sensor_data() <NEW_LINE> state = int(information[1]) <NEW_LINE> attributes = information[0] <NEW_LINE> attributes['hidden'] = self.hidden <NEW_LINE> self.hass.states.async_set( 'sensor.custom_component_tracker', state, attributes) <NEW_LINE> <DEDENT> async def install(self, element): <NEW_LINE> <INDENT> _LOGGER.debug('CustomComponents - install') <NEW_LINE> await self.pyupdate.install(element) | Custom components controller. | 6259907b56b00c62f0fb42e8 |
class TestConverters(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.simple_model = create_simple_model_with_json_representation()[0] <NEW_LINE> self.simple_model_as_json = create_simple_model_with_json_representation()[1] <NEW_LINE> <DEDENT> def test_json_encoder_to_serializer(self): <NEW_LINE> <INDENT> serializer_cls = json_encoder_to_serializer(BasicSimpleModelJSONEncoder) <NEW_LINE> serializer = serializer_cls() <NEW_LINE> self.assertIsInstance(serializer, Serializer) <NEW_LINE> serialized = serializer.serialize(self.simple_model) <NEW_LINE> encoded = BasicSimpleModelJSONEncoder().default(self.simple_model) <NEW_LINE> self.assertDictEqual(serialized, encoded) <NEW_LINE> <DEDENT> def test_json_decoder_to_deserializer(self): <NEW_LINE> <INDENT> deserializer_cls = json_decoder_to_deserializer(BasicSimpleModelJSONDecoder) <NEW_LINE> deserializer = deserializer_cls() <NEW_LINE> self.assertIsInstance(deserializer, Deserializer) <NEW_LINE> deserialized = deserializer.deserialize(self.simple_model_as_json) <NEW_LINE> decoded = BasicSimpleModelJSONDecoder().decode(json.dumps(self.simple_model_as_json)) <NEW_LINE> self.assertEqual(deserialized, decoded) | Tests for `json_encoder_to_serializer` and `json_decoder_to_deserializer`. | 6259907b91f36d47f2231b99 |
class Noticias(models.Model): <NEW_LINE> <INDENT> fecha = models.DateField() <NEW_LINE> titulo = models.CharField(max_length=200) <NEW_LINE> autor = models.CharField(max_length=200) <NEW_LINE> pais = models.ForeignKey(Pais) <NEW_LINE> texto = models.TextField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "Noticias" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.titulo <NEW_LINE> <DEDENT> def adjunto(self): <NEW_LINE> <INDENT> adjunto = Galeria.objects.filter(noticia__id=self.id) <NEW_LINE> return adjunto | Modelo que contendra las noticias del sitio
| 6259907b2c8b7c6e89bd5200 |
@endpoint("openapi/port/v1/accounts/subscriptions/", "POST", 201) <NEW_LINE> class SubscriptionCreate(Portfolio): <NEW_LINE> <INDENT> HEADERS = {"Content-Type": "application/json"} <NEW_LINE> @dyndoc_insert(responses) <NEW_LINE> def __init__(self, data): <NEW_LINE> <INDENT> super(SubscriptionCreate, self).__init__() <NEW_LINE> self.data = data | Set up a subscription and returns an initial snapshot containing
a list of accounts as specified by the parameters in the request. | 6259907b71ff763f4b5e91c1 |
class CreateSkyDome(QueenbeeTask): <NEW_LINE> <INDENT> _input_params = luigi.DictParameter() <NEW_LINE> @property <NEW_LINE> def sky_density(self): <NEW_LINE> <INDENT> return self._input_params['sky_density'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def execution_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self._input_params['simulation_folder']).as_posix() <NEW_LINE> <DEDENT> @property <NEW_LINE> def initiation_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self._input_params['simulation_folder']).as_posix() <NEW_LINE> <DEDENT> @property <NEW_LINE> def params_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self.execution_folder, self._input_params['params_folder']).resolve().as_posix() <NEW_LINE> <DEDENT> def command(self): <NEW_LINE> <INDENT> return 'honeybee-radiance sky skydome --name rflux_sky.sky --sky-density {sky_density}'.format(sky_density=self.sky_density) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return { 'sky_dome': luigi.LocalTarget( pathlib.Path(self.execution_folder, 'resources/sky.dome').resolve().as_posix() ) } <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_artifacts(self): <NEW_LINE> <INDENT> return [ { 'name': 'sky-dome', 'from': 'rflux_sky.sky', 'to': pathlib.Path(self.execution_folder, 'resources/sky.dome').resolve().as_posix(), 'optional': False, 'type': 'file' }] | Create a skydome for daylight coefficient studies. | 6259907b1b99ca4002290240 |
@implementer(IMessage) <NEW_LINE> class Cancel(Message): <NEW_LINE> <INDENT> MESSAGE_TYPE = 49 <NEW_LINE> SKIP = 'skip' <NEW_LINE> ABORT = 'abort' <NEW_LINE> KILL = 'kill' <NEW_LINE> def __init__(self, request, mode = None): <NEW_LINE> <INDENT> Message.__init__(self) <NEW_LINE> self.request = request <NEW_LINE> self.mode = mode <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(wmsg): <NEW_LINE> <INDENT> assert(len(wmsg) > 0 and wmsg[0] == Cancel.MESSAGE_TYPE) <NEW_LINE> if len(wmsg) != 3: <NEW_LINE> <INDENT> raise ProtocolError("invalid message length {} for CANCEL".format(len(wmsg))) <NEW_LINE> <DEDENT> request = check_or_raise_id(wmsg[1], "'request' in CANCEL") <NEW_LINE> options = check_or_raise_extra(wmsg[2], "'options' in CANCEL") <NEW_LINE> mode = None <NEW_LINE> if options.has_key('mode'): <NEW_LINE> <INDENT> option_mode = options['mode'] <NEW_LINE> if type(option_mode) not in (str, unicode): <NEW_LINE> <INDENT> raise ProtocolError("invalid type {} for 'mode' option in CANCEL".format(type(option_mode))) <NEW_LINE> <DEDENT> if option_mode not in [Cancel.SKIP, Cancel.ABORT, Cancel.KILL]: <NEW_LINE> <INDENT> raise ProtocolError("invalid value '{}' for 'mode' option in CANCEL".format(option_mode)) <NEW_LINE> <DEDENT> mode = option_mode <NEW_LINE> <DEDENT> obj = Cancel(request, mode = mode) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> options = {} <NEW_LINE> if self.mode is not None: <NEW_LINE> <INDENT> options['mode'] = self.mode <NEW_LINE> <DEDENT> return [Cancel.MESSAGE_TYPE, self.request, options] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "WAMP CANCEL Message (request = {}, mode = '{}'')".format(self.request, self.mode) | A WAMP `CANCEL` message.
Format: `[CANCEL, CALL.Request|id, Options|dict]` | 6259907bbf627c535bcb2ee5 |
class Solver1D(AbstractSolver): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> super(Solver1D, self).__init__(model) <NEW_LINE> <DEDENT> def solve(self, *args, **kwargs): <NEW_LINE> <INDENT> return nls.solve_nls(*args, **kwargs) <NEW_LINE> <DEDENT> def chemicalPotentialRoutine(self, *args, **kwargs): <NEW_LINE> <INDENT> return nls.chemical_potential_1d(*args, **kwargs) | One dimensional solver that call native Fortran routine that solves NLS equation in axial symmentry in 2D.
| 6259907bbe7bc26dc9252b60 |
class TestContainerManager(TestCase): <NEW_LINE> <INDENT> IMAGE = "busybox" <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> docker_client = docker.from_env() <NEW_LINE> TestContainerManager._remove_image(docker_client) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.manager = ContainerManager() <NEW_LINE> self.docker_client = docker.from_env() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self._remove_image(self.docker_client) <NEW_LINE> <DEDENT> def test_pull_image(self): <NEW_LINE> <INDENT> self.assertFalse(self.manager.has_image(self.IMAGE)) <NEW_LINE> self.manager.pull_image(self.IMAGE) <NEW_LINE> self.assertTrue(self.manager.has_image(self.IMAGE)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _remove_image(cls, docker_client): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> docker_client.images.remove(cls.IMAGE) <NEW_LINE> <DEDENT> except docker.errors.ImageNotFound: <NEW_LINE> <INDENT> pass | Verifies functionality of ContainerManager by calling Docker APIs | 6259907b796e427e53850190 |
class RVegan(RPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/vegandevs/vegan" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/vegan_2.4-3.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/vegan" <NEW_LINE> version('2.5-7', sha256='e63b586951ea7d8b0118811f329c700212892ec1db3b93951603ce1d68aa462a') <NEW_LINE> version('2.5-5', sha256='876b5266f29f3034fed881020d16f476e62d145a00cb450a1a213e019e056971') <NEW_LINE> version('2.5-4', sha256='5116a440111fca49b5f95cfe888b180ff29a112e6301d5e2ac5cae0e628493e0') <NEW_LINE> version('2.4-3', sha256='2556b1281a62e53f32bb57539bc600c00a599d0699867912220535d1a3ebec97') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', when='@2.5-1', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', when='@2.5-2:2.5-4', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', when='@2.5-5:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('r-lattice', type=('build', 'run')) <NEW_LINE> depends_on('r-mass', type=('build', 'run')) <NEW_LINE> depends_on('r-cluster', type=('build', 'run')) <NEW_LINE> depends_on('r-mgcv', type=('build', 'run')) | Community Ecology Package
Ordination methods, diversity analysis and other functions for
community and vegetation ecologists. | 6259907baad79263cf4301cf |
class IndependentPipelineManager(PipelineManager): <NEW_LINE> <INDENT> changes_merge = False <NEW_LINE> def _postConfig(self, layout): <NEW_LINE> <INDENT> super(IndependentPipelineManager, self)._postConfig(layout) <NEW_LINE> <DEDENT> def getChangeQueue(self, change, event, existing=None): <NEW_LINE> <INDENT> log = get_annotated_logger(self.log, event) <NEW_LINE> if existing: <NEW_LINE> <INDENT> return DynamicChangeQueueContextManager(existing) <NEW_LINE> <DEDENT> change_queue = model.ChangeQueue(self.pipeline) <NEW_LINE> change_queue.addProject(change.project) <NEW_LINE> self.pipeline.addQueue(change_queue) <NEW_LINE> log.debug("Dynamically created queue %s", change_queue) <NEW_LINE> return DynamicChangeQueueContextManager(change_queue) <NEW_LINE> <DEDENT> def enqueueChangesAhead(self, change, event, quiet, ignore_requirements, change_queue, history=None): <NEW_LINE> <INDENT> log = get_annotated_logger(self.log, event) <NEW_LINE> if hasattr(change, 'number'): <NEW_LINE> <INDENT> history = history or [] <NEW_LINE> history = history + [change] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> ret = self.checkForChangesNeededBy(change, change_queue, event) <NEW_LINE> if ret in [True, False]: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> log.debug(" Changes %s must be merged ahead of %s" % (ret, change)) <NEW_LINE> for needed_change in ret: <NEW_LINE> <INDENT> r = self.addChange(needed_change, event, quiet=True, ignore_requirements=True, live=False, change_queue=change_queue, history=history) <NEW_LINE> if not r: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def checkForChangesNeededBy(self, change, change_queue, event): <NEW_LINE> <INDENT> log = get_annotated_logger(self.log, event) <NEW_LINE> if self.pipeline.ignore_dependencies: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> log.debug("Checking for changes needed by %s:" % change) <NEW_LINE> if (hasattr(change, 'commit_needs_changes') and (change.refresh_deps or change.commit_needs_changes is None)): <NEW_LINE> <INDENT> self.updateCommitDependencies(change, None, event) <NEW_LINE> <DEDENT> if not hasattr(change, 'needs_changes'): <NEW_LINE> <INDENT> log.debug(" %s does not support dependencies" % type(change)) <NEW_LINE> return True <NEW_LINE> <DEDENT> if not change.needs_changes: <NEW_LINE> <INDENT> log.debug(" No changes needed") <NEW_LINE> return True <NEW_LINE> <DEDENT> changes_needed = [] <NEW_LINE> for needed_change in change.needs_changes: <NEW_LINE> <INDENT> log.debug(" Change %s needs change %s:" % ( change, needed_change)) <NEW_LINE> if needed_change.is_merged: <NEW_LINE> <INDENT> log.debug(" Needed change is merged") <NEW_LINE> continue <NEW_LINE> <DEDENT> if self.isChangeAlreadyInQueue(needed_change, change_queue): <NEW_LINE> <INDENT> log.debug(" Needed change is already ahead in the queue") <NEW_LINE> continue <NEW_LINE> <DEDENT> log.debug(" Change %s is needed" % needed_change) <NEW_LINE> if needed_change not in changes_needed: <NEW_LINE> <INDENT> changes_needed.append(needed_change) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> if changes_needed: <NEW_LINE> <INDENT> return changes_needed <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def dequeueItem(self, item): <NEW_LINE> <INDENT> super(IndependentPipelineManager, self).dequeueItem(item) <NEW_LINE> if not item.queue.queue: <NEW_LINE> <INDENT> self.pipeline.removeQueue(item.queue) | PipelineManager that puts every Change into its own ChangeQueue. | 6259907bd268445f2663a869 |
class Ship(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_game): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.screen_rect = ai_game.screen.get_rect() <NEW_LINE> """ Load the ship image and get its rect """ <NEW_LINE> self.image = pygame.image.load("images/ship.bmp") <NEW_LINE> self.image.convert() <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.center_ship() <NEW_LINE> self.moving_right = False <NEW_LINE> self.moving_left = False <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.moving_right and self.rect.right < self.screen_rect.right: <NEW_LINE> <INDENT> self.float_x += self.settings.ship_speed <NEW_LINE> <DEDENT> if self.moving_left and self.rect.left > 0: <NEW_LINE> <INDENT> self.float_x -= self.settings.ship_speed <NEW_LINE> <DEDENT> self.rect.x = self.float_x <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def center_ship(self): <NEW_LINE> <INDENT> self.rect.midbottom = self.screen_rect.midbottom <NEW_LINE> self.float_x = float(self.rect.x) | A class to manage the ship | 6259907b97e22403b383c917 |
class SelectorCV(ModelSelector): <NEW_LINE> <INDENT> def calc_best_score_cv(self, score_cv): <NEW_LINE> <INDENT> return max(score_cv, key = lambda x: x[0]) <NEW_LINE> <DEDENT> def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> kf = KFold(n_splits = 3, shuffle = False, random_state = None) <NEW_LINE> log_likelihoods = [] <NEW_LINE> score_cvs = [] <NEW_LINE> for num_states in range(self.min_n_components, self.max_n_components + 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(self.sequences) > 2: <NEW_LINE> <INDENT> for train_index, test_index in kf.split(self.sequences): <NEW_LINE> <INDENT> self.X, self.lengths = combine_sequences(train_index, self.sequences) <NEW_LINE> X_test, lengths_test = combine_sequences(test_index, self.sequences) <NEW_LINE> hmm_model = self.base_model(num_states) <NEW_LINE> log_likelihood = hmm_model.score(X_test, lengths_test) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> hmm_model = self.base_model(num_states) <NEW_LINE> log_likelihood = hmm_model.score(self.X, self.lengths) <NEW_LINE> <DEDENT> log_likelihoods.append(log_likelihood) <NEW_LINE> score_cvs_avg = np.mean(log_likelihoods) <NEW_LINE> score_cvs.append(tuple([score_cvs_avg, hmm_model])) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self.calc_best_score_cv(score_cvs)[1] if score_cvs else None | select best model based on average log Likelihood of cross-validation folds
| 6259907b7d43ff2487428120 |
class S3Control(Control): <NEW_LINE> <INDENT> def __init__(self, descriptor=None, endpoint_url=None): <NEW_LINE> <INDENT> self.setinitial("endpointUrl", endpoint_url) <NEW_LINE> super().__init__(descriptor) <NEW_LINE> <DEDENT> @property <NEW_LINE> def endpoint_url(self): <NEW_LINE> <INDENT> return ( self.get("endpointUrl") or os.environ.get("S3_ENDPOINT_URL") or DEFAULT_ENDPOINT_URL ) <NEW_LINE> <DEDENT> def expand(self): <NEW_LINE> <INDENT> self.setdefault("endpointUrl", self.endpoint_url) <NEW_LINE> <DEDENT> metadata_profile = { "type": "object", "additionalProperties": False, "properties": { "endpointUrl": {"type": "string"}, }, } | S3 control representation
API | Usage
-------- | --------
Public | `from frictionless.plugins.s3 import S3Control`
Parameters:
descriptor? (str|dict): descriptor
endpoint_url? (string): endpoint url
Raises:
FrictionlessException: raise any error that occurs during the process | 6259907b5fdd1c0f98e5f996 |
class item_ensemble_input: <NEW_LINE> <INDENT> def __init__(self, location_type='url', item_locations=[]): <NEW_LINE> <INDENT> self.items = [] <NEW_LINE> self.location_type = location_type <NEW_LINE> self.item_locations = item_locations <NEW_LINE> <DEDENT> def label_items(self, item_dict): <NEW_LINE> <INDENT> for i, item_location in enumerate(self.item_locations): <NEW_LINE> <INDENT> self.items.append( clothing_item_input(location_type=self.location_type, location=item_location) ) <NEW_LINE> self.items[i].label_item(item_dict=item_dict) <NEW_LINE> <DEDENT> <DEDENT> def find_existing_categories(self): <NEW_LINE> <INDENT> self.existing_categories = [item.item_category for item in self.items] <NEW_LINE> return(self.existing_categories) <NEW_LINE> <DEDENT> def find_missing_categories(self, category_list=None): <NEW_LINE> <INDENT> if category_list==None: <NEW_LINE> <INDENT> raise ValueError('Need to provide list of clothing categories.') <NEW_LINE> return <NEW_LINE> <DEDENT> self.find_existing_categories() <NEW_LINE> self.missing_categories = [cat for cat in category_list if cat not in self.existing_categories] | need location_type='url' or 'local'
provide list of local paths or urls | 6259907b91f36d47f2231b9a |
class PycbcSplitInspinjExecutable(Executable): <NEW_LINE> <INDENT> current_retention_level = Executable.INTERMEDIATE_PRODUCT <NEW_LINE> def __init__(self, cp, exe_name, num_splits, universe=None, ifo=None, out_dir=None): <NEW_LINE> <INDENT> super(PycbcSplitInspinjExecutable, self).__init__(cp, exe_name, universe, ifo, out_dir, tags=[]) <NEW_LINE> self.num_splits = int(num_splits) <NEW_LINE> <DEDENT> def create_node(self, parent, tags=None): <NEW_LINE> <INDENT> if tags is None: <NEW_LINE> <INDENT> tags = [] <NEW_LINE> <DEDENT> node = Node(self) <NEW_LINE> node.add_input_opt('--input-file', parent) <NEW_LINE> if parent.name.endswith("gz"): <NEW_LINE> <INDENT> ext = ".xml.gz" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ext = ".xml" <NEW_LINE> <DEDENT> out_files = FileList([]) <NEW_LINE> for i in range(self.num_splits): <NEW_LINE> <INDENT> curr_tag = 'split%d' % i <NEW_LINE> curr_tags = parent.tags + [curr_tag] <NEW_LINE> job_tag = parent.description + "_" + self.name.upper() <NEW_LINE> out_file = File(parent.ifo_list, job_tag, parent.segment, extension=ext, directory=self.out_dir, tags=curr_tags, store_file=self.retain_files) <NEW_LINE> out_files.append(out_file) <NEW_LINE> <DEDENT> node.add_output_list_opt('--output-files', out_files) <NEW_LINE> return node | The class responsible for running the pycbc_split_inspinj executable | 6259907b5166f23b2e244dee |
class WSGIApplication(web.Application): <NEW_LINE> <INDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> return WSGIAdapter(self)(environ, start_response) | A WSGI equivalent of `tornado.web.Application`.
.. deprecated: 3.3::
Use a regular `.Application` and wrap it in `WSGIAdapter` instead. | 6259907bad47b63b2c5a9266 |
class DeVilliersGlasser01(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=4): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounds = list(zip([1.0] * self.dimensions, [100.0] * self.dimensions)) <NEW_LINE> self.global_optimum = [60.137, 1.371, 3.112, 1.761] <NEW_LINE> self.fglob = 0.0 <NEW_LINE> <DEDENT> def evaluator(self, x, *args): <NEW_LINE> <INDENT> self.fun_evals += 1 <NEW_LINE> t_i = 0.1*numpy.arange(24) <NEW_LINE> y_i = 60.137*(1.371**t_i)*sin(3.112*t_i + 1.761) <NEW_LINE> x1, x2, x3, x4 = x <NEW_LINE> return sum((x1*(x2**t_i)*sin(x3*t_i + x4) - y_i)**2.0) | DeVilliers-Glasser 1 test objective function.
This class defines the DeVilliers-Glasser 1 function global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{DeVilliersGlasser01}}(\mathbf{x}) = \sum_{i=1}^{24} \left[ x_1x_2^{t_i} \sin(x_3t_i + x_4) - y_i \right ]^2
Where, in this exercise, :math:`t_i = 0.1(i-1)` and :math:`y_i = 60.137(1.371^{t_i}) \sin(3.112t_i + 1.761)`.
Here, :math:`n` represents the number of dimensions and :math:`x_i \in [1, 100]` for :math:`i=1,...,n`.
*Global optimum*: :math:`f(x_i) = 0` for :math:`x_i = 0` for :math:`\mathbf{x} = [60.137, 1.371, 3.112, 1.761]`. | 6259907b283ffb24f3cf52b7 |
class PerSourceFlag(SandboxDerived): <NEW_LINE> <INDENT> __slots__ = ( 'file_name', 'flags', ) <NEW_LINE> def __init__(self, sandbox, file_name, flags): <NEW_LINE> <INDENT> SandboxDerived.__init__(self, sandbox) <NEW_LINE> self.file_name = file_name <NEW_LINE> self.flags = flags | Describes compiler flags specified for individual source files. | 6259907b4a966d76dd5f08fd |
class EntityCache(caching.ProcessScopedSingleton): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_cache_len(cls): <NEW_LINE> <INDENT> return len(cls.instance()._cache.items.keys()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_cache_size(cls): <NEW_LINE> <INDENT> return cls.instance()._cache.total_size <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._cache = caching.LRUCache(max_size_bytes=max_size_bytes) <NEW_LINE> self._cache.get_entry_size = self._get_entry_size <NEW_LINE> <DEDENT> def _get_entry_size(self, key, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return sys.getsizeof(key) + sys.getsizeof(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cache(self): <NEW_LINE> <INDENT> return self._cache | This class holds in-process global cache of objects. | 6259907bbf627c535bcb2ee7 |
class TestCredentials(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_credentials = Credentials("Twitter","Muriuki","1234yruty") <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> self.assertEqual(self.new_credentials.account_name,"Twitter") <NEW_LINE> self.assertEqual(self.new_credentials.username,"Muriuki") <NEW_LINE> self.assertEqual(self.new_credentials.password,"1234yruty") <NEW_LINE> <DEDENT> def test_save_credentials(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> self.assertEqual(len(Credentials.credentials_list),1) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> Credentials.credentials_list = [] <NEW_LINE> <DEDENT> def test_delete_credentials(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> test_credentials = Credentials("Test","user","kwekwe") <NEW_LINE> test_credentials.save_credentials() <NEW_LINE> self.new_credentials.delete_credentials() <NEW_LINE> self.assertEqual(len(Credentials.credentials_list),1) <NEW_LINE> <DEDENT> def test_save_multiple_credentials(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> test_credentials = Credentials("Test","user","test@user") <NEW_LINE> test_credentials.save_credentials() <NEW_LINE> self.assertEqual(len(Credentials.credentials_list),2) <NEW_LINE> <DEDENT> def test_find_credentials_by_accountname(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> test_credentials = Credentials("Test","user","test@user") <NEW_LINE> test_credentials.save_credentials() <NEW_LINE> found_credentials = Credentials.find_by_accountname("Test") <NEW_LINE> self.assertEqual(found_credentials.password,test_credentials.password) <NEW_LINE> <DEDENT> def test_credentials_exists(self): <NEW_LINE> <INDENT> self.new_credentials.save_credentials() <NEW_LINE> test_credentials = Credentials("Test","user","test@user") <NEW_LINE> test_credentials.save_credentials() <NEW_LINE> credentials_exists = Credentials.credentials_exist("Test") <NEW_LINE> self.assertTrue(credentials_exists) <NEW_LINE> <DEDENT> def test_display_all_credentials(self): <NEW_LINE> <INDENT> self.assertEqual(Credentials.display_credentials(),Credentials.credentials_list) | Test class that defines test cases for the Credentials class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases | 6259907b796e427e53850192 |
class BadDataException(MetadbException): <NEW_LINE> <INDENT> pass | Should be used when incorrect data is being submitted. | 6259907bf548e778e596cfa9 |
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) <NEW_LINE> class AddBackendAlpha(AddBackendBeta): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> flags.GLOBAL_REGIONAL_BACKEND_SERVICE_ARG.AddArgument(parser) <NEW_LINE> backend_flags.AddDescription(parser) <NEW_LINE> flags.MULTISCOPE_INSTANCE_GROUP_ARG.AddArgument( parser, operation_type='add to the backend service') <NEW_LINE> backend_flags.AddBalancingMode(parser) <NEW_LINE> backend_flags.AddCapacityLimits(parser) <NEW_LINE> backend_flags.AddCapacityScalar(parser) | Add a backend to a backend service.
*{command}* is used to add a backend to a backend service. A
backend is a group of tasks that can handle requests sent to a
backend service. Currently, the group of tasks can be one or
more Google Compute Engine virtual machine instances grouped
together using an instance group.
Traffic is first spread evenly across all virtual machines in
the group. When the group is full, traffic is sent to the next
nearest group(s) that still have remaining capacity.
To modify the parameters of a backend after it has been added
to the backend service, use
`gcloud compute backend-services update-backend` or
`gcloud compute backend-services edit`. | 6259907b3346ee7daa33836d |
@attr(shard=2) <NEW_LINE> class DiscussionOpenClosedThreadTest(BaseDiscussionTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(DiscussionOpenClosedThreadTest, self).setUp() <NEW_LINE> self.thread_id = "test_thread_{}".format(uuid4().hex) <NEW_LINE> <DEDENT> def setup_user(self, roles=[]): <NEW_LINE> <INDENT> roles_str = ','.join(roles) <NEW_LINE> self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() <NEW_LINE> <DEDENT> def setup_view(self, **thread_kwargs): <NEW_LINE> <INDENT> thread_kwargs.update({'commentable_id': self.discussion_id}) <NEW_LINE> view = SingleThreadViewFixture( Thread(id=self.thread_id, **thread_kwargs) ) <NEW_LINE> view.addResponse(Response(id="response1")) <NEW_LINE> view.push() <NEW_LINE> <DEDENT> def setup_openclosed_thread_page(self, closed=False): <NEW_LINE> <INDENT> self.setup_user(roles=['Moderator']) <NEW_LINE> if closed: <NEW_LINE> <INDENT> self.setup_view(closed=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setup_view() <NEW_LINE> <DEDENT> page = self.create_single_thread_page(self.thread_id) <NEW_LINE> page.visit() <NEW_LINE> page.close_open_thread() <NEW_LINE> return page <NEW_LINE> <DEDENT> def test_originally_open_thread_vote_display(self): <NEW_LINE> <INDENT> page = self.setup_openclosed_thread_page() <NEW_LINE> self.assertFalse(page.is_element_visible('.thread-main-wrapper .action-vote')) <NEW_LINE> self.assertTrue(page.is_element_visible('.thread-main-wrapper .display-vote')) <NEW_LINE> self.assertFalse(page.is_element_visible('.response_response1 .action-vote')) <NEW_LINE> self.assertTrue(page.is_element_visible('.response_response1 .display-vote')) <NEW_LINE> <DEDENT> def test_originally_closed_thread_vote_display(self): <NEW_LINE> <INDENT> page = self.setup_openclosed_thread_page(True) <NEW_LINE> self.assertTrue(page.is_element_visible('.thread-main-wrapper .action-vote')) <NEW_LINE> self.assertFalse(page.is_element_visible('.thread-main-wrapper .display-vote')) <NEW_LINE> self.assertTrue(page.is_element_visible('.response_response1 .action-vote')) <NEW_LINE> self.assertFalse(page.is_element_visible('.response_response1 .display-vote')) <NEW_LINE> <DEDENT> @attr('a11y') <NEW_LINE> def test_page_accessibility(self): <NEW_LINE> <INDENT> page = self.setup_openclosed_thread_page() <NEW_LINE> page.a11y_audit.config.set_rules({ 'ignore': [ 'section', 'aria-valid-attr-value', 'color-contrast', 'link-href', 'icon-aria-hidden', ] }) <NEW_LINE> page.a11y_audit.check_for_accessibility_errors() <NEW_LINE> page = self.setup_openclosed_thread_page(True) <NEW_LINE> page.a11y_audit.config.set_rules({ 'ignore': [ 'section', 'aria-valid-attr-value', 'color-contrast', 'link-href', 'icon-aria-hidden', ] }) <NEW_LINE> page.a11y_audit.check_for_accessibility_errors() | Tests for checking the display of attributes on open and closed threads | 6259907b56b00c62f0fb42ec |
class MixedSourceEstimate(_BaseSourceEstimate): <NEW_LINE> <INDENT> @verbose <NEW_LINE> def __init__(self, data, vertices=None, tmin=None, tstep=None, subject=None, verbose=None): <NEW_LINE> <INDENT> if not isinstance(vertices, list) or len(vertices) < 2: <NEW_LINE> <INDENT> raise ValueError('Vertices must be a list of numpy arrays with ' 'one array per source space.') <NEW_LINE> <DEDENT> _BaseSourceEstimate.__init__(self, data, vertices=vertices, tmin=tmin, tstep=tstep, subject=subject, verbose=verbose) <NEW_LINE> <DEDENT> def plot_surface(self, src, subject=None, surface='inflated', hemi='lh', colormap='auto', time_label='time=%02.f ms', smoothing_steps=10, transparent=None, alpha=1.0, time_viewer=False, config_opts=None, subjects_dir=None, figure=None, views='lat', colorbar=True, clim='auto'): <NEW_LINE> <INDENT> surf = _ensure_src(src, kind='surf') <NEW_LINE> data = self.data[:surf[0]['nuse'] + surf[1]['nuse']] <NEW_LINE> vertices = [s['vertno'] for s in surf] <NEW_LINE> stc = SourceEstimate(data, vertices, self.tmin, self.tstep, self.subject, self.verbose) <NEW_LINE> return plot_source_estimates(stc, subject, surface=surface, hemi=hemi, colormap=colormap, time_label=time_label, smoothing_steps=smoothing_steps, transparent=transparent, alpha=alpha, time_viewer=time_viewer, config_opts=config_opts, subjects_dir=subjects_dir, figure=figure, views=views, colorbar=colorbar, clim=clim) | Container for mixed surface and volume source estimates.
Parameters
----------
data : array of shape (n_dipoles, n_times) | 2-tuple (kernel, sens_data)
The data in source space. The data can either be a single array or
a tuple with two arrays: "kernel" shape (n_vertices, n_sensors) and
"sens_data" shape (n_sensors, n_times). In this case, the source
space data corresponds to "numpy.dot(kernel, sens_data)".
vertices : list of arrays
Vertex numbers corresponding to the data.
tmin : scalar
Time point of the first sample in data.
tstep : scalar
Time step between successive samples in data.
subject : str | None
The subject name. While not necessary, it is safer to set the
subject parameter to avoid analysis errors.
verbose : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
Attributes
----------
subject : str | None
The subject name.
times : array of shape (n_times,)
The time vector.
vertices : list of arrays of shape (n_dipoles,)
The indices of the dipoles in each source space.
data : array of shape (n_dipoles, n_times)
The data in source space.
shape : tuple
The shape of the data. A tuple of int (n_dipoles, n_times).
Notes
-----
.. versionadded:: 0.9.0
See Also
--------
SourceEstimate : A container for surface source estimates.
VectorSourceEstimate : A container for vector source estimates.
VolSourceEstimate : A container for volume source estimates. | 6259907b3539df3088ecdcb0 |
class MultiGetFileTestFlow(flow.GRRFlow): <NEW_LINE> <INDENT> args_type = MultiGetFileTestFlowArgs <NEW_LINE> @flow.StateHandler(next_state=["HashFile"]) <NEW_LINE> def Start(self): <NEW_LINE> <INDENT> self.state.Register("client_hashes", {}) <NEW_LINE> urandom = rdf_paths.PathSpec(path="/dev/urandom", pathtype=rdf_paths.PathSpec.PathType.OS) <NEW_LINE> for _ in range(self.args.file_limit): <NEW_LINE> <INDENT> self.CallClient("CopyPathToFile", offset=0, length=2 * 1024 * 1024, src_path=urandom, dest_dir="", gzip_output=False, lifetime=600, next_state="HashFile") <NEW_LINE> <DEDENT> <DEDENT> @flow.StateHandler(next_state=["MultiGetFile"]) <NEW_LINE> def HashFile(self, responses): <NEW_LINE> <INDENT> if not responses.success: <NEW_LINE> <INDENT> raise flow.FlowError(responses.status) <NEW_LINE> <DEDENT> for response in responses: <NEW_LINE> <INDENT> self.CallFlow("FingerprintFile", next_state="MultiGetFile", pathspec=response.dest_path) <NEW_LINE> <DEDENT> <DEDENT> @flow.StateHandler(next_state="VerifyHashes") <NEW_LINE> def MultiGetFile(self, responses): <NEW_LINE> <INDENT> if not responses.success: <NEW_LINE> <INDENT> raise flow.FlowError(responses.status) <NEW_LINE> <DEDENT> for response in responses: <NEW_LINE> <INDENT> fd = aff4.FACTORY.Open(response.file_urn, "VFSFile", mode="r", token=self.token) <NEW_LINE> binary_hash = fd.Get(fd.Schema.FINGERPRINT) <NEW_LINE> hash_digest = binary_hash.results[0].GetItem("sha256").encode("hex") <NEW_LINE> self.state.client_hashes[str(response.file_urn)] = hash_digest <NEW_LINE> self.CallFlow("MultiGetFile", pathspecs=[binary_hash.pathspec], next_state="VerifyHashes") <NEW_LINE> <DEDENT> <DEDENT> @flow.StateHandler() <NEW_LINE> def VerifyHashes(self, responses): <NEW_LINE> <INDENT> if not responses.success: <NEW_LINE> <INDENT> raise flow.FlowError(responses.status) <NEW_LINE> <DEDENT> for response in responses: <NEW_LINE> <INDENT> fd = aff4.FACTORY.Open(response.aff4path, "VFSBlobImage", mode="r", token=self.token) <NEW_LINE> server_hash = hashlib.sha256(fd.Read(response.st_size)).hexdigest() <NEW_LINE> client_hash = self.state.client_hashes[response.aff4path] <NEW_LINE> if server_hash != client_hash: <NEW_LINE> <INDENT> format_string = ("Hash mismatch server hash: %s doesn't match" "client hash: %s for file: %s") <NEW_LINE> raise flow.FlowError(format_string % (server_hash, client_hash, response.aff4path)) | This flow checks MultiGetFile correctly transfers files. | 6259907baad79263cf4301d2 |
class Topology(object): <NEW_LINE> <INDENT> swagger_types = { 'nodes': 'list[str]', 'links': 'list[str]' } <NEW_LINE> attribute_map = { 'nodes': 'nodes', 'links': 'links' } <NEW_LINE> def __init__(self, nodes=None, links=None): <NEW_LINE> <INDENT> self._nodes = None <NEW_LINE> self._links = None <NEW_LINE> self.discriminator = None <NEW_LINE> if nodes is not None: <NEW_LINE> <INDENT> self.nodes = nodes <NEW_LINE> <DEDENT> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def nodes(self): <NEW_LINE> <INDENT> return self._nodes <NEW_LINE> <DEDENT> @nodes.setter <NEW_LINE> def nodes(self, nodes): <NEW_LINE> <INDENT> self._nodes = nodes <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._links <NEW_LINE> <DEDENT> @links.setter <NEW_LINE> def links(self, links): <NEW_LINE> <INDENT> self._links = links <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(Topology, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Topology): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907b5166f23b2e244df0 |
class CTD_ANON_ (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_EMPTY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = None <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 54, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __label = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(Namespace, u'label'), 'label', '__httpwww_w3_org1999xlink_CTD_ANON__httpwww_w3_org1999xlinklabel', pyxb.binding.datatypes.NMTOKEN, required=True) <NEW_LINE> __label._DeclarationLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 44, 1) <NEW_LINE> __label._UseLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 57, 3) <NEW_LINE> label = property(__label.value, __label.set, None, None) <NEW_LINE> __type = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(Namespace, u'type'), 'type', '__httpwww_w3_org1999xlink_CTD_ANON__httpwww_w3_org1999xlinktype', pyxb.binding.datatypes.anySimpleType, fixed=True, unicode_default=u'resource') <NEW_LINE> __type._DeclarationLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 55, 3) <NEW_LINE> __type._UseLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 55, 3) <NEW_LINE> type = property(__type.value, __type.set, None, None) <NEW_LINE> __title = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(Namespace, u'title'), 'title', '__httpwww_w3_org1999xlink_CTD_ANON__httpwww_w3_org1999xlinktitle', pyxb.binding.datatypes.string) <NEW_LINE> __title._DeclarationLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 71, 1) <NEW_LINE> __title._UseLocation = pyxb.utils.utility.Location(u'i:\\xml_editor\\xml_editor\\schema\\xlink.xsd', 56, 3) <NEW_LINE> title = property(__title.value, __title.set, None, None) <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ __label.name() : __label, __type.name() : __type, __title.name() : __title }) | Complex type [anonymous] with content type EMPTY | 6259907b91f36d47f2231b9b |
class Transition(_FSMObjBase): <NEW_LINE> <INDENT> def __init__(self, name=None, predicates=None, instruction=None, next_state=None): <NEW_LINE> <INDENT> super(Transition, self).__init__(name) <NEW_LINE> self.predicates = predicates if predicates is not None else [] <NEW_LINE> self.instruction = instruction if instruction is not None else Instruction() <NEW_LINE> self.next_state = next_state <NEW_LINE> <DEDENT> @property <NEW_LINE> def predicates(self): <NEW_LINE> <INDENT> return self._predicates <NEW_LINE> <DEDENT> @predicates.setter <NEW_LINE> def predicates(self, val): <NEW_LINE> <INDENT> if type(val) != list: <NEW_LINE> <INDENT> raise TypeError("Predicates needs to be type list.") <NEW_LINE> <DEDENT> self._predicates = val <NEW_LINE> <DEDENT> def __call__(self, app_state): <NEW_LINE> <INDENT> for predicate in self._predicates: <NEW_LINE> <INDENT> if not predicate(app_state): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def to_desc(self): <NEW_LINE> <INDENT> for pred in self._predicates: <NEW_LINE> <INDENT> self._pb.predicates.extend([pred.to_desc()]) <NEW_LINE> <DEDENT> if self.instruction is not None: <NEW_LINE> <INDENT> self._pb.instruction.CopyFrom(self.instruction.to_desc()) <NEW_LINE> <DEDENT> if self.next_state: <NEW_LINE> <INDENT> self._pb.next_state = self.next_state.name <NEW_LINE> <DEDENT> return super(Transition, self).to_desc() <NEW_LINE> <DEDENT> def from_desc(self): <NEW_LINE> <INDENT> raise NotImplementedError("Transition itself does not know enough information " "to build from its description. " "next_state variable depends on a FSM. " "Use StateMachine Helper Class instead.") | Links among FSM states that defines state changes and results to return when changing states.
A Transition has the following components:
* transition predicates: The conditions that need to be satisfied to take this transition.
* next_state: The next FSM state to visit after taking the transition.
* instructions: Instructions returned to users when this
transition is taken. | 6259907b01c39578d7f14441 |
class FileSizeGrowsAboveThreshold(TestCompareRPMs): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.before_rpm.add_installed_file( "/some/file", rpmfluff.SourceFile("file", "a" * 5) ) <NEW_LINE> self.after_rpm.add_installed_file( "/some/file", rpmfluff.SourceFile("file", "a" * 10) ) <NEW_LINE> self.inspection = "filesize" <NEW_LINE> self.result = "VERIFY" <NEW_LINE> self.waiver_auth = "Anyone" <NEW_LINE> self.message = f"/some/file grew by 100% on {platform.machine()}" <NEW_LINE> <DEDENT> def configFile(self): <NEW_LINE> <INDENT> super().configFile() <NEW_LINE> instream = open(self.conffile, "r") <NEW_LINE> cfg = yaml.full_load(instream) <NEW_LINE> instream.close() <NEW_LINE> cfg["filesize"]["size_threshold"] = "20" <NEW_LINE> outstream = open(self.conffile, "w") <NEW_LINE> outstream.write(yaml.dump(cfg).replace("- ", " - ")) <NEW_LINE> outstream.close() | Assert when a file grows by more than the configured threshold, VERIFY result occurs. | 6259907b4f88993c371f122e |
class FromError(ElasticFeedException): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "From must be integer" | Exception raised when ElasticFeeds checks whether the from is integer. | 6259907b71ff763f4b5e91c5 |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._visited = 0 <NEW_LINE> self.discovery_time = None <NEW_LINE> self.finishing_time = None <NEW_LINE> <DEDENT> def neighbors(self, adjacency_list): <NEW_LINE> <INDENT> return adjacency_list[self] <NEW_LINE> <DEDENT> @property <NEW_LINE> def visited(self): <NEW_LINE> <INDENT> return self._visited <NEW_LINE> <DEDENT> @visited.setter <NEW_LINE> def visited(self, value): <NEW_LINE> <INDENT> if value == 1: <NEW_LINE> <INDENT> self.discovery_time = time.clock() <NEW_LINE> <DEDENT> elif value == 2: <NEW_LINE> <INDENT> self.finishing_time = time.clock() <NEW_LINE> <DEDENT> self._visited = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.name) | Represents a node. | 6259907b56ac1b37e63039ef |
class Role: <NEW_LINE> <INDENT> Feature = 'Feature' <NEW_LINE> Label = 'Label' <NEW_LINE> Weight = 'ExampleWeight' <NEW_LINE> GroupId = 'RowGroup' <NEW_LINE> User = 'User' <NEW_LINE> Item = 'Item' <NEW_LINE> Name = 'Name' <NEW_LINE> RowId = 'RowId' <NEW_LINE> @staticmethod <NEW_LINE> def get_column_name(role, suffix="ColumnName"): <NEW_LINE> <INDENT> if not isinstance(role, str): <NEW_LINE> <INDENT> raise TypeError("Unexpected role '{0}'".format(role)) <NEW_LINE> <DEDENT> if role == "Weight": <NEW_LINE> <INDENT> return Role.Weight + suffix <NEW_LINE> <DEDENT> if role == "GroupId": <NEW_LINE> <INDENT> return Role.GroupId + suffix <NEW_LINE> <DEDENT> return role + suffix <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def to_attribute(role, suffix="_column_name"): <NEW_LINE> <INDENT> if not isinstance(role, str): <NEW_LINE> <INDENT> raise TypeError("Unexpected role '{0}'".format(role)) <NEW_LINE> <DEDENT> if role == "weight": <NEW_LINE> <INDENT> return ("weight", "example_weight" + suffix) <NEW_LINE> <DEDENT> if role == "groupid": <NEW_LINE> <INDENT> return ("group_id", "row_group" + suffix) <NEW_LINE> <DEDENT> if role == "rowid": <NEW_LINE> <INDENT> return ("row_id", "row_id" + suffix) <NEW_LINE> <DEDENT> return (role.lower(), role.lower() + suffix) | See same class in *nimbusml*. | 6259907b55399d3f05627f2d |
class k_winners(torch.autograd.Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, x, dutyCycles, k, boostStrength): <NEW_LINE> <INDENT> if boostStrength > 0.0: <NEW_LINE> <INDENT> targetDensity = float(k) / x.size(1) <NEW_LINE> boostFactors = torch.exp((targetDensity - dutyCycles) * boostStrength) <NEW_LINE> boosted = x.detach() * boostFactors <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> boosted = x.detach() <NEW_LINE> <DEDENT> res = torch.zeros_like(x) <NEW_LINE> topk, indices = boosted.topk(k, sorted=False) <NEW_LINE> for i in range(x.shape[0]): <NEW_LINE> <INDENT> res[i, indices[i]] = x[i, indices[i]] <NEW_LINE> <DEDENT> ctx.save_for_backward(indices) <NEW_LINE> return res <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_output): <NEW_LINE> <INDENT> indices, = ctx.saved_tensors <NEW_LINE> grad_x = torch.zeros_like(grad_output, requires_grad=True) <NEW_LINE> for i in range(grad_output.size(0)): <NEW_LINE> <INDENT> grad_x[i, indices[i]] = grad_output[i, indices[i]] <NEW_LINE> <DEDENT> return grad_x, None, None, None | A simple K-winner take all autograd function for creating layers with sparse
output.
.. note::
Code adapted from this excellent tutorial:
https://github.com/jcjohnson/pytorch-examples | 6259907bf9cc0f698b1c5fd9 |
class GhibliStudioAdapter(BaseMovieProviderAdapter): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def parse_movies(request_body): <NEW_LINE> <INDENT> movies = {} <NEW_LINE> for movie in request_body: <NEW_LINE> <INDENT> movies[movie['url']] = { "title": movie['title'], "release_date": movie['release_date'], "people": [] } <NEW_LINE> <DEDENT> return movies <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.base_url = "https://ghibliapi.herokuapp.com" <NEW_LINE> <DEDENT> def get_people(self): <NEW_LINE> <INDENT> endpoint = f"{self.base_url}/people?fields=name,films" <NEW_LINE> request = requests.get(endpoint) <NEW_LINE> body = [] <NEW_LINE> if request.status_code == 200: <NEW_LINE> <INDENT> body = request.json() <NEW_LINE> <DEDENT> return body <NEW_LINE> <DEDENT> def get_movies(self): <NEW_LINE> <INDENT> endpoint = f"{self.base_url}/films?fields=title,url,release_date" <NEW_LINE> request = requests.get(endpoint) <NEW_LINE> body = [] <NEW_LINE> if request.status_code == 200: <NEW_LINE> <INDENT> body = request.json() <NEW_LINE> <DEDENT> return body <NEW_LINE> <DEDENT> def collect(self): <NEW_LINE> <INDENT> movies = self.get_movies() <NEW_LINE> movies = self.parse_movies(movies) <NEW_LINE> people = self.get_people() <NEW_LINE> for person in people: <NEW_LINE> <INDENT> for film in person['films']: <NEW_LINE> <INDENT> movies[film]['people'].append(person['name']) <NEW_LINE> <DEDENT> <DEDENT> movies = sorted(movies.items(), key=lambda m: m[1]['release_date'], reverse=True) <NEW_LINE> return dict(movies) | This class is adapter for GhibliStudio | 6259907b796e427e53850194 |
class SlimDriverWithSutMethod(object): <NEW_LINE> <INDENT> def init(self): <NEW_LINE> <INDENT> self._sut = _PersonInterface() <NEW_LINE> <DEDENT> def sut(self): <NEW_LINE> <INDENT> return self._sut | Fixture class to name in fitnesse table, with sut() method | 6259907b7d847024c075ddf7 |
class res_partner_followup_category(orm.Model): <NEW_LINE> <INDENT> _name = 'res.partner.followup.category' <NEW_LINE> _description = 'Partner followup category' <NEW_LINE> _columns = { 'name': fields.char('Category', size=64, required=True), 'note': fields.text('Note'), } | Followup event
| 6259907b7c178a314d78e8f8 |
class AzureMonitorPrivateLinkScopeListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[AzureMonitorPrivateLinkScope]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: List["AzureMonitorPrivateLinkScope"], next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(AzureMonitorPrivateLinkScopeListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link | Describes the list of Azure Monitor PrivateLinkScope resources.
All required parameters must be populated in order to send to Azure.
:ivar value: Required. List of Azure Monitor PrivateLinkScope definitions.
:vartype value: list[~$(python-base-namespace).v2019_10_17.models.AzureMonitorPrivateLinkScope]
:ivar next_link: The URI to get the next set of Azure Monitor PrivateLinkScope definitions if
too many PrivateLinkScopes where returned in the result set.
:vartype next_link: str | 6259907b5166f23b2e244df2 |
class CaseInsensitive(FunctionElement): <NEW_LINE> <INDENT> __visit_name__ = 'notacolumn' <NEW_LINE> name = 'CaseInsensitive' <NEW_LINE> type = VARCHAR() | Function for case insensite indexes | 6259907b656771135c48ad3d |
class Dev_Note(db.Model): <NEW_LINE> <INDENT> __tablename__ = "dev_Notice" <NEW_LINE> id = db.Column("ID", db.Integer, primary_key=True) <NEW_LINE> articlename = db.Column("ArticleName", db.Text) <NEW_LINE> article = db.Column("Article", db.Text) <NEW_LINE> createdate = db.Column("CreateDate", db.String(255)) <NEW_LINE> createuser = db.Column("CreateUser", db.String(255)) <NEW_LINE> def __init__(self, articlename, article, createdate, createuser): <NEW_LINE> <INDENT> self.article = article <NEW_LINE> self.articlename = articlename <NEW_LINE> self.createdate = createdate <NEW_LINE> self.createuser = createuser <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return { 'articlename': self.articlename, 'createuser': self.createuser, 'createdate': self.createdate, 'article': self.article } | 通知公告模型 | 6259907be1aae11d1e7cf51e |
class TestOptionSet(TestCase): <NEW_LINE> <INDENT> family = 'wikipedia' <NEW_LINE> code = 'en' <NEW_LINE> def test_non_lazy_load(self): <NEW_LINE> <INDENT> options = api.OptionSet(self.get_site(), 'recentchanges', 'show') <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> options.__setitem__('invalid_name', True) <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> options.__setitem__('anon', 'invalid_value') <NEW_LINE> <DEDENT> options['anon'] = True <NEW_LINE> self.assertCountEqual(['anon'], options._enabled) <NEW_LINE> self.assertEqual(set(), options._disabled) <NEW_LINE> self.assertLength(options, 1) <NEW_LINE> self.assertEqual(['anon'], list(options)) <NEW_LINE> self.assertEqual(['anon'], list(options.api_iter())) <NEW_LINE> options['bot'] = False <NEW_LINE> self.assertCountEqual(['anon'], options._enabled) <NEW_LINE> self.assertCountEqual(['bot'], options._disabled) <NEW_LINE> self.assertLength(options, 2) <NEW_LINE> self.assertEqual(['anon', 'bot'], list(options)) <NEW_LINE> self.assertEqual(['anon', '!bot'], list(options.api_iter())) <NEW_LINE> options.clear() <NEW_LINE> self.assertEqual(set(), options._enabled) <NEW_LINE> self.assertEqual(set(), options._disabled) <NEW_LINE> self.assertIsEmpty(options) <NEW_LINE> self.assertEqual([], list(options)) <NEW_LINE> self.assertEqual([], list(options.api_iter())) <NEW_LINE> <DEDENT> def test_lazy_load(self): <NEW_LINE> <INDENT> options = api.OptionSet() <NEW_LINE> options['invalid_name'] = True <NEW_LINE> options['anon'] = True <NEW_LINE> self.assertIn('invalid_name', options._enabled) <NEW_LINE> self.assertLength(options, 2) <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> options._set_site(self.get_site(), 'recentchanges', 'show') <NEW_LINE> <DEDENT> self.assertLength(options, 2) <NEW_LINE> options._set_site(self.get_site(), 'recentchanges', 'show', True) <NEW_LINE> self.assertLength(options, 1) <NEW_LINE> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> options._set_site(self.get_site(), 'recentchanges', 'show') | OptionSet class test class. | 6259907b091ae35668706659 |
class WindowsConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'provision_vm_agent': {'key': 'provisionVMAgent', 'type': 'bool'}, 'enable_automatic_updates': {'key': 'enableAutomaticUpdates', 'type': 'bool'}, 'time_zone': {'key': 'timeZone', 'type': 'str'}, 'additional_unattend_content': {'key': 'additionalUnattendContent', 'type': '[AdditionalUnattendContent]'}, 'patch_settings': {'key': 'patchSettings', 'type': 'PatchSettings'}, 'win_rm': {'key': 'winRM', 'type': 'WinRMConfiguration'}, } <NEW_LINE> def __init__( self, *, provision_vm_agent: Optional[bool] = None, enable_automatic_updates: Optional[bool] = None, time_zone: Optional[str] = None, additional_unattend_content: Optional[List["AdditionalUnattendContent"]] = None, patch_settings: Optional["PatchSettings"] = None, win_rm: Optional["WinRMConfiguration"] = None, **kwargs ): <NEW_LINE> <INDENT> super(WindowsConfiguration, self).__init__(**kwargs) <NEW_LINE> self.provision_vm_agent = provision_vm_agent <NEW_LINE> self.enable_automatic_updates = enable_automatic_updates <NEW_LINE> self.time_zone = time_zone <NEW_LINE> self.additional_unattend_content = additional_unattend_content <NEW_LINE> self.patch_settings = patch_settings <NEW_LINE> self.win_rm = win_rm | Specifies Windows operating system settings on the virtual machine.
:ivar provision_vm_agent: Indicates whether virtual machine agent should be provisioned on the
virtual machine. :code:`<br>`:code:`<br>` When this property is not specified in the request
body, default behavior is to set it to true. This will ensure that VM Agent is installed on
the VM so that extensions can be added to the VM later.
:vartype provision_vm_agent: bool
:ivar enable_automatic_updates: Indicates whether Automatic Updates is enabled for the Windows
virtual machine. Default value is true. :code:`<br>`:code:`<br>` For virtual machine scale
sets, this property can be updated and updates will take effect on OS reprovisioning.
:vartype enable_automatic_updates: bool
:ivar time_zone: Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time".
:code:`<br>`:code:`<br>` Possible values can be `TimeZoneInfo.Id
<https://docs.microsoft.com/dotnet/api/system.timezoneinfo.id?#System_TimeZoneInfo_Id>`_ value
from time zones returned by `TimeZoneInfo.GetSystemTimeZones
<https://docs.microsoft.com/dotnet/api/system.timezoneinfo.getsystemtimezones>`_.
:vartype time_zone: str
:ivar additional_unattend_content: Specifies additional base-64 encoded XML formatted
information that can be included in the Unattend.xml file, which is used by Windows Setup.
:vartype additional_unattend_content:
list[~azure.mgmt.compute.v2021_07_01.models.AdditionalUnattendContent]
:ivar patch_settings: [Preview Feature] Specifies settings related to VM Guest Patching on
Windows.
:vartype patch_settings: ~azure.mgmt.compute.v2021_07_01.models.PatchSettings
:ivar win_rm: Specifies the Windows Remote Management listeners. This enables remote Windows
PowerShell.
:vartype win_rm: ~azure.mgmt.compute.v2021_07_01.models.WinRMConfiguration | 6259907b283ffb24f3cf52bb |
class TestDegreesView(TestCase): <NEW_LINE> <INDENT> def test_correct_template_used(self): <NEW_LINE> <INDENT> response = self.client.get('/withers/degree/') <NEW_LINE> self.assertTemplateUsed(response, 'citeIt/degrees.html') <NEW_LINE> <DEDENT> def test_degrees_list_loads(self): <NEW_LINE> <INDENT> factories.CitationFactory() <NEW_LINE> response = self.client.get('/withers/degree/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(len(response.context['degrees']), 1) | Test that the degrees view functions correctly. | 6259907bbf627c535bcb2eeb |
class Robot: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.xpos = 10 <NEW_LINE> self.ypos = 10 <NEW_LINE> self.fuel = 100 <NEW_LINE> self.active = True <NEW_LINE> <DEDENT> def move_left(self): <NEW_LINE> <INDENT> if self.check_fuel(5): <NEW_LINE> <INDENT> print("Insufficient fuel to perform action") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xpos -= 1 <NEW_LINE> self.fuel -= 5 <NEW_LINE> <DEDENT> <DEDENT> def move_right(self): <NEW_LINE> <INDENT> if self.check_fuel(5): <NEW_LINE> <INDENT> print("Insufficient fuel to perform action") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xpos += 1 <NEW_LINE> self.fuel -= 5 <NEW_LINE> <DEDENT> <DEDENT> def move_up(self): <NEW_LINE> <INDENT> if self.check_fuel(5): <NEW_LINE> <INDENT> print("Insufficient fuel to perform action") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ypos -= 1 <NEW_LINE> self.fuel -= 5 <NEW_LINE> <DEDENT> <DEDENT> def move_down(self): <NEW_LINE> <INDENT> if self.check_fuel(5): <NEW_LINE> <INDENT> print("Insufficient fuel to perform action") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ypos += 1 <NEW_LINE> self.fuel -= 5 <NEW_LINE> <DEDENT> <DEDENT> def fire(self): <NEW_LINE> <INDENT> if self.check_fuel(15): <NEW_LINE> <INDENT> print("Insufficient fuel to perform action") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fuel -= 15 <NEW_LINE> print("Pew! Pew!") <NEW_LINE> <DEDENT> <DEDENT> def status(self): <NEW_LINE> <INDENT> print(f'({self.xpos}, {self.ypos}) - Fuel: {self.fuel}') <NEW_LINE> <DEDENT> def power_switch(self): <NEW_LINE> <INDENT> self.active = not self.active <NEW_LINE> if not self.active: <NEW_LINE> <INDENT> print("Goodbye.") <NEW_LINE> <DEDENT> <DEDENT> def command(self, action): <NEW_LINE> <INDENT> switch = { "left": self.move_left, "right": self.move_right, "up": self.move_up, "down": self.move_down, "status": self.status, "fire": self.fire, "quit": self.power_switch } <NEW_LINE> if action in switch: <NEW_LINE> <INDENT> return switch[action]() <NEW_LINE> <DEDENT> <DEDENT> def check_fuel(self, cost): <NEW_LINE> <INDENT> return cost > self.fuel | The robot class can be used to create a robot that can move
up, down, left, and right. It can also fire lasers and
report it's status.
member variables: xpos, ypos, fuel, active
member functions: move_left, move_right, move_up,
move_down, fire, status, power_switch, command,
check_fuel | 6259907b442bda511e95da65 |
class Em(Range): <NEW_LINE> <INDENT> def y(o, x, reset=False): <NEW_LINE> <INDENT> return o.m(reset) * (x - 3) + 1 | Effort Multiplier | 6259907bbe7bc26dc9252b63 |
class Results(object): <NEW_LINE> <INDENT> def __init__(self, page=0, pages=0): <NEW_LINE> <INDENT> self.page = page <NEW_LINE> self.pages = pages <NEW_LINE> self.items = [] | A simple object prototype for collections of results | 6259907b99fddb7c1ca63ae5 |
class Gcloud_template(BASE, HeatBase): <NEW_LINE> <INDENT> __tablename__ = 'gcloud_template' <NEW_LINE> id = sqlalchemy.Column(sqlalchemy.String(36), primary_key=True, default=lambda: str(uuid.uuid4())) <NEW_LINE> name = sqlalchemy.Column('name', sqlalchemy.String(255), nullable=True, unique=True) <NEW_LINE> content = sqlalchemy.Column('content', Json) <NEW_LINE> nested_content = sqlalchemy.Column('nested_content', Json) <NEW_LINE> description = sqlalchemy.Column('description', sqlalchemy.String(255)) <NEW_LINE> isShare = sqlalchemy.Column('isShare', sqlalchemy.Boolean, default=True) <NEW_LINE> type = sqlalchemy.Column('type', sqlalchemy.String(50), nullable=True) <NEW_LINE> creater = sqlalchemy.Column('creater', sqlalchemy.String(50)) <NEW_LINE> creater_id = sqlalchemy.Column('creater_id', sqlalchemy.String(36)) <NEW_LINE> gcloud_resource= relationship(Gcloud_resource, uselist=False, cascade="delete,all", backref=backref('gcloud_template')) | Represents a gcloud_template created by gcloud_template_managger . | 6259907b56b00c62f0fb42f0 |
class Site(models.Model): <NEW_LINE> <INDENT> job = models.ForeignKey('Job', related_name='sites') <NEW_LINE> site_id = models.CharField(max_length=128) <NEW_LINE> url = models.URLField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('job', 'site_id') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return 'job: %d, site_id: %s, url: %s' % (self.job.job_id, self.site_id, self.url) | The Site model contains a site URL and its job-specific ID. | 6259907bf548e778e596cfae |
class Authenticate(Message): <NEW_LINE> <INDENT> MESSAGE_TYPE = 5 <NEW_LINE> def __init__(self, signature, extra = None): <NEW_LINE> <INDENT> assert(type(signature) == six.text_type) <NEW_LINE> assert(extra is None or type(extra) == dict) <NEW_LINE> Message.__init__(self) <NEW_LINE> self.signature = signature <NEW_LINE> self.extra = extra or {} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(wmsg): <NEW_LINE> <INDENT> assert(len(wmsg) > 0 and wmsg[0] == Authenticate.MESSAGE_TYPE) <NEW_LINE> if len(wmsg) != 3: <NEW_LINE> <INDENT> raise ProtocolError("invalid message length {0} for AUTHENTICATE".format(len(wmsg))) <NEW_LINE> <DEDENT> signature = wmsg[1] <NEW_LINE> if type(signature) != six.text_type: <NEW_LINE> <INDENT> raise ProtocolError("invalid type {0} for 'signature' in AUTHENTICATE".format(type(signature))) <NEW_LINE> <DEDENT> extra = check_or_raise_extra(wmsg[2], u"'extra' in AUTHENTICATE") <NEW_LINE> obj = Authenticate(signature, extra) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> return [Authenticate.MESSAGE_TYPE, self.signature, self.extra] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "WAMP AUTHENTICATE Message (signature = {0}, extra = {1})".format(self.signature, self.extra) | A WAMP ``AUTHENTICATE`` message.
Format: ``[AUTHENTICATE, Signature|string, Extra|dict]`` | 6259907bd486a94d0ba2d9d4 |
class callback(_external): <NEW_LINE> <INDENT> def __init__(self, mc, energy_function, composite=False): <NEW_LINE> <INDENT> hoomd.util.print_status_line(); <NEW_LINE> _external.__init__(self); <NEW_LINE> cls = None; <NEW_LINE> if not hoomd.context.exec_conf.isCUDAEnabled(): <NEW_LINE> <INDENT> if isinstance(mc, integrate.sphere): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackSphere; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.convex_polygon): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackConvexPolygon; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.simple_polygon): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackSimplePolygon; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.convex_polyhedron): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackConvexPolyhedron; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.convex_spheropolyhedron): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackSpheropolyhedron; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.ellipsoid): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackEllipsoid; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.convex_spheropolygon): <NEW_LINE> <INDENT> cls =_hpmc.ExternalCallbackSpheropolygon; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.faceted_sphere): <NEW_LINE> <INDENT> cls =_hpmc.ExternalCallbackFacetedSphere; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.polyhedron): <NEW_LINE> <INDENT> cls =_hpmc.ExternalCallbackPolyhedron; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.sphinx): <NEW_LINE> <INDENT> cls =_hpmc.ExternalCallbackSphinx; <NEW_LINE> <DEDENT> elif isinstance(mc, integrate.sphere_union): <NEW_LINE> <INDENT> cls = _hpmc.ExternalCallbackSphereUnion; <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hoomd.context.msg.error("hpmc.field.callback: Unsupported integrator.\n"); <NEW_LINE> raise RuntimeError("Error initializing python callback"); <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> hoomd.context.msg.error("GPU not supported") <NEW_LINE> raise RuntimeError("Error initializing hpmc.field.callback"); <NEW_LINE> <DEDENT> self.compute_name = "callback" <NEW_LINE> self.cpp_compute = cls(hoomd.context.current.system_definition, energy_function) <NEW_LINE> hoomd.context.current.system.addCompute(self.cpp_compute, self.compute_name) <NEW_LINE> if not composite: <NEW_LINE> <INDENT> mc.set_external(self); | Use a python-defined energy function in MC integration
Args:
mc (:py:mod:`hoomd.hpmc.integrate`): MC integrator.
callback (callable): A python function to evaluate the energy of a configuration
composite (bool): True if this evaluator is part of a composite external field
Example::
def energy(snapshot):
# evaluate the energy in a linear potential gradient along the x-axis
gradient = (5,0,0)
e = 0
for p in snap.particles.position:
e -= numpy.dot(gradient,p)
return e
mc = hpmc.integrate.sphere(seed=415236);
mc.shape_param.set('A',diameter=1.0)
hpmc.field.callback(mc=mc, energy_function=energy);
run(100) | 6259907b7c178a314d78e8f9 |
class LineageForCertnameTest(BaseCertManagerTest): <NEW_LINE> <INDENT> @mock.patch('certbot.util.make_or_verify_dir') <NEW_LINE> @mock.patch('certbot._internal.storage.renewal_file_for_certname') <NEW_LINE> @mock.patch('certbot._internal.storage.RenewableCert') <NEW_LINE> def test_found_match(self, mock_renewable_cert, mock_renewal_conf_file, mock_make_or_verify_dir): <NEW_LINE> <INDENT> mock_renewal_conf_file.return_value = "somefile.conf" <NEW_LINE> mock_match = mock.Mock(lineagename="example.com") <NEW_LINE> mock_renewable_cert.return_value = mock_match <NEW_LINE> from certbot._internal import cert_manager <NEW_LINE> self.assertEqual(cert_manager.lineage_for_certname(self.config, "example.com"), mock_match) <NEW_LINE> self.assertTrue(mock_make_or_verify_dir.called) <NEW_LINE> <DEDENT> @mock.patch('certbot.util.make_or_verify_dir') <NEW_LINE> @mock.patch('certbot._internal.storage.renewal_file_for_certname') <NEW_LINE> def test_no_match(self, mock_renewal_conf_file, mock_make_or_verify_dir): <NEW_LINE> <INDENT> mock_renewal_conf_file.return_value = "other.com.conf" <NEW_LINE> from certbot._internal import cert_manager <NEW_LINE> self.assertIsNone(cert_manager.lineage_for_certname(self.config, "example.com")) <NEW_LINE> self.assertTrue(mock_make_or_verify_dir.called) <NEW_LINE> <DEDENT> @mock.patch('certbot.util.make_or_verify_dir') <NEW_LINE> @mock.patch('certbot._internal.storage.renewal_file_for_certname') <NEW_LINE> def test_no_renewal_file(self, mock_renewal_conf_file, mock_make_or_verify_dir): <NEW_LINE> <INDENT> mock_renewal_conf_file.side_effect = errors.CertStorageError() <NEW_LINE> from certbot._internal import cert_manager <NEW_LINE> self.assertIsNone(cert_manager.lineage_for_certname(self.config, "example.com")) <NEW_LINE> self.assertTrue(mock_make_or_verify_dir.called) | Tests for certbot._internal.cert_manager.lineage_for_certname | 6259907b2c8b7c6e89bd5205 |
class INZipCodeField(_BaseRegexField): <NEW_LINE> <INDENT> min_length = 6 <NEW_LINE> max_length = 7 <NEW_LINE> regex = r'^\d{3}\s?\d{3}$' | India ZIP Code Field (XXXXXX or XXX XXX). | 6259907ba05bb46b3848be37 |
class ChatRoom(models.Model): <NEW_LINE> <INDENT> sender = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chatroom_sender', verbose_name='Sender' ) <NEW_LINE> recipient = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chatroom_recipient' ) <NEW_LINE> created_at = models.DateTimeField('sent at', auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-created_at'] <NEW_LINE> unique_together = ('sender', 'recipient') | A private char room
Attributes:
created_at (datetime): datetime value when chatroom is created.
recipient (user): user whom the chatroom sends first message.
sender (user): user who created the chatroom | 6259907b01c39578d7f14443 |
class RandomSeedOffset(JobProperty): <NEW_LINE> <INDENT> statusOn = True <NEW_LINE> allowedTypes = ['int'] <NEW_LINE> StoredValue = 0 | Integer value that will be added to initialization value the
seed for each random number stream. Default value (=0) will be
always be used in straight athena jobs. | 6259907b71ff763f4b5e91c9 |
class PortControl(Yang): <NEW_LINE> <INDENT> def __init__(self, tag="control", parent=None, controller=None, orchestrator=None): <NEW_LINE> <INDENT> super(PortControl, self).__init__(tag, parent) <NEW_LINE> self._sorted_children = ["controller", "orchestrator"] <NEW_LINE> self.controller = StringLeaf("controller", parent=self, value=controller) <NEW_LINE> self.orchestrator = StringLeaf("orchestrator", parent=self, value=orchestrator) | Used to connect this port to a UNIFY orchestrator's Cf-Or reference point. Support controller - orchestrator or orchestrator - controller connection establishment. | 6259907bbf627c535bcb2eed |
class InternationalMelonOrder(AbstractMelonOrder): <NEW_LINE> <INDENT> tax = 0.17 <NEW_LINE> def __init__(self, species, qty, country_code): <NEW_LINE> <INDENT> super(InternationalMelonOrder, self).__init__(species, qty, "international") <NEW_LINE> self.country_code = country_code <NEW_LINE> <DEDENT> def get_country_code(self): <NEW_LINE> <INDENT> return self.country_code | An international (non-US) melon order. | 6259907b4a966d76dd5f0903 |
class integer_modulo(datashader.reductions.category_codes): <NEW_LINE> <INDENT> def __init__(self, column, modulo): <NEW_LINE> <INDENT> super().__init__(column) <NEW_LINE> self.modulo = modulo <NEW_LINE> <DEDENT> def apply(self, df): <NEW_LINE> <INDENT> return _column_modulo(df, self.column, self.modulo) | A variation on category_codes that replaces categories by the values from an integer column, modulo a certain number | 6259907bbe7bc26dc9252b64 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.