code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class PCA(object): <NEW_LINE> <INDENT> def __init__(self, x, n_components=None): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.dimension = x.shape[1] <NEW_LINE> if n_components and n_components >= self.dimension: <NEW_LINE> <INDENT> raise DimensionValueError("n_components error") <NEW_LINE> <DEDENT> self.n_components = n_components <NEW_LINE> <DEDENT> def cov(self): <NEW_LINE> <INDENT> x_T = np.transpose(self.x) <NEW_LINE> x_cov = np.cov(x_T) <NEW_LINE> return x_cov <NEW_LINE> <DEDENT> def get_feature(self): <NEW_LINE> <INDENT> x_cov = self.cov() <NEW_LINE> a, b = np.linalg.eig(x_cov) <NEW_LINE> m = a.shape[0] <NEW_LINE> c = np.hstack((a.reshape((m,1)), b)) <NEW_LINE> c_df = pd.DataFrame(c) <NEW_LINE> c_df_sort = c_df.sort(columns=0, ascending=False) <NEW_LINE> return c_df_sort <NEW_LINE> <DEDENT> def explained_varience_(self): <NEW_LINE> <INDENT> c_df_sort = self.get_feature() <NEW_LINE> return c_df_sort.values[:, 0] <NEW_LINE> <DEDENT> def paint_varience_(self): <NEW_LINE> <INDENT> explained_variance_ = self.explained_varience_() <NEW_LINE> plt.figure() <NEW_LINE> plt.plot(explained_variance_, 'k') <NEW_LINE> plt.xlabel('n_components', fontsize=16) <NEW_LINE> plt.ylabel('explained_variance_', fontsize=16) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def reduce_dimension(self): <NEW_LINE> <INDENT> c_df_sort = self.get_feature() <NEW_LINE> varience = self.explained_varience_() <NEW_LINE> if self.n_components: <NEW_LINE> <INDENT> p = c_df_sort.values[0:self.n_components, 1:] <NEW_LINE> y = np.dot(p, np.transpose(self.x)) <NEW_LINE> return np.transpose(y) <NEW_LINE> <DEDENT> varience_sum = sum(varience) <NEW_LINE> varience_radio = varience / varience_sum <NEW_LINE> varience_contribution = 0 <NEW_LINE> for R in xrange(self.dimension): <NEW_LINE> <INDENT> varience_contribution += varience_radio[R] <NEW_LINE> if varience_contribution >= 0.99: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> p = c_df_sort.values[0:R+1, 1:] <NEW_LINE> y = np.dot(p, np.transpose(self.x)) <NEW_LINE> return np.transpose(y)
定义PCA类
6259904f30c21e258be99c75
@register <NEW_LINE> @serializable <NEW_LINE> class CenterIOULoss(object): <NEW_LINE> <INDENT> def __init__(self, iou_loss_type='iou', with_ciou_term=False): <NEW_LINE> <INDENT> assert iou_loss_type in ['iou', 'linear_iou', 'giou'], "expected 'iou | giou | linear_iou', but got {}".format(iou_loss_type) <NEW_LINE> self.iou_loss_type = iou_loss_type <NEW_LINE> self.with_ciou_term = with_ciou_term <NEW_LINE> <DEDENT> def _transpose_reshape(self, pred, target, gt_mask): <NEW_LINE> <INDENT> pred = fluid.layers.reshape(pred, [-1, 2]) <NEW_LINE> target = fluid.layers.reshape(target, [-1, 2]) <NEW_LINE> gt_mask = fluid.layers.reshape(gt_mask, [-1, 2]) <NEW_LINE> return pred, target, gt_mask <NEW_LINE> <DEDENT> def __call__(self, pred, target, gt_mask, ind, bs): <NEW_LINE> <INDENT> eps = 1e-4 <NEW_LINE> pred = mask_feat(pred, ind, bs) <NEW_LINE> pred = fluid.layers.exp(pred) <NEW_LINE> mask = fluid.layers.cast(gt_mask, 'float32') <NEW_LINE> avg_factor = fluid.layers.reduce_sum(mask) <NEW_LINE> avg_factor.stop_gradient = True <NEW_LINE> mask = fluid.layers.unsqueeze(mask, [2]) <NEW_LINE> mask = fluid.layers.expand_as(mask, pred) <NEW_LINE> pred, target, mask = self._transpose_reshape(pred, target, mask) <NEW_LINE> mask.stop_gradient = True <NEW_LINE> target.stop_gradient = True <NEW_LINE> pred = pred * mask <NEW_LINE> target = target * mask <NEW_LINE> inter_wh = fluid.layers.elementwise_min(pred, target) <NEW_LINE> inter_area = inter_wh[:, 0] * inter_wh[:, 1] <NEW_LINE> pred_area = pred[:, 0] * pred[:, 1] <NEW_LINE> tar_area = target[:, 0] * target[:, 1] <NEW_LINE> ious = (inter_area + eps) / (pred_area + tar_area - inter_area + eps) <NEW_LINE> if self.iou_loss_type.lower() == 'linear_iou': <NEW_LINE> <INDENT> loss = 1.0 - ious <NEW_LINE> <DEDENT> elif self.iou_loss_type.lower() == 'giou': <NEW_LINE> <INDENT> enclose_wh = fluid.layers.elementwise_max(pred, target) <NEW_LINE> enclose_area = enclose_wh[:, 0] * enclose_wh[:, 1] <NEW_LINE> area_union = pred_area + tar_area - inter_area <NEW_LINE> gious = ious - (enclose_area - area_union + eps) / (enclose_area + eps) <NEW_LINE> loss = 1.0 - gious <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss = 0.0 - fluid.layers.log(ious + eps) <NEW_LINE> <DEDENT> loss = fluid.layers.reduce_sum(loss * mask[:, 0]) <NEW_LINE> return loss / (avg_factor + eps)
Using iou loss for bounding box regression Args: with_ciou_term (bool): whether to add complete iou term (considering the w/h ratio) iou_loss_type: wether to use giou to replace the normal iou
6259904f7cff6e4e811b6eac
class CardPickerElement(CardElement): <NEW_LINE> <INDENT> tag: Literal[CardTag.DATE_PICKER] = CardTag.DATE_PICKER <NEW_LINE> initial_date: Optional[str] = None <NEW_LINE> initial_time: Optional[str] = None <NEW_LINE> initial_datetime: Optional[str] = None <NEW_LINE> placeholder: Optional[str] = None <NEW_LINE> value: Optional[dict] = None <NEW_LINE> confirm: Optional[CardConfirmObject] = None
datePicker元素 https://open.feishu.cn/document/ukTMukTMukTM/uQzNwUjL0cDM14CN3ATN Args: tag 可以是"date_picker", "picker_time", "picker_datetime" initial_date "YYYY-MM-DD" initial_time "HH:mm" initial_datetime "YYYY-MM-DD HH:mm" placeholder 占位符, 无初始值时必填 { "tag": "date_picker", "placeholder": { "tag": "plain_text", "content": "Please select date" }, "value": { "key": "value" } }
6259904f8e71fb1e983bcf35
class Meta: <NEW_LINE> <INDENT> verbose_name = "Object Creator Types" <NEW_LINE> verbose_name_plural = "Object Creator Types"
Define Django meta options
6259904f96565a6dacd2d9c1
class ProjectExperice(Experience): <NEW_LINE> <INDENT> __tablename__ = 'preject_experience' <NEW_LINE> name = db.Column(db.String(32), nullable=False) <NEW_LINE> role = db.Column(db.String(32)) <NEW_LINE> technologys = db.Column(db.String(64)) <NEW_LINE> resume_id = db.Column(db.Integer, db.ForeignKey('resume.id')) <NEW_LINE> resume = db.relationship('Resume', uselist=False)
工作经历
6259904f3539df3088ecd713
class BreedSerializerWithSeparateWritablePK(serializers.ModelSerializer): <NEW_LINE> <INDENT> species = SpeciesSerializer(read_only=True) <NEW_LINE> species_id = serializers.PrimaryKeyRelatedField( queryset=models.Species.objects.all(), write_only=True, required=True, allow_null=False, ) <NEW_LINE> def validate(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data['species'] = data.pop('species_id') <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> fields = '__all__' <NEW_LINE> model = models.Breed
Breed with option 2: write a separate PK field
6259904ff7d966606f7492f0
class ThreeLayerConvNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.dtype = dtype <NEW_LINE> c, h, w = input_dim <NEW_LINE> self.params['W1'] = np.random.normal(0.0, weight_scale, (num_filters, c, filter_size, filter_size)) <NEW_LINE> self.params['b1'] = np.zeros(num_filters) <NEW_LINE> self.params['W2'] = np.random.normal(0.0, weight_scale, (int(num_filters * h * w / 4), hidden_dim)) <NEW_LINE> self.params['b2'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W3'] = np.random.normal(0.0, weight_scale, (hidden_dim, num_classes)) <NEW_LINE> self.params['b3'] = np.zeros(num_classes) <NEW_LINE> for k, v in self.params.items(): <NEW_LINE> <INDENT> self.params[k] = v.astype(dtype) <NEW_LINE> <DEDENT> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> W3, b3 = self.params['W3'], self.params['b3'] <NEW_LINE> filter_size = W1.shape[2] <NEW_LINE> conv_param = {'stride': 1, 'pad': (filter_size - 1) // 2} <NEW_LINE> pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} <NEW_LINE> scores, cache_conv = conv_relu_forward(X, W1, b1, conv_param) <NEW_LINE> scores, cache_max = max_pool_forward_fast(scores, pool_param) <NEW_LINE> scores, cache_1 = affine_relu_forward(scores, W2, b2) <NEW_LINE> scores, cache_2 = affine_forward(scores, W3, b3) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> grads = {} <NEW_LINE> reg_term = 0 <NEW_LINE> loss, dout = softmax_loss(scores, y) <NEW_LINE> dout, grads['W3'], grads['b3'] = affine_backward(dout, cache_2) <NEW_LINE> grads['W3'] += self.reg * self.params['W3'] <NEW_LINE> reg_term += np.sum(cache_2[1] ** 2) <NEW_LINE> dout, grads['W2'], grads['b2'] = affine_relu_backward(dout, cache_1) <NEW_LINE> grads['W2'] += self.reg * self.params['W2'] <NEW_LINE> reg_term += np.sum(cache_1[1] ** 2) <NEW_LINE> dout = max_pool_backward_fast(dout, cache_max) <NEW_LINE> dout, grads['W1'], grads['b1'] = conv_relu_backward(dout, cache_conv) <NEW_LINE> grads['W1'] += self.reg * self.params['W1'] <NEW_LINE> reg_term += np.sum(cache_conv[1] ** 2) <NEW_LINE> loss += .5 * self.reg * reg_term <NEW_LINE> return loss, grads
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels.
6259904f7d847024c075d844
class CASMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> error = ("The Django CAS middleware requires authentication " "middleware to be installed. Edit your MIDDLEWARE_CLASSES " "setting to insert 'django.contrib.auth.middleware." "AuthenticationMiddleware'.") <NEW_LINE> assert hasattr(request, 'user'), error <NEW_LINE> <DEDENT> def process_view(self, request, view_func, view_args, view_kwargs): <NEW_LINE> <INDENT> if view_func == login: <NEW_LINE> <INDENT> return cas_login(request, *view_args, **view_kwargs) <NEW_LINE> <DEDENT> if view_func == logout: <NEW_LINE> <INDENT> return cas_logout(request, *view_args, **view_kwargs) <NEW_LINE> <DEDENT> if not view_func.__module__.startswith('django.contrib.admin.'): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if request.user.is_staff: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise PermissionDenied("No staff privileges") <NEW_LINE> <DEDENT> <DEDENT> params = urlencode({auth.REDIRECT_FIELD_NAME: request.get_full_path()}) <NEW_LINE> return HttpResponseRedirect(settings.LOGIN_URL + '?' + params) <NEW_LINE> <DEDENT> def process_exception(self, request, exception): <NEW_LINE> <INDENT> if isinstance(exception, CasTicketException): <NEW_LINE> <INDENT> auth.logout(request) <NEW_LINE> return HttpResponseRedirect(request.path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Middleware that allows CAS authentication on admin pages
6259904f63d6d428bbee3c3c
class MLP(nn.Module): <NEW_LINE> <INDENT> def __init__(self, n_features, n_classes, n_channels=None): <NEW_LINE> <INDENT> super(MLP, self).__init__() <NEW_LINE> self.hidden = nn.Linear(n_features[0], 256) <NEW_LINE> self.fc = nn.Linear(256, n_classes) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = F.relu(self.hidden(x)) <NEW_LINE> x = self.fc(x) <NEW_LINE> return x
Basic MLP architecture.
6259904f55399d3f0562798b
class AbstractFactory(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def create_product_a(self) -> AbstractProductA: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_product_b(self) -> AbstractProductB: <NEW_LINE> <INDENT> pass
La interfaz AbstractFactory declara un conjunto de métodos que devuelven diferentes productos abstractos. Estos se denominan familia y son relacionados por un concepto de alto nivel. Los productos de una familia suelen ser capaces de colaborar entre ellos. Una familia de productos puede tener varias variantes, pero los productos de una variante no son compatibles con los productos de otra
6259904f76e4537e8c3f09f7
class TestCSApiResponseOrganisationGroup(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testCSApiResponseOrganisationGroup(self): <NEW_LINE> <INDENT> pass
CSApiResponseOrganisationGroup unit test stubs
6259904fd6c5a102081e358f
class SaxLocatorAdapter(object): <NEW_LINE> <INDENT> def __init__(self, locator=None): <NEW_LINE> <INDENT> self.locator= locator <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{:d}:{:d}".format(self.line, self.column) <NEW_LINE> <DEDENT> @property <NEW_LINE> def line(self): <NEW_LINE> <INDENT> return self.locator.getLineNumber() <NEW_LINE> <DEDENT> @property <NEW_LINE> def column(self): <NEW_LINE> <INDENT> return self.locator.getColumnNumber()
Adapter for an XML SAX2 Locator object Wraps a SAX2 locator to behave like a :class:`schema.Locator`. About SAX2 Locators: If a SAX parser provides location information to the SAX application, it does so by implementing this interface and then passing an instance to the application using the content handler's setDocumentLocator method. The application can use the object to obtain the location of any other SAX event in the XML source document. Note that the results returned by the object will be valid only during the scope of each callback method: the application will receive unpredictable results if it attempts to use the locator at any other time, or after parsing completes. SAX parsers are not required to supply a locator, but they are very strongly encouraged to do so. If the parser supplies a locator, it must do so before reporting any other document events. If no locator has been set by the time the application receives the startDocument event, the application should assume that a locator is not available. Arguments: locator (sax2.Locator): XML Sax locator to wrap Attributes: locator (sax2.Locator): Wrapped locator
6259904f07d97122c4218115
class dict_with_strkey(dict): <NEW_LINE> <INDENT> def __missing__(self, key): <NEW_LINE> <INDENT> if isinstance(key, str): <NEW_LINE> <INDENT> raise KeyError("%s does not exist in our dictionary" % key) <NEW_LINE> <DEDENT> return self[str(key)] <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.keys() or str(key) in self.keys()
this is a user-defined dict class using string keys if a key lookup fails, the key will be converted to its string type and then do the lookup
6259904f16aa5153ce40195f
class FlowsEndpoint(ListAPIMixin, BaseAPIView): <NEW_LINE> <INDENT> permission = 'flows.flow_api' <NEW_LINE> model = Flow <NEW_LINE> serializer_class = FlowReadSerializer <NEW_LINE> pagination_class = CreatedOnCursorPagination <NEW_LINE> def filter_queryset(self, queryset): <NEW_LINE> <INDENT> params = self.request.query_params <NEW_LINE> uuid = params.get('uuid') <NEW_LINE> if uuid: <NEW_LINE> <INDENT> queryset = queryset.filter(uuid=uuid) <NEW_LINE> <DEDENT> queryset = queryset.prefetch_related('labels') <NEW_LINE> return self.filter_before_after(queryset, 'modified_on') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_read_explorer(cls): <NEW_LINE> <INDENT> return { 'method': "GET", 'title': "List Flows", 'url': reverse('api.v2.flows'), 'slug': 'flow-list', 'params': [ {'name': "uuid", 'required': False, 'help': "A flow UUID filter by. ex: 5f05311e-8f81-4a67-a5b5-1501b6d6496a"}, {'name': 'before', 'required': False, 'help': "Only return flows modified before this date, ex: 2017-01-28T18:00:00.000"}, {'name': 'after', 'required': False, 'help': "Only return flows modified after this date, ex: 2017-01-28T18:00:00.000"} ] }
This endpoint allows you to list flows in your account. ## Listing Flows A **GET** returns the list of flows for your organization, in the order of last created. * **uuid** - the UUID of the flow (string), filterable as `uuid` * **name** - the name of the flow (string) * **archived** - whether this flow is archived (boolean) * **labels** - the labels for this flow (array of objects) * **expires** - the time (in minutes) when this flow's inactive contacts will expire (integer) * **created_on** - when this flow was created (datetime) * **modified_on** - when this flow was last modified (datetime), filterable as `before` and `after`. * **runs** - the counts of completed, interrupted and expired runs (object) Example: GET /api/v2/flows.json Response containing the flows for your organization: { "next": null, "previous": null, "results": [ { "uuid": "5f05311e-8f81-4a67-a5b5-1501b6d6496a", "name": "Survey", "archived": false, "labels": [{"name": "Important", "uuid": "5a4eb79e-1b1f-4ae3-8700-09384cca385f"}], "expires": 600, "created_on": "2016-01-06T15:33:00.813162Z", "modified_on": "2017-01-07T13:14:00.453567Z", "runs": { "active": 47, "completed": 123, "interrupted": 2, "expired": 34 } }, ... ] }
6259904fbaa26c4b54d5071c
class TestTasks(CCTestCase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> out = self.run_client('--list') <NEW_LINE> self.assertTrue(out.find('sample') > 0) <NEW_LINE> out = self.run_client('--show', 'cc.task.sample') <NEW_LINE> self.assertTrue(out.find('Params') > 0) <NEW_LINE> out = self.send_task('task_handler=cc.task.sample', 'cmd=test') <NEW_LINE> self.assertTrue(out.find('starting') > 0) <NEW_LINE> self.assertTrue(out.find('done') > 0) <NEW_LINE> out = self.send_task('task_handler=cc.task.sample', 'cmd=crash-run') <NEW_LINE> self.assertTrue(out.find('failed') > 0) <NEW_LINE> out = self.send_task('task_handler=cc.task.sample', 'cmd=crash-launch') <NEW_LINE> self.assertTrue(out.find('finished') > 0) <NEW_LINE> out = self.send_task('task_handler=cc.task.nonexist') <NEW_LINE> self.assertTrue(out.find('failed') > 0 or out.find('stopped') > 0) <NEW_LINE> <DEDENT> def send_task(self, *args): <NEW_LINE> <INDENT> return self.run_client('--send', 'task_host=testhost', *args) <NEW_LINE> <DEDENT> def run_client(self, *args): <NEW_LINE> <INDENT> cf = os.path.join(TMPDIR, 'taskclient.ini') <NEW_LINE> cmd = (sys.executable, '-m', 'cc.taskclient', cf) <NEW_LINE> return self.runcmd(cmd + args)
Test logging. task-host.ini:: [ccserver] logfile = TMP/%(job_name)s.log pidfile = TMP/%(job_name)s.pid cc-role = local cc-socket = PORT1 [routes] task = h:taskproxy job = h:jobmgr log = h:locallogger [h:locallogger] handler = cc.handler.locallogger [h:taskproxy] handler = cc.handler.proxy remote-cc = PORT2 [h:jobmgr] handler = cc.handler.jobmgr daemons = d:taskrunner [d:taskrunner] module = cc.daemon.taskrunner local-id = testhost #reg-period = 300 #maint-period = 60 [cc.task.sample] # sudo = xx task-router.ini:: [ccserver] logfile = TMP/%(job_name)s.log pidfile = TMP/%(job_name)s.pid cc-role = remote cc-socket = PORT2 [routes] task = h:taskrouter [h:taskrouter] handler = cc.handler.taskrouter #route-lifetime = 3600 #maint-period = 60 taskclient.ini:: [taskclient] cc = PORT2
6259904fd486a94d0ba2d436
class PowerDepthLevel(IntEnum): <NEW_LINE> <INDENT> TARGET = -1 <NEW_LINE> SENSOR = 0 <NEW_LINE> SOCKET = 1 <NEW_LINE> CORE = 2
Enumeration that specify which report level use to group by the reports
6259904f4e696a045264e859
class ESStatistics(object): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> self.best_epoch = 1 <NEW_LINE> self.best_ppl = float("inf") <NEW_LINE> self.best_nll = float("inf") <NEW_LINE> self.best_kl = 0 <NEW_LINE> self.bad_counter = 0 <NEW_LINE> self.ppl_history = [] <NEW_LINE> self.patience = args.patience <NEW_LINE> self.tol = args.tol <NEW_LINE> <DEDENT> def update_best(self, epoch, stats): <NEW_LINE> <INDENT> self.best_epoch = epoch <NEW_LINE> self.best_ppl = stats.ppl() <NEW_LINE> self.best_nll = stats.nll() <NEW_LINE> self.best_kl = stats.kl() <NEW_LINE> self.bad_counter = 0 <NEW_LINE> <DEDENT> def update_history(self, ppl): <NEW_LINE> <INDENT> self.ppl_history.append(ppl) <NEW_LINE> if len(self.ppl_history) > self.patience and ppl + self.tol >= min( self.ppl_history[: -self.patience] ): <NEW_LINE> <INDENT> self.bad_counter += 1 <NEW_LINE> utils.logger.info("Patience so far: %d", self.bad_counter)
Accumulator for early stopping statistics
6259904f3eb6a72ae038bacd
class DeleteHealthMonitor(neutronV20.DeleteCommand): <NEW_LINE> <INDENT> resource = 'health_monitor' <NEW_LINE> allow_names = False
Delete a given health monitor.
6259904f8da39b475be04657
@skip_if_bug_open('bugzilla', 1262037) <NEW_LINE> class SmartProxyMissingAttrTestCase(APITestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(SmartProxyMissingAttrTestCase, cls).setUpClass() <NEW_LINE> smart_proxies = entities.SmartProxy().search() <NEW_LINE> assert len(smart_proxies) > 0 <NEW_LINE> cls.smart_proxy_attrs = set(smart_proxies[0].update_json([]).keys()) <NEW_LINE> <DEDENT> @tier1 <NEW_LINE> def test_positive_update_loc(self): <NEW_LINE> <INDENT> names = one_to_many_names('location') <NEW_LINE> self.assertGreater( len(names & self.smart_proxy_attrs), 1, 'None of {0} are in {1}'.format(names, self.smart_proxy_attrs), ) <NEW_LINE> <DEDENT> @tier1 <NEW_LINE> def test_positive_update_org(self): <NEW_LINE> <INDENT> names = one_to_many_names('organization') <NEW_LINE> self.assertGreater( len(names & self.smart_proxy_attrs), 1, 'None of {0} are in {1}'.format(names, self.smart_proxy_attrs), )
Tests to see if the server returns the attributes it should. Satellite should return a full description of an entity each time an entity is created, read or updated. These tests verify that certain attributes really are returned. The ``one_to_*_names`` functions know what names Satellite may assign to fields.
6259904f009cb60464d029ab
class SendChatScreenshotTakenNotification(Object): <NEW_LINE> <INDENT> ID = "sendChatScreenshotTakenNotification" <NEW_LINE> def __init__(self, chat_id, extra=None, **kwargs): <NEW_LINE> <INDENT> self.extra = extra <NEW_LINE> self.chat_id = chat_id <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(q: dict, *args) -> "SendChatScreenshotTakenNotification": <NEW_LINE> <INDENT> chat_id = q.get('chat_id') <NEW_LINE> return SendChatScreenshotTakenNotification(chat_id)
Sends a notification about a screenshot taken in a chat. Supported only in private and secret chats Attributes: ID (:obj:`str`): ``SendChatScreenshotTakenNotification`` Args: chat_id (:obj:`int`): Chat identifier Returns: Ok Raises: :class:`telegram.Error`
6259904f7cff6e4e811b6eae
class QParallelAnimationGroup(QAnimationGroup): <NEW_LINE> <INDENT> def childEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def customEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def disconnectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def duration(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def event(self, QEvent): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isSignalConnected(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def receivers(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sender(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def senderSignalIndex(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def timerEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def updateCurrentTime(self, p_int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def updateDirection(self, QAbstractAnimation_Direction): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def updateState(self, QAbstractAnimation_State, QAbstractAnimation_State_1): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> pass
QParallelAnimationGroup(parent: QObject = None)
6259904f8e71fb1e983bcf38
class ObjectSolver(Solver): <NEW_LINE> <INDENT> solvable_resources = (Object,) <NEW_LINE> def coerce(self, value, resource): <NEW_LINE> <INDENT> return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
Solver aimed to retrieve many fields from values. This solver can only handle ``dataql.resources.Object`` resources. Example ------- >>> from dataql.solvers.registry import Registry >>> registry = Registry() >>> from datetime import date >>> registry.register(date) # Create an object from which we'll want an object (``date``) >>> from dataql.solvers.registry import EntryPoints >>> obj = EntryPoints(registry, ... date = date(2015, 6, 1), ... ) >>> solver = ObjectSolver(registry) >>> d = solver.solve( ... obj, ... Object('date', resources=[Field('day'), Field('month'), Field('year')]) ... ) >>> [(k, d[k]) for k in sorted(d)] [('day', 1), ('month', 6), ('year', 2015)]
6259904f379a373c97d9a49e
class DiffHolder(): <NEW_LINE> <INDENT> def __init__(self, pygit_diff): <NEW_LINE> <INDENT> self.patches = [PatchHolder(p) for p in pygit_diff] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.patches)
Hold diff-information.
6259904fec188e330fdf9d11
class EnvCnfViews(Resource): <NEW_LINE> <INDENT> def get(self, env,configKey): <NEW_LINE> <INDENT> app.logger.info(f"EnvCnfViews get(env={env} configKey={configKey})") <NEW_LINE> msg = MsgBuilder() <NEW_LINE> config = EnvCnf.query.filter_by(env=env, key=configKey, active=1).first() <NEW_LINE> envCnfSchema = EnvCnfSchema() <NEW_LINE> configSerialized = envCnfSchema.dump(config) <NEW_LINE> msg.setSucceed(respData=configSerialized) <NEW_LINE> return jsonify(msg.getMsg()) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> app.logger.info(f"EnvCnfViews post({envCnfParams.parse_args()})") <NEW_LINE> msg=MsgBuilder() <NEW_LINE> args = removeNoneKey(envCnfParams.parse_args()) <NEW_LINE> if EnvCnf.query.filter_by(env=args.get("env"), key=args.get("key")).first(): <NEW_LINE> <INDENT> msg.setFailed(ResCode.UNIQUE_ERROR, msg=f'env={args.get("env")} key={args.get("key")}已存在!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> envCnfSchema = EnvCnfSchema() <NEW_LINE> args["value"] =strToJson(args.get("value")) <NEW_LINE> EnvCnf.create(**jsonToStr(args)) <NEW_LINE> res = EnvCnf.query.filter_by(env=args.get("env"), key=args.get("key")).first() <NEW_LINE> msg.setSucceed(respData=envCnfSchema.dump(res)) <NEW_LINE> <DEDENT> return jsonify(msg.getMsg()) <NEW_LINE> <DEDENT> def put(self): <NEW_LINE> <INDENT> app.logger.info(f"envCnfViews put({envCnfParams.parse_args()})") <NEW_LINE> msg = MsgBuilder() <NEW_LINE> args = removeNoneKey(envCnfParams.parse_args()) <NEW_LINE> key = args.get("key") <NEW_LINE> env = args.get("env") <NEW_LINE> cnf = EnvCnf.query.filter_by(env=env,key=key).first() <NEW_LINE> if cnf: <NEW_LINE> <INDENT> args["value"] = strToJson(args.get("value")) <NEW_LINE> cnf.update(**jsonToStr(args)) <NEW_LINE> res = EnvCnf.query.filter_by(env=args.get("env"),key=args.get("key")).first() <NEW_LINE> envCnfSchema = EnvCnfSchema() <NEW_LINE> msg.setSucceed(respData=envCnfSchema.dump(res)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg.setFailed(ResCode.NOT_FOUND, msg=f'env={args.get("env")} key={args.get("key")}不存在!') <NEW_LINE> <DEDENT> return jsonify(msg.getMsg()) <NEW_LINE> <DEDENT> def delete(self, env, configKey): <NEW_LINE> <INDENT> app.logger.info(f"envCnfViews delete(env={env} configKey={configKey})") <NEW_LINE> msg = MsgBuilder() <NEW_LINE> cnf = EnvCnf.query.filter_by(env=env, key=configKey).first() <NEW_LINE> if cnf: <NEW_LINE> <INDENT> cnf.update(active=0) <NEW_LINE> res = EnvCnf.query.filter_by(env=env, key=configKey).first() <NEW_LINE> envCnfSchema = EnvCnfSchema() <NEW_LINE> msg.setSucceed(respData=envCnfSchema.dump(res)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg.setFailed(ResCode.NOT_FOUND, msg=f'key={configKey}不存在!') <NEW_LINE> <DEDENT> return jsonify(msg.getMsg())
环境配置类单一视图
6259904f462c4b4f79dbce72
class HTTPClient(Client): <NEW_LINE> <INDENT> def open(self, url, verb, data=None): <NEW_LINE> <INDENT> self.check_verb(verb) <NEW_LINE> url = self.url_normalize(url) <NEW_LINE> method = getattr(requests, verb.lower()) <NEW_LINE> response = method(url, data) <NEW_LINE> return HTTPResponse(response)
Client interface that performs real HTTP requests. It uses the requests library to
6259904f004d5f362081fa22
class ListOfFunctionTerms(Qual): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ListOfFunctionTerms, self).__init__('listOfFunctionTerms') <NEW_LINE> <DEDENT> def create_default_term(self): <NEW_LINE> <INDENT> default = DefaultTerm() <NEW_LINE> return default.create()
contains 1 default terms and any number of function terms
6259904f26068e7796d4ddb7
class DummySubsegment(Subsegment): <NEW_LINE> <INDENT> def __init__(self, segment, name='dummy'): <NEW_LINE> <INDENT> super(DummySubsegment, self).__init__(name, 'dummy', segment) <NEW_LINE> self.sampled = False <NEW_LINE> <DEDENT> def set_aws(self, aws_meta): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def put_http_meta(self, key, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def put_annotation(self, key, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def put_metadata(self, key, value, namespace='default'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_sql(self, sql): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def apply_status_code(self, status_code): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_exception(self, exception, stack, remote=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> pass
A dummy subsegment will be created when ``xray_recorder`` tries to create a subsegment under a not sampled segment. Adding data to a dummy subsegment becomes no-op. Dummy subsegment will not be sent to the X-Ray daemon.
6259904f07f4c71912bb08a8
class SafetyGenerator(object): <NEW_LINE> <INDENT> implements(ITerrainGenerator) <NEW_LINE> def populate(self, chunk, seed): <NEW_LINE> <INDENT> for x, z in XZ: <NEW_LINE> <INDENT> chunk.set_block((x, 0, z), blocks["bedrock"].slot) <NEW_LINE> chunk.set_block((x, 126, z), blocks["air"].slot) <NEW_LINE> chunk.set_block((x, 127, z), blocks["air"].slot) <NEW_LINE> <DEDENT> <DEDENT> name = "safety" <NEW_LINE> before = ("boring", "simplex", "complex", "cliffs", "float", "caves") <NEW_LINE> after = tuple()
Generates terrain features essential for the safety of clients.
6259904fa219f33f346c7c75
class PhoneNumberInstance(InstanceResource): <NEW_LINE> <INDENT> def __init__(self, version, payload, service_sid, sid=None): <NEW_LINE> <INDENT> super(PhoneNumberInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload.get('sid'), 'account_sid': payload.get('account_sid'), 'service_sid': payload.get('service_sid'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'phone_number': payload.get('phone_number'), 'friendly_name': payload.get('friendly_name'), 'iso_country': payload.get('iso_country'), 'capabilities': payload.get('capabilities'), 'url': payload.get('url'), 'is_reserved': payload.get('is_reserved'), 'in_use': deserialize.integer(payload.get('in_use')), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = PhoneNumberContext( self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def service_sid(self): <NEW_LINE> <INDENT> return self._properties['service_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def phone_number(self): <NEW_LINE> <INDENT> return self._properties['phone_number'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._properties['friendly_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def iso_country(self): <NEW_LINE> <INDENT> return self._properties['iso_country'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def capabilities(self): <NEW_LINE> <INDENT> return self._properties['capabilities'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_reserved(self): <NEW_LINE> <INDENT> return self._properties['is_reserved'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def in_use(self): <NEW_LINE> <INDENT> return self._properties['in_use'] <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def update(self, is_reserved=values.unset): <NEW_LINE> <INDENT> return self._proxy.update(is_reserved=is_reserved, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Proxy.V1.PhoneNumberInstance {}>'.format(context)
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
6259904f097d151d1a2c24e4
class LongThrower(ThrowerAnt): <NEW_LINE> <INDENT> name = 'Long' <NEW_LINE> food_cost = 2 <NEW_LINE> min_range = 5 <NEW_LINE> max_range = 100 <NEW_LINE> implemented = False
A ThrowerAnt that only throws leaves at Bees at least 5 places away.
6259904fb57a9660fecd2ef0
class PosTagger(object): <NEW_LINE> <INDENT> def __init__(self, tokens): <NEW_LINE> <INDENT> self.tokens = tokens <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> return nltk.pos_tag(self.tokens)
Given a list of tokens, return a list of tuples of the form: (token, part-of-speech-tag)
6259904f009cb60464d029ad
class AssetHistoryAdmin(SimpleHistoryAdmin): <NEW_LINE> <INDENT> list_display = ['name', 'status', 'owner', 'history']
将simple_history集成到Django Admin
6259904f1f037a2d8b9e52a6
class Interfaces(object): <NEW_LINE> <INDENT> def __init__(self, function): <NEW_LINE> <INDENT> self.api = izi.api.from_object(function) <NEW_LINE> self.spec = getattr(function, 'original', function) <NEW_LINE> self.arguments = introspect.arguments(function) <NEW_LINE> self.name = introspect.name(function) <NEW_LINE> self._function = function <NEW_LINE> self.is_coroutine = introspect.is_coroutine(self.spec) <NEW_LINE> if self.is_coroutine: <NEW_LINE> <INDENT> self.spec = getattr(self.spec, '__wrapped__', self.spec) <NEW_LINE> <DEDENT> self.takes_args = introspect.takes_args(self.spec) <NEW_LINE> self.takes_kwargs = introspect.takes_kwargs(self.spec) <NEW_LINE> self.parameters = list(introspect.arguments(self.spec, self.takes_kwargs + self.takes_args)) <NEW_LINE> if self.takes_kwargs: <NEW_LINE> <INDENT> self.kwarg = self.parameters.pop(-1) <NEW_LINE> <DEDENT> if self.takes_args: <NEW_LINE> <INDENT> self.arg = self.parameters.pop(-1) <NEW_LINE> <DEDENT> self.parameters = tuple(self.parameters) <NEW_LINE> self.defaults = dict(zip(reversed(self.parameters), reversed(self.spec.__defaults__ or ()))) <NEW_LINE> self.required = self.parameters[:-(len(self.spec.__defaults__ or ())) or None] <NEW_LINE> self.is_method = introspect.is_method(self.spec) or introspect.is_method(function) <NEW_LINE> if self.is_method: <NEW_LINE> <INDENT> self.required = self.required[1:] <NEW_LINE> self.parameters = self.parameters[1:] <NEW_LINE> <DEDENT> self.all_parameters = set(self.parameters) <NEW_LINE> if self.spec is not function: <NEW_LINE> <INDENT> self.all_parameters.update(self.arguments) <NEW_LINE> <DEDENT> self.transform = self.spec.__annotations__.get('return', None) <NEW_LINE> self.directives = {} <NEW_LINE> self.input_transformations = {} <NEW_LINE> for name, transformer in self.spec.__annotations__.items(): <NEW_LINE> <INDENT> if isinstance(transformer, str): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif hasattr(transformer, 'directive'): <NEW_LINE> <INDENT> self.directives[name] = transformer <NEW_LINE> continue <NEW_LINE> <DEDENT> if hasattr(transformer, 'from_string'): <NEW_LINE> <INDENT> transformer = transformer.from_string <NEW_LINE> <DEDENT> elif hasattr(transformer, 'load'): <NEW_LINE> <INDENT> transformer = MarshmallowInputSchema(transformer) <NEW_LINE> <DEDENT> elif hasattr(transformer, 'deserialize'): <NEW_LINE> <INDENT> transformer = transformer.deserialize <NEW_LINE> <DEDENT> self.input_transformations[name] = transformer <NEW_LINE> <DEDENT> <DEDENT> def __call__(__izi_internal_self, *args, **kwargs): <NEW_LINE> <INDENT> if not __izi_internal_self.is_coroutine: <NEW_LINE> <INDENT> return __izi_internal_self._function(*args, **kwargs) <NEW_LINE> <DEDENT> return asyncio_call(__izi_internal_self._function, *args, **kwargs)
Defines the per-function singleton applied to iziged functions defining common data needed by all interfaces
6259904f7d847024c075d848
class BlockchainInstance(AbstractBlockchainInstanceProvider): <NEW_LINE> <INDENT> _sharedInstance = SharedInstance <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get("peerplays_instance"): <NEW_LINE> <INDENT> kwargs["blockchain_instance"] = kwargs["peerplays_instance"] <NEW_LINE> <DEDENT> AbstractBlockchainInstanceProvider.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def get_instance_class(self): <NEW_LINE> <INDENT> import peerplays as ppy <NEW_LINE> return ppy.PeerPlays <NEW_LINE> <DEDENT> @property <NEW_LINE> def peerplays(self): <NEW_LINE> <INDENT> return self.blockchain
This is a class that allows compatibility with previous naming conventions
6259904f96565a6dacd2d9c3
class CompoundBacktracker(Sealed): <NEW_LINE> <INDENT> __plugin__ = 'glue.CompoundBacktracker' <NEW_LINE> name = "CompoundBacktracker" <NEW_LINE> logger = None <NEW_LINE> backtraceIncoming = True <NEW_LINE> backtraceOutgoing = True <NEW_LINE> def __init__(self, parentLogger = None, **kw): <NEW_LINE> <INDENT> self.logger = openwns.logger.Logger("GLUE", "CompoundBacktracker", True, parentLogger) <NEW_LINE> attrsetter(self, kw)
Compound Backtracker FU
6259904f55399d3f0562798f
class BaseFormWithSubjectCheck(BaseFormWithUser): <NEW_LINE> <INDENT> def __init__(self, user, *args, **kwargs): <NEW_LINE> <INDENT> super(BaseFormWithSubjectCheck, self).__init__(user, *args, **kwargs) <NEW_LINE> self.fields['subject'].queryset = Subject.objects.filter(school__id=get_school_from_user(user).id) .order_by('name') <NEW_LINE> <DEDENT> def clean_subject(self): <NEW_LINE> <INDENT> if get_school_from_user(self.user) != self.cleaned_data['subject'].school: <NEW_LINE> <INDENT> self.add_error(None, forms.ValidationError(_('The subject {} is not taught in the school ({}).'.format( self.cleaned_data['subject'], self.cleaned_data['subject'].school )))) <NEW_LINE> <DEDENT> return self.cleaned_data['subject']
Base form class, which allows to retrieve only the correct subject according to the school of the user logged. Moreover it inherits from BaseFormWithUser
6259904f462c4b4f79dbce74
class EdgeLabelSet(collections.abc.MutableSet, GraphComponent): <NEW_LINE> <INDENT> def __init__(self, eid: EdgeID, graph_store: GraphStore): <NEW_LINE> <INDENT> GraphComponent.__init__(self, graph_store) <NEW_LINE> self._eid = eid <NEW_LINE> <DEDENT> def __contains__(self, label: Label) -> bool: <NEW_LINE> <INDENT> return self._graph_store.has_edge_label(self._eid, label) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[Label]: <NEW_LINE> <INDENT> return self._graph_store.iter_edge_labels(self._eid) <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return self._graph_store.count_edge_labels(self._eid) <NEW_LINE> <DEDENT> def add(self, label: Label) -> None: <NEW_LINE> <INDENT> self._graph_store.add_edge_label(self._eid, label) <NEW_LINE> <DEDENT> def remove(self, label: Label) -> None: <NEW_LINE> <INDENT> if not self._graph_store.discard_edge_label(self._eid, label): <NEW_LINE> <INDENT> raise KeyError(label) <NEW_LINE> <DEDENT> <DEDENT> def discard(self, label: Label) -> None: <NEW_LINE> <INDENT> self._graph_store.discard_edge_label(self._eid, label)
The set of all labels associated with this edge.
6259904f507cdc57c63a6215
class _Site: <NEW_LINE> <INDENT> def __init__(self,obj): <NEW_LINE> <INDENT> self.Type = "Site" <NEW_LINE> obj.Proxy = self <NEW_LINE> self.Object = obj <NEW_LINE> <DEDENT> def execute(self,obj): <NEW_LINE> <INDENT> self.Object = obj <NEW_LINE> <DEDENT> def onChanged(self,obj,prop): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def addObject(self,child): <NEW_LINE> <INDENT> if hasattr(self,"Object"): <NEW_LINE> <INDENT> g = self.Object.Group <NEW_LINE> if not child in g: <NEW_LINE> <INDENT> g.append(child) <NEW_LINE> self.Object.Group = g <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def removeObject(self,child): <NEW_LINE> <INDENT> if hasattr(self,"Object"): <NEW_LINE> <INDENT> g = self.Object.Group <NEW_LINE> if child in g: <NEW_LINE> <INDENT> g.remove(child) <NEW_LINE> self.Object.Group = g
The Site object
6259904f26068e7796d4ddb9
class EvaluatorBenchmark(Evaluator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def get_info(self): <NEW_LINE> <INDENT> self.problem, range_in, dim_in, dim_out, n_constr = load_problem(settings["data"]["problem"]) <NEW_LINE> self.results = ["F","G"] if n_constr else ["F"] <NEW_LINE> return range_in, dim_in, dim_out, n_constr <NEW_LINE> <DEDENT> def evaluate(self,samples,verify): <NEW_LINE> <INDENT> response_all = self.problem.evaluate(samples,return_values_of=self.results,return_as_dictionary=True) <NEW_LINE> response = np.concatenate([response_all[column] for column in response_all if column in self.results], axis=1) <NEW_LINE> return response
Evaluate a benchmark problem on the given sample. Attributes: problem (): Benchmark problem. results (list): List of values requested from the problem.
6259904fe76e3b2f99fd9e76
class BaseActionRequestHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> person = None <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> super(BaseActionRequestHandler, self).__init__(*args) <NEW_LINE> user = users.get_current_user() <NEW_LINE> if not user: <NEW_LINE> <INDENT> raise Exception("Missing user!") <NEW_LINE> <DEDENT> self.person = person_utils.get_person_by_email(user.email()) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> self.post()
ALL action handlers should inherit from this one.
6259904f6fece00bbaccce30
class ProfitBricksAvailabilityZone(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return (('<ProfitBricksAvailabilityZone: name=%s>') % (self.name))
Extension class which stores information about a ProfitBricks availability zone. :param name: The availability zone name. :type name: ``str`` Note: This class is ProfitBricks specific.
6259904f7b25080760ed8718
class LookupTransform(Transform): <NEW_LINE> <INDENT> _schema = {'$ref': '#/definitions/LookupTransform'} <NEW_LINE> def __init__(self, lookup=Undefined, default=Undefined, **kwds): <NEW_LINE> <INDENT> super(LookupTransform, self).__init__(lookup=lookup, default=default, **kwds)
LookupTransform schema wrapper Mapping(required=[lookup, from]) Attributes ---------- lookup : string Key in primary data source. default : string The default value to use if lookup fails. **Default value:** ``null`` as : anyOf(:class:`FieldName`, List(:class:`FieldName`)) The output fields on which to store the looked up data values. For data lookups, this property may be left blank if ``from.fields`` has been specified (those field names will be used); if ``from.fields`` has not been specified, ``as`` must be a string. For selection lookups, this property is optional: if unspecified, looked up values will be stored under a property named for the selection; and if specified, it must correspond to ``from.fields``. from : anyOf(:class:`LookupData`, :class:`LookupSelection`) Data source or selection for secondary data reference.
6259904f097d151d1a2c24e6
class DashVariables: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.attr = {} <NEW_LINE> <DEDENT> def update_attr(self, value, attr): <NEW_LINE> <INDENT> self.attr[attr] = value
Class to store information useful to callbacks
6259904f07d97122c421811a
class TestVehicleStatsDecorationsFuelPercents(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return VehicleStatsDecorationsFuelPercents( value = 54 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return VehicleStatsDecorationsFuelPercents( value = 54, ) <NEW_LINE> <DEDENT> <DEDENT> def testVehicleStatsDecorationsFuelPercents(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
VehicleStatsDecorationsFuelPercents unit test stubs
6259904f8e7ae83300eea508
@implementer(IService) <NEW_LINE> class HookableService(Service): <NEW_LINE> <INDENT> def register_hook(self, name, listener): <NEW_LINE> <INDENT> if not hasattr(self, 'event_listeners'): <NEW_LINE> <INDENT> self.event_listeners = defaultdict(list) <NEW_LINE> <DEDENT> log.debug('registering hook %s->%s' % (name, listener)) <NEW_LINE> self.event_listeners[name].append(listener) <NEW_LINE> <DEDENT> def trigger_hook(self, name, **data): <NEW_LINE> <INDENT> def react_to_hook(listener, name, **kw): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(listener, 'hook_' + name)(**kw) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> log.failure('Error while triggering hook') <NEW_LINE> raise RuntimeError( "Tried to notify a hook, but the listener " "service class %s does not seem to have " "defined the proper method: %s" % (listener.__class__, 'hook_' + name)) <NEW_LINE> <DEDENT> <DEDENT> if not hasattr(self, 'event_listeners'): <NEW_LINE> <INDENT> self.event_listeners = defaultdict(list) <NEW_LINE> <DEDENT> listeners = self._get_listener_services(name) <NEW_LINE> if listeners: <NEW_LINE> <INDENT> for listener in listeners: <NEW_LINE> <INDENT> react_to_hook(listener, name, **data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_sibling_service(self, name): <NEW_LINE> <INDENT> if self.parent: <NEW_LINE> <INDENT> return self.parent.getServiceNamed(name) <NEW_LINE> <DEDENT> <DEDENT> def _get_listener_services(self, hook): <NEW_LINE> <INDENT> if hook in self.event_listeners: <NEW_LINE> <INDENT> service_names = self.event_listeners[hook] <NEW_LINE> services = [ self._get_sibling_service(name) for name in service_names] <NEW_LINE> return services
This service allows for other services in a Twisted Service tree to be notified whenever a certain kind of hook is triggered. During the service composition, one is expected to register a hook name with the name of the service that wants to react to the triggering of the hook. All the services, both hooked and listeners, should be registered against the same parent service. Upon the hook being triggered, the method "hook_<name>" will be called with the passed data in the listener service.
6259904fa79ad1619776b4f6
class CopyDirectory(WorkerBuildStep): <NEW_LINE> <INDENT> name = 'CopyDirectory' <NEW_LINE> description = ['Copying'] <NEW_LINE> descriptionDone = ['Copied'] <NEW_LINE> renderables = ['src', 'dest'] <NEW_LINE> haltOnFailure = True <NEW_LINE> flunkOnFailure = True <NEW_LINE> def __init__(self, src, dest, timeout=120, maxTime=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.src = src <NEW_LINE> self.dest = dest <NEW_LINE> self.timeout = timeout <NEW_LINE> self.maxTime = maxTime <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def run(self): <NEW_LINE> <INDENT> self.checkWorkerHasCommand('cpdir') <NEW_LINE> args = {'fromdir': self.src, 'todir': self.dest} <NEW_LINE> args['timeout'] = self.timeout <NEW_LINE> if self.maxTime: <NEW_LINE> <INDENT> args['maxTime'] = self.maxTime <NEW_LINE> <DEDENT> cmd = remotecommand.RemoteCommand('cpdir', args) <NEW_LINE> yield self.runCommand(cmd) <NEW_LINE> if cmd.didFail(): <NEW_LINE> <INDENT> self.descriptionDone = ["Copying", self.src, "to", self.dest, "failed."] <NEW_LINE> return FAILURE <NEW_LINE> <DEDENT> self.descriptionDone = ["Copied", self.src, "to", self.dest] <NEW_LINE> return SUCCESS
Copy a directory tree on the worker.
6259904f21a7993f00c673df
class Setting(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> description = models.CharField(max_length=500, blank=True) <NEW_LINE> value = models.CharField(max_length=100, blank=True) <NEW_LINE> readonly = models.BooleanField(default=False) <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True, blank=True) <NEW_LINE> date_modified = models.DateTimeField(auto_now=True, blank=True)
Settings
6259904f94891a1f408ba130
class ExtendedInfo(object): <NEW_LINE> <INDENT> TITLE = (By.CSS_SELECTOR, "#extended-info .main-title") <NEW_LINE> BUTTON_MAP_TO = ( By.CSS_SELECTOR, '[data-test-id="extended_info_button_map"]') <NEW_LINE> ALREADY_MAPPED = ( By.CSS_SELECTOR, '[data-test-id="extended_info_object_already_mapped"]')
Locators for Extended info tooltip in LHN after hovering over member object.
6259904f596a897236128fea
class KeyFrameAnnotation(models.Model): <NEW_LINE> <INDENT> frame_nr = models.PositiveIntegerField() <NEW_LINE> image_annotation = models.ForeignKey(ImageAnnotation, on_delete=models.CASCADE) <NEW_LINE> frame_metadata = models.CharField(default='', max_length=512, help_text='A text field for storing arbitrary metadata on the current frame') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.frame_nr)
Represents an annotation of a frame of an image_sequence
6259904fd53ae8145f9198d9
class HighlightDelegate(QtWidgets.QStyledItemDelegate): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QtWidgets.QStyledItemDelegate.__init__(self, parent) <NEW_LINE> self.highlight_text = '' <NEW_LINE> self.case_sensitive = False <NEW_LINE> self.doc = QtGui.QTextDocument() <NEW_LINE> try: <NEW_LINE> <INDENT> self.doc.setDocumentMargin(0) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def set_highlight_text(self, text, case_sensitive): <NEW_LINE> <INDENT> self.highlight_text = text <NEW_LINE> self.case_sensitive = case_sensitive <NEW_LINE> <DEDENT> def paint(self, painter, option, index): <NEW_LINE> <INDENT> if not self.highlight_text: <NEW_LINE> <INDENT> return QtWidgets.QStyledItemDelegate.paint(self, painter, option, index) <NEW_LINE> <DEDENT> text = index.data() <NEW_LINE> if self.case_sensitive: <NEW_LINE> <INDENT> html = text.replace(self.highlight_text, '<strong>%s</strong>' % self.highlight_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> match = re.match(r'(.*)(%s)(.*)' % re.escape(self.highlight_text), text, re.IGNORECASE) <NEW_LINE> if match: <NEW_LINE> <INDENT> start = match.group(1) or '' <NEW_LINE> middle = match.group(2) or '' <NEW_LINE> end = match.group(3) or '' <NEW_LINE> html = (start + ('<strong>%s</strong>' % middle) + end) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html = text <NEW_LINE> <DEDENT> <DEDENT> self.doc.setHtml(html) <NEW_LINE> params = QtWidgets.QStyleOptionViewItem(option) <NEW_LINE> self.initStyleOption(params, index) <NEW_LINE> params.text = '' <NEW_LINE> style = QtWidgets.QApplication.style() <NEW_LINE> style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, params, painter) <NEW_LINE> ctx = QtGui.QAbstractTextDocumentLayout.PaintContext() <NEW_LINE> if (params.state & QtWidgets.QStyle.State_Selected): <NEW_LINE> <INDENT> color = params.palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText) <NEW_LINE> ctx.palette.setColor(QtGui.QPalette.Text, color) <NEW_LINE> <DEDENT> item_text = QtWidgets.QStyle.SE_ItemViewItemText <NEW_LINE> rect = style.subElementRect(item_text, params) <NEW_LINE> painter.save() <NEW_LINE> start = rect.topLeft() + QtCore.QPoint(defs.margin, 0) <NEW_LINE> painter.translate(start) <NEW_LINE> self.doc.documentLayout().draw(painter, ctx) <NEW_LINE> painter.restore()
A delegate used for auto-completion to give formatted completion
6259904fd53ae8145f9198da
class NoStimulus(Stimulus): <NEW_LINE> <INDENT> def prepare(self, conditions=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def init_trial(self, cond=False): <NEW_LINE> <INDENT> self.isrunning = True
This class does not present any stimulus and water is delivered upon a lick
6259904f379a373c97d9a4a2
class JuMEG_Epocher_OutputMode(object): <NEW_LINE> <INDENT> __slots__ =["events","epochs","evoked","stage","annotations","use_condition_in_path","path"] <NEW_LINE> def __init__(self,**kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._init(**kwargs) <NEW_LINE> <DEDENT> def get_parameter(self,key=None): <NEW_LINE> <INDENT> if key: return self.__getattribute__(key) <NEW_LINE> return {slot: self.__getattribute__(slot) for slot in self.__slots__} <NEW_LINE> <DEDENT> def _init(self,**kwargs): <NEW_LINE> <INDENT> for k in self.__slots__: <NEW_LINE> <INDENT> self.__setattr__(k,None) <NEW_LINE> <DEDENT> self._update_from_kwargs(**kwargs) <NEW_LINE> <DEDENT> def update(self,**kwargs): <NEW_LINE> <INDENT> self._update_from_kwargs(**kwargs) <NEW_LINE> <DEDENT> def _update_from_kwargs(self,**kwargs): <NEW_LINE> <INDENT> if not kwargs: return <NEW_LINE> for k in kwargs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__setattr__(k,kwargs.get(k)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def make_output_path(self,condition=None,**kwargs): <NEW_LINE> <INDENT> self._update_from_kwargs(**kwargs) <NEW_LINE> self.path = self.stage <NEW_LINE> if self.path: <NEW_LINE> <INDENT> self.path = jumeg_base.expandvars(self.path) <NEW_LINE> if self.use_condition_in_path: <NEW_LINE> <INDENT> if condition: <NEW_LINE> <INDENT> self.path = os.path.join(self.path,condition) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> os.makedirs(self.path,exist_ok=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> msg=[" --> can not create epocher epochs output path: {}".format(self.path)," -> ouput mode parameter: "] <NEW_LINE> for k in self.__slots__: <NEW_LINE> <INDENT> msg.append(" -> {} : {}".format(k,self.__getattribute__(k))) <NEW_LINE> <DEDENT> logger.exception("\n".join(msg)) <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> return self.path
6259904f24f1403a92686309
class GamessUK70SPunTest(GenericSPunTest): <NEW_LINE> <INDENT> def testdimmocoeffs(self): <NEW_LINE> <INDENT> self.assertEqual(type(self.data.mocoeffs), type([])) <NEW_LINE> self.assertEqual(len(self.data.mocoeffs), 2) <NEW_LINE> shape_alpha = (self.data.homos[0]+6, self.data.nbasis) <NEW_LINE> shape_beta = (self.data.homos[1]+6, self.data.nbasis) <NEW_LINE> self.assertEqual(self.data.mocoeffs[0].shape, shape_alpha) <NEW_LINE> self.assertEqual(self.data.mocoeffs[1].shape, shape_beta) <NEW_LINE> <DEDENT> def testnooccnos(self): <NEW_LINE> <INDENT> self.assertEqual(self.data.nooccnos.shape, (self.data.nmo, ))
Customized unrestricted single point unittest
6259904f3c8af77a43b68979
class Or_l (Operation2) : <NEW_LINE> <INDENT> def __init__ ( self , a , b ) : <NEW_LINE> <INDENT> super(Or_l,self).__init__ ( a , b , _For () , ' or ' )
OR (logical) -operation >>> op = Or_l ( fun1 , fun2 )
6259904f26068e7796d4ddbb
class Entry: <NEW_LINE> <INDENT> def __init__(self, name, module_name, ext, options): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.module_name = module_name <NEW_LINE> self.options = options <NEW_LINE> self.ext = ext <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'case {}, options: {}, ext: {}'.format(self.name, self.options, self.ext) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Entry({!r}, {!r}, {!r}, {!r})".format(self.name, self.module_name, self.options, self.ext)
A file used as a test.
6259904fe64d504609df9e0a
class NoMatchingReleasesError(VcsRepoMgrError): <NEW_LINE> <INDENT> pass
Exception raised when no matching releases are found. Raised by :func:`~vcs_repo_mgr.Repository.select_release()` when no matching releases are found in the repository.
6259904f07f4c71912bb08ac
class SpiderState: <NEW_LINE> <INDENT> def __init__(self, jobdir=None): <NEW_LINE> <INDENT> self.jobdir = jobdir <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler): <NEW_LINE> <INDENT> jobdir = job_dir(crawler.settings) <NEW_LINE> if not jobdir: <NEW_LINE> <INDENT> raise NotConfigured <NEW_LINE> <DEDENT> obj = cls(jobdir) <NEW_LINE> crawler.signals.connect(obj.spider_closed, signal=signals.spider_closed) <NEW_LINE> crawler.signals.connect(obj.spider_opened, signal=signals.spider_opened) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def spider_closed(self, spider): <NEW_LINE> <INDENT> if self.jobdir: <NEW_LINE> <INDENT> with open(self.statefn, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(spider.state, f, protocol=2) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def spider_opened(self, spider): <NEW_LINE> <INDENT> if self.jobdir and os.path.exists(self.statefn): <NEW_LINE> <INDENT> with open(self.statefn, 'rb') as f: <NEW_LINE> <INDENT> spider.state = pickle.load(f) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> spider.state = {} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def statefn(self): <NEW_LINE> <INDENT> return os.path.join(self.jobdir, 'spider.state')
Store and load spider state during a scraping job
6259904f29b78933be26aafe
class Shards(FlipTile): <NEW_LINE> <INDENT> def __init__(self, width): <NEW_LINE> <INDENT> FlipTile.__init__(self, 1) <NEW_LINE> self.__shards = [ OneShard(self.getFrame(), width, 0, 5), OneShard(self.getFrame(), width, 1, 6), OneShard(self.getFrame(), width, 2, 7), OneShard(self.getFrame(), width, 3, 8), OneShard(self.getFrame(), width, 4, 9), OneShard(self.getFrame(), width, 5, 10), OneShard(self.getFrame(), width, 6, 11), OneShard(self.getFrame(), width, 7, 12) ] <NEW_LINE> <DEDENT> def clock(self, hundredths): <NEW_LINE> <INDENT> s = self.__shards <NEW_LINE> for i in range(len(s)): s[i].kick()
Animated shards which bounce from left to right; width is parameterised.
6259904f0c0af96317c5779c
class Tag(object): <NEW_LINE> <INDENT> def __init__(self, tag_name, attribs=None, **kwattribs): <NEW_LINE> <INDENT> self.contents = [] <NEW_LINE> self.tag_name = tag_name <NEW_LINE> if attribs is None: <NEW_LINE> <INDENT> attribs = {} <NEW_LINE> <DEDENT> self.attribs = attribs <NEW_LINE> for kwattrib_name in ['class', 'type']: <NEW_LINE> <INDENT> kwattrib_name_ = kwattrib_name + "_" <NEW_LINE> if kwattrib_name_ in kwattribs: <NEW_LINE> <INDENT> kwattrib_value = kwattribs.pop(kwattrib_name_) <NEW_LINE> if kwattrib_value is not None: <NEW_LINE> <INDENT> self.attribs[kwattrib_name] = kwattrib_value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.attribs.update(kwattribs) <NEW_LINE> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> self.contents.append(item) <NEW_LINE> return self <NEW_LINE> <DEDENT> def extend(self, items): <NEW_LINE> <INDENT> self.contents.extend(items) <NEW_LINE> return self <NEW_LINE> <DEDENT> def append_escaped(self, text): <NEW_LINE> <INDENT> escaped = re.sub('[&]', '&amp;', text) <NEW_LINE> escaped = re.sub('[<]', '&lt;', escaped) <NEW_LINE> escaped = re.sub('[>]', '&gt;', escaped) <NEW_LINE> escaped = re.sub('[%]', '&#37;', escaped) <NEW_LINE> escaped = re.sub('\xA0', '&nbsp;', escaped) <NEW_LINE> self.contents.append(escaped) <NEW_LINE> return self <NEW_LINE> <DEDENT> def append_new_tag(self, *args, **kwargs): <NEW_LINE> <INDENT> new_tag = Tag(*args, **kwargs) <NEW_LINE> self.contents.append(new_tag) <NEW_LINE> return new_tag <NEW_LINE> <DEDENT> def get_attribs_str(self): <NEW_LINE> <INDENT> astr = "" <NEW_LINE> attribs_list = [] <NEW_LINE> for k,v in self.attribs.items(): <NEW_LINE> <INDENT> attribs_list.append('%s="%s"' % (k, v)) <NEW_LINE> <DEDENT> if attribs_list: <NEW_LINE> <INDENT> astr += " " + (" ".join(attribs_list)) <NEW_LINE> <DEDENT> return astr <NEW_LINE> <DEDENT> def get_opening_tag(self): <NEW_LINE> <INDENT> return "<%s%s>" % (self.tag_name, self.get_attribs_str()) <NEW_LINE> <DEDENT> def get_closing_tag(self): <NEW_LINE> <INDENT> return "</%s>" % self.tag_name <NEW_LINE> <DEDENT> def get_empty_tag(self): <NEW_LINE> <INDENT> return "<%s%s/>" % (self.tag_name, self.get_attribs_str()) <NEW_LINE> <DEDENT> def set(self, attrib, newval): <NEW_LINE> <INDENT> self.attribs[attrib] = newval <NEW_LINE> return self <NEW_LINE> <DEDENT> def get(self, attrib): <NEW_LINE> <INDENT> return self.attribs.get(attrib) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if not self.contents: <NEW_LINE> <INDENT> return self.get_empty_tag() <NEW_LINE> <DEDENT> elif len(self.contents) == 1 and not isinstance(self.contents[0], Tag): <NEW_LINE> <INDENT> return self.get_opening_tag() + str(self.contents[0]) + self.get_closing_tag() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s\n%s\n%s" % (self.get_opening_tag(), "\n".join((indented(str(x), 2) for x in self.contents)), self.get_closing_tag())
Holds a tag with a name, attributes and content. content is a list of either tags or strings.
6259904fcb5e8a47e493cbc2
class SignalLogHandler(logging.handlers.BufferingHandler): <NEW_LINE> <INDENT> def __init__(self, signal: QtCore.SignalInstance) -> None: <NEW_LINE> <INDENT> super().__init__(capacity=10) <NEW_LINE> self._signal = signal <NEW_LINE> <DEDENT> def emit(self, record: LogRecord) -> None: <NEW_LINE> <INDENT> result = logging.Formatter().format(record) <NEW_LINE> self._signal.emit(result, record.levelno)
Qt Signal based log handler. Emits the log as a signal. Warnings: This is problematic, the signal could be GC and cause a segfault
6259904fb57a9660fecd2ef4
class Square: <NEW_LINE> <INDENT> def __init__(self, size=0, position=(0, 0)): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.position = position <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return (self.__size) <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, value): <NEW_LINE> <INDENT> self.__check_size__(value) <NEW_LINE> self.__size = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return (self.__position) <NEW_LINE> <DEDENT> @position.setter <NEW_LINE> def position(self, value): <NEW_LINE> <INDENT> self.__check_pos__(value) <NEW_LINE> self.__position = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return (self.__size ** 2) <NEW_LINE> <DEDENT> def my_print(self): <NEW_LINE> <INDENT> if self.__size == 0: <NEW_LINE> <INDENT> print() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(self.__position[1]): <NEW_LINE> <INDENT> print() <NEW_LINE> <DEDENT> for j in range(self.__size): <NEW_LINE> <INDENT> for h in range(self.__position[0]): <NEW_LINE> <INDENT> print(" ", end="") <NEW_LINE> <DEDENT> for k in range(self.__size): <NEW_LINE> <INDENT> if k == (self.size - 1): <NEW_LINE> <INDENT> print("#") <NEW_LINE> break <NEW_LINE> <DEDENT> print("#", end="") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __check_pos__(self, position): <NEW_LINE> <INDENT> if (type(position) != tuple or len(position) != 2 or type(position[0]) != int or type(position[1]) != int or position[0] < 0 or position[1] < 0): <NEW_LINE> <INDENT> raise TypeError("position must be a tuple of 2 positive integers") <NEW_LINE> <DEDENT> <DEDENT> def __check_size__(self, size): <NEW_LINE> <INDENT> if type(size) != int: <NEW_LINE> <INDENT> raise TypeError("size must be an integer") <NEW_LINE> <DEDENT> if size < 0: <NEW_LINE> <INDENT> raise ValueError("size must be >= 0")
Square class for square objects. Square square square. Square is one of those words that looks stranger the more you type it.
6259904fd99f1b3c44d06b12
class Solution: <NEW_LINE> <INDENT> def myAtoi(self, str): <NEW_LINE> <INDENT> str = str.strip() <NEW_LINE> if not str: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> ans = [] <NEW_LINE> ch = str[0] <NEW_LINE> if ch == "-": <NEW_LINE> <INDENT> c = -1 <NEW_LINE> <DEDENT> elif ch == "+": <NEW_LINE> <INDENT> c = 1 <NEW_LINE> <DEDENT> elif ch.isdigit(): <NEW_LINE> <INDENT> ans.append(ch) <NEW_LINE> c = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> for ch in str[1:]: <NEW_LINE> <INDENT> if ch.isdigit(): <NEW_LINE> <INDENT> ans.append(ch) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> ans_str = "".join(ans) <NEW_LINE> if ans_str: <NEW_LINE> <INDENT> ans = c * int(ans_str) <NEW_LINE> if ans > 2147483647: <NEW_LINE> <INDENT> return 2147483647 <NEW_LINE> <DEDENT> elif ans < -2147483648: <NEW_LINE> <INDENT> return -2147483648 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ans <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return 0
Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Example 1: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Example 4: Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
6259904f30dc7b76659a0cad
class SecretGenerateSupportedPluginNotFound(exception.BarbicanHTTPException): <NEW_LINE> <INDENT> client_message = u._("Secret generate supported plugin not found.") <NEW_LINE> status_code = 400 <NEW_LINE> def __init__(self, key_spec): <NEW_LINE> <INDENT> message = u._("Could not find a secret store plugin for generating " "secret with algorithm '{alg}' and bit-length " "'{len}'.").format(alg=key_spec.alg, len=key_spec.bit_length) <NEW_LINE> super(SecretGenerateSupportedPluginNotFound, self).__init__( message)
Raised when no secret generate supported plugin is found.
6259904f3cc13d1c6d466bb1
class Solution: <NEW_LINE> <INDENT> def maxSubArrayLen(self, nums, k): <NEW_LINE> <INDENT> prefix_sum_arr = [0] <NEW_LINE> prefix_sum = 0 <NEW_LINE> prefixSum_plus_k_to_index = {} <NEW_LINE> prefixSum_plus_k_to_index[k] = 0 <NEW_LINE> max_length = 0 <NEW_LINE> for i in range(0, len(nums)): <NEW_LINE> <INDENT> prefix_sum += nums[i] <NEW_LINE> prefix_sum_arr.append(prefix_sum) <NEW_LINE> if prefix_sum in prefixSum_plus_k_to_index: <NEW_LINE> <INDENT> max_length = max(max_length, i + 1 - prefixSum_plus_k_to_index[prefix_sum]) <NEW_LINE> <DEDENT> if prefix_sum + k not in prefixSum_plus_k_to_index: <NEW_LINE> <INDENT> prefixSum_plus_k_to_index[prefix_sum + k] = i + 1 <NEW_LINE> <DEDENT> <DEDENT> return max_length
@param nums: an array @param k: a target value @return: the maximum length of a subarray that sums to k
6259904fdc8b845886d54a36
class LoginSerializer(serializers.Serializer): <NEW_LINE> <INDENT> email = serializers.EmailField(max_length=256, required=True) <NEW_LINE> password = serializers.CharField(required=True, min_length=5) <NEW_LINE> username = serializers.SerializerMethodField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> <DEDENT> def get_username(self,obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return User.objects.get(email=obj['email']).username <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IncorrectAuthCredentials(detail="Incorrect authentication credentials", code=401)
This is the serializer used for logging in user
6259904f7d847024c075d84c
class PoemTypescriptConvolute(ArchiveElement, Convolute): <NEW_LINE> <INDENT> def __init__(self, containsEarlierStagesOfPublication=None, convoluteHasContentRepresentation=None, containsLaterStagesOfManuscriptConvolute=None, hasArchiveSignature=None, convoluteHasOriginDescription=None, hasCarrierCollectionDescription=None, containsLaterStagesOfNotebook=None, convoluteHasSizeDescription=None, hasCreating=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self._namespace = ONTOLOGY_NS <NEW_LINE> self._project_id = PROJECT_ID <NEW_LINE> self._name = "PoemTypescriptConvolute" <NEW_LINE> self.containsEarlierStagesOfPublication = ContainsEarlierStagesOfPublication(containsEarlierStagesOfPublication) <NEW_LINE> self.convoluteHasContentRepresentation = ConvoluteHasContentRepresentation(convoluteHasContentRepresentation) <NEW_LINE> self.containsLaterStagesOfManuscriptConvolute = ContainsLaterStagesOfManuscriptConvolute(containsLaterStagesOfManuscriptConvolute) <NEW_LINE> self.hasArchiveSignature = HasArchiveSignature(hasArchiveSignature) <NEW_LINE> self.convoluteHasOriginDescription = ConvoluteHasOriginDescription(convoluteHasOriginDescription) <NEW_LINE> self.hasCarrierCollectionDescription = HasCarrierCollectionDescription(hasCarrierCollectionDescription) <NEW_LINE> self.containsLaterStagesOfNotebook = ContainsLaterStagesOfNotebook(containsLaterStagesOfNotebook) <NEW_LINE> self.convoluteHasSizeDescription = ConvoluteHasSizeDescription(convoluteHasSizeDescription) <NEW_LINE> self.hasCreating = HasCreating(hasCreating)
Poem typescript convolute with poems authored by Kuno Raeber. Labels: Gedicht-Typoskriptenonvolut (de) / poem typescript convolute (en)
6259904f3539df3088ecd71b
class NSNitroNserrGslbNoqualifier(NSNitroGslbErrors): <NEW_LINE> <INDENT> pass
Nitro error code 1828 At least one qualifier should be given for the location
6259904ff7d966606f7492f4
class PrivateIngredientsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> self.user = get_user_model().objects.create_user( '[email protected]', 'testpass' ) <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_ingredient_list(self): <NEW_LINE> <INDENT> Ingredient.objects.create(user=self.user, name='Kale') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Salt') <NEW_LINE> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> ingredients = Ingredient.objects.all().order_by('-name') <NEW_LINE> serializer = IngredientSerializer(ingredients, many=True) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, serializer.data) <NEW_LINE> <DEDENT> def test_ingredients_limited_to_user(self): <NEW_LINE> <INDENT> user2 = get_user_model().objects.create_user( '[email protected]', 'testpass' ) <NEW_LINE> Ingredient.objects.create(user=user2, name='Vinegar') <NEW_LINE> ingredient = Ingredient.objects.create(user=self.user, name="Tumeric") <NEW_LINE> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(res.data), 1) <NEW_LINE> self.assertEqual(res.data[0]['name'], ingredient.name) <NEW_LINE> <DEDENT> def test_create_ingredient_successful(self): <NEW_LINE> <INDENT> payload = {'name': 'Cabbage'} <NEW_LINE> self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> exists = Ingredient.objects.filter( user=self.user, name=payload['name'], ).exists() <NEW_LINE> self.assertTrue(exists) <NEW_LINE> <DEDENT> def test_create_ingredient_invalid(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> res = self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test the private ingredient api
6259904f0a50d4780f7067f9
class GenericModelChoiceField(FieldBase, forms.Field): <NEW_LINE> <INDENT> widget = ChoiceWidget <NEW_LINE> def prepare_value(self, value): <NEW_LINE> <INDENT> from django.contrib.contenttypes.models import ContentType <NEW_LINE> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif isinstance(value, models.Model): <NEW_LINE> <INDENT> return '%s-%s' % (ContentType.objects.get_for_model(value).pk, value.pk) <NEW_LINE> <DEDENT> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> from django.contrib.contenttypes.models import ContentType <NEW_LINE> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> content_type_id, object_id = value.split('-', 1) <NEW_LINE> try: <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_id(content_type_id) <NEW_LINE> <DEDENT> except ContentType.DoesNotExist: <NEW_LINE> <INDENT> raise forms.ValidationError('Wrong content type') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> model = content_type.model_class() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return model.objects.get(pk=object_id) <NEW_LINE> <DEDENT> except model.DoesNotExist: <NEW_LINE> <INDENT> raise forms.ValidationError('Wrong object id')
Simple form field that converts strings to models.
6259904fd7e4931a7ef3d4f1
class StatusCodeType_(SamlBase): <NEW_LINE> <INDENT> c_tag = 'StatusCodeType' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = SamlBase.c_children.copy() <NEW_LINE> c_attributes = SamlBase.c_attributes.copy() <NEW_LINE> c_child_order = SamlBase.c_child_order[:] <NEW_LINE> c_cardinality = SamlBase.c_cardinality.copy() <NEW_LINE> c_cardinality['status_code'] = {"min": 0, "max": 1} <NEW_LINE> c_attributes['Value'] = ('value', 'anyURI', True) <NEW_LINE> c_child_order.extend(['status_code']) <NEW_LINE> def __init__(self, status_code=None, value=None, text=None, extension_elements=None, extension_attributes=None): <NEW_LINE> <INDENT> SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) <NEW_LINE> self.status_code = status_code <NEW_LINE> self.value = value
The urn:oasis:names:tc:SAML:2.0:protocol:StatusCodeType element
6259904f45492302aabfd94c
class Car: <NEW_LINE> <INDENT> def __init__(self, engine): <NEW_LINE> <INDENT> self.engine = engine <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.engine
Example car.
6259904f76d4e153a661dcb5
class InvalidPositionError(ValueError): <NEW_LINE> <INDENT> pass
Exception for bad coordinates
6259904f7b25080760ed871a
class TaskForm(FlaskForm): <NEW_LINE> <INDENT> name = StringField('任务名', validators=[DataRequired(message='不能为空'), Length(3, 64, message='长度不正确')]) <NEW_LINE> url = StringField('监控URL', default=TaskMonitor.gen_uuid) <NEW_LINE> period = StringField('循环周期', validators=[InputRequired(), validate_crontab, Regexp('^ *(\S+ +){4}\S+ *$', message='只能包含5个字段')]) <NEW_LINE> grace_time = IntegerField('超时时间', validators=[NumberRange(min=1, message='必须大于等于1')]) <NEW_LINE> status = BooleanField('生效标识') <NEW_LINE> business = SelectField('Business', coerce=int) <NEW_LINE> submit = SubmitField('提交') <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TaskForm, self).__init__(*args, **kwargs) <NEW_LINE> query_all = Business.select(Business.id, Business.business_name) <NEW_LINE> query = perm_check(query_all) <NEW_LINE> self.business.choices = [(business.id, business.business_name) for business in query]
任务表单
6259904f07f4c71912bb08af
class AssertOutputCommand(Assertion): <NEW_LINE> <INDENT> NAME = "assert-output" <NEW_LINE> def __init__(self, spec): <NEW_LINE> <INDENT> assert isinstance(spec, str) <NEW_LINE> self.template = spec <NEW_LINE> <DEDENT> def run(self, state, case): <NEW_LINE> <INDENT> expected = substitute_env_vars(self.template) <NEW_LINE> try: <NEW_LINE> <INDENT> actual = os.environ["OUTPUT"] <NEW_LINE> case.assertEqual( expected.strip(), actual.strip() ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> case.fail("No command ran before assert-output")
Test condition command. Asserts that the output of the last command matches a given string:: --- # A very simple test! - !run > echo Hello world! - !assert-output > Hello world!
6259904f3eb6a72ae038bad5
class AuthenticationFormTests(TestCaseBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.active_user = user(save=True, username='activeuser', is_active=True) <NEW_LINE> self.inactive_user = user(save=True, username='inactiveuser', is_active=False) <NEW_LINE> <DEDENT> def test_only_active(self): <NEW_LINE> <INDENT> form = AuthenticationForm(data={'username': self.active_user.username, 'password': 'testpass'}) <NEW_LINE> assert form.is_valid() <NEW_LINE> form = AuthenticationForm(data={ 'username': self.inactive_user.username, 'password': 'testpass'}) <NEW_LINE> assert not form.is_valid() <NEW_LINE> <DEDENT> def test_allow_inactive(self): <NEW_LINE> <INDENT> form = AuthenticationForm(only_active=False, data={'username': self.active_user.username, 'password': 'testpass'}) <NEW_LINE> assert form.is_valid() <NEW_LINE> form = AuthenticationForm(only_active=False, data={ 'username': self.inactive_user.username, 'password': 'testpass'}) <NEW_LINE> assert form.is_valid()
AuthenticationForm tests.
6259904f23849d37ff852538
class File(object): <NEW_LINE> <INDENT> def __init__(self, short_path): <NEW_LINE> <INDENT> self.short_path = short_path
Mock Skylark File class for testing.
6259904f21a7993f00c673e3
class InputHookManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if ctypes is None: <NEW_LINE> <INDENT> warn( "IPython GUI event loop requires ctypes, %gui will not be available") <NEW_LINE> return <NEW_LINE> <DEDENT> self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int) <NEW_LINE> self.guihooks = {} <NEW_LINE> self.aliases = {} <NEW_LINE> self.apps = {} <NEW_LINE> self._reset() <NEW_LINE> <DEDENT> def _reset(self): <NEW_LINE> <INDENT> self._callback_pyfunctype = None <NEW_LINE> self._callback = None <NEW_LINE> self._installed = False <NEW_LINE> self._current_gui = None <NEW_LINE> <DEDENT> def get_pyos_inputhook(self): <NEW_LINE> <INDENT> return ctypes.c_void_p.in_dll(ctypes.pythonapi, "PyOS_InputHook") <NEW_LINE> <DEDENT> def get_pyos_inputhook_as_func(self): <NEW_LINE> <INDENT> return self.PYFUNC.in_dll(ctypes.pythonapi, "PyOS_InputHook") <NEW_LINE> <DEDENT> def set_inputhook(self, callback): <NEW_LINE> <INDENT> ignore_CTRL_C() <NEW_LINE> self._callback = callback <NEW_LINE> self._callback_pyfunctype = self.PYFUNC(callback) <NEW_LINE> pyos_inputhook_ptr = self.get_pyos_inputhook() <NEW_LINE> original = self.get_pyos_inputhook_as_func() <NEW_LINE> pyos_inputhook_ptr.value = ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value <NEW_LINE> self._installed = True <NEW_LINE> return original <NEW_LINE> <DEDENT> def clear_inputhook(self, app=None): <NEW_LINE> <INDENT> pyos_inputhook_ptr = self.get_pyos_inputhook() <NEW_LINE> original = self.get_pyos_inputhook_as_func() <NEW_LINE> pyos_inputhook_ptr.value = ctypes.c_void_p(None).value <NEW_LINE> allow_CTRL_C() <NEW_LINE> self._reset() <NEW_LINE> return original <NEW_LINE> <DEDENT> def clear_app_refs(self, gui=None): <NEW_LINE> <INDENT> if gui is None: <NEW_LINE> <INDENT> self.apps = {} <NEW_LINE> <DEDENT> elif gui in self.apps: <NEW_LINE> <INDENT> del self.apps[gui] <NEW_LINE> <DEDENT> <DEDENT> def register(self, toolkitname, *aliases): <NEW_LINE> <INDENT> def decorator(cls): <NEW_LINE> <INDENT> inst = cls(self) <NEW_LINE> self.guihooks[toolkitname] = inst <NEW_LINE> for a in aliases: <NEW_LINE> <INDENT> self.aliases[a] = toolkitname <NEW_LINE> <DEDENT> return cls <NEW_LINE> <DEDENT> return decorator <NEW_LINE> <DEDENT> def current_gui(self): <NEW_LINE> <INDENT> return self._current_gui <NEW_LINE> <DEDENT> def enable_gui(self, gui=None, app=None): <NEW_LINE> <INDENT> if gui in (None, GUI_NONE): <NEW_LINE> <INDENT> return self.disable_gui() <NEW_LINE> <DEDENT> if gui in self.aliases: <NEW_LINE> <INDENT> return self.enable_gui(self.aliases[gui], app) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> gui_hook = self.guihooks[gui] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> e = "Invalid GUI request {!r}, valid ones are: {}" <NEW_LINE> raise ValueError(e.format(gui, ', '.join(self.guihooks))) <NEW_LINE> <DEDENT> self._current_gui = gui <NEW_LINE> app = gui_hook.enable(app) <NEW_LINE> if app is not None: <NEW_LINE> <INDENT> app._in_event_loop = True <NEW_LINE> self.apps[gui] = app <NEW_LINE> <DEDENT> return app <NEW_LINE> <DEDENT> def disable_gui(self): <NEW_LINE> <INDENT> gui = self._current_gui <NEW_LINE> if gui in self.apps: <NEW_LINE> <INDENT> self.apps[gui]._in_event_loop = False <NEW_LINE> <DEDENT> return self.clear_inputhook()
Manage PyOS_InputHook for different GUI toolkits. This class installs various hooks under ``PyOSInputHook`` to handle GUI event loop integration.
6259904fcad5886f8bdc5abb
class MultiHeadAtten(nn.Module): <NEW_LINE> <INDENT> def __init__(self, atten_unit, encode_size, num_heads=8, dropout=0.1): <NEW_LINE> <INDENT> super(MultiHeadAtten, self).__init__() <NEW_LINE> model_dim = encode_size * 2 <NEW_LINE> self.attention = atten_unit <NEW_LINE> self.num_heads = num_heads <NEW_LINE> self.dim_per_head = d_k = d_v = model_dim // num_heads <NEW_LINE> self.linear_q = nn.Linear(model_dim, num_heads * d_k) <NEW_LINE> self.linear_k = nn.Linear(model_dim, num_heads * d_k) <NEW_LINE> self.linear_v = nn.Linear(model_dim, num_heads * d_v) <NEW_LINE> unit_encode_size = d_k // 2 <NEW_LINE> self.attention = atten_unit(unit_encode_size, dropout) <NEW_LINE> self.linear_final = nn.Linear(num_heads * d_v, model_dim) <NEW_LINE> self.dropout = nn.Dropout(dropout) <NEW_LINE> self.layer_norm = nn.LayerNorm(model_dim) <NEW_LINE> <DEDENT> def forward(self, query, key, value, atten_mask=None): <NEW_LINE> <INDENT> residual = query <NEW_LINE> dim_per_head = self.dim_per_head <NEW_LINE> num_heads = self.num_heads <NEW_LINE> batch_size = query.size(0) <NEW_LINE> query = self.linear_q(query) <NEW_LINE> key = self.linear_k(key) <NEW_LINE> value = self.linear_v(value) <NEW_LINE> query = query.view(batch_size * num_heads, -1, dim_per_head) <NEW_LINE> key = key.view(batch_size * num_heads, -1, dim_per_head) <NEW_LINE> value = value.view(batch_size * num_heads, -1, dim_per_head) <NEW_LINE> if atten_mask: <NEW_LINE> <INDENT> atten_mask = atten_mask.repeat(num_heads, 1, 1) <NEW_LINE> <DEDENT> context, atten = self.attention(query, key, value, atten_mask) <NEW_LINE> context = context.view(batch_size, -1, dim_per_head * num_heads) <NEW_LINE> output = self.linear_final(context) <NEW_LINE> output = self.dropout(output) <NEW_LINE> output = self.layer_norm(residual + output) <NEW_LINE> return output, atten
Multi head attetnion
6259904ff7d966606f7492f5
class line2(): <NEW_LINE> <INDENT> def __init__(self, a, b): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> self.b = b <NEW_LINE> <DEDENT> def __contains__(self, other): <NEW_LINE> <INDENT> if isinstance(other, point2): <NEW_LINE> <INDENT> return other.y == self.a * other.x + self.b <NEW_LINE> <DEDENT> elif isinstance(other, segment): <NEW_LINE> <INDENT> return (other.a.y == self.a * other.a.x + self.b) and (other.b.y == self.a * other.b.x + self.b) <NEW_LINE> <DEDENT> else: raise NotImplementedError
defined by a and b of the y = ax + b equation where a is the slope and b the y_intercept
6259904fdd821e528d6da356
class PingTestsMixin(object): <NEW_LINE> <INDENT> def test_periodic_noops(self): <NEW_LINE> <INDENT> expected_pings = 3 <NEW_LINE> reactor = Clock() <NEW_LINE> locator = _NoOpCounter() <NEW_LINE> peer = AMP(locator=locator) <NEW_LINE> protocol = self.build_protocol(reactor) <NEW_LINE> pump = connectedServerAndClient(lambda: protocol, lambda: peer)[2] <NEW_LINE> for i in range(expected_pings): <NEW_LINE> <INDENT> reactor.advance(PING_INTERVAL.total_seconds()) <NEW_LINE> pump.flush() <NEW_LINE> <DEDENT> self.assertEqual(locator.noops, expected_pings) <NEW_LINE> <DEDENT> def test_stop_pinging_on_connection_lost(self): <NEW_LINE> <INDENT> reactor = Clock() <NEW_LINE> protocol = self.build_protocol(reactor) <NEW_LINE> transport = StringTransport() <NEW_LINE> protocol.makeConnection(transport) <NEW_LINE> transport.clear() <NEW_LINE> protocol.connectionLost(Failure(ConnectionDone("test, simulated"))) <NEW_LINE> reactor.advance(PING_INTERVAL.total_seconds()) <NEW_LINE> self.assertEqual(b"", transport.value())
Mixin for ``TestCase`` defining tests for an ``AMP`` protocol that periodically sends no-op ping messages.
6259904f91af0d3eaad3b29f
class ExistingFile(str): <NEW_LINE> <INDENT> __metaclass__ = ValueMeta <NEW_LINE> @classmethod <NEW_LINE> def __instancecheck__(cls, instance): <NEW_LINE> <INDENT> if isinstance(instance, str): <NEW_LINE> <INDENT> if os.path.isfile(instance): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Non-instanced type-checking class (a VOG).
6259904f55399d3f05627995
class ClusterNodeSensors(object): <NEW_LINE> <INDENT> swagger_types = { 'sensors': 'list[ClusterNodeSensor]' } <NEW_LINE> attribute_map = { 'sensors': 'sensors' } <NEW_LINE> def __init__(self, sensors=None): <NEW_LINE> <INDENT> self._sensors = None <NEW_LINE> self.discriminator = None <NEW_LINE> if sensors is not None: <NEW_LINE> <INDENT> self.sensors = sensors <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def sensors(self): <NEW_LINE> <INDENT> return self._sensors <NEW_LINE> <DEDENT> @sensors.setter <NEW_LINE> def sensors(self, sensors): <NEW_LINE> <INDENT> self._sensors = sensors <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ClusterNodeSensors): <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.
6259904fd53ae8145f9198dd
class Signal(object): <NEW_LINE> <INDENT> assert_named_signals = False <NEW_LINE> def __init__(self, value, name=None, base=None, readonly=False): <NEW_LINE> <INDENT> self._value = np.asarray(value).view() <NEW_LINE> self._value.setflags(write=False) <NEW_LINE> if base is not None: <NEW_LINE> <INDENT> assert not base.is_view <NEW_LINE> if base.value.base is None: <NEW_LINE> <INDENT> assert value.base is base.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert value.base is base.value.base <NEW_LINE> <DEDENT> <DEDENT> self._base = base <NEW_LINE> if self.assert_named_signals: <NEW_LINE> <INDENT> assert name <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> self._readonly = bool(readonly) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Signal(%s, shape=%s)" % (self._name, self.shape) <NEW_LINE> <DEDENT> @property <NEW_LINE> def base(self): <NEW_LINE> <INDENT> return self if self._base is None else self._base <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self.value.dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def elemstrides(self): <NEW_LINE> <INDENT> return tuple(s / self.itemsize for s in self.value.strides) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_view(self): <NEW_LINE> <INDENT> return self._base is not None <NEW_LINE> <DEDENT> @property <NEW_LINE> def itemsize(self): <NEW_LINE> <INDENT> return self._value.itemsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name if self._name is not None else ("0x%x" % id(self)) <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def ndim(self): <NEW_LINE> <INDENT> return self.value.ndim <NEW_LINE> <DEDENT> @property <NEW_LINE> def offset(self): <NEW_LINE> <INDENT> return npext.array_offset(self.value) / self.itemsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def readonly(self): <NEW_LINE> <INDENT> return self._readonly <NEW_LINE> <DEDENT> @readonly.setter <NEW_LINE> def readonly(self, readonly): <NEW_LINE> <INDENT> self._readonly = bool(readonly) <NEW_LINE> <DEDENT> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> return self.value.shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.value.size <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, val): <NEW_LINE> <INDENT> raise RuntimeError("Cannot change signal value after initialization") <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> if not isinstance(item, tuple): <NEW_LINE> <INDENT> item = (item,) <NEW_LINE> <DEDENT> if not all(is_integer(i) or isinstance(i, slice) for i in item): <NEW_LINE> <INDENT> raise ValueError("Can only index or slice into signals") <NEW_LINE> <DEDENT> if all(map(is_integer, item)): <NEW_LINE> <INDENT> item = item[:-1] + (slice(item[-1], item[-1]+1),) <NEW_LINE> <DEDENT> return Signal(self._value[item], name="%s[%s]" % (self.name, item), base=self.base) <NEW_LINE> <DEDENT> def reshape(self, *shape): <NEW_LINE> <INDENT> return Signal(self._value.reshape(*shape), name="%s.reshape(%s)" % (self.name, shape), base=self.base) <NEW_LINE> <DEDENT> def may_share_memory(self, other): <NEW_LINE> <INDENT> return np.may_share_memory(self.value, other.value)
Represents data or views onto data within Nengo
6259904f287bf620b6273065
class BaseTrainer(abc.ABC): <NEW_LINE> <INDENT> def __init__(self, opt, model, optimizer, criterion, train_loader, val_loader): <NEW_LINE> <INDENT> self.opt = opt <NEW_LINE> self.use_cuda = opt.use_cuda <NEW_LINE> self.model = model <NEW_LINE> self.optim = optimizer <NEW_LINE> self.criterion = criterion <NEW_LINE> self.train_loader = train_loader <NEW_LINE> self.val_loader = val_loader <NEW_LINE> self.out = opt.out <NEW_LINE> if not os.path.exists(opt.out): <NEW_LINE> <INDENT> os.makedirs(opt.out) <NEW_LINE> <DEDENT> self.epoch = 0 <NEW_LINE> self.iteration = 0 <NEW_LINE> self.max_iter = opt.max_iter <NEW_LINE> self.valid_iter = opt.valid_iter <NEW_LINE> self.tb_pusher = tensorboard_helper.TensorboardPusher(opt) <NEW_LINE> self.push_opt_to_tb() <NEW_LINE> self.need_resume = opt.resume <NEW_LINE> if self.need_resume: <NEW_LINE> <INDENT> self.resume(self.opt) <NEW_LINE> <DEDENT> <DEDENT> def push_opt_to_tb(self): <NEW_LINE> <INDENT> opt_str = options_utils.opt_to_string(self.opt) <NEW_LINE> tb_datapack = tensorboard_helper.TensorboardDatapack() <NEW_LINE> tb_datapack.set_training(False) <NEW_LINE> tb_datapack.set_iteration(self.iteration) <NEW_LINE> tb_datapack.add_text({'options': opt_str}) <NEW_LINE> self.tb_pusher.push_to_tensorboard(tb_datapack) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def validate_batch(self, data_pack): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def train_batch(self, data_pack): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train_epoch(self): <NEW_LINE> <INDENT> self.model.train() <NEW_LINE> for batch_idx, data_pack in tqdm.tqdm(enumerate(self.train_loader), initial=self.iteration % len(self.train_loader), total=len(self.train_loader), desc='Train epoch={0}'.format(self.epoch), ncols=80, leave=True, ): <NEW_LINE> <INDENT> if self.iteration % self.valid_iter == 0: <NEW_LINE> <INDENT> self.validate() <NEW_LINE> <DEDENT> self.train_batch(data_pack) <NEW_LINE> if self.iteration >= self.max_iter: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.iteration += 1 <NEW_LINE> <DEDENT> <DEDENT> def train(self): <NEW_LINE> <INDENT> max_epoch = int(math.ceil(1. * self.max_iter / len(self.train_loader))) <NEW_LINE> for epoch in tqdm.trange(self.epoch, max_epoch, desc='Train', ncols=80): <NEW_LINE> <INDENT> self.epoch = epoch <NEW_LINE> self.train_epoch() <NEW_LINE> if self.iteration >= self.max_iter: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @abc.abstractmethod <NEW_LINE> def resume(self, opt): <NEW_LINE> <INDENT> pass
base trainer class. contains methods for training, validation, and writing output.
6259904f23e79379d538d977
class App_pyside(App_qt): <NEW_LINE> <INDENT> def importCoreAndGui(self): <NEW_LINE> <INDENT> import PySide <NEW_LINE> from PySide import QtGui, QtCore <NEW_LINE> return QtGui, QtCore
Hijack the PySide mainloop.
6259904f76e4537e8c3f0a01
class UserModelAdmin(ModelAdmin): <NEW_LINE> <INDENT> save_on_top = True <NEW_LINE> readonly_fields = ('created_by', 'updated_by') <NEW_LINE> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> instance = form.save(commit=False) <NEW_LINE> self._update_instance(instance, request.user) <NEW_LINE> instance.save() <NEW_LINE> return instance <NEW_LINE> <DEDENT> def save_formset(self, request, form, formset, change): <NEW_LINE> <INDENT> instances = formset.save(commit=False) <NEW_LINE> try: <NEW_LINE> <INDENT> for obj in formset.deleted_objects: <NEW_LINE> <INDENT> obj.delete() <NEW_LINE> <DEDENT> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for instance in instances: <NEW_LINE> <INDENT> self._update_instance(instance, request.user) <NEW_LINE> instance.save() <NEW_LINE> <DEDENT> formset.save_m2m() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _update_instance(instance, user): <NEW_LINE> <INDENT> if not instance.pk: <NEW_LINE> <INDENT> instance.created_by = user <NEW_LINE> <DEDENT> instance.updated_by = user
ModelAdmin subclass that will automatically update created_by and updated_by fields
6259904fd53ae8145f9198de
class AxisAlignedMargins(object): <NEW_LINE> <INDENT> def ToString(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self, geometry, x1, y1, z1, x2, y2, z2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Geometry = None <NEW_LINE> X1 = None <NEW_LINE> X2 = None <NEW_LINE> Y1 = None <NEW_LINE> Y2 = None <NEW_LINE> Z1 = None <NEW_LINE> Z2 = None
AxisAlignedMargins(geometry: StructureMarginGeometry, x1: float, y1: float, z1: float, x2: float, y2: float, z2: float)
6259904f3c8af77a43b6897b
class NVBTEXTURE_BOX_OPS(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "nvb.texture_info_box_ops" <NEW_LINE> bl_label = "Box Controls" <NEW_LINE> bl_description = "Show/hide this property list" <NEW_LINE> boxname = bpy.props.StringProperty(default='') <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> if self.boxname == '': <NEW_LINE> <INDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> attrname = 'box_visible_' + self.boxname <NEW_LINE> texture = context.object.active_material.active_texture <NEW_LINE> current_state = getattr(texture.nvb, attrname) <NEW_LINE> setattr(texture.nvb, attrname, not current_state) <NEW_LINE> return {'FINISHED'}
Hide/show Texture Info sub-groups
6259904f004d5f362081fa26
class emuiaDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dialog = emuiaDialog(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dialog = None <NEW_LINE> <DEDENT> def test_dialog_ok(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Ok) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Accepted) <NEW_LINE> <DEDENT> def test_dialog_cancel(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Cancel) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Rejected)
Test dialog works.
6259904fbe383301e0254c96
class Hover(): <NEW_LINE> <INDENT> def __init__(self, init_pose=None, init_velocities=None, init_angle_velocities=None, runtime=5., target_pos=None,position_noise=None): <NEW_LINE> <INDENT> print(":::::::::: Task to hover :::::::::: ") <NEW_LINE> self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime) <NEW_LINE> self.action_repeat = 3 <NEW_LINE> self.state_size = self.action_repeat * 6 <NEW_LINE> self.action_low = 0 <NEW_LINE> self.action_high = 900 <NEW_LINE> self.action_size = 4 <NEW_LINE> self.position_noise = position_noise <NEW_LINE> self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.]) <NEW_LINE> <DEDENT> def get_reward(self): <NEW_LINE> <INDENT> reward = 0.0 <NEW_LINE> posDiff = abs(self.sim.pose[2] - self.target_pos[2]) <NEW_LINE> if posDiff > 0.1: <NEW_LINE> <INDENT> reward += 10/posDiff <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> reward += 100 <NEW_LINE> <DEDENT> return reward <NEW_LINE> <DEDENT> def step(self, rotor_speeds): <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> pose_all = [] <NEW_LINE> for _ in range(self.action_repeat): <NEW_LINE> <INDENT> done = self.sim.next_timestep(rotor_speeds) <NEW_LINE> reward += self.get_reward() <NEW_LINE> pose_all.append(self.sim.pose) <NEW_LINE> <DEDENT> def is_equal(x, y, delta=0.0): <NEW_LINE> <INDENT> return abs(x-y) <= delta <NEW_LINE> <DEDENT> if is_equal(self.target_pos[2], self.sim.pose[2], delta=1): <NEW_LINE> <INDENT> reward += 50.0 <NEW_LINE> <DEDENT> if self.sim.time > self.sim.runtime and is_equal(self.target_pos[2], self.sim.pose[2], delta=1): <NEW_LINE> <INDENT> print("########## good finish still on the air") <NEW_LINE> reward += 1000.0 <NEW_LINE> done = True <NEW_LINE> <DEDENT> next_state = np.concatenate(pose_all) <NEW_LINE> return next_state, reward, done <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.sim.reset() <NEW_LINE> if self.position_noise is not None: <NEW_LINE> <INDENT> rand_pose = np.copy(self.sim.init_pose) <NEW_LINE> if self.position_noise is not None and self.position_noise > 0: <NEW_LINE> <INDENT> rand_pose[:3] += np.random.normal(0.0, self.position_noise, 3) <NEW_LINE> <DEDENT> self.sim.pose = np.copy(rand_pose) <NEW_LINE> self.target_pos = np.copy(rand_pose) <NEW_LINE> <DEDENT> state = np.concatenate([self.sim.pose] * self.action_repeat) <NEW_LINE> return state
Task (environment) that defines the goal and provides feedback to the agent.
6259904f26068e7796d4ddbf
class Block(collections.namedtuple('Block', ['scope', 'unit_fn', 'args'])): <NEW_LINE> <INDENT> pass
A named tuple describing a ResNet block.
6259904f1f037a2d8b9e52a9
class EmoticonCache(Cache.Cache): <NEW_LINE> <INDENT> def __init__(self, config_path, user): <NEW_LINE> <INDENT> Cache.Cache.__init__(self, os.path.join(config_path, user.strip()), 'emoticons', True) <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> emotes = {} <NEW_LINE> with file(self.info_path) as handle: <NEW_LINE> <INDENT> for line in handle.readlines(): <NEW_LINE> <INDENT> shortcut, hash_ = line.split(' ', 1) <NEW_LINE> shortcut = urllib.unquote(shortcut) <NEW_LINE> emotes[shortcut] = hash_.strip() <NEW_LINE> <DEDENT> <DEDENT> return emotes <NEW_LINE> <DEDENT> def list(self): <NEW_LINE> <INDENT> return self.parse().items() <NEW_LINE> <DEDENT> def insert(self, item): <NEW_LINE> <INDENT> shortcut, path = item <NEW_LINE> hash_ = Cache.get_file_path_hash(path) <NEW_LINE> if hash_ is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> new_path = os.path.join(self.path, hash_) <NEW_LINE> shutil.copy2(path, new_path) <NEW_LINE> return self.__add_entry(shortcut, hash_) <NEW_LINE> <DEDENT> def insert_raw(self, item): <NEW_LINE> <INDENT> shortcut, image = item <NEW_LINE> position = image.tell() <NEW_LINE> image.seek(0) <NEW_LINE> hash_ = Cache.get_file_hash(image) <NEW_LINE> if hash_ is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> path = os.path.join(self.path, hash_) <NEW_LINE> image.seek(0) <NEW_LINE> handle = file(path, 'w') <NEW_LINE> handle.write(image.read()) <NEW_LINE> image.seek(position) <NEW_LINE> return self.__add_entry(shortcut, hash_) <NEW_LINE> <DEDENT> def __add_entry(self, shortcut, hash_): <NEW_LINE> <INDENT> handle = file(self.info_path, 'a') <NEW_LINE> handle.write('%s %s\n' % (urllib.quote(shortcut), hash_)) <NEW_LINE> handle.close() <NEW_LINE> return shortcut, hash_ <NEW_LINE> <DEDENT> def __remove_entry(self, hash_to_remove): <NEW_LINE> <INDENT> entries = self.list() <NEW_LINE> handle = file(self.info_path, 'w') <NEW_LINE> for stamp, hash_ in entries: <NEW_LINE> <INDENT> if hash_ != hash_to_remove: <NEW_LINE> <INDENT> handle.write('%s %s\n' % (str(stamp), hash_)) <NEW_LINE> <DEDENT> <DEDENT> handle.close() <NEW_LINE> <DEDENT> def add_entry(self, shortcut, hash_): <NEW_LINE> <INDENT> return self.__add_entry(shortcut, hash_) <NEW_LINE> <DEDENT> def remove_entry(self, hash_to_remove): <NEW_LINE> <INDENT> self.__remove_entry(hash_to_remove) <NEW_LINE> <DEDENT> def remove(self, item): <NEW_LINE> <INDENT> if item not in self: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> os.remove(os.path.join(self.path, item)) <NEW_LINE> self.__remove_entry(item) <NEW_LINE> return True <NEW_LINE> <DEDENT> def __contains__(self, name): <NEW_LINE> <INDENT> return os.path.isfile(os.path.join(self.path, name))
a class to maintain a cache of an user emoticons
6259904f07f4c71912bb08b1
class Mapping(Element): <NEW_LINE> <INDENT> def __init__(self, name: str): <NEW_LINE> <INDENT> super(Mapping, self).__init__(name) <NEW_LINE> self._category = None <NEW_LINE> <DEDENT> def add_category(self, category: str) -> 'Mapping': <NEW_LINE> <INDENT> self._category = category <NEW_LINE> if category not in self.attrs: <NEW_LINE> <INDENT> self.attributes(category, OrderedDict()) <NEW_LINE> return self <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def add_item(self, key: str, value: Any) -> 'Mapping': <NEW_LINE> <INDENT> m = self.attrs[self._category] <NEW_LINE> m[key] = value <NEW_LINE> return self <NEW_LINE> <DEDENT> def find_in_map(self, top_level_key: str, second_level_key: str) -> IntrinsicFunction: <NEW_LINE> <INDENT> if isinstance(top_level_key, str): <NEW_LINE> <INDENT> if top_level_key not in self.attrs: <NEW_LINE> <INDENT> raise ValueError('missing top_level_key. top_level_key: %r' % top_level_key) <NEW_LINE> <DEDENT> if isinstance(second_level_key, str): <NEW_LINE> <INDENT> if second_level_key not in self.attrs[top_level_key]: <NEW_LINE> <INDENT> raise ValueError('missing second_level_key. second_level_key: %r' % second_level_key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return Intrinsics.find_in_map(self, top_level_key, second_level_key)
The `Mapping` class is a subclass of :class:`Element`, each instance of which matches a key to a corresponding set of named values.
6259904f6fece00bbaccce36
class BaseClassesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_base_object(self): <NEW_LINE> <INDENT> bo = base._BaseObject(id="id0") <NEW_LINE> self.assertEqual(bo.id, "id0") <NEW_LINE> self.assertEqual(bo.ns, config.KMLNS) <NEW_LINE> self.assertEqual(bo.targetId, None) <NEW_LINE> self.assertEqual(bo.__name__, None) <NEW_LINE> bo.targetId = "target" <NEW_LINE> self.assertEqual(bo.targetId, "target") <NEW_LINE> bo.ns = "" <NEW_LINE> bo.id = None <NEW_LINE> self.assertEqual(bo.id, None) <NEW_LINE> self.assertEqual(bo.ns, "") <NEW_LINE> self.assertRaises(NotImplementedError, bo.etree_element) <NEW_LINE> element = etree.Element(config.KMLNS + "Base") <NEW_LINE> self.assertRaises(TypeError, bo.from_element) <NEW_LINE> self.assertRaises(TypeError, bo.from_element, element) <NEW_LINE> bo.__name__ = "NotABaseObject" <NEW_LINE> self.assertRaises(TypeError, bo.from_element, element) <NEW_LINE> bo.__name__ = "Base" <NEW_LINE> bo.ns = config.KMLNS <NEW_LINE> bo.from_element(element) <NEW_LINE> self.assertEqual(bo.id, None) <NEW_LINE> self.assertEqual(bo.ns, config.KMLNS) <NEW_LINE> self.assertFalse(bo.etree_element(), None) <NEW_LINE> self.assertGreater(len(bo.to_string()), 1) <NEW_LINE> <DEDENT> def test_feature(self): <NEW_LINE> <INDENT> f = kml._Feature(name="A Feature") <NEW_LINE> self.assertRaises(NotImplementedError, f.etree_element) <NEW_LINE> self.assertEqual(f.name, "A Feature") <NEW_LINE> self.assertEqual(f.visibility, 1) <NEW_LINE> self.assertEqual(f.isopen, 0) <NEW_LINE> self.assertEqual(f._atom_author, None) <NEW_LINE> self.assertEqual(f._atom_link, None) <NEW_LINE> self.assertEqual(f.address, None) <NEW_LINE> self.assertEqual(f._snippet, None) <NEW_LINE> self.assertEqual(f.description, None) <NEW_LINE> self.assertEqual(f._styleUrl, None) <NEW_LINE> self.assertEqual(f._styles, []) <NEW_LINE> self.assertEqual(f._time_span, None) <NEW_LINE> self.assertEqual(f._time_stamp, None) <NEW_LINE> f.__name__ = "Feature" <NEW_LINE> f.styleUrl = "#default" <NEW_LINE> self.assertIn("Feature>", str(f.to_string())) <NEW_LINE> self.assertIn("#default", str(f.to_string())) <NEW_LINE> <DEDENT> def test_container(self): <NEW_LINE> <INDENT> f = kml._Container(name="A Container") <NEW_LINE> p = kml.Placemark() <NEW_LINE> f.append(p) <NEW_LINE> self.assertRaises(NotImplementedError, f.etree_element) <NEW_LINE> <DEDENT> def test_overlay(self): <NEW_LINE> <INDENT> o = kml._Overlay(name="An Overlay") <NEW_LINE> self.assertEqual(o._color, None) <NEW_LINE> self.assertEqual(o._drawOrder, None) <NEW_LINE> self.assertEqual(o._icon, None) <NEW_LINE> self.assertRaises(NotImplementedError, o.etree_element) <NEW_LINE> <DEDENT> def test_atom_link(self): <NEW_LINE> <INDENT> ns = "{http://www.opengis.net/kml/2.2}" <NEW_LINE> l = atom.Link(ns=ns) <NEW_LINE> self.assertEqual(l.ns, ns) <NEW_LINE> <DEDENT> def test_atom_person(self): <NEW_LINE> <INDENT> ns = "{http://www.opengis.net/kml/2.2}" <NEW_LINE> p = atom._Person(ns=ns) <NEW_LINE> self.assertEqual(p.ns, ns)
BaseClasses must raise a NotImplementedError on etree_element and a TypeError on from_element
6259904fb57a9660fecd2ef8
class LoadsideBankVersion(NumericValue): <NEW_LINE> <INDENT> bank = BANK_204 <NEW_LINE> locations = MemoryLocation(address=0x03, default=0x01, type_=MemoryType.ROM)
Version of the loadside energy and power memory bank
6259904f3cc13d1c6d466bb5
class Tersoff(PotentialAbstract): <NEW_LINE> <INDENT> potential_fname = "potential.pot" <NEW_LINE> def validate_data(self, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_external_content(self): <NEW_LINE> <INDENT> potential_file = ( "# Potential file generated by aiida plugin " "(please check citation in the original file)\n" ) <NEW_LINE> for key in sorted(self.data.keys()): <NEW_LINE> <INDENT> potential_file += "{} {}\n".format(key, self.data[key]) <NEW_LINE> <DEDENT> return {self.potential_fname: potential_file} <NEW_LINE> <DEDENT> def get_input_potential_lines(self): <NEW_LINE> <INDENT> lammps_input_text = "pair_style tersoff\n" <NEW_LINE> lammps_input_text += "pair_coeff * * {} {{kind_symbols}}\n".format( self.potential_fname ) <NEW_LINE> return lammps_input_text <NEW_LINE> <DEDENT> @property <NEW_LINE> def allowed_element_names(self): <NEW_LINE> <INDENT> allowed = [] <NEW_LINE> for key in self.data: <NEW_LINE> <INDENT> allowed.extend(key.split()) <NEW_LINE> <DEDENT> return list(set(allowed)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def atom_style(self): <NEW_LINE> <INDENT> return "atomic" <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_units(self): <NEW_LINE> <INDENT> return "metal"
Class for creation of Tersoff potential inputs.
6259904f8e71fb1e983bcf41
class OpenStackGlance(Plugin): <NEW_LINE> <INDENT> plugin_name = "openstack_glance" <NEW_LINE> profiles = ('openstack', 'openstack_controller') <NEW_LINE> option_list = [] <NEW_LINE> var_puppet_gen = "/var/lib/config-data/puppet-generated/glance_api" <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> if self.get_option("all_logs"): <NEW_LINE> <INDENT> self.add_copy_spec([ "/var/log/glance/", ]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_copy_spec([ "/var/log/glance/*.log", ]) <NEW_LINE> <DEDENT> self.add_copy_spec([ "/etc/glance/", self.var_puppet_gen + "/etc/glance/", self.var_puppet_gen + "/etc/my.cnf.d/tripleo.cnf" ]) <NEW_LINE> service_status = self.get_command_output( "systemctl status openstack-glance-api.service" ) <NEW_LINE> in_container = self.running_in_container() <NEW_LINE> if (service_status['status'] == 0) or in_container: <NEW_LINE> <INDENT> glance_config = "" <NEW_LINE> if in_container: <NEW_LINE> <INDENT> glance_config = "--config-dir " + self.var_puppet_gen + "/etc/glance/" <NEW_LINE> <DEDENT> self.add_cmd_output( "glance-manage " + glance_config + " db_version", suggest_filename="glance_db_version" ) <NEW_LINE> vars_all = [p in os.environ for p in [ 'OS_USERNAME', 'OS_PASSWORD']] <NEW_LINE> vars_any = [p in os.environ for p in [ 'OS_TENANT_NAME', 'OS_PROJECT_NAME']] <NEW_LINE> if not (all(vars_all) and any(vars_any)): <NEW_LINE> <INDENT> self.soslog.warning("Not all environment variables set. " "Source the environment file for the user " "intended to connect to the OpenStack " "environment.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_cmd_output("openstack image list --long") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def running_in_container(self): <NEW_LINE> <INDENT> for runtime in ["docker", "podman"]: <NEW_LINE> <INDENT> container_status = self.get_command_output(runtime + " ps") <NEW_LINE> if container_status['status'] == 0: <NEW_LINE> <INDENT> for line in container_status['output'].splitlines(): <NEW_LINE> <INDENT> if line.endswith("glance_api"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def apply_regex_sub(self, regexp, subst): <NEW_LINE> <INDENT> self.do_path_regex_sub("/etc/glance/*", regexp, subst) <NEW_LINE> self.do_path_regex_sub( self.var_puppet_gen + "/etc/glance/*", regexp, subst ) <NEW_LINE> <DEDENT> def postproc(self): <NEW_LINE> <INDENT> protect_keys = [ "admin_password", "password", "qpid_password", "rabbit_password", "s3_store_secret_key", "ssl_key_password", "vmware_server_password", "transport_url" ] <NEW_LINE> connection_keys = ["connection"] <NEW_LINE> self.apply_regex_sub( r"((?m)^\s*(%s)\s*=\s*)(.*)" % "|".join(protect_keys), r"\1*********" ) <NEW_LINE> self.apply_regex_sub( r"((?m)^\s*(%s)\s*=\s*(.*)://(\w*):)(.*)(@(.*))" % "|".join(connection_keys), r"\1*********\6" )
OpenStack Glance
6259904f8da39b475be04662
class harmonicosci: <NEW_LINE> <INDENT> def __init__(self, elO, ecO,nelem0): <NEW_LINE> <INDENT> self.el = elO <NEW_LINE> self.ec = ecO <NEW_LINE> self.ej = 0 <NEW_LINE> self.nelem = nelem0 <NEW_LINE> self.phi_AO = math.pow(8*ecO/elO,0.25) <NEW_LINE> <DEDENT> def mmatele(self,n,m): <NEW_LINE> <INDENT> if(n==m): <NEW_LINE> <INDENT> return math.sqrt(8*self.el*self.ec)*n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def matrixform_H(self): <NEW_LINE> <INDENT> mat = [[self.mmatele(n,m) for n in range(self.nelem)] for m in range(self.nelem)] <NEW_LINE> return numpy.array(mat) <NEW_LINE> <DEDENT> def matrixform_X(self): <NEW_LINE> <INDENT> xop = [[self.phi_AO*xopmm(n,m) for n in range(self.nelem)] for m in range(self.nelem)] <NEW_LINE> return numpy.array(xop) <NEW_LINE> <DEDENT> def matrixform_V(self): <NEW_LINE> <INDENT> vop = [[vopmm(n,m)/self.phi_AO for n in range(self.nelem)] for m in range(self.nelem)] <NEW_LINE> return numpy.array(vop)
harmonic osci this construc the relevan matrix for the armonic oscilator H, X and H. those are express in the diagoanl basis for the H. - in the class i have also to define some internal variable. - to make a harmonic osci you do harmonicosci(EL,EC,EJ,number of element the space is trocated) - .matriform the form of the H .xop and .vop the result
6259904f004d5f362081fa27
class GeneralizedTimeZone(datetime.tzinfo): <NEW_LINE> <INDENT> def __init__(self,offsetstr="Z"): <NEW_LINE> <INDENT> super(GeneralizedTimeZone, self).__init__() <NEW_LINE> self.name = offsetstr <NEW_LINE> self.houroffset = 0 <NEW_LINE> self.minoffset = 0 <NEW_LINE> if offsetstr == "Z": <NEW_LINE> <INDENT> self.houroffset = 0 <NEW_LINE> self.minoffset = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (len(offsetstr) >= 3) and re.match(r'[-+]\d\d', offsetstr): <NEW_LINE> <INDENT> self.houroffset = int(offsetstr[0:3]) <NEW_LINE> offsetstr = offsetstr[3:] <NEW_LINE> <DEDENT> if (len(offsetstr) >= 2) and re.match(r'\d\d', offsetstr): <NEW_LINE> <INDENT> self.minoffset = int(offsetstr[0:2]) <NEW_LINE> offsetstr = offsetstr[2:] <NEW_LINE> <DEDENT> if len(offsetstr) > 0: <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> <DEDENT> if self.houroffset < 0: <NEW_LINE> <INDENT> self.minoffset *= -1 <NEW_LINE> <DEDENT> <DEDENT> def utcoffset(self, dt): <NEW_LINE> <INDENT> return datetime.timedelta(hours=self.houroffset, minutes=self.minoffset) <NEW_LINE> <DEDENT> def dst(self, dt): <NEW_LINE> <INDENT> return datetime.timedelta(0) <NEW_LINE> <DEDENT> def tzname(self, dt): <NEW_LINE> <INDENT> return self.name
This class is a basic timezone wrapper for the offset specified in a Generalized Time. It is dst-ignorant.
6259904fac7a0e7691f73958
class TestSequence(unittest.TestCase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> rptable = RPTable() <NEW_LINE> self.assertEqual(not (oh_add_resource(rptable, rptentries[0], None, 0)), True)
runTest : Starting with an empty RPTable, adds 1 resource to it with a null table. Passes the test if the interface returns an error, else it fails. Return value: 0 on success, 1 on failure
6259904f82261d6c52730905