code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class SystemCertClient(object): <NEW_LINE> <INDENT> def __init__(self, connection, subsystem=None): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> self.cert_url = '/rest/config/cert' <NEW_LINE> if subsystem: <NEW_LINE> <INDENT> self.cert_url = '/' + subsystem + self.cert_url <NEW_LINE> <DEDENT> elif connection.subsystem is None: <NEW_LINE> <INDENT> self.cert_url = '/ca' + self.cert_url <NEW_LINE> <DEDENT> self.headers = {'Content-type': 'application/json', 'Accept': 'application/json'} <NEW_LINE> <DEDENT> @pki.handle_exceptions() <NEW_LINE> def get_transport_cert(self): <NEW_LINE> <INDENT> url = self.cert_url + '/transport' <NEW_LINE> response = self.connection.get(url, self.headers) <NEW_LINE> cert_data = CertData.from_json(response.json()) <NEW_LINE> pem = cert_data.encoded <NEW_LINE> b64 = pem[len(pki.CERT_HEADER):len(pem) - len(pki.CERT_FOOTER)] <NEW_LINE> cert_data.binary = decode_cert(b64) <NEW_LINE> return cert_data | Class encapsulating and mirroring the functionality in the
SystemCertResource Java interface class defining the REST API for
system certificate resources. | 62599067baa26c4b54d50a30 |
class ConnectWrapSyncCommit(ConnectWrapBase): <NEW_LINE> <INDENT> def __init__(self, connection): <NEW_LINE> <INDENT> ConnectWrapBase.__init__(self, connection) <NEW_LINE> self.__dict__["commit"] = self.dbConn.commit <NEW_LINE> self.__dict__["syncCommit"] = self.dbConn.commit <NEW_LINE> self.__dict__["rollback"] = self.dbConn.rollback | Connection wrapper for synchronous commit | 625990677b180e01f3e49c29 |
class TCNNConfig(object): <NEW_LINE> <INDENT> embedding_dim = 64 <NEW_LINE> seq_length = 60 <NEW_LINE> num_classes = 5 <NEW_LINE> num_filters = 256 <NEW_LINE> kernel_size = 5 <NEW_LINE> vocab_size = 5000 <NEW_LINE> hidden_dim = 128 <NEW_LINE> dropout_keep_prob = 0.5 <NEW_LINE> learning_rate = 1e-3 <NEW_LINE> batch_size = 64 <NEW_LINE> num_epochs = 20 <NEW_LINE> print_per_batch = 100 <NEW_LINE> save_per_batch = 10 | CNN配置参数 | 625990672c8b7c6e89bd4f70 |
class BernoulliBandit: <NEW_LINE> <INDENT> def __init__(self, k, p=None): <NEW_LINE> <INDENT> assert p is None or len(p) == k <NEW_LINE> self.k = k <NEW_LINE> np.random.seed(int(time.time())) <NEW_LINE> if p is None: <NEW_LINE> <INDENT> self.p = [np.random.random() for _ in range(self.k)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.p = p <NEW_LINE> <DEDENT> self.max_p = max(self.p) <NEW_LINE> <DEDENT> def get_reward(self, i): <NEW_LINE> <INDENT> return int(np.random.random() < self.p[i]) | create k armed bernoulli bandit with given or randomly assigned probability p | 6259906791f36d47f2231a54 |
class CardWidth(proto.Enum): <NEW_LINE> <INDENT> CARD_WIDTH_UNSPECIFIED = 0 <NEW_LINE> SMALL = 1 <NEW_LINE> MEDIUM = 2 | The width of the cards in the carousel. | 625990674f88993c371f10e4 |
class Core500Exception(CoreException): <NEW_LINE> <INDENT> def __init__(self, infos): <NEW_LINE> <INDENT> error(infos) <NEW_LINE> super(Core500Exception, self).__init__(500, 'Internal Server Error', infos) | Create a 500 *Internal Server Error* exception.
:param str infos: A message describing the error. | 625990673617ad0b5ee078dc |
class ListAPIView(FormatResponse, mixins.ListModelMixin, generics.GenericAPIView): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(ListAPIView, self).get_response(self.list(request, *args, **kwargs)) | Concrete view for listing a queryset. | 6259906756ac1b37e63038a8 |
class TRIG_MODE: <NEW_LINE> <INDENT> RUN = 0 <NEW_LINE> RGM = 2 <NEW_LINE> RTM = 3 | Define trigger modes. | 6259906701c39578d7f142fa |
class Git(object): <NEW_LINE> <INDENT> pypis = ["cloudmesh-common", "cloudmesh-cmd5", "cloudmesh-sys", "cloudmesh-comet", "cloudmesh-openapi"] <NEW_LINE> commits = pypis + ["cloudmesh-bar"] <NEW_LINE> @classmethod <NEW_LINE> def upload(cls): <NEW_LINE> <INDENT> banner("CREATE DIST") <NEW_LINE> for p in cls.pypis: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.system(f"cd {p}; make dist") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Console.error("can not create dist " + p) <NEW_LINE> print(e) <NEW_LINE> <DEDENT> <DEDENT> banner("UPLOAD TO PYPI") <NEW_LINE> for p in cls.pypis: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.system(f"cd {p}; make upload") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Console.error("can upload " + p) <NEW_LINE> print(e) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def commit(cls, msg): <NEW_LINE> <INDENT> banner("COMMIT " + msg) <NEW_LINE> for p in cls.commits: <NEW_LINE> <INDENT> banner("repo " + p) <NEW_LINE> os.system(f'cd {p}; git commit -a -m "{msg}"') <NEW_LINE> os.system(f'cd {p}; git push') | Git management for the preparation to upload the code to pypi | 625990676e29344779b01ddc |
class DemoLight(Light): <NEW_LINE> <INDENT> def __init__( self, name, state, rgb=None, ct=None, brightness=180, xy_color=(.5, .5), white=200): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._state = state <NEW_LINE> self._rgb = rgb <NEW_LINE> self._ct = ct or random.choice(LIGHT_TEMPS) <NEW_LINE> self._brightness = brightness <NEW_LINE> self._xy_color = xy_color <NEW_LINE> self._white = white <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> return self._brightness <NEW_LINE> <DEDENT> @property <NEW_LINE> def xy_color(self): <NEW_LINE> <INDENT> return self._xy_color <NEW_LINE> <DEDENT> @property <NEW_LINE> def rgb_color(self): <NEW_LINE> <INDENT> return self._rgb <NEW_LINE> <DEDENT> @property <NEW_LINE> def color_temp(self): <NEW_LINE> <INDENT> return self._ct <NEW_LINE> <DEDENT> @property <NEW_LINE> def white_value(self): <NEW_LINE> <INDENT> return self._white <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> return SUPPORT_DEMO <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> self._state = True <NEW_LINE> if ATTR_RGB_COLOR in kwargs: <NEW_LINE> <INDENT> self._rgb = kwargs[ATTR_RGB_COLOR] <NEW_LINE> <DEDENT> if ATTR_COLOR_TEMP in kwargs: <NEW_LINE> <INDENT> self._ct = kwargs[ATTR_COLOR_TEMP] <NEW_LINE> <DEDENT> if ATTR_BRIGHTNESS in kwargs: <NEW_LINE> <INDENT> self._brightness = kwargs[ATTR_BRIGHTNESS] <NEW_LINE> <DEDENT> if ATTR_XY_COLOR in kwargs: <NEW_LINE> <INDENT> self._xy_color = kwargs[ATTR_XY_COLOR] <NEW_LINE> <DEDENT> if ATTR_WHITE_VALUE in kwargs: <NEW_LINE> <INDENT> self._white = kwargs[ATTR_WHITE_VALUE] <NEW_LINE> <DEDENT> self.update_ha_state() <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> self.update_ha_state() | Represenation of a demo light. | 62599067e5267d203ee6cf83 |
class DiscogsSensor(Entity): <NEW_LINE> <INDENT> def __init__(self, discogs_data, name, sensor_type): <NEW_LINE> <INDENT> self._discogs_data = discogs_data <NEW_LINE> self._name = name <NEW_LINE> self._type = sensor_type <NEW_LINE> self._state = None <NEW_LINE> self._attrs = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "{} {}".format(self._name, SENSORS[self._type]['name']) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return SENSORS[self._type]['icon'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return SENSORS[self._type]['unit_of_measurement'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> if self._state is None or self._attrs is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self._type != SENSOR_RANDOM_RECORD_TYPE: <NEW_LINE> <INDENT> return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_IDENTITY: self._discogs_data['user'], } <NEW_LINE> <DEDENT> return { 'cat_no': self._attrs['labels'][0]['catno'], 'cover_image': self._attrs['cover_image'], 'format': "{} ({})".format( self._attrs['formats'][0]['name'], self._attrs['formats'][0]['descriptions'][0]), 'label': self._attrs['labels'][0]['name'], 'released': self._attrs['year'], ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_IDENTITY: self._discogs_data['user'], } <NEW_LINE> <DEDENT> def get_random_record(self): <NEW_LINE> <INDENT> collection = self._discogs_data['folders'][0] <NEW_LINE> random_index = random.randrange(collection.count) <NEW_LINE> random_record = collection.releases[random_index].release <NEW_LINE> self._attrs = random_record.data <NEW_LINE> return "{} - {}".format( random_record.data['artists'][0]['name'], random_record.data['title']) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self._type == SENSOR_COLLECTION_TYPE: <NEW_LINE> <INDENT> self._state = self._discogs_data['collection_count'] <NEW_LINE> <DEDENT> elif self._type == SENSOR_WANTLIST_TYPE: <NEW_LINE> <INDENT> self._state = self._discogs_data['wantlist_count'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state = self.get_random_record() | Create a new Discogs sensor for a specific type. | 625990673317a56b869bf108 |
class DiagnosticDetectorResponse(ProxyOnlyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, 'issue_detected': {'key': 'properties.issueDetected', 'type': 'bool'}, 'detector_definition': {'key': 'properties.detectorDefinition', 'type': 'DetectorDefinition'}, 'metrics': {'key': 'properties.metrics', 'type': '[DiagnosticMetricSet]'}, 'abnormal_time_periods': {'key': 'properties.abnormalTimePeriods', 'type': '[DetectorAbnormalTimePeriod]'}, 'data': {'key': 'properties.data', 'type': '[[NameValuePair]]'}, 'response_meta_data': {'key': 'properties.responseMetaData', 'type': 'ResponseMetaData'}, } <NEW_LINE> def __init__(self, kind=None, start_time=None, end_time=None, issue_detected=None, detector_definition=None, metrics=None, abnormal_time_periods=None, data=None, response_meta_data=None): <NEW_LINE> <INDENT> super(DiagnosticDetectorResponse, self).__init__(kind=kind) <NEW_LINE> self.start_time = start_time <NEW_LINE> self.end_time = end_time <NEW_LINE> self.issue_detected = issue_detected <NEW_LINE> self.detector_definition = detector_definition <NEW_LINE> self.metrics = metrics <NEW_LINE> self.abnormal_time_periods = abnormal_time_periods <NEW_LINE> self.data = data <NEW_LINE> self.response_meta_data = response_meta_data | Class representing Reponse from Diagnostic Detectors.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
:param start_time: Start time of the period
:type start_time: datetime
:param end_time: End time of the period
:type end_time: datetime
:param issue_detected: Flag representing Issue was detected.
:type issue_detected: bool
:param detector_definition: Detector's definition
:type detector_definition: ~azure.mgmt.web.models.DetectorDefinition
:param metrics: Metrics provided by the detector
:type metrics: list[~azure.mgmt.web.models.DiagnosticMetricSet]
:param abnormal_time_periods: List of Correlated events found by the
detector
:type abnormal_time_periods:
list[~azure.mgmt.web.models.DetectorAbnormalTimePeriod]
:param data: Additional Data that detector wants to send.
:type data: list[list[~azure.mgmt.web.models.NameValuePair]]
:param response_meta_data: Meta Data
:type response_meta_data: ~azure.mgmt.web.models.ResponseMetaData | 625990672ae34c7f260ac873 |
class FailureCount(generics.ListAPIView): <NEW_LINE> <INDENT> serializer_class = FailureCountSerializer <NEW_LINE> queryset = None <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> query_params = FailuresQueryParamsSerializer(data=request.query_params) <NEW_LINE> if not query_params.is_valid(): <NEW_LINE> <INDENT> return Response(data=query_params.errors, status=HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> startday = query_params.validated_data['startday'] <NEW_LINE> endday = get_end_of_day(query_params.validated_data['endday']) <NEW_LINE> repo = query_params.validated_data['tree'] <NEW_LINE> bug_id = query_params.validated_data['bug'] <NEW_LINE> push_query = ( Push.failures.filter(time__range=(startday, endday)) .by_repo(repo, False) .annotate(date=TruncDate('time')) .values('date') .annotate(test_runs=Count('author')) .values('date', 'test_runs') ) <NEW_LINE> if bug_id: <NEW_LINE> <INDENT> job_query = ( BugJobMap.failures.by_date(startday, endday) .by_repo(repo) .by_bug(bug_id) .annotate(date=TruncDate('job__push__time')) .values('date') .annotate(failure_count=Count('id')) .values('date', 'failure_count') ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> job_query = ( Job.failures.filter( push__time__range=(startday, endday), failure_classification_id=4 ) .by_repo(repo, False) .select_related('push') .annotate(date=TruncDate('push__time')) .values('date') .annotate(failure_count=Count('id')) .values('date', 'failure_count') ) <NEW_LINE> <DEDENT> self.queryset = [] <NEW_LINE> for push in push_query: <NEW_LINE> <INDENT> match = [job for job in job_query if push['date'] == job['date']] <NEW_LINE> if match: <NEW_LINE> <INDENT> match[0]['test_runs'] = push['test_runs'] <NEW_LINE> self.queryset.append(match[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.queryset.append( {'date': push['date'], 'test_runs': push['test_runs'], 'failure_count': 0} ) <NEW_LINE> <DEDENT> <DEDENT> serializer = self.get_serializer(self.queryset, many=True) <NEW_LINE> return Response(serializer.data) | List of failures (optionally by bug) and testruns by day per date range and repo | 625990673cc13d1c6d466ed0 |
class ListDict(UserDict): <NEW_LINE> <INDENT> def __setitem__(self, key, val): <NEW_LINE> <INDENT> if key in self.data: <NEW_LINE> <INDENT> self.data[key].append(val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data[key] = [val] <NEW_LINE> <DEDENT> <DEDENT> def addList(self, key, valList): <NEW_LINE> <INDENT> valList = list(valList) <NEW_LINE> if key in self.data: <NEW_LINE> <INDENT> self.data[key] += valList <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data[key] = valList <NEW_LINE> <DEDENT> <DEDENT> def remove(self, key, val): <NEW_LINE> <INDENT> self.data.get(key).remove(val) | A dictionary whose values are a list of items.
| 62599067f7d966606f749480 |
@override_settings( PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF="admin_views.urls", ) <NEW_LINE> class GetFormsetsWithInlinesArgumentTest(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpTestData(cls): <NEW_LINE> <INDENT> cls.superuser = User.objects.create( password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', last_login=datetime.datetime(2007, 5, 30, 13, 20, 10), is_superuser=True, username='super', first_name='Super', last_name='User', email='[email protected]', is_staff=True, is_active=True, date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10) ) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.client.force_login(self.superuser) <NEW_LINE> <DEDENT> def test_explicitly_provided_pk(self): <NEW_LINE> <INDENT> post_data = {'name': '1'} <NEW_LINE> response = self.client.post(reverse('admin:admin_views_explicitlyprovidedpk_add'), post_data) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> post_data = {'name': '2'} <NEW_LINE> response = self.client.post(reverse('admin:admin_views_explicitlyprovidedpk_change', args=(1,)), post_data) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> <DEDENT> def test_implicitly_generated_pk(self): <NEW_LINE> <INDENT> post_data = {'name': '1'} <NEW_LINE> response = self.client.post(reverse('admin:admin_views_implicitlygeneratedpk_add'), post_data) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> post_data = {'name': '2'} <NEW_LINE> response = self.client.post(reverse('admin:admin_views_implicitlygeneratedpk_change', args=(1,)), post_data) <NEW_LINE> self.assertEqual(response.status_code, 302) | #23934 - When adding a new model instance in the admin, the 'obj' argument
of get_formsets_with_inlines() should be None. When changing, it should be
equal to the existing model instance.
The GetFormsetsArgumentCheckingAdmin ModelAdmin throws an exception
if obj is not None during add_view or obj is None during change_view. | 625990671f5feb6acb164378 |
class NeuralNetwork: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> weights = np.array([0,1]) <NEW_LINE> bias = 0 <NEW_LINE> self.h1 = Neuron(weights,bias) <NEW_LINE> self.h2 = Neuron(weights,bias) <NEW_LINE> self.o1 = Neuron(weights,bias) <NEW_LINE> <DEDENT> def feedforward(self,x): <NEW_LINE> <INDENT> out_h1 = self.h1.feedforward(x) <NEW_LINE> out_h2 = self.h2.feedforward(x) <NEW_LINE> print(out_h1) <NEW_LINE> out_o1 = self.o1.feedforward(np.array([out_h1,out_h2])) <NEW_LINE> return out_o1 | A neural network with:
- 2 inputs
- a hidden layer with 2 neurons (h1, h2)
- an output layer with 1 neuron (o1)
Each neuron has the same weights and bias:
- w = [0, 1]
- b = 0 | 62599067442bda511e95d91f |
class UndefinedReferenceException(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(UndefinedReferenceException, self).__init__(message) | gerador_roteiros.datatypes.exceptions.UndefinedReferenceException
~~~~~~~~~~
Esta exceção deve ser lançada somente se existirem links apontando para
passos cujo número de sequência não existe dentro do caso de uso. | 625990672ae34c7f260ac874 |
class UserCreateCase(APITestCase): <NEW_LINE> <INDENT> def setUp(self) -> None: <NEW_LINE> <INDENT> self.url = '/user' <NEW_LINE> self.user = User.objects.create( email='[email protected]', name='user', username='user', password='user', ) <NEW_LINE> <DEDENT> def test_success(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'name': 'test', 'username': 'test', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertEqual(response.data['email'], data['email']) <NEW_LINE> self.assertEqual(response.data['name'], data['name']) <NEW_LINE> self.assertEqual(response.data['username'], data['username']) <NEW_LINE> <DEDENT> def test_wrong_authenticate(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'name': 'test', 'username': 'test', 'password': 'test', } <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> def test_overlap_email(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'name': 'test', 'username': 'test', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_overlap_username(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'name': 'test', 'username': 'user', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_none_email(self): <NEW_LINE> <INDENT> data = { 'name': 'test', 'username': 'test', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_none_name(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'username': 'test', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_none_username(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'name': 'test', 'password': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_none_password(self): <NEW_LINE> <INDENT> data = { 'email': '[email protected]', 'username': 'test', 'name': 'test', } <NEW_LINE> response = self.client.post(self.url, data=data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_none_all(self): <NEW_LINE> <INDENT> response = self.client.post(self.url) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) | Create User Test Code | 6259906763d6d428bbee3e4f |
class Restaurant: <NEW_LINE> <INDENT> def __init__(self, name, cuisine): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.cuisine = cuisine <NEW_LINE> <DEDENT> def describe_restaurant(self): <NEW_LINE> <INDENT> print(f"{self.name} is a {self.cuisine} restaurant.") <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print(f"{self.name} is open.") | A model of a restaurant | 62599067baa26c4b54d50a32 |
class Union(TypeContainer): <NEW_LINE> <INDENT> pass | Class representing a combination of SimpleTypes (for type value enforcement) | 6259906744b2445a339b7526 |
class OperationDisplay(Model): <NEW_LINE> <INDENT> _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, } <NEW_LINE> def __init__(self, provider=None, resource=None, operation=None): <NEW_LINE> <INDENT> self.provider = provider <NEW_LINE> self.resource = resource <NEW_LINE> self.operation = operation | The object that represents the operation.
:param provider: Service provider: Microsoft.Logic
:type provider: str
:param resource: Resource on which the operation is performed: Profile,
endpoint, etc.
:type resource: str
:param operation: Operation type: Read, write, delete, etc.
:type operation: str | 625990679c8ee82313040d4e |
class ElasticsearchTarget(luigi.Target): <NEW_LINE> <INDENT> marker_index = luigi.configuration.get_config().get('elasticsearch', 'marker-index', 'update_log') <NEW_LINE> marker_doc_type = luigi.configuration.get_config().get('elasticsearch', 'marker-doc-type', 'entry') <NEW_LINE> def __init__(self, host, port, index, doc_type, update_id, marker_index_hist_size=0, http_auth=None): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.http_auth = http_auth <NEW_LINE> self.index = index <NEW_LINE> self.doc_type = doc_type <NEW_LINE> self.update_id = update_id <NEW_LINE> self.marker_index_hist_size = marker_index_hist_size <NEW_LINE> self.es = elasticsearch.Elasticsearch( connection_class=Urllib3HttpConnection, host=self.host, port=self.port, http_auth=self.http_auth ) <NEW_LINE> <DEDENT> def marker_index_document_id(self): <NEW_LINE> <INDENT> params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id) <NEW_LINE> return hashlib.sha1(params).hexdigest() <NEW_LINE> <DEDENT> def touch(self): <NEW_LINE> <INDENT> self.create_marker_index() <NEW_LINE> self.es.index(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id(), body={ 'update_id': self.update_id, 'target_index': self.index, 'target_doc_type': self.doc_type, 'date': datetime.datetime.now()}) <NEW_LINE> self.es.indices.flush(index=self.marker_index) <NEW_LINE> self.ensure_hist_size() <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _ = self.es.get(index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker_index_document_id()) <NEW_LINE> return True <NEW_LINE> <DEDENT> except elasticsearch.NotFoundError: <NEW_LINE> <INDENT> logger.debug('Marker document not found.') <NEW_LINE> <DEDENT> except elasticsearch.ElasticsearchException as err: <NEW_LINE> <INDENT> logger.warn(err) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def create_marker_index(self): <NEW_LINE> <INDENT> if not self.es.indices.exists(index=self.marker_index): <NEW_LINE> <INDENT> self.es.indices.create(index=self.marker_index) <NEW_LINE> <DEDENT> <DEDENT> def ensure_hist_size(self): <NEW_LINE> <INDENT> if self.marker_index_hist_size == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result = self.es.search(index=self.marker_index, doc_type=self.marker_doc_type, body={'query': { 'term': {'target_index': self.index}}}, sort=('date:desc',)) <NEW_LINE> for i, hit in enumerate(result.get('hits').get('hits'), start=1): <NEW_LINE> <INDENT> if i > self.marker_index_hist_size: <NEW_LINE> <INDENT> marker_document_id = hit.get('_id') <NEW_LINE> self.es.delete(id=marker_document_id, index=self.marker_index, doc_type=self.marker_doc_type) <NEW_LINE> <DEDENT> <DEDENT> self.es.indices.flush(index=self.marker_index) | Target for a resource in Elasticsearch. | 625990672c8b7c6e89bd4f72 |
class AzureFirewallNatRule(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'}, 'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'}, 'destination_ports': {'key': 'destinationPorts', 'type': '[str]'}, 'protocols': {'key': 'protocols', 'type': '[str]'}, 'translated_address': {'key': 'translatedAddress', 'type': 'str'}, 'translated_port': {'key': 'translatedPort', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureFirewallNatRule, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.description = kwargs.get('description', None) <NEW_LINE> self.source_addresses = kwargs.get('source_addresses', None) <NEW_LINE> self.destination_addresses = kwargs.get('destination_addresses', None) <NEW_LINE> self.destination_ports = kwargs.get('destination_ports', None) <NEW_LINE> self.protocols = kwargs.get('protocols', None) <NEW_LINE> self.translated_address = kwargs.get('translated_address', None) <NEW_LINE> self.translated_port = kwargs.get('translated_port', None) | Properties of a NAT rule.
:param name: Name of the NAT rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses for this rule.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param protocols: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
:type protocols: list[str or
~azure.mgmt.network.v2018_10_01.models.AzureFirewallNetworkRuleProtocol]
:param translated_address: The translated address for this NAT rule.
:type translated_address: str
:param translated_port: The translated port for this NAT rule.
:type translated_port: str | 625990677b180e01f3e49c2a |
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length = 255, unique = True) <NEW_LINE> name = models.CharField(max_length = 255) <NEW_LINE> is_active = models.BooleanField(default = True) <NEW_LINE> is_staff = models.BooleanField(default = False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELD = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email | Respents the "user profile" inside our system. | 6259906732920d7e50bc77d3 |
class DeviceRegistry(): <NEW_LINE> <INDENT> DEFAULT_FILENAME = "registry.kvs" <NEW_LINE> def __init__(self, filename=None): <NEW_LINE> <INDENT> self.store = KVS(filename) <NEW_LINE> self.fsk_router = None <NEW_LINE> <DEDENT> def set_fsk_router(self, fsk_router): <NEW_LINE> <INDENT> self.fsk_router = fsk_router <NEW_LINE> <DEDENT> def load_from(self, filename=None): <NEW_LINE> <INDENT> if filename == None: filename = DeviceRegistry.DEFAULT_FILENAME <NEW_LINE> self.store = KVS(filename) <NEW_LINE> self.store.load(filename, Devices.DeviceFactory.get_device_from_name) <NEW_LINE> <DEDENT> def load_into(self, context): <NEW_LINE> <INDENT> if context == None: <NEW_LINE> <INDENT> raise ValueError("Must provide a context to hold new variables") <NEW_LINE> <DEDENT> for name in self.store.keys(): <NEW_LINE> <INDENT> c = self.get(name) <NEW_LINE> setattr(context, name, c) <NEW_LINE> <DEDENT> <DEDENT> def add(self, device, name): <NEW_LINE> <INDENT> self.store[name] = device <NEW_LINE> <DEDENT> def get(self, name): <NEW_LINE> <INDENT> c = self.store[name] <NEW_LINE> if self.fsk_router != None: <NEW_LINE> <INDENT> if c.can_send(): <NEW_LINE> <INDENT> if isinstance(c, Devices.MiHomeDevice): <NEW_LINE> <INDENT> print("Adding rx route for transmit enabled device %s" % c) <NEW_LINE> address = (c.manufacturer_id, c.product_id, c.device_id) <NEW_LINE> self.fsk_router.add(address, c) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return c <NEW_LINE> <DEDENT> def rename(self, old_name, new_name): <NEW_LINE> <INDENT> c = self.store[old_name] <NEW_LINE> self.delete(old_name) <NEW_LINE> self.add(c, new_name) <NEW_LINE> <DEDENT> def delete(self, name): <NEW_LINE> <INDENT> del self.store[name] <NEW_LINE> <DEDENT> def list(self): <NEW_LINE> <INDENT> print("REGISTERED DEVICES:") <NEW_LINE> for k in self.store.keys(): <NEW_LINE> <INDENT> print(" %s -> %s" % (k, self.store[k])) <NEW_LINE> <DEDENT> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self.store.size() <NEW_LINE> <DEDENT> def devices(self): <NEW_LINE> <INDENT> for k in self.store.keys(): <NEW_LINE> <INDENT> device = self.store[k] <NEW_LINE> yield device <NEW_LINE> <DEDENT> <DEDENT> def names(self): <NEW_LINE> <INDENT> devices = list(self.store.keys()) <NEW_LINE> i = 0 <NEW_LINE> while i < len(devices): <NEW_LINE> <INDENT> k = devices[i] <NEW_LINE> yield k <NEW_LINE> i += 1 | A persistent registry for device class instance configurations | 625990673617ad0b5ee078de |
class LeaveOneOut(BaseCrossValidator): <NEW_LINE> <INDENT> def _iter_test_indices(self, X, y=None, groups=None): <NEW_LINE> <INDENT> n_samples = _num_samples(X) <NEW_LINE> if n_samples <= 1: <NEW_LINE> <INDENT> raise ValueError( 'Cannot perform LeaveOneOut with n_samples={}.'.format( n_samples) ) <NEW_LINE> <DEDENT> return range(n_samples) <NEW_LINE> <DEDENT> def get_n_splits(self, X, y=None, groups=None): <NEW_LINE> <INDENT> if X is None: <NEW_LINE> <INDENT> raise ValueError("The 'X' parameter should not be None.") <NEW_LINE> <DEDENT> return _num_samples(X) | Leave-One-Out cross-validator
Provides train/test indices to split data in train/test sets. Each
sample is used once as a test set (singleton) while the remaining
samples form the training set.
Note: ``LeaveOneOut()`` is equivalent to ``KFold(n_splits=n)`` and
``LeavePOut(p=1)`` where ``n`` is the number of samples.
Due to the high number of test sets (which is the same as the
number of samples) this cross-validation method can be very costly.
For large datasets one should favor :class:`KFold`, :class:`ShuffleSplit`
or :class:`StratifiedKFold`.
Read more in the :ref:`User Guide <cross_validation>`.
Examples
--------
>>> import numpy as np
>>> from sklearn.model_selection import LeaveOneOut
>>> X = np.array([[1, 2], [3, 4]])
>>> y = np.array([1, 2])
>>> loo = LeaveOneOut()
>>> loo.get_n_splits(X)
2
>>> print(loo)
LeaveOneOut()
>>> for train_index, test_index in loo.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
TRAIN: [1] TEST: [0]
[[3 4]] [[1 2]] [2] [1]
TRAIN: [0] TEST: [1]
[[1 2]] [[3 4]] [1] [2]
See also
--------
LeaveOneGroupOut
For splitting the data according to explicit, domain-specific
stratification of the dataset.
GroupKFold: K-fold iterator variant with non-overlapping groups. | 62599067dd821e528d6da547 |
class GoogleCloudDialogflowV2ListIntentsResponse(_messages.Message): <NEW_LINE> <INDENT> intents = _messages.MessageField('GoogleCloudDialogflowV2Intent', 1, repeated=True) <NEW_LINE> nextPageToken = _messages.StringField(2) | The response message for Intents.ListIntents.
Fields:
intents: The list of agent intents. There will be a maximum number of
items returned based on the page_size field in the request.
nextPageToken: Token to retrieve the next page of results, or empty if
there are no more results in the list. | 625990671f037a2d8b9e5431 |
class BaseAssociateMetadata(BasePersonMetadata): <NEW_LINE> <INDENT> pass | Metadata that describes an associate
Generally does not change over the course of a sports-events. | 625990672c8b7c6e89bd4f73 |
class IpFilterRule(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'filter_name': {'required': True}, 'action': {'required': True}, 'ip_mask': {'required': True}, } <NEW_LINE> _attribute_map = { 'filter_name': {'key': 'filterName', 'type': 'str'}, 'action': {'key': 'action', 'type': 'str'}, 'ip_mask': {'key': 'ipMask', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, filter_name: str, action: Union[str, "IpFilterActionType"], ip_mask: str, **kwargs ): <NEW_LINE> <INDENT> super(IpFilterRule, self).__init__(**kwargs) <NEW_LINE> self.filter_name = filter_name <NEW_LINE> self.action = action <NEW_LINE> self.ip_mask = ip_mask | The IP filter rules for the IoT hub.
All required parameters must be populated in order to send to Azure.
:ivar filter_name: Required. The name of the IP filter rule.
:vartype filter_name: str
:ivar action: Required. The desired action for requests captured by this rule. Possible values
include: "Accept", "Reject".
:vartype action: str or ~azure.mgmt.iothub.v2021_03_31.models.IpFilterActionType
:ivar ip_mask: Required. A string that contains the IP address range in CIDR notation for the
rule.
:vartype ip_mask: str | 625990674e4d562566373b94 |
class ComputeTool(ShelfTool): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super( ComputeTool, self).__init__() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def toolTip(): <NEW_LINE> <INDENT> return "call compute method for selected nodes" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getIcon(): <NEW_LINE> <INDENT> return QtGui.QIcon(RESOURCES_DIR + "compute.png") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def name(): <NEW_LINE> <INDENT> return str("ComputeTool") <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> nodes=FreeCAD.PF.graphManager.get().getAllNodes() <NEW_LINE> nodes2 = sorted(nodes, key=lambda node: node.x) <NEW_LINE> say("selected Nodes ...") <NEW_LINE> for n in nodes2: <NEW_LINE> <INDENT> if n.getWrapper().isSelected(): <NEW_LINE> <INDENT> say(n,n.x) <NEW_LINE> n.compute() | docstring for PreviewTool. | 62599067d6c5a102081e38b4 |
class CustomSession(AbstractBaseSession): <NEW_LINE> <INDENT> account_id = models.IntegerField(null=True, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_lablel = 'mysessions' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_session_store_class(cls): <NEW_LINE> <INDENT> return SessionStore | CustomSession. | 625990678da39b475be04978 |
class Node: <NEW_LINE> <INDENT> node = 0 <NEW_LINE> adj = None <NEW_LINE> visited = False <NEW_LINE> parent = -1 | Class containing various information about nodes
Attributes:
node(int): Identifier
adj(list): List of adjacent nodes
visited(boolean): Switch intended to turn on once node is visited
parent(int): Identifier of parent node | 625990674428ac0f6e659cc0 |
class BuildingStructureCode(models.Model): <NEW_LINE> <INDENT> code = models.CharField(primary_key=True, max_length=1, verbose_name=u"代码") <NEW_LINE> name = models.CharField(unique=True, max_length=32, verbose_name=u"名称") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | 建筑物结构码 | 62599067627d3e7fe0e08618 |
class Tiers(Session): <NEW_LINE> <INDENT> def __init__(self, session, tier_guid='', provider_guid=''): <NEW_LINE> <INDENT> self.api_key = session.api_key <NEW_LINE> self.api_endpoint = '/v1/tiers' <NEW_LINE> self.api_variables = { 'tier_guid': tier_guid, 'provider_guid': provider_guid } <NEW_LINE> self.api_paths = { 'root': '/', 'tiers': '/%(tier_guid)s', 'companies': '/%(tier_guid)s/companies', 'providers': '/%(tier_guid)s/providers', 'provider dependents': '/%(tier_guid)s/providers/%(provider_guid)s/companies', 'provider products': '/%(tier_guid)s/providers/%(provider_guid)s/products' } <NEW_LINE> self.api_params = [ 'limit', 'offset', 'q', 'sort', 'fields', 'data', 'description', 'companies', 'rank', 'email_enabled', 'guid', 'name' 'remove_companies', 'add_companies', 'relationship_type' ] | Tiers class | 62599067baa26c4b54d50a34 |
class AbortConfigException(Exception): <NEW_LINE> <INDENT> pass | This exception is thrown if the configuration script should be aborted
immediately. No other config script methods will be called after this
exception. | 62599067a219f33f346c7f95 |
class LowSpeedShaftMass(om.ExplicitComponent): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.add_input("blade_mass", 0.0, units="kg") <NEW_LINE> self.add_input("machine_rating", 0.0, units="kW") <NEW_LINE> self.add_input("lss_mass_coeff", 13.0) <NEW_LINE> self.add_input("lss_mass_exp", 0.65) <NEW_LINE> self.add_input("lss_mass_intercept", 775.0) <NEW_LINE> self.add_output("lss_mass", 0.0, units="kg") <NEW_LINE> <DEDENT> def compute(self, inputs, outputs): <NEW_LINE> <INDENT> blade_mass = inputs["blade_mass"] <NEW_LINE> machine_rating = inputs["machine_rating"] <NEW_LINE> lss_mass_coeff = inputs["lss_mass_coeff"] <NEW_LINE> lss_mass_exp = inputs["lss_mass_exp"] <NEW_LINE> lss_mass_intercept = inputs["lss_mass_intercept"] <NEW_LINE> outputs["lss_mass"] = ( lss_mass_coeff * (blade_mass * machine_rating / 1000.0) ** lss_mass_exp + lss_mass_intercept ) | Compute low speed shaft mass in the form of :math:`mass = k*(m_{blade}*power)^b1 + b2`.
Value of :math:`k` was updated in 2015 to be 13.
Value of :math:`b1` was updated in 2015 to be 0.65.
Value of :math:`b2` was updated in 2015 to be 775.
Parameters
----------
blade_mass : float, [kg]
mass for a single wind turbine blade
machine_rating : float, [kW]
machine rating
lss_mass_coeff : float
k inthe lss mass equation: k*(blade_mass*rated_power)^b1 + b2
lss_mass_exp : float
b1 in the lss mass equation: k*(blade_mass*rated_power)^b1 + b2
lss_mass_intercept : float
b2 in the lss mass equation: k*(blade_mass*rated_power)^b1 + b2
Returns
-------
lss_mass : float, [kg]
component mass | 62599067796e427e5384ff05 |
class IOriginalFileExternalLinks(IPortletDataProvider): <NEW_LINE> <INDENT> pass | A portlet
It inherits from IPortletDataProvider because for this portlet, the
data that is being rendered and the portlet assignment itself are the
same. | 625990677b180e01f3e49c2b |
class MediaStreamTrack(EventEmitter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__ended = False <NEW_LINE> self.__id = str(uuid.uuid4()) <NEW_LINE> self.__copy_codec = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self.__id <NEW_LINE> <DEDENT> @property <NEW_LINE> def readyState(self): <NEW_LINE> <INDENT> return 'ended' if self.__ended else 'live' <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if not self.__ended: <NEW_LINE> <INDENT> self.__ended = True <NEW_LINE> self.emit('ended') <NEW_LINE> self.remove_all_listeners() | A single media track within a stream.
See :class:`AudioStreamTrack` and :class:`VideoStreamTrack`. | 6259906745492302aabfdc6b |
class AttributeError(Exception): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(*args, **kwargs): <NEW_LINE> <INDENT> pass | Attribute not found. | 625990678a43f66fc4bf391f |
class TrelloCardSearchView(ReviewRequestViewMixin, View): <NEW_LINE> <INDENT> def get(self, request, **kwargs): <NEW_LINE> <INDENT> from rbintegrations.trello.integration import TrelloIntegration <NEW_LINE> integration_manager = get_integration_manager() <NEW_LINE> integration = integration_manager.get_integration( TrelloIntegration.integration_id) <NEW_LINE> configs = ( config for config in integration.get_configs( self.review_request.local_site) if config.match_conditions(form_cls=integration.config_form_cls, review_request=self.review_request) ) <NEW_LINE> results = [] <NEW_LINE> params = { 'card_board': 'true', 'card_fields': 'id,name,shortUrl', 'card_list': 'true', 'cards_limit': 20, 'modelTypes': 'cards', 'partial': 'true', 'query': request.GET.get('q'), } <NEW_LINE> for config in configs: <NEW_LINE> <INDENT> params['key'] = config.settings['trello_api_key'] <NEW_LINE> params['token'] = config.settings['trello_api_token'] <NEW_LINE> url = 'https://api.trello.com/1/search?%s' % urlencode(params) <NEW_LINE> try: <NEW_LINE> <INDENT> response = urlopen(url) <NEW_LINE> data = json.loads(response.read()) <NEW_LINE> for card in data['cards']: <NEW_LINE> <INDENT> results.append({ 'id': card['id'], 'name': card['name'], 'board': card.get('board', {}).get('name', ''), 'list': card.get('list', {}).get('name', ''), 'url': card['shortUrl'], }) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.exception('Unexpected error when searching for Trello ' 'cards: %s', e) <NEW_LINE> <DEDENT> <DEDENT> return HttpResponse(json.dumps(results), content_type='application/json') | The view to search for Trello cards (for use with auto-complete). | 6259906723849d37ff852845 |
class DataStore(object): <NEW_LINE> <INDENT> def __init__(self, config, **kwargs): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.intrafield_delimiter = self.config['DATASTORE']['intrafield_delimiter'] <NEW_LINE> if not 'DATASTORE' in self.config: <NEW_LINE> <INDENT> raise KeyError <NEW_LINE> <DEDENT> <DEDENT> def process(self): <NEW_LINE> <INDENT> datasets = [] <NEW_LINE> for source in self.get_sources(): <NEW_LINE> <INDENT> _path, ext = os.path.splitext(source) <NEW_LINE> if ext in self.config['DATASTORE']['formats']: <NEW_LINE> <INDENT> _head, key = os.path.split(_path) <NEW_LINE> dataset_raw = self._extract_data(source) <NEW_LINE> if dataset_raw: <NEW_LINE> <INDENT> dataset_clean = self._clean_data(dataset_raw) <NEW_LINE> datasets.append((key, dataset_clean)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return datasets <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> rv = {} <NEW_LINE> for dataset in self.process(): <NEW_LINE> <INDENT> rv[dataset[0]] = dataset[1] <NEW_LINE> <DEDENT> return rv <NEW_LINE> <DEDENT> def get_location(self): <NEW_LINE> <INDENT> return self.config['DATASTORE']['location'] <NEW_LINE> <DEDENT> def get_sources(self): <NEW_LINE> <INDENT> sources = [] <NEW_LINE> for (dirpath, _, filenames) in os.walk(self.get_location()): <NEW_LINE> <INDENT> sources.extend(os.path.join(dirpath, filename) for filename in filenames) <NEW_LINE> <DEDENT> return sources <NEW_LINE> <DEDENT> def _extract_data(self, data_source): <NEW_LINE> <INDENT> with open(data_source) as f: <NEW_LINE> <INDENT> stream = f.read() <NEW_LINE> extracted = tablib.import_set(stream) <NEW_LINE> <DEDENT> return extracted <NEW_LINE> <DEDENT> def _clean_data(self, raw_dataset): <NEW_LINE> <INDENT> dataset_clean_headers = self._normalize_headers(raw_dataset) <NEW_LINE> dataset_clean = self._normalize_rows(dataset_clean_headers) <NEW_LINE> return dataset_clean <NEW_LINE> <DEDENT> def _normalize_headers(self, dataset): <NEW_LINE> <INDENT> transform_chars = { ord('-'): None, ord('"'): None, ord(' '): None, ord("'"): None, } <NEW_LINE> for index, header in enumerate(dataset.headers): <NEW_LINE> <INDENT> tmp = unicode(header).translate(transform_chars).lower() <NEW_LINE> dataset.headers[index] = tmp <NEW_LINE> <DEDENT> return dataset <NEW_LINE> <DEDENT> def _normalize_rows(self, dataset): <NEW_LINE> <INDENT> workspace = dataset.dict <NEW_LINE> for item in workspace: <NEW_LINE> <INDENT> for k, v in item.iteritems(): <NEW_LINE> <INDENT> item[k] = v.strip() <NEW_LINE> if v in self.config['DATASTORE']['true_strings']: <NEW_LINE> <INDENT> item[k] = True <NEW_LINE> <DEDENT> if v in self.config['DATASTORE']['false_strings']: <NEW_LINE> <INDENT> item[k] = False <NEW_LINE> <DEDENT> if v in self.config['DATASTORE']['none_strings']: <NEW_LINE> <INDENT> item[k] = None <NEW_LINE> <DEDENT> if self.intrafield_delimiter in v: <NEW_LINE> <INDENT> item[k] = v.split(self.intrafield_delimiter) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> dataset.dict = workspace <NEW_LINE> return dataset | Interface for static file datastore.
self.build() returns a dict where `key` is the name of the dataset,
and `value` is a tablib.Dataset object.
At present, should support any file format that tablib can import:
* csv
* json
* yaml
* see tablib for full support. | 625990674e4d562566373b96 |
class gblog_out(component): <NEW_LINE> <INDENT> def __init__(self, gblog_connector, name='component.output.gblog_out', transformer=None, row_limit=0): <NEW_LINE> <INDENT> super(gblog_out, self).__init__(name=name, connector=gblog_connector, transformer=transformer, row_limit=row_limit) <NEW_LINE> self._type = 'component.output.gblog_out' <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> res = gblog_out(self.connector, self.name, self.transformer, self.row_limit) <NEW_LINE> return res <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> res = super(gblog_out, self).__getstate__() <NEW_LINE> return res <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> super(gblog_out, self).__setstate__(state) <NEW_LINE> self.__dict__ = state <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> from gdata import service <NEW_LINE> import gdata <NEW_LINE> import atom <NEW_LINE> gblog_service = self.connector.open() <NEW_LINE> feed = gblog_service.Get('/feeds/default/blogs') <NEW_LINE> self_link = feed.entry[0].GetSelfLink() <NEW_LINE> if self_link: <NEW_LINE> <INDENT> blog_id = self_link.href.split('/')[-1] <NEW_LINE> <DEDENT> for channel, trans in self.input_get().items(): <NEW_LINE> <INDENT> for iterator in trans: <NEW_LINE> <INDENT> for d in iterator: <NEW_LINE> <INDENT> entry = gdata.GDataEntry() <NEW_LINE> entry.author.append(atom.Author(atom.Name(text='uid'))) <NEW_LINE> entry.title = atom.Title(title_type='xhtml', text=d['name']) <NEW_LINE> entry.content = atom.Content(content_type='html', text=d['description']) <NEW_LINE> gblog_service.Post(entry, '/feeds/' + blog_id + '/posts/default') <NEW_LINE> yield d, 'main' | This is an ETL Component that writes data to google blogger. | 6259906771ff763f4b5e8f35 |
class TestReview(unittest.TestCase): <NEW_LINE> <INDENT> def test_class(self): <NEW_LINE> <INDENT> self.assertEqual(Review.place_id, "") <NEW_LINE> self.assertEqual(Review.user_id, "") <NEW_LINE> self.assertEqual(Review.text, "") <NEW_LINE> self.assertTrue(issubclass(Review, BaseModel)) <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> my_review = Review() <NEW_LINE> self.assertEqual(my_review.place_id, "") <NEW_LINE> self.assertEqual(my_review.user_id, "") <NEW_LINE> self.assertEqual(my_review.text, "") <NEW_LINE> self.assertTrue(isinstance(my_review, BaseModel)) | Test review | 62599067d6c5a102081e38b6 |
class RegisterUserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> email = serializers.EmailField( validators=[UniqueValidator( queryset=User.objects.all(), message='Email already exists' )] ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'email', 'password') <NEW_LINE> extra_kwargs = {'password': {'write_only': True}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user = User( username=validated_data['username'], email=validated_data['email'] ) <NEW_LINE> user.set_password(validated_data['password']) <NEW_LINE> user.save() <NEW_LINE> return user | Data serialization for user registration | 62599067f7d966606f749482 |
class Scaffold(Command): <NEW_LINE> <INDENT> def run(self, cmdargs): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( prog="%s scaffold" % sys.argv[0].split(os.path.sep)[-1], description=self.__doc__, epilog=self.epilog(), ) <NEW_LINE> parser.add_argument( '-t', '--template', type=template, default=template('default'), help="Use a custom module template, can be a template name or the" " path to a module template (default: %(default)s)") <NEW_LINE> parser.add_argument('name', help="Name of the module to create") <NEW_LINE> parser.add_argument( 'dest', default='.', nargs='?', help="Directory to create the module in (default: %(default)s)") <NEW_LINE> if not cmdargs: <NEW_LINE> <INDENT> sys.exit(parser.print_help()) <NEW_LINE> <DEDENT> args = parser.parse_args(args=cmdargs) <NEW_LINE> args.template.render_to( snake(args.name), directory(args.dest, create=True), {'name': args.name}) <NEW_LINE> <DEDENT> def epilog(self): <NEW_LINE> <INDENT> return "Built-in templates available are: %s" % ', '.join( d for d in os.listdir(builtins()) if d != 'base' ) | Generates an Odoo module skeleton. | 625990678da39b475be0497a |
class VethFixture(fixtures.Fixture): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(VethFixture, self).setUp() <NEW_LINE> ip_wrapper = ip_lib.IPWrapper() <NEW_LINE> def _create_veth(name0): <NEW_LINE> <INDENT> name1 = name0.replace(VETH0_PREFIX, VETH1_PREFIX) <NEW_LINE> return ip_wrapper.add_veth(name0, name1) <NEW_LINE> <DEDENT> self.ports = common_base.create_resource(VETH0_PREFIX, _create_veth) <NEW_LINE> self.addCleanup(self.destroy) <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> for port in self.ports: <NEW_LINE> <INDENT> ip_wrapper = ip_lib.IPWrapper(port.namespace) <NEW_LINE> try: <NEW_LINE> <INDENT> ip_wrapper.del_veth(port.name) <NEW_LINE> break <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_peer_name(name): <NEW_LINE> <INDENT> if name.startswith(VETH0_PREFIX): <NEW_LINE> <INDENT> return name.replace(VETH0_PREFIX, VETH1_PREFIX) <NEW_LINE> <DEDENT> elif name.startswith(VETH1_PREFIX): <NEW_LINE> <INDENT> return name.replace(VETH1_PREFIX, VETH0_PREFIX) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tools.fail('%s is not a valid VethFixture veth endpoint' % name) | Create a veth.
:ivar ports: created veth ports
:type ports: IPDevice 2-uplet | 625990672ae34c7f260ac878 |
class Event(object): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._value = False <NEW_LINE> self._waiters = set() <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "<%s %s>" % ( self.__class__.__name__, "set" if self.is_set() else "clear", ) <NEW_LINE> <DEDENT> def is_set(self) -> bool: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def set(self) -> None: <NEW_LINE> <INDENT> if not self._value: <NEW_LINE> <INDENT> self._value = True <NEW_LINE> for fut in self._waiters: <NEW_LINE> <INDENT> if not fut.done(): <NEW_LINE> <INDENT> fut.set_result(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def clear(self) -> None: <NEW_LINE> <INDENT> self._value = False <NEW_LINE> <DEDENT> def wait(self, timeout: Union[float, datetime.timedelta] = None) -> "Future[None]": <NEW_LINE> <INDENT> fut = Future() <NEW_LINE> if self._value: <NEW_LINE> <INDENT> fut.set_result(None) <NEW_LINE> return fut <NEW_LINE> <DEDENT> self._waiters.add(fut) <NEW_LINE> fut.add_done_callback(lambda fut: self._waiters.remove(fut)) <NEW_LINE> if timeout is None: <NEW_LINE> <INDENT> return fut <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> timeout_fut = gen.with_timeout( timeout, fut, quiet_exceptions=(CancelledError,) ) <NEW_LINE> timeout_fut.add_done_callback( lambda tf: fut.cancel() if not fut.done() else None ) <NEW_LINE> return timeout_fut | An event blocks coroutines until its internal flag is set to True.
Similar to `threading.Event`.
A coroutine can wait for an event to be set. Once it is set, calls to
``yield event.wait()`` will not block unless the event has been cleared:
.. testcode::
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Event
event = Event()
async def waiter():
print("Waiting for event")
await event.wait()
print("Not waiting this time")
await event.wait()
print("Done")
async def setter():
print("About to set the event")
event.set()
async def runner():
await gen.multi([waiter(), setter()])
IOLoop.current().run_sync(runner)
.. testoutput::
Waiting for event
About to set the event
Not waiting this time
Done | 625990674a966d76dd5f0684 |
class StubWithFormat(object): <NEW_LINE> <INDENT> _format = object() | A stub object used to check that convenience methods call Inter's. | 62599067379a373c97d9a7af |
class BadRequestError(Error): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super().__init__(message, 400) | To be raised when the client data sent in the
request is in inappropriate format. | 625990679c8ee82313040d50 |
class Post(models.Model): <NEW_LINE> <INDENT> title = models.CharField('タイトル',max_length=255) <NEW_LINE> thumbnail = models.ImageField('サムネ',upload_to='documents/', default='/no_img.jpg') <NEW_LINE> created_at = models.DateTimeField('作成日',default=timezone.now,null=True) <NEW_LINE> tags = models.ManyToManyField(Tag,verbose_name='タグ',blank=True,null=True) <NEW_LINE> detail = models.TextField('詳細文',max_length=255,blank=True,null=True) <NEW_LINE> ref = models.URLField('外部リンク',max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title | ブログの記事 | 62599067fff4ab517ebcefac |
class InlineQueryResultLocation(InlineQueryResult): <NEW_LINE> <INDENT> def __init__( self, id: str, latitude: float, longitude: float, title: str, live_period: int = None, reply_markup: 'ReplyMarkup' = None, input_message_content: 'InputMessageContent' = None, thumb_url: str = None, thumb_width: int = None, thumb_height: int = None, **_kwargs: Any, ): <NEW_LINE> <INDENT> super().__init__('location', id) <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.title = title <NEW_LINE> self.live_period = live_period <NEW_LINE> self.reply_markup = reply_markup <NEW_LINE> self.input_message_content = input_message_content <NEW_LINE> self.thumb_url = thumb_url <NEW_LINE> self.thumb_width = thumb_width <NEW_LINE> self.thumb_height = thumb_height | Represents a location on a map. By default, the location will be sent by the user.
Alternatively, you can use :attr:`input_message_content` to send a message with the specified
content instead of the location.
Attributes:
type (:obj:`str`): 'location'.
id (:obj:`str`): Unique identifier for this result, 1-64 bytes.
latitude (:obj:`float`): Location latitude in degrees.
longitude (:obj:`float`): Location longitude in degrees.
title (:obj:`str`): Location title.
live_period (:obj:`int`): Optional. Period in seconds for which the location can be
updated, should be between 60 and 86400.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the location.
thumb_url (:obj:`str`): Optional. Url of the thumbnail for the result.
thumb_width (:obj:`int`): Optional. Thumbnail width.
thumb_height (:obj:`int`): Optional. Thumbnail height.
Args:
id (:obj:`str`): Unique identifier for this result, 1-64 bytes.
latitude (:obj:`float`): Location latitude in degrees.
longitude (:obj:`float`): Location longitude in degrees.
title (:obj:`str`): Location title.
live_period (:obj:`int`, optional): Period in seconds for which the location can be
updated, should be between 60 and 86400.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the location.
thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments. | 6259906738b623060ffaa41a |
class RestBinarySensor(BinarySensorDevice): <NEW_LINE> <INDENT> def __init__(self, hass, rest, name, value_template): <NEW_LINE> <INDENT> self._hass = hass <NEW_LINE> self.rest = rest <NEW_LINE> self._name = name <NEW_LINE> self._state = False <NEW_LINE> self._value_template = value_template <NEW_LINE> self.update() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> if self.rest.data is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._value_template is not None: <NEW_LINE> <INDENT> self.rest.data = template.render_with_possible_json_value( self._hass, self._value_template, self.rest.data, False) <NEW_LINE> <DEDENT> return bool(int(self.rest.data)) <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.rest.update() | Implements a REST binary sensor. | 62599067796e427e5384ff07 |
class LoggerRsyslog(LoggerSyslog): <NEW_LINE> <INDENT> name = 'rsyslog' <NEW_LINE> plugin = 'rsyslog' <NEW_LINE> def __init__(self, *, app_name=None, host=None, facility=None, split=None, packet_size=None, alias=None): <NEW_LINE> <INDENT> super().__init__(app_name=app_name, facility=facility, alias=alias) <NEW_LINE> self.args.insert(0, host) <NEW_LINE> self._set('rsyslog-packet-size', packet_size) <NEW_LINE> self._set('rsyslog-split-messages', split, cast=bool) | Allows logging into Unix standard syslog or a remote syslog. | 6259906701c39578d7f142fd |
class AbstractQuerier(AQuerier, CommonMonetDB): <NEW_LINE> <INDENT> def __init__(self, configuration): <NEW_LINE> <INDENT> AQuerier.__init__(self, configuration) <NEW_LINE> self.setVariables(configuration) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def prepareQuery(self, cursor, queryId, queriesParameters, addGeom = False): <NEW_LINE> <INDENT> self.queryIndex = int(queryId) <NEW_LINE> self.resultTable = 'query_results_' + str(self.queryIndex) <NEW_LINE> self.qp = queriesParameters.getQueryParameters('mon', queryId) <NEW_LINE> logging.debug(self.qp.queryKey) <NEW_LINE> if addGeom: <NEW_LINE> <INDENT> cursor.execute("INSERT INTO " + utils.QUERY_TABLE + " VALUES (%s,GeomFromText(%s,%s))", [self.queryIndex, self.qp.wkt, self.srid]) <NEW_LINE> cursor.connection.commit() <NEW_LINE> <DEDENT> <DEDENT> def addContainsCondition(self, queryParameters, queryArgs, xname, yname): <NEW_LINE> <INDENT> queryArgs.extend([queryParameters.wkt, self.srid,]) <NEW_LINE> return (None, "contains(GeomFromText(%s,%s)," + xname + "," + yname + ")") | Abstract class for the queriers to be implemented for each different
solution for the benchmark | 625990674f88993c371f10e7 |
class InvalidDHCPLeaseFileError(Exception): <NEW_LINE> <INDENT> pass | Raised when parsing an empty or invalid dhcp.leases file.
Current uses are DataSourceAzure and DataSourceEc2 during ephemeral
boot to scrape metadata. | 6259906799cbb53fe6832675 |
class Builder(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.wrapped = () <NEW_LINE> self.pending = [] <NEW_LINE> self.intervals = [] <NEW_LINE> <DEDENT> def insert(self, value): <NEW_LINE> <INDENT> _validate_integer_in_range('value', value) <NEW_LINE> self.pending.append(value) <NEW_LINE> <DEDENT> def insert_interval(self, start, end): <NEW_LINE> <INDENT> if start >= end: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.intervals.append([start, end]) <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> self.pending.sort() <NEW_LINE> still_pending = [] <NEW_LINE> i = 0 <NEW_LINE> while i < len(self.pending): <NEW_LINE> <INDENT> j = i <NEW_LINE> while j + 1 < len(self.pending): <NEW_LINE> <INDENT> if self.pending[j + 1] == self.pending[j] + 1: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if i < j: <NEW_LINE> <INDENT> self.intervals.append([ self.pending[i], self.pending[j] + 1 ]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> still_pending.append(self.pending[i]) <NEW_LINE> <DEDENT> i = j + 1 <NEW_LINE> <DEDENT> self.pending = [] <NEW_LINE> if still_pending: <NEW_LINE> <INDENT> self.wrapped = _union( self.wrapped, _from_sorted_list(still_pending, 0, len(still_pending)) ) <NEW_LINE> <DEDENT> if self.intervals: <NEW_LINE> <INDENT> intervals = _normalize_intervals(self.intervals) <NEW_LINE> self.intervals = [] <NEW_LINE> self.wrapped = _union( self.wrapped, _from_intervals(intervals)) <NEW_LINE> <DEDENT> return IntSet._wrap(self.wrapped) | An IntSet.Builder is for building up an IntSet incrementally through
a series of insertions.
This will typically be much faster than repeatedly calling
insert on an IntSet object. The intended usage is to repeatedly
call insert() or insert_interval() on a builder, then call
build() at the end. Note that you can continue to insert further
data into a Builder afterwards if you wish, and this will not
affect previously built IntSet instances. | 625990671f037a2d8b9e5433 |
class MuProcedure(UserDefinedProcedure): <NEW_LINE> <INDENT> def __init__(self, formals, body): <NEW_LINE> <INDENT> self.formals = formals <NEW_LINE> self.body = body <NEW_LINE> <DEDENT> "*** REPLACE THIS LINE ***" <NEW_LINE> def make_call_frame(self, args, env): <NEW_LINE> <INDENT> while args is not nil: <NEW_LINE> <INDENT> env.define(self.formals.first,args.first) <NEW_LINE> self.formals,args=self.formals.second,args.second <NEW_LINE> <DEDENT> return env <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(Pair('mu', Pair(self.formals, self.body))) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'MuProcedure({0}, {1})'.format( repr(self.formals), repr(self.body)) | A procedure defined by a mu expression, which has dynamic scope.
_________________
< Scheme is cool! >
-----------------
\ ^__^
\ (oo)\_______
(__)\ )\/ ||----w |
|| ||
─▄▀▀▀▀▄─█──█────▄▀▀█─▄▀▀▀▀▄─█▀▀▄
─█────█─█──█────█────█────█─█──█
─█────█─█▀▀█────█─▄▄─█────█─█──█
─▀▄▄▄▄▀─█──█────▀▄▄█─▀▄▄▄▄▀─█▄▄▀
─────────▄██████▀▀▀▀▀▀▄
─────▄█████████▄───────▀▀▄▄
──▄█████████████───────────▀▀▄
▄██████████████─▄▀───▀▄─▀▄▄▄──▀▄
███████████████──▄▀─▀▄▄▄▄▄▄────█
█████████████████▀█──▄█▄▄▄──────█
███████████──█▀█──▀▄─█─█─█───────█
████████████████───▀█─▀██▄▄──────█
█████████████████──▄─▀█▄─────▄───█
█████████████████▀███▀▀─▀▄────█──█
████████████████──────────█──▄▀──█
████████████████▄▀▀▀▀▀▀▄──█──────█
████████████████▀▀▀▀▀▀▀▄──█──────█
▀████████████████▀▀▀▀▀▀──────────█
──███████████████▀▀─────█──────▄▀
──▀█████████████────────█────▄▀
────▀████████████▄───▄▄█▀─▄█▀
──────▀████████████▀▀▀──▄███
──────████████████████████─█
─────████████████████████──█
────████████████████████───█
────██████████████████─────█
────██████████████████─────█
────██████████████████─────█
────██████████████████─────█
────██████████████████▄▄▄▄▄█
─────────────█─────█─█──█─█───█
─────────────█─────█─█──█─▀█─█▀
─────────────█─▄█▄─█─█▀▀█──▀█▀
─────────────██▀─▀██─█──█───█
| 625990674428ac0f6e659cc2 |
class TaskInfoNew(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TaskId = None <NEW_LINE> self.TaskType = None <NEW_LINE> self.TransId = None <NEW_LINE> self.ClusterId = None <NEW_LINE> self.ClusterName = None <NEW_LINE> self.Progress = None <NEW_LINE> self.StartTime = None <NEW_LINE> self.UpdateTime = None <NEW_LINE> self.Operator = None <NEW_LINE> self.Content = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TaskId = params.get("TaskId") <NEW_LINE> self.TaskType = params.get("TaskType") <NEW_LINE> self.TransId = params.get("TransId") <NEW_LINE> self.ClusterId = params.get("ClusterId") <NEW_LINE> self.ClusterName = params.get("ClusterName") <NEW_LINE> self.Progress = params.get("Progress") <NEW_LINE> self.StartTime = params.get("StartTime") <NEW_LINE> self.UpdateTime = params.get("UpdateTime") <NEW_LINE> self.Operator = params.get("Operator") <NEW_LINE> self.Content = params.get("Content") | 任务信息详情
| 625990675fdd1c0f98e5f715 |
class CategoryViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = CategorySerializer <NEW_LINE> permission_classes = (IsAdminOrReadOnly,) <NEW_LINE> queryset = Category.objects.all() <NEW_LINE> filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] <NEW_LINE> ordering_fields = ['name'] <NEW_LINE> search_fields = ['name'] <NEW_LINE> filterset_class = CategoryFilter <NEW_LINE> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.queryset = Category.objects.active().order_by('name') <NEW_LINE> return super().list(request, *args, **kwargs) | Handle creating, updating, deleting categories, admin only | 625990673317a56b869bf10b |
class _Manifest(object): <NEW_LINE> <INDENT> def __init__(self, sha_names): <NEW_LINE> <INDENT> self.sha_names = sorted(sha_names, key=lambda t: t[1]) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, _Manifest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.sha_names == other.sha_names <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> for sha, name in self.sha_names: <NEW_LINE> <INDENT> if name == key: <NEW_LINE> <INDENT> return sha <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("no item with name '%s'" % key) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> for idx, sha_name in enumerate(self.sha_names): <NEW_LINE> <INDENT> sha, name = sha_name <NEW_LINE> if name == key: <NEW_LINE> <INDENT> self.sha_names[idx] = (value, name) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> raise KeyError("no item with name '%s'" % key) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> tmpl = " ('%s',\n '%s')," <NEW_LINE> lines = [tmpl % (sha, name) for sha, name in self.sha_names] <NEW_LINE> return 'manifest = [\n%s\n]' % '\n'.join(lines) <NEW_LINE> <DEDENT> def diff(self, other, filename_1, filename_2): <NEW_LINE> <INDENT> text_1, text_2 = str(self), str(other) <NEW_LINE> lines_1 = text_1.split('\n') <NEW_LINE> lines_2 = text_2.split('\n') <NEW_LINE> diff = unified_diff(lines_1, lines_2, filename_1, filename_2) <NEW_LINE> return '\n'.join([line for line in diff]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_dir(dirpath): <NEW_LINE> <INDENT> sha_names = [] <NEW_LINE> for filepath in sorted(_Manifest._filepaths_in_dir(dirpath)): <NEW_LINE> <INDENT> with open(filepath, 'rb') as f: <NEW_LINE> <INDENT> blob = f.read() <NEW_LINE> <DEDENT> sha = hashlib.sha1(blob).hexdigest() <NEW_LINE> name = os.path.relpath(filepath, dirpath).replace('\\', '/') <NEW_LINE> sha_names.append((sha, name)) <NEW_LINE> <DEDENT> return _Manifest(sha_names) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_zip(zip_file_path): <NEW_LINE> <INDENT> zipf = ZipFile(zip_file_path) <NEW_LINE> sha_names = [] <NEW_LINE> for name in sorted(zipf.namelist()): <NEW_LINE> <INDENT> blob = zipf.read(name) <NEW_LINE> sha = hashlib.sha1(blob).hexdigest() <NEW_LINE> sha_names.append((sha, name)) <NEW_LINE> <DEDENT> zipf.close() <NEW_LINE> return _Manifest(sha_names) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _filepaths_in_dir(dirpath): <NEW_LINE> <INDENT> filepaths = [] <NEW_LINE> for root, dirnames, filenames in os.walk(dirpath): <NEW_LINE> <INDENT> for filename in filenames: <NEW_LINE> <INDENT> filepath = os.path.join(root, filename) <NEW_LINE> filepaths.append(filepath) <NEW_LINE> <DEDENT> <DEDENT> return sorted(filepaths) | A sorted sequence of SHA1, name 2-tuples that unambiguously characterize
the contents of an OPC package, providing a basis for asserting
equivalence of two packages, whether stored as a zip archive or a package
extracted into a directory. | 6259906745492302aabfdc6e |
class EditUserResource(PictureVideoUploadResource, AuthUserResource): <NEW_LINE> <INDENT> class Meta(BaseUserResource.Meta): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> allowed_methods = ['patch'] <NEW_LINE> authorization = UserAuthorization() <NEW_LINE> authentication = ExpireApiKeyAuthentication() <NEW_LINE> resource_name = "edit_user" <NEW_LINE> always_return_data = True <NEW_LINE> object_name = "user" <NEW_LINE> <DEDENT> def hydrate(self, bundle): <NEW_LINE> <INDENT> user = bundle.obj <NEW_LINE> if User.USERNAME_FIELD in bundle.data and bundle.data[User.USERNAME_FIELD] != getattr(user, User.USERNAME_FIELD) and len(bundle.data[User.USERNAME_FIELD]) > 0: <NEW_LINE> <INDENT> username_field = bundle.data[User.USERNAME_FIELD].replace(' ', '') <NEW_LINE> username_field_filter = {"{0}__iexact".format(User.USERNAME_FIELD): username_field} <NEW_LINE> if User.objects.filter(**username_field_filter): <NEW_LINE> <INDENT> raise BadRequest("That {0} has already been used".format(User.USERNAME_FIELD)) <NEW_LINE> <DEDENT> <DEDENT> if 'email' in bundle.data and bundle.data['email'] != user.email and len(bundle.data['email']) > 0: <NEW_LINE> <INDENT> if User.objects.filter(email=bundle.data['email']): <NEW_LINE> <INDENT> raise BadRequest("That email has already been used") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_email(bundle.data['email']) <NEW_LINE> <DEDENT> except ValidationError: <NEW_LINE> <INDENT> raise BadRequest("Email address is not formatted properly") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return bundle <NEW_LINE> <DEDENT> def dispatch(self, request_type, request, **kwargs): <NEW_LINE> <INDENT> return super(EditUserResource, self).dispatch('detail', request, **kwargs) <NEW_LINE> <DEDENT> def patch_detail(self, request, **kwargs): <NEW_LINE> <INDENT> kwargs['id'] = request.user.pk <NEW_LINE> return super(EditUserResource, self).patch_detail(request, **kwargs) <NEW_LINE> <DEDENT> def get_detail(self, request, **kwargs): <NEW_LINE> <INDENT> kwargs['id'] = request.user.pk <NEW_LINE> return super(EditUserResource, self).get_detail(request, **kwargs) | Allows the UserModel's USERNAME_FIELD and email to be changed | 62599067d6c5a102081e38b8 |
class ErrorFlags(Flag): <NEW_LINE> <INDENT> NONE = 0b0 <NEW_LINE> CAL_RAM_CHECKSUM = 0b1 <NEW_LINE> RAM_FAILURE = 0b10 <NEW_LINE> ROM_FAILURE = 0b100 <NEW_LINE> AD_SLOPE_CONVERGENCE = 0b1000 <NEW_LINE> AD_SELFTEST_FAILURE = 0b10000 <NEW_LINE> AD_LINK_FAILURE = 0b100000 | The error register flags. See page 62 of the manual for details. | 62599067a17c0f6771d5d770 |
class LogisticRegressionModel(LinearModel): <NEW_LINE> <INDENT> def predict(self, x): <NEW_LINE> <INDENT> _linear_predictor_typecheck(x, self._coeff) <NEW_LINE> margin = dot(x, self._coeff) + self._intercept <NEW_LINE> prob = 1/(1 + exp(-margin)) <NEW_LINE> return 1 if prob > 0.5 else 0 | A linear binary classification model derived from logistic regression.
>>> data = array([0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 1.0, 3.0]).reshape(4,2)
>>> lrm = LogisticRegressionWithSGD.train(sc, sc.parallelize(data))
>>> lrm.predict(array([1.0])) != None
True | 62599067cc0a2c111447c699 |
class GroupProcessingLayer(ProcessingLayer): <NEW_LINE> <INDENT> def __init__(self, group_size=4, **kwargs): <NEW_LINE> <INDENT> super(GroupProcessingLayer, self).__init__(**kwargs) <NEW_LINE> self.group_size = group_size <NEW_LINE> self.output_shape = None <NEW_LINE> self.num_group = None <NEW_LINE> self.shape_rank = None <NEW_LINE> <DEDENT> def _pre_forward(self, input): <NEW_LINE> <INDENT> super(GroupProcessingLayer, self)._pre_forward(input) <NEW_LINE> if type(input) is list: <NEW_LINE> <INDENT> last_dim = 0 <NEW_LINE> for t in input: <NEW_LINE> <INDENT> shape = t.get_shape().as_list() <NEW_LINE> last_dim += shape[-1] <NEW_LINE> <DEDENT> self.output_shape = input[0].get_shape().as_list() <NEW_LINE> self.output_shape[-1] = last_dim <NEW_LINE> self.rank = len(self.output_shape) <NEW_LINE> self.num_group = len(input) <NEW_LINE> self.log("Number of groups: {}".format(self.num_group)) <NEW_LINE> group_size_list = [t.get_shape().as_list()[-1] for t in input] <NEW_LINE> self.log("Group size of each group are {}".format(group_size_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output_shape = input.get_shape().as_list() <NEW_LINE> self.rank = len(self.output_shape) <NEW_LINE> if self.output_shape[-1] % self.group_size is not 0: <NEW_LINE> <INDENT> raise Exception("Group size {} should evenly divide output channel" " number {}".format(self.group_size, self.output_shape[-1])) <NEW_LINE> <DEDENT> out_channel_num = self.output_shape[-1] <NEW_LINE> self.num_group = out_channel_num // self.group_size <NEW_LINE> self.log("Feature maps of layer {} is divided into {} group".format( self.name, self.num_group)) <NEW_LINE> self.log("All groups have equal size {}.".format(self.group_size)) | A abstract layer that processes layer by group. This is a meta class
(`_forward` is not implemented).
Two modes are possible for this layer. The first is to divide the
neurons of this layer evenly using `group_size`. The second mode the
input should be a list of tensors. In this case, `group_size` is
ignored, and each tensor in the list is taken as a group. In both case,
only the last dimension of the tensor indexes group member, the other
dimensions index groups. | 62599067a8370b77170f1b5a |
class SequenceMatcher(difflib.SequenceMatcher, object): <NEW_LINE> <INDENT> def find_longest_match(self, alo, ahi, blo, bhi): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> for n, (el, line) in enumerate(zip(self.a[alo:ahi], self.b[blo:bhi])): <NEW_LINE> <INDENT> if el != line and match(el, line): <NEW_LINE> <INDENT> self.a[alo + n] = line <NEW_LINE> matches.append((n, el)) <NEW_LINE> <DEDENT> <DEDENT> ret = super(SequenceMatcher, self).find_longest_match(alo, ahi, blo, bhi) <NEW_LINE> for n, el in matches: <NEW_LINE> <INDENT> self.a[alo + n] = el <NEW_LINE> <DEDENT> return ret | Like difflib.SequenceMatcher, but matches globs and regexes. | 62599067e76e3b2f99fda193 |
class IdxWORD19F(db.Model): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __tablename__ = 'idxWORD19F' <NEW_LINE> id = db.Column(db.MediumInteger(9, unsigned=True), primary_key=True, autoincrement=True) <NEW_LINE> term = db.Column(db.String(50), nullable=True, unique=True) <NEW_LINE> hitlist = db.Column(db.iLargeBinary, nullable=True) | Represents a IdxWORD19F record. | 62599067009cb60464d02ccb |
class DeletePost(DeleteView): <NEW_LINE> <INDENT> context_object_name = "get_place" <NEW_LINE> def get_success_url(self): <NEW_LINE> <INDENT> space = self.kwargs['space_url'] <NEW_LINE> return '/spaces/%s' % (space) <NEW_LINE> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> return get_object_or_404(Post, pk=self.kwargs['post_id']) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(DeletePost, self).get_context_data(**kwargs) <NEW_LINE> context['get_place'] = get_object_or_404(Space, url=self.kwargs['space_url']) <NEW_LINE> return context | Delete an existent post. Post deletion is only reserved to spaces
administrators or site admins. | 6259906776e4537e8c3f0d15 |
class ResearchExperimentReplicateCreateAPIView(CreateAPIView): <NEW_LINE> <INDENT> queryset = ResearchExperimentReplicate.objects.all() <NEW_LINE> permission_classes = [IsAuthenticated] <NEW_LINE> def get_serializer_class(self): <NEW_LINE> <INDENT> model_type, url_parameter, user = get_http_request(self.request, slug=False) <NEW_LINE> create_research_experiment_replicate_serializer = research_experiment_replicate_serializers[ 'create_research_experiment_replicate_serializer' ] <NEW_LINE> return create_research_experiment_replicate_serializer(model_type, url_parameter, user) | Creates a single record. | 6259906732920d7e50bc77d9 |
class CutoffLocationSobekModelSettingF(factory.Factory): <NEW_LINE> <INDENT> FACTORY_FOR = models.CutoffLocationSobekModelSetting <NEW_LINE> cutofflocation = factory.LazyAttribute( lambda obj: CutoffLocationF.create()) <NEW_LINE> sobekmodel = factory.LazyAttribute( lambda obj: SobekModelF.create()) <NEW_LINE> sobekid = "some sobekid" | Factory for CutoffLocationSobekModelSetting. | 62599067379a373c97d9a7b1 |
class Polyhedron_RDF(Polyhedron_base): <NEW_LINE> <INDENT> def _is_zero(self, x): <NEW_LINE> <INDENT> return abs(x)<=1e-6 <NEW_LINE> <DEDENT> def _is_nonneg(self, x): <NEW_LINE> <INDENT> return x>=-1e-6 <NEW_LINE> <DEDENT> def _is_positive(self, x): <NEW_LINE> <INDENT> return x>=-1e-6 <NEW_LINE> <DEDENT> _base_ring = RDF | Base class for polyhedra over ``RDF``.
TESTS::
sage: p = Polyhedron([(0,0)], base_ring=RDF); p
A 0-dimensional polyhedron in RDF^2 defined as the convex hull of 1 vertex
sage: TestSuite(p).run() | 6259906797e22403b383c6a0 |
class ModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): <NEW_LINE> <INDENT> pass | Adaptation of DRF ModelViewSet | 62599067097d151d1a2c27ff |
class CloudMonitorNotificationPlanManager(BaseManager): <NEW_LINE> <INDENT> def create(self, label=None, name=None, critical_state=None, ok_state=None, warning_state=None): <NEW_LINE> <INDENT> uri = "/%s" % self.uri_base <NEW_LINE> body = {"label": label or name} <NEW_LINE> def make_list_of_ids(parameter): <NEW_LINE> <INDENT> params = utils.coerce_string_to_list(parameter) <NEW_LINE> return [utils.get_id(param) for param in params] <NEW_LINE> <DEDENT> if critical_state: <NEW_LINE> <INDENT> critical_state = utils.coerce_string_to_list(critical_state) <NEW_LINE> body["critical_state"] = make_list_of_ids(critical_state) <NEW_LINE> <DEDENT> if warning_state: <NEW_LINE> <INDENT> warning_state = utils.coerce_string_to_list(warning_state) <NEW_LINE> body["warning_state"] = make_list_of_ids(warning_state) <NEW_LINE> <DEDENT> if ok_state: <NEW_LINE> <INDENT> ok_state = utils.coerce_string_to_list(ok_state) <NEW_LINE> body["ok_state"] = make_list_of_ids(ok_state) <NEW_LINE> <DEDENT> resp, resp_body = self.api.method_post(uri, body=body) <NEW_LINE> return self.get(resp["x-object-id"]) | Handles all of the requests dealing with Notification Plans. | 625990675fdd1c0f98e5f717 |
class Conv1dGLU(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, kernel_size, style_embedding, speaker_embedding, dropout, style_embed_dim=None, speaker_embed_dim=None, padding=None, dilation=1, causal=False, residual=False, *args, **kwargs): <NEW_LINE> <INDENT> super(Conv1dGLU, self).__init__() <NEW_LINE> self.dropout = dropout <NEW_LINE> self.residual = residual <NEW_LINE> if padding is None: <NEW_LINE> <INDENT> if causal: <NEW_LINE> <INDENT> padding = (kernel_size - 1) * dilation <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> padding = (kernel_size - 1) // 2 * dilation <NEW_LINE> <DEDENT> <DEDENT> self.causal = causal <NEW_LINE> self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size, dropout=dropout, padding=padding, dilation=dilation, *args, **kwargs) <NEW_LINE> if style_embedding: <NEW_LINE> <INDENT> self.style_proj = Linear(style_embed_dim, out_channels) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.style_proj = None <NEW_LINE> <DEDENT> if speaker_embedding: <NEW_LINE> <INDENT> self.speaker_proj = Linear(speaker_embed_dim, out_channels) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.speaker_proj = None <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x, style_embed=None, speaker_embed=None): <NEW_LINE> <INDENT> return self._forward(x, style_embed, speaker_embed, False) <NEW_LINE> <DEDENT> def incremental_forward(self, x, style_embed=None, speaker_embed=None): <NEW_LINE> <INDENT> return self._forward(x, style_embed, speaker_embed, True) <NEW_LINE> <DEDENT> def _forward(self, x, style_embed, speaker_embed, is_incremental): <NEW_LINE> <INDENT> residual = x <NEW_LINE> x = F.dropout(x, p=self.dropout, training=self.training) <NEW_LINE> if is_incremental: <NEW_LINE> <INDENT> splitdim = -1 <NEW_LINE> x = self.conv.incremental_forward(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> splitdim = 1 <NEW_LINE> x = self.conv(x) <NEW_LINE> x = x[:, :, :residual.size(-1)] if self.causal else x <NEW_LINE> <DEDENT> a, b = x.split(x.size(splitdim) // 2, dim=splitdim) <NEW_LINE> if self.style_proj is not None: <NEW_LINE> <INDENT> softsign = F.softsign(self.style_proj(style_embed)) <NEW_LINE> softsign = softsign if is_incremental else softsign.transpose(1, 2) <NEW_LINE> a = a + softsign <NEW_LINE> <DEDENT> if self.speaker_proj is not None: <NEW_LINE> <INDENT> softsign = F.softsign(self.speaker_proj(speaker_embed)) <NEW_LINE> softsign = softsign if is_incremental else softsign.transpose(1, 2) <NEW_LINE> a = a + softsign <NEW_LINE> <DEDENT> x = a * F.sigmoid(b) <NEW_LINE> return (x + residual) * math.sqrt(0.5) if self.residual else x <NEW_LINE> <DEDENT> def clear_buffer(self): <NEW_LINE> <INDENT> self.conv.clear_buffer() | (Dilated) Conv1d + Gated linear unit + (optionally) speaker embedding
| 625990677d847024c075db6c |
class TR(AttrElem): <NEW_LINE> <INDENT> _accepting = True <NEW_LINE> def __init__(self, attrs, bgcolor=None, honor_colors=False, valign=DEFAULT_VALIGN): <NEW_LINE> <INDENT> AttrElem.__init__(self, attrs) <NEW_LINE> self.Ahalign = self.attribute('align', conv=conv_halign) <NEW_LINE> self.Avalign = self.attribute('valign', conv=conv_valign, default=valign) <NEW_LINE> if honor_colors: <NEW_LINE> <INDENT> self.Abgcolor = self.attribute('bgcolor', conv=conv_color, default=bgcolor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Abgcolor = bgcolor <NEW_LINE> <DEDENT> self.cells = [] <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._accepting = False <NEW_LINE> <DEDENT> def is_accepting(self): <NEW_LINE> <INDENT> return self._accepting | A TR table row element. | 625990674f6381625f19a06f |
class ExceptionTestResultMixin(object): <NEW_LINE> <INDENT> pdb_type = 'pdb' <NEW_LINE> def get_pdb(self): <NEW_LINE> <INDENT> if self.pdb_type == 'ipdb' and has_ipdb(): <NEW_LINE> <INDENT> import ipdb <NEW_LINE> return ipdb <NEW_LINE> <DEDENT> return pdb <NEW_LINE> <DEDENT> def addError(self, test, err): <NEW_LINE> <INDENT> super(ExceptionTestResultMixin, self).addError(test, err) <NEW_LINE> exctype, value, tb = err <NEW_LINE> self.stream.writeln() <NEW_LINE> self.stream.writeln(self.separator1) <NEW_LINE> self.stream.writeln(">>> %s" % (self.getDescription(test))) <NEW_LINE> self.stream.writeln(self.separator2) <NEW_LINE> self.stream.writeln(self._exc_info_to_string(err, test).rstrip()) <NEW_LINE> self.stream.writeln(self.separator1) <NEW_LINE> self.stream.writeln() <NEW_LINE> self.get_pdb().post_mortem(tb) <NEW_LINE> <DEDENT> def addFailure(self, test, err): <NEW_LINE> <INDENT> super(ExceptionTestResultMixin, self).addFailure(test, err) <NEW_LINE> exctype, value, tb = err <NEW_LINE> self.stream.writeln() <NEW_LINE> self.stream.writeln(self.separator1) <NEW_LINE> self.stream.writeln(">>> %s" % (self.getDescription(test))) <NEW_LINE> self.stream.writeln(self.separator2) <NEW_LINE> self.stream.writeln(self._exc_info_to_string(err, test).rstrip()) <NEW_LINE> self.stream.writeln(self.separator1) <NEW_LINE> self.stream.writeln() <NEW_LINE> self.get_pdb().post_mortem(tb) | A mixin class that can be added to any test result class.
Drops into pdb on test errors/failures. | 625990678a43f66fc4bf3925 |
class DhcpConfig: <NEW_LINE> <INDENT> def __init__(self, mac, ip_address, gateway=None, networkmask=None): <NEW_LINE> <INDENT> self.additional_statements = {} <NEW_LINE> self.mac = None <NEW_LINE> self.ip_address = None <NEW_LINE> self.gateway = None <NEW_LINE> self.networkmask = None <NEW_LINE> self.dhcp_hostname = None <NEW_LINE> self.set_settings(True, mac, ip_address, gateway, networkmask) <NEW_LINE> <DEDENT> def set_settings( self, allow_none_value_for_not_required_parameter=False, mac=None, ip_address=None, gateway=None, networkmask=None): <NEW_LINE> <INDENT> self.mac = mac <NEW_LINE> if gateway is not None or allow_none_value_for_not_required_parameter: <NEW_LINE> <INDENT> self.gateway = gateway <NEW_LINE> <DEDENT> if networkmask is not None or allow_none_value_for_not_required_parameter: <NEW_LINE> <INDENT> self.networkmask = networkmask <NEW_LINE> <DEDENT> if validation.is_cidr(ip_address): <NEW_LINE> <INDENT> self.ip_address = validation.get_ip_from_cidr(ip_address) <NEW_LINE> if self.networkmask is None: <NEW_LINE> <INDENT> self.networkmask = validation.get_nm_from_cidr(ip_address) <NEW_LINE> <DEDENT> if self.gateway is None and config[ 'DHCPConfig'].getboolean('force_gateway'): <NEW_LINE> <INDENT> self.gateway = validation.get_gw_from_cidr(ip_address) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ip_address = ip_address <NEW_LINE> <DEDENT> self.dhcp_hostname = config['Common'].get('FQDN') <NEW_LINE> <DEDENT> def add_additional_statement(self, key, value): <NEW_LINE> <INDENT> self.additional_statements[key] = value <NEW_LINE> <DEDENT> def create_isc_ldap(self): <NEW_LINE> <INDENT> isc_dhcp_config = ISCDhcpLdapConfig(self) <NEW_LINE> isc_dhcp_config.save() <NEW_LINE> <DEDENT> def remove_by_ipv4(self): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.remove_by_ipv4(self.ip_address) > 0 <NEW_LINE> <DEDENT> def remove_by_mac(self): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.remove_by_mac(self.mac) > 0 <NEW_LINE> <DEDENT> def remove_all(self): <NEW_LINE> <INDENT> ipv4_removed_count = ISCDhcpLdapConfig.remove_by_ipv4(self.ip_address) <NEW_LINE> mac_removed_count = ISCDhcpLdapConfig.remove_by_mac(self.mac) <NEW_LINE> return (ipv4_removed_count + mac_removed_count) > 0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def all(): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.get_all_db_entries() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_ip(ip_address): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.get_by_ip(ip_address) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_mac(mac): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.get_by_mac(mac) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exists_ipv4(ip_address): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.get_by_ip(ip_address) is not None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exists_mac(mac_address): <NEW_LINE> <INDENT> return ISCDhcpLdapConfig.get_by_mac(mac_address) is not None | Model for a DHCP object. | 62599067cc0a2c111447c69a |
class SpikingNeuralNetwork(NeuralNetwork): <NEW_LINE> <INDENT> pass | Slightly more specific, will have weight initializers as well as the opportunity for additional parameters. | 625990676e29344779b01de6 |
class Metric(_MLflowObject): <NEW_LINE> <INDENT> def __init__(self, key, value, timestamp): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> self._value = value <NEW_LINE> self._timestamp = timestamp <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self): <NEW_LINE> <INDENT> return self._key <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def timestamp(self): <NEW_LINE> <INDENT> return self._timestamp <NEW_LINE> <DEDENT> def to_proto(self): <NEW_LINE> <INDENT> metric = ProtoMetric() <NEW_LINE> metric.key = self.key <NEW_LINE> metric.value = self.value <NEW_LINE> metric.timestamp = self.timestamp <NEW_LINE> return metric <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_proto(cls, proto): <NEW_LINE> <INDENT> return cls(proto.key, proto.value, proto.timestamp) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _properties(cls): <NEW_LINE> <INDENT> return ["key", "value", "timestamp"] | Metric object. | 625990674527f215b58eb56c |
class ModelLogSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> action_verbose = serializers.CharField(source='get_action_flag_display', read_only=True) <NEW_LINE> content = serializers.SerializerMethodField() <NEW_LINE> def get_content(self, obj): <NEW_LINE> <INDENT> return obj.get_content() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = ModelLog <NEW_LINE> fields = ( 'id', 'user', 'action', 'action_verbose', 'package', 'model', 'object_id', 'address', 'time_added', 'content' ) | 模块日志 序列化模型 | 625990672ae34c7f260ac87c |
class HttpException(Exception): <NEW_LINE> <INDENT> def __init__(self, url, status_code): <NEW_LINE> <INDENT> self.message = f'Received status code {status_code} from \'{url}\'.' <NEW_LINE> self.url = url <NEW_LINE> self.status_code = status_code <NEW_LINE> super().__init__(self.message, self.url, self.status_code) | Raised when a HTTP request returns an
unsuccessful (i.e. not 200 OK) status code. | 6259906767a9b606de54766c |
class TestLoad(unittest.TestCase): <NEW_LINE> <INDENT> def test_http(self): <NEW_LINE> <INDENT> def example(request): <NEW_LINE> <INDENT> body = 'example' <NEW_LINE> return (200, {'Content-type': 'text/plain', 'Content-length': len(body) }, body) <NEW_LINE> <DEDENT> host = '127.0.0.1' <NEW_LINE> httpd = mozhttpd.MozHttpd(host=host, port=8888, urlhandlers=[{'method': 'GET', 'path': '.*', 'function': example}]) <NEW_LINE> try: <NEW_LINE> <INDENT> httpd.start(block=False) <NEW_LINE> content = load('http://127.0.0.1:8888/foo').read() <NEW_LINE> self.assertEqual(content, 'example') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> httpd.stop() <NEW_LINE> <DEDENT> <DEDENT> def test_file_path(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tmp = tempfile.NamedTemporaryFile(delete=False) <NEW_LINE> tmp.write('foo bar') <NEW_LINE> tmp.close() <NEW_LINE> contents = file(tmp.name).read() <NEW_LINE> self.assertEqual(contents, 'foo bar') <NEW_LINE> self.assertEqual(load(tmp.name).read(), contents) <NEW_LINE> self.assertEqual(load('file://%s' % tmp.name).read(), contents) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if os.path.exists(tmp.name): <NEW_LINE> <INDENT> os.remove(tmp.name) | test the load function | 6259906799cbb53fe6832679 |
class DriveSystem(object): <NEW_LINE> <INDENT> def __init__(self, left_wheel_port=ev3.OUTPUT_B, right_wheel_port=ev3.OUTPUT_C): <NEW_LINE> <INDENT> self.left_wheel = low_level_rb.Wheel(left_wheel_port) <NEW_LINE> self.right_wheel = low_level_rb.Wheel(right_wheel_port) <NEW_LINE> <DEDENT> def start_moving(self, left_wheel_duty_cycle_percent=100, right_wheel_duty_cycle_percent=100): <NEW_LINE> <INDENT> self.left_wheel.start_spinning(left_wheel_duty_cycle_percent) <NEW_LINE> self.right_wheel.start_spinning(right_wheel_duty_cycle_percent) <NEW_LINE> <DEDENT> def stop_moving(self, stop_action=StopAction.BRAKE.value): <NEW_LINE> <INDENT> self.left_wheel.stop_spinning() <NEW_LINE> self.right_wheel.stop_spinning() <NEW_LINE> <DEDENT> def move_for_seconds(self, seconds, left_wheel_duty_cycle_percent=100, right_wheel_duty_cycle_percent=100, stop_action=StopAction.BRAKE): <NEW_LINE> <INDENT> self.start_moving(left_wheel_duty_cycle_percent, right_wheel_duty_cycle_percent) <NEW_LINE> self.start_moving(left_wheel_duty_cycle_percent, right_wheel_duty_cycle_percent) <NEW_LINE> start_time = time.time() <NEW_LINE> while True: <NEW_LINE> <INDENT> if time.time() - start_time > seconds: <NEW_LINE> <INDENT> self.stop_moving(stop_action.value) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def go_straight_inches(self, inches, duty_cycle_percent=100, stop_action=StopAction.BRAKE): <NEW_LINE> <INDENT> self.start_moving(duty_cycle_percent, duty_cycle_percent) <NEW_LINE> while True: <NEW_LINE> <INDENT> if math.fabs(self.right_wheel.get_degrees_spun()) >= 85 * inches: <NEW_LINE> <INDENT> self.stop_moving() <NEW_LINE> self.right_wheel.reset_degrees_spun() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def spin_in_place_degrees(self, degrees, duty_cycle_percent=100, stop_action=StopAction.BRAKE): <NEW_LINE> <INDENT> self.start_moving(duty_cycle_percent, -duty_cycle_percent) <NEW_LINE> while True: <NEW_LINE> <INDENT> if math.fabs(self.right_wheel.get_degrees_spun()) >= 396 * degrees / 90: <NEW_LINE> <INDENT> self.stop_moving() <NEW_LINE> self.right_wheel.reset_degrees_spun() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def turn_degrees(self, degrees, duty_cycle_percent=100, stop_action=StopAction.BRAKE): <NEW_LINE> <INDENT> self.start_moving(duty_cycle_percent, 0) <NEW_LINE> while True: <NEW_LINE> <INDENT> if math.fabs(self.left_wheel.get_degrees_spun()) >= 940 * degrees / 90: <NEW_LINE> <INDENT> self.stop_moving() <NEW_LINE> self.left_wheel.reset_degrees_spun() <NEW_LINE> break | A class for driving (moving) the robot.
Primary authors: The ev3dev authors, David Mutchler, Dave Fisher,
their colleagues, the entire team, and Nathaniel Blanco. | 6259906791f36d47f2231a59 |
class EventDispatcher(object): <NEW_LINE> <INDENT> __handle = None <NEW_LINE> def __init__(self, numDispatcherThreads=1): <NEW_LINE> <INDENT> self.__handle = internals.blpapi_EventDispatcher_create( numDispatcherThreads) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.destroy() <NEW_LINE> <DEDENT> except (NameError, AttributeError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> if self.__handle: <NEW_LINE> <INDENT> internals.blpapi_EventDispatcher_destroy(self.__handle) <NEW_LINE> self.__handle = None <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> return internals.blpapi_EventDispatcher_start(self.__handle) <NEW_LINE> <DEDENT> def stop(self, async_=False, **kwargs): <NEW_LINE> <INDENT> if 'async' in kwargs: <NEW_LINE> <INDENT> warnings.warn( "async parameter has been deprecated in favor of async_", DeprecationWarning) <NEW_LINE> async_ = kwargs.pop('async') <NEW_LINE> <DEDENT> if kwargs: <NEW_LINE> <INDENT> raise TypeError("EventDispatcher.stop() got an unexpected keyword " "argument. Only 'async' is allowed for backwards " "compatibility.") <NEW_LINE> <DEDENT> return internals.blpapi_EventDispatcher_stop(self.__handle, async_) <NEW_LINE> <DEDENT> def _handle(self): <NEW_LINE> <INDENT> return self.__handle | Dispatches events from one or more Sessions through callbacks
EventDispatcher objects are optionally specified when Session objects are
created. A single EventDispatcher can be shared by multiple Session
objects.
The EventDispatcher provides an event-driven interface, generating
callbacks from one or more internal threads for one or more sessions. | 625990675fdd1c0f98e5f719 |
class SuggestionActionHandler(base.BaseHandler): <NEW_LINE> <INDENT> _ACCEPT_ACTION = 'accept' <NEW_LINE> _REJECT_ACTION = 'reject' <NEW_LINE> @editor.require_editor <NEW_LINE> def put(self, exploration_id, thread_id): <NEW_LINE> <INDENT> action = self.payload.get('action') <NEW_LINE> if action == self._ACCEPT_ACTION: <NEW_LINE> <INDENT> exp_services.accept_suggestion( self.user_id, thread_id, exploration_id, self.payload.get('commit_message')) <NEW_LINE> <DEDENT> elif action == self._REJECT_ACTION: <NEW_LINE> <INDENT> exp_services.reject_suggestion( self.user_id, thread_id, exploration_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise self.InvalidInputException('Invalid action.') <NEW_LINE> <DEDENT> self.render_json(self.values) | "Handles actions performed on threads with suggestions. | 6259906745492302aabfdc71 |
class vn46_t288(rose.upgrade.MacroUpgrade): <NEW_LINE> <INDENT> BEFORE_TAG = "vn4.6_t298" <NEW_LINE> AFTER_TAG = "vn4.6_t288" <NEW_LINE> def upgrade(self, config, meta_config=None): <NEW_LINE> <INDENT> self.add_setting(config, ["namelist:jules_surface", "l_layeredc"], ".false.") <NEW_LINE> self.add_setting(config, ["namelist:jules_surface", "bio_hum_cn"], "10.0") <NEW_LINE> self.add_setting(config, ["namelist:jules_surface", "tau_resp"], "2.0") <NEW_LINE> self.add_setting(config, ["namelist:jules_surface", "tau_lit"], "5.0") <NEW_LINE> self.add_setting(config, ["namelist:jules_surface", "diff_n_pft"], "100.0") <NEW_LINE> return config, self.reports | Upgrade macro from JULES by Eleanor Burke | 6259906763d6d428bbee3e53 |
class ApplicationGatewayUrlPathMap(SubResource): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'}, 'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'}, 'default_redirect_configuration': {'key': 'properties.defaultRedirectConfiguration', 'type': 'SubResource'}, 'path_rules': {'key': 'properties.pathRules', 'type': '[ApplicationGatewayPathRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } <NEW_LINE> def __init__(self, id=None, default_backend_address_pool=None, default_backend_http_settings=None, default_redirect_configuration=None, path_rules=None, provisioning_state=None, name=None, etag=None, type=None): <NEW_LINE> <INDENT> super(ApplicationGatewayUrlPathMap, self).__init__(id=id) <NEW_LINE> self.default_backend_address_pool = default_backend_address_pool <NEW_LINE> self.default_backend_http_settings = default_backend_http_settings <NEW_LINE> self.default_redirect_configuration = default_redirect_configuration <NEW_LINE> self.path_rules = path_rules <NEW_LINE> self.provisioning_state = provisioning_state <NEW_LINE> self.name = name <NEW_LINE> self.etag = etag <NEW_LINE> self.type = type | UrlPathMaps give a url path to the backend mapping information for
PathBasedRouting.
:param id: Resource ID.
:type id: str
:param default_backend_address_pool: Default backend address pool resource
of URL path map.
:type default_backend_address_pool:
~azure.mgmt.network.v2017_10_01.models.SubResource
:param default_backend_http_settings: Default backend http settings
resource of URL path map.
:type default_backend_http_settings:
~azure.mgmt.network.v2017_10_01.models.SubResource
:param default_redirect_configuration: Default redirect configuration
resource of URL path map.
:type default_redirect_configuration:
~azure.mgmt.network.v2017_10_01.models.SubResource
:param path_rules: Path rule of URL path map resource.
:type path_rules:
list[~azure.mgmt.network.v2017_10_01.models.ApplicationGatewayPathRule]
:param provisioning_state: Provisioning state of the backend http settings
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param name: Name of the resource that is unique within a resource group.
This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
:param type: Type of the resource.
:type type: str | 62599067a219f33f346c7f9c |
class MovingTargetOutline: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__video_frames = [] <NEW_LINE> <DEDENT> def add_frame(self, frame): <NEW_LINE> <INDENT> self.__video_frames.append(frame) <NEW_LINE> <DEDENT> def set_frames(self, frames): <NEW_LINE> <INDENT> self.__video_frames = frames <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.__video_frames = [] <NEW_LINE> <DEDENT> def get_max_difference_frame(self): <NEW_LINE> <INDENT> frame_len = len(self.__video_frames) <NEW_LINE> if frame_len <= 1: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> result_difference_frame = [] <NEW_LINE> for i in range(0, (frame_len - 2) if frame_len % 2 == 0 else (frame_len - 1)): <NEW_LINE> <INDENT> difference_frame = self._get_difference_frame(self.__video_frames[i], self.__video_frames[i + 1]) <NEW_LINE> result_difference_frame.append(difference_frame) <NEW_LINE> <DEDENT> with multiprocessing.Pool() as pool: <NEW_LINE> <INDENT> max_none_zero = 0 <NEW_LINE> max_difference_frame = None <NEW_LINE> max_difference_frame_index = None <NEW_LINE> for none_zero, frame_index, and_frame in pool.imap_unordered( self._get_and_frame, map( lambda x: (x, result_difference_frame[x], x + 1, result_difference_frame[x + 1]), range(0, len(result_difference_frame) - 1) ) ): <NEW_LINE> <INDENT> if none_zero > max_none_zero: <NEW_LINE> <INDENT> max_none_zero = none_zero <NEW_LINE> max_difference_frame = and_frame <NEW_LINE> max_difference_frame_index = frame_index + 1 <NEW_LINE> <DEDENT> <DEDENT> if max_difference_frame_index: <NEW_LINE> <INDENT> return self.__video_frames[max_difference_frame_index], max_difference_frame <NEW_LINE> <DEDENT> <DEDENT> return None, None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_difference_frame(pre_frame, next_frame): <NEW_LINE> <INDENT> img = cv2.absdiff(pre_frame, next_frame) <NEW_LINE> img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <NEW_LINE> img = cv2.GaussianBlur(img, (5, 5), 2.5) <NEW_LINE> _, img = ImageUtils.binary(img, threshold_type=cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) <NEW_LINE> return img <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_and_frame(args): <NEW_LINE> <INDENT> img = cv2.bitwise_and(args[1], args[3]) <NEW_LINE> return cv2.countNonZero(img), args[0], img | 对连续帧运动目标提取轮廓 | 625990673d592f4c4edbc673 |
class GameStatePublisher(Thread): <NEW_LINE> <INDENT> def __init__(self, tss_model, zmq_context, update_delay=GAMESTATE_PUBLISH_DELAY, publisher="0.0.0.0:8181"): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.message_box = [] <NEW_LINE> self.tss_model = tss_model <NEW_LINE> self.zmq_context = zmq_context <NEW_LINE> self.update_delay = update_delay <NEW_LINE> self.finished_flag = False <NEW_LINE> self.socket = self.zmq_context.socket(zmq.PUB) <NEW_LINE> self.socket.bind("tcp://%s" % publisher) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self.finished_flag: <NEW_LINE> <INDENT> message = {'is_running' : self.tss_model.is_game_running(), 'gamestate': self.tss_model.get_leadingstate()} <NEW_LINE> s = "gamestate|"+json.dumps(message, cls=GameStateEncoder) <NEW_LINE> self.socket.send(s) <NEW_LINE> time.sleep(self.update_delay/1000.0) <NEW_LINE> <DEDENT> self.socket.close() <NEW_LINE> <DEDENT> def stop_publishing(self): <NEW_LINE> <INDENT> self.finished_flag = True | This class is responsible to publish game states
to ZMQ publisher which will be read by clients. | 62599067baa26c4b54d50a3a |
@dataclass(frozen=True) <NEW_LINE> class Video: <NEW_LINE> <INDENT> file_id: str <NEW_LINE> file_unique_id: str <NEW_LINE> width: int <NEW_LINE> height: int <NEW_LINE> duration: int <NEW_LINE> thumb: Optional[PhotoSize] <NEW_LINE> file_name: Optional[str] <NEW_LINE> mime_type: Optional[str] <NEW_LINE> file_size: Optional[int] <NEW_LINE> @classmethod <NEW_LINE> def parse(cls, data: dict) -> Optional['Video']: <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return cls(data['file_id'], data['file_unique_id'], data['width'], data['height'], data['duration'], PhotoSize.parse(data.get('thumb')), data.get('file_name'), data.get('mime_type'), data.get('file_size')) | Represents Video object:
https://core.telegram.org/bots/api#video | 625990677d43ff2487427fdb |
class EncryptionFlowable(StandardEncryption, Flowable): <NEW_LINE> <INDENT> def wrap(self, availWidth, availHeight): <NEW_LINE> <INDENT> return (0,0) <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> encryptCanvas(self.canv, self.userPassword, self.ownerPassword, self.canPrint, self.canModify, self.canCopy, self.canAnnotate) | Drop this in your Platypus story and it will set up the encryption options.
If you do it multiple times, the last one before saving will win. | 625990677cff6e4e811b71dd |
class Analyze: <NEW_LINE> <INDENT> def __init__(self, text=""): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> self._sentiment_analysis = 0.0 <NEW_LINE> self._sentiment_analysis_subjectivity = 0.0 <NEW_LINE> self._ranked_words = [] <NEW_LINE> self._place_interest = [] <NEW_LINE> self._selected_images = [] <NEW_LINE> self._selected_images_url = [] <NEW_LINE> <DEDENT> def sentiment_analysis(self)->int: <NEW_LINE> <INDENT> new_analysis = TextBlob(self._text) <NEW_LINE> self._sentiment_analysis = new_analysis.sentiment.polarity <NEW_LINE> self._sentiment_analysis_subjectivity = new_analysis.subjectivity <NEW_LINE> return self._sentiment_analysis <NEW_LINE> <DEDENT> def place_interest(self) -> list: <NEW_LINE> <INDENT> new_text = self._text <NEW_LINE> new_list = dict() <NEW_LINE> for sent in nltk.sent_tokenize(new_text): <NEW_LINE> <INDENT> for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))): <NEW_LINE> <INDENT> if hasattr(chunk, 'label'): <NEW_LINE> <INDENT> if (chunk.label() not in new_list): <NEW_LINE> <INDENT> new_list[chunk.label()] = ' '.join(c[0] for c in chunk).lower() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temporary = [new_list[chunk.label()]] <NEW_LINE> temporary.append((' '.join(c[0] for c in chunk)).lower()) <NEW_LINE> new_list[chunk.label()] = temporary <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self._place_interest = new_list <NEW_LINE> <DEDENT> def keyword_extraction(self): <NEW_LINE> <INDENT> new_keyword_find = Rake() <NEW_LINE> new_keyword_find.extract_keywords_from_text(self._text) <NEW_LINE> ranked_words = new_keyword_find.get_ranked_phrases_with_scores() <NEW_LINE> self._ranked_words = ranked_words <NEW_LINE> <DEDENT> def google_search(self, **kwargs): <NEW_LINE> <INDENT> my_api_key = "AIzaSyBTfn4y7zrQx1vUM88tjs1dC7wetpbmDJs" <NEW_LINE> my_cse_id = "013938504458615515541:cmbncicbmdc" <NEW_LINE> service = build('customsearch', "v1", developerKey=my_api_key) <NEW_LINE> for val in self._selected_images: <NEW_LINE> <INDENT> res = service.cse().list(q=val, cx=my_cse_id, searchType='image', num = 1, fileType='png', safe='off').execute() <NEW_LINE> if not 'items' in res: <NEW_LINE> <INDENT> print ('No result!!\nres is: {}'.format(res)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for item in res['items']: <NEW_LINE> <INDENT> print('{}:\n\t{}'.format(item['title'],item['link'])) <NEW_LINE> self._selected_images_url.append(item['link']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def image_list(self): <NEW_LINE> <INDENT> temporary = [] <NEW_LINE> temporary_ranked = [] <NEW_LINE> for val in self._place_interest.values(): <NEW_LINE> <INDENT> if type(val) == list: <NEW_LINE> <INDENT> for i in val: <NEW_LINE> <INDENT> temporary.append(i) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> temporary.append(val) <NEW_LINE> <DEDENT> <DEDENT> for val in self._ranked_words: <NEW_LINE> <INDENT> temporary_ranked.append(val[1]) <NEW_LINE> <DEDENT> self._selected_images.append(temporary_ranked[0]) <NEW_LINE> for val_temp in temporary: <NEW_LINE> <INDENT> for val_temp_ranked in temporary_ranked: <NEW_LINE> <INDENT> if val_temp in val_temp_ranked: <NEW_LINE> <INDENT> self._selected_images.append(val_temp_ranked) | class analyze would analyze the text and prepare the right type of slides | 62599067cb5e8a47e493cd4e |
class AccountAdapter(DefaultAccountAdapter): <NEW_LINE> <INDENT> def is_open_for_signup(self, request: HttpRequest): <NEW_LINE> <INDENT> return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) | Custom adapter for normal accounts. | 625990672ae34c7f260ac87d |
class Block(pg.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, image, position, *groups): <NEW_LINE> <INDENT> pg.sprite.Sprite.__init__(self, *groups) <NEW_LINE> self.image = image <NEW_LINE> self.rect = self.image.get_rect(topleft=position) <NEW_LINE> self.speed = 1 <NEW_LINE> <DEDENT> def reset_pos(self, screen_rect): <NEW_LINE> <INDENT> self.rect.x = random.randrange(screen_rect.width-self.rect.width) <NEW_LINE> self.rect.y = random.randrange(-100, -20) <NEW_LINE> <DEDENT> def update(self, keys, screen_rect): <NEW_LINE> <INDENT> self.rect.y += self.speed <NEW_LINE> if self.rect.y > screen_rect.bottom: <NEW_LINE> <INDENT> self.reset_pos(screen_rect) <NEW_LINE> <DEDENT> <DEDENT> def get_copy(self): <NEW_LINE> <INDENT> return copy.copy(self) | This class represents the block. | 6259906721bff66bcd7243fc |
@total_ordering <NEW_LINE> class TubRef(object): <NEW_LINE> <INDENT> def __init__(self, tubID, locationHints=None): <NEW_LINE> <INDENT> if locationHints is None: <NEW_LINE> <INDENT> locationHints = [] <NEW_LINE> <DEDENT> assert isinstance(locationHints, list), locationHints <NEW_LINE> assert all([isinstance(hint, str) for hint in locationHints]), locationHints <NEW_LINE> self.tubID = tubID and six.ensure_str(tubID) <NEW_LINE> self.locationHints = locationHints <NEW_LINE> <DEDENT> def getLocations(self): <NEW_LINE> <INDENT> return self.locationHints <NEW_LINE> <DEDENT> def getTubID(self): <NEW_LINE> <INDENT> return self.tubID <NEW_LINE> <DEDENT> def getShortTubID(self): <NEW_LINE> <INDENT> return self.tubID[:4] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "pb://" + self.tubID <NEW_LINE> <DEDENT> def _distinguishers(self): <NEW_LINE> <INDENT> return (self.tubID,) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self._distinguishers()) <NEW_LINE> <DEDENT> def __lt__(self, them): <NEW_LINE> <INDENT> return self._distinguishers() < them._distinguishers() <NEW_LINE> <DEDENT> def __eq__(self, them): <NEW_LINE> <INDENT> return (type(self) is type(them) and self.__class__ == them.__class__ and self._distinguishers() == them._distinguishers()) <NEW_LINE> <DEDENT> def __ne__(self, them): <NEW_LINE> <INDENT> return not self == them | This is a little helper class which provides a comparable identifier
for Tubs. TubRefs can be used as keys in dictionaries that track
connections to remote Tubs. | 625990677c178a314d78e7b6 |
class SslCertificateIssuerTest(TestCase): <NEW_LINE> <INDENT> def test_getorcreate(self): <NEW_LINE> <INDENT> self.assertIsInstance(SslCertificateIssuer.get_or_create({}), SslCertificateIssuer) | Tests for SSL Certificat Issuer | 62599067cc0a2c111447c69b |
class BasicHistogram: <NEW_LINE> <INDENT> seen = [] <NEW_LINE> semiEmpty = None <NEW_LINE> def __init__(self, vMin=0, vMax=256): <NEW_LINE> <INDENT> self.seen = [] <NEW_LINE> self.semiEmpty = [] <NEW_LINE> for _ in range(vMin, vMax+1): <NEW_LINE> <INDENT> self.seen.append(0) <NEW_LINE> <DEDENT> <DEDENT> def how_many(self, aChr): <NEW_LINE> <INDENT> if isinstance(aChr, str): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for c in aChr: <NEW_LINE> <INDENT> count += self.seen[ord(c)] <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(aChr, int): <NEW_LINE> <INDENT> count = self.seen[c] <NEW_LINE> <DEDENT> return count | Basic histogram class | 62599067dd821e528d6da54c |
class ReadFile: <NEW_LINE> <INDENT> FILENAME = None <NEW_LINE> KEY = None <NEW_LINE> CACHED = False <NEW_LINE> def __init__(self, pid=None, root=None): <NEW_LINE> <INDENT> self.pid = pid <NEW_LINE> LOGGER.debug("pid %s", self.pid) <NEW_LINE> self.root = root or DEFAULT_ROOT <NEW_LINE> LOGGER.debug("root %s", self.root) <NEW_LINE> if self.FILENAME is None: <NEW_LINE> <INDENT> raise ValueError("filename not specified") <NEW_LINE> <DEDENT> if self.pid is not None: <NEW_LINE> <INDENT> self.filename = ospath.join( self.root, self.FILENAME % (self.pid, ), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filename = ospath.join( self.root, self.FILENAME, ) <NEW_LINE> <DEDENT> if self.KEY is None: <NEW_LINE> <INDENT> raise ValueError("key must be string") <NEW_LINE> <DEDENT> LOGGER.debug("key %s", self.KEY) <NEW_LINE> LOGGER.debug("filename %s", self.filename) <NEW_LINE> self.data = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s (%s)' % (self.KEY, self.FILENAME, ) <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> if not self.CACHED or not self.data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.filename, 'rt') as fhandle: <NEW_LINE> <INDENT> self.data = fhandle.read().strip() <NEW_LINE> <DEDENT> <DEDENT> except OSError as ex: <NEW_LINE> <INDENT> LOGGER.error( "Error %s for %s", strerror(ex.errno), self.filename, ) <NEW_LINE> self.data = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.debug("Read %s", self.filename) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def lines(self): <NEW_LINE> <INDENT> return self.data.split('\n') if self.data else [] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def convert(val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = literal_eval(val.strip()) <NEW_LINE> <DEDENT> except (ValueError, SyntaxError): <NEW_LINE> <INDENT> ret = val.strip() <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def normalize(self): <NEW_LINE> <INDENT> raise NotImplementedError("normalize method is undefined") | Read File from filesystem | 62599067e1aae11d1e7cf3d7 |
class PartitionRequest(Part): <NEW_LINE> <INDENT> parts = ( ("partition_id", Int32), ("time", Int64), ("max_offsets", Int32), ) | ::
PartitionRequeset =>
partition_id => Int32
time => Int64
max_offsets => Int32 | 625990677047854f46340b4b |
class InactiveChats(TLObject): <NEW_LINE> <INDENT> __slots__ = ["dates", "chats", "users"] <NEW_LINE> ID = 0xa927fec5 <NEW_LINE> QUALNAME = "types.messages.InactiveChats" <NEW_LINE> def __init__(self, *, dates: list, chats: list, users: list): <NEW_LINE> <INDENT> self.dates = dates <NEW_LINE> self.chats = chats <NEW_LINE> self.users = users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "InactiveChats": <NEW_LINE> <INDENT> dates = TLObject.read(b, Int) <NEW_LINE> chats = TLObject.read(b) <NEW_LINE> users = TLObject.read(b) <NEW_LINE> return InactiveChats(dates=dates, chats=chats, users=users) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(Vector(self.dates, Int)) <NEW_LINE> b.write(Vector(self.chats)) <NEW_LINE> b.write(Vector(self.users)) <NEW_LINE> return b.getvalue() | Attributes:
LAYER: ``112``
Attributes:
ID: ``0xa927fec5``
Parameters:
dates: List of ``int`` ``32-bit``
chats: List of either :obj:`ChatEmpty <pyrogram.api.types.ChatEmpty>`, :obj:`Chat <pyrogram.api.types.Chat>`, :obj:`ChatForbidden <pyrogram.api.types.ChatForbidden>`, :obj:`Channel <pyrogram.api.types.Channel>` or :obj:`ChannelForbidden <pyrogram.api.types.ChannelForbidden>`
users: List of either :obj:`UserEmpty <pyrogram.api.types.UserEmpty>` or :obj:`User <pyrogram.api.types.User>`
See Also:
This object can be returned by :obj:`channels.GetInactiveChannels <pyrogram.api.functions.channels.GetInactiveChannels>`. | 62599067009cb60464d02ccf |
class action_traceability(osv.osv_memory): <NEW_LINE> <INDENT> _name = "action.traceability" <NEW_LINE> _description = "Action traceability " <NEW_LINE> def action_traceability(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> lot_id = ids <NEW_LINE> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> type1 = context['type'] or 'move_history_ids2' <NEW_LINE> field = context['field'] or 'tracking_id' <NEW_LINE> obj = self.pool.get('stock.move') <NEW_LINE> ids = obj.search(cr, uid, [(field, 'in',lot_id)]) <NEW_LINE> cr.execute('select id from ir_ui_view where model=%s and field_parent=%s and type=%s', ('stock.move', type1, 'tree')) <NEW_LINE> view_id = cr.fetchone()[0] <NEW_LINE> value = { 'domain': "[('id','in',["+','.join(map(str, ids))+"])]", 'name': ((type1=='move_history_ids2') and _('Upstream Traceability')) or _('Downstream Traceability'), 'view_type': 'tree', 'res_model': 'stock.move', 'field_parent': type1, 'view_id': (view_id,'View'), 'type': 'ir.actions.act_window', 'nodestroy':True, } <NEW_LINE> return value | This class defines a function action_traceability for wizard | 625990674e4d562566373b9d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.