repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
ProzorroUKR/openprocurement.audit.api
|
openprocurement/audit/monitoring/tests/test_document.py
|
<filename>openprocurement/audit/monitoring/tests/test_document.py
# -*- coding: utf-8 -*-
import unittest
from hashlib import sha512
from unittest import mock
from openprocurement.audit.monitoring.tests.base import BaseWebTest, DSWebTestMixin
from openprocurement.audit.monitoring.tests.test_elimination import MonitoringEliminationBaseTest
from openprocurement.audit.monitoring.tests.utils import get_errors_field_names
class MonitoringDecisionDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringDecisionDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
'documentType': 'notice',
'id': '0' * 32
}
self.test_monitoring_activation_data = {
"status": "active",
"decision": {
"date": "2015-05-10T23:11:39.720908+03:00",
"description": "text",
"documents": [self.test_docservice_document_data]
}
}
def test_document_get_single(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_id = response.json['data']['decision']['documents'][-1]['id']
response = self.app.get('/monitorings/{}/decision/documents/{}'.format(self.monitoring_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
self.assertEqual(document_data["documentType"], "notice")
def test_document_get_list(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.get('/monitorings/{}/decision/documents'.format(self.monitoring_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
def test_document_download(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']['decision']['documents'][-1]
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/decision/documents/{}?download=some_id'.format(
self.monitoring_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/decision/documents/{}?download={}'.format(
self.monitoring_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
def test_document_upload(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {'decision': self.test_monitoring_activation_data['decision']}})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/decision/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
def test_document_upload_forbidden(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/decision/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data}, status=403)
self.assertEqual(response.status_code, 403)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(
('body', 'data'),
next(get_errors_field_names(response, 'Can\'t add document in current active monitoring status.')))
class MonitoringPostActiveDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringPostActiveDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
"status": "active",
"decision": {
"date": "2015-05-10T23:11:39.720908+03:00",
"description": "text",
"documents": [self.test_docservice_document_data]
}
}}
)
self.post_data = {
'title': 'Lorem ipsum',
'description': 'Lorem ipsum dolor sit amet',
'documents': [self.test_docservice_document_data]
}
def test_document_get_single(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/posts'.format(self.monitoring_id),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
document_id = response.json['data']['documents'][-1]['id']
response = self.app.get('/monitorings/{}/posts/{}/documents/{}'.format(self.monitoring_id, post_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
def test_document_get_list(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/posts'.format(self.monitoring_id),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
response = self.app.get('/monitorings/{}/posts/{}/documents'.format(self.monitoring_id, post_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
def test_document_download(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/posts'.format(self.monitoring_id),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
document_data = response.json['data']['documents'][-1]
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/posts/{}/documents/{}?download=some_id'.format(
self.monitoring_id, post_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/posts/{}/documents/{}?download={}'.format(
self.monitoring_id, post_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
def test_document_upload(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/posts'.format(self.monitoring_id),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
response = self.app.post_json('/monitorings/{}/posts/{}/documents'.format(
self.monitoring_id, post_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
def test_document_upload_forbidden(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/posts'.format(self.monitoring_id),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
"status": "addressed",
"conclusion": {
"violationOccurred": True,
"violationType": ["corruptionProcurementMethodType"],
}
}}
)
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.post_json('/monitorings/{}/posts/{}/documents'.format(
self.monitoring_id, post_id),
{'data': self.test_docservice_document_data}, status=403)
self.assertEqual(response.status_code, 403)
self.assertEqual(response.content_type, 'application/json')
class MonitoringPostAddressedDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringPostAddressedDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
"status": "active",
"decision": {
"date": "2015-05-10T23:11:39.720908+03:00",
"description": "text",
"documents": [self.test_docservice_document_data]
}
}}
)
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
"conclusion": {
"description": "Some text",
"violationOccurred": True,
"violationType": ["corruptionProcurementMethodType", "corruptionAwarded"],
"documents": [self.test_docservice_document_data]
},
"status": "addressed",
}}
)
self.post_data = {
'title': 'Lorem ipsum',
'description': 'Lorem ipsum dolor sit amet',
'documents': [self.test_docservice_document_data]
}
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_get_single(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
document_id = response.json['data']['documents'][-1]['id']
response = self.app.get('/monitorings/{}/posts/{}/documents/{}'.format(self.monitoring_id, post_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_get_list(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
response = self.app.get('/monitorings/{}/posts/{}/documents'.format(self.monitoring_id, post_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_download(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
document_data = response.json['data']['documents'][-1]
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/posts/{}/documents/{}?download=some_id'.format(
self.monitoring_id, post_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/posts/{}/documents/{}?download={}'.format(
self.monitoring_id, post_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_upload_no_token(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
response = self.app.post_json('/monitorings/{}/posts/{}/documents'.format(
self.monitoring_id, post_id),
{'data': self.test_docservice_document_data}, status=403)
self.assertEqual(response.status_code, 403)
self.assertEqual(response.content_type, 'application/json')
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_upload(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
response = self.app.post_json('/monitorings/{}/posts/{}/documents?acc_token={}'.format(
self.monitoring_id, post_id, tender_owner_token),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
@mock.patch('openprocurement.audit.monitoring.validation.TendersClient')
def test_document_upload_author_forbidden(self, mock_api_client):
mock_api_client.return_value.extract_credentials.return_value = {
'data': {'tender_token': sha512(b'tender_token').hexdigest()}
}
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
response = self.app.patch_json(
'/monitorings/{}/credentials?acc_token={}'.format(self.monitoring_id, 'tender_token')
)
tender_owner_token = response.json['access']['token']
response = self.app.post_json(
'/monitorings/{}/posts?acc_token={}'.format(self.monitoring_id, tender_owner_token),
{'data': self.post_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
post_id = response.json['data']['id']
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.post_json('/monitorings/{}/posts/{}/documents'.format(
self.monitoring_id, post_id),
{'data': self.test_docservice_document_data}, status=403)
class MonitoringDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.test_monitoring_activation_data = {
"documents": [self.test_docservice_document_data],
}
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
'status': "cancelled",
'cancellation': {
"description": "text"
}
}})
def test_document_get_single(self):
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_id = response.json['data']['documents'][-1]['id']
response = self.app.get('/monitorings/{}/documents/{}'.format(self.monitoring_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
def test_document_get_list(self):
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.get('/monitorings/{}/documents'.format(self.monitoring_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
def test_document_download(self):
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']['documents'][-1]
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/documents/{}?download=some_id'.format(
self.monitoring_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/documents/{}?download={}'.format(
self.monitoring_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
def test_document_upload(self):
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
class MonitoringCancellationDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringCancellationDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.test_monitoring_activation_data = {
'status': "cancelled",
'cancellation': {
"description": "text",
"documents": []
}
}
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_activation_data})
self.end_point = '/monitorings/%s/cancellation/documents' % self.monitoring_id
def test_get_single(self):
response = self.app.post_json(
'/monitorings/{}/cancellation/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
document_id = response.json['data']['id']
response = self.app.get('/monitorings/{}/cancellation/documents/{}'.format(self.monitoring_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
def test_document_get_list(self):
response = self.app.post_json(
'/monitorings/{}/cancellation/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
response = self.app.get('/monitorings/{}/cancellation/documents'.format(self.monitoring_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
def test_document_download(self):
response = self.app.post_json(
'/monitorings/{}/cancellation/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/cancellation/documents/{}?download=some_id'.format(
self.monitoring_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/cancellation/documents/{}?download={}'.format(
self.monitoring_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
def test_document_upload(self):
response = self.app.post_json('/monitorings/{}/cancellation/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
class MonitoringEliminationResolutionDocumentResourceTest(MonitoringEliminationBaseTest):
def setUp(self):
super(MonitoringEliminationResolutionDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.create_monitoring_with_resolution()
def test_document_get_single(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
document_id = response.json['data']['id']
response = self.app.get(
'/monitorings/{}/eliminationResolution/documents/{}'.format(self.monitoring_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
def test_document_get_list(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
response = self.app.get('/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(2, len(response.json['data']))
self.assertIn('lorem.doc', [doc['title'] for doc in response.json['data']])
def test_document_download(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json(
'/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
key = document_data["url"].split('/')[-1].split('?')[0]
document_id = document_data['id']
response = self.app.get('/monitorings/{}/eliminationResolution/documents/{}?download=some_id'.format(
self.monitoring_id, document_id), status=404)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.json['status'], 'error')
self.assertEqual(response.json['errors'], [
{'description': 'Not Found', 'location': 'url', 'name': 'download'}
])
response = self.app.get('/monitorings/{}/eliminationResolution/documents/{}?download={}'.format(
self.monitoring_id, document_id, key))
self.assertEqual(response.status_code, 302)
self.assertIn('http://localhost/get/', response.location)
self.assertIn('Signature=', response.location)
self.assertIn('KeyID=', response.location)
self.assertNotIn('Expires=', response.location)
def test_document_upload(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.post_json('/monitorings/{}/eliminationResolution/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
def test_patch_document(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
request_data = {
'title': 'another.txt',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '1' * 32,
'format': 'application/msword',
}
response = self.app.get('/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id))
doc_to_update = response.json['data'][0]
response = self.app.patch_json(
'/monitorings/{}/eliminationResolution/documents/{}'.format(
self.monitoring_id, doc_to_update["id"]
),
{"data": request_data}
)
self.assertEqual(response.json["data"]["title"], request_data["title"])
self.assertEqual(response.json["data"]["format"], request_data["format"])
self.assertNotEqual(
response.json["data"]["url"].split("Signature")[0],
request_data["url"].split("Signature")[0],
)
self.assertNotEqual(response.json["data"]["hash"], request_data["hash"])
def test_patch_document_forbidden(self):
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
document = {
'title': 'another.txt',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '1' * 32,
'format': 'application/msword',
}
response = self.app.get('/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id))
doc_to_update = response.json['data'][0]
self.app.patch_json(
'/monitorings/{}/eliminationResolution/documents/{}?acc_token={}'.format(
self.monitoring_id, doc_to_update["id"], self.tender_owner_token
),
{"data": document},
status=403
)
def test_put_document(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
request_data = {
'title': 'my_new_file.txt',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'text/css',
}
response = self.app.get('/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id))
doc_to_update = response.json['data'][0]
response = self.app.put_json(
'/monitorings/{}/eliminationResolution/documents/{}'.format(
self.monitoring_id, doc_to_update["id"]
),
{"data": request_data}
)
self.assertEqual(response.json["data"]["title"], request_data["title"])
self.assertEqual(
response.json["data"]["url"].split("Signature")[0],
request_data["url"].split("Signature")[0],
)
self.assertEqual(response.json["data"]["format"], request_data["format"])
self.assertEqual(response.json["data"]["hash"], request_data["hash"])
def test_put_document_forbidden(self):
self.app.authorization = ('Basic', (self.broker_name, self.broker_pass))
document = {
'title': 'my_new_file.txt',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'text/css',
}
response = self.app.get('/monitorings/{}/eliminationResolution/documents'.format(self.monitoring_id))
doc_to_update = response.json['data'][0]
self.app.put_json(
'/monitorings/{}/eliminationResolution/documents/{}?acc_token={}'.format(
self.monitoring_id, doc_to_update["id"], self.tender_owner_token
),
{"data": document},
status=403
)
class MonitoringConclusionDocumentResourceTest(BaseWebTest, DSWebTestMixin):
def setUp(self):
super(MonitoringConclusionDocumentResourceTest, self).setUp()
self.app.app.registry.docservice_url = 'http://localhost'
self.create_monitoring()
self.test_docservice_document_data = {
'title': 'lorem.doc',
'url': self.generate_docservice_url(),
'hash': 'md5:' + '0' * 32,
'format': 'application/msword',
}
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {
"status": "active",
"decision": {
"date": "2015-05-10T23:11:39.720908+03:00",
"description": "text",
"documents": [self.test_docservice_document_data]
}
}}
)
self.test_monitoring_addressed_data = {
"conclusion": {
"description": "Some text",
"violationOccurred": True,
"violationType": ["corruptionProcurementMethodType", "corruptionAwarded"],
"documents": [self.test_docservice_document_data]
},
"status": "addressed",
}
def test_document_get_single(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_addressed_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_id = response.json['data']['conclusion']['documents'][-1]['id']
response = self.app.get('/monitorings/{}/conclusion/documents/{}'.format(self.monitoring_id, document_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
document_data = response.json['data']
self.assertEqual(document_data['title'], 'lorem.doc')
self.assertIn('Signature=', document_data["url"])
self.assertIn('KeyID=', document_data["url"])
self.assertNotIn('Expires=', document_data["url"])
def test_document_get_list(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_addressed_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.get('/monitorings/{}/conclusion/documents'.format(self.monitoring_id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(len(response.json['data']), 1)
document_data = response.json['data'][-1]
self.assertEqual(document_data['title'], 'lorem.doc')
def test_document_upload(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {'conclusion': self.test_monitoring_addressed_data['conclusion']}})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/conclusion/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
def test_document_patch(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': {'conclusion': self.test_monitoring_addressed_data['conclusion']}})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/conclusion/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data})
self.assertEqual(response.status_code, 201)
self.assertEqual(response.content_type, 'application/json')
doc_id = response.json["data"]["id"]
old_dateModified = response.json["data"]["dateModified"]
response = self.app.patch_json('/monitorings/{}/conclusion/documents/{}'.format(
self.monitoring_id, doc_id),
{'data': {'title': self.test_docservice_document_data["title"]}}
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, None)
response = self.app.patch_json('/monitorings/{}/conclusion/documents/{}'.format(
self.monitoring_id, doc_id),
{'data': {'title': 'lorem1.doc'}}
)
self.assertEqual(response.status_code, 200)
self.assertNotEqual(response.json["data"]["dateModified"], old_dateModified)
def test_document_upload_forbidden(self):
self.app.authorization = ('Basic', (self.sas_name, self.sas_pass))
response = self.app.patch_json(
'/monitorings/{}'.format(self.monitoring_id),
{'data': self.test_monitoring_addressed_data})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content_type, 'application/json')
response = self.app.post_json('/monitorings/{}/conclusion/documents'.format(
self.monitoring_id),
{'data': self.test_docservice_document_data}, status=403)
self.assertEqual(response.status_code, 403)
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(
('body', 'data'),
next(get_errors_field_names(response, 'Can\'t add document in current addressed monitoring status.')))
|
bfarka/assertj-core
|
src/test/java/org/assertj/core/internal/throwables/Throwables_assertHasMessageMatching_Test.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2018 the original author or authors.
*/
package org.assertj.core.internal.throwables;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.error.ShouldHaveMessageMatchingRegex.shouldHaveMessageMatchingRegex;
import static org.assertj.core.test.TestData.someInfo;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.api.ThrowableAssert;
import org.assertj.core.internal.ThrowablesBaseTest;
import org.junit.Test;
/**
* Tests for <code>{@link ThrowableAssert#hasMessageMatching(String)}</code>.
*
* @author <NAME>
*/
public class Throwables_assertHasMessageMatching_Test extends ThrowablesBaseTest {
public static final String REGEX = "Given id='\\d{2,4}' not exists";
@Test
public void should_pass_if_throwable_message_matches_given_regex() {
actual = new RuntimeException("Given id='259' not exists");
throwables.assertHasMessageMatching(someInfo(), actual, REGEX);
}
@Test
public void should_pass_if_throwable_message_is_empty_and_regex_is_too() {
actual = new RuntimeException("");
throwables.assertHasMessageMatching(someInfo(), actual, "");
}
@Test
public void should_fail_if_throwable_message_does_not_match_given_regex() {
AssertionInfo info = someInfo();
try {
throwables.assertHasMessageMatching(info, actual, REGEX);
fail("AssertionError expected");
} catch (AssertionError err) {
verify(failures).failure(info, shouldHaveMessageMatchingRegex(actual, REGEX));
}
}
@Test
public void should_fail_if_given_regex_is_null() {
thrown.expectNullPointerException("regex must not be null");
throwables.assertHasMessageMatching(someInfo(), actual, null);
}
@Test
public void should_fail_if_throwable_does_not_have_a_message() {
actual = new RuntimeException();
AssertionInfo info = someInfo();
try {
throwables.assertHasMessageMatching(info, actual, REGEX);
fail("AssertionError expected");
} catch (AssertionError err) {
verify(failures).failure(info, shouldHaveMessageMatchingRegex(actual, REGEX));
}
}
}
|
jiangxiaoxin/CodingMart_iOS
|
CodingMart/Controllers/EAProjectPrivate/Cell/EAProjectPrivate/EAProjectPrivateHeaderCell.h
|
//
// EAProjectPrivateHeaderCell.h
// CodingMart
//
// Created by Easeeeeeeeee on 2017/10/19.
// Copyright © 2017年 <EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface EAProjectPrivateHeaderCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@end
|
gilles-leblanc/gameproject
|
RandomNameGeneration/input_loader.rb
|
require 'yaml'
# load the input data from a file containing a plain text sample data of
# names separated by spaces
class FileInputLoader
# @param [Object] input filename containing plain text sample data of names.
def load(input)
begin
IO.read(input).downcase
rescue Errno::ENOENT => e
puts e.inspect
puts "Input fully qualified filename : #{Dir.pwd}#{input}"
raise e
end
end
end
# load the input data from a string or array in memory which is passed
# as a parameter to load
class MemoryInputLoader
# @param [Object] input string or array in memory containing sample names
# data.
def load(input)
input.downcase
end
end
# load the input data from a file which contains the already
# calculated frequencies serialized to YAML
class YAMLInputLoader
# @param [Object] input file containing a hash of frequencies serialized
# to YAML.
def load(input)
YAML.load_file(input)
end
end
|
haniot/android-app
|
app/src/main/java/br/edu/uepb/nutes/haniot/parse/YunmaiParser.java
|
<gh_stars>1-10
package br.edu.uepb.nutes.haniot.parse;
import android.bluetooth.BluetoothGattCharacteristic;
import android.support.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
import br.edu.uepb.nutes.haniot.utils.DateUtils;
/**
* Parse for body composition.
*
* @author <NAME> <<EMAIL>>
* @version 1.0
* @copyright Copyright (c) 2017, NUTES UEPB
*/
public class YunmaiParser {
/**
* Parse for YUNMAI device.
* Supported Models: smart scale (M1301, M1302, M1303, M1501).
*
* @param characteristic BluetoothGattCharacteristic
* @return JSONObject
* @throws JSONException
*/
public static JSONObject parse(@NonNull final BluetoothGattCharacteristic characteristic) throws JSONException {
final byte[] data = characteristic.getValue();
JSONObject result = new JSONObject();
double bodyMass = 0f;
if (data.length > 0) {
/**
* Timestamp current
*/
result.put("timestamp", DateUtils.getCurrentDateTimeUTC());
/**
* 03: response type
* 01 - unfinished weighing
* 02 - finished weighing
*/
boolean isFinalized = String.format("%02X", data[3]).equals("02");
result.put("isFinalized", isFinalized);
/**
* unfinished weighing
* 08-09: weight - BE uint16 times 0.01
*/
bodyMass = Integer.valueOf(String.format("%02X", data[8]) + String.format("%02X", data[9]), 16) * 0.01f;
result.put("bodyMass", bodyMass);
// Body Mass Unit default
result.put("bodyMassUnit", "kg");
// Finalized
if (isFinalized) {
/**
* finished weighing
* 13-14: weight - BE uint16 times 0.01
*/
bodyMass = Integer.valueOf(String.format("%02X", data[13]) + String.format("%02X", data[14]), 16) * 0.01f;
result.put("bodyMass", bodyMass);
/**
* 15-16: resistance - BE uint 16
*/
final double resistance = Integer.valueOf(String.format("%02X", data[15]) + String.format("%02X", data[16]), 16);
result.put("resistance", resistance);
/**
* Body Fat in percentage
*
* 17-18: - BE uint16 times 0.01
*/
final double bodyFat = Integer.valueOf(String.format("%02X", data[17]) + String.format("%02X", data[18]), 16) * 0.01f;
result.put("bodyFat", bodyFat);
result.put("bodyFatUnit", "%"); // value fixed
/**
* USER ID
* 09-12: recognized userID - BE uint32
*/
// Integer userID = Integer.valueOf(String.format("%02X", data[9]) +
// String.format("%02X", data[10]) +
// String.format("%02X", data[11]) +
// String.format("%02X", data[12]), 32
// );
//
// result.put("userID", userID);
}
}
return result;
}
}
|
pawelmhm/pyjsparser
|
tests/pass/aab51bc524d9c623.js
|
(function () {
a(null!=(b?c:void 1));
}());
|
core-ml/coreml
|
tests/data/test_classification_dataset.py
|
"""Tests coreml.data.classification.ClassificationDataset"""
import unittest
from os.path import join, exists
import subprocess
import torch
import numpy as np
from coreml.config import DATA_ROOT
from coreml.data.classification import get_classification_dataset
from coreml.data.vision.base import BaseImageDataset
from coreml.data.transforms import DataProcessor, \
ClassificationAnnotationTransform
class ClassificationDatasetTestCase(unittest.TestCase):
"""Class to run tests on ClassificationDataset"""
@classmethod
def setUpClass(cls):
if not exists(join(DATA_ROOT, 'CIFAR10')):
subprocess.call(
'python /workspace/coreml/coreml/data/process/CIFAR10.py',
shell=True)
classes = np.arange(10).tolist()
cls.target_transform = ClassificationAnnotationTransform(classes)
cls.dataset_config = [
{
'name': 'CIFAR10',
'version': 'default',
'mode': 'test'
}
]
transform_config = [
{
'name': 'Permute',
'params': {
'order': [2, 0, 1]
}
},
{
'name': 'Resize',
'params': {
'size': [30, 30]
}
}
]
cls.signal_transform = DataProcessor(transform_config)
def test_different_modes(self):
"""Test ClassificationDataset object for different modes"""
test_dataset_config = {
'name': 'CIFAR10',
'version': 'default',
'mode': 'test'
}
train_dataset_config = {
'name': 'CIFAR10',
'version': 'default',
'mode': 'train'
}
test_dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT, [test_dataset_config])
train_dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT, [train_dataset_config])
self.assertTrue(len(test_dataset.items) != len(train_dataset.items))
def test_fraction(self):
"""Test creating ClassificationDataset object using fraction < 1"""
dataset_config = {
'name': 'CIFAR10',
'version': 'default',
'mode': 'test'
}
fraction = 0.5
dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT, [dataset_config], fraction=fraction)
self.assertEqual(5000, len(dataset.items))
def test_dataset_no_transform(self):
"""Checks dataset using no transform"""
dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT, self.dataset_config)
instance = dataset[0]
self.assertEqual(
instance['item'].path,
'/data/CIFAR10/processed/images/50000.png')
self.assertTrue(isinstance(instance['signal'], torch.Tensor))
self.assertEqual(instance['label'], [3])
def test_dataset_with_target_transform(self):
"""Checks dataset with target transform"""
dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT,
self.dataset_config,
target_transform=self.target_transform)
instance = dataset[0]
self.assertEqual(
instance['item'].path,
'/data/CIFAR10/processed/images/50000.png')
self.assertTrue(isinstance(instance['signal'], torch.Tensor))
self.assertEqual(instance['label'], 3)
def test_dataset_with_signal_transform(self):
"""Checks dataset with signal transform"""
dataset = get_classification_dataset(BaseImageDataset)(
DATA_ROOT,
self.dataset_config,
signal_transform=self.signal_transform,
target_transform=self.target_transform)
instance = dataset[0]
self.assertEqual(instance['signal'].shape, (3, 30, 30))
if __name__ == "__main__":
unittest.main()
|
mohitjain97/isilon_sdk_python
|
isi_sdk_8_2_0/isi_sdk_8_2_0/models/certificate_server_certificate.py
|
<filename>isi_sdk_8_2_0/isi_sdk_8_2_0/models/certificate_server_certificate.py<gh_stars>10-100
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 7
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_2_0.models.certificate_server_certificate_fingerprint import CertificateServerCertificateFingerprint # noqa: F401,E501
class CertificateServerCertificate(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'description': 'str',
'dnsnames': 'list[str]',
'fingerprints': 'list[CertificateServerCertificateFingerprint]',
'id': 'str',
'issuer': 'str',
'name': 'str',
'not_after': 'int',
'not_before': 'int',
'status': 'str',
'subject': 'str'
}
attribute_map = {
'description': 'description',
'dnsnames': 'dnsnames',
'fingerprints': 'fingerprints',
'id': 'id',
'issuer': 'issuer',
'name': 'name',
'not_after': 'not_after',
'not_before': 'not_before',
'status': 'status',
'subject': 'subject'
}
def __init__(self, description=None, dnsnames=None, fingerprints=None, id=None, issuer=None, name=None, not_after=None, not_before=None, status=None, subject=None): # noqa: E501
"""CertificateServerCertificate - a model defined in Swagger""" # noqa: E501
self._description = None
self._dnsnames = None
self._fingerprints = None
self._id = None
self._issuer = None
self._name = None
self._not_after = None
self._not_before = None
self._status = None
self._subject = None
self.discriminator = None
self.description = description
self.dnsnames = dnsnames
self.fingerprints = fingerprints
self.id = id
self.issuer = issuer
self.name = name
self.not_after = not_after
self.not_before = not_before
self.status = status
self.subject = subject
@property
def description(self):
"""Gets the description of this CertificateServerCertificate. # noqa: E501
Description field associated with a certificate provided for administrative convenience. # noqa: E501
:return: The description of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this CertificateServerCertificate.
Description field associated with a certificate provided for administrative convenience. # noqa: E501
:param description: The description of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if description is None:
raise ValueError("Invalid value for `description`, must not be `None`") # noqa: E501
if description is not None and len(description) > 2048:
raise ValueError("Invalid value for `description`, length must be less than or equal to `2048`") # noqa: E501
if description is not None and len(description) < 0:
raise ValueError("Invalid value for `description`, length must be greater than or equal to `0`") # noqa: E501
self._description = description
@property
def dnsnames(self):
"""Gets the dnsnames of this CertificateServerCertificate. # noqa: E501
A list of DNS names/patterns for which this certificate is valid. This list is extracted from the certificates CN (Common Name) and subjectAtlName extension fields. # noqa: E501
:return: The dnsnames of this CertificateServerCertificate. # noqa: E501
:rtype: list[str]
"""
return self._dnsnames
@dnsnames.setter
def dnsnames(self, dnsnames):
"""Sets the dnsnames of this CertificateServerCertificate.
A list of DNS names/patterns for which this certificate is valid. This list is extracted from the certificates CN (Common Name) and subjectAtlName extension fields. # noqa: E501
:param dnsnames: The dnsnames of this CertificateServerCertificate. # noqa: E501
:type: list[str]
"""
if dnsnames is None:
raise ValueError("Invalid value for `dnsnames`, must not be `None`") # noqa: E501
self._dnsnames = dnsnames
@property
def fingerprints(self):
"""Gets the fingerprints of this CertificateServerCertificate. # noqa: E501
A list of zero or more certificate fingerprints which can be used for certificate identification. # noqa: E501
:return: The fingerprints of this CertificateServerCertificate. # noqa: E501
:rtype: list[CertificateServerCertificateFingerprint]
"""
return self._fingerprints
@fingerprints.setter
def fingerprints(self, fingerprints):
"""Sets the fingerprints of this CertificateServerCertificate.
A list of zero or more certificate fingerprints which can be used for certificate identification. # noqa: E501
:param fingerprints: The fingerprints of this CertificateServerCertificate. # noqa: E501
:type: list[CertificateServerCertificateFingerprint]
"""
if fingerprints is None:
raise ValueError("Invalid value for `fingerprints`, must not be `None`") # noqa: E501
self._fingerprints = fingerprints
@property
def id(self):
"""Gets the id of this CertificateServerCertificate. # noqa: E501
Unique server certificate identifier. # noqa: E501
:return: The id of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this CertificateServerCertificate.
Unique server certificate identifier. # noqa: E501
:param id: The id of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
if id is not None and len(id) > 512:
raise ValueError("Invalid value for `id`, length must be less than or equal to `512`") # noqa: E501
if id is not None and len(id) < 1:
raise ValueError("Invalid value for `id`, length must be greater than or equal to `1`") # noqa: E501
self._id = id
@property
def issuer(self):
"""Gets the issuer of this CertificateServerCertificate. # noqa: E501
Certificate issuer field extracted from the certificate. # noqa: E501
:return: The issuer of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._issuer
@issuer.setter
def issuer(self, issuer):
"""Sets the issuer of this CertificateServerCertificate.
Certificate issuer field extracted from the certificate. # noqa: E501
:param issuer: The issuer of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if issuer is None:
raise ValueError("Invalid value for `issuer`, must not be `None`") # noqa: E501
if issuer is not None and len(issuer) > 2048:
raise ValueError("Invalid value for `issuer`, length must be less than or equal to `2048`") # noqa: E501
if issuer is not None and len(issuer) < 1:
raise ValueError("Invalid value for `issuer`, length must be greater than or equal to `1`") # noqa: E501
self._issuer = issuer
@property
def name(self):
"""Gets the name of this CertificateServerCertificate. # noqa: E501
Administrator specified name identifier. # noqa: E501
:return: The name of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this CertificateServerCertificate.
Administrator specified name identifier. # noqa: E501
:param name: The name of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
if name is not None and len(name) > 128:
raise ValueError("Invalid value for `name`, length must be less than or equal to `128`") # noqa: E501
if name is not None and len(name) < 0:
raise ValueError("Invalid value for `name`, length must be greater than or equal to `0`") # noqa: E501
if name is not None and not re.search('^[a-zA-Z0-9_-]*$', name): # noqa: E501
raise ValueError("Invalid value for `name`, must be a follow pattern or equal to `/^[a-zA-Z0-9_-]*$/`") # noqa: E501
self._name = name
@property
def not_after(self):
"""Gets the not_after of this CertificateServerCertificate. # noqa: E501
Certificate notAfter field extracted from the certificate encoded as a UNIX epoch timestamp. The certificate is not valid after this timestamp. # noqa: E501
:return: The not_after of this CertificateServerCertificate. # noqa: E501
:rtype: int
"""
return self._not_after
@not_after.setter
def not_after(self, not_after):
"""Sets the not_after of this CertificateServerCertificate.
Certificate notAfter field extracted from the certificate encoded as a UNIX epoch timestamp. The certificate is not valid after this timestamp. # noqa: E501
:param not_after: The not_after of this CertificateServerCertificate. # noqa: E501
:type: int
"""
if not_after is None:
raise ValueError("Invalid value for `not_after`, must not be `None`") # noqa: E501
if not_after is not None and not_after > 9223372036854775807: # noqa: E501
raise ValueError("Invalid value for `not_after`, must be a value less than or equal to `9223372036854775807`") # noqa: E501
if not_after is not None and not_after < 0: # noqa: E501
raise ValueError("Invalid value for `not_after`, must be a value greater than or equal to `0`") # noqa: E501
self._not_after = not_after
@property
def not_before(self):
"""Gets the not_before of this CertificateServerCertificate. # noqa: E501
Certificate notBefore field extracted from the certificate encoded as a UNIX epoch timestamp. The certificate is not valid before this timestamp. # noqa: E501
:return: The not_before of this CertificateServerCertificate. # noqa: E501
:rtype: int
"""
return self._not_before
@not_before.setter
def not_before(self, not_before):
"""Sets the not_before of this CertificateServerCertificate.
Certificate notBefore field extracted from the certificate encoded as a UNIX epoch timestamp. The certificate is not valid before this timestamp. # noqa: E501
:param not_before: The not_before of this CertificateServerCertificate. # noqa: E501
:type: int
"""
if not_before is None:
raise ValueError("Invalid value for `not_before`, must not be `None`") # noqa: E501
if not_before is not None and not_before > 9223372036854775807: # noqa: E501
raise ValueError("Invalid value for `not_before`, must be a value less than or equal to `9223372036854775807`") # noqa: E501
if not_before is not None and not_before < 0: # noqa: E501
raise ValueError("Invalid value for `not_before`, must be a value greater than or equal to `0`") # noqa: E501
self._not_before = not_before
@property
def status(self):
"""Gets the status of this CertificateServerCertificate. # noqa: E501
Certificate validity status # noqa: E501
:return: The status of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this CertificateServerCertificate.
Certificate validity status # noqa: E501
:param status: The status of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501
allowed_values = ["valid", "invalid", "expired", "expiring"] # noqa: E501
if status not in allowed_values:
raise ValueError(
"Invalid value for `status` ({0}), must be one of {1}" # noqa: E501
.format(status, allowed_values)
)
self._status = status
@property
def subject(self):
"""Gets the subject of this CertificateServerCertificate. # noqa: E501
Certificate subject field extracted from the certificate. # noqa: E501
:return: The subject of this CertificateServerCertificate. # noqa: E501
:rtype: str
"""
return self._subject
@subject.setter
def subject(self, subject):
"""Sets the subject of this CertificateServerCertificate.
Certificate subject field extracted from the certificate. # noqa: E501
:param subject: The subject of this CertificateServerCertificate. # noqa: E501
:type: str
"""
if subject is None:
raise ValueError("Invalid value for `subject`, must not be `None`") # noqa: E501
if subject is not None and len(subject) > 2048:
raise ValueError("Invalid value for `subject`, length must be less than or equal to `2048`") # noqa: E501
if subject is not None and len(subject) < 1:
raise ValueError("Invalid value for `subject`, length must be greater than or equal to `1`") # noqa: E501
self._subject = subject
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CertificateServerCertificate):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
klueless-io/k_dsl
|
lib/k_dsl/resources/factories/json_document_factory.rb
|
<reponame>klueless-io/k_dsl<gh_stars>0
# frozen_string_literal: true
require 'csv'
module KDsl
module Resources
module Factories
# JsonDocumentFactory can handle JSON content to produce a document
class JsonDocumentFactory < DocumentFactory
def initialize(resource)
super(resource, KDsl::Resources::Resource::TYPE_JSON)
end
def create_documents
@document = add_document(new_document)
end
def parse_content
data = JSON.parse(content)
@document.set_data(data)
end
def debug
L.ostruct(KDsl::Util.data.to_struct(@document.data))
end
end
end
end
end
|
olafurpg/mbrowse
|
sbt-metadoc/src/main/scala/metadoc.sbt/MetadocPlugin.scala
|
<filename>sbt-metadoc/src/main/scala/metadoc.sbt/MetadocPlugin.scala
package metadoc.sbt
import sbt._
import sbt.Keys._
/**
* Generate a staic Metadoc site.
*
* == Usage ==
*
* This plugin must be explicitly enabled in the project that generates the
* static metadoc site. To enable it add the following line
* to your `.sbt` file:
* {{{
* enablePlugins(MetadocPlugin)
* }}}
*
* The static site includes sources for projects that enable the semanticdb-scalac
* compiler plugin, see http://scalameta.org/tutorial/#semanticdb-scalac.
* To enable the compiler plugin, add the following to your projects settings
*
* {{{
* lazy val projectToIncludeSourcesForMetadocSite = project.settings(
* metadocSettings // important, must *appear* after scalacOptions.
* )
* }}}
*
* By default, semantic data is read from `metadocClasspath` which is
* automatically populated based on the various filter settings.
*/
object MetadocPlugin extends AutoPlugin {
object autoImport {
val Metadoc = config("metadoc")
val metadocSettings = MetadocPlugin.metadocSettings
val metadocScopeFilter =
settingKey[ScopeFilter]("Control sources to be included in metadoc.")
val metadocProjectFilter = settingKey[ScopeFilter.ProjectFilter](
"Control projects to be included in metadoc."
)
val metadocConfigurationFilter =
settingKey[ScopeFilter.ConfigurationFilter](
"Control configurations to be included in metadoc."
)
val metadocClasspath =
taskKey[Seq[Classpath]]("Class directories to be included in metadoc")
val metadoc = taskKey[File]("Generate a static Metadoc site")
}
import autoImport._
override def requires = plugins.JvmPlugin
override def trigger: PluginTrigger = allRequirements
lazy val metadocSettings: List[Def.Setting[_]] = List(
addCompilerPlugin(
"org.scalameta" % "semanticdb-scalac" % BuildInfo.scalametaVersion cross CrossVersion.full
),
scalacOptions ++= Seq(
"-Yrangepos",
"-Xplugin-require:semanticdb"
)
)
lazy val classpathTask = Def.taskDyn {
fullClasspath.all(metadocScopeFilter.value)
}
override def projectSettings: Seq[Setting[_]] = Seq(
ivyConfigurations += Metadoc,
libraryDependencies ++= List(
// Explicitly set the Scala version dependency so the resolution doesn't pick
// up the Scala version of the project the plugin is enabled in.
"org.scala-lang" % "scala-reflect" % BuildInfo.scalaVersion % Metadoc,
"org.scalameta" % s"metadoc-cli_${BuildInfo.scalaBinaryVersion}" % BuildInfo.version % Metadoc
),
metadocClasspath := classpathTask.value,
metadocScopeFilter := ScopeFilter(
metadocProjectFilter.value,
metadocConfigurationFilter.value
),
metadocProjectFilter := inAnyProject,
metadocConfigurationFilter := inConfigurations(Compile, Test),
target in metadoc := target.value / "metadoc",
mainClass in Metadoc := Some("metadoc.cli.MetadocCli"),
fullClasspath in Metadoc := Classpaths
.managedJars(Metadoc, classpathTypes.value, update.value),
runner in (Metadoc, run) := {
val forkOptions = ForkOptions(
bootJars = Nil,
javaHome = javaHome.value,
connectInput = connectInput.value,
outputStrategy = outputStrategy.value,
runJVMOptions = javaOptions.value,
workingDirectory = Some(baseDirectory.value),
envVars = envVars.value
)
new ForkRun(forkOptions)
},
metadoc := {
val output = (target in metadoc).value
val classpath = metadocClasspath.value.flatten
val classDirectories = Attributed
.data(classpath)
.collect {
case entry if entry.isDirectory => entry.getAbsolutePath
}
.distinct
val options = Seq(
"--clean-target-first",
"--target",
output.getAbsolutePath
) ++ classDirectories
(runner in (Metadoc, run)).value.run(
(mainClass in Metadoc).value.get,
Attributed.data((fullClasspath in Metadoc).value),
options,
streams.value.log
)
output
}
)
}
|
0x27/coyim
|
xmpp/streams.go
|
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package xmpp implements the XMPP IM protocol, as specified in RFC 6120 and
// 6121.
package xmpp
import (
"encoding/xml"
"errors"
"fmt"
)
//Send an initial stream header and receive the features required for
//continuation of the stream negotiation process.
//RFC 6120 section 4.3
func (c *Conn) sendInitialStreamHeader() error {
if _, err := fmt.Fprintf(c.out, "<?xml version='1.0'?><stream:stream to='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>\n", xmlEscape(c.originDomain), NsClient, NsStream); err != nil {
return err
}
se, err := nextStart(c.in)
if err != nil {
return err
}
if se.Name.Space != NsStream || se.Name.Local != "stream" {
//TODO: should send bad-namespace-prefix error?
return errors.New("xmpp: expected <stream> but got <" + se.Name.Local + "> in " + se.Name.Space)
}
//TODO: there must be an ID in the response stream header
//TODO: there must be an xml:lang in the response stream header
//RFC 6120, Section 4.7.3
// Stream features MUST follow the response stream header
// RFC 6120, section 4.3.2
if err := c.in.DecodeElement(&c.features, nil); err != nil {
//TODO: should send bad-format error?
return errors.New("xmpp: error to unmarshal <features>: " + err.Error())
}
return nil
}
// RFC 3920 C.1 Streams name space
//TODO RFC 6120 obsoletes RFC 3920
type streamFeatures struct {
XMLName xml.Name `xml:"http://etherx.jabber.org/streams features"`
StartTLS tlsStartTLS
Mechanisms saslMechanisms
Bind bindBind
InBandRegistration *inBandRegistration
// This is a hack for now to get around the fact that the new encoding/xml
// doesn't unmarshal to XMLName elements.
Session *string `xml:"session"`
//TODO: Support additional features, like
//https://xmpp.org/extensions/xep-0115.html
//Roster versioning: rfc6121 section 2.6
//and the features described here
//https://xmpp.org/registrar/stream-features.html
any []Any `xml:",any,omitempty"`
}
// StreamClose represents a request to close the stream
type StreamClose struct{}
|
guedeWebGate/org.openntf.base
|
org.openntf.base.jaxb.dxl/src/org/openntf/base/jaxb/dxl/Databaseinfo.java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.12.23 at 02:06:11 PM CET
//
package org.openntf.base.jaxb.dxl;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for databaseinfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="databaseinfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="datamodified" type="{http://www.lotus.com/dxl}datamodified" minOccurs="0"/>
* <element name="designmodified" type="{http://www.lotus.com/dxl}designmodified" minOccurs="0"/>
* <element name="created" type="{http://www.lotus.com/dxl}created" minOccurs="0"/>
* <element name="modified" type="{http://www.lotus.com/dxl}modified" minOccurs="0"/>
* </sequence>
* <attribute name="dbid" type="{http://www.lotus.com/dxl}noteshex" />
* <attribute name="replicaid" type="{http://www.lotus.com/dxl}noteshex" />
* <attribute name="odsversion" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="diskspace" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="numberofdocuments" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="percentused" type="{http://www.w3.org/2001/XMLSchema}float" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "databaseinfo", namespace = "http://www.lotus.com/dxl", propOrder = {
"datamodified",
"designmodified",
"created",
"modified"
})
public class Databaseinfo {
protected Datamodified datamodified;
protected Designmodified designmodified;
protected Created created;
protected Modified modified;
@XmlAttribute
protected String dbid;
@XmlAttribute
protected String replicaid;
@XmlAttribute
protected BigInteger odsversion;
@XmlAttribute
protected BigInteger diskspace;
@XmlAttribute
protected BigInteger numberofdocuments;
@XmlAttribute
protected Float percentused;
/**
* Gets the value of the datamodified property.
*
* @return
* possible object is
* {@link Datamodified }
*
*/
public Datamodified getDatamodified() {
return datamodified;
}
/**
* Sets the value of the datamodified property.
*
* @param value
* allowed object is
* {@link Datamodified }
*
*/
public void setDatamodified(Datamodified value) {
this.datamodified = value;
}
/**
* Gets the value of the designmodified property.
*
* @return
* possible object is
* {@link Designmodified }
*
*/
public Designmodified getDesignmodified() {
return designmodified;
}
/**
* Sets the value of the designmodified property.
*
* @param value
* allowed object is
* {@link Designmodified }
*
*/
public void setDesignmodified(Designmodified value) {
this.designmodified = value;
}
/**
* Gets the value of the created property.
*
* @return
* possible object is
* {@link Created }
*
*/
public Created getCreated() {
return created;
}
/**
* Sets the value of the created property.
*
* @param value
* allowed object is
* {@link Created }
*
*/
public void setCreated(Created value) {
this.created = value;
}
/**
* Gets the value of the modified property.
*
* @return
* possible object is
* {@link Modified }
*
*/
public Modified getModified() {
return modified;
}
/**
* Sets the value of the modified property.
*
* @param value
* allowed object is
* {@link Modified }
*
*/
public void setModified(Modified value) {
this.modified = value;
}
/**
* Gets the value of the dbid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDbid() {
return dbid;
}
/**
* Sets the value of the dbid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDbid(String value) {
this.dbid = value;
}
/**
* Gets the value of the replicaid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReplicaid() {
return replicaid;
}
/**
* Sets the value of the replicaid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReplicaid(String value) {
this.replicaid = value;
}
/**
* Gets the value of the odsversion property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getOdsversion() {
return odsversion;
}
/**
* Sets the value of the odsversion property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setOdsversion(BigInteger value) {
this.odsversion = value;
}
/**
* Gets the value of the diskspace property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getDiskspace() {
return diskspace;
}
/**
* Sets the value of the diskspace property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setDiskspace(BigInteger value) {
this.diskspace = value;
}
/**
* Gets the value of the numberofdocuments property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumberofdocuments() {
return numberofdocuments;
}
/**
* Sets the value of the numberofdocuments property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumberofdocuments(BigInteger value) {
this.numberofdocuments = value;
}
/**
* Gets the value of the percentused property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getPercentused() {
return percentused;
}
/**
* Sets the value of the percentused property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setPercentused(Float value) {
this.percentused = value;
}
}
|
bydan/pre
|
erp_ejb/src_cartera/com/bydan/erp/cartera/business/logic/TipoViviendaLogic.java
|
<filename>erp_ejb/src_cartera/com/bydan/erp/cartera/business/logic/TipoViviendaLogic.java<gh_stars>0
/*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.cartera.business.logic;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.Date;
import java.util.Calendar;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.log4j.Logger;
//VALIDACION
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import com.bydan.framework.ConstantesCommon;
import com.bydan.framework.erp.business.entity.GeneralEntityLogic;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.DatoGeneralMinimo;
import com.bydan.framework.erp.business.entity.DatoGeneralMaximo;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.util.*;
import com.bydan.erp.cartera.util.*;
import com.bydan.erp.cartera.util.TipoViviendaConstantesFunciones;
import com.bydan.erp.cartera.util.TipoViviendaParameterReturnGeneral;
//import com.bydan.erp.cartera.util.TipoViviendaParameterGeneral;
import com.bydan.erp.cartera.business.entity.TipoVivienda;
import com.bydan.erp.cartera.business.logic.TipoViviendaLogicAdditional;
import com.bydan.erp.cartera.business.dataaccess.*;
import com.bydan.erp.cartera.business.entity.*;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.seguridad.business.logic.*;
import com.bydan.erp.seguridad.util.*;
import com.bydan.erp.seguridad.business.dataaccess.*;
@SuppressWarnings("unused")
public class TipoViviendaLogic extends GeneralEntityLogic {
static Logger logger = Logger.getLogger(TipoViviendaLogic.class);
protected TipoViviendaDataAccess tipoviviendaDataAccess;
protected TipoVivienda tipovivienda;
protected List<TipoVivienda> tipoviviendas;
protected Object tipoviviendaObject;
protected List<Object> tipoviviendasObject;
public static ClassValidator<TipoVivienda> tipoviviendaValidator = new ClassValidator<TipoVivienda>(TipoVivienda.class);
public InvalidValue[] invalidValues=null;
public StringBuilder stringBuilder=new StringBuilder();
public Boolean conMostrarMensajesStringBuilder=true;
protected TipoViviendaLogicAdditional tipoviviendaLogicAdditional=null;
public TipoViviendaLogicAdditional getTipoViviendaLogicAdditional() {
return this.tipoviviendaLogicAdditional;
}
public void setTipoViviendaLogicAdditional(TipoViviendaLogicAdditional tipoviviendaLogicAdditional) {
try {
this.tipoviviendaLogicAdditional=tipoviviendaLogicAdditional;
} catch(Exception e) {
;
}
}
/*
protected ArrayList<DatoGeneral> arrDatoGeneral;
protected Connexion connexion;
protected DatosCliente datosCliente;
protected ConnexionType connexionType;
protected ParameterDbType parameterDbType;
protected EntityManagerFactory entityManagerFactory;
protected DatosDeep datosDeep;
protected Boolean isConDeep=false;
*/
public TipoViviendaLogic()throws SQLException,Exception {
super();
try {
this.tipoviviendaDataAccess = new TipoViviendaDataAccess();
this.tipoviviendas= new ArrayList<TipoVivienda>();
this.tipovivienda= new TipoVivienda();
this.tipoviviendaObject=new Object();
this.tipoviviendasObject=new ArrayList<Object>();
/*
this.connexion=new Connexion();
this.datosCliente=new DatosCliente();
this.arrDatoGeneral= new ArrayList<DatoGeneral>();
//INICIALIZA PARAMETROS CONEXION
this.connexionType=Constantes.CONNEXIONTYPE;
this.parameterDbType=Constantes.PARAMETERDBTYPE;
if(Constantes.CONNEXIONTYPE.equals(ConnexionType.HIBERNATE)) {
this.entityManagerFactory=ConstantesCommon.JPAENTITYMANAGERFACTORY;
}
this.datosDeep=new DatosDeep();
this.isConDeep=false;
*/
this.tipoviviendaDataAccess.setConnexionType(this.connexionType);
this.tipoviviendaDataAccess.setParameterDbType(this.parameterDbType);
this.invalidValues=new InvalidValue[0];
this.stringBuilder=new StringBuilder();
this.conMostrarMensajesStringBuilder=true;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public TipoViviendaLogic(Connexion newConnexion)throws Exception {
super(newConnexion);
try {
//this.connexion=newConnexion;
this.tipoviviendaDataAccess = new TipoViviendaDataAccess();
this.tipoviviendas= new ArrayList<TipoVivienda>();
this.tipovivienda= new TipoVivienda();
this.tipoviviendaObject=new Object();
this.tipoviviendasObject=new ArrayList<Object>();
/*
this.datosCliente=new DatosCliente();
this.arrDatoGeneral= new ArrayList<DatoGeneral>();
//INICIALIZA PARAMETROS CONEXION
this.connexionType=Constantes.CONNEXIONTYPE;
this.parameterDbType=Constantes.PARAMETERDBTYPE;
if(Constantes.CONNEXIONTYPE.equals(ConnexionType.HIBERNATE)) {
this.entityManagerFactory=ConstantesCommon.JPAENTITYMANAGERFACTORY;
}
this.datosDeep=new DatosDeep();
this.isConDeep=false;
*/
this.tipoviviendaDataAccess.setConnexionType(this.connexionType);
this.tipoviviendaDataAccess.setParameterDbType(this.parameterDbType);
this.invalidValues=new InvalidValue[0];
this.stringBuilder=new StringBuilder();
this.conMostrarMensajesStringBuilder=true;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public TipoVivienda getTipoVivienda() throws Exception {
TipoViviendaLogicAdditional.checkTipoViviendaToGet(tipovivienda,this.datosCliente,this.arrDatoGeneral);
TipoViviendaLogicAdditional.updateTipoViviendaToGet(tipovivienda,this.arrDatoGeneral);
return tipovivienda;
}
public void setTipoVivienda(TipoVivienda newTipoVivienda) {
this.tipovivienda = newTipoVivienda;
}
public TipoViviendaDataAccess getTipoViviendaDataAccess() {
return tipoviviendaDataAccess;
}
public void setTipoViviendaDataAccess(TipoViviendaDataAccess newtipoviviendaDataAccess) {
this.tipoviviendaDataAccess = newtipoviviendaDataAccess;
}
public List<TipoVivienda> getTipoViviendas() throws Exception {
this.quitarTipoViviendasNulos();
TipoViviendaLogicAdditional.checkTipoViviendaToGets(tipoviviendas,this.datosCliente,this.arrDatoGeneral);
for (TipoVivienda tipoviviendaLocal: tipoviviendas ) {
TipoViviendaLogicAdditional.updateTipoViviendaToGet(tipoviviendaLocal,this.arrDatoGeneral);
}
return tipoviviendas;
}
public void setTipoViviendas(List<TipoVivienda> newTipoViviendas) {
this.tipoviviendas = newTipoViviendas;
}
public Object getTipoViviendaObject() {
this.tipoviviendaObject=this.tipoviviendaDataAccess.getEntityObject();
return this.tipoviviendaObject;
}
public void setTipoViviendaObject(Object newTipoViviendaObject) {
this.tipoviviendaObject = newTipoViviendaObject;
}
public List<Object> getTipoViviendasObject() {
this.tipoviviendasObject=this.tipoviviendaDataAccess.getEntitiesObject();
return this.tipoviviendasObject;
}
public void setTipoViviendasObject(List<Object> newTipoViviendasObject) {
this.tipoviviendasObject = newTipoViviendasObject;
}
/*
public Connexion getConnexion() {
return this.connexion;
}
public void setConnexion(Connexion newConnexion) {
this.connexion=newConnexion;
}
public DatosCliente getDatosCliente() {
return datosCliente;
}
*/
public void setDatosCliente(DatosCliente datosCliente) {
this.datosCliente = datosCliente;
if(this.tipoviviendaDataAccess!=null) {
this.tipoviviendaDataAccess.setDatosCliente(datosCliente);
}
}
/*
public DatosDeep getDatosDeep() {
return this.datosDeep;
}
public void setDatosDeep(DatosDeep datosDeep) {
this.datosDeep = datosDeep;
}
public void setDatosDeepFromDatosCliente() {
this.datosDeep = this.datosCliente.getDatosDeep();
this.isConDeep=this.datosCliente.getIsConDeep();
}
public Boolean getIsConDeep() {
return this.isConDeep;
}
public void setIsConDeep(Boolean isConDeep) {
this.isConDeep = isConDeep;
}
public ArrayList<DatoGeneral> getArrDatoGeneral() {
return arrDatoGeneral;
}
public void setArrDatoGeneral(ArrayList<DatoGeneral> arrDatoGeneral) {
this.arrDatoGeneral = arrDatoGeneral;
}
public ConnexionType getConnexionType() {
return connexionType;
}
public void setConnexionType(ConnexionType connexionType) {
this.connexionType = connexionType;
}
public ParameterDbType getParameterDbType() {
return parameterDbType;
}
public void setParameterDbType(ParameterDbType parameterDbType) {
this.parameterDbType = parameterDbType;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
*/
public void setDatosDeepParametros(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String strTituloMensaje) {
this.datosDeep.setIsDeep(isDeep);
this.datosDeep.setDeepLoadType(deepLoadType);
this.datosDeep.setClases(clases);
this.datosDeep.setSTituloMensaje(strTituloMensaje);
}
public InvalidValue[] getInvalidValues() {
return invalidValues;
}
public void setInvalidValues(InvalidValue[] invalidValues) {
this.invalidValues = invalidValues;
}
public StringBuilder getStringBuilder() {
return this.stringBuilder;
}
public void setStringBuilder(StringBuilder stringBuilder) {
this.stringBuilder = stringBuilder;
}
public Boolean getConMostrarMensajesStringBuilder() {
return this.conMostrarMensajesStringBuilder;
}
public void setConMostrarMensajesStringBuilder(Boolean conMostrarMensajesStringBuilder) {
this.conMostrarMensajesStringBuilder = conMostrarMensajesStringBuilder;
}
public void getNewConnexionToDeep()throws Exception {
//this.getNewConnexionToDeep();
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,"");connexion.begin();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void getNewConnexionToDeep(String sDetalle)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,sDetalle);connexion.begin();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void commitNewConnexionToDeep()throws Exception {
try {
this.connexion.commit();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void rollbackNewConnexionToDeep()throws Exception {
try {
this.connexion.rollback();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void closeNewConnexionToDeep()throws Exception {
try {
this.connexion.close();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void executeQueryWithConnection(String sQueryExecute) throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-executeQueryWithConnection");connexion.begin();
tipoviviendaDataAccess.executeQuery(connexion, sQueryExecute);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void executeQuery(String sQueryExecute) throws Exception {
try {
tipoviviendaDataAccess.executeQuery(connexion, sQueryExecute);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(Long id) throws Exception {
tipovivienda = new TipoVivienda();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
tipovivienda=tipoviviendaDataAccess.getEntity(connexion, id);
if(this.isConDeep) {
this.deepLoad(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntity(Long id) throws Exception {
tipovivienda = new TipoVivienda();
try {
tipovivienda=tipoviviendaDataAccess.getEntity(connexion, id);
if(this.isConDeep) {
this.deepLoad(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(QueryWhereSelectParameters queryWhereSelectParameters) throws Exception {
tipovivienda = new TipoVivienda();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
tipovivienda=tipoviviendaDataAccess.getEntity(connexion, queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoad(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntityWithConnection(String sFinalQuery) throws Exception {
tipovivienda = new TipoVivienda();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntityWithConnection(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
}
}
public void getEntity(QueryWhereSelectParameters queryWhereSelectParameters) throws Exception {
tipovivienda = new TipoVivienda();
try {
tipovivienda=tipoviviendaDataAccess.getEntity(connexion, queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoad(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntity(String sFinalQuery) throws Exception {
tipovivienda = new TipoVivienda();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntity(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
;
}
}
public DatoGeneralMinimo getEntityDatoGeneralMinimoGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
DatoGeneralMinimo datoGeneralMinimo = new DatoGeneralMinimo();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntityDatoGeneralMinimoGenericoWithConnection");connexion.begin();
datoGeneralMinimo =tipoviviendaDataAccess.getEntityDatoGeneralMinimoGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGeneralMinimo;
}
public DatoGeneralMinimo getEntityDatoGeneralMinimoGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
DatoGeneralMinimo datoGeneralMinimo = new DatoGeneralMinimo();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGeneralMinimo=tipoviviendaDataAccess.getEntityDatoGeneralMinimoGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGeneralMinimo;
}
public ArrayList<DatoGeneral> getEntitiesDatoGeneralGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneral> datoGenerals = new ArrayList<DatoGeneral>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesDatoGeneralGenericoWithConnection");connexion.begin();
datoGenerals =tipoviviendaDataAccess.getEntitiesDatoGeneralGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGenerals;
}
public ArrayList<DatoGeneral> getEntitiesDatoGeneralGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneral> datoGenerals = new ArrayList<DatoGeneral>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGenerals=tipoviviendaDataAccess.getEntitiesDatoGeneralGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGenerals;
}
public ArrayList<DatoGeneralMaximo> getEntitiesDatoGeneralMaximoGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneralMaximo> datoGeneralMaximos = new ArrayList<DatoGeneralMaximo>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesDatoGeneralMaximoGenericoWithConnection");connexion.begin();
datoGeneralMaximos =tipoviviendaDataAccess.getEntitiesDatoGeneralMaximoGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGeneralMaximos;
}
public ArrayList<DatoGeneralMaximo> getEntitiesDatoGeneralMaximoGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneralMaximo> datoGeneralMaximos = new ArrayList<DatoGeneralMaximo>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGeneralMaximos=tipoviviendaDataAccess.getEntitiesDatoGeneralMaximoGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGeneralMaximos;
}
public void getEntitiesWithConnection(QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIES","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntitiesWithConnection(String sFinalQuery)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntitiesWithConnection(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
}
}
public void getEntities(QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIES","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntities(String sFinalQuery)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntities(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
;
}
}
public void getEntitiesWithConnection(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntities(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
/**
* Trae cualquier tipo de query select
* @conMapGenerico Si es true, trae todo como objeto generico, Si es false trae query en campos de la clase, usando unicamente los determinados en listColumns y deepLoadType
* @deepLoadType Si conMapGenerico es false trae query select con las columnas de listColumns, incluyento o excludendo deacuerdo a deepLoadType
*/
public void getEntitiesWithConnection(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntities(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipovivienda=tipoviviendaDataAccess.getEntity(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarTipoVivienda(tipovivienda);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntity(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
tipovivienda = new TipoVivienda();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipovivienda=tipoviviendaDataAccess.getEntity(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarTipoVivienda(tipovivienda);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntitiesSimpleQueryBuildWithConnection(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getEntitiesSimpleQueryBuildWithConnection");connexion.begin();
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESSIMPLEQUERY","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntitiesSimpleQueryBuild(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntitiesSimpleQueryBuild(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESSIMPLEQUERY","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntitiesSimpleQueryBuild(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getTodosTipoViviendasWithConnection(String sFinalQuery,Pagination pagination)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getTodosTipoViviendasWithConnection");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters("");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"TODOS","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getTodosTipoViviendas(String sFinalQuery,Pagination pagination)throws Exception {
tipoviviendas = new ArrayList<TipoVivienda>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters("");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"TODOS","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,queryWhereSelectParameters);
this.validarGuardarManejarTipoVivienda(tipoviviendas);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public Boolean validarGuardarTipoVivienda(TipoVivienda tipovivienda) throws Exception {
Boolean estaValidado=false;
if(tipovivienda.getIsNew() || tipovivienda.getIsChanged()) {
this.invalidValues = tipoviviendaValidator.getInvalidValues(tipovivienda);
if(this.invalidValues==null || this.invalidValues.length<=0) {
estaValidado=true;
} else {
this.guardarInvalidValues(tipovivienda);
}
} else {
estaValidado=true;
}
return estaValidado;
}
public Boolean validarGuardarTipoVivienda(List<TipoVivienda> TipoViviendas) throws Exception {
Boolean estaValidado=true;
Boolean estaValidadoObjeto=false;
for(TipoVivienda tipoviviendaLocal:tipoviviendas) {
estaValidadoObjeto=this.validarGuardarTipoVivienda(tipoviviendaLocal);
if(!estaValidadoObjeto) {
if(estaValidado) {
estaValidado=false;
}
}
}
return estaValidado;
}
public void validarGuardarManejarTipoVivienda(List<TipoVivienda> TipoViviendas) throws Exception {
if(Constantes2.ISDEVELOPING_VALIDACIONDATOS_TRAER) {
if(!this.validarGuardarTipoVivienda(tipoviviendas)) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
}
}
public void validarGuardarManejarTipoVivienda(TipoVivienda TipoVivienda) throws Exception {
if(Constantes2.ISDEVELOPING_VALIDACIONDATOS_TRAER) {
if(!this.validarGuardarTipoVivienda(tipovivienda)) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
}
}
public void guardarInvalidValues(TipoVivienda tipovivienda) throws Exception {
String sCampo="";
String sMensajeCampo="";
String sMensaje="";
String sIdMensaje="";
sIdMensaje="\r\nID="+tipovivienda.getId();
sMensaje+=sIdMensaje;
for (InvalidValue invalidValue : this.invalidValues) {
sCampo=TipoViviendaConstantesFunciones.getTipoViviendaLabelDesdeNombre(invalidValue.getPropertyName());
sMensajeCampo=invalidValue.getMessage();
sMensaje+="\r\n"+sCampo+"->"+sMensajeCampo;
//MOSTRAR CAMPOS INVALIDOS
}
if(!sMensaje.equals("")) {
this.stringBuilder.append(sMensaje);
}
}
public void manejarMensajesStringBuilder(String sMensajeExcepcion) throws Exception {
String sMensajeDetalleExcepcion="";
sMensajeDetalleExcepcion=this.stringBuilder.toString();
if(!sMensajeDetalleExcepcion.equals("")) {
Funciones.manageException(logger,this.stringBuilder,this.datosCliente.getDatosExportar().getsPath(),"tipovivienda","validar_datos");
if(ConstantesMensajes.CON_MOSTRAR_MENSAJES_DETALLE) {
throw new Exception(TipoViviendaConstantesFunciones.SCLASSWEBTITULO + sMensajeDetalleExcepcion);//ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS
} else {
throw new Exception(TipoViviendaConstantesFunciones.SCLASSWEBTITULO + sMensajeExcepcion);//ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS
}
}
}
public void saveTipoViviendaWithConnection()throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-saveTipoViviendaWithConnection");connexion.begin();
TipoViviendaLogicAdditional.checkTipoViviendaToSave(this.tipovivienda,this.datosCliente,connexion,this.arrDatoGeneral);
TipoViviendaLogicAdditional.updateTipoViviendaToSave(this.tipovivienda,this.arrDatoGeneral);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),this.tipovivienda,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
//TEMPORAL
//this.getSetVersionRowTipoVivienda();
this.stringBuilder=new StringBuilder();
if(this.validarGuardarTipoVivienda(this.tipovivienda)) {
TipoViviendaDataAccess.save(this.tipovivienda, connexion);
} else {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSave(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
}
TipoViviendaLogicAdditional.checkTipoViviendaToSaveAfter(this.tipovivienda,this.datosCliente,connexion,this.arrDatoGeneral);
//SOLO FUNCIONA PARA ACTUALIZAR Y CON CONNEXION
this.getSetVersionRowTipoVivienda();
connexion.commit();
if(this.tipovivienda.getIsDeleted()) {
this.tipovivienda=null;
}
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void saveTipoVivienda()throws Exception {
try {
TipoViviendaLogicAdditional.checkTipoViviendaToSave(this.tipovivienda,this.datosCliente,connexion,this.arrDatoGeneral);
TipoViviendaLogicAdditional.updateTipoViviendaToSave(this.tipovivienda,this.arrDatoGeneral);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),this.tipovivienda,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
this.stringBuilder=new StringBuilder();
if(this.validarGuardarTipoVivienda(this.tipovivienda)) {
TipoViviendaDataAccess.save(this.tipovivienda, connexion);
} else {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSave(this.tipovivienda,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
}
TipoViviendaLogicAdditional.checkTipoViviendaToSaveAfter(this.tipovivienda,this.datosCliente,connexion,this.arrDatoGeneral);
if(this.tipovivienda.getIsDeleted()) {
this.tipovivienda=null;
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void saveTipoViviendasWithConnection()throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-saveTipoViviendasWithConnection");connexion.begin();
TipoViviendaLogicAdditional.checkTipoViviendaToSaves(tipoviviendas,this.datosCliente,connexion,this.arrDatoGeneral);
//TEMPORAL
//this.getSetVersionRowTipoViviendas();
Boolean validadoTodosTipoVivienda=true;
this.stringBuilder=new StringBuilder();
for(TipoVivienda tipoviviendaLocal:tipoviviendas) {
if(tipoviviendaLocal.getsType().contains(Constantes2.S_TOTALES)) {
continue;
}
TipoViviendaLogicAdditional.updateTipoViviendaToSave(tipoviviendaLocal,this.arrDatoGeneral);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),tipoviviendaLocal,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
if(this.validarGuardarTipoVivienda(tipoviviendaLocal)) {
TipoViviendaDataAccess.save(tipoviviendaLocal, connexion);
} else {
validadoTodosTipoVivienda=false;
}
}
if(!validadoTodosTipoVivienda) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSaves(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(), this.datosDeep.getSTituloMensaje());
}
TipoViviendaLogicAdditional.checkTipoViviendaToSavesAfter(tipoviviendas,this.datosCliente,connexion,this.arrDatoGeneral);
//SOLO FUNCIONA PARA ACTUALIZAR Y CON CONNEXION
this.getSetVersionRowTipoViviendas();
connexion.commit();
this.quitarTipoViviendasEliminados();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void saveTipoViviendas()throws Exception {
try {
TipoViviendaLogicAdditional.checkTipoViviendaToSaves(tipoviviendas,this.datosCliente,connexion,this.arrDatoGeneral);
Boolean validadoTodosTipoVivienda=true;
this.stringBuilder=new StringBuilder();
for(TipoVivienda tipoviviendaLocal:tipoviviendas) {
if(tipoviviendaLocal.getsType().contains(Constantes2.S_TOTALES)) {
continue;
}
TipoViviendaLogicAdditional.updateTipoViviendaToSave(tipoviviendaLocal,this.arrDatoGeneral);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),tipoviviendaLocal,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
if(this.validarGuardarTipoVivienda(tipoviviendaLocal)) {
TipoViviendaDataAccess.save(tipoviviendaLocal, connexion);
} else {
validadoTodosTipoVivienda=false;
}
}
if(!validadoTodosTipoVivienda) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSaves(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(), this.datosDeep.getSTituloMensaje());
}
TipoViviendaLogicAdditional.checkTipoViviendaToSavesAfter(tipoviviendas,this.datosCliente,connexion,this.arrDatoGeneral);
this.quitarTipoViviendasEliminados();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public TipoViviendaParameterReturnGeneral procesarAccionTipoViviendas(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,String sProceso,List<TipoVivienda> tipoviviendas,TipoViviendaParameterReturnGeneral tipoviviendaParameterGeneral)throws Exception {
try {
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral=new TipoViviendaParameterReturnGeneral();
TipoViviendaLogicAdditional.procesarAccions(parametroGeneralUsuario,modulo,opcion,usuario,this,sProceso,tipoviviendas,tipoviviendaParameterGeneral,tipoviviendaReturnGeneral);
return tipoviviendaReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public TipoViviendaParameterReturnGeneral procesarAccionTipoViviendasWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,String sProceso,List<TipoVivienda> tipoviviendas,TipoViviendaParameterReturnGeneral tipoviviendaParameterGeneral)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-procesarAccionTipoViviendasWithConnection");connexion.begin();
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral=new TipoViviendaParameterReturnGeneral();
TipoViviendaLogicAdditional.procesarAccions(parametroGeneralUsuario,modulo,opcion,usuario,this,sProceso,tipoviviendas,tipoviviendaParameterGeneral,tipoviviendaReturnGeneral);
this.connexion.commit();
return tipoviviendaReturnGeneral;
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public TipoViviendaParameterReturnGeneral procesarEventosTipoViviendas(ParametroGeneralUsuario parametroGeneralUsuario,Modulo moduloActual,Opcion opcionActual,Usuario usuarioActual,EventoGlobalTipo eventoGlobalTipo,ControlTipo controlTipo,EventoTipo eventoTipo,EventoSubTipo eventoSubTipo,String sTipo,List<TipoVivienda> tipoviviendas,TipoVivienda tipovivienda,TipoViviendaParameterReturnGeneral tipoviviendaParameterGeneral,Boolean isEsNuevoTipoVivienda,ArrayList<Classe> clases)throws Exception {
try {
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral=new TipoViviendaParameterReturnGeneral();
//SI ES PARA FORMULARIO-> NUEVO PREPARAR, RECARGAR POR DEFECTO FORMULARIO (PARA MANEJAR VALORES POR DEFECTO)
if(eventoGlobalTipo.equals(EventoGlobalTipo.FORM_RECARGAR) && controlTipo.equals(ControlTipo.FORM)
&& eventoTipo.equals(EventoTipo.LOAD) && eventoSubTipo.equals(EventoSubTipo.NEW)
&& sTipo.equals("FORM")) {
tipoviviendaReturnGeneral.setConRecargarPropiedades(true);
}
TipoViviendaLogicAdditional.procesarEventos(parametroGeneralUsuario,moduloActual,opcionActual,usuarioActual,this,eventoGlobalTipo,controlTipo,eventoTipo,eventoSubTipo,sTipo,tipoviviendas,tipovivienda,tipoviviendaParameterGeneral,tipoviviendaReturnGeneral,isEsNuevoTipoVivienda,clases);
return tipoviviendaReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public TipoViviendaParameterReturnGeneral procesarEventosTipoViviendasWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo moduloActual,Opcion opcionActual,Usuario usuarioActual,EventoGlobalTipo eventoGlobalTipo,ControlTipo controlTipo,EventoTipo eventoTipo,EventoSubTipo eventoSubTipo,String sTipo,List<TipoVivienda> tipoviviendas,TipoVivienda tipovivienda,TipoViviendaParameterReturnGeneral tipoviviendaParameterGeneral,Boolean isEsNuevoTipoVivienda,ArrayList<Classe> clases)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-procesarEventosTipoViviendasWithConnection");connexion.begin();
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral=new TipoViviendaParameterReturnGeneral();
tipoviviendaReturnGeneral.setTipoVivienda(tipovivienda);
//SI ES PARA FORMULARIO-> NUEVO PREPARAR, RECARGAR POR DEFECTO FORMULARIO (PARA MANEJAR VALORES POR DEFECTO)
if(eventoGlobalTipo.equals(EventoGlobalTipo.FORM_RECARGAR) && controlTipo.equals(ControlTipo.FORM)
&& eventoTipo.equals(EventoTipo.LOAD) && eventoSubTipo.equals(EventoSubTipo.NEW)
&& sTipo.equals("FORM")) {
tipoviviendaReturnGeneral.setConRecargarPropiedades(true);
}
TipoViviendaLogicAdditional.procesarEventos(parametroGeneralUsuario,moduloActual,opcionActual,usuarioActual,this,eventoGlobalTipo,controlTipo,eventoTipo,eventoSubTipo,sTipo,tipoviviendas,tipovivienda,tipoviviendaParameterGeneral,tipoviviendaReturnGeneral,isEsNuevoTipoVivienda,clases);
this.connexion.commit();
return tipoviviendaReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public TipoViviendaParameterReturnGeneral procesarImportacionTipoViviendasWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,List<DatoGeneralMinimo> datoGeneralMinimos,TipoViviendaParameterReturnGeneral tipoviviendaParameterGeneral)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-procesarImportacionTipoViviendasWithConnection");connexion.begin();
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral=new TipoViviendaParameterReturnGeneral();
Boolean esPrimero=true;
Boolean conColumnasBase=true;//SIEMPRE
String sDelimiter=Funciones2.getTipoDelimiter(parametroGeneralUsuario);
String sLinea="";
String[] arrColumnas=null;//new String[5];
Integer iColumn=0;
this.tipoviviendas=new ArrayList<TipoVivienda>();
for(DatoGeneralMinimo datoGeneralMinimo:datoGeneralMinimos) {
iColumn=0;
if(esPrimero && parametroGeneralUsuario.getcon_exportar_cabecera()) {
esPrimero=false;
continue;
}
sLinea=datoGeneralMinimo.getsDescripcion();
arrColumnas=sLinea.split(sDelimiter);
this.tipovivienda=new TipoVivienda();
if(conColumnasBase) {this.tipovivienda.setId(Long.parseLong(arrColumnas[iColumn++]));}
if(parametroGeneralUsuario.getcon_exportar_campo_version()){
this.tipovivienda.setVersionRow(Timestamp.valueOf(arrColumnas[iColumn++]));
}
this.tipovivienda.setcodigo(arrColumnas[iColumn++]);
this.tipovivienda.setnombre(arrColumnas[iColumn++]);
this.tipoviviendas.add(this.tipovivienda);
}
this.saveTipoViviendas();
this.connexion.commit();
tipoviviendaReturnGeneral.setConRetornoEstaProcesado(true);
tipoviviendaReturnGeneral.setsMensajeProceso("IMPORTADO CORRECTAMENTE");
return tipoviviendaReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public void quitarTipoViviendasEliminados() throws Exception {
List<TipoVivienda> tipoviviendasAux= new ArrayList<TipoVivienda>();
for(TipoVivienda tipovivienda:tipoviviendas) {
if(!tipovivienda.getIsDeleted()) {
tipoviviendasAux.add(tipovivienda);
}
}
tipoviviendas=tipoviviendasAux;
}
public void quitarTipoViviendasNulos() throws Exception {
List<TipoVivienda> tipoviviendasAux= new ArrayList<TipoVivienda>();
for(TipoVivienda tipovivienda : this.tipoviviendas) {
if(tipovivienda==null) {
tipoviviendasAux.add(tipovivienda);
}
}
//this.tipoviviendas=tipoviviendasAux;
this.tipoviviendas.removeAll(tipoviviendasAux);
}
public void getSetVersionRowTipoViviendaWithConnection()throws Exception {
//VERIFICA EL OBJETO NO IMPORTA ESTADO
if(tipovivienda.getIsChangedAuxiliar() && Constantes.ISSETVERSIONROWUPDATE) {
//TEMPORAL
//if((tipovivienda.getIsDeleted() || (tipovivienda.getIsChanged()&&!tipovivienda.getIsNew()))&& Constantes.ISSETVERSIONROWUPDATE) {
Timestamp timestamp=null;
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory);connexion.begin();
timestamp=tipoviviendaDataAccess.getSetVersionRowTipoVivienda(connexion,tipovivienda.getId());
if(!tipovivienda.getVersionRow().equals(timestamp)) {
tipovivienda.setVersionRow(timestamp);
}
connexion.commit();
tipovivienda.setIsChangedAuxiliar(false);
} catch(Exception e) {
connexion.rollback();
throw e;
} finally {
connexion.close();
}
}
}
private void getSetVersionRowTipoVivienda()throws Exception {
if(tipovivienda.getIsChangedAuxiliar() && Constantes.ISSETVERSIONROWUPDATE) {
//TEMPORAL
//if((tipovivienda.getIsDeleted() || (tipovivienda.getIsChanged()&&!tipovivienda.getIsNew()))&& Constantes.ISSETVERSIONROWUPDATE) {
Timestamp timestamp=tipoviviendaDataAccess.getSetVersionRowTipoVivienda(connexion,tipovivienda.getId());
try {
if(!tipovivienda.getVersionRow().equals(timestamp)) {
tipovivienda.setVersionRow(timestamp);
}
tipovivienda.setIsChangedAuxiliar(false);
} catch(Exception e) {
throw e;
} finally {
;
}
}
}
public void getSetVersionRowTipoViviendasWithConnection()throws Exception {
if(tipoviviendas!=null && Constantes.ISSETVERSIONROWUPDATE) {
try {
Timestamp timestamp=null;
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory);connexion.begin();
for(TipoVivienda tipoviviendaAux:tipoviviendas) {
//VERIFICA EL OBJETO NO IMPORTA ESTADO
//if(tipoviviendaAux.getIsChangedAuxiliar()) {
//TEMPORAL
//if(tipoviviendaAux.getIsDeleted() || (tipoviviendaAux.getIsChanged()&&!tipoviviendaAux.getIsNew())) {
timestamp=tipoviviendaDataAccess.getSetVersionRowTipoVivienda(connexion,tipoviviendaAux.getId());
if(!tipovivienda.getVersionRow().equals(timestamp)) {
tipoviviendaAux.setVersionRow(timestamp);
}
tipoviviendaAux.setIsChangedAuxiliar(false);
//}
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
throw e;
} finally {
connexion.close();
}
}
}
private void getSetVersionRowTipoViviendas()throws Exception {
if(tipoviviendas!=null && Constantes.ISSETVERSIONROWUPDATE) {
try {
Timestamp timestamp=null;
for(TipoVivienda tipoviviendaAux:tipoviviendas) {
if(tipoviviendaAux.getIsChangedAuxiliar()) {
//TEMPORAL
//if(tipoviviendaAux.getIsDeleted() || (tipoviviendaAux.getIsChanged()&&!tipoviviendaAux.getIsNew())) {
timestamp=tipoviviendaDataAccess.getSetVersionRowTipoVivienda(connexion,tipoviviendaAux.getId());
if(!tipoviviendaAux.getVersionRow().equals(timestamp)) {
tipoviviendaAux.setVersionRow(timestamp);
}
tipoviviendaAux.setIsChangedAuxiliar(false);
}
}
} catch(Exception e) {
throw e;
} finally {
;
}
}
}
public TipoViviendaParameterReturnGeneral cargarCombosLoteForeignKeyTipoViviendaWithConnection(String finalQueryGlobalEmpresa) throws Exception {
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral =new TipoViviendaParameterReturnGeneral();
ArrayList<Classe> clases=new ArrayList<Classe>();
ArrayList<String> arrClasses=new ArrayList<String>();
Classe classe=new Classe();
DatosDeep datosDeep=new DatosDeep(false,DeepLoadType.INCLUDE,clases,"");
try {
this.connexion=this.connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-cargarCombosLoteForeignKeyTipoViviendaWithConnection");connexion.begin();
tipoviviendaReturnGeneral =new TipoViviendaParameterReturnGeneral();
List<Empresa> empresasForeignKey=new ArrayList<Empresa>();
EmpresaLogic empresaLogic=new EmpresaLogic();
empresaLogic.setConnexion(this.connexion);
//empresaLogic.getEmpresaDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpresa.equals("NONE")) {
empresaLogic.getTodosEmpresas(finalQueryGlobalEmpresa,new Pagination());
empresasForeignKey=empresaLogic.getEmpresas();
}
tipoviviendaReturnGeneral.setempresasForeignKey(empresasForeignKey);
this.connexion.commit();
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
return tipoviviendaReturnGeneral;
}
public TipoViviendaParameterReturnGeneral cargarCombosLoteForeignKeyTipoVivienda(String finalQueryGlobalEmpresa) throws Exception {
TipoViviendaParameterReturnGeneral tipoviviendaReturnGeneral =new TipoViviendaParameterReturnGeneral();
ArrayList<Classe> clases=new ArrayList<Classe>();
ArrayList<String> arrClasses=new ArrayList<String>();
Classe classe=new Classe();
DatosDeep datosDeep=new DatosDeep(false,DeepLoadType.INCLUDE,clases,"");
try {
tipoviviendaReturnGeneral =new TipoViviendaParameterReturnGeneral();
List<Empresa> empresasForeignKey=new ArrayList<Empresa>();
EmpresaLogic empresaLogic=new EmpresaLogic();
empresaLogic.setConnexion(this.connexion);
//empresaLogic.getEmpresaDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpresa.equals("NONE")) {
empresaLogic.getTodosEmpresas(finalQueryGlobalEmpresa,new Pagination());
empresasForeignKey=empresaLogic.getEmpresas();
}
tipoviviendaReturnGeneral.setempresasForeignKey(empresasForeignKey);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
return tipoviviendaReturnGeneral;
}
public void cargarRelacionesLoteForeignKeyTipoViviendaWithConnection() throws Exception {
ArrayList<Classe> classes=new ArrayList<Classe>();
DireccionLogic direccionLogic=new DireccionLogic();
try {
this.connexion=this.connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-cargarRelacionesLoteForeignKeyTipoViviendaWithConnection");connexion.begin();
classes.add(new Classe(Direccion.class));
direccionLogic.setConnexion(this.getConnexion());
direccionLogic.setDatosCliente(this.datosCliente);
direccionLogic.setIsConRefrescarForeignKeys(true);
this.deepLoads(false, DeepLoadType.INCLUDE, classes, "");
for(TipoVivienda tipovivienda:this.tipoviviendas) {
classes=new ArrayList<Classe>();
classes=DireccionConstantesFunciones.getClassesForeignKeysOfDireccion(new ArrayList<Classe>(),DeepLoadType.NONE);
direccionLogic.setDireccions(tipovivienda.direccions);
direccionLogic.deepLoads(false, DeepLoadType.INCLUDE, classes, "");
}
this.connexion.commit();
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public void deepLoad(TipoVivienda tipovivienda,Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception {
Boolean existe=false;
try {
TipoViviendaLogicAdditional.updateTipoViviendaToGet(tipovivienda,this.arrDatoGeneral);
if(!isDeep) {
if(deepLoadType.equals(DeepLoadType.NONE)) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
continue;
}
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
if(this.isConDeep) {
DireccionLogic direccionLogic= new DireccionLogic(this.connexion);
direccionLogic.setDireccions(tipovivienda.getDireccions());
ArrayList<Classe> classesLocal=DireccionConstantesFunciones.getClassesForeignKeysOfDireccion(new ArrayList<Classe>(),DeepLoadType.NONE);
direccionLogic.deepLoads(false,DeepLoadType.INCLUDE, classesLocal,"");
DireccionConstantesFunciones.refrescarForeignKeysDescripcionesDireccion(direccionLogic.getDireccions());
tipovivienda.setDireccions(direccionLogic.getDireccions());
}
continue;
}
}
}
else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) {
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
existe=true;
break;
}
}
if(!existe) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
existe=true;
break;
}
}
if(!existe) {
clases.add(new Classe(Direccion.class));
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
}
}
}
else {
if(deepLoadType.equals(DeepLoadType.NONE)) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(tipovivienda.getEmpresa(),isDeep,deepLoadType,clases);
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
for(Direccion direccion:tipovivienda.getDireccions()) {
DireccionLogic direccionLogic= new DireccionLogic(connexion);
direccionLogic.deepLoad(direccion,isDeep,deepLoadType,clases);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(tipovivienda.getEmpresa(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
for(Direccion direccion:tipovivienda.getDireccions()) {
DireccionLogic direccionLogic= new DireccionLogic(connexion);
direccionLogic.deepLoad(direccion,isDeep,deepLoadType,clases);
}
continue;
}
}
}
else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) {
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
existe=true;
break;
}
}
if(!existe) {
tipovivienda.setEmpresa(tipoviviendaDataAccess.getEmpresa(connexion,tipovivienda));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(tipovivienda.getEmpresa(),isDeep,deepLoadType,clases);
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
existe=true;
break;
}
}
if(!existe) {
clases.add(new Classe(Direccion.class));
tipovivienda.setDireccions(tipoviviendaDataAccess.getDireccions(connexion,tipovivienda));
for(Direccion direccion:tipovivienda.getDireccions()) {
DireccionLogic direccionLogic= new DireccionLogic(connexion);
direccionLogic.deepLoad(direccion,isDeep,deepLoadType,clases);
}
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepSave(TipoVivienda tipovivienda,Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception {
Boolean existe=false;
try {
TipoViviendaLogicAdditional.updateTipoViviendaToSave(tipovivienda,this.arrDatoGeneral);
TipoViviendaDataAccess.save(tipovivienda, connexion);
if(!isDeep) {
if(deepLoadType.equals(DeepLoadType.NONE)) {
EmpresaDataAccess.save(tipovivienda.getEmpresa(),connexion);
for(Direccion direccion:tipovivienda.getDireccions()) {
direccion.setid_tipo_vivienda(tipovivienda.getId());
DireccionDataAccess.save(direccion,connexion);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
EmpresaDataAccess.save(tipovivienda.getEmpresa(),connexion);
continue;
}
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
for(Direccion direccion:tipovivienda.getDireccions()) {
direccion.setid_tipo_vivienda(tipovivienda.getId());
DireccionDataAccess.save(direccion,connexion);
}
continue;
}
}
}
}
else {
if(deepLoadType.equals(DeepLoadType.NONE)) {
EmpresaDataAccess.save(tipovivienda.getEmpresa(),connexion);
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(tipovivienda.getEmpresa(),isDeep,deepLoadType,clases);
for(Direccion direccion:tipovivienda.getDireccions()) {
DireccionLogic direccionLogic= new DireccionLogic(connexion);
direccion.setid_tipo_vivienda(tipovivienda.getId());
DireccionDataAccess.save(direccion,connexion);
direccionLogic.deepSave(direccion,isDeep,deepLoadType,clases);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
EmpresaDataAccess.save(tipovivienda.getEmpresa(),connexion);
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepSave(tipovivienda.getEmpresa(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Direccion.class)&&clas.blnActivo) {
clas.blnActivo=false;
for(Direccion direccion:tipovivienda.getDireccions()) {
DireccionLogic direccionLogic= new DireccionLogic(connexion);
direccion.setid_tipo_vivienda(tipovivienda.getId());
DireccionDataAccess.save(direccion,connexion);
direccionLogic.deepSave(direccion,isDeep,deepLoadType,clases);
}
continue;
}
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepLoadWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(TipoVivienda.class.getSimpleName()+"-deepLoadWithConnection");
this.deepLoad(tipovivienda,isDeep,deepLoadType,clases);
if(this.isConRefrescarForeignKeys) {
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(tipovivienda);
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepLoad(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.deepLoad(this.tipovivienda,isDeep,deepLoadType,clases);
if(this.isConRefrescarForeignKeys) {
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipovivienda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepLoadsWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(TipoVivienda.class.getSimpleName()+"-deepLoadsWithConnection");
if(tipoviviendas!=null) {
for(TipoVivienda tipovivienda:tipoviviendas) {
this.deepLoad(tipovivienda,isDeep,deepLoadType,clases);
}
if(this.isConRefrescarForeignKeys) {
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(tipoviviendas);
}
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepLoads(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
if(tipoviviendas!=null) {
for(TipoVivienda tipovivienda:tipoviviendas) {
this.deepLoad(tipovivienda,isDeep,deepLoadType,clases);
}
if(this.isConRefrescarForeignKeys) {
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(tipoviviendas);
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void deepSaveWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(TipoVivienda.class.getSimpleName()+"-deepSaveWithConnection");
this.deepSave(tipovivienda,isDeep,deepLoadType,clases);
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepSavesWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(TipoVivienda.class.getSimpleName()+"-deepSavesWithConnection");
if(tipoviviendas!=null) {
for(TipoVivienda tipovivienda:tipoviviendas) {
this.deepSave(tipovivienda,isDeep,deepLoadType,clases);
}
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
}finally {
this.closeNewConnexionToDeep();
}
}
public void deepSaves(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
if(tipoviviendas!=null) {
for(TipoVivienda tipovivienda:tipoviviendas) {
this.deepSave(tipovivienda,isDeep,deepLoadType,clases);
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getTipoViviendasFK_IdEmpresaWithConnection(String sFinalQuery,Pagination pagination,Long id_empresa)throws Exception {
try
{
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,TipoVivienda.class.getSimpleName()+"-getBusquedaIndice");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpresa= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpresa.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empresa,TipoViviendaConstantesFunciones.IDEMPRESA,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpresa);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpresa","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
connexion.commit();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getTipoViviendasFK_IdEmpresa(String sFinalQuery,Pagination pagination,Long id_empresa)throws Exception {
try
{
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpresa= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpresa.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empresa,TipoViviendaConstantesFunciones.IDEMPRESA,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpresa);
TipoViviendaLogic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpresa","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
tipoviviendas=tipoviviendaDataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
TipoViviendaConstantesFunciones.refrescarForeignKeysDescripcionesTipoVivienda(this.tipoviviendas);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
}
public static void registrarAuditoria(Connexion connexion,Long idUsuario,String sProcesoBusqueda,String sDetalleProcesoBusqueda,QueryWhereSelectParameters queryWhereSelectParameters,String sUsuarioPC,String sNamePC,String sIPPC)throws Exception {
////AuditoriaLogicAdditional auditoriaLogicAdditional=new AuditoriaLogicAdditional();
////auditoriaLogicAdditional.setConnexion(connexion);
////AuditoriaDataAccess.SCHEMA="bydan_erp";
try {
if(TipoViviendaConstantesFunciones.ISCONAUDITORIA) {
String sDetalleBusqueda=sDetalleProcesoBusqueda+Funciones.getDetalleBusqueda(queryWhereSelectParameters);
////auditoriaLogicAdditional.registrarNuevaAuditoriaBusqueda(Constantes.LIDSISTEMAACTUAL,idUsuario,TipoViviendaDataAccess.TABLENAME, 0L, Constantes.SAUDITORIABUSCAR,sProcesoBusqueda,sUsuarioPC,sNamePC,sIPPC,new Date(),sDetalleBusqueda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public static void registrarAuditoria(Connexion connexion,Long idUsuario,TipoVivienda tipovivienda,String sUsuarioPC,String sNamePC,String sIPPC)throws Exception {
////AuditoriaLogicAdditional auditoriaLogicAdditional=new AuditoriaLogicAdditional();
////auditoriaLogicAdditional.setConnexion(connexion);
////AuditoriaDataAccess.SCHEMA="bydan_erp";
try {
if(TipoViviendaConstantesFunciones.ISCONAUDITORIA) {
if(tipovivienda.getIsNew()) {
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,TipoViviendaDataAccess.TABLENAME, tipovivienda.getId(), Constantes.SAUDITORIAINSERTAR,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
if(TipoViviendaConstantesFunciones.ISCONAUDITORIADETALLE) {
////TipoViviendaLogic.registrarAuditoriaDetallesTipoVivienda(connexion,tipovivienda,auditoriaLogicAdditional.getAuditoria());
}
} else if(tipovivienda.getIsDeleted()) {
/*if(!tipovivienda.getIsExpired()) {
////auditoriaLogicAdditional.RegistrarNuevaAuditoria(Constantes.getLOidSistemaActual(),idUsuario,TipoViviendaDataAccess.TABLENAME, tipovivienda.getId(), Constantes.getSAuditoriaEliminarLogicamente(),"",sUsuarioPC,sNamePC,sIPPC,Timestamp.valueOf(Funciones.getStringMySqlCurrentDateTime()),"");
////TipoViviendaLogic.registrarAuditoriaDetallesTipoVivienda(connexion,tipovivienda,auditoriaLogicAdditional.getAuditoria());
} else {*/
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,TipoViviendaDataAccess.TABLENAME, tipovivienda.getId(), Constantes.SAUDITORIAELIMINARFISICAMENTE,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
//}
} else if(tipovivienda.getIsChanged()) {
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,TipoViviendaDataAccess.TABLENAME, tipovivienda.getId(), Constantes.SAUDITORIAACTUALIZAR,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
if(TipoViviendaConstantesFunciones.ISCONAUDITORIADETALLE) {
////TipoViviendaLogic.registrarAuditoriaDetallesTipoVivienda(connexion,tipovivienda,auditoriaLogicAdditional.getAuditoria());
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
private static void registrarAuditoriaDetallesTipoVivienda(Connexion connexion,TipoVivienda tipovivienda)throws Exception {
////AuditoriaDetalleLogicAdditional auditoriaDetalleLogicAdditional= new AuditoriaDetalleLogicAdditional();
////auditoriaDetalleLogicAdditional.setConnexion(connexion);
////AuditoriaDetalleDataAccess.SCHEMA="bydan_erp";
String strValorActual=null;
String strValorNuevo=null;
if(tipovivienda.getIsNew()||!tipovivienda.getid_empresa().equals(tipovivienda.getTipoViviendaOriginal().getid_empresa()))
{
strValorActual=null;
strValorNuevo=null;
if(tipovivienda.getTipoViviendaOriginal().getid_empresa()!=null)
{
strValorActual=tipovivienda.getTipoViviendaOriginal().getid_empresa().toString();
}
if(tipovivienda.getid_empresa()!=null)
{
strValorNuevo=tipovivienda.getid_empresa().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),TipoViviendaConstantesFunciones.IDEMPRESA,strValorActual,strValorNuevo);
}
if(tipovivienda.getIsNew()||!tipovivienda.getcodigo().equals(tipovivienda.getTipoViviendaOriginal().getcodigo()))
{
strValorActual=null;
strValorNuevo=null;
if(tipovivienda.getTipoViviendaOriginal().getcodigo()!=null)
{
strValorActual=tipovivienda.getTipoViviendaOriginal().getcodigo();
}
if(tipovivienda.getcodigo()!=null)
{
strValorNuevo=tipovivienda.getcodigo() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),TipoViviendaConstantesFunciones.CODIGO,strValorActual,strValorNuevo);
}
if(tipovivienda.getIsNew()||!tipovivienda.getnombre().equals(tipovivienda.getTipoViviendaOriginal().getnombre()))
{
strValorActual=null;
strValorNuevo=null;
if(tipovivienda.getTipoViviendaOriginal().getnombre()!=null)
{
strValorActual=tipovivienda.getTipoViviendaOriginal().getnombre();
}
if(tipovivienda.getnombre()!=null)
{
strValorNuevo=tipovivienda.getnombre() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),TipoViviendaConstantesFunciones.NOMBRE,strValorActual,strValorNuevo);
}
}
public void saveTipoViviendaRelacionesWithConnection(TipoVivienda tipovivienda,List<Direccion> direccions) throws Exception {
if(!tipovivienda.getsType().contains(Constantes2.S_TOTALES)) {
this.saveTipoViviendaRelacionesBase(tipovivienda,direccions,true);
}
}
public void saveTipoViviendaRelaciones(TipoVivienda tipovivienda,List<Direccion> direccions)throws Exception {
if(!tipovivienda.getsType().contains(Constantes2.S_TOTALES)) {
this.saveTipoViviendaRelacionesBase(tipovivienda,direccions,false);
}
}
public void saveTipoViviendaRelacionesBase(TipoVivienda tipovivienda,List<Direccion> direccions,Boolean conConexion)throws Exception {
try {
if(conConexion) {this.getNewConnexionToDeep("TipoVivienda-saveRelacionesWithConnection");}
tipovivienda.setDireccions(direccions);
this.setTipoVivienda(tipovivienda);
if(TipoViviendaLogicAdditional.validarSaveRelaciones(tipovivienda,this)) {
TipoViviendaLogicAdditional.updateRelacionesToSave(tipovivienda,this);
if((tipovivienda.getIsNew()||tipovivienda.getIsChanged())&&!tipovivienda.getIsDeleted()) {
this.saveTipoVivienda();
this.saveTipoViviendaRelacionesDetalles(direccions);
} else if(tipovivienda.getIsDeleted()) {
this.saveTipoViviendaRelacionesDetalles(direccions);
this.saveTipoVivienda();
}
TipoViviendaLogicAdditional.updateRelacionesToSaveAfter(tipovivienda,this);
} else {
throw new Exception("LOS DATOS SON INVALIDOS");
}
if(conConexion) {connexion.commit();}
} catch(Exception e) {
DireccionConstantesFunciones.InicializarGeneralEntityAuxiliaresDireccions(direccions,true,true);
if(conConexion){connexion.rollback();}
Funciones.manageException(logger,e);
throw e;
} finally {
if(conConexion){this.closeNewConnexionToDeep();}
}
}
private void saveTipoViviendaRelacionesDetalles(List<Direccion> direccions)throws Exception {
try {
Long idTipoViviendaActual=this.getTipoVivienda().getId();
DireccionLogic direccionLogic_Desde_TipoVivienda=new DireccionLogic();
direccionLogic_Desde_TipoVivienda.setDireccions(direccions);
direccionLogic_Desde_TipoVivienda.setConnexion(this.getConnexion());
direccionLogic_Desde_TipoVivienda.setDatosCliente(this.datosCliente);
for(Direccion direccion_Desde_TipoVivienda:direccionLogic_Desde_TipoVivienda.getDireccions()) {
direccion_Desde_TipoVivienda.setid_tipo_vivienda(idTipoViviendaActual);
}
direccionLogic_Desde_TipoVivienda.saveDireccions();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
//IF MAX CODE
public static ArrayList<Classe> getClassesForeignKeysOfTipoVivienda(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception {
try {
ArrayList<Classe> classes=TipoViviendaConstantesFunciones.getClassesForeignKeysOfTipoVivienda(classesP,deepLoadType);
return classes;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public static ArrayList<Classe> getClassesRelationshipsOfTipoVivienda(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception {
try {
ArrayList<Classe> classes=TipoViviendaConstantesFunciones.getClassesRelationshipsOfTipoVivienda(classesP,deepLoadType);
return classes;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
}
|
tqma113/DP-front
|
src/components/ArticleCard/index.js
|
<filename>src/components/ArticleCard/index.js
import React from 'react'
import { Card, Row, Col, Icon, message } from 'antd'
import moment from 'moment'
import map from '@map'
import Less from './index.module.less'
const ArticleCard = (props) => {
const { article, store = {}, handlers = {}, mutate, mutations = {}, query, querys = {}, username } = props
const { session = {}, users = {} } = store
const { info = {}, status } = session
const { username: currentUsername, token } = info
const currentUser = users[currentUsername]
const isLiked = article.likes ? article.likes.some(item => Number(item.user_id) === Number(currentUser.id)) : false
const isCollected = article.collections ? article.collections.some(item => Number(item.user_id) === Number(currentUser.id)) : false
const handleStarClick = () => {
if (status) {
articleStar()
}
}
const handleLikeClick = () => {
if (status) {
articleLike()
}
}
const articleStar = async () => {
let data = await mutate(
mutations.ArticleStarMutation,
{
username: currentUsername,
token,
articleId: Number(article.id),
status: isCollected
}
)
const { articleStar: { isSuccess } = {} } = data
if (isSuccess) {
if (username) {
loadUser(username, 'no-cache')
}
} else {
message.error('点赞失败,请重试')
}
}
const articleLike = async () => {
let data = await mutate(
mutations.ArticleLikeMutation,
{
username: currentUsername,
token,
articleId: Number(article.id),
status: isLiked
}
)
const { articleLike: { isSuccess } = {} } = data
if (isSuccess) {
if (username) {
loadUser(username, 'no-cache')
}
} else {
message.error('点赞失败,请重试')
}
}
const loadUser = async (username, fetchPolicy) => {
const data = await query(
querys.QueryUsers,
{
usernames: [username]
},
{
fetchPolicy
}
)
let { users: { isSuccess, users } = {} } = data
if (isSuccess) {
handlers.setUsers({ users })
}
}
return (
<Card>
<Row type="flex" justify="space-between">
<Col>
<a className={Less['title']} href={`/article/${article.id}`}>{article.title}</a>
</Col>
<Col offset={1}>
<span className={Less['edit']}>编辑</span>
</Col>
</Row>
<Row className={Less['row']}>{article.abstract}</Row>
<Row type="flex" justify="space-between" className={Less['row']}>
<Col>发布于 {moment(article.release_time, 'x').fromNow()}</Col>
<Col><Icon onClick={handleLikeClick} type="like" theme={isLiked ? 'filled' : 'outlined'} /> {article.likes.length || 0}</Col>
<Col><Icon onClick={handleStarClick} type="star" theme={isCollected ? 'filled' : 'outlined'} /> {article.collections.length || 0}</Col>
</Row>
</Card>
)
}
export default map(ArticleCard, 'ArticleCard')
|
deonna/accountabilibuddies
|
app/src/main/java/com/accountabilibuddies/accountabilibuddies/fragments/CommentsFragment.java
|
package com.accountabilibuddies.accountabilibuddies.fragments;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.accountabilibuddies.accountabilibuddies.R;
import com.accountabilibuddies.accountabilibuddies.adapter.CommentsAdapter;
import com.accountabilibuddies.accountabilibuddies.application.ParseApplication;
import com.accountabilibuddies.accountabilibuddies.databinding.FragmentCommentBinding;
import com.accountabilibuddies.accountabilibuddies.model.Comment;
import com.accountabilibuddies.accountabilibuddies.network.APIClient;
import com.accountabilibuddies.accountabilibuddies.util.ImageUtils;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CommentsFragment extends Fragment {
private FragmentCommentBinding binding;
private CommentsAdapter mAdapter;
private APIClient client;
private ArrayList<Comment> mCommentList;
private LinearLayoutManager layoutManager;
private EditText etComment;
static final String TAG = CommentsFragment.class.getSimpleName();
static final String POST_ID = "postId";
public CommentsFragment() {
}
public static CommentsFragment getInstance(String postId) {
CommentsFragment frag = new CommentsFragment();
Bundle args = new Bundle();
args.putString(POST_ID, postId);
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_comment,container,false);
client = APIClient.getClient();
mCommentList = new ArrayList<>();
mAdapter = new CommentsAdapter(getContext(), mCommentList);
binding.rVComments.setAdapter(mAdapter);
binding.rVComments.setItemAnimator(new DefaultItemAnimator());
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
binding.rVComments.addItemDecoration(itemDecoration);
layoutManager = new LinearLayoutManager(getContext());
binding.rVComments.setLayoutManager(layoutManager);
setUpNewCommentListener();
//Fetch Comments
getComments();
return binding.getRoot();
}
private void setUpNewCommentListener() {
ImageView ivAvatar = (ImageView) binding.lNewComment.findViewById(R.id.ivAvatar);
ParseUser user = ParseUser.getCurrentUser();
String profilePhotoUrl = (String) user.get("profilePhotoUrl");
ImageUtils.loadCircularProfileImage(
getContext(),
profilePhotoUrl,
ivAvatar
);
ImageButton ibComment = (ImageButton) binding.lNewComment.findViewById(R.id.ibComment);
etComment = (EditText) binding.lNewComment.findViewById(R.id.etComment);
etComment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.length()==0) {
ibComment.setImageResource(R.drawable.send_false);
} else if(charSequence.length()>0) {
ibComment.setImageResource(R.drawable.send);
}
}
@Override
public void afterTextChanged(Editable editable) {}
});
ibComment.setOnClickListener(
(View v) -> {
String comment = etComment.getText().toString();
if(comment.length()>0) {
postComment(comment);
}
}
);
etComment.requestFocus();
}
private void getComments() {
client.getCommentList(getArguments().getString(POST_ID), new APIClient.GetCommentsListListener() {
@Override
public void onSuccess(List<Comment> commentsList) {
if (commentsList != null) {
mCommentList.clear();
Collections.reverse(commentsList);
mCommentList.addAll(commentsList);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(String error_message) {
}
});
}
public void postComment(String postComment) {
Comment comment = new Comment();
comment.setText(postComment);
comment.setUser(ParseApplication.getCurrentUser());
APIClient.getClient().addComment(getArguments().getString(POST_ID), comment,
new APIClient.PostListener() {
@Override
public void onSuccess() {
etComment.setText("");
mCommentList.add(0,comment);
mAdapter.notifyItemInserted(0);
layoutManager.scrollToPosition(0);
}
@Override
public void onFailure(String error_message) {
//TODO: handle failure
}
});
}
}
|
friendliai/crane-public
|
crane/common/api_model/mini_cluster.py
|
# Copyright (C) 2018-2021 Seoul National University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Job router models."""
from __future__ import annotations
from dataclasses import field
from datetime import datetime
from typing import List, Optional, Tuple
from uuid import UUID
from crane.common.model import dataclass, mini_cluster
from crane.common.model.resource import PhysicalCluster
from crane.common.util.serialization import (
DataClassJSONSerializeMixin,
DataClassYAMLMixin,
)
@dataclass
class MCCreateResponse(DataClassJSONSerializeMixin):
"""Mini cluster create response.
Args:
mc_id (str): mini cluster ID
name (str): mini cluster name
add_time (float): creation timestamp
"""
mc_id: str
name: str
add_time: float
@dataclass
class MCStates(DataClassJSONSerializeMixin):
"""Mini cluster state history.
Args:
states (list): a list of state history
"""
states: List[Tuple[str, datetime]]
@classmethod
def from_state_history(cls, state_history: mini_cluster.StateHistory) -> MCStates:
"""Create MCStates from state history."""
return MCStates(
[
(state.name, datetime.utcfromtimestamp(time))
for state, time in state_history
]
)
@property
def curr(self) -> str:
"""Get the current state."""
return self.states[-1][0]
@property
def timestamp(self) -> datetime:
"""Get the latest transition timestamp."""
return self.states[-1][1]
@property
def created(self) -> datetime:
"""Get the creation timestamp."""
return self.states[0][1]
@dataclass
class MCInspectResponse(DataClassJSONSerializeMixin, DataClassYAMLMixin):
"""Job status.
Args:
user_id (str): user that owns the job
job_id (UUID): job identifier
name (Optional[str]): job name
tags (List[str]): job tags
job_config (Config): job configuration
state_history (MCStates): job state history
acquired_resource (PhysicalCluster): resource allocated to this job
"""
user_id: str
job_id: UUID
name: str
tags: List[str]
job_config: mini_cluster.Config
state_history: MCStates
acquired_resource: PhysicalCluster
@dataclass
class MCCreateRequest(DataClassJSONSerializeMixin):
"""Job request.
Args:
config (Config): job configuration
name (str): job name
workspace_id (str) : workspace id if needed
tags (List[str]): list of job tags
"""
config: mini_cluster.Config
name: Optional[str]
workspace_id: Optional[str]
tags: List[str] = field(default_factory=list)
|
wuzhihao7/go-learning
|
gin-gonic-example/purejson.go
|
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// Normally, JSON replaces special HTML characters with their unicode entities, e.g. < becomes \u003c. If you want to encode such characters literally, you can use PureJSON instead. This feature is unavailable in Go 1.6 and lower.
func main() {
r := gin.Default()
// Serves unicode entities
r.GET("/json", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"html": "<b>Hello, world!</b>",
})
})
// Serves literal characters
r.GET("purejson", func(c *gin.Context) {
c.PureJSON(http.StatusOK, gin.H{
"html": "<b>Hello, world!</b>",
})
})
r.Run(":8080")
}
|
W-H-Hs/go-dsa
|
sorting/quick_sort.go
|
<reponame>W-H-Hs/go-dsa
package sorting
// TODO: 算法描述,时间复杂度分析。
func sortOfQuick(arr []int, begin, end int) {
if end-begin < 2 {
return
}
oldBegin := begin
oldEnd := end
pivotEle := arr[begin]
isBeginShift := false
for {
if isBeginShift {
if arr[begin] > pivotEle {
arr[end-1] = arr[begin]
end--
isBeginShift = false
} else {
begin++
}
} else {
if arr[end-1] < pivotEle {
arr[begin] = arr[end-1]
begin++
isBeginShift = true
} else {
end--
}
}
if begin == end-1 {
arr[begin] = pivotEle
break
}
}
sortOfQuick(arr, oldBegin, begin)
sortOfQuick(arr, begin+1, oldEnd)
}
func QuickSort(arr []int) {
if arr == nil {
return
}
sortOfQuick(arr, 0, len(arr))
}
|
carlotacb/ACAP
|
Practicas/Practica-6/Codigos/PROC_SEG_ModSecu_relI_PreSig/documentacio/html/search/files_6.js
|
var searchData=
[
['ini_5fmem_5fi_5fpkg_2evhd',['ini_mem_I_pkg.vhd',['../ini__mem__I__pkg_8vhd.html',1,'']]],
['ini_5fmem_5fpkg_2evhd',['ini_mem_pkg.vhd',['../ini__mem__pkg_8vhd.html',1,'']]],
['inst_5flatproh_2evhd',['inst_latproh.vhd',['../inst__latproh_8vhd.html',1,'']]]
];
|
nilamjadhav/TypeScript
|
tests/baselines/reference/sourceMapValidationDestructuringVariableStatementDefaultValues.js
|
<filename>tests/baselines/reference/sourceMapValidationDestructuringVariableStatementDefaultValues.js
//// [sourceMapValidationDestructuringVariableStatementDefaultValues.ts]
interface Robot {
name: string;
skill: string;
}
declare var console: {
log(msg: string): void;
}
var hello = "hello";
var robotA: Robot = { name: "mower", skill: "mowing" };
var robotB: Robot = { name: "trimmer", skill: "trimming" };
var { name: nameA = "<NoName>" } = robotA;
var { name: nameB = "<NoName>", skill: skillB = "<skillUnspecified>" } = robotB;
var { name: nameC = "<NoName>", skill: skillC = "<skillUnspecified>" } = { name: "Edger", skill: "cutting edges" };
if (nameA == nameB) {
console.log(skillB);
}
else {
console.log(nameC);
}
//// [sourceMapValidationDestructuringVariableStatementDefaultValues.js]
var hello = "hello";
var robotA = { name: "mower", skill: "mowing" };
var robotB = { name: "trimmer", skill: "trimming" };
var _a = robotA.name, nameA = _a === void 0 ? "<NoName>" : _a;
var _b = robotB.name, nameB = _b === void 0 ? "<NoName>" : _b, _c = robotB.skill, skillB = _c === void 0 ? "<skillUnspecified>" : _c;
var _d = { name: "Edger", skill: "cutting edges" }, _e = _d.name, nameC = _e === void 0 ? "<NoName>" : _e, _f = _d.skill, skillC = _f === void 0 ? "<skillUnspecified>" : _f;
if (nameA == nameB) {
console.log(skillB);
}
else {
console.log(nameC);
}
//# sourceMappingURL=sourceMapValidationDestructuringVariableStatementDefaultValues.js.map
|
SOCLabs/Adenium_Normalizer
|
src/main/scala/com/adenium/parser/structs/ReplaceField.scala
|
<reponame>SOCLabs/Adenium_Normalizer
package com.adenium.parser.structs
case class ReplaceField( mid: Int,
instr: String,
outstr: String,
vendor: Long,
ignoreVendor: Boolean = true)
object ReplaceField {
def find( parsed: Array[(Int, String)], agn: Agent, replaces: Option[Map[Int, Array[ReplaceField]]])
: Array[(Int, String)] = {
def replaceString( mid: Int, value: String): Option[(Int, String)] = {
for {
rfs <- replaces
arr <- rfs.get( mid )
rep = arr.filter ( _.instr == value) // todo: may need some performance improvement...
ret <- rep.find( _.vendor == agn.vendorId) orElse rep.find ( _.ignoreVendor )
} yield {
mid -> ret.outstr
}
}
val ret = parsed.flatMap { case( mid, value) => replaceString ( mid, value.trim.toUpperCase) }
ret
}
}
|
youzhi0403/micro-mall
|
micro-mall-mbg/src/main/java/com/youzhi/model/OmsOrderExample.java
|
package com.youzhi.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OmsOrderExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public OmsOrderExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andOrderNumIsNull() {
addCriterion("order_num is null");
return (Criteria) this;
}
public Criteria andOrderNumIsNotNull() {
addCriterion("order_num is not null");
return (Criteria) this;
}
public Criteria andOrderNumEqualTo(String value) {
addCriterion("order_num =", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumNotEqualTo(String value) {
addCriterion("order_num <>", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumGreaterThan(String value) {
addCriterion("order_num >", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumGreaterThanOrEqualTo(String value) {
addCriterion("order_num >=", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumLessThan(String value) {
addCriterion("order_num <", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumLessThanOrEqualTo(String value) {
addCriterion("order_num <=", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumLike(String value) {
addCriterion("order_num like", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumNotLike(String value) {
addCriterion("order_num not like", value, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumIn(List<String> values) {
addCriterion("order_num in", values, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumNotIn(List<String> values) {
addCriterion("order_num not in", values, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumBetween(String value1, String value2) {
addCriterion("order_num between", value1, value2, "orderNum");
return (Criteria) this;
}
public Criteria andOrderNumNotBetween(String value1, String value2) {
addCriterion("order_num not between", value1, value2, "orderNum");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUserIdIsNull() {
addCriterion("user_id is null");
return (Criteria) this;
}
public Criteria andUserIdIsNotNull() {
addCriterion("user_id is not null");
return (Criteria) this;
}
public Criteria andUserIdEqualTo(Integer value) {
addCriterion("user_id =", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotEqualTo(Integer value) {
addCriterion("user_id <>", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThan(Integer value) {
addCriterion("user_id >", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {
addCriterion("user_id >=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThan(Integer value) {
addCriterion("user_id <", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThanOrEqualTo(Integer value) {
addCriterion("user_id <=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdIn(List<Integer> values) {
addCriterion("user_id in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotIn(List<Integer> values) {
addCriterion("user_id not in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdBetween(Integer value1, Integer value2) {
addCriterion("user_id between", value1, value2, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotBetween(Integer value1, Integer value2) {
addCriterion("user_id not between", value1, value2, "userId");
return (Criteria) this;
}
public Criteria andUserAccountIsNull() {
addCriterion("user_account is null");
return (Criteria) this;
}
public Criteria andUserAccountIsNotNull() {
addCriterion("user_account is not null");
return (Criteria) this;
}
public Criteria andUserAccountEqualTo(String value) {
addCriterion("user_account =", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountNotEqualTo(String value) {
addCriterion("user_account <>", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountGreaterThan(String value) {
addCriterion("user_account >", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountGreaterThanOrEqualTo(String value) {
addCriterion("user_account >=", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountLessThan(String value) {
addCriterion("user_account <", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountLessThanOrEqualTo(String value) {
addCriterion("user_account <=", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountLike(String value) {
addCriterion("user_account like", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountNotLike(String value) {
addCriterion("user_account not like", value, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountIn(List<String> values) {
addCriterion("user_account in", values, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountNotIn(List<String> values) {
addCriterion("user_account not in", values, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountBetween(String value1, String value2) {
addCriterion("user_account between", value1, value2, "userAccount");
return (Criteria) this;
}
public Criteria andUserAccountNotBetween(String value1, String value2) {
addCriterion("user_account not between", value1, value2, "userAccount");
return (Criteria) this;
}
public Criteria andTotalAmountIsNull() {
addCriterion("total_amount is null");
return (Criteria) this;
}
public Criteria andTotalAmountIsNotNull() {
addCriterion("total_amount is not null");
return (Criteria) this;
}
public Criteria andTotalAmountEqualTo(BigDecimal value) {
addCriterion("total_amount =", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountNotEqualTo(BigDecimal value) {
addCriterion("total_amount <>", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountGreaterThan(BigDecimal value) {
addCriterion("total_amount >", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("total_amount >=", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountLessThan(BigDecimal value) {
addCriterion("total_amount <", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("total_amount <=", value, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountIn(List<BigDecimal> values) {
addCriterion("total_amount in", values, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountNotIn(List<BigDecimal> values) {
addCriterion("total_amount not in", values, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("total_amount between", value1, value2, "totalAmount");
return (Criteria) this;
}
public Criteria andTotalAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("total_amount not between", value1, value2, "totalAmount");
return (Criteria) this;
}
public Criteria andPayAmountIsNull() {
addCriterion("pay_amount is null");
return (Criteria) this;
}
public Criteria andPayAmountIsNotNull() {
addCriterion("pay_amount is not null");
return (Criteria) this;
}
public Criteria andPayAmountEqualTo(BigDecimal value) {
addCriterion("pay_amount =", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountNotEqualTo(BigDecimal value) {
addCriterion("pay_amount <>", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountGreaterThan(BigDecimal value) {
addCriterion("pay_amount >", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("pay_amount >=", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountLessThan(BigDecimal value) {
addCriterion("pay_amount <", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("pay_amount <=", value, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountIn(List<BigDecimal> values) {
addCriterion("pay_amount in", values, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountNotIn(List<BigDecimal> values) {
addCriterion("pay_amount not in", values, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("pay_amount between", value1, value2, "payAmount");
return (Criteria) this;
}
public Criteria andPayAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("pay_amount not between", value1, value2, "payAmount");
return (Criteria) this;
}
public Criteria andFreightAmountIsNull() {
addCriterion("freight_amount is null");
return (Criteria) this;
}
public Criteria andFreightAmountIsNotNull() {
addCriterion("freight_amount is not null");
return (Criteria) this;
}
public Criteria andFreightAmountEqualTo(BigDecimal value) {
addCriterion("freight_amount =", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountNotEqualTo(BigDecimal value) {
addCriterion("freight_amount <>", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountGreaterThan(BigDecimal value) {
addCriterion("freight_amount >", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("freight_amount >=", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountLessThan(BigDecimal value) {
addCriterion("freight_amount <", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("freight_amount <=", value, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountIn(List<BigDecimal> values) {
addCriterion("freight_amount in", values, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountNotIn(List<BigDecimal> values) {
addCriterion("freight_amount not in", values, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("freight_amount between", value1, value2, "freightAmount");
return (Criteria) this;
}
public Criteria andFreightAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("freight_amount not between", value1, value2, "freightAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountIsNull() {
addCriterion("coupons_amount is null");
return (Criteria) this;
}
public Criteria andCouponsAmountIsNotNull() {
addCriterion("coupons_amount is not null");
return (Criteria) this;
}
public Criteria andCouponsAmountEqualTo(BigDecimal value) {
addCriterion("coupons_amount =", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountNotEqualTo(BigDecimal value) {
addCriterion("coupons_amount <>", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountGreaterThan(BigDecimal value) {
addCriterion("coupons_amount >", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("coupons_amount >=", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountLessThan(BigDecimal value) {
addCriterion("coupons_amount <", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountLessThanOrEqualTo(BigDecimal value) {
addCriterion("coupons_amount <=", value, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountIn(List<BigDecimal> values) {
addCriterion("coupons_amount in", values, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountNotIn(List<BigDecimal> values) {
addCriterion("coupons_amount not in", values, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("coupons_amount between", value1, value2, "couponsAmount");
return (Criteria) this;
}
public Criteria andCouponsAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("coupons_amount not between", value1, value2, "couponsAmount");
return (Criteria) this;
}
public Criteria andPayTypeIsNull() {
addCriterion("pay_type is null");
return (Criteria) this;
}
public Criteria andPayTypeIsNotNull() {
addCriterion("pay_type is not null");
return (Criteria) this;
}
public Criteria andPayTypeEqualTo(Integer value) {
addCriterion("pay_type =", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeNotEqualTo(Integer value) {
addCriterion("pay_type <>", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeGreaterThan(Integer value) {
addCriterion("pay_type >", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("pay_type >=", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeLessThan(Integer value) {
addCriterion("pay_type <", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeLessThanOrEqualTo(Integer value) {
addCriterion("pay_type <=", value, "payType");
return (Criteria) this;
}
public Criteria andPayTypeIn(List<Integer> values) {
addCriterion("pay_type in", values, "payType");
return (Criteria) this;
}
public Criteria andPayTypeNotIn(List<Integer> values) {
addCriterion("pay_type not in", values, "payType");
return (Criteria) this;
}
public Criteria andPayTypeBetween(Integer value1, Integer value2) {
addCriterion("pay_type between", value1, value2, "payType");
return (Criteria) this;
}
public Criteria andPayTypeNotBetween(Integer value1, Integer value2) {
addCriterion("pay_type not between", value1, value2, "payType");
return (Criteria) this;
}
public Criteria andSourceTypeIsNull() {
addCriterion("source_type is null");
return (Criteria) this;
}
public Criteria andSourceTypeIsNotNull() {
addCriterion("source_type is not null");
return (Criteria) this;
}
public Criteria andSourceTypeEqualTo(Integer value) {
addCriterion("source_type =", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeNotEqualTo(Integer value) {
addCriterion("source_type <>", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeGreaterThan(Integer value) {
addCriterion("source_type >", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("source_type >=", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeLessThan(Integer value) {
addCriterion("source_type <", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeLessThanOrEqualTo(Integer value) {
addCriterion("source_type <=", value, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeIn(List<Integer> values) {
addCriterion("source_type in", values, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeNotIn(List<Integer> values) {
addCriterion("source_type not in", values, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeBetween(Integer value1, Integer value2) {
addCriterion("source_type between", value1, value2, "sourceType");
return (Criteria) this;
}
public Criteria andSourceTypeNotBetween(Integer value1, Integer value2) {
addCriterion("source_type not between", value1, value2, "sourceType");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Integer value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Integer value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Integer value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Integer value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Integer value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Integer value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Integer> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Integer> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Integer value1, Integer value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Integer value1, Integer value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andOrderTypeIsNull() {
addCriterion("order_type is null");
return (Criteria) this;
}
public Criteria andOrderTypeIsNotNull() {
addCriterion("order_type is not null");
return (Criteria) this;
}
public Criteria andOrderTypeEqualTo(Integer value) {
addCriterion("order_type =", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeNotEqualTo(Integer value) {
addCriterion("order_type <>", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeGreaterThan(Integer value) {
addCriterion("order_type >", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("order_type >=", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeLessThan(Integer value) {
addCriterion("order_type <", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeLessThanOrEqualTo(Integer value) {
addCriterion("order_type <=", value, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeIn(List<Integer> values) {
addCriterion("order_type in", values, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeNotIn(List<Integer> values) {
addCriterion("order_type not in", values, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeBetween(Integer value1, Integer value2) {
addCriterion("order_type between", value1, value2, "orderType");
return (Criteria) this;
}
public Criteria andOrderTypeNotBetween(Integer value1, Integer value2) {
addCriterion("order_type not between", value1, value2, "orderType");
return (Criteria) this;
}
public Criteria andDeliveryCompanyIsNull() {
addCriterion("delivery_company is null");
return (Criteria) this;
}
public Criteria andDeliveryCompanyIsNotNull() {
addCriterion("delivery_company is not null");
return (Criteria) this;
}
public Criteria andDeliveryCompanyEqualTo(String value) {
addCriterion("delivery_company =", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyNotEqualTo(String value) {
addCriterion("delivery_company <>", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyGreaterThan(String value) {
addCriterion("delivery_company >", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyGreaterThanOrEqualTo(String value) {
addCriterion("delivery_company >=", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyLessThan(String value) {
addCriterion("delivery_company <", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyLessThanOrEqualTo(String value) {
addCriterion("delivery_company <=", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyLike(String value) {
addCriterion("delivery_company like", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyNotLike(String value) {
addCriterion("delivery_company not like", value, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyIn(List<String> values) {
addCriterion("delivery_company in", values, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyNotIn(List<String> values) {
addCriterion("delivery_company not in", values, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyBetween(String value1, String value2) {
addCriterion("delivery_company between", value1, value2, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryCompanyNotBetween(String value1, String value2) {
addCriterion("delivery_company not between", value1, value2, "deliveryCompany");
return (Criteria) this;
}
public Criteria andDeliveryNumIsNull() {
addCriterion("delivery_num is null");
return (Criteria) this;
}
public Criteria andDeliveryNumIsNotNull() {
addCriterion("delivery_num is not null");
return (Criteria) this;
}
public Criteria andDeliveryNumEqualTo(String value) {
addCriterion("delivery_num =", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumNotEqualTo(String value) {
addCriterion("delivery_num <>", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumGreaterThan(String value) {
addCriterion("delivery_num >", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumGreaterThanOrEqualTo(String value) {
addCriterion("delivery_num >=", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumLessThan(String value) {
addCriterion("delivery_num <", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumLessThanOrEqualTo(String value) {
addCriterion("delivery_num <=", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumLike(String value) {
addCriterion("delivery_num like", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumNotLike(String value) {
addCriterion("delivery_num not like", value, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumIn(List<String> values) {
addCriterion("delivery_num in", values, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumNotIn(List<String> values) {
addCriterion("delivery_num not in", values, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumBetween(String value1, String value2) {
addCriterion("delivery_num between", value1, value2, "deliveryNum");
return (Criteria) this;
}
public Criteria andDeliveryNumNotBetween(String value1, String value2) {
addCriterion("delivery_num not between", value1, value2, "deliveryNum");
return (Criteria) this;
}
public Criteria andAutoConfirmDayIsNull() {
addCriterion("auto_confirm_day is null");
return (Criteria) this;
}
public Criteria andAutoConfirmDayIsNotNull() {
addCriterion("auto_confirm_day is not null");
return (Criteria) this;
}
public Criteria andAutoConfirmDayEqualTo(Integer value) {
addCriterion("auto_confirm_day =", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayNotEqualTo(Integer value) {
addCriterion("auto_confirm_day <>", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayGreaterThan(Integer value) {
addCriterion("auto_confirm_day >", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayGreaterThanOrEqualTo(Integer value) {
addCriterion("auto_confirm_day >=", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayLessThan(Integer value) {
addCriterion("auto_confirm_day <", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayLessThanOrEqualTo(Integer value) {
addCriterion("auto_confirm_day <=", value, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayIn(List<Integer> values) {
addCriterion("auto_confirm_day in", values, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayNotIn(List<Integer> values) {
addCriterion("auto_confirm_day not in", values, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayBetween(Integer value1, Integer value2) {
addCriterion("auto_confirm_day between", value1, value2, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andAutoConfirmDayNotBetween(Integer value1, Integer value2) {
addCriterion("auto_confirm_day not between", value1, value2, "autoConfirmDay");
return (Criteria) this;
}
public Criteria andReceiverNameIsNull() {
addCriterion("receiver_name is null");
return (Criteria) this;
}
public Criteria andReceiverNameIsNotNull() {
addCriterion("receiver_name is not null");
return (Criteria) this;
}
public Criteria andReceiverNameEqualTo(String value) {
addCriterion("receiver_name =", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameNotEqualTo(String value) {
addCriterion("receiver_name <>", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameGreaterThan(String value) {
addCriterion("receiver_name >", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameGreaterThanOrEqualTo(String value) {
addCriterion("receiver_name >=", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameLessThan(String value) {
addCriterion("receiver_name <", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameLessThanOrEqualTo(String value) {
addCriterion("receiver_name <=", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameLike(String value) {
addCriterion("receiver_name like", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameNotLike(String value) {
addCriterion("receiver_name not like", value, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameIn(List<String> values) {
addCriterion("receiver_name in", values, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameNotIn(List<String> values) {
addCriterion("receiver_name not in", values, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameBetween(String value1, String value2) {
addCriterion("receiver_name between", value1, value2, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverNameNotBetween(String value1, String value2) {
addCriterion("receiver_name not between", value1, value2, "receiverName");
return (Criteria) this;
}
public Criteria andReceiverPhoneIsNull() {
addCriterion("receiver_phone is null");
return (Criteria) this;
}
public Criteria andReceiverPhoneIsNotNull() {
addCriterion("receiver_phone is not null");
return (Criteria) this;
}
public Criteria andReceiverPhoneEqualTo(String value) {
addCriterion("receiver_phone =", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneNotEqualTo(String value) {
addCriterion("receiver_phone <>", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneGreaterThan(String value) {
addCriterion("receiver_phone >", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneGreaterThanOrEqualTo(String value) {
addCriterion("receiver_phone >=", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneLessThan(String value) {
addCriterion("receiver_phone <", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneLessThanOrEqualTo(String value) {
addCriterion("receiver_phone <=", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneLike(String value) {
addCriterion("receiver_phone like", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneNotLike(String value) {
addCriterion("receiver_phone not like", value, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneIn(List<String> values) {
addCriterion("receiver_phone in", values, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneNotIn(List<String> values) {
addCriterion("receiver_phone not in", values, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneBetween(String value1, String value2) {
addCriterion("receiver_phone between", value1, value2, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPhoneNotBetween(String value1, String value2) {
addCriterion("receiver_phone not between", value1, value2, "receiverPhone");
return (Criteria) this;
}
public Criteria andReceiverPostCodeIsNull() {
addCriterion("receiver_post_code is null");
return (Criteria) this;
}
public Criteria andReceiverPostCodeIsNotNull() {
addCriterion("receiver_post_code is not null");
return (Criteria) this;
}
public Criteria andReceiverPostCodeEqualTo(String value) {
addCriterion("receiver_post_code =", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeNotEqualTo(String value) {
addCriterion("receiver_post_code <>", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeGreaterThan(String value) {
addCriterion("receiver_post_code >", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeGreaterThanOrEqualTo(String value) {
addCriterion("receiver_post_code >=", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeLessThan(String value) {
addCriterion("receiver_post_code <", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeLessThanOrEqualTo(String value) {
addCriterion("receiver_post_code <=", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeLike(String value) {
addCriterion("receiver_post_code like", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeNotLike(String value) {
addCriterion("receiver_post_code not like", value, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeIn(List<String> values) {
addCriterion("receiver_post_code in", values, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeNotIn(List<String> values) {
addCriterion("receiver_post_code not in", values, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeBetween(String value1, String value2) {
addCriterion("receiver_post_code between", value1, value2, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverPostCodeNotBetween(String value1, String value2) {
addCriterion("receiver_post_code not between", value1, value2, "receiverPostCode");
return (Criteria) this;
}
public Criteria andReceiverProvinceIsNull() {
addCriterion("receiver_province is null");
return (Criteria) this;
}
public Criteria andReceiverProvinceIsNotNull() {
addCriterion("receiver_province is not null");
return (Criteria) this;
}
public Criteria andReceiverProvinceEqualTo(String value) {
addCriterion("receiver_province =", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceNotEqualTo(String value) {
addCriterion("receiver_province <>", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceGreaterThan(String value) {
addCriterion("receiver_province >", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceGreaterThanOrEqualTo(String value) {
addCriterion("receiver_province >=", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceLessThan(String value) {
addCriterion("receiver_province <", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceLessThanOrEqualTo(String value) {
addCriterion("receiver_province <=", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceLike(String value) {
addCriterion("receiver_province like", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceNotLike(String value) {
addCriterion("receiver_province not like", value, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceIn(List<String> values) {
addCriterion("receiver_province in", values, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceNotIn(List<String> values) {
addCriterion("receiver_province not in", values, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceBetween(String value1, String value2) {
addCriterion("receiver_province between", value1, value2, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverProvinceNotBetween(String value1, String value2) {
addCriterion("receiver_province not between", value1, value2, "receiverProvince");
return (Criteria) this;
}
public Criteria andReceiverCityIsNull() {
addCriterion("receiver_city is null");
return (Criteria) this;
}
public Criteria andReceiverCityIsNotNull() {
addCriterion("receiver_city is not null");
return (Criteria) this;
}
public Criteria andReceiverCityEqualTo(String value) {
addCriterion("receiver_city =", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityNotEqualTo(String value) {
addCriterion("receiver_city <>", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityGreaterThan(String value) {
addCriterion("receiver_city >", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityGreaterThanOrEqualTo(String value) {
addCriterion("receiver_city >=", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityLessThan(String value) {
addCriterion("receiver_city <", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityLessThanOrEqualTo(String value) {
addCriterion("receiver_city <=", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityLike(String value) {
addCriterion("receiver_city like", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityNotLike(String value) {
addCriterion("receiver_city not like", value, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityIn(List<String> values) {
addCriterion("receiver_city in", values, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityNotIn(List<String> values) {
addCriterion("receiver_city not in", values, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityBetween(String value1, String value2) {
addCriterion("receiver_city between", value1, value2, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverCityNotBetween(String value1, String value2) {
addCriterion("receiver_city not between", value1, value2, "receiverCity");
return (Criteria) this;
}
public Criteria andReceiverRegionIsNull() {
addCriterion("receiver_region is null");
return (Criteria) this;
}
public Criteria andReceiverRegionIsNotNull() {
addCriterion("receiver_region is not null");
return (Criteria) this;
}
public Criteria andReceiverRegionEqualTo(String value) {
addCriterion("receiver_region =", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionNotEqualTo(String value) {
addCriterion("receiver_region <>", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionGreaterThan(String value) {
addCriterion("receiver_region >", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionGreaterThanOrEqualTo(String value) {
addCriterion("receiver_region >=", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionLessThan(String value) {
addCriterion("receiver_region <", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionLessThanOrEqualTo(String value) {
addCriterion("receiver_region <=", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionLike(String value) {
addCriterion("receiver_region like", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionNotLike(String value) {
addCriterion("receiver_region not like", value, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionIn(List<String> values) {
addCriterion("receiver_region in", values, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionNotIn(List<String> values) {
addCriterion("receiver_region not in", values, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionBetween(String value1, String value2) {
addCriterion("receiver_region between", value1, value2, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverRegionNotBetween(String value1, String value2) {
addCriterion("receiver_region not between", value1, value2, "receiverRegion");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressIsNull() {
addCriterion("receiver_detail_address is null");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressIsNotNull() {
addCriterion("receiver_detail_address is not null");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressEqualTo(String value) {
addCriterion("receiver_detail_address =", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressNotEqualTo(String value) {
addCriterion("receiver_detail_address <>", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressGreaterThan(String value) {
addCriterion("receiver_detail_address >", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressGreaterThanOrEqualTo(String value) {
addCriterion("receiver_detail_address >=", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressLessThan(String value) {
addCriterion("receiver_detail_address <", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressLessThanOrEqualTo(String value) {
addCriterion("receiver_detail_address <=", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressLike(String value) {
addCriterion("receiver_detail_address like", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressNotLike(String value) {
addCriterion("receiver_detail_address not like", value, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressIn(List<String> values) {
addCriterion("receiver_detail_address in", values, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressNotIn(List<String> values) {
addCriterion("receiver_detail_address not in", values, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressBetween(String value1, String value2) {
addCriterion("receiver_detail_address between", value1, value2, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andReceiverDetailAddressNotBetween(String value1, String value2) {
addCriterion("receiver_detail_address not between", value1, value2, "receiverDetailAddress");
return (Criteria) this;
}
public Criteria andRemarkIsNull() {
addCriterion("remark is null");
return (Criteria) this;
}
public Criteria andRemarkIsNotNull() {
addCriterion("remark is not null");
return (Criteria) this;
}
public Criteria andRemarkEqualTo(String value) {
addCriterion("remark =", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotEqualTo(String value) {
addCriterion("remark <>", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThan(String value) {
addCriterion("remark >", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThanOrEqualTo(String value) {
addCriterion("remark >=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThan(String value) {
addCriterion("remark <", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThanOrEqualTo(String value) {
addCriterion("remark <=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLike(String value) {
addCriterion("remark like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotLike(String value) {
addCriterion("remark not like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkIn(List<String> values) {
addCriterion("remark in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotIn(List<String> values) {
addCriterion("remark not in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkBetween(String value1, String value2) {
addCriterion("remark between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotBetween(String value1, String value2) {
addCriterion("remark not between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andConfirmStatusIsNull() {
addCriterion("confirm_status is null");
return (Criteria) this;
}
public Criteria andConfirmStatusIsNotNull() {
addCriterion("confirm_status is not null");
return (Criteria) this;
}
public Criteria andConfirmStatusEqualTo(Integer value) {
addCriterion("confirm_status =", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusNotEqualTo(Integer value) {
addCriterion("confirm_status <>", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusGreaterThan(Integer value) {
addCriterion("confirm_status >", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusGreaterThanOrEqualTo(Integer value) {
addCriterion("confirm_status >=", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusLessThan(Integer value) {
addCriterion("confirm_status <", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusLessThanOrEqualTo(Integer value) {
addCriterion("confirm_status <=", value, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusIn(List<Integer> values) {
addCriterion("confirm_status in", values, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusNotIn(List<Integer> values) {
addCriterion("confirm_status not in", values, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusBetween(Integer value1, Integer value2) {
addCriterion("confirm_status between", value1, value2, "confirmStatus");
return (Criteria) this;
}
public Criteria andConfirmStatusNotBetween(Integer value1, Integer value2) {
addCriterion("confirm_status not between", value1, value2, "confirmStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusIsNull() {
addCriterion("delete_status is null");
return (Criteria) this;
}
public Criteria andDeleteStatusIsNotNull() {
addCriterion("delete_status is not null");
return (Criteria) this;
}
public Criteria andDeleteStatusEqualTo(Integer value) {
addCriterion("delete_status =", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusNotEqualTo(Integer value) {
addCriterion("delete_status <>", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusGreaterThan(Integer value) {
addCriterion("delete_status >", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusGreaterThanOrEqualTo(Integer value) {
addCriterion("delete_status >=", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusLessThan(Integer value) {
addCriterion("delete_status <", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusLessThanOrEqualTo(Integer value) {
addCriterion("delete_status <=", value, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusIn(List<Integer> values) {
addCriterion("delete_status in", values, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusNotIn(List<Integer> values) {
addCriterion("delete_status not in", values, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusBetween(Integer value1, Integer value2) {
addCriterion("delete_status between", value1, value2, "deleteStatus");
return (Criteria) this;
}
public Criteria andDeleteStatusNotBetween(Integer value1, Integer value2) {
addCriterion("delete_status not between", value1, value2, "deleteStatus");
return (Criteria) this;
}
public Criteria andPaymentTimeIsNull() {
addCriterion("payment_time is null");
return (Criteria) this;
}
public Criteria andPaymentTimeIsNotNull() {
addCriterion("payment_time is not null");
return (Criteria) this;
}
public Criteria andPaymentTimeEqualTo(Date value) {
addCriterion("payment_time =", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotEqualTo(Date value) {
addCriterion("payment_time <>", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeGreaterThan(Date value) {
addCriterion("payment_time >", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeGreaterThanOrEqualTo(Date value) {
addCriterion("payment_time >=", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeLessThan(Date value) {
addCriterion("payment_time <", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeLessThanOrEqualTo(Date value) {
addCriterion("payment_time <=", value, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeIn(List<Date> values) {
addCriterion("payment_time in", values, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotIn(List<Date> values) {
addCriterion("payment_time not in", values, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeBetween(Date value1, Date value2) {
addCriterion("payment_time between", value1, value2, "paymentTime");
return (Criteria) this;
}
public Criteria andPaymentTimeNotBetween(Date value1, Date value2) {
addCriterion("payment_time not between", value1, value2, "paymentTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeIsNull() {
addCriterion("delivery_time is null");
return (Criteria) this;
}
public Criteria andDeliveryTimeIsNotNull() {
addCriterion("delivery_time is not null");
return (Criteria) this;
}
public Criteria andDeliveryTimeEqualTo(Date value) {
addCriterion("delivery_time =", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeNotEqualTo(Date value) {
addCriterion("delivery_time <>", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeGreaterThan(Date value) {
addCriterion("delivery_time >", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeGreaterThanOrEqualTo(Date value) {
addCriterion("delivery_time >=", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeLessThan(Date value) {
addCriterion("delivery_time <", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeLessThanOrEqualTo(Date value) {
addCriterion("delivery_time <=", value, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeIn(List<Date> values) {
addCriterion("delivery_time in", values, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeNotIn(List<Date> values) {
addCriterion("delivery_time not in", values, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeBetween(Date value1, Date value2) {
addCriterion("delivery_time between", value1, value2, "deliveryTime");
return (Criteria) this;
}
public Criteria andDeliveryTimeNotBetween(Date value1, Date value2) {
addCriterion("delivery_time not between", value1, value2, "deliveryTime");
return (Criteria) this;
}
public Criteria andReceiveTimeIsNull() {
addCriterion("receive_time is null");
return (Criteria) this;
}
public Criteria andReceiveTimeIsNotNull() {
addCriterion("receive_time is not null");
return (Criteria) this;
}
public Criteria andReceiveTimeEqualTo(Date value) {
addCriterion("receive_time =", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeNotEqualTo(Date value) {
addCriterion("receive_time <>", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeGreaterThan(Date value) {
addCriterion("receive_time >", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeGreaterThanOrEqualTo(Date value) {
addCriterion("receive_time >=", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeLessThan(Date value) {
addCriterion("receive_time <", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeLessThanOrEqualTo(Date value) {
addCriterion("receive_time <=", value, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeIn(List<Date> values) {
addCriterion("receive_time in", values, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeNotIn(List<Date> values) {
addCriterion("receive_time not in", values, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeBetween(Date value1, Date value2) {
addCriterion("receive_time between", value1, value2, "receiveTime");
return (Criteria) this;
}
public Criteria andReceiveTimeNotBetween(Date value1, Date value2) {
addCriterion("receive_time not between", value1, value2, "receiveTime");
return (Criteria) this;
}
public Criteria andCommentTimeIsNull() {
addCriterion("comment_time is null");
return (Criteria) this;
}
public Criteria andCommentTimeIsNotNull() {
addCriterion("comment_time is not null");
return (Criteria) this;
}
public Criteria andCommentTimeEqualTo(Date value) {
addCriterion("comment_time =", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeNotEqualTo(Date value) {
addCriterion("comment_time <>", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeGreaterThan(Date value) {
addCriterion("comment_time >", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeGreaterThanOrEqualTo(Date value) {
addCriterion("comment_time >=", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeLessThan(Date value) {
addCriterion("comment_time <", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeLessThanOrEqualTo(Date value) {
addCriterion("comment_time <=", value, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeIn(List<Date> values) {
addCriterion("comment_time in", values, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeNotIn(List<Date> values) {
addCriterion("comment_time not in", values, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeBetween(Date value1, Date value2) {
addCriterion("comment_time between", value1, value2, "commentTime");
return (Criteria) this;
}
public Criteria andCommentTimeNotBetween(Date value1, Date value2) {
addCriterion("comment_time not between", value1, value2, "commentTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
pokulo/trickytripper
|
app/src/main/java/de/koelle/christian/trickytripper/strategies/impl/SpendingSumAmountStrategy.java
|
package de.koelle.christian.trickytripper.strategies.impl;
import java.util.Map.Entry;
import de.koelle.christian.trickytripper.model.Amount;
import de.koelle.christian.trickytripper.model.Participant;
import de.koelle.christian.trickytripper.model.Payment;
import de.koelle.christian.trickytripper.model.PaymentCategory;
import de.koelle.christian.trickytripper.strategies.SumReport;
public class SpendingSumAmountStrategy extends AbstractSumAmountStrategy {
@Override
protected void doAddAmountParticipantResult(SumReport sumReport, Participant participant, Payment payment) {
for (Entry<Participant, Amount> entry : payment.getParticipantToSpending().entrySet()) {
Amount amount = sumReport.getSpendingByUser().get(participant);
Amount amountBalance = sumReport.getBalanceByUser().get(participant);
Integer count = sumReport.getSpendingByUserCount().get(participant);
Amount amountForCategory = (sumReport.getSpendingByUserByCategory().get(participant)
.get(payment.getCategory()) == null) ? getAmountFactory().createAmount() : sumReport
.getSpendingByUserByCategory().get(participant).get(payment.getCategory());
Integer countCategory = (sumReport.getSpendingByUserByCategoryCount().get(participant)
.get(payment.getCategory()) == null) ? Integer.valueOf(0) : sumReport
.getSpendingByUserByCategoryCount().get(participant).get(payment.getCategory());
if (participant.equals(entry.getKey())) {
if (!payment.getCategory().isInternal()) {
amount.addAmount(entry.getValue());
amountForCategory.addAmount(entry.getValue());
count = count + 1;
countCategory = countCategory + 1;
}
else if (payment.getCategory().isInternal() &&
entry.getValue().getValue() > 0) {
sumReport.getPaymentByUser().get(participant).addValue(entry.getValue().getValue());
}
amountBalance.addAmount(entry.getValue());
}
sumReport.getBalanceByUser().put(participant, amountBalance);
sumReport.getSpendingByUser().put(participant, amount);
sumReport.getSpendingByUserByCategory().get(participant).put(payment.getCategory(), amountForCategory);
sumReport.getSpendingByUserCount().put(participant, count);
sumReport.getSpendingByUserByCategoryCount().get(participant).put(payment.getCategory(), countCategory);
}
}
@Override
protected void doAddAmountTotalResult(SumReport sumReport, Payment payment) {
final PaymentCategory category = payment.getCategory();
if (!category.isInternal()) {
for (Entry<Participant, Amount> entry : payment.getParticipantToSpending().entrySet()) {
Amount amountTotal = (sumReport.getTotalSpending() == null) ? getAmountFactory().createAmount()
: sumReport.getTotalSpending();
amountTotal.addAmount(entry.getValue());
Amount amountTotalForCategory = (sumReport.getTotalSpendingByCategory().get(category) == null) ? getAmountFactory()
.createAmount()
: sumReport.getTotalSpendingByCategory().get(category);
amountTotalForCategory.addAmount(entry.getValue());
sumReport.setTotalSpending(amountTotal);
sumReport.getTotalSpendingByCategory().put(category, amountTotalForCategory);
}
Integer countCategory = (sumReport.getTotalSpendingByCategoryCount().get(category) == null) ? Integer
.valueOf(0) : sumReport.getTotalSpendingByCategoryCount().get(category);
countCategory = countCategory + 1;
int countTotal = sumReport.getTotalSpendingCount() + 1;
sumReport.getTotalSpendingByCategoryCount().put(category, countCategory);
sumReport.setTotalSpendingCount(countTotal);
}
}
}
|
kaizer88/emps
|
operations/fleet_management/migrations/0045_auto_20180605_1501.py
|
<reponame>kaizer88/emps
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-05 13:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fleet_management', '0044_auto_20180605_1453'),
]
operations = [
migrations.AlterField(
model_name='vehicledriver',
name='reason',
field=models.CharField(choices=[(b'discretionary change', b'Discretionary Vehicle Change'), (b'new employee', b'New Employee'), (b'pool car', b'Pool Car'), (b'relocation', b'Relocation'), (b'temp vehicle', b'Temp Vehicle')], max_length=255),
),
]
|
nickpartner-goahead/resilient-community-apps
|
fn_slack/fn_slack/components/slack_post_attachment.py
|
<gh_stars>10-100
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved.
"""Function implementation to Slack.
This function uploads file to Slack and creates a Slack message based on a Resilient Attachments.
Many of the features of posting a Slack message are under customer control including:
- Creating private or public channels
- Inviting users to conversations
- Uploading Incident, Task or Artifact Attachments
"""
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from resilient_lib import RequestsCommon
from fn_slack.lib.slack_common import *
LOG = logging.getLogger(__name__)
SLACK_SECTION_HDR = "fn_slack"
class FunctionComponent(ResilientComponent):
"""Component that implements Resilient function 'slack_post_message"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(SLACK_SECTION_HDR, {})
self.resoptions = opts.get("resilient", {})
@handler("reload")
def _reload(self, event, opts):
"""Configuration options have changed, save new values"""
self.opts = opts
self.options = opts.get(SLACK_SECTION_HDR, {})
self.resoptions = opts.get("resilient", {})
@function("slack_post_attachment")
def _slack_post_attachment(self, event, *args, **kwargs):
"""Function: Function uploads Incident, Task or Artifact Attachments to Slack channel."""
try:
validate_fields(['api_token'], self.options)
validate_fields(['incident_id'], kwargs)
# Get the function parameters:
incident_id = kwargs.get("incident_id") # number (required)
task_id = kwargs.get("task_id") # number (optional)
artifact_id = kwargs.get("artifact_id") # number (optional)
attachment_id = kwargs.get("attachment_id") # number (required)
input_channel_name = kwargs.get("slack_channel") # text (optional)
slack_is_private = kwargs.get("slack_is_channel_private") # Boolean (optional)
slack_participant_emails = kwargs.get("slack_participant_emails") # text (optional)
slack_text = kwargs.get("slack_text") # text (optional)
LOG.info("incident_id: %s", incident_id)
LOG.info("task_id: %s", task_id)
LOG.info("artifact_id: %s", artifact_id)
LOG.info("attachment_id: %s", attachment_id)
LOG.debug("slack_channel: %s", input_channel_name)
LOG.debug("slack_text: %s", slack_text)
LOG.debug("slack_is_private: %s", slack_is_private)
LOG.debug("slack_participant_emails: %s", slack_participant_emails)
# configuration specific slack parameters
api_token = self.options['api_token']
# get proxies if they exist
rc = RequestsCommon(opts=self.opts, function_opts=self.options)
# Initialize SlackClient
slack_utils = SlackUtils(api_token, proxies=rc.get_proxies())
# Initialize Resilient API object
res_client = self.rest_client()
# Find or create a channel
slack_channel_name, has_association_in_slack_db = slack_utils.find_or_create_channel(
input_channel_name, slack_is_private, res_client, incident_id, task_id)
# Add users to the channel
if slack_participant_emails:
# Find user ids based on their emails
user_id_list = slack_utils.find_user_ids_based_on_email(slack_participant_emails)
# invite users to a channel
if user_id_list:
slack_utils.invite_users_to_channel(user_id_list)
# Get the the attachment from Incident or Task
attachment_content, attachment_data = slack_utils.get_file_attachment_data(res_client, incident_id,
artifact_id, task_id, attachment_id)
# Upload file to Slack
results_attachment_uploaded = slack_utils.slack_post_attachment(attachment_content, attachment_data, slack_text)
# Find ts for file upload message
file_ts = slack_utils.get_ts_from_file_upload_results(results_attachment_uploaded)
# Generate a permalink URL to join this conversation
conversation_url = slack_utils.get_permalink(file_ts)
# Create an association if there isn't one
if has_association_in_slack_db is False:
slack_utils.create_row_in_datatable(res_client, incident_id, task_id, conversation_url)
# Yield Status Messages
for warn in slack_utils.get_warnings():
yield StatusMessage(warn)
results = {"channel": slack_channel_name,
"url": conversation_url}
LOG.info(results)
# Produce a FunctionResult with the results
yield FunctionResult(results)
except Exception as err:
LOG.error(err)
yield FunctionError()
|
BlackholeMTA/lqdtu
|
src/views/post/editCate/ContentCate.js
|
<reponame>BlackholeMTA/lqdtu<filename>src/views/post/editCate/ContentCate.js
import {React, useEffect, useState} from 'react'
import edit from './edit.css'
function ContentCate(props) {
const cate = props.cate
console.log(cate)
const {onSubmit} = props
const [name, setName] = useState()
const handleSubmitForm = (e) => {
e.preventDefault()
if (!onSubmit) return
const data ={
name: name
}
onSubmit(data)
}
function handleChangeCate(e) {
setName(e.target.value)
}
useEffect(() => {
async function SetValue() {
setName(cate.name)
// console.log(valueEditor)
console.log(name)
}
SetValue()
}, [cate])
return (
<>
<div className= "wp-wrapper">
<form onSubmit = {handleSubmitForm}>
<div className= "form-group">
<label htmlFor="cate">Category</label>
<input type="text" name="cate" value= {name} onChange = {handleChangeCate} className= "form-control" placeholder ="Name Category"/>
</div>
<div className ="text-center">
<button className ="btn-submit btn btn-success" type="" onSubmit = {handleSubmitForm}>Update</button>
</div>
</form>
</div>
</>
)
}
export default ContentCate
|
audreytnt/jabref
|
src/main/java/org/jabref/logic/citationstyle/CitationStyleGenerator.java
|
package org.jabref.logic.citationstyle;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jbibtex.TokenMgrException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Facade to unify the access to the citation style engine. Use these methods if you need rendered BibTeX item(s) in a
* given journal style. This class uses {@link CSLAdapter} to create output.
*/
public class CitationStyleGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(CitationStyleGenerator.class);
private static final CSLAdapter CSL_ADAPTER = new CSLAdapter();
private CitationStyleGenerator() {
}
/**
* Generates a Citation based on the given entry and style
* @implNote the citation is generated using JavaScript which may take some time, better call it from outside the main Thread
*/
protected static String generateCitation(BibEntry entry, CitationStyle style) {
return generateCitation(entry, style.getSource(), CitationStyleOutputFormat.HTML);
}
/**
* Generates a Citation based on the given entry and style
* @implNote the citation is generated using JavaScript which may take some time, better call it from outside the main Thread
*/
protected static String generateCitation(BibEntry entry, String style) {
return generateCitation(entry, style, CitationStyleOutputFormat.HTML);
}
/**
* Generates a Citation based on the given entry, style, and output format
* @implNote the citation is generated using JavaScript which may take some time, better call it from outside the main Thread
*/
protected static String generateCitation(BibEntry entry, String style, CitationStyleOutputFormat outputFormat) {
return generateCitations(Collections.singletonList(entry), style, outputFormat).stream().findFirst().orElse("");
}
/**
* Generates the citation for multiple entries at once.
* @implNote The citations are generated using JavaScript which may take some time, better call it from outside the main thread.
*/
public static List<String> generateCitations(List<BibEntry> bibEntries, String style, CitationStyleOutputFormat outputFormat) {
try {
return CSL_ADAPTER.makeBibliography(bibEntries, style, outputFormat);
} catch (IllegalArgumentException ignored) {
LOGGER.error("Could not generate BibEntry citation. The CSL engine could not create a preview for your item.");
return Collections.singletonList(Localization.lang("Cannot generate preview based on selected citation style."));
} catch (IOException | ArrayIndexOutOfBoundsException e) {
LOGGER.error("Could not generate BibEntry citation", e);
return Collections.singletonList(Localization.lang("Cannot generate preview based on selected citation style."));
} catch (TokenMgrException e) {
LOGGER.error("Bad character inside BibEntry", e);
// sadly one cannot easily retrieve the bad char from the TokenMgrError
return Collections.singletonList(new StringBuilder()
.append(Localization.lang("Cannot generate preview based on selected citation style."))
.append(outputFormat.getLineSeparator())
.append(Localization.lang("Bad character inside entry"))
.append(outputFormat.getLineSeparator())
.append(e.getLocalizedMessage())
.toString());
}
}
}
|
roversch/blasfeo
|
kernel/avx2/kernel_dgelqf_4_lib4_bkp.c
|
<filename>kernel/avx2/kernel_dgelqf_4_lib4_bkp.c
/**************************************************************************************************
* *
* This file is part of BLASFEO. *
* *
* BLASFEO -- BLAS For Embedded Optimization. *
* Copyright (C) 2019 by <NAME>. *
* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. *
* All rights reserved. *
* *
* The 2-Clause BSD License *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* Author: <NAME>, gianluca.frison (at) imtek.uni-freiburg.de *
* *
**************************************************************************************************/
#include <math.h>
#include <stdio.h>
#include <mmintrin.h>
#include <xmmintrin.h> // SSE
#include <emmintrin.h> // SSE2
#include <pmmintrin.h> // SSE3
#include <smmintrin.h> // SSE4
#include <immintrin.h> // AVX
#include "../../include/blasfeo_common.h"
#include "../../include/blasfeo_d_aux.h"
#include "../../include/blasfeo_d_kernel.h"
// assume n>=4
void kernel_dgelqf_dlarft_4_lib4(int n, double *pD, double *dD, double *pT)
{
return;
int ii, jj, ll;
double alpha, beta, tmp, w0, w1, w2, w3;
const int ps = 4;
// zero tau matrix
for(ii=0; ii<16; ii++)
pT[ii] = 0.0;
// first column
beta = 0.0;
for(ii=1; ii<n; ii++)
{
tmp = pD[0+ps*ii];
beta += tmp*tmp;
}
if(beta==0.0)
{
dD[0] = 0.0;
goto col2;
}
alpha = pD[0+ps*0];
beta += alpha*alpha;
beta = sqrt(beta);
if(alpha>0)
beta = -beta;
dD[0] = (beta-alpha) / beta;
pT[0+ps*0] = - dD[0];
tmp = -1.0 / (beta-alpha);
//
pD[0+ps*0] = beta;
w1 = pD[1+ps*0];
w2 = pD[2+ps*0];
w3 = pD[3+ps*0];
//
pD[0+ps*1] *= tmp;
w1 += pD[1+ps*1] * pD[0+ps*1];
w2 += pD[2+ps*1] * pD[0+ps*1];
w3 += pD[3+ps*1] * pD[0+ps*1];
//
pD[0+ps*2] *= tmp;
w1 += pD[1+ps*2] * pD[0+ps*2];
w2 += pD[2+ps*2] * pD[0+ps*2];
w3 += pD[3+ps*2] * pD[0+ps*2];
//
pD[0+ps*3] *= tmp;
w1 += pD[1+ps*3] * pD[0+ps*3];
w2 += pD[2+ps*3] * pD[0+ps*3];
w3 += pD[3+ps*3] * pD[0+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[0+ps*ii] *= tmp;
w1 += pD[1+ps*ii] * pD[0+ps*ii];
w2 += pD[2+ps*ii] * pD[0+ps*ii];
w3 += pD[3+ps*ii] * pD[0+ps*ii];
}
//
w1 = - dD[0] * w1;
w2 = - dD[0] * w2;
w3 = - dD[0] * w3;
//
pD[1+ps*0] += w1;
pD[2+ps*0] += w2;
pD[3+ps*0] += w3;
//
pD[1+ps*1] += w1 * pD[0+ps*1];
pD[2+ps*1] += w2 * pD[0+ps*1];
pD[3+ps*1] += w3 * pD[0+ps*1];
//
pD[1+ps*2] += w1 * pD[0+ps*2];
pD[2+ps*2] += w2 * pD[0+ps*2];
pD[3+ps*2] += w3 * pD[0+ps*2];
beta = pD[1+ps*2] * pD[1+ps*2];
//
pD[1+ps*3] += w1 * pD[0+ps*3];
pD[2+ps*3] += w2 * pD[0+ps*3];
pD[3+ps*3] += w3 * pD[0+ps*3];
beta += pD[1+ps*3] * pD[1+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[1+ps*ii] += w1 * pD[0+ps*ii];
pD[2+ps*ii] += w2 * pD[0+ps*ii];
pD[3+ps*ii] += w3 * pD[0+ps*ii];
beta += pD[1+ps*ii] * pD[1+ps*ii];
}
// second column
col2:
if(beta==0.0)
{
dD[1] = 0.0;
tmp = 0.0;
goto col3;
}
alpha = pD[1+ps*1];
beta += alpha*alpha;
beta = sqrt(beta);
if(alpha>0)
beta = -beta;
dD[1] = (beta-alpha) / beta;
pT[1+ps*1] = - dD[1];
tmp = 1.0 / (alpha-beta);
//
pD[1+ps*1] = beta;
w0 = pD[0+ps*1]; //
w2 = pD[2+ps*1];
w3 = pD[3+ps*1];
//
pD[1+ps*2] *= tmp;
w0 += pD[0+ps*2] * pD[1+ps*2]; //
w2 += pD[2+ps*2] * pD[1+ps*2];
w3 += pD[3+ps*2] * pD[1+ps*2];
//
pD[1+ps*3] *= tmp;
w0 += pD[0+ps*3] * pD[1+ps*3]; //
w2 += pD[2+ps*3] * pD[1+ps*3];
w3 += pD[3+ps*3] * pD[1+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[1+ps*ii] *= tmp;
w0 += pD[0+ps*ii] * pD[1+ps*ii]; //
w2 += pD[2+ps*ii] * pD[1+ps*ii];
w3 += pD[3+ps*ii] * pD[1+ps*ii];
}
//
pT[0+ps*1] = - dD[1] * (w0*pT[0+ps*0]);
w2 = - dD[1] * w2;
w3 = - dD[1] * w3;
//
pD[2+ps*1] += w2;
pD[3+ps*1] += w3;
//
pD[2+ps*2] += w2 * pD[1+ps*2];
pD[3+ps*2] += w3 * pD[1+ps*2];
//
pD[2+ps*3] += w2 * pD[1+ps*3];
pD[3+ps*3] += w3 * pD[1+ps*3];
beta = pD[2+ps*3] * pD[2+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[2+ps*ii] += w2 * pD[1+ps*ii];
pD[3+ps*ii] += w3 * pD[1+ps*ii];
beta += pD[2+ps*ii] * pD[2+ps*ii];
}
// third column
col3:
if(beta==0.0)
{
dD[2] = 0.0;
tmp = 0.0;
goto col4;
}
alpha = pD[2+ps*2];
beta += alpha*alpha;
beta = sqrt(beta);
if(alpha>0)
beta = -beta;
dD[2] = (beta-alpha) / beta;
pT[2+ps*2] = - dD[2];
tmp = 1.0 / (alpha-beta);
//
pD[2+ps*2] = beta;
w0 = pD[0+ps*2];
w1 = pD[1+ps*2];
w3 = pD[3+ps*2];
//
pD[2+ps*3] *= tmp;
w0 += pD[0+ps*3] * pD[2+ps*3];
w1 += pD[1+ps*3] * pD[2+ps*3];
w3 += pD[3+ps*3] * pD[2+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[2+ps*ii] *= tmp;
w0 += pD[0+ps*ii] * pD[2+ps*ii];
w1 += pD[1+ps*ii] * pD[2+ps*ii];
w3 += pD[3+ps*ii] * pD[2+ps*ii];
}
//
pT[0+ps*2] = - dD[2] * (w0*pT[0+ps*0] + w1*pT[0+ps*1]);
pT[1+ps*2] = - dD[2] * (w1*pT[1+ps*1]);
w3 = - dD[2] * w3;
//printf("\n%f %f %f\n", pT[0+ps*2], pT[1+ps*2], w3);
//return;
//
pD[3+ps*2] += w3;
//
pD[3+ps*3] += w3 * pD[2+ps*3];
//
beta = 0.0;
for(ii=4; ii<n; ii++)
{
pD[3+ps*ii] += w3 * pD[2+ps*ii];
beta += pD[3+ps*ii] * pD[3+ps*ii];
}
// fourth column
col4:
if(beta==0.0)
{
dD[3] = 0.0;
tmp = 0.0;
return;
}
alpha = pD[3+ps*3];
beta += alpha*alpha;
beta = sqrt(beta);
if(alpha>0)
beta = -beta;
dD[3] = (beta-alpha) / beta;
pT[3+ps*3] = - dD[3];
tmp = 1.0 / (alpha-beta);
//
pD[3+ps*3] = beta;
w0 = pD[0+ps*3];
w1 = pD[1+ps*3];
w2 = pD[2+ps*3];
//
for(ii=4; ii<n; ii++)
{
pD[3+ps*ii] *= tmp;
w0 += pD[0+ps*ii] * pD[3+ps*ii];
w1 += pD[1+ps*ii] * pD[3+ps*ii];
w2 += pD[2+ps*ii] * pD[3+ps*ii];
}
//
pT[0+ps*3] = - dD[3] * (w0*pT[0+ps*0] + w1*pT[0+ps*1] + w2*pT[0+ps*2]);
pT[1+ps*3] = - dD[3] * (w1*pT[1+ps*1] + w2*pT[1+ps*2]);
pT[2+ps*3] = - dD[3] * (w2*pT[2+ps*2]);
return;
}
|
610yilingliu/leetcode
|
Python3/435.non-overlapping-intervals.py
|
#
# @lc app=leetcode id=435 lang=python3
#
# [435] Non-overlapping Intervals
#
# @lc code=start
class Solution:
def eraseOverlapIntervals(self, intervals):
if len(intervals) == 1 or len(intervals) == 0:
return 0
time = 0
intervals.sort(key = lambda x:(-x[0], -x[1]))
for i in range(len(intervals) - 2, -1, -1):
if intervals[i][0] == intervals[i + 1][0]:
intervals.pop(i)
time += 1
else:
if intervals[i][1] < intervals[i + 1][1]:
intervals.pop(i + 1)
time += 1
if intervals[i][0] < intervals[i + 1][1]:
if intervals[i][0] < intervals[i + 1][1]:
intervals.pop(i)
time +=1
return time
if __name__ == '__main__':
a = Solution()
b = a.eraseOverlapIntervals([[1,100],[11,22],[1,11],[2,12]])
print(b)
# @lc code=end
|
ownzandy/blueprint-admin
|
tests/components/NavBar.spec.js
|
import React from 'react'
import { bindActionCreators } from 'redux'
import NavBar from 'components/NavBar'
import classes from 'components/NavBar/NavBar.scss'
import { shallow} from 'enzyme'
describe('(Component) NavBar', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
leftItem: 'leftItem',
leftClick: _spies.leftClick = sinon.spy(),
rightItem: 'rightItem',
rightClick: _spies.rightClick = sinon.spy(),
title: 'title'
}
_wrapper = shallow(<NavBar {..._props} />)
})
it('has one title', () => {
expect(_wrapper.find('.' + classes.barTitle)).to.have.length(1)
})
it('calls the left click when the left side is clicked', () => {
const leftButton = _wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.leftItem)
leftButton.simulate('click')
_spies.leftClick.should.have.been.called
})
it('calls the right click when the right side is clicked', () => {
const rightButton = _wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.rightItem)
rightButton.simulate('click')
_spies.rightClick.should.have.been.called
})
it('has two buttons with names given initial props', () => {
expect(_wrapper.find('button')).to.have.length(2)
expect(_wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.leftItem)).to.have.length(1)
expect(_wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.rightItem)).to.have.length(1)
})
it('has one item if the rightItem is empty', () => {
_wrapper.setProps({rightItem: ''})
expect(_wrapper.find('button')).to.have.length(1)
expect(_wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.leftItem)).to.have.length(1)
expect(_wrapper.find('button').filterWhere(a => a.text() === _wrapper.instance().props.rightItem)).to.have.length(0)
})
it('has no buttons if both items are empty', () => {
_wrapper.setProps({rightItem: '', leftItem: ''})
expect(_wrapper.find('button')).to.have.length(0)
})
})
|
davydehaas98/advent-of-code-2021
|
src/main/java/nl/davydehaas/year2021/day12/Part1.java
|
<reponame>davydehaas98/advent-of-code-2021
package nl.davydehaas.year2021.day12;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import nl.davydehaas.utils.InputReader;
import java.awt.image.AreaAveragingScaleFilter;
import java.util.ArrayList;
import java.util.List;
public class Part1 {
public static void main(String[] args) {
List<String[]> connections = getConnections();
List<Cave> caves = getCaves(connections);
List<List<Cave>> paths = new ArrayList<>();
Cave startPoint = caves.stream().filter(cave -> cave.getName().equals("start")).findAny().orElseThrow();
Cave endPoint = caves.stream().filter(cave -> cave.getName().equals("start")).findAny().orElseThrow();
calculatePath(startPoint, endPoint);
System.out.println("The total paths that go through the caves and visit the small caves at most once is:");
System.out.println(caves);
}
private static List<Cave> calculatePath(Cave startPoint, Cave endPoint) {
return null;
}
private static List<Cave> getCaves(List<String[]> connections) {
List<Cave> caves = new ArrayList<>();
connections.forEach(connection -> {
String startCaveName = connection[0];
String endCaveName = connection[1];
Cave startCave = caves.stream().filter(c -> c.getName().equals(startCaveName)).findAny().orElse(null);
Cave endCave = caves.stream().filter(c -> c.getName().equals(endCaveName)).findAny().orElse(null);
// Check if caves exist
if (startCave == null) {
startCave = new Cave(startCaveName);
caves.add(startCave);
}
if (endCave == null) {
endCave = new Cave(endCaveName);
caves.add(endCave);
}
startCave.addConnectedCave(endCave);
endCave.addConnectedCave(startCave);
});
return caves;
}
private static List<String[]> getConnections() {
List<String[]> connections = new ArrayList<>();
InputReader.readFile("/year2021/day12-input-test.txt")
.forEach(l -> {
String[] connection = l.split("-");
connections.add(connection);
});
return connections;
}
}
@Getter
class Cave {
private String name;
private boolean isSmallCave;
private List<Cave> connectedCaves;
private int visits;
Cave(String name) {
this.name = name;
this.isSmallCave = Character.isLowerCase(name.charAt(0));
this.connectedCaves = new ArrayList<>();
this.visits = 0;
}
public void addConnectedCave(Cave connectedCave) {
this.connectedCaves.add(connectedCave);
}
public void setVisits(int visits) {
this.visits = visits;
}
}
|
golbi/test-import
|
web-common/src/main/java/pl/edu/icm/unity/webui/common/LabelAsTextField.java
|
/*
* Copyright (c) 2020 Bixbit - <NAME>. All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import com.vaadin.ui.Label;
/**
* Simple not editable text field
*
* @author P.Piernik
*
*/
public class LabelAsTextField extends CustomField<String>
{
private Label content;
public LabelAsTextField(String caption)
{
content = new Label();
setCaption(caption);
}
@Override
public String getValue()
{
return content.getValue();
}
@Override
protected Component initContent()
{
return content;
}
@Override
protected void doSetValue(String value)
{
content.setValue(value);
}
}
|
Sam-Gao-Xin/Courses-
|
UBCx-Software-Construction-Data-Abstraction-SoftConst1x/long-form-problem-starters/FitLifeGymChain/src/ui/GymChainInfo.java
|
<reponame>Sam-Gao-Xin/Courses-
package ui;
import model.GymChain;
import model.cardio.Elliptical;
import model.cardio.IndoorBike;
import model.cardio.Treadmill;
import model.gym.DeluxeGym;
import model.gym.FitnessClass;
import model.gym.Gym;
import model.members.Member;
import model.weights.Barbell;
import model.weights.Dumbbell;
import model.weights.Plate;
import model.weights.WeightMachine;
import static model.members.MembershipLevel.*;
public class GymChainInfo {
public static final String SUNNY_GROVE_GYM_NAME = "Sunny Grove";
public static final String PINE_VALLEY_GYM_NAME = "Pine Valley";
public static final String PALM_LAKE_GYM_NAME = "Palm Lake";
public static final String AMY_MEMBER_NAME = "Amy";
public static final String JAMES_MEMBER_NAME = "James";
public static final String MICHELA_MEMBER_NAME = "Michela";
//TODO 1: assign a different value to the constant below
public static final String YOUR_GYM_NAME = "Your Gym";
//TODO 1: assign a different value to the constant below
public static final String YOUR_MEMBER_NAME = "Your Name";
public static void main(String[] args) {
GymChain chain = new GymChain();
loadGyms(chain);
loadMembers(chain);
InfoManager info = new InfoManager(chain);
System.out.println("You are now in the FitLife information console.");
info.handleUserInput();
}
private static void loadMembers(GymChain chain){
Member m1 = new Member(AMY_MEMBER_NAME);
m1.setMembershipLevel(CLASSES);
Member m2 = new Member(JAMES_MEMBER_NAME);
m2.setMembershipLevel(DELUXE);
Member m3 = new Member(MICHELA_MEMBER_NAME);
m3.setMembershipLevel(BASIC);
chain.signUpMember(m1);
chain.signUpMember(m2);
chain.signUpMember(m3);
//TODO 3: construct a new Member object with the parameter YOUR_MEMBER_NAME
// Member m4 = ...
//TODO 3: uncomment these 2 lines:
// m4.setMembershipLevel(DELUXE);
// chain.signUpMember(m4);
}
private static void loadGyms(GymChain chain){
Gym g1 = new Gym(SUNNY_GROVE_GYM_NAME);
initializeGym1(g1);
chain.addGym(g1);
WeightMachine wm = new WeightMachine("quadriceps", 75);
//TODO 2: pass in parameters to these methods:
// g1.setHasPool(...);
// wm.setWeight(...);
// g1.addWeight(...);
Gym g2 = new DeluxeGym(PINE_VALLEY_GYM_NAME);
initializeGym2(g2);
chain.addGym(g2);
Gym g3 = new Gym(PALM_LAKE_GYM_NAME);
initializeGym3(g3);
chain.addGym(g3);
//TODO 4: pick a variable name for the gym below and uncomment:
// Gym ... = new Gym(YOUR_GYM_NAME);
//TODO 4: add your new gym's variable name and uncomment:
// initializeGym0(...);
//TODO 4: add your new gym's variable name and uncomment:
// chain.addGym(...);
}
private static void initializeGym0(Gym gym){
//TODO 4: uncomment the next 4 lines:
// Barbell bar = //TODO 4: make a new barbell
// IndoorBike bike = //TODO 4: make a new IndoorBike
// gym.addWeight(bar);
// gym.addCardioMachine(bike);
// NOTE: the Barbell constructor takes one parameter, an int
// NOTE: the IndoorBike constructor doesn't take any parameters
}
private static void initializeGym1(Gym gym){
gym.setHasChildCare(true);
gym.setHasPool(true);
gym.addWeight(new Barbell(135));
gym.addWeight(new Plate(20));
gym.addWeight(new Plate(20));
gym.addWeight(new WeightMachine("biceps", 50));
gym.addCardioMachine(new IndoorBike());
gym.addCardioMachine(new Treadmill());
FitnessClass fc = new FitnessClass("HIIT", "Friday at 4PM");
gym.addFitnessClass(fc);
}
private static void initializeGym2(Gym gym){
gym.setHasChildCare(true);
gym.setHasPool(false);
gym.addWeight(new Dumbbell(15));
gym.addWeight(new Dumbbell(15));
gym.addWeight(new WeightMachine("hamstrings", 130));
gym.addCardioMachine(new IndoorBike());
gym.addCardioMachine(new Treadmill());
gym.addCardioMachine(new Elliptical());
FitnessClass fc = new FitnessClass("Power Lift", "Wednesday at 8AM");
gym.addFitnessClass(fc);
FitnessClass fc2 = new FitnessClass("Hatha Yoga", "Sunday at 11AM");
gym.addFitnessClass(fc2);
}
private static void initializeGym3(Gym gym){
gym.setHasChildCare(true);
gym.setHasPool(true);
gym.addWeight(new WeightMachine("trapezius", 70));
gym.addWeight(new WeightMachine("triceps", 30));
gym.addWeight(new Barbell(90));
gym.addCardioMachine(new Treadmill());
gym.addCardioMachine(new Treadmill());
gym.addCardioMachine(new IndoorBike());
gym.addCardioMachine(new Elliptical());
FitnessClass fc = new FitnessClass("Cardio Blast", "Monday at 6:30AM");
gym.addFitnessClass(fc);
}
}
|
osman-demirci/digital-guard-app-ipcamera
|
node_modules/opencv4nodejs/cc/modules/machinelearning/machinelearning.h
|
#include "macros.h"
#include <opencv2/core.hpp>
#include <opencv2/ml.hpp>
#ifndef __FF_MACHINELEARNING_H__
#define __FF_MACHINELEARNING_H__
class MachineLearning {
public:
static NAN_MODULE_INIT(Init);
};
#endif
|
pritamsavst/frontend
|
web/rainmaker/dev-packages/egov-rented-properties-dev/src/ui-config/screens/specs/rented-properties/search-mortgage.js
|
<gh_stars>0
import {
getCommonHeader,
getLabel,
getBreak,
getCommonContainer
} from "egov-ui-framework/ui-config/screens/specs/utils";
import { setRoute } from "egov-ui-framework/ui-redux/app/actions";
import { getQueryArg } from "egov-ui-framework/ui-utils/commons";
import { prepareFinalObject } from "egov-ui-framework/ui-redux/screen-configuration/actions";
import { localStorageGet,getTenantId } from "egov-ui-kit/utils/localStorageUtils";
import { httpRequest } from "../../../../ui-utils";
import find from "lodash/find";
import get from "lodash/get";
import { searchMortgageApplication } from "./searchResource/rentedPropertyApplication";
import { searchMortgage } from "./searchResource/functions"
import { mortgageSearchResults } from "./searchResource/searchResults";
import { getColonyTypes } from "./apply";
import { getStatusList } from "./search";
const header = getCommonHeader({
labelName: "Mortgage",
labelKey: "RP_MORTAGE_HEADER"
});
const mortagageSearchAndResult = {
uiFramework: "material-ui",
name: "search-mortgage",
beforeInitScreen: (action, state, dispatch) => {
const queryObject = [{ key: "tenantId", value: getTenantId() },
{ key: "businessServices", value: "PermissionToMortgage" }]
dispatch(prepareFinalObject("searchScreen", {}))
searchMortgage(state, dispatch, true)
getStatusList(action, state, dispatch, queryObject, "search-mortgage", "components.div.children.searchMortgageApplication.children.cardContent.children.statusContainer.children.status")
return action
},
components: {
div: {
uiFramework: "custom-atoms",
componentPath: "Form",
props: {
className: "common-div-css",
id: "search"
},
children: {
headerDiv: {
uiFramework: "custom-atoms",
componentPath: "Container",
children: {
header: {
gridDefination: {
xs: 12,
sm: 6
},
...header
}
}
},
searchMortgageApplication,
breakAfterSearch: getBreak(),
mortgageSearchResults
}
}
}
};
export default mortagageSearchAndResult;
|
dineshkumar2509/learning-python
|
threading/threading_create.py
|
#!/usr/bin/env python
import threading
import datetime
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
print("%s says Hello World at time: %s" % (self.getName(), now))
for i in range(2):
t = ThreadClass()
t.start()
|
yorkulibraries/book_search
|
app/controllers/find_this_item/legal_controller.rb
|
<gh_stars>1-10
class FindThisItem::LegalController < ApplicationController
layout "external_integration"
SESSION_REFERER_ID = "find_this_item_referer"
SESSION_ITEM_DATA = "find_this_item_data"
# path to this should be /find_this_item/test_cases
def index
# this is a page with temporary book lists for testing
@tickets = []
3.times do |i|
ticket = SearchTicket.new
ticket.item_title = Faker::Book.unique.title
ticket.item_callnumber = "CD #{Faker::Code.unique.asin}"
ticket.item_author = Faker::Book.unique.author
ticket.item_id = rand(2900020030020..2900020040020)
ticket.item_volume = "Vol 1"
ticket.item_issue = "Issue 2"
ticket.item_year = rand(1998..2017)
ticket.item_location = Location.all.pluck(:ils_code).sample
@tickets<< ticket
end
ticket = SearchTicket.new
ticket.item_title = Faker::Book.unique.title
ticket.item_callnumber = "CD #{Faker::Code.unique.asin}"
ticket.item_author = Faker::Book.unique.author
ticket.item_id = rand(2900020030020..2900020040020)
ticket.item_volume = "Vol 1"
ticket.item_issue = "Issue 2"
ticket.item_year = rand(1998..2017)
ticket.item_location = "WONDERLAND"
@tickets<< ticket
end
def show
# record referrer
session[SESSION_REFERER_ID] = request.env["HTTP_REFERER"]
# save book item details into session
session[SESSION_ITEM_DATA] = params[:item]
@item_json = params[:item]
if params[:item]
@item = ActiveSupport::HashWithIndifferentAccess.new(JSON.parse params[:item])
else
ticket = SearchTicket.new
ticket.item_title = "Test"
@item = ticket.attributes
end
end
end
|
protegeproject/webprotege-backend-api-java
|
src/test/java/edu/stanford/protege/webprotege/issues/events/IssueReopened_TestCase.java
|
<filename>src/test/java/edu/stanford/protege/webprotege/issues/events/IssueReopened_TestCase.java
package edu.stanford.protege.webprotege.issues.events;
import edu.stanford.protege.webprotege.common.ProjectId;
import edu.stanford.protege.webprotege.common.UserId;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.mock;
@RunWith(MockitoJUnitRunner.class)
public class IssueReopened_TestCase {
private IssueReopenedEvent issueReopened;
private UserId userId = new UserId("UserA");
private final long timestamp = 1L;
private ProjectId projectId = ProjectId.generate();
@Before
public void setUp() {
issueReopened = new IssueReopenedEvent(projectId, userId, timestamp);
}
@SuppressWarnings("ConstantConditions")
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionIf_userId_IsNull() {
new IssueReopenedEvent(projectId, null, timestamp);
}
@Test
public void shouldReturnSupplied_userId() {
assertThat(issueReopened.userId(), is(this.userId));
}
@Test
public void shouldReturnSupplied_timestamp() {
assertThat(issueReopened.timestamp(), is(this.timestamp));
}
@Test
public void shouldBeEqualToSelf() {
assertThat(issueReopened, is(issueReopened));
}
@Test
@SuppressWarnings("ObjectEqualsNull")
public void shouldNotBeEqualToNull() {
assertThat(issueReopened.equals(null), is(false));
}
@Test
public void shouldBeEqualToOther() {
assertThat(issueReopened, is(new IssueReopenedEvent(projectId, userId, timestamp)));
}
@Test
public void shouldNotBeEqualToOtherThatHasDifferent_userId() {
assertThat(issueReopened, is(not(new IssueReopenedEvent(projectId, new UserId("OtherUser"), timestamp))));
}
@Test
public void shouldNotBeEqualToOtherThatHasDifferent_timestamp() {
assertThat(issueReopened, is(not(new IssueReopenedEvent(projectId, userId, 2L))));
}
@Test
public void shouldBeEqualToOtherHashCode() {
assertThat(issueReopened.hashCode(), is(new IssueReopenedEvent(projectId, userId, timestamp).hashCode()));
}
@Test
public void shouldImplementToString() {
assertThat(issueReopened.toString(), startsWith("IssueReopened"));
}
}
|
Sh11ntar0/CICCC-OOP
|
src/week2/arrays/CopyingArrays.java
|
package week2.arrays;
import java.util.Random;
public class CopyingArrays {
public static void main( String[] args ) {
int[] arr1 = new int[10];
Random random = new Random();
for ( int i = 0; i < arr1.length ; i++ ) {
arr1[i] = random.nextInt(100) +1;
}
int[] arr2 = arr1.clone();
arr1[arr1.length - 1]= -7;
System.out.print("array1: ");
for(int i: arr1) {
System.out.print(" " + i);
}
System.out.print("\narray2: ");
for(int j: arr2) {
System.out.print(" " + j);
}
}
}
|
silky/circuit
|
kit/fs/rh/rh.go
|
// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
// 2013 <NAME> <<EMAIL>>
// Package rh provides a the interface for the Resource Hierarchy file system
package rh
// Originally inspired from:
// http://plan9.bell-labs.com/sys/man/5/INDEX.html
// Server is the low-level interface that a X9P file server must implement
type Server interface {
// SignIn opens a new session with the server for user, rooted at dir
SignIn(user, dir string) (Session, error)
// String returns a short name, identifying this server
String() string
}
type Session interface {
// Walk returns a new unopened FID, corresponding to the given relative path.
// In particular, Walk(nil) returns an unopened FID for the root.
Walk(name []string) (FID, error)
// ?
SignOut()
// String returns a short name, identifying this session
String() string
}
type Identifier interface {
// String returns a short readable name, identifying this FID. The name need not conform to any syntactic rules.
String() string
// Q returns the QID of this FID.
Q() Q
}
type Walker interface {
// Walk returns a new unopened FID, corresponding to the given relative path.
// In particular, Walk(nil) returns an unopened FID for the current file.
Walk(wname []string) (FID, error)
}
type Stater interface {
// Stat inquires about the file identified by this FID.
Stat() (*Dir, error)
// Wstat can change some of the file's meta information.
Wstat(*Wdir) error
}
// Prompt is the value of an interrupt notification.
// Currently unused, it is meant for things like OS signal info, etc.
type Prompt interface{}
// Intr is a channel that receives interrupt notifications
type Intr <-chan Prompt
// Abandon is a channel that sends interrupt notifications
type Abandon chan<- Prompt
func NewIntr() (Intr, Abandon) {
ch := make(chan Prompt, 1)
return Intr(ch), Abandon(ch)
}
//
type Conn interface {
// Open asks the file server to check permissions and prepare this FID for I/O with subsequent read and write invocations.
Open(flag Flag, intr Intr) error
//
Create(name string, flag Flag, mode Mode, perm Perm) (FID, error)
// Clunk releases this FID immediately.
// The FID should also be released automatically if the FID object is garbage-collected.
Clunk() error
// If count equals zero, all data should be returned.
Read(offset int64, count int, intr Intr) (Chunk, error)
//
Write(offset int64, data Chunk, intr Intr) (int, error)
}
type Traverser interface {
// Remove asks the file server both to remove this file and to clunk this FID, even if the remove fails.
// If a file has been opened as multiple fids, possibly on different
// connections, and one fid is used to remove the file, whether the other
// fids continue to provide access to the file is implementation–defined.
Remove() error
// Move moves this FID to dir with the given name.
Move(dir FID, name string) error
}
type FID interface {
Identifier
Walker
Stater
Conn
Traverser
}
const (
MaxWalk = 16 // Suggested maximum depth of walk sequences
)
// Mixing AnchoredFID into your type takes care of rejecting meta- or location-modifying requests.
type AnchoredFID struct{}
func (AnchoredFID) Create(string, Flag, Mode, Perm) (FID, error) {
return nil, ErrPerm
}
func (AnchoredFID) Wstat(*Wdir) error {
return ErrPerm
}
func (AnchoredFID) Remove() error {
return ErrPerm
}
func (AnchoredFID) Move(FID, string) error {
return ErrPerm
}
// Mixing ReadOnlyFID into your type takes care of rejecting write-side calls.
type ReadOnlyFID struct {
AnchoredFID
DontWriteFID
}
type DontWriteFID struct{}
func (DontWriteFID) Write(int64, Chunk, Intr) (int, error) {
return 0, ErrPerm
}
// Mixing WriteOnlyFID into your type takes care of rejecting read-side calls.
type WriteOnlyFID struct {
AnchoredFID
DontReadFID
}
type DontReadFID struct{}
func (DontReadFID) Read(int64, int, Intr) (Chunk, error) {
return nil, ErrPerm
}
//
type ZeroFID struct {
AnchoredFID
DontReadFID
DontWriteFID
}
|
filelug/filelug-desktop
|
src/main/java/com/filelug/desktop/service/websocket/FileTransferOutWebSocketService.java
|
<filename>src/main/java/com/filelug/desktop/service/websocket/FileTransferOutWebSocketService.java
package com.filelug.desktop.service.websocket;
import ch.qos.logback.classic.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.filelug.desktop.ClopuccinoMessages;
import com.filelug.desktop.Constants;
import com.filelug.desktop.Utility;
import com.filelug.desktop.dao.FileTransferOutDao;
import com.filelug.desktop.db.DatabaseConstants;
import com.filelug.desktop.model.*;
import com.filelug.desktop.service.*;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.nio.protocol.BasicAsyncResponseConsumer;
import org.apache.http.nio.protocol.HttpAsyncResponseConsumer;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.File;
/**
* <code>FileTransferOutWebSocketService</code> receives and process the web socket message from server with service id: DOWNLOAD_FILE2_V2
*
* @author masonhsieh
* @version 1.0
*/
public class FileTransferOutWebSocketService {
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(FileTransferOutWebSocketService.class.getSimpleName());
private final Session session;
private final String message;
private final ConnectSocket connectSocket;
public FileTransferOutWebSocketService(final Session session, final String message, final ConnectSocket connectSocket) {
this.session = session;
this.message = message;
this.connectSocket = connectSocket;
}
public void onFileTransferOutWebSocket() {
// requested to upload file to server
String operatorId = null;
String clientLocale = null;
String clientSessionId = null; // keep the value of download key
String filePath = null;
ObjectMapper mapper = Utility.createObjectMapper();
try {
RequestFileDownloadModel requestModel = mapper.readValue(message, RequestFileDownloadModel.class);
operatorId = requestModel.getOperatorId();
clientLocale = requestModel.getLocale();
filePath = requestModel.getPath();
long availableBytes = requestModel.getAvailableBytes();
long downloadSizeLimitInBytes = requestModel.getDownloadSizeLimitInBytes();
// Actually the client session id is the download key
clientSessionId = requestModel.getClientSessionId();
if (!connectSocket.validate(true)) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_UNAUTHORIZED, ClopuccinoMessages.localizedMessage(clientLocale, "invalid.session"), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (clientSessionId == null || clientSessionId.trim().length() < 1) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "empty.client.session"), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (filePath == null || !new File(filePath).exists()) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "directory.or.file.not.found", filePath != null ? filePath : ""), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (!new File(filePath).isFile() && !BundleDirectoryService.isBundleDirectory(new File(filePath))) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "not.file", filePath), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (!new File(filePath).canRead()) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "file.read.permission.denied", filePath), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (availableBytes < 1) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "param.null.or.empty", "available volumes"), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (availableBytes < new File(filePath).length()) {
String fileSizeForRepresentation = Utility.representationFileSizeFromBytes(availableBytes);
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_FORBIDDEN, ClopuccinoMessages.localizedMessage(clientLocale, "not.enough.transfer.bytes", fileSizeForRepresentation), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else if (downloadSizeLimitInBytes < new File(filePath).length()) {
String fileSizeForRepresentation = Utility.representationFileSizeFromBytes(new File(filePath).length());
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, Constants.HTTP_STATUS_FILE_SIZE_LIMIT_EXCEEDED, ClopuccinoMessages.localizedMessage(clientLocale, "exceed.download.size.limit", fileSizeForRepresentation), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else {
// Check if a bundle directory
// Bundle directory not supports resume-download
// for the header value Last-Modified is always different than the last one
// because the zip file is generate on the fly.
File zipFile = null;
File directory = new File(filePath);
if (BundleDirectoryService.isBundleDirectory(directory)) {
try {
zipFile = BundleDirectoryService.createZipFileFromBundleDirectory(directory, false);
zipFile.deleteOnExit();
filePath = zipFile.getAbsolutePath();
} catch (Exception e) {
LOGGER.error("Error on creating zip file from bundle directory: " + filePath, e);
}
}
if (directory.isDirectory() && zipFile == null) {
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_BAD_REQUEST, ClopuccinoMessages.localizedMessage(clientLocale, "not.file", filePath), operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} else {
boolean deleteFileAfterUpload = (zipFile != null);
final String range = requestModel.getRange();
final String transferKey = clientSessionId;
final String filePathCopy = filePath;
File file = new File(filePath);
final long fileSize = file.length();
final long lastModifiedDateInMillis = file.lastModified();
// It's possible that the FileDownloaded with the same downloadKey exists
// because resume-downloading is supported.
long startingBytes = findStartingByteFromRange(range);
final FileTransferOutDao fileTransferOutDao = connectSocket.getFileTransferOutDao();
final String userId = connectSocket.getUserId();
final String lugServerId = connectSocket.getLugServerId();
// If stargingBytes is 0, meaning transfer file from start, the file size and last modified date need to be updated;
// if not from start, compare the values of file size and last modified date in local db with the values for the current file to make sure file is not modified.
FileTransferOut fileTransferOut = fileTransferOutDao.findFileTransferOutForTransferKey(transferKey);
if (startingBytes < 1 || fileTransferOut == null) {
// transfer from start
startingBytes = 0L;
fileTransferOut = new FileTransferOut(transferKey, userId, filePath, fileSize, lastModifiedDateInMillis, System.currentTimeMillis(), 0L, DatabaseConstants.TRANSFER_STATUS_PROCESSING);
fileTransferOutDao.createFileTransferOut(fileTransferOut);
} else {
final Long originalFileSize = fileTransferOut.getFileSize();
final Long originalLastModifiedDateInMillis = fileTransferOut.getFileLastModifiedDate();
if (startingBytes >= fileSize || fileSize != originalFileSize || lastModifiedDateInMillis != originalLastModifiedDateInMillis) {
// transfer from start
startingBytes = 0L;
fileTransferOut.setFilePath(filePath);
fileTransferOut.setFileSize(fileSize);
fileTransferOut.setFileLastModifiedDate(lastModifiedDateInMillis);
}
// remain the old start timestamp
// fileTransferOut.setStartTimestamp(System.currentTimeMillis());
fileTransferOut.setStatus(DatabaseConstants.TRANSFER_STATUS_PROCESSING);
fileTransferOut.setEndTimestamp(0L);
fileTransferOutDao.updateFileTransferOut(fileTransferOut);
}
final long finalStartingBytes = startingBytes;
Utility.getExecutorService().execute(() -> {
try {
HttpAsyncResponseConsumer<HttpResponse> consumer = new BasicAsyncResponseConsumer();
FutureCallback<HttpResponse> callback = new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
int status = result.getStatusLine().getStatusCode();
// Consider partial content 206 as successfully downloaded file
if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_PARTIAL_CONTENT) {
fileTransferOutDao.updateFileTransferOutStatus(transferKey, DatabaseConstants.TRANSFER_STATUS_SUCCESS, System.currentTimeMillis());
LOGGER.info(String.format("File transferred out successfully: '%s'", filePathCopy));
} else {
fileTransferOutDao.updateFileTransferOutStatus(transferKey, DatabaseConstants.TRANSFER_STATUS_FAILURE, System.currentTimeMillis());
if (status == Constants.HTTP_STATUS_CLIENT_CLOSE_REQUEST) {
// user canceled
LOGGER.info(String.format("User canceled transfering file out: '%s'", filePathCopy));
} else {
LOGGER.info(String.format("File transferred out completely with error. Status code: %d\nfile: '%s'", status, filePathCopy));
}
}
}
@Override
public void failed(Exception ex) {
fileTransferOutDao.updateFileTransferOutStatus(transferKey, DatabaseConstants.TRANSFER_STATUS_FAILURE, System.currentTimeMillis());
String errorMessage = ex.getMessage();
if (errorMessage != null && errorMessage.toLowerCase().contains("connection reset by peer")) {
LOGGER.warn("User canceled the file to transfer out. File path: " + filePathCopy);
} else if (errorMessage != null && errorMessage.toLowerCase().contains("broken pipe")) {
LOGGER.warn("Network reset or user canceled the file to transfer out. File path: " + filePathCopy);
} else {
LOGGER.error("Failed on transfering file out. file: " + filePathCopy, ex);
}
}
@Override
public void cancelled() {
LOGGER.warn("User canceled transfering out file: " + filePathCopy);
}
};
final DirectoryService directoryService = new DefaultDirectoryService();
directoryService.doAsyncUploadFile3(userId, lugServerId, filePathCopy, transferKey, finalStartingBytes, consumer, callback, deleteFileAfterUpload);
} catch (Exception e) {
// already handled by FutureCallback,failed(Exception), DO NOT HANDLED AGAIN.
// fileTransferOutDao.updateFileDownload(DatabaseConstants.TRANSFER_STATUS_FAILURE, System.currentTimeMillis(), 0, downloadKey);
//
// String errorMessage = e.getMessage();
//
// if (errorMessage != null && errorMessage.contains("Connection reset by peer")) {
// LOGGER.warn("User canceled the file download. File path: " + filePathCopy);
// } else {
// LOGGER.error("Failed on upload file to server. File path: " + filePathCopy, e);
// }
}
});
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_OK, null, operatorId, System.currentTimeMillis(), clientSessionId, filePath, fileSize);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
}
}
} catch (Exception e) {
/* websocket sent internal error */
try {
String errorMessage = ClopuccinoMessages.localizedMessage(clientLocale, "error.invoke.service", "DOWNLOAD_FILE2_V2", e.getMessage() != null ? e.getMessage() : "");
LOGGER.error(errorMessage, e);
ResponseFileDownloadModel responseModel = new ResponseFileDownloadModel(Sid.DOWNLOAD_FILE2_V2, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage, operatorId, System.currentTimeMillis(), clientSessionId, filePath, 0L);
session.getAsyncRemote().sendText(mapper.writeValueAsString(responseModel));
} catch (Exception e1) {
LOGGER.error("Error on sent internal error message! Class: " + e1.getClass().getName() + ", Reason: " + e.getMessage());
}
}
}
private static long findStartingByteFromRange(String range) {
long startingBytes = 0L;
String rangePrefix = "bytes=";
if (range != null && range.startsWith(rangePrefix) && range.contains("-")) { // bytes=9500-
int indexHyphen = range.indexOf("-");
String rangeNumber = range.substring(rangePrefix.length(), indexHyphen);
try {
startingBytes = Long.parseLong(rangeNumber);
} catch (Exception e) {
LOGGER.debug("Range header value not supported: " + range);
}
} else {
LOGGER.debug("Range header value not supported: " + range);
}
return startingBytes;
}
}
|
gianricardo/OpcUaStack
|
src/OpcUaStackCore/ServiceSet/DeleteNodesResponse.cpp
|
/*
Copyright 2015 <NAME> (<EMAIL>)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: <NAME> (<EMAIL>)
*/
#include "OpcUaStackCore/ServiceSet/DeleteNodesResponse.h"
namespace OpcUaStackCore
{
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// DeleteNodesResponse
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
DeleteNodesResponse::DeleteNodesResponse(void)
: Object()
, deleteNodesResultArraySPtr_(constructSPtr<DeleteNodesResultArray>())
, diagnosticInfoArraySPtr_(constructSPtr<OpcUaDiagnosticInfoArray>())
{
}
DeleteNodesResponse::~DeleteNodesResponse(void)
{
}
void
DeleteNodesResponse::results(
const DeleteNodesResultArray::SPtr deleteNodesResultArraySPtr)
{
deleteNodesResultArraySPtr_ = deleteNodesResultArraySPtr;
}
DeleteNodesResultArray::SPtr
DeleteNodesResponse::results() const
{
return deleteNodesResultArraySPtr_;
}
void
DeleteNodesResponse::diagnosticInfos(const OpcUaDiagnosticInfoArray::SPtr diagnosticInfosSPtr)
{
diagnosticInfoArraySPtr_ = diagnosticInfosSPtr;
}
OpcUaDiagnosticInfoArray::SPtr
DeleteNodesResponse::diagnosticInfos(void) const
{
return diagnosticInfoArraySPtr_;
}
void
DeleteNodesResponse::opcUaBinaryEncode(std::ostream& os) const
{
deleteNodesResultArraySPtr_->opcUaBinaryEncode(os);
diagnosticInfoArraySPtr_->opcUaBinaryEncode(os);
}
void
DeleteNodesResponse::opcUaBinaryDecode(std::istream& is)
{
deleteNodesResultArraySPtr_->opcUaBinaryDecode(is);
diagnosticInfoArraySPtr_->opcUaBinaryDecode(is);
}
}
|
Rudedog9d/pypsi
|
test/test_cmdline/test_condense.py
|
<reponame>Rudedog9d/pypsi<gh_stars>10-100
import pytest
from pypsi.cmdline import *
from pypsi.features import BashFeatures
class TestCondense(object):
def setup(self):
self.parser = StatementParser(features=BashFeatures())
def test_whitespace(self):
tokens = [
StringToken(0, "echo"),
WhitespaceToken(1),
StringToken(2, "hello")
]
assert self.parser.condense(tokens) == [
StringToken(0, "echo"),
StringToken(1, "hello")
]
def test_condense_strings(self):
assert (
self.parser.condense([
StringToken(0, "echo"),
WhitespaceToken(1),
StringToken(2, "hello"),
StringToken(3, "world", quote="'")
]) == [
StringToken(0, "echo"),
StringToken(2, "helloworld", quote="'"),
]
)
def test_condense_mixed_quotes(self):
assert (
self.parser.condense([
StringToken(0, "echo", quote="'"),
StringToken(1, "hello"),
StringToken(2, "world", quote="\"")
]) == [StringToken(0, "echohelloworld", quote="\"")]
)
def test_all_whitespace(self):
assert self.parser.condense([WhitespaceToken(0), WhitespaceToken(1)]) == []
def test_operator(self):
assert (
self.parser.condense([
StringToken(0, "echo"),
WhitespaceToken(1),
StringToken(2, "hello world", quote="'"),
WhitespaceToken(3),
OperatorToken(4, ">"),
WhitespaceToken(5),
StringToken(6, "output.txt")
]) == [
StringToken(0, "echo"),
StringToken(1, "hello world", quote="'"),
OperatorToken(2, ">"),
StringToken(3, "output.txt")
]
)
|
arifparvez14/Basic-and-competetive-programming
|
Basic-Programming/Pointer/Pointer assign to int.cpp
|
<reponame>arifparvez14/Basic-and-competetive-programming
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x=10;
int *p;
int y;
printf("The value of x: %d\n",x);
p=&x;
y=*p;
*p=15;
printf("Value of x: %d\n",x);
printf("Value of y: %d\n",y);
printf("Value of *p: %d\n",*p);
printf("Address of x: %p\n",&x);
printf("Address of y: %p\n",&y);
printf("Value of p: %p\n",p);
return 0;
}
|
UbuntuEvangelist/contrail-controller
|
src/vnsw/agent/uve/vrouter_uve_entry.h
|
<filename>src/vnsw/agent/uve/vrouter_uve_entry.h
/*
* Copyright (c) 2013 <NAME>, Inc. All rights reserved.
*/
#ifndef vnsw_agent_vrouter_uve_entry_h
#define vnsw_agent_vrouter_uve_entry_h
#include <uve/vrouter_uve_entry_base.h>
#include <uve/stats_manager.h>
//The class that defines data-structures to store VRouter information
//required for sending VRouter UVE.
class VrouterUveEntry : public VrouterUveEntryBase {
public:
VrouterUveEntry(Agent *agent);
virtual ~VrouterUveEntry();
L4PortBitmap port_bitmap() { return port_bitmap_; }
virtual bool SendVrouterMsg();
void UpdateBitmap(uint8_t proto, uint16_t sport, uint16_t dport);
protected:
uint8_t bandwidth_count_;
L4PortBitmap port_bitmap_;
uint64_t prev_flow_setup_rate_export_time_;
uint64_t prev_flow_created_;
uint64_t prev_flow_aged_;
private:
void InitPrevStats() const;
void FetchDropStats(AgentDropStats &ds) const;
bool SetVrouterPortBitmap(VrouterStatsAgent &vr_stats);
uint64_t CalculateBandwitdh(uint64_t bytes, int speed_mbps,
int diff_seconds, double *utilization_bps) const;
uint64_t GetBandwidthUsage(StatsManager::InterfaceStats *s,
bool dir_in, int mins, double *util) const;
bool BuildPhysicalInterfaceBandwidth(std::vector<AgentIfBandwidth> &list,
uint8_t mins) const;
bool BuildPhysicalInterfaceBandwidth(map<string,uint64_t> &imp,
map<string,uint64_t> &omp,
uint8_t mins, double &in_util,
double &out_util) const;
bool BuildPhysicalInterfaceList(std::vector<AgentIfStats> &list) const;
std::string GetMacAddress(const MacAddress &mac) const;
void BuildXmppStatsList(std::vector<AgentXmppStats> &list) const;
uint64_t start_time_;
DISALLOW_COPY_AND_ASSIGN(VrouterUveEntry);
};
#endif // vnsw_agent_vrouter_uve_entry_h
|
navikt/testnorge
|
apps/testnorge-hodejegeren/src/main/java/no/nav/registre/hodejegeren/provider/rs/responses/NavEnhetResponse.java
|
package no.nav.registre.hodejegeren.provider.rs.responses;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class NavEnhetResponse {
private String ident;
private String navEnhet;
private String navEnhetBeskrivelse;
}
|
rkh/heroku
|
lib/heroku/command/ps.rb
|
<reponame>rkh/heroku
require "heroku/command/base"
# manage dynos (dynos, workers)
#
class Heroku::Command::Ps < Heroku::Command::Base
COSTS = {"Free"=>0, "Hobby"=>7, "Standard-1X"=>25, "Standard-2X"=>50, "Performance-M"=>250, "Performance"=>500, "Performance-L"=>500, "1X"=>36, "2X"=>72, "PX"=>576}
# ps:dynos [QTY]
#
# DEPRECATED: use `heroku ps:scale dynos=N`
#
# scale to QTY web processes
#
# if QTY is not specified, display the number of web processes currently running
#
#Example:
#
# $ heroku ps:dynos 3
# Scaling dynos... done, now running 3
#
def dynos
# deprecation notice added to v2.21.3 on 03/16/12
display("~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`")
dynos = shift_argument
validate_arguments!
if dynos
action("Scaling dynos") do
new_dynos = api.put_dynos(app, dynos).body["dynos"]
status("now running #{new_dynos}")
end
else
app_data = api.get_app(app).body
if app_data["stack"] == "cedar"
raise(Heroku::Command::CommandFailed, "For Cedar apps, use `heroku ps`")
else
display("#{app} is running #{quantify("dyno", app_data["dynos"])}")
end
end
end
alias_command "dynos", "ps:dynos"
# ps:workers [QTY]
#
# DEPRECATED: use `heroku ps:scale workers=N`
#
# scale to QTY background processes
#
# if QTY is not specified, display the number of background processes currently running
#
#Example:
#
# $ heroku ps:dynos 3
# Scaling workers... done, now running 3
#
def workers
# deprecation notice added to v2.21.3 on 03/16/12
display("~ `heroku ps:workers QTY` has been deprecated and replaced with `heroku ps:scale workers=QTY`")
workers = shift_argument
validate_arguments!
if workers
action("Scaling workers") do
new_workers = api.put_workers(app, workers).body["workers"]
status("now running #{new_workers}")
end
else
app_data = api.get_app(app).body
if app_data["stack"] == "cedar"
raise(Heroku::Command::CommandFailed, "For Cedar apps, use `heroku ps`")
else
display("#{app} is running #{quantify("worker", app_data["workers"])}")
end
end
end
alias_command "workers", "ps:workers"
# ps
#
# list dynos for an app
#
#Example:
#
# $ heroku ps
# === run: one-off dyno
# run.1: up for 5m: `bash`
#
# === web: `bundle exec thin start -p $PORT`
# web.1: created for 30s
#
def index
validate_arguments!
quota_resp = api.request(
:expects => [200, 404],
:method => :post,
:path => "/apps/#{app}/actions/get-quota",
:headers => {
"Accept" => "application/vnd.heroku+json; version=3.app-quotas",
"Content-Type" => "application/json"
}
)
if quota_resp.status = 200
quota = quota_resp.body
now = Time.now.getutc
quota_message = if quota["allow_until"]
"Free quota left:"
elsif quota["deny_until"]
"Free quota exhausted. Unidle available in:"
end
if quota_message
quota_timestamp = (quota["allow_until"] ? Time.parse(quota["allow_until"]).getutc : Time.parse(quota["deny_until"]).getutc)
time_left = time_remaining(Time.now.getutc, quota_timestamp)
display("#{quota_message} #{time_left}")
end
end
processes_resp = api.request(
:expects => 200,
:method => :get,
:path => "/apps/#{app}/dynos",
:headers => {
"Accept" => "application/vnd.heroku+json; version=3",
"Content-Type" => "application/json"
}
)
processes = processes_resp.body
processes_by_command = Hash.new {|hash,key| hash[key] = []}
processes.each do |process|
now = Time.now
type = process["type"]
elapsed = now - Time.iso8601(process['updated_at'])
since = time_ago(now - elapsed)
size = process["size"] || "1X"
if type == "run"
key = "run: one-off processes"
item = "%s (%s): %s %s: `%s`" % [ process["name"], size, process["state"], since, process["command"] ]
else
key = "#{type} (#{size}): `#{process["command"]}`"
item = "%s: %s %s" % [ process['name'], process['state'], since ]
end
processes_by_command[key] << item
end
extract_run_id = /\.(\d+).*:/
processes_by_command.keys.each do |key|
processes_by_command[key] = processes_by_command[key].sort do |x,y|
x.match(extract_run_id).captures.first.to_i <=> y.match(extract_run_id).captures.first.to_i
end
end
processes_by_command.keys.sort.each do |key|
styled_header(key)
styled_array(processes_by_command[key], :sort => false)
end
end
# ps:restart [DYNO]
#
# restart an app dyno
#
# if DYNO is not specified, restarts all dynos on the app
#
#Examples:
#
# $ heroku ps:restart web.1
# Restarting web.1 dyno... done
#
# $ heroku ps:restart web
# Restarting web dyno... done
#
# $ heroku ps:restart
# Restarting dynos... done
#
def restart
dyno = shift_argument
validate_arguments!
message, options = case dyno
when NilClass
["Restarting dynos", {}]
when /.+\..+/
ps = args.first
["Restarting #{ps} dyno", { :ps => ps }]
else
type = args.first
["Restarting #{type} dynos", { :type => type }]
end
action(message) do
api.post_ps_restart(app, options)
end
end
alias_command "restart", "ps:restart"
# ps:scale DYNO1=AMOUNT1 [DYNO2=AMOUNT2 ...]
#
# scale dynos by the given amount
#
# appending a size (eg. web=2:2X) allows simultaneous scaling and resizing
#
#Examples:
#
# $ heroku ps:scale web=3:2X worker+1
# Scaling dynos... done, now running web at 3:2X, worker at 1:1X.
#
def scale
requires_preauth
changes = args.map do |arg|
if change = arg.scan(/^([a-zA-Z0-9_]+)([=+-]\d+)(?::([\w-]+))?$/).first
formation, quantity, size = change
quantity = quantity[1..-1].to_i if quantity[0] == "="
{ "type" => formation, "quantity" => quantity, "size" => size}
end
end.compact
if changes.empty?
error("Usage: heroku ps:scale DYNO1=AMOUNT1[:SIZE] [DYNO2=AMOUNT2 ...]\nMust specify DYNO and AMOUNT to scale.\nDYNO must be alphanumeric.")
end
action("Scaling dynos") do
new_scales = scale_dynos(get_formation, changes)
.map {|p| "#{p["type"]} at #{p["quantity"]}:#{p["size"]}" }
status("now running " + new_scales.join(", ") + ".")
end
end
alias_command "scale", "ps:scale"
# ps:stop DYNOS
#
# stop an app dyno
#
# Examples:
#
# $ heroku stop run.3
# Stopping run.3 dyno... done
#
# $ heroku stop run
# Stopping run dynos... done
#
def stop
dyno = shift_argument
validate_arguments!
message, options = case dyno
when NilClass
error("Usage: heroku ps:stop DYNO\nMust specify DYNO to stop.")
when /.+\..+/
ps = args.first
["Stopping #{ps} dyno", { :ps => ps }]
else
type = args.first
["Stopping #{type} dynos", { :type => type }]
end
action(message) do
api.post_ps_stop(app, options)
end
end
alias_command "stop", "ps:stop"
# ps:type [TYPE | DYNO=TYPE [DYNO=TYPE ...]]
#
# manage dyno types
#
# called with no arguments shows the current dyno type
#
# called with one argument sets the type
# where type is one of free|hobby|standard-1x|standard-2x|performance
#
# called with 1..n DYNO=TYPE arguments sets the type per dyno
#
def type
requires_preauth
app
formation = get_formation
changes = if args.any?{|arg| arg =~ /=/}
args.map do |arg|
if arg =~ /^([a-zA-Z0-9_]+)=([\w-]+)$/
p = formation.find{|f| f["type"] == $1}.clone
p["size"] = $2
p
end
end.compact
elsif args.any?
size = shift_argument.downcase
validate_arguments!
formation.map{|p| p["size"] = size; p}
end
scale_dynos(formation, changes) if changes
display_dyno_type_and_costs(get_formation)
end
alias_method :resize, :type
alias_command "resize", "ps:type"
private
def patch_tier(process_tier)
api.request(
:method => :patch,
:path => "/apps/#{app}",
:body => json_encode("process_tier" => process_tier),
:headers => {
"Accept" => "application/vnd.heroku+json; version=edge",
"Content-Type" => "application/json"
}
)
end
def display_dyno_type_and_costs(formation)
annotated = formation.sort_by{|d| d['type']}.map do |dyno|
cost = COSTS[dyno["size"]]
{
'dyno' => dyno['type'],
'type' => dyno['size'].rjust(4),
'qty' => dyno['quantity'].to_s.rjust(3),
'cost/mo' => cost ? (cost * dyno["quantity"]).to_s.rjust(7) : ''
}
end
if annotated.empty?
error "No process types on #{app}.\nUpload a Procfile to add process types.\nhttps://devcenter.heroku.com/articles/procfile"
else
display_table(annotated, annotated.first.keys, annotated.first.keys)
end
end
def get_formation
api.request(
:expects => 200,
:method => :get,
:path => "/apps/#{app}/formation",
:headers => {
"Accept" => "application/vnd.heroku+json; version=3",
"Content-Type" => "application/json"
}
).body
end
def change_tier_if_needed(formation, changes)
# first find what tier(s) the user wants to move to
# if there are multiple it will be caught later
new_tiers = tiers_in_formation(changes)
# no tier specified, so we don't need to change anything
return if new_tiers.length == 0
# we have an unknown tier
# instead of validating in the CLI, just continue
# the API will error if there is an issue
return unless new_tiers.all?
new_tier = new_tiers[0]
current_tier = tiers_in_formation(formation).first
# the formation has no tier
# change the tier to the requested one
return patch_tier(new_tier) unless current_tier
# tiers in formation and ps:scale are the same
# just continue
return if new_tier == current_tier
# is the user changing all the dyno types to the new tier?
if consistent_tier_after_changes?(formation, changes)
# all dyno types are changing to the new tier so we can change to it
patch_tier(new_tier)
else
# some of the proposed changes are in a different tier than existing dyno types
# this is not allowed
from_type = formation[0]["size"]
to_type = changes.map{|c| c["size"]}.compact.first
error("Cannot mix #{to_type} with #{from_type} dynos.\nTo change all dynos to #{to_type}, run `heroku ps:type #{to_type}`.")
end
end
def tiers_in_formation(formation)
tier_map = {
"free" => "free",
"hobby" => "hobby",
"standard-1x" => "production",
"standard-2x" => "production",
"performance" => "production",
}
formation
.select { |p| p["size"]} # types with a size
.select { |p| p["quantity"] > 0 } # types that have active dynos
.map { |p| p["size"]} # get the size of the type
.map { |s| tier_map[s.downcase]} # get the tier of the size
.uniq
end
def consistent_tier_after_changes?(formation, changes)
formation = pretend_changes_to_formation(formation, changes)
tiers_in_formation(formation).length == 1
end
# return a new formation object with changes applied
# in-memory only, does not hit API
def pretend_changes_to_formation(formation, changes)
formation = deep_clone(formation)
changes.each do |change|
ps = formation.find{|p| p["type"] == change["type"]}
next unless ps
ps["size"] = change["size"] if change["size"]
q = change["quantity"]
if q.is_a? Fixnum
ps["quantity"] = q
elsif q.start_with?('+')
ps["quantity"] += q[1..-1].to_i
elsif q.start_with?('-')
ps["quantity"] -= q[1..-1].to_i
end
end
formation
end
def scale_dynos(formation, changes)
change_tier_if_needed(formation, changes)
# The V3 API supports atomic scale+resize, so we make a raw request here
# since the heroku-api gem still only supports V2.
resp = api.request(
:expects => 200,
:method => :patch,
:path => "/apps/#{app}/formation",
:body => json_encode("updates" => changes),
:headers => {
"Accept" => "application/vnd.heroku+json; version=3",
"Content-Type" => "application/json"
}
)
resp.body.select {|p| changes.any?{|c| c["type"] == p["type"]} }
end
end
%w[type restart scale stop].each do |cmd|
Heroku::Command::Base.alias_command "dyno:#{cmd}", "ps:#{cmd}"
end
|
iuvhub/kunlun
|
internal/searcher/merge_test.go
|
<filename>internal/searcher/merge_test.go<gh_stars>10-100
package searcher
import (
"flag"
"testing"
"github.com/stretchr/testify/assert"
"github.com/huichen/kunlun/internal/common_types"
"github.com/huichen/kunlun/internal/query"
"github.com/huichen/kunlun/pkg/types"
)
func TestMergeSections(t *testing.T) {
flag.Parse()
sections := []*[]types.Section{
{{1, 2}},
{{3, 4}},
{{7, 8}},
}
r, err := mergeSections(sections)
assert.Nil(t, err)
assert.Equal(t, []types.Section{
{1, 2}, {3, 4}, {7, 8},
}, r)
sections = []*[]types.Section{
{{1, 2}, {3, 4}, {2, 4}, {7, 8}},
{{1, 2}, {3, 4}, {7, 8}},
}
_, err = mergeSections(sections)
logger.Error(err)
assert.NotNil(t, err)
sections = []*[]types.Section{
{{1, 2}, {3, 4}, {7, 8}},
{{1, 2}, {2, 4}, {4, 8}, {11, 12}},
}
r, _ = mergeSections(sections)
assert.Equal(t, []types.Section{
{1, 2}, {2, 4}, {3, 4}, {4, 8}, {7, 8}, {11, 12},
}, r)
sections = []*[]types.Section{
{{1, 2}, {3, 2}, {7, 8}},
{{1, 2}, {2, 4}, {4, 8}, {11, 12}},
}
r, _ = mergeSections(sections)
logger.Error(err)
assert.NotNil(t, err)
}
func TestMergeQueries1(t *testing.T) {
flag.Parse()
queries := []*query.Query{
{ID: 0},
{ID: 1},
{ID: 2},
}
context := Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {7, 8},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
},
},
},
}
r, err := mergeQueries(&context, queries, true)
assert.Nil(t, err)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {7, 8}, {10, 11}, {11, 12},
},
},
{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {5, 6}, {10, 11}, {11, 12},
},
},
{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
}, r)
r, err = mergeQueries(&context, queries, false)
assert.Nil(t, err)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {7, 8}, {10, 11}, {11, 12},
},
},
}, r)
queries = []*query.Query{
{ID: 0},
{ID: 1, Negate: true},
}
context = Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 14}, {11, 18},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 14}, {11, 18},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 14}, {7, 18},
},
},
},
},
},
}
r, err = mergeQueries(&context, queries, false)
assert.Nil(t, err)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 14}, {11, 18},
},
}}, r)
}
func TestMergeQueriesError(t *testing.T) {
flag.Parse()
queries := []*query.Query{
{ID: 0},
{ID: 1},
{ID: 2},
}
context := Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {7, 8},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
},
},
},
}
_, err := mergeQueries(&context, queries, true)
logger.Error(err)
assert.NotNil(t, err)
}
func TestMergeQueriesEmpty(t *testing.T) {
flag.Parse()
queries := []*query.Query{
{ID: 0},
{ID: 1},
{ID: 2},
}
context := Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
},
},
},
}
r, _ := mergeQueries(&context, queries, true)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {5, 6}, {10, 11}, {11, 12},
},
},
{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {5, 6}, {10, 11}, {11, 12},
},
},
{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
}, r)
r, _ = mergeQueries(&context, queries, false)
assert.Equal(t, []common_types.DocumentWithSections{}, r)
}
func TestMergeQueriesNegate(t *testing.T) {
flag.Parse()
queries := []*query.Query{
{ID: 0},
{ID: 1, Negate: true},
{ID: 2},
}
context := Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {7, 8},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 2,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
common_types.DocumentWithSections{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
},
},
},
}
r, err := mergeQueries(&context, queries, false)
assert.Nil(t, err)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 3,
Sections: []types.Section{
{1, 2}, {2, 3}, {5, 6}, {10, 11}, {11, 12},
},
},
}, r)
}
func TestMergeMoreQueries(t *testing.T) {
flag.Parse()
queries := []*query.Query{
{ID: 0},
{ID: 1},
}
context := Context{
query: &SearchQuery{
QueryResults: []*[]common_types.DocumentWithSections{
{
common_types.DocumentWithSections{
DocumentID: 4,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {7, 8},
},
},
},
{
common_types.DocumentWithSections{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
},
},
},
}
r, err := mergeQueries(&context, queries, true)
assert.Nil(t, err)
assert.Equal(t, []common_types.DocumentWithSections{
{
DocumentID: 1,
Sections: []types.Section{
{1, 2}, {2, 3}, {4, 5}, {11, 12},
},
},
{
DocumentID: 4,
Sections: []types.Section{
{1, 2}, {2, 3}, {3, 4}, {7, 8},
},
},
}, r)
}
|
arslansajid/rank-page
|
src/containers/AppMain/index.js
|
<filename>src/containers/AppMain/index.js
import React, {useEffect, useState} from 'react';
// import axios from "axios";
import { requestFirebaseNotificationPermission, onMessageListener } from '../../backend/utility'
import axiosInstance from "../../api/api.config";
import Cookie from "js-cookie";
import { makeStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
import { checkIfLoggedIn, UpdateFCMtoken } from "./actions";
import { userLogin } from "../../actions/LoginActions";
import LoadingSpinner from "../../components/Common/LoadingSpinner"
import ListCreation from "../../components/ListCreation";
import PoolCreation from "../../components/PoolCreation";
import SigninSignup from "../SigninSignup"
const AppContainer = (props) => {
const classes = useStyles();
const [isLoading, setIsLoading] = useState(true);
onMessageListener()
.then((payload) => {
console.log("############", payload)
})
useEffect(() => {
requestNotifications();
checkIfLoggedIn()
.then((res) => {
// console.log("res ###", res.data.data.user)
const token = Cookie.get('rankpage_access_token')
console.log("token ###", token)
// axios.defaults.headers.common['Authorization'] = `${token}`;
axiosInstance.defaults.headers['Authorization'] = `${token}`;
props.dispatch(userLogin(res.data.data.user));
setIsLoading(false);
})
.catch((err) => {
console.log("### USER IS NOT SIGNED IN !!! ###")
setIsLoading(false);
})
}, [])
const requestNotifications = () => {
requestFirebaseNotificationPermission()
.then((firebaseToken) => {
// eslint-disable-next-line no-console
console.log("############### firebaseToken", firebaseToken);
const data= {
fcm_web_token: firebaseToken,
fcm_mobile_token: null,
}
UpdateFCMtoken(data)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
})
.catch((err) => {
console.log("############### err", err);
return err;
});
}
if(isLoading) {
return (
<LoadingSpinner
loading={true}
text="Loading..."
size="large"
/>
)
} else {
return (
<>
<SigninSignup />
<ListCreation />
<PoolCreation />
</>
)
}
}
const useStyles = makeStyles((theme) => ({
})
)
function mapStateToProps(state) {
return {
user: state.user,
};
}
export default connect(mapStateToProps)(AppContainer);
|
riosun/dice
|
src/components/index.js
|
/**
* 组件入口点
* 引用方式: import { FootBar, GroupList } from '../../components';
*/
// import FootBar from './FootBar/FootBar';
// import MessageList from './MessageList/MessageList';
// import ContactsList from './ContactsList/ContactsList';
import Loading from './Loading/'
import BaseModal from './BaseModal/'
export { Loading, BaseModal }
|
kaebmoo/simple-server
|
app/schema/api/v2/schema.rb
|
<reponame>kaebmoo/simple-server
class Api::V2::Schema < Api::Current::Schema
class << self
def all_definitions
definitions.merge(Api::V2::Models.definitions)
end
end
end
|
JulianoCristian/GameServerCore
|
src/main/java/info/xiaomo/core/network/mina/service/ClientServerService.java
|
<filename>src/main/java/info/xiaomo/core/network/mina/service/ClientServerService.java
package info.xiaomo.core.network.mina.service;
import java.util.Map;
import info.xiaomo.core.network.mina.TcpServer;
import info.xiaomo.core.network.mina.code.ClientProtocolCodecFactory;
import info.xiaomo.core.network.mina.config.MinaServerConfig;
import info.xiaomo.core.network.mina.handler.ClientProtocolHandler;
import info.xiaomo.core.server.GameService;
import info.xiaomo.core.thread.ServerThread;
import info.xiaomo.core.thread.ThreadPoolExecutorConfig;
import info.xiaomo.core.thread.ThreadType;
import info.xiaomo.core.thread.timer.event.ServerHeartTimer;
import org.apache.mina.core.filterchain.IoFilter;
/**
* 游戏前端消息接收 服务
*
*
* @version $Id: $Id
* 2017年6月29日 下午2:15:38
*/
public class ClientServerService extends GameService<MinaServerConfig> {
protected final TcpServer tcpServer;
protected final MinaServerConfig minaServerConfig;
protected final ClientProtocolHandler clientProtocolHandler;
/**
* 不创建默认IO线程池
*/
public ClientServerService(MinaServerConfig minaServerConfig) {
this(null, minaServerConfig);
}
/**
* 使用默认消息处理器
*/
public ClientServerService(ThreadPoolExecutorConfig threadExecutorConfig, MinaServerConfig minaServerConfig) {
this(threadExecutorConfig, minaServerConfig, new ClientProtocolHandler(8));
}
/**
* <p>Constructor for ClientServerService.</p>
*
* @param threadExecutorConfig 线程池配置
* @param minaServerConfig 服务器配置
* @param clientProtocolHandler 消息处理器
*/
public ClientServerService(ThreadPoolExecutorConfig threadExecutorConfig, MinaServerConfig minaServerConfig,
ClientProtocolHandler clientProtocolHandler) {
super(threadExecutorConfig);
this.minaServerConfig = minaServerConfig;
this.clientProtocolHandler = clientProtocolHandler;
tcpServer = new TcpServer(minaServerConfig, clientProtocolHandler, new ClientProtocolCodecFactory());
}
/**
* <p>Constructor for ClientServerService.</p>
*
* @param threadExecutorConfig 线程池配置
* @param minaServerConfig 服务器配置
* @param clientProtocolHandler 消息处理器
* @param filters a {@link Map} object.
*/
public ClientServerService(ThreadPoolExecutorConfig threadExecutorConfig, MinaServerConfig minaServerConfig,
ClientProtocolHandler clientProtocolHandler, Map<String, IoFilter> filters) {
super(threadExecutorConfig);
this.minaServerConfig = minaServerConfig;
this.clientProtocolHandler = clientProtocolHandler;
tcpServer = new TcpServer(minaServerConfig, clientProtocolHandler, new ClientProtocolCodecFactory(), filters);
}
/**
* {@inheritDoc}
*/
@Override
protected void running() {
clientProtocolHandler.setService(this);
tcpServer.run();
// 添加定时器 ,如果心跳配置为0,则没有定时器
ServerThread syncThread = getExecutor(ThreadType.SYNC);
if (syncThread != null) {
syncThread.addTimerEvent(new ServerHeartTimer());
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onShutdown() {
super.onShutdown();
tcpServer.stop();
}
/**
* <p>Getter for the field <code>minaServerConfig</code>.</p>
*
*/
public MinaServerConfig getMinaServerConfig() {
return minaServerConfig;
}
/**
* <p>Getter for the field <code>tcpServer</code>.</p>
*
*/
public TcpServer getTcpServer() {
return tcpServer;
}
}
|
noche-x/Stardust-Engine
|
src/Graphics/3D/Mesh.cpp
|
<reponame>noche-x/Stardust-Engine
#include <Graphics/3D/Mesh.h>
namespace Stardust::Graphics::Render3D {
void Mesh::addVertex(Stardust::Graphics::Vertex v)
{
vertices.push_back(v);
}
void Mesh::clearMesh()
{
vertices.clear();
}
size_t Mesh::getSize()
{
return vertices.size();
}
void* Mesh::getData()
{
return vertices.data();
}
void Mesh::drawMesh()
{
sceGuEnable(GU_TEXTURE_2D);
sceGuFrontFace(GU_CCW);
sceGumDrawArray(GU_TRIANGLES, GU_VERTEX_32BITF | GU_TEXTURE_32BITF | GU_COLOR_8888 | GU_TRANSFORM_3D, getSize(), nullptr, getData());
}
void UntexturedMesh::addVertex(Stardust::Graphics::ColorVertex v)
{
vertices.push_back(v);
}
void UntexturedMesh::clearMesh()
{
vertices.clear();
}
size_t UntexturedMesh::getSize()
{
return vertices.size();
}
void* UntexturedMesh::getData()
{
return vertices.data();
}
void UntexturedMesh::drawMesh()
{
sceGuFrontFace(GU_CCW);
sceGumDrawArray(GU_TRIANGLES, GU_VERTEX_32BITF | GU_COLOR_8888 | GU_TRANSFORM_3D, getSize(), nullptr, getData());
}
}
|
akumetsuv/flood
|
src/EngineManaged/Bindings/UniformBuffer.h
|
<reponame>akumetsuv/flood
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
#include <Graphics/UniformBuffer.h>
namespace Flood
{
enum struct UniformDataType : unsigned char;
ref class UniformBufferElement;
ref class UniformBuffer;
value struct Vector3;
ref class Matrix4x3;
value struct Matrix4x4;
value struct Vector4;
ref class RefPtr;
public enum struct UniformDataType : unsigned char
{
Scalar_F = 0,
Scalar_I = 1,
Vector2_F = 2,
Vector3_F = 3,
Matrix2_F = 4,
Matrix3_F = 5,
Matrix4_F = 6,
Matrix2x3_F = 7,
Matrix3x2_F = 8,
Matrix2x4_F = 9,
Matrix4x2_F = 10,
Matrix3x4_F = 11,
Matrix4x3_F = 12
};
/// <summary>
/// Uniforms are named constants that can be set in programs. These are
/// allocated from a special frame bump allocator, that frees all the memory
/// when the frame ends.
/// </summary>
public ref class UniformBufferElement
{
public:
property ::UniformBufferElement* NativePtr;
UniformBufferElement(::UniformBufferElement* native);
UniformBufferElement(System::IntPtr native);
property System::String^ Name;
property Flood::UniformDataType Type;
property unsigned short Count;
property cli::array<unsigned char>^ Data;
};
/// <summary>
/// Represents a uniform buffer.
/// </summary>
public ref class UniformBuffer
{
public:
property ::UniformBuffer* NativePtr;
UniformBuffer(::UniformBuffer* native);
UniformBuffer(System::IntPtr native);
Flood::UniformBufferElement^ GetElement(System::String^ name, unsigned int size);
void RemoveUniform(System::String^ slot);
void SetUniform(System::String^ slot, int data);
void SetUniform(System::String^ slot, float value);
void SetUniform(System::String^ slot, Flood::Vector3 vec);
void SetUniform(System::String^ slot, Flood::Matrix4x4 _196);
};
}
|
NathanGugel/melon
|
src/melon/modules/cli/cli_module.c
|
#include "melon/modules/cli/cli_module.h"
#include "melon/modules/modules.h"
#include "melon/core/array.h"
#include "melon/core/tstring.h"
/***
* @module
*
* This module exposes an interface with the command line to make it
* easier to write utility scripts or terminal applications.
*/
#include <stdlib.h>
#include <assert.h>
static const char** argv = NULL;
static int argc = 0;
TRet melSetArgs(VM* vm, const char** eargv, int eargc)
{
argv = eargv;
argc = eargc;
return 0;
}
/***
* Returns the arguments passed on the command line to the current
* application.
*
* @returns An array of strings, each string is an argument
*/
static TByte getArgsFunc(VM* vm)
{
GCItem* arr = melNewArray(vm);
melM_stackEnsure(&vm->stack, vm->stack.top + 1);
Value* arrVal = melM_stackAllocRaw(&vm->stack);
arrVal->type = arr->type;
arrVal->pack.obj = arr;
for (int i = 0; i < argc; i++)
{
Value strVal;
strVal.type = MELON_TYPE_STRING;
strVal.pack.obj = melNewString(vm, argv[i], strlen(argv[i]));
melPushArray(vm, arr, &strVal);
}
return 1;
}
static const ModuleFunction funcs[] = {
// name, args, locals, func
{ "getArgs", 0, 0, &getArgsFunc },
{ NULL, 0, 0, NULL }
};
TRet melCliModuleInit(VM* vm)
{
return melNewModule(vm, funcs);
}
|
kagwicharles/Seniorproject-ui
|
node_modules/@iconify/icons-ic/round-person-add-alt-1.js
|
<reponame>kagwicharles/Seniorproject-ui
var data = {
"body": "<circle cx=\"9\" cy=\"8\" r=\"4\" fill=\"currentColor\"/><path d=\"M9 14c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4zm11-4V7h-2v3h-3v2h3v3h2v-3h3v-2z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
|
workze/jallcode
|
spr/src/main/java/com/ze/home/book/Book.java
|
<filename>spr/src/main/java/com/ze/home/book/Book.java
package com.ze.home.book;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
String name;
String id;
}
|
DeppSRL/open_bilanci
|
bilanci_project/bilanci/templatetags/voice_values.py
|
<reponame>DeppSRL/open_bilanci
# -*- coding: utf-8 -*-
from django import template
import hashlib
register = template.Library()
def comma2dot(value):
return value.replace(",", ".")
register.filter('comma2dot', comma2dot)
@register.inclusion_tag("bilanci/_voice_values.html", takes_context=True)
def voice_values(context, voice_slug, values, is_interventi=False):
"""
Compute the values for the given voice_slug.
is_interventi is a flag, set to True when the tag is called
within an interventi view
"""
absolute_value = ''
percapita_value = ''
if voice_slug in values['absolute'].keys():
absolute_value = values['absolute'][voice_slug]
if voice_slug in values['percapita'].keys():
percapita_value = values['percapita'][voice_slug]
return {
'absolute_value': absolute_value,
'percapita_value': percapita_value,
}
@register.inclusion_tag("bilanci/_voice_composition.html", takes_context=True)
def voice_composition(context, voice_slug, values):
# from the voce slug (in the somma funzioni branch) gets the investimenti and spese correnti values
# and computes the % of investment of the voice
if "interventi" in voice_slug.lower():
return {}
subslug_somma_funzioni = 'spese-somma-funzioni'
investimenti_voice_slug = voice_slug.replace(subslug_somma_funzioni, "spese-per-investimenti-funzioni")
correnti_voice_slug = voice_slug.replace(subslug_somma_funzioni, "spese-correnti-funzioni")
if voice_slug in values['absolute'].keys():
correnti = float(values['absolute'][correnti_voice_slug])
if investimenti_voice_slug in values['absolute'].keys():
investimenti = float(values['absolute'][investimenti_voice_slug])
total = values['absolute'][voice_slug]
if total:
correnti_perc = correnti / total * 100.0
investimenti_perc = investimenti / total * 100.0
else:
correnti_perc = 0.0
investimenti_perc = 0.0
return {
'hash': hashlib.sha512(voice_slug).hexdigest()[:8],
'correnti_value': correnti,
'correnti_perc': correnti_perc,
'investimenti_value': investimenti,
'investimenti_perc': investimenti_perc,
}
|
lechium/tvOS142Headers
|
System/Library/PrivateFrameworks/AssistantServices.framework/AFInterstitialProviderDelegate.h
|
<reponame>lechium/tvOS142Headers<filename>System/Library/PrivateFrameworks/AssistantServices.framework/AFInterstitialProviderDelegate.h
/*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:12:59 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/AssistantServices.framework/AssistantServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
@protocol AFInterstitialProviderDelegate <NSObject>
@required
-(void)interstitialProvider:(id)arg1 handlePhase:(long long)arg2 displayText:(id)arg3 speakableText:(id)arg4 expectedDelay:(double)arg5 context:(id)arg6 completion:(/*^block*/id)arg7;
@end
|
hafeez3000/panamax-ui
|
spec/support/fake_panamax_api.rb
|
require 'sinatra/base'
RSpec.configure do |config|
config.before(:each) do
stub_request(:any, /^#{PanamaxApi::URL}/).to_rack(FakePanamaxApi)
end
end
class FakePanamaxApi < Sinatra::Base
get '/search.json' do
json_response 200, 'search_results.json'
end
get '/local_images.json' do
json_response 200, 'images_representation.json'
end
post '/deployment_targets.json' do
json_response 201, 'deployment_target_representation.json'
end
get '/deployment_targets/:id.json' do
json_response 200, 'deployment_target_representation.json'
end
get '/deployment_targets.json' do
json_response 200, 'deployment_targets_representation.json'
end
get '/deployment_targets/:target_id/deployments.json' do
json_response 200, 'deployments_representation.json'
end
post '/deployment_targets/:target_id/deployments.json' do
json_response 201, 'deployment_representation.json'
end
post '/deployment_targets/:id/metadata/refresh.json' do
json_response 201, 'deployment_target_refresh_representation.json'
end
post '/jobs.json' do
json_response 201, 'job_representation.json'
end
get '/jobs.json' do
json_response 200, 'jobs_representation.json'
end
get '/jobs/:key/log.json' do
json_response 200, 'job_log_representation.json'
end
get '/job_templates/:id.json' do
json_response 200, 'job_template_representation.json'
end
get '/job_templates.json' do
json_response 200, 'job_templates_representation.json'
end
get '/registries.json' do
json_response 200, 'registries_representation.json'
end
get '/templates/:id.json' do
json_response 200, 'template_representation.json'
end
post '/templates.json' do
json_response 201, 'template_representation.json'
end
post '/templates/:id/save.json*' do
json_response 201, 'template_representation.json'
end
get '/repositories/:repo/tags' do
content_type :json
status 200
%w(foo bar).to_json
end
get '/apps.json' do
json_response 200, 'app_list_representation.json'
end
post '/apps.json' do
json_response 201, 'app_representation.json'
end
get '/apps/:id.:format' do |id, _format|
json_response 200, 'app_representation.json'
end
get '/apps/:app_id/services.json' do
json_response 200, 'services_representation.json'
end
get '/apps/:app_id/services/:id.?:format' do |_app_id, id, _format|
json_response 200, "service_representation_#{id}.json"
end
get '/apps/:app_id/categories/:id.?:format' do |_app_id, id, _format|
categories = [
{ 'id' => '1', 'name' => 'foo' },
{ 'id' => '2', 'name' => 'baz' },
{ 'id' => '3', 'name' => 'bar' },
{ 'id' => '4', 'name' => 'Web Tier' }
]
content_type :json
status 200
categories.find { |cat| cat['id'] == id.to_s }.to_json
end
put '/apps/:app_id/services/:id' do
status 204
end
put '/apps/:app_id/rebuild.:format' do
status 204
end
put '/apps/:app_id.:format' do
status 204
end
get '/user.json' do
json_response 200, 'user_representation.json'
end
delete '/apps/:app_id/services/:id.?:format' do
json_response 200, 'service_representation_1.json'
end
get '/keywords.json' do
json_response 200, 'keywords_representation.json'
end
get '/types.json' do
json_response 200, 'types_representation.json'
end
get '/template_repos.json' do
json_response 200, 'template_repos_representation.json'
end
post '/template_repos.json' do
status 201
end
delete '/template_repos/1.json' do
status 200
end
private
def json_response(response_code, file_name)
content_type :json
status response_code
File.open(File.dirname(__FILE__) + '/fixtures/' + file_name, 'rb').read
end
end
|
javietanh/cs544
|
src/main/java/edu/mum/domain/Buyer.java
|
package edu.mum.domain;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
public class Buyer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer points = 0;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "buyer", cascade = CascadeType.ALL)
private Set<Order> orders = new HashSet<>();
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "buyer", cascade = CascadeType.ALL)
private Set<CartItem> cartItems = new HashSet<>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "following", joinColumns = {@JoinColumn(name = "buyer_id")}, inverseJoinColumns = {@JoinColumn(name = "seller_id")})
private List<Seller> sellers = new ArrayList<Seller>();
public void followSeller(Seller seller) {
sellers.add(seller);
}
public void unfollowSeller(Seller seller) {
sellers.remove(seller);
}
public void addCartItem(CartItem item) {
cartItems.add(item);
}
public void removeCartItem(CartItem item) {
cartItems.remove(item);
}
public void addOrder(Order order) {
orders.add(order);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getPoints() {
return points;
}
public void setPoints(Integer points) {
this.points = points;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
public Set<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(Set<CartItem> cartItems) {
this.cartItems = cartItems;
}
public List<Seller> getSellers() {
return sellers;
}
public void setSellers(List<Seller> sellers) {
this.sellers = sellers;
}
}
|
FabioSenac/ProjetoIntegradorGrupo1
|
Web_Service/abastecimento/src/main/java/com/bd/model/Abastecimento.java
|
<reponame>FabioSenac/ProjetoIntegradorGrupo1
package com.bd.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "abastecimento")
public class Abastecimento {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "abas_id")
private long id;
@Column(name = "abas_data")
private Date data;
@Column(name = "abas_totlitros")
private double totLitros;
@Column(name = "abas_odometro")
private int odometro;
// @Column(name = "abas_valor_tot")
// private double valor_tot;
@Column(name = "abas_vlr_unit")
private double valor_unit;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public double getTotLitros() {
return totLitros;
}
public void setTotLitros(double totLitros) {
this.totLitros = totLitros;
}
public int getOdometro() {
return odometro;
}
public void setOdometro(int odometro) {
this.odometro = odometro;
}
// public double getValor_tot() {
// return valor_tot;
// }
//
// public void setValor_tot(double valor_tot) {
// this.valor_tot = valor_tot;
// }
public double getValor_unit() {
return valor_unit;
}
public void setValor_unit(double valor_unit) {
this.valor_unit = valor_unit;
}
@ManyToOne
@JoinColumn(name = "Vei_id")
private Veiculo veiculo;
public Veiculo getVeiculo() {
return veiculo;
}
public void setVeiculo(Veiculo veiculo) {
this.veiculo = veiculo;
}
@ManyToOne
@JoinColumn(name = "pos_id")
private Posto posto;
public Posto getPosto() {
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
}
|
romanczukrobert/currencycloud-java
|
src/main/java/com/currencycloud/client/model/ConversionSplit.java
|
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionSplit implements Entity {
private String id;
private BigDecimal amount;
private ConversionSplitDetails parentConversion;
private ConversionSplitDetails childConversion;
protected ConversionSplit() {
}
private ConversionSplit(String id, BigDecimal amount) {
this.id = id;
this.amount = amount;
}
public static ConversionSplit create() {
return new ConversionSplit();
}
public static ConversionSplit create(String id, BigDecimal amount) {
return new ConversionSplit(id, amount);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public ConversionSplitDetails getParentConversion() {
return parentConversion;
}
public void setParentConversion(ConversionSplitDetails parentConversion) {
this.parentConversion = parentConversion;
}
public ConversionSplitDetails getChildConversion() {
return childConversion;
}
public void setChildConversion(ConversionSplitDetails childConversion) {
this.childConversion = childConversion;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("parentConversion", parentConversion);
map.put("childConversion", childConversion);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
|
kad3nce/collective
|
gems/gems/data_objects-0.9.5/lib/data_objects/result.rb
|
module DataObjects
class Result
attr_accessor :insert_id, :affected_rows
def initialize(command, affected_rows, insert_id = nil)
@command, @affected_rows, @insert_id = command, affected_rows, insert_id
end
def to_i
@affected_rows
end
end
end
|
nodumo/scala_template_platform_backend
|
common/src/test/scala/org/mastermold/platform/common/validation/generator/data/DataAddress.scala
|
package org.mastermold.platform.common.validation.generator.data
object DataAddress {
}
|
seunghyunbaek/ThreeLine-Diary
|
app/src/main/java/com/example/myapplication/com/example/myapplication/data/DiaryBookSharedPreference.java
|
<filename>app/src/main/java/com/example/myapplication/com/example/myapplication/data/DiaryBookSharedPreference.java
package com.example.myapplication.com.example.myapplication.data;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.Map;
public class DiaryBookSharedPreference extends BaseSharedPreference {
// 일기책 데이터를 관리하는 클래스
// 생성자
public DiaryBookSharedPreference(SharedPreferences sharedPreferences) {
super(sharedPreferences);
}
// 일기책 저장하기
public void saveDiaryBook(DiaryBook diaryBook) {
// 일기책 데이터를 JSON형식으로 변경해줍니다
String diaryBookJson = gson.toJson(diaryBook, DiaryBook.class);
editor.putString(diaryBook.getDiaryBookKey(), diaryBookJson);
editor.commit();
}
public void saveMapData(String key, String value) {
editor.putString(key, value);
editor.commit();
}
// 일기책 찾기
public DiaryBook findDiaryBook(String diaryBookKey) {
String diaryBookJson = sharedPreferences.getString(diaryBookKey, "");
// 키에 맞는 일기책이 없으면 null값을 리턴
if (diaryBookJson.equals(""))
return null;
// 일기책을 리턴해줍니다
DiaryBook diaryBook = gson.fromJson(diaryBookJson, DiaryBook.class);
return diaryBook;
}
// 모든 일기책을 돌려줍니다
public ArrayList<DiaryBook> loadOpenAllDiaryBook() {
// 저장된 모든 일기책을 가져온다
ArrayList<DiaryBook> diaryBooks = new ArrayList<DiaryBook>();
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
String diaryBookJson = sharedPreferences.getString(entry.getKey(), "");
DiaryBook diaryBook = gson.fromJson(diaryBookJson, DiaryBook.class);
if (diaryBook.isActivate())
if (diaryBook.isOpen())
diaryBooks.add(diaryBook);
}
return diaryBooks;
}
// 모든 일기책을 돌려줍니다
public ArrayList<DiaryBook> loadAllDiaryBook() {
// 저장된 모든 일기책을 가져온다
ArrayList<DiaryBook> diaryBooks = new ArrayList<DiaryBook>();
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
String diaryBookJson = sharedPreferences.getString(entry.getKey(), "");
DiaryBook diaryBook = gson.fromJson(diaryBookJson, DiaryBook.class);
diaryBooks.add(diaryBook);
}
return diaryBooks;
}
// 해당 유저의 모든 일기책 목록을 돌려줍니다
public ArrayList<DiaryBook> userDiaryBook(String useremail) {
ArrayList<DiaryBook> diaryBooks = new ArrayList<DiaryBook>(); // 유저의 일기책을 담을 리스트
ArrayList<DiaryBook> allDiaryBooks = loadAllDiaryBook(); // 모든 일기책을 가져옵니다
for (DiaryBook diaryBook : allDiaryBooks) {
if (diaryBook.isUserDiaryBook(useremail)) // 유저의 일기책입니까? true -> 리스트에 추가하기
// if (diaryBook.isActivate())
diaryBooks.add(diaryBook);
}
return diaryBooks; // 유저의 일기책들을 반환해줍니다
}
// 유저의 활성화된 일기책 목록을 돌려줍니다
public ArrayList<DiaryBook> activatedUserDiaryBook(String useremail) {
ArrayList<DiaryBook> userDiaryBooks = userDiaryBook(useremail);
ArrayList<DiaryBook> activatedDiaryBooks = new ArrayList<DiaryBook>();
for (DiaryBook userDiaryBook : userDiaryBooks) {
if (userDiaryBook.isActivate()) // 활성화된 일기책이면 활성화된 일기책 목록에 추가해줍니다
activatedDiaryBooks.add(userDiaryBook);
}
return activatedDiaryBooks;
}
// 유저의 혼자쓰는 일기책을 돌려줍니다
public ArrayList<DiaryBook> userAloneDiaryBook(String useremail) {
ArrayList<DiaryBook> diaryBooks = new ArrayList<DiaryBook>(); // 유저의 혼자쓰는 일기책을 담을 리스트
ArrayList<DiaryBook> userDiaryBooks = userDiaryBook(useremail); // 유저의 모든 일기책을 가져옵니다
// 유저의 일기책 중 혼자 쓰는 일기책인지 체크합니다
for (DiaryBook userDiaryBook : userDiaryBooks) {
if (userDiaryBook.isAloneDIaryBook()) // 유저의 일기책이 혼자쓰는 일기책입니까? true -> 리스트에 추가하기
diaryBooks.add(userDiaryBook);
}
return diaryBooks;
}
// 유저의 같이쓰는 일기책을 돌려줍니다
public ArrayList<DiaryBook> userJoinDiaryBook(String useremail) {
ArrayList<DiaryBook> diaryBooks = new ArrayList<DiaryBook>(); // 유저의 같이쓰는 일기책을 담을 리스트
ArrayList<DiaryBook> userDiaryBooks = userDiaryBook(useremail); // 유저의 모든 일기책을 가져옵니다
// 유저의 일기책 중 같이쓰는 일기책인지 체크합니다
for (DiaryBook userDiaryBook : userDiaryBooks) {
if (!userDiaryBook.isAloneDIaryBook()) // 유저의 일기책이 혼자쓰는 일기책입니까? false -> 같이쓰는 일기책이므로 추가하기
diaryBooks.add(userDiaryBook);
}
return diaryBooks;
}
// 유저의 구독중인 일기책을 돌려줍니다
public ArrayList<DiaryBook> userSubscribeDiaryBook(String useremail) {
ArrayList<DiaryBook> userSubscribeDiaryBooks = new ArrayList<DiaryBook>();
ArrayList<DiaryBook> allDiaryBooks = loadOpenAllDiaryBook();
for (DiaryBook diaryBook : allDiaryBooks) {
if (diaryBook.isSubscribeDiaryBook(useremail)) // 구독중인 일기책이면
userSubscribeDiaryBooks.add(diaryBook); // 유저의 구독중인 일기책에 추가해줍니다
}
return userSubscribeDiaryBooks;
}
// 유저의 일기책 데이터를 삭제합니다
public void removeUserDiaryBook(String diaryBookKey) {
editor.remove(diaryBookKey);
editor.commit();
}
public void clearDiaryBooks() {
editor.clear();
editor.commit();
}
}
|
edwnmrtnz/posko-rails
|
app/models/order.rb
|
class Order < ApplicationRecord
has_many :order_lines
has_many :transactions
belongs_to :account
belongs_to :user
belongs_to :customer
validates :order_number, presence: true
validates :total_line_items_price, presence: true
validates :total_discounts, presence: true
validates :subtotal, presence: true
validates :total_price, presence: true
validates :total_tax, presence: true
validates :total_weight, presence: true
# Temporary code to comply to orders requirement
before_validation :pass_validations, on: :create
def pass_validations
self.total_line_items_price = 0
self.total_discounts = 0
self.subtotal = 0
self.total_price = 0
self.total_tax = 0
self.total_weight =0
end
end
|
Archive-42/a-whole-bunch-o-gatsby-templates
|
css-custom-properties-examples/main.js
|
<gh_stars>0
const root = document.documentElement;
const button = document.querySelector(".special-button");
const colorInput = document.querySelector("#choose-theme-color");
document.addEventListener("mousemove", e => {
/* Frank's eyes */
const Frank_x = e.clientX / innerWidth;
const Frank_y = e.clientY / innerHeight;
root.style.setProperty('--mouse-x', Frank_x);
root.style.setProperty('--mouse-y', Frank_y);
/* Button Gradient Effect */
const Button_x = e.pageX - e.target.offsetLeft;
const Button_y = e.pageY - e.target.offsetTop;
button.style.setProperty('--x', `${Button_x}px`);
button.style.setProperty('--y', `${Button_y}px`);
});
/* Themed Site */
colorInput.addEventListener("change", function() {
root.style.setProperty('--themeColor', this.value);
});
|
jaouahbi/VampPlugins
|
qm-dsp/dsp/segmentation/cluster_melt.c
|
<reponame>jaouahbi/VampPlugins<gh_stars>0
/*
* cluster.c
* cluster_melt
*
* Created by <NAME> on 21/02/2006.
* Copyright 2006 Centre for Digital Music, Queen Mary, University of London.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*
*/
#include <stdlib.h>
#include "cluster_melt.h"
#define DEFAULT_LAMBDA 0.02;
#define DEFAULT_LIMIT 20;
double kldist(double* a, double* b, int n) {
/* NB assume that all a[i], b[i] are non-negative
because a, b represent probability distributions */
double q, d;
int i;
d = 0;
for (i = 0; i < n; i++)
{
q = (a[i] + b[i]) / 2.0;
if (q > 0)
{
if (a[i] > 0)
d += a[i] * log(a[i] / q);
if (b[i] > 0)
d += b[i] * log(b[i] / q);
}
}
return d;
}
void cluster_melt(double *h, int m, int n, double *Bsched, int t, int k, int l, int *c) {
double lambda, sum, beta, logsumexp, maxlp;
int i, j, a, b, b0, b1, limit, B, it, maxiter, maxiter0, maxiter1;
double** cl; /* reference histograms for each cluster */
int** nc; /* neighbour counts for each histogram */
double** lp; /* soft assignment probs for each histogram */
int* oldc; /* previous hard assignments (to check convergence) */
/* NB h is passed as a 1d row major array */
/* parameter values */
lambda = DEFAULT_LAMBDA;
if (l > 0)
limit = l;
else
limit = DEFAULT_LIMIT; /* use default if no valid neighbourhood limit supplied */
B = 2 * limit + 1;
maxiter0 = 20; /* number of iterations at initial temperature */
maxiter1 = 5; /* number of iterations at subsequent temperatures */
/* allocate memory */
cl = (double**) malloc(k*sizeof(double*));
for (i= 0; i < k; i++)
cl[i] = (double*) malloc(m*sizeof(double));
nc = (int**) malloc(n*sizeof(int*));
for (i= 0; i < n; i++)
nc[i] = (int*) malloc(k*sizeof(int));
lp = (double**) malloc(n*sizeof(double*));
for (i= 0; i < n; i++)
lp[i] = (double*) malloc(k*sizeof(double));
oldc = (int*) malloc(n * sizeof(int));
/* initialise */
for (i = 0; i < k; i++)
{
sum = 0;
for (j = 0; j < m; j++)
{
cl[i][j] = rand(); /* random initial reference histograms */
sum += cl[i][j] * cl[i][j];
}
sum = sqrt(sum);
for (j = 0; j < m; j++)
{
cl[i][j] /= sum; /* normalise */
}
}
//print_array(cl, k, m);
for (i = 0; i < n; i++)
c[i] = 1; /* initially assign all histograms to cluster 1 */
for (a = 0; a < t; a++)
{
beta = Bsched[a];
if (a == 0)
maxiter = maxiter0;
else
maxiter = maxiter1;
for (it = 0; it < maxiter; it++)
{
//if (it == maxiter - 1)
// mexPrintf("hasn't converged after %d iterations\n", maxiter);
for (i = 0; i < n; i++)
{
/* save current hard assignments */
oldc[i] = c[i];
/* calculate soft assignment logprobs for each cluster */
sum = 0;
for (j = 0; j < k; j++)
{
lp[i][ j] = -beta * kldist(cl[j], &h[i*m], m);
/* update matching neighbour counts for this histogram, based on current hard assignments */
/* old version:
nc[i][j] = 0;
if (i >= limit && i <= n - 1 - limit)
{
for (b = i - limit; b <= i + limit; b++)
{
if (c[b] == j+1)
nc[i][j]++;
}
nc[i][j] = B - nc[i][j];
}
*/
b0 = i - limit;
if (b0 < 0)
b0 = 0;
b1 = i + limit;
if (b1 >= n)
b1 = n - 1;
nc[i][j] = b1 - b0 + 1; /* = B except at edges */
for (b = b0; b <= b1; b++)
if (c[b] == j+1)
nc[i][j]--;
sum += exp(lp[i][j]);
}
/* normalise responsibilities and add duration logprior */
logsumexp = log(sum);
for (j = 0; j < k; j++)
lp[i][j] -= logsumexp + lambda * nc[i][j];
}
//print_array(lp, n, k);
/*
for (i = 0; i < n; i++)
{
for (j = 0; j < k; j++)
mexPrintf("%d ", nc[i][j]);
mexPrintf("\n");
}
*/
/* update the assignments now that we know the duration priors
based on the current assignments */
for (i = 0; i < n; i++)
{
maxlp = lp[i][0];
c[i] = 1;
for (j = 1; j < k; j++)
if (lp[i][j] > maxlp)
{
maxlp = lp[i][j];
c[i] = j+1;
}
}
/* break if assignments haven't changed */
i = 0;
while (i < n && oldc[i] == c[i])
i++;
if (i == n)
break;
/* update reference histograms now we know new responsibilities */
for (j = 0; j < k; j++)
{
for (b = 0; b < m; b++)
{
cl[j][b] = 0;
for (i = 0; i < n; i++)
{
cl[j][b] += exp(lp[i][j]) * h[i*m+b];
}
}
sum = 0;
for (i = 0; i < n; i++)
sum += exp(lp[i][j]);
for (b = 0; b < m; b++)
cl[j][b] /= sum; /* normalise */
}
//print_array(cl, k, m);
//mexPrintf("\n\n");
}
}
/* free memory */
for (i = 0; i < k; i++)
free(cl[i]);
free(cl);
for (i = 0; i < n; i++)
free(nc[i]);
free(nc);
for (i = 0; i < n; i++)
free(lp[i]);
free(lp);
free(oldc);
}
|
caijh/supermarket-cloud
|
authorization-server/src/main/java/com/coding/commons/domain/client/model/ClientUserDetails.java
|
<reponame>caijh/supermarket-cloud
package com.coding.commons.domain.client.model;
import java.util.Collection;
import com.coding.commons.base.IndexEnum;
import com.coding.commons.domain.user.model.User;
import com.coding.commons.domain.user.model.UserStatusEnum;
import com.coding.commons.util.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
public class ClientUserDetails implements UserDetails {
private User user;
public ClientUserDetails(User user) {
this.user = user;
}
public User getUser() {
return user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if (CollectionUtils.isEmpty(this.user.getRoles())) {
return emptyList();
}
return this.user.getRoles().parallelStream().map(role -> (GrantedAuthority) role::getCode).collect(toList());
}
@Override
public String getPassword() {
return this.user.getPassword();
}
@Override
public String getUsername() {
return this.user.getAccount();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return UserStatusEnum.LOCKED != IndexEnum.valueOf(this.user.getStatus(), UserStatusEnum.class);
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return UserStatusEnum.NORMAL == IndexEnum.valueOf(this.user.getStatus(), UserStatusEnum.class);
}
}
|
szendezsombor/thesis
|
Codes/backend/models/item-type.model.js
|
const dataBase = require('../util/database').promise();
module.exports = class ItemType {
static getAllItemType() {
return new Promise((resolve, reject) => {
dataBase.execute('call getAllItemType()').then(([rows]) => {
if (rows[0][0] && rows[0][0].item_type_id) {
const itemTypes = [];
rows[0].forEach(itemType => {
itemTypes.push(ItemType.createItemTypeDataModel(itemType));
});
resolve(itemTypes);
} else {
reject(new Error('There Is No Item Type In The DataBase'));
}
}).catch(error => {
reject(new Error(`Get All Item Type Failed: ${error.message}`));
});
});
}
static getItemTypeById(itemTypeId) {
return new Promise(((resolve, reject) => {
dataBase.execute('call getItemTypeById(?)', [itemTypeId]).then(([rows]) => {
if (rows[0][0] && rows[0][0].item_type_id) {
resolve(ItemType.createItemTypeDataModel(rows[0][0]));
} else {
reject(new Error(`There Is No Item Type With This Id: ${itemTypeId}`));
}
}).catch(error => {
reject(new Error(`Get Item Type By Id Failed: ${error.message}`));
});
}));
}
static createItemType(type, subType) {
return new Promise(((resolve, reject) => {
dataBase.execute('call createItemType(?, ?)', [type, subType]).then(([rows]) => {
if (rows[0][0] && rows[0][0].item_type_id) {
resolve(ItemType.createItemTypeDataModel(rows[0][0]));
} else {
reject(new Error(`Item Type Already Exists`));
}
}).catch(error => {
reject(new Error(`Create Item Type Failed: ${error.message}`));
});
}));
}
static modifyItemType(itemTypeId, type, subType) {
return new Promise(((resolve, reject) => {
dataBase.execute('call modifyItemType(?, ?, ?)', [itemTypeId, type, subType]).then(([rows]) => {
if (rows[0][0] && rows[0][0].item_type_id) {
resolve(ItemType.createItemTypeDataModel(rows[0][0]));
} else {
reject(new Error(`Item Type Can Not Modify With An Id: ${supId}`));
}
}).catch(error => {
reject(new Error(`Modify Item Type Failed: ${error.message}`));
});
}));
}
static deleteItemType(itemTypeId) {
return new Promise(((resolve, reject) => {
dataBase.execute('call deleteItemType(?)', [itemTypeId]).then(([rows]) => {
if (rows[0][0] && rows[0][0].item_type_id_in && rows[0][0].item_type_id_in.toString() === itemTypeId.toString()) {
resolve('Deleted Item Type Successfully');
} else {
reject(new Error(`Can Not Delete Item Type With This Id: ${itemTypeId}`));
}
}).catch(error => {
reject(new Error(`Delete Item Type Failed: ${error.message}`));
});
}));
}
static createItemTypeDataModel(data) {
return {
itemTypeId: data.item_type_id,
type: data.type,
subType: data.sub_type
}
}
}
|
smhadisadati/TMTDyn
|
v2_TMTDyn_IJRR2020/Samples/Fabric/2. Passive/code/codegen/mex/EOM_eq/sprdmpF116.c
|
/*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
*
* sprdmpF116.c
*
* Code generation for function 'sprdmpF116'
*
*/
/* Include files */
#include <string.h>
#include "rt_nonfinite.h"
#include "EOM_eq.h"
#include "sprdmpF116.h"
#include "sqrt.h"
/* Variable Definitions */
static emlrtRSInfo fab_emlrtRSI = { 24,/* lineNo */
"sprdmpF116", /* fcnName */
"/home/hadi/MEGAsync/Hadi/AutoTMTDyn/Code/AutoTMTDyn/Beta/v1.0/Fabric/code/sprdmpF116.m"/* pathName */
};
static emlrtRSInfo gab_emlrtRSI = { 30,/* lineNo */
"sprdmpF116", /* fcnName */
"/home/hadi/MEGAsync/Hadi/AutoTMTDyn/Code/AutoTMTDyn/Beta/v1.0/Fabric/code/sprdmpF116.m"/* pathName */
};
static emlrtRSInfo kab_emlrtRSI = { 142,/* lineNo */
"sprdmpF116", /* fcnName */
"/home/hadi/MEGAsync/Hadi/AutoTMTDyn/Code/AutoTMTDyn/Beta/v1.0/Fabric/code/sprdmpF116.m"/* pathName */
};
static emlrtRSInfo lab_emlrtRSI = { 182,/* lineNo */
"sprdmpF116", /* fcnName */
"/home/hadi/MEGAsync/Hadi/AutoTMTDyn/Code/AutoTMTDyn/Beta/v1.0/Fabric/code/sprdmpF116.m"/* pathName */
};
/* Function Definitions */
void sprdmpF116(const emlrtStack *sp, const real_T in2[198], real_T out1[546],
real_T out2[6], real_T out3[6], real_T out4[6])
{
real_T t2;
real_T t3;
real_T t4;
real_T t5;
real_T t6;
real_T t7;
real_T t8;
real_T t9;
real_T t10;
real_T t11;
real_T t12;
real_T t15_tmp;
real_T t18_tmp;
real_T t19;
real_T t22;
real_T t25;
real_T t28_tmp;
real_T t33_tmp_tmp;
real_T t33_tmp;
real_T b_t33_tmp;
real_T t33;
real_T t36;
real_T t43_tmp_tmp;
real_T t43_tmp;
real_T b_t43_tmp;
real_T t47_tmp;
real_T t54_tmp;
real_T t52_tmp_tmp;
real_T t52_tmp;
real_T t56;
real_T t59_tmp;
real_T t60;
real_T t62;
real_T t63;
real_T t64_tmp;
real_T b_t64_tmp;
real_T c_t64_tmp;
real_T t64;
real_T t67;
real_T t68;
real_T t74;
real_T t75;
real_T t77_tmp;
real_T t92;
real_T t93;
real_T t111;
real_T t94_tmp;
real_T t96;
real_T t100;
real_T t103;
real_T t107;
real_T t108_tmp;
real_T t117_tmp;
real_T t118;
real_T t119;
real_T t124;
real_T t125;
real_T t126;
real_T t130_tmp;
real_T b_t130_tmp;
real_T t130;
real_T t133;
real_T t138_tmp;
real_T t148;
real_T t150;
real_T t158_tmp;
real_T t158;
real_T t159;
real_T t160_tmp;
int32_T i;
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
/* SPRDMPF116 */
/* [OUT1,OUT2,OUT3,OUT4,OUT5,OUT6,OUT7,OUT8] = SPRDMPF116(IN1,IN2,S) */
/* This function was generated by the Symbolic Math Toolbox version 8.2. */
/* 08-Jan-2019 02:42:27 */
t2 = in2[4] * in2[4];
t3 = in2[5] * in2[5];
t4 = in2[3] * in2[3];
t5 = ((-t2 - t3) - t4) + 1.0;
t6 = t5;
st.site = &fab_emlrtRSI;
b_sqrt(&st, &t6);
t7 = in2[5] * t6 * 2.0;
t8 = t3 * 2.0;
t9 = in2[3] * t6 * 2.0;
t10 = t4 * 2.0;
t11 = t2 * 2.0;
st.site = &gab_emlrtRSI;
b_sqrt(&st, &t5);
t12 = 1.0 / t5;
t15_tmp = in2[4] * 0.03 - t6 * 0.038;
t18_tmp = in2[4] * 0.038 + t6 * 0.03;
t19 = in2[3] * 0.038;
t22 = in2[3] * 0.03 + in2[5] * 0.038;
t25 = in2[5] * 0.03;
t5 = t19 - t25;
t28_tmp = ((((-in2[0] + in2[84]) + t6 * t15_tmp) + in2[4] * t18_tmp) + in2[5] *
t22) - in2[3] * t5;
t33_tmp_tmp = in2[3] * in2[4];
t33_tmp = t33_tmp_tmp * t12;
b_t33_tmp = in2[3] * t12;
t33 = ((in2[3] * 0.09 + in2[5] * 0.076) + t33_tmp * 0.038) + b_t33_tmp *
t18_tmp;
t36 = ((t19 + t33_tmp * 0.03) + b_t33_tmp * t15_tmp) - in2[5] * 0.06;
t43_tmp_tmp = in2[3] * in2[5];
t43_tmp = t43_tmp_tmp * t12;
b_t43_tmp = t4 * t12;
t4 = (((b_t43_tmp * 0.03 + b_t33_tmp * t22) + t43_tmp * 0.038) - in2[4] *
0.076) - t6 * 0.06;
t47_tmp = ((((in2[2] - in2[86]) + in2[4] * t15_tmp) + in2[3] * t22) + in2[5] *
t5) - t6 * t18_tmp;
t54_tmp = in2[5] * t15_tmp;
t52_tmp_tmp = (((in2[1] - in2[85]) + in2[3] * t18_tmp) + t6 * t22) + in2[4] *
t5;
t52_tmp = t52_tmp_tmp - t54_tmp;
t56 = (((t47_tmp + in2[3] * t33) - in2[5] * t36) - t6 * t4) - b_t33_tmp *
t52_tmp;
t59_tmp = ((in2[4] * t33 + in2[5] * t4) - t6 * t36) - b_t33_tmp * t28_tmp;
t60 = b_t33_tmp * t47_tmp;
t62 = ((t28_tmp + in2[4] * t4) - in2[3] * t36) - in2[5] * t33;
t63 = t6 * t52_tmp;
t64_tmp = in2[4] * t36;
b_t64_tmp = in2[3] * t4;
c_t64_tmp = t6 * t33;
t64 = (((t52_tmp + t60) - t64_tmp) - b_t64_tmp) - c_t64_tmp;
t67 = in2[5] * t28_tmp;
t68 = in2[3] * t47_tmp;
t74 = in2[4] * t28_tmp;
t75 = in2[3] * t52_tmp;
t77_tmp = in2[4] * t12;
t5 = t77_tmp * 0.03 - 0.038;
t4 = t77_tmp * 0.038 + 0.03;
t36 = ((t18_tmp + t6 * t4) - in2[4] * t5) - t77_tmp * t15_tmp;
t33 = ((t15_tmp + t6 * t5) + in2[4] * t4) + t77_tmp * t18_tmp;
t5 = (((-t19 + t25) + in2[3] * t5) + in2[5] * t4) + t77_tmp * t22;
t92 = t6 * t28_tmp;
t93 = in2[4] * t47_tmp;
t111 = in2[5] * t52_tmp;
t94_tmp = (t92 + t93) - t111;
t96 = ((t52_tmp + in2[5] * t33) - in2[3] * t36) - in2[4] * t5;
t100 = ((in2[3] * t33 + in2[5] * t36) - t6 * t5) - t77_tmp * t52_tmp;
t103 = (((t28_tmp + in2[4] * t36) + t77_tmp * t47_tmp) - t6 * t33) - in2[3] *
t5;
t107 = (((t47_tmp + t6 * t36) + in2[4] * t33) + in2[5] * t5) - t77_tmp *
t28_tmp;
t108_tmp = (t63 + t67) + t68;
t117_tmp = t6 * t47_tmp;
t118 = in2[89] * 2.0;
t119 = in2[3] - in2[87];
t4 = ((-(in2[87] * in2[87]) - in2[88] * in2[88]) - in2[89] * in2[89]) + 1.0;
t124 = t4;
st.site = &kab_emlrtRSI;
b_sqrt(&st, &t124);
t125 = in2[4] - in2[88];
t126 = in2[5] - in2[89];
t5 = in2[4] * in2[5];
t130_tmp = t5 * t12;
b_t130_tmp = in2[5] * t12;
t130 = ((-t25 + in2[3] * 0.076) + t130_tmp * 0.038) + b_t130_tmp * t18_tmp;
t133 = ((in2[3] * 0.06 + in2[5] * 0.114) - t130_tmp * 0.03) - b_t130_tmp *
t15_tmp;
t138_tmp = t3 * t12;
t25 = (((in2[4] * 0.06 + t138_tmp * 0.038) + b_t130_tmp * t22) + t43_tmp *
0.03) - t6 * 0.076;
t22 = (((t28_tmp + in2[5] * t133) + in2[3] * t130) - t6 * t25) - b_t130_tmp *
t52_tmp;
t148 = (((t52_tmp + b_t130_tmp * t28_tmp) - t6 * t133) - in2[4] * t130) - in2
[5] * t25;
t150 = ((t47_tmp + in2[5] * t130) - in2[3] * t133) - in2[4] * t25;
t158_tmp = t74 + t75;
t158 = t158_tmp - t117_tmp;
t159 = in2[87] * 2.0;
t160_tmp = in2[4] * t6 * 2.0;
t15_tmp = t33_tmp_tmp * 2.0;
t3 = t43_tmp_tmp * 2.0;
t18_tmp = t5 * 2.0;
st.site = &lab_emlrtRSI;
b_sqrt(&st, &t4);
t36 = 1.0 / t4;
t33 = t6 * 2.0;
t19 = in2[4] * 2.0;
out1[0] = (t8 + t11) - 1.0;
out1[1] = -t7 - t15_tmp;
out1[2] = t160_tmp - t3;
t4 = (in2[3] * t28_tmp - in2[5] * t47_tmp) - in2[4] * t52_tmp;
out1[3] = ((((t4 - in2[5] * t56) + in2[3] * t62) + t6 * t59_tmp) - in2[4] *
(((((t52_tmp_tmp + t60) - t54_tmp) - t64_tmp) - b_t64_tmp) -
c_t64_tmp)) - b_t33_tmp * t94_tmp;
out1[4] = ((((((-t74 - t75) + t117_tmp) - in2[3] * t96) - in2[5] * t100) -
in2[4] * t103) + t6 * t107) - t77_tmp * t94_tmp;
t5 = ((in2[4] * t133 + b_t130_tmp * t47_tmp) - in2[3] * t25) - t6 * t130;
out1[5] = ((((((-t63 - t67) - t68) - in2[5] * t22) - in2[3] * t150) - t6 *
t148) - in2[4] * t5) - b_t130_tmp * t94_tmp;
memset(&out1[6], 0, 78U * sizeof(real_T));
out1[84] = (-t8 - t11) + 1.0;
out1[85] = t7 + t15_tmp;
out1[86] = -t160_tmp + t3;
out1[87] = 0.0;
out1[88] = 0.0;
out1[89] = 0.0;
out1[90] = 0.0;
out1[91] = t7 - t15_tmp;
out1[92] = (t8 + t10) - 1.0;
out1[93] = -t9 - t18_tmp;
out1[94] = (((((t158_tmp - in2[5] * t59_tmp) + in2[4] * t62) + in2[3] * t64) -
t117_tmp) - t6 * t56) + b_t33_tmp * t108_tmp;
out1[95] = ((((t4 - in2[4] * t96) + in2[3] * t103) - in2[5] * t107) - t6 *
t100) + t77_tmp * t108_tmp;
out1[96] = ((((((-t92 - t93) + t111) + in2[5] * t148) - in2[4] * t150) - t6 *
t22) + in2[3] * t5) + b_t130_tmp * t108_tmp;
memset(&out1[97], 0, 78U * sizeof(real_T));
out1[175] = -t7 + t15_tmp;
out1[176] = (-t8 - t10) + 1.0;
out1[177] = t9 + t18_tmp;
out1[178] = 0.0;
out1[179] = 0.0;
out1[180] = 0.0;
out1[181] = 0.0;
out1[182] = t43_tmp_tmp * -2.0 - t160_tmp;
out1[183] = t9 - t18_tmp;
out1[184] = (t10 + t11) - 1.0;
out1[185] = ((((t108_tmp + in2[3] * t56) + in2[5] * t62) + t6 * t64) + in2[4] *
t59_tmp) - b_t33_tmp * ((t74 + t75) - t6 * t47_tmp);
out1[186] = ((((t94_tmp - in2[5] * t96) + in2[3] * t100) + in2[4] * t107) + t6
* t103) - t77_tmp * t158;
out1[187] = ((((t4 + in2[3] * t22) - in2[4] * t148) - in2[5] * t150) + t6 * t5)
- b_t130_tmp * t158;
memset(&out1[188], 0, 78U * sizeof(real_T));
out1[266] = t160_tmp + t3;
out1[267] = -t9 + t18_tmp;
out1[268] = (-t10 - t11) + 1.0;
out1[269] = 0.0;
out1[270] = 0.0;
out1[271] = 0.0;
out1[272] = 0.0;
out1[273] = 0.0;
out1[274] = 0.0;
out1[275] = 0.0;
out1[276] = (t124 * -2.0 - b_t43_tmp * 2.0) + b_t33_tmp * t119 * 2.0;
t4 = t33_tmp * 2.0;
out1[277] = (-t118 - t4) + t77_tmp * t119 * 2.0;
t5 = t43_tmp * 2.0;
out1[278] = (in2[88] * 2.0 - t5) + b_t130_tmp * t119 * 2.0;
memset(&out1[279], 0, 81U * sizeof(real_T));
out1[360] = t33 + in2[3] * in2[87] * t36 * 2.0;
out1[361] = in2[5] * 2.0 + in2[3] * in2[88] * t36 * 2.0;
out1[362] = -t19 + in2[3] * in2[89] * t36 * 2.0;
out1[363] = 0.0;
out1[364] = 0.0;
out1[365] = 0.0;
out1[366] = 0.0;
out1[367] = (t118 - t4) + b_t33_tmp * t125 * 2.0;
out1[368] = (t124 * -2.0 - t2 * t12 * 2.0) + t77_tmp * t125 * 2.0;
t4 = t130_tmp * 2.0;
out1[369] = (-t159 - t4) + b_t130_tmp * t125 * 2.0;
memset(&out1[370], 0, 81U * sizeof(real_T));
out1[451] = in2[5] * -2.0 + in2[4] * in2[87] * t36 * 2.0;
out1[452] = t33 + in2[4] * in2[88] * t36 * 2.0;
out1[453] = in2[3] * 2.0 + in2[4] * in2[89] * t36 * 2.0;
out1[454] = 0.0;
out1[455] = 0.0;
out1[456] = 0.0;
out1[457] = 0.0;
out1[458] = (in2[88] * -2.0 - t5) + b_t33_tmp * t126 * 2.0;
out1[459] = (t159 - t4) + t77_tmp * t126 * 2.0;
out1[460] = (t124 * -2.0 - t138_tmp * 2.0) + b_t130_tmp * t126 * 2.0;
memset(&out1[461], 0, 81U * sizeof(real_T));
out1[542] = t19 + in2[5] * in2[87] * t36 * 2.0;
out1[543] = in2[3] * -2.0 + in2[5] * in2[88] * t36 * 2.0;
out1[544] = t33 + in2[5] * in2[89] * t36 * 2.0;
out1[545] = 0.0;
for (i = 0; i < 6; i++) {
out2[i] = 0.0;
out3[i] = 0.0;
out4[i] = 0.0;
}
}
/* End of code generation (sprdmpF116.c) */
|
cardosofede/hummingbot
|
test/hummingbot/connector/exchange/altmarkets/test_altmarkets_auth.py
|
from unittest.mock import patch
from unittest import TestCase
from hummingbot.connector.exchange.altmarkets.altmarkets_auth import AltmarketsAuth
from hummingbot.connector.exchange.altmarkets.altmarkets_constants import Constants
class AltmarketsAuthTests(TestCase):
def setUp(self) -> None:
super().setUp()
self._api_key = 'testApiKey'
self._secret_key = 'testSecretKey'
self._username = 'testUserName'
self.auth = AltmarketsAuth(
api_key=self._api_key,
secret_key=self._secret_key
)
@patch("hummingbot.connector.exchange.altmarkets.altmarkets_auth.AltmarketsAuth._nonce")
def test_get_headers(self, nonce_mock):
nonce_mock.return_value = '1234567899'
headers = self.auth.get_headers()
self.assertEqual("application/json", headers["Content-Type"])
self.assertEqual(self._api_key, headers["X-Auth-Apikey"])
self.assertEqual('1234567899', headers["X-Auth-Nonce"])
self.assertEqual('13e611ce9c44f18aced4905a9cfb9133fddb1f85d02e1d3764a6aaf1803a22b0', # noqa: mock
headers["X-Auth-Signature"])
self.assertEqual(Constants.USER_AGENT, headers["User-Agent"])
|
SENA-CEET/1349397-Trimestre-2
|
POO/ProyectosPOO/src/main/java/co/edu/sena/proyectospoo/polimorfismo2/Gerente.java
|
<reponame>SENA-CEET/1349397-Trimestre-2
package co.edu.sena.proyectospoo.polimorfismo2;
public class Gerente extends Empleado {
@Override
public void trabajar(){
System.out.println("yo trabajo como gerente");
}
public void mandar(){
System.out.println("mando a los empleados");
}
}
|
minixalpha/SourceLearning
|
webpy/sample/googlemodules/src/app/controllers/cloud.py
|
<gh_stars>100-1000
# Author: <NAME>
import web
from app.models import tags
from app.helpers import render
from config import view
class tag_cloud:
def GET(self):
cloud = tags.get_tag_cloud()
return render.layout(view.tag_cloud(cloud), title = 'All Tags')
class author_cloud:
def GET(self):
cloud = tags.get_author_cloud()
return render.layout(view.tag_cloud_author(cloud), title = 'All Authors')
|
greedy/tinkerpop3
|
tinkergraph-gremlin/src/main/java/com/tinkerpop/gremlin/tinkergraph/process/graph/strategy/TinkerElementStepStrategy.java
|
package com.tinkerpop.gremlin.tinkergraph.process.graph.strategy;
import com.tinkerpop.gremlin.process.Step;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.TraversalEngine;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.GraphStep;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.IdentityStep;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.StartStep;
import com.tinkerpop.gremlin.process.graph.strategy.AbstractTraversalStrategy;
import com.tinkerpop.gremlin.process.util.TraversalHelper;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.util.empty.EmptyGraph;
/**
* @author <NAME> (http://markorodriguez.com)
*/
public class TinkerElementStepStrategy extends AbstractTraversalStrategy {
private static final TinkerElementStepStrategy INSTANCE = new TinkerElementStepStrategy();
private TinkerElementStepStrategy() {
}
@Override
public void apply(final Traversal.Admin<?, ?> traversal, final TraversalEngine engine) {
if (engine.equals(TraversalEngine.STANDARD))
return;
final StartStep<Element> startStep = (StartStep<Element>) traversal.getStartStep();
if (startStep.startAssignableTo(Vertex.class, Edge.class)) {
final Element element = ((StartStep<?>) startStep).getStart();
traversal.removeStep(startStep);
startStep.getLabel().ifPresent(label -> {
final Step identityStep = new IdentityStep(traversal);
identityStep.setLabel(label);
traversal.addStep(0, identityStep);
});
traversal.addStep(0, new GraphStep<>(traversal, EmptyGraph.instance(), element.getClass(), element.id()));
}
}
public static TinkerElementStepStrategy instance() {
return INSTANCE;
}
}
|
afanasyev-ilya/VectorGraphLibrary
|
algorithms/bfs/change_state/change_state.hpp
|
#pragma once
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define ALPHA 15
#define BETA 18
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GraphStructure check_graph_structure(VectorCSRGraph &_graph)
{
int vertices_count = _graph.get_vertices_count();
long long edges_count = _graph.get_edges_count ();
long long *vertex_pointers = _graph.get_vertex_pointers ();
int *adjacent_ids = _graph.get_adjacent_ids ();
int portion_of_first_vertices = 0.01 * vertices_count + 1;
long long number_of_edges_in_first_portion = vertex_pointers[portion_of_first_vertices];
if((100.0 * number_of_edges_in_first_portion) / edges_count > POWER_LAW_EDGES_THRESHOLD)
return POWER_LAW_GRAPH;
else
return UNIFORM_GRAPH;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool check_if_vector_extension_should_be_used(int _non_zero_vertices_count, int _not_visited_count, StateOfBFS _current_state)
{
if(_current_state == BOTTOM_UP)
{
//cout << (100.0 * _not_visited_count) / _non_zero_vertices_count << " %" << endl;
//if((100.0 * _not_visited_count) / _non_zero_vertices_count > )
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
StateOfBFS nec_change_state(int _current_queue_size, int _next_queue_size, int _vertices_count, long long _edges_count,
StateOfBFS _old_state, int _vis, int _in_lvl, bool &_use_vect_CSR_extension, int _cur_level,
GraphStructure _graph_structure, int *_levels, int _number_of_bu_steps)
{
StateOfBFS new_state = _old_state;
int factor = (_edges_count / _vertices_count) / 2;
if(_current_queue_size < _next_queue_size) // growing phase
{
if(_old_state == TOP_DOWN)
{
if(((_levels[0] != UNVISITED_VERTEX) || (_levels[1] != UNVISITED_VERTEX)) && (_next_queue_size > 500))
{
new_state = BOTTOM_UP;
}
else
{
if(_in_lvl < ((_vertices_count - _vis) * factor + _vertices_count) / ALPHA)
{
new_state = TOP_DOWN;
}
else
{
new_state = BOTTOM_UP;
}
}
}
}
else // shrinking phase
{
if(_old_state == BOTTOM_UP)
{
if((_next_queue_size < ((_vertices_count - _vis) * factor) / (factor * BETA)) && (_number_of_bu_steps > 1))
{
new_state = TOP_DOWN;
}
else
{
new_state = BOTTOM_UP;
}
}
}
_use_vect_CSR_extension = true;
if(_number_of_bu_steps <= 1)
{
_use_vect_CSR_extension = true;
}
else
{
_use_vect_CSR_extension = false;
}
return new_state;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
StateOfBFS gpu_change_state(int _current_queue_size, int _next_queue_size, int _vertices_count, long long _edges_count,
StateOfBFS _old_state, int _vis, int _in_lvl, int _current_level, GraphStructure _graph_structure)
{
StateOfBFS new_state = _old_state;
int factor = (_edges_count / _vertices_count) / 2;
if(_current_queue_size < _next_queue_size) // growing phase
{
if(_old_state == TOP_DOWN)
{
if(_in_lvl < ((_vertices_count - _vis) * factor + _vertices_count) / ALPHA)
{
new_state = TOP_DOWN;
}
else
{
new_state = BOTTOM_UP;
}
}
}
else // shrinking phase
{
if(_old_state == BOTTOM_UP)
{
if(_next_queue_size < ((_vertices_count - _vis) * factor + _vertices_count) / (factor * BETA))
{
new_state = TOP_DOWN;
}
else
{
new_state = BOTTOM_UP;
}
}
}
//if(_current_level == 1)
// new_state = BOTTOM_UP;
//cout << "ch: " << _current_queue_size << " -> " << _next_queue_size << endl;
return new_state;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
salonimalhotra-ui/seo-audits-toolkit
|
toolkit/controller/seo/lighthouse.py
|
from toolkit.lib.http_tools import request_page
from flask import current_app
def audit_google_lighthouse_full(url):
pagespeed = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + url + "&category=BEST_PRACTICES&category=ACCESSIBILITY&category=PERFORMANCE&category=PWA&category=SEO"
if current_app.config['GOOGLE_API_KEY'] != "None":
pagespeed += "&key=" + current_app.config["GOOGLE_API_KEY"]
result = request_page(pagespeed , timeout=30)
return result.json()
def audit_google_lighthouse_seo(url):
pagespeed = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url="
result = request_page(pagespeed + url + "&category=seo", timeout=30)
content = result.json()
result_seo = {}
result_seo["summary"] = {}
result_seo["summary"]["requestedUrl"] = content["lighthouseResult"]["requestedUrl"]
result_seo["summary"]["finalUrl"] = content["lighthouseResult"]["finalUrl"]
result_seo["summary"]["timing"] = content["lighthouseResult"]["timing"]["total"]
result_seo["summary"]["date"] = content["lighthouseResult"]["fetchTime"]
result_seo["results"] = {}
for key in content["lighthouseResult"]["audits"]:
result_seo["results"][key] = {}
result_seo["results"][key]["short_desc"] = content["lighthouseResult"]["audits"][key]["title"]
result_seo["results"][key]["long_desc"] = content["lighthouseResult"]["audits"][key]["description"]
result_seo["results"][key]["score"] = content["lighthouseResult"]["audits"][key]["score"]
return result_seo
|
antopen/alipay-sdk-python-all
|
alipay/aop/api/domain/SubVenueAuditStatus.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SubVenueAuditStatus(object):
def __init__(self):
self._out_sub_venue_id = None
self._sub_venue_id = None
self._sub_venue_status = None
@property
def out_sub_venue_id(self):
return self._out_sub_venue_id
@out_sub_venue_id.setter
def out_sub_venue_id(self, value):
self._out_sub_venue_id = value
@property
def sub_venue_id(self):
return self._sub_venue_id
@sub_venue_id.setter
def sub_venue_id(self, value):
self._sub_venue_id = value
@property
def sub_venue_status(self):
return self._sub_venue_status
@sub_venue_status.setter
def sub_venue_status(self, value):
self._sub_venue_status = value
def to_alipay_dict(self):
params = dict()
if self.out_sub_venue_id:
if hasattr(self.out_sub_venue_id, 'to_alipay_dict'):
params['out_sub_venue_id'] = self.out_sub_venue_id.to_alipay_dict()
else:
params['out_sub_venue_id'] = self.out_sub_venue_id
if self.sub_venue_id:
if hasattr(self.sub_venue_id, 'to_alipay_dict'):
params['sub_venue_id'] = self.sub_venue_id.to_alipay_dict()
else:
params['sub_venue_id'] = self.sub_venue_id
if self.sub_venue_status:
if hasattr(self.sub_venue_status, 'to_alipay_dict'):
params['sub_venue_status'] = self.sub_venue_status.to_alipay_dict()
else:
params['sub_venue_status'] = self.sub_venue_status
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = SubVenueAuditStatus()
if 'out_sub_venue_id' in d:
o.out_sub_venue_id = d['out_sub_venue_id']
if 'sub_venue_id' in d:
o.sub_venue_id = d['sub_venue_id']
if 'sub_venue_status' in d:
o.sub_venue_status = d['sub_venue_status']
return o
|
pupper68k/arcusplatform
|
platform/bridge-common/src/main/java/com/iris/bridge/server/traffic/DefaultTrafficHandler.java
|
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.bridge.server.traffic;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.Gauge;
import com.iris.bridge.metrics.BridgeMetrics;
import com.iris.metrics.IrisMetrics;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.handler.traffic.TrafficCounter;
import io.netty.channel.ChannelHandler.Sharable;
@Sharable
public class DefaultTrafficHandler extends GlobalTrafficShapingHandler implements TrafficHandler {
public static final long CHECK_INTERVAL = TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS);
public static final long MAX_TIME = TimeUnit.MILLISECONDS.convert(300, TimeUnit.SECONDS);
public static final long WRITE_GLOBAL_LIMIT = 0; // no limit
public static final long READ_GLOBAL_LIMIT = 0; // no limit
public DefaultTrafficHandler(BridgeMetrics metrics) {
super(Executors.newScheduledThreadPool(1), WRITE_GLOBAL_LIMIT, READ_GLOBAL_LIMIT, CHECK_INTERVAL, MAX_TIME);
IrisMetrics.metrics("bridge." + metrics.getBridgeName() + ".bytes").gauge("sent", (Gauge<Long>)() -> {
TrafficCounter tc = trafficCounter();
return tc != null ? tc.cumulativeWrittenBytes() : 0L;
});
IrisMetrics.metrics("bridge." + metrics.getBridgeName() + ".bytes").gauge("received", (Gauge<Long>)() -> {
TrafficCounter tc = trafficCounter();
return tc != null ? tc.cumulativeReadBytes() : 0L;
});
}
}
|
markjolesen/mjo
|
mjoextra/vector/src/vperpush.c
|
<reponame>markjolesen/mjo<gh_stars>0
/*
CC0 1.0 Universal --- Public Domain
To the extent possible under law, <NAME> has waived all copyright
and related or neighboring rights to this file (vperpush.c).
This work is published from: United States.
This file is part of the mjo_extra library.
Full text of this license can be found in '${MJO_EXTRA_HOME}/licenses/CC-CC0'
or visit 'https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt' or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
*/
#include <errno.h>
/**/
#include <mstdlib.h>
#include <mstr.h>
#include <mstring.h>
/**/
#include "_vector.h"
extern int
mjo_vector_mem_permute_push(mjo_vector_t *const io_var,
unsigned char const *i_str,
char const *i_fn,
size_t const i_ln)
{
struct mjo_vector_arena *l_arena;
int l_rc;
size_t l_count;
union
{
short m_short;
unsigned short m_ushort;
int m_int;
unsigned int m_uint;
long m_long;
unsigned long m_ulong;
size_t m_size_t;
ptrdiff_t m_ptrdiff_t;
double m_double;
void const *m_ptr;
} l_value;
l_rc = MJO_FAIL;
do
{
if ((0 == io_var) || (0 == *io_var))
{
errno = EINVAL;
break;
}
if (0 == i_str)
{
errno = EINVAL;
break;
}
l_arena = _mjo_vector_ptr_to_arena(*io_var);
if (0 == l_arena->m_size)
{
errno = E2BIG;
break;
}
l_count = 1;
memset(&l_value, 0, sizeof(l_value));
switch (l_arena->m_variant)
{
case mjo_vector_variant_struct:
l_value.m_ptr = i_str;
l_rc = 0;
break;
case mjo_vector_variant_ptrstr:
mjo_strdup((unsigned char **)&l_value.m_ptr, i_str);
l_rc = 0;
break;
case mjo_vector_variant_char:
l_count = strlen((char const *)i_str);
l_value.m_ptr = i_str;
l_rc = 0;
break;
case mjo_vector_variant_short:
l_rc = mjo_str_to_short(&l_value.m_short, i_str);
break;
case mjo_vector_variant_ushort:
l_rc = mjo_str_to_ushort(&l_value.m_ushort, i_str);
break;
case mjo_vector_variant_bool:
l_rc = mjo_str_to_bool(&l_value.m_int, i_str);
break;
case mjo_vector_variant_int:
l_rc = mjo_str_to_int(&l_value.m_int, i_str);
break;
case mjo_vector_variant_uint:
l_rc = mjo_str_to_uint(&l_value.m_uint, i_str);
break;
case mjo_vector_variant_long:
l_rc = mjo_str_to_long(&l_value.m_long, i_str);
break;
case mjo_vector_variant_ulong:
l_rc = mjo_str_to_ulong(&l_value.m_ulong, i_str);
break;
case mjo_vector_variant_size_t:
l_rc = mjo_str_to_size_t(&l_value.m_size_t, i_str);
break;
case mjo_vector_variant_ptrdiff_t:
l_rc = mjo_str_to_ptrdiff_t(&l_value.m_ptrdiff_t, i_str);
break;
case mjo_vector_variant_double:
l_rc = mjo_str_to_double(&l_value.m_double, i_str);
break;
}
if (l_rc)
{
break;
}
if (l_count)
{
l_rc = mjo_vector_mem_push(
io_var, (void *const) & l_value, l_count, i_fn, i_ln);
}
}
while (0);
return l_rc;
}
|
storagezhang/Object-Oriented-Programming
|
elevator_2/src/elevator/Elevator.java
|
<reponame>storagezhang/Object-Oriented-Programming<filename>elevator_2/src/elevator/Elevator.java<gh_stars>1-10
package elevator;
import com.oocourse.TimableOutput;
import request.Request;
import request.RequestQueue;
public class Elevator {
private int floor;
private Request taker;
private RequestQueue queue;
private RequestQueue pigQueue;
private boolean get;
private static final int doorTime = 200;
public Elevator(RequestQueue queue) {
this.floor = 1;
this.taker = null;
this.queue = queue;
this.pigQueue = new RequestQueue();
get = false;
}
public boolean isEmpty() {
return queue.isEmpty() & pigQueue.isEmpty();
}
public synchronized void setTaker() {
get = false;
if (!pigQueue.isEmpty()) {
taker = pigQueue.getRequest(0);
get = true;
} else if (queue.isEmpty()) {
taker = null;
} else {
taker = queue.getRequest(0);
if (taker != null) {
queue.getPiggy(taker);
}
}
}
void waitTime(int from, int to, boolean up) throws InterruptedException {
if (up) {
for (int i = from; i <= to; i++) {
if (i == 0) {
continue;
}
Thread.sleep(400);
TimableOutput.println("ARRIVE-" + i);
addPigQueue(i);
}
} else {
for (int i = from; i >= to; i--) {
if (i == 0) {
continue;
}
Thread.sleep(400);
TimableOutput.println("ARRIVE-" + i);
addPigQueue(i);
}
}
}
private synchronized void addPigQueue(int from)
throws InterruptedException {
int open = 0;
for (int i = 0; i < queue.size(); i++) {
Request r = queue.getRequest(i);
if (from == r.getFrom()) {
if (open == 0) {
TimableOutput.println("OPEN-" + from);
Thread.sleep(doorTime);
open = 1;
}
TimableOutput.println("IN-" + r.getId() + "-" + r.getFrom());
queue.removeRequest(i);
pigQueue.addAndSort(r);
i--;
}
}
for (int i = 0; i < pigQueue.size(); i++) {
Request r = pigQueue.getRequest(i);
if (from == r.getTo()) {
if (open == 0) {
TimableOutput.println("OPEN-" + from);
Thread.sleep(doorTime);
open = 1;
}
TimableOutput.println("OUT-" + r.getId() + "-" + r.getTo());
pigQueue.removeRequest(i);
i--;
}
}
if (open == 1) {
Thread.sleep(doorTime);
TimableOutput.println("CLOSE-" + from);
}
}
private synchronized void addPigQueue(int from, boolean open) {
for (int i = 0; i < queue.size(); i++) {
Request r = queue.getRequest(i);
if (from == r.getFrom()) {
TimableOutput.println("IN-" + r.getId() + "-" + r.getFrom());
queue.removeRequest(i);
pigQueue.addAndSort(r);
i--;
}
}
}
void runTime(int from, int to, boolean up) throws InterruptedException {
int updateTo = to;
int i;
if (up) {
for (i = from; (!pigQueue.isEmpty()) & (i <= updateTo); i++) {
if (pigQueue.getLast().getTo() > updateTo) {
updateTo = pigQueue.getLast().getTo();
}
if (i == 0) {
continue;
}
upAndDown(i);
}
} else {
for (i = from; (!pigQueue.isEmpty()) & (i >= updateTo); i--) {
if (pigQueue.getFirst().getTo() < updateTo) {
updateTo = pigQueue.getFirst().getTo();
}
if (i == 0) {
continue;
}
upAndDown(i);
}
}
if (up) {
floor = i - 1;
} else {
floor = i + 1;
}
}
private void upAndDown(int i) throws InterruptedException {
Thread.sleep(400);
TimableOutput.println("ARRIVE-" + i);
addPigQueue(i);
if (pigQueue.isEmpty()) {
return;
}
if (pigQueue.getLast().getTo() == i
| pigQueue.getFirst().getTo() == i) {
TimableOutput.println("OPEN-" + i);
Thread.sleep(doorTime);
addPigQueue(i, true);
for (int j = 0; j < pigQueue.size(); j++) {
Request r = pigQueue.getRequest(j);
if (r.getTo() == i) {
TimableOutput.println("OUT-" + r.getId() + "-" + r.getTo());
pigQueue.removeRequest(j);
j--;
}
}
Thread.sleep(doorTime);
TimableOutput.println("CLOSE-" + i);
}
}
void work() throws InterruptedException {
Thread.sleep(1);
setTaker();
if (taker == null) {
return;
}
int from = floor;
int to;
if (get) {
to = taker.getTo();
} else {
to = taker.getFrom();
}
boolean up;
if (from < to) {
from++;
up = true;
} else {
from--;
up = false;
}
waitTime(from, to, up);
Thread.sleep(1);
addPigQueue(to);
from = to;
if (pigQueue.isEmpty()) {
floor = to;
return;
}
if (taker.getFrom() - taker.getTo() < 0) {
to = pigQueue.getLast().getTo();
} else {
to = pigQueue.getFirst().getTo();
}
if (from < to) {
from++;
up = true;
} else {
from--;
up = false;
}
runTime(from, to, up);
}
}
|
rizalgowandy/Sparta
|
cloudtest/trigger.go
|
package cloudtest
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sqs"
)
////////////////////////////////////////////////////////////////////////////////
//
type cloudNOPTrigger struct {
}
func (cnp *cloudNOPTrigger) Send(t CloudTest, output *lambda.GetFunctionOutput) (interface{}, error) {
t.Logf("NOP Trigger")
return nil, nil
}
func (cnp *cloudNOPTrigger) Cleanup(t CloudTest, output *lambda.GetFunctionOutput) {
}
// NewNOPTrigger is an empty trigger that does nothing
func NewNOPTrigger() Trigger {
return &cloudNOPTrigger{}
}
////////////////////////////////////////////////////////////////////////////////
//
type lambdaInvokeTrigger struct {
eventBody []byte
}
func (lim *lambdaInvokeTrigger) Send(t CloudTest, output *lambda.GetFunctionOutput) (interface{}, error) {
lambdaSvc := lambda.New(t.Session())
invokeInput := &lambda.InvokeInput{
FunctionName: output.Configuration.FunctionArn,
LogType: aws.String(lambda.LogTypeTail),
Payload: lim.eventBody,
}
t.Logf("Submitting LambdaInvoke: %#v\n", invokeInput)
return lambdaSvc.Invoke(invokeInput)
}
func (lim *lambdaInvokeTrigger) Cleanup(t CloudTest, output *lambda.GetFunctionOutput) {
}
// NewLambdaInvokeTrigger returns a Trigger instance that directly invokes
// a Lambda function
func NewLambdaInvokeTrigger(event []byte) Trigger {
return &lambdaInvokeTrigger{
eventBody: event,
}
}
////////////////////////////////////////////////////////////////////////////////
//
type sqsMessageTrigger struct {
sqsURL string
messageBody string
}
func (ssub *sqsMessageTrigger) Send(t CloudTest,
output *lambda.GetFunctionOutput) (interface{}, error) {
sqsSvc := sqs.New(t.Session())
messageInput := &sqs.SendMessageInput{
MessageBody: aws.String(ssub.messageBody),
QueueUrl: aws.String(ssub.sqsURL),
}
t.Logf("Submitting SQS Message: %#v\n", messageInput)
return sqsSvc.SendMessage(messageInput)
}
func (ssub *sqsMessageTrigger) Cleanup(t CloudTest, output *lambda.GetFunctionOutput) {
}
// NewSQSMessageTrigger is a trigger that submits a message to an SQS URL
func NewSQSMessageTrigger(sqsURL string, messageBody string) Trigger {
return &sqsMessageTrigger{
sqsURL: sqsURL,
messageBody: messageBody,
}
}
////////////////////////////////////////////////////////////////////////////////
//
type s3PayloadTrigger struct {
putObjectParams *s3.PutObjectInput
}
func (spt *s3PayloadTrigger) Send(t CloudTest,
output *lambda.GetFunctionOutput) (interface{}, error) {
s3Svc := s3.New(t.Session())
t.Logf("Submitting S3 object: %#v\n", spt.putObjectParams)
return s3Svc.PutObject(spt.putObjectParams)
}
func (spt *s3PayloadTrigger) Cleanup(t CloudTest, output *lambda.GetFunctionOutput) {
delObjectInput := &s3.DeleteObjectInput{
Bucket: spt.putObjectParams.Bucket,
Key: spt.putObjectParams.Key,
}
s3Svc := s3.New(t.Session())
_, delErr := s3Svc.DeleteObject(delObjectInput)
if delErr != nil {
t.Logf("Failed to delete object: %s", delErr.Error())
}
}
// NewS3MessageTrigger returns an S3 Trigger that posts a payload
// to the given bucket, key
func NewS3MessageTrigger(s3Bucket string, s3Key string, body io.ReadSeeker) Trigger {
return &s3PayloadTrigger{
putObjectParams: &s3.PutObjectInput{
Bucket: aws.String(s3Bucket),
Key: aws.String(s3Key),
Body: body,
},
}
}
// NewS3FileMessageTrigger returns an S3 Trigger that posts a payload
// to the given bucket, key
func NewS3FileMessageTrigger(s3Bucket string, s3Key string, localFilePath string) Trigger {
trigger := &s3PayloadTrigger{
putObjectParams: &s3.PutObjectInput{
Bucket: aws.String(s3Bucket),
Key: aws.String(s3Key),
Body: nil,
},
}
// Read the body...
/* #nosec G304 */
allData, allDataErr := ioutil.ReadFile(localFilePath)
if allDataErr != nil {
trigger.putObjectParams.Body = bytes.NewReader(allData)
contentType := http.DetectContentType(allData)
trigger.putObjectParams.ContentType = aws.String(contentType)
}
return trigger
}
|
ASimpleIronBlock/GameAutoMusicPlayer
|
AutoMusicPlayerMain/src/main/java/me/ironblock/automusicplayer/ui/annotations/WindowComponent.java
|
package me.ironblock.automusicplayer.ui.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author :Iron__Block
* @Date :2022/2/17 2:10
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface WindowComponent {
String name();
int x();
int y();
int width();
int height();
String initPara() default "";
String parent() default "";
String initializer() default "";
String[] listeners() default {};
String background() default "";
}
|
sdran/onos-e2sub
|
vendor/github.com/atomix/go-framework/pkg/atomix/log/log.pb.go
|
<gh_stars>0
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: atomix/log/log.proto
package log
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
_ "github.com/gogo/protobuf/types"
github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
io "io"
math "math"
math_bits "math/bits"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
var _ = time.Kitchen
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type UpdateStatus int32
const (
UpdateStatus_OK UpdateStatus = 0
UpdateStatus_NOOP UpdateStatus = 1
UpdateStatus_WRITE_LOCK UpdateStatus = 2
UpdateStatus_PRECONDITION_FAILED UpdateStatus = 3
)
var UpdateStatus_name = map[int32]string{
0: "OK",
1: "NOOP",
2: "WRITE_LOCK",
3: "PRECONDITION_FAILED",
}
var UpdateStatus_value = map[string]int32{
"OK": 0,
"NOOP": 1,
"WRITE_LOCK": 2,
"PRECONDITION_FAILED": 3,
}
func (x UpdateStatus) String() string {
return proto.EnumName(UpdateStatus_name, int32(x))
}
func (UpdateStatus) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{0}
}
type ListenResponse_Type int32
const (
ListenResponse_NONE ListenResponse_Type = 0
ListenResponse_APPENDED ListenResponse_Type = 1
ListenResponse_REMOVED ListenResponse_Type = 3
)
var ListenResponse_Type_name = map[int32]string{
0: "NONE",
1: "APPENDED",
3: "REMOVED",
}
var ListenResponse_Type_value = map[string]int32{
"NONE": 0,
"APPENDED": 1,
"REMOVED": 3,
}
func (x ListenResponse_Type) String() string {
return proto.EnumName(ListenResponse_Type_name, int32(x))
}
func (ListenResponse_Type) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{25, 0}
}
// Log snapshot
type LogSnapshot struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Entries []*LogEntryValue `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"`
}
func (m *LogSnapshot) Reset() { *m = LogSnapshot{} }
func (m *LogSnapshot) String() string { return proto.CompactTextString(m) }
func (*LogSnapshot) ProtoMessage() {}
func (*LogSnapshot) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{0}
}
func (m *LogSnapshot) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LogSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LogSnapshot.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LogSnapshot) XXX_Merge(src proto.Message) {
xxx_messageInfo_LogSnapshot.Merge(m, src)
}
func (m *LogSnapshot) XXX_Size() int {
return m.Size()
}
func (m *LogSnapshot) XXX_DiscardUnknown() {
xxx_messageInfo_LogSnapshot.DiscardUnknown(m)
}
var xxx_messageInfo_LogSnapshot proto.InternalMessageInfo
func (m *LogSnapshot) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *LogSnapshot) GetEntries() []*LogEntryValue {
if m != nil {
return m.Entries
}
return nil
}
// Log entry value
type LogEntryValue struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *LogEntryValue) Reset() { *m = LogEntryValue{} }
func (m *LogEntryValue) String() string { return proto.CompactTextString(m) }
func (*LogEntryValue) ProtoMessage() {}
func (*LogEntryValue) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{1}
}
func (m *LogEntryValue) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LogEntryValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LogEntryValue.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LogEntryValue) XXX_Merge(src proto.Message) {
xxx_messageInfo_LogEntryValue.Merge(m, src)
}
func (m *LogEntryValue) XXX_Size() int {
return m.Size()
}
func (m *LogEntryValue) XXX_DiscardUnknown() {
xxx_messageInfo_LogEntryValue.DiscardUnknown(m)
}
var xxx_messageInfo_LogEntryValue proto.InternalMessageInfo
func (m *LogEntryValue) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *LogEntryValue) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *LogEntryValue) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type ContainsIndexRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *ContainsIndexRequest) Reset() { *m = ContainsIndexRequest{} }
func (m *ContainsIndexRequest) String() string { return proto.CompactTextString(m) }
func (*ContainsIndexRequest) ProtoMessage() {}
func (*ContainsIndexRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{2}
}
func (m *ContainsIndexRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ContainsIndexRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ContainsIndexRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ContainsIndexRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ContainsIndexRequest.Merge(m, src)
}
func (m *ContainsIndexRequest) XXX_Size() int {
return m.Size()
}
func (m *ContainsIndexRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ContainsIndexRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ContainsIndexRequest proto.InternalMessageInfo
func (m *ContainsIndexRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type ContainsIndexResponse struct {
ContainsIndex bool `protobuf:"varint,1,opt,name=contains_index,json=containsIndex,proto3" json:"contains_index,omitempty"`
}
func (m *ContainsIndexResponse) Reset() { *m = ContainsIndexResponse{} }
func (m *ContainsIndexResponse) String() string { return proto.CompactTextString(m) }
func (*ContainsIndexResponse) ProtoMessage() {}
func (*ContainsIndexResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{3}
}
func (m *ContainsIndexResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ContainsIndexResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ContainsIndexResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ContainsIndexResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_ContainsIndexResponse.Merge(m, src)
}
func (m *ContainsIndexResponse) XXX_Size() int {
return m.Size()
}
func (m *ContainsIndexResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ContainsIndexResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ContainsIndexResponse proto.InternalMessageInfo
func (m *ContainsIndexResponse) GetContainsIndex() bool {
if m != nil {
return m.ContainsIndex
}
return false
}
type SizeRequest struct {
}
func (m *SizeRequest) Reset() { *m = SizeRequest{} }
func (m *SizeRequest) String() string { return proto.CompactTextString(m) }
func (*SizeRequest) ProtoMessage() {}
func (*SizeRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{4}
}
func (m *SizeRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SizeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SizeRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SizeRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_SizeRequest.Merge(m, src)
}
func (m *SizeRequest) XXX_Size() int {
return m.Size()
}
func (m *SizeRequest) XXX_DiscardUnknown() {
xxx_messageInfo_SizeRequest.DiscardUnknown(m)
}
var xxx_messageInfo_SizeRequest proto.InternalMessageInfo
type SizeResponse struct {
Size_ int32 `protobuf:"varint,1,opt,name=size,proto3" json:"size,omitempty"`
}
func (m *SizeResponse) Reset() { *m = SizeResponse{} }
func (m *SizeResponse) String() string { return proto.CompactTextString(m) }
func (*SizeResponse) ProtoMessage() {}
func (*SizeResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{5}
}
func (m *SizeResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *SizeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_SizeResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *SizeResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_SizeResponse.Merge(m, src)
}
func (m *SizeResponse) XXX_Size() int {
return m.Size()
}
func (m *SizeResponse) XXX_DiscardUnknown() {
xxx_messageInfo_SizeResponse.DiscardUnknown(m)
}
var xxx_messageInfo_SizeResponse proto.InternalMessageInfo
func (m *SizeResponse) GetSize_() int32 {
if m != nil {
return m.Size_
}
return 0
}
type IndexRequest struct {
}
func (m *IndexRequest) Reset() { *m = IndexRequest{} }
func (m *IndexRequest) String() string { return proto.CompactTextString(m) }
func (*IndexRequest) ProtoMessage() {}
func (*IndexRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{6}
}
func (m *IndexRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *IndexRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_IndexRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *IndexRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_IndexRequest.Merge(m, src)
}
func (m *IndexRequest) XXX_Size() int {
return m.Size()
}
func (m *IndexRequest) XXX_DiscardUnknown() {
xxx_messageInfo_IndexRequest.DiscardUnknown(m)
}
var xxx_messageInfo_IndexRequest proto.InternalMessageInfo
type IndexResponse struct {
Key uint64 `protobuf:"varint,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *IndexResponse) Reset() { *m = IndexResponse{} }
func (m *IndexResponse) String() string { return proto.CompactTextString(m) }
func (*IndexResponse) ProtoMessage() {}
func (*IndexResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{7}
}
func (m *IndexResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *IndexResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_IndexResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *IndexResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_IndexResponse.Merge(m, src)
}
func (m *IndexResponse) XXX_Size() int {
return m.Size()
}
func (m *IndexResponse) XXX_DiscardUnknown() {
xxx_messageInfo_IndexResponse.DiscardUnknown(m)
}
var xxx_messageInfo_IndexResponse proto.InternalMessageInfo
func (m *IndexResponse) GetKey() uint64 {
if m != nil {
return m.Key
}
return 0
}
type AppendRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
IfEmpty bool `protobuf:"varint,3,opt,name=if_empty,json=ifEmpty,proto3" json:"if_empty,omitempty"`
}
func (m *AppendRequest) Reset() { *m = AppendRequest{} }
func (m *AppendRequest) String() string { return proto.CompactTextString(m) }
func (*AppendRequest) ProtoMessage() {}
func (*AppendRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{8}
}
func (m *AppendRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AppendRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AppendRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AppendRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_AppendRequest.Merge(m, src)
}
func (m *AppendRequest) XXX_Size() int {
return m.Size()
}
func (m *AppendRequest) XXX_DiscardUnknown() {
xxx_messageInfo_AppendRequest.DiscardUnknown(m)
}
var xxx_messageInfo_AppendRequest proto.InternalMessageInfo
func (m *AppendRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *AppendRequest) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *AppendRequest) GetIfEmpty() bool {
if m != nil {
return m.IfEmpty
}
return false
}
type AppendResponse struct {
Status UpdateStatus `protobuf:"varint,1,opt,name=status,proto3,enum=atomix.log.service.UpdateStatus" json:"status,omitempty"`
Index uint64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *AppendResponse) Reset() { *m = AppendResponse{} }
func (m *AppendResponse) String() string { return proto.CompactTextString(m) }
func (*AppendResponse) ProtoMessage() {}
func (*AppendResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{9}
}
func (m *AppendResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AppendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AppendResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *AppendResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_AppendResponse.Merge(m, src)
}
func (m *AppendResponse) XXX_Size() int {
return m.Size()
}
func (m *AppendResponse) XXX_DiscardUnknown() {
xxx_messageInfo_AppendResponse.DiscardUnknown(m)
}
var xxx_messageInfo_AppendResponse proto.InternalMessageInfo
func (m *AppendResponse) GetStatus() UpdateStatus {
if m != nil {
return m.Status
}
return UpdateStatus_OK
}
func (m *AppendResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *AppendResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type GetRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *GetRequest) Reset() { *m = GetRequest{} }
func (m *GetRequest) String() string { return proto.CompactTextString(m) }
func (*GetRequest) ProtoMessage() {}
func (*GetRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{10}
}
func (m *GetRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetRequest.Merge(m, src)
}
func (m *GetRequest) XXX_Size() int {
return m.Size()
}
func (m *GetRequest) XXX_DiscardUnknown() {
xxx_messageInfo_GetRequest.DiscardUnknown(m)
}
var xxx_messageInfo_GetRequest proto.InternalMessageInfo
func (m *GetRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type GetResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *GetResponse) Reset() { *m = GetResponse{} }
func (m *GetResponse) String() string { return proto.CompactTextString(m) }
func (*GetResponse) ProtoMessage() {}
func (*GetResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{11}
}
func (m *GetResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_GetResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *GetResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetResponse.Merge(m, src)
}
func (m *GetResponse) XXX_Size() int {
return m.Size()
}
func (m *GetResponse) XXX_DiscardUnknown() {
xxx_messageInfo_GetResponse.DiscardUnknown(m)
}
var xxx_messageInfo_GetResponse proto.InternalMessageInfo
func (m *GetResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *GetResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *GetResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type FirstEntryRequest struct {
}
func (m *FirstEntryRequest) Reset() { *m = FirstEntryRequest{} }
func (m *FirstEntryRequest) String() string { return proto.CompactTextString(m) }
func (*FirstEntryRequest) ProtoMessage() {}
func (*FirstEntryRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{12}
}
func (m *FirstEntryRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *FirstEntryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_FirstEntryRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *FirstEntryRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_FirstEntryRequest.Merge(m, src)
}
func (m *FirstEntryRequest) XXX_Size() int {
return m.Size()
}
func (m *FirstEntryRequest) XXX_DiscardUnknown() {
xxx_messageInfo_FirstEntryRequest.DiscardUnknown(m)
}
var xxx_messageInfo_FirstEntryRequest proto.InternalMessageInfo
type FirstEntryResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *FirstEntryResponse) Reset() { *m = FirstEntryResponse{} }
func (m *FirstEntryResponse) String() string { return proto.CompactTextString(m) }
func (*FirstEntryResponse) ProtoMessage() {}
func (*FirstEntryResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{13}
}
func (m *FirstEntryResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *FirstEntryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_FirstEntryResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *FirstEntryResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_FirstEntryResponse.Merge(m, src)
}
func (m *FirstEntryResponse) XXX_Size() int {
return m.Size()
}
func (m *FirstEntryResponse) XXX_DiscardUnknown() {
xxx_messageInfo_FirstEntryResponse.DiscardUnknown(m)
}
var xxx_messageInfo_FirstEntryResponse proto.InternalMessageInfo
func (m *FirstEntryResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *FirstEntryResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *FirstEntryResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type LastEntryRequest struct {
}
func (m *LastEntryRequest) Reset() { *m = LastEntryRequest{} }
func (m *LastEntryRequest) String() string { return proto.CompactTextString(m) }
func (*LastEntryRequest) ProtoMessage() {}
func (*LastEntryRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{14}
}
func (m *LastEntryRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LastEntryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LastEntryRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LastEntryRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_LastEntryRequest.Merge(m, src)
}
func (m *LastEntryRequest) XXX_Size() int {
return m.Size()
}
func (m *LastEntryRequest) XXX_DiscardUnknown() {
xxx_messageInfo_LastEntryRequest.DiscardUnknown(m)
}
var xxx_messageInfo_LastEntryRequest proto.InternalMessageInfo
type LastEntryResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *LastEntryResponse) Reset() { *m = LastEntryResponse{} }
func (m *LastEntryResponse) String() string { return proto.CompactTextString(m) }
func (*LastEntryResponse) ProtoMessage() {}
func (*LastEntryResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{15}
}
func (m *LastEntryResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *LastEntryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LastEntryResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *LastEntryResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_LastEntryResponse.Merge(m, src)
}
func (m *LastEntryResponse) XXX_Size() int {
return m.Size()
}
func (m *LastEntryResponse) XXX_DiscardUnknown() {
xxx_messageInfo_LastEntryResponse.DiscardUnknown(m)
}
var xxx_messageInfo_LastEntryResponse proto.InternalMessageInfo
func (m *LastEntryResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *LastEntryResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *LastEntryResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type PrevEntryRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *PrevEntryRequest) Reset() { *m = PrevEntryRequest{} }
func (m *PrevEntryRequest) String() string { return proto.CompactTextString(m) }
func (*PrevEntryRequest) ProtoMessage() {}
func (*PrevEntryRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{16}
}
func (m *PrevEntryRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PrevEntryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PrevEntryRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PrevEntryRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_PrevEntryRequest.Merge(m, src)
}
func (m *PrevEntryRequest) XXX_Size() int {
return m.Size()
}
func (m *PrevEntryRequest) XXX_DiscardUnknown() {
xxx_messageInfo_PrevEntryRequest.DiscardUnknown(m)
}
var xxx_messageInfo_PrevEntryRequest proto.InternalMessageInfo
func (m *PrevEntryRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type PrevEntryResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *PrevEntryResponse) Reset() { *m = PrevEntryResponse{} }
func (m *PrevEntryResponse) String() string { return proto.CompactTextString(m) }
func (*PrevEntryResponse) ProtoMessage() {}
func (*PrevEntryResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{17}
}
func (m *PrevEntryResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PrevEntryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PrevEntryResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PrevEntryResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_PrevEntryResponse.Merge(m, src)
}
func (m *PrevEntryResponse) XXX_Size() int {
return m.Size()
}
func (m *PrevEntryResponse) XXX_DiscardUnknown() {
xxx_messageInfo_PrevEntryResponse.DiscardUnknown(m)
}
var xxx_messageInfo_PrevEntryResponse proto.InternalMessageInfo
func (m *PrevEntryResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *PrevEntryResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *PrevEntryResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type NextEntryRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *NextEntryRequest) Reset() { *m = NextEntryRequest{} }
func (m *NextEntryRequest) String() string { return proto.CompactTextString(m) }
func (*NextEntryRequest) ProtoMessage() {}
func (*NextEntryRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{18}
}
func (m *NextEntryRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *NextEntryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_NextEntryRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *NextEntryRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_NextEntryRequest.Merge(m, src)
}
func (m *NextEntryRequest) XXX_Size() int {
return m.Size()
}
func (m *NextEntryRequest) XXX_DiscardUnknown() {
xxx_messageInfo_NextEntryRequest.DiscardUnknown(m)
}
var xxx_messageInfo_NextEntryRequest proto.InternalMessageInfo
func (m *NextEntryRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type NextEntryResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *NextEntryResponse) Reset() { *m = NextEntryResponse{} }
func (m *NextEntryResponse) String() string { return proto.CompactTextString(m) }
func (*NextEntryResponse) ProtoMessage() {}
func (*NextEntryResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{19}
}
func (m *NextEntryResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *NextEntryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_NextEntryResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *NextEntryResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_NextEntryResponse.Merge(m, src)
}
func (m *NextEntryResponse) XXX_Size() int {
return m.Size()
}
func (m *NextEntryResponse) XXX_DiscardUnknown() {
xxx_messageInfo_NextEntryResponse.DiscardUnknown(m)
}
var xxx_messageInfo_NextEntryResponse proto.InternalMessageInfo
func (m *NextEntryResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *NextEntryResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *NextEntryResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type RemoveRequest struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
}
func (m *RemoveRequest) Reset() { *m = RemoveRequest{} }
func (m *RemoveRequest) String() string { return proto.CompactTextString(m) }
func (*RemoveRequest) ProtoMessage() {}
func (*RemoveRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{20}
}
func (m *RemoveRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RemoveRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RemoveRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RemoveRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_RemoveRequest.Merge(m, src)
}
func (m *RemoveRequest) XXX_Size() int {
return m.Size()
}
func (m *RemoveRequest) XXX_DiscardUnknown() {
xxx_messageInfo_RemoveRequest.DiscardUnknown(m)
}
var xxx_messageInfo_RemoveRequest proto.InternalMessageInfo
func (m *RemoveRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *RemoveRequest) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
type RemoveResponse struct {
Status UpdateStatus `protobuf:"varint,1,opt,name=status,proto3,enum=atomix.log.service.UpdateStatus" json:"status,omitempty"`
Index uint64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"`
PreviousValue []byte `protobuf:"bytes,3,opt,name=previous_value,json=previousValue,proto3" json:"previous_value,omitempty"`
Timestamp time.Time `protobuf:"bytes,4,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *RemoveResponse) Reset() { *m = RemoveResponse{} }
func (m *RemoveResponse) String() string { return proto.CompactTextString(m) }
func (*RemoveResponse) ProtoMessage() {}
func (*RemoveResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{21}
}
func (m *RemoveResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RemoveResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RemoveResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *RemoveResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_RemoveResponse.Merge(m, src)
}
func (m *RemoveResponse) XXX_Size() int {
return m.Size()
}
func (m *RemoveResponse) XXX_DiscardUnknown() {
xxx_messageInfo_RemoveResponse.DiscardUnknown(m)
}
var xxx_messageInfo_RemoveResponse proto.InternalMessageInfo
func (m *RemoveResponse) GetStatus() UpdateStatus {
if m != nil {
return m.Status
}
return UpdateStatus_OK
}
func (m *RemoveResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *RemoveResponse) GetPreviousValue() []byte {
if m != nil {
return m.PreviousValue
}
return nil
}
func (m *RemoveResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
type ClearRequest struct {
}
func (m *ClearRequest) Reset() { *m = ClearRequest{} }
func (m *ClearRequest) String() string { return proto.CompactTextString(m) }
func (*ClearRequest) ProtoMessage() {}
func (*ClearRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{22}
}
func (m *ClearRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ClearRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ClearRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ClearRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ClearRequest.Merge(m, src)
}
func (m *ClearRequest) XXX_Size() int {
return m.Size()
}
func (m *ClearRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ClearRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ClearRequest proto.InternalMessageInfo
type ClearResponse struct {
}
func (m *ClearResponse) Reset() { *m = ClearResponse{} }
func (m *ClearResponse) String() string { return proto.CompactTextString(m) }
func (*ClearResponse) ProtoMessage() {}
func (*ClearResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{23}
}
func (m *ClearResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ClearResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ClearResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ClearResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_ClearResponse.Merge(m, src)
}
func (m *ClearResponse) XXX_Size() int {
return m.Size()
}
func (m *ClearResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ClearResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ClearResponse proto.InternalMessageInfo
type ListenRequest struct {
Replay bool `protobuf:"varint,1,opt,name=replay,proto3" json:"replay,omitempty"`
Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
Index uint64 `protobuf:"varint,3,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *ListenRequest) Reset() { *m = ListenRequest{} }
func (m *ListenRequest) String() string { return proto.CompactTextString(m) }
func (*ListenRequest) ProtoMessage() {}
func (*ListenRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{24}
}
func (m *ListenRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ListenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ListenRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ListenRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ListenRequest.Merge(m, src)
}
func (m *ListenRequest) XXX_Size() int {
return m.Size()
}
func (m *ListenRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ListenRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ListenRequest proto.InternalMessageInfo
func (m *ListenRequest) GetReplay() bool {
if m != nil {
return m.Replay
}
return false
}
func (m *ListenRequest) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *ListenRequest) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type ListenResponse struct {
Type ListenResponse_Type `protobuf:"varint,1,opt,name=type,proto3,enum=atomix.log.service.ListenResponse_Type" json:"type,omitempty"`
Index uint64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"`
Key string `protobuf:"bytes,3,opt,name=key,proto3" json:"key,omitempty"`
Value []byte `protobuf:"bytes,4,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,5,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
StreamId int64 `protobuf:"varint,6,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
}
func (m *ListenResponse) Reset() { *m = ListenResponse{} }
func (m *ListenResponse) String() string { return proto.CompactTextString(m) }
func (*ListenResponse) ProtoMessage() {}
func (*ListenResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{25}
}
func (m *ListenResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ListenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ListenResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ListenResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_ListenResponse.Merge(m, src)
}
func (m *ListenResponse) XXX_Size() int {
return m.Size()
}
func (m *ListenResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ListenResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ListenResponse proto.InternalMessageInfo
func (m *ListenResponse) GetType() ListenResponse_Type {
if m != nil {
return m.Type
}
return ListenResponse_NONE
}
func (m *ListenResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *ListenResponse) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *ListenResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *ListenResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
func (m *ListenResponse) GetStreamId() int64 {
if m != nil {
return m.StreamId
}
return 0
}
type EntriesRequest struct {
}
func (m *EntriesRequest) Reset() { *m = EntriesRequest{} }
func (m *EntriesRequest) String() string { return proto.CompactTextString(m) }
func (*EntriesRequest) ProtoMessage() {}
func (*EntriesRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{26}
}
func (m *EntriesRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *EntriesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_EntriesRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *EntriesRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_EntriesRequest.Merge(m, src)
}
func (m *EntriesRequest) XXX_Size() int {
return m.Size()
}
func (m *EntriesRequest) XXX_DiscardUnknown() {
xxx_messageInfo_EntriesRequest.DiscardUnknown(m)
}
var xxx_messageInfo_EntriesRequest proto.InternalMessageInfo
type EntriesResponse struct {
Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,proto3,stdtime" json:"timestamp"`
}
func (m *EntriesResponse) Reset() { *m = EntriesResponse{} }
func (m *EntriesResponse) String() string { return proto.CompactTextString(m) }
func (*EntriesResponse) ProtoMessage() {}
func (*EntriesResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{27}
}
func (m *EntriesResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *EntriesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_EntriesResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *EntriesResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_EntriesResponse.Merge(m, src)
}
func (m *EntriesResponse) XXX_Size() int {
return m.Size()
}
func (m *EntriesResponse) XXX_DiscardUnknown() {
xxx_messageInfo_EntriesResponse.DiscardUnknown(m)
}
var xxx_messageInfo_EntriesResponse proto.InternalMessageInfo
func (m *EntriesResponse) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
func (m *EntriesResponse) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func (m *EntriesResponse) GetTimestamp() time.Time {
if m != nil {
return m.Timestamp
}
return time.Time{}
}
// Listener is a log listener
type Listener struct {
SessionId uint64 `protobuf:"varint,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
StreamId uint64 `protobuf:"varint,2,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
Index uint64 `protobuf:"varint,4,opt,name=index,proto3" json:"index,omitempty"`
}
func (m *Listener) Reset() { *m = Listener{} }
func (m *Listener) String() string { return proto.CompactTextString(m) }
func (*Listener) ProtoMessage() {}
func (*Listener) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{28}
}
func (m *Listener) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Listener) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Listener.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Listener) XXX_Merge(src proto.Message) {
xxx_messageInfo_Listener.Merge(m, src)
}
func (m *Listener) XXX_Size() int {
return m.Size()
}
func (m *Listener) XXX_DiscardUnknown() {
xxx_messageInfo_Listener.DiscardUnknown(m)
}
var xxx_messageInfo_Listener proto.InternalMessageInfo
func (m *Listener) GetSessionId() uint64 {
if m != nil {
return m.SessionId
}
return 0
}
func (m *Listener) GetStreamId() uint64 {
if m != nil {
return m.StreamId
}
return 0
}
func (m *Listener) GetIndex() uint64 {
if m != nil {
return m.Index
}
return 0
}
type UnlistenRequest struct {
StreamId uint64 `protobuf:"varint,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
}
func (m *UnlistenRequest) Reset() { *m = UnlistenRequest{} }
func (m *UnlistenRequest) String() string { return proto.CompactTextString(m) }
func (*UnlistenRequest) ProtoMessage() {}
func (*UnlistenRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{29}
}
func (m *UnlistenRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *UnlistenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_UnlistenRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *UnlistenRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_UnlistenRequest.Merge(m, src)
}
func (m *UnlistenRequest) XXX_Size() int {
return m.Size()
}
func (m *UnlistenRequest) XXX_DiscardUnknown() {
xxx_messageInfo_UnlistenRequest.DiscardUnknown(m)
}
var xxx_messageInfo_UnlistenRequest proto.InternalMessageInfo
func (m *UnlistenRequest) GetStreamId() uint64 {
if m != nil {
return m.StreamId
}
return 0
}
type UnlistenResponse struct {
}
func (m *UnlistenResponse) Reset() { *m = UnlistenResponse{} }
func (m *UnlistenResponse) String() string { return proto.CompactTextString(m) }
func (*UnlistenResponse) ProtoMessage() {}
func (*UnlistenResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_dfa61300f829c393, []int{30}
}
func (m *UnlistenResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *UnlistenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_UnlistenResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *UnlistenResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_UnlistenResponse.Merge(m, src)
}
func (m *UnlistenResponse) XXX_Size() int {
return m.Size()
}
func (m *UnlistenResponse) XXX_DiscardUnknown() {
xxx_messageInfo_UnlistenResponse.DiscardUnknown(m)
}
var xxx_messageInfo_UnlistenResponse proto.InternalMessageInfo
func init() {
proto.RegisterEnum("atomix.log.service.UpdateStatus", UpdateStatus_name, UpdateStatus_value)
proto.RegisterEnum("atomix.log.service.ListenResponse_Type", ListenResponse_Type_name, ListenResponse_Type_value)
proto.RegisterType((*LogSnapshot)(nil), "atomix.log.service.LogSnapshot")
proto.RegisterType((*LogEntryValue)(nil), "atomix.log.service.LogEntryValue")
proto.RegisterType((*ContainsIndexRequest)(nil), "atomix.log.service.ContainsIndexRequest")
proto.RegisterType((*ContainsIndexResponse)(nil), "atomix.log.service.ContainsIndexResponse")
proto.RegisterType((*SizeRequest)(nil), "atomix.log.service.SizeRequest")
proto.RegisterType((*SizeResponse)(nil), "atomix.log.service.SizeResponse")
proto.RegisterType((*IndexRequest)(nil), "atomix.log.service.IndexRequest")
proto.RegisterType((*IndexResponse)(nil), "atomix.log.service.IndexResponse")
proto.RegisterType((*AppendRequest)(nil), "atomix.log.service.AppendRequest")
proto.RegisterType((*AppendResponse)(nil), "atomix.log.service.AppendResponse")
proto.RegisterType((*GetRequest)(nil), "atomix.log.service.GetRequest")
proto.RegisterType((*GetResponse)(nil), "atomix.log.service.GetResponse")
proto.RegisterType((*FirstEntryRequest)(nil), "atomix.log.service.FirstEntryRequest")
proto.RegisterType((*FirstEntryResponse)(nil), "atomix.log.service.FirstEntryResponse")
proto.RegisterType((*LastEntryRequest)(nil), "atomix.log.service.LastEntryRequest")
proto.RegisterType((*LastEntryResponse)(nil), "atomix.log.service.LastEntryResponse")
proto.RegisterType((*PrevEntryRequest)(nil), "atomix.log.service.PrevEntryRequest")
proto.RegisterType((*PrevEntryResponse)(nil), "atomix.log.service.PrevEntryResponse")
proto.RegisterType((*NextEntryRequest)(nil), "atomix.log.service.NextEntryRequest")
proto.RegisterType((*NextEntryResponse)(nil), "atomix.log.service.NextEntryResponse")
proto.RegisterType((*RemoveRequest)(nil), "atomix.log.service.RemoveRequest")
proto.RegisterType((*RemoveResponse)(nil), "atomix.log.service.RemoveResponse")
proto.RegisterType((*ClearRequest)(nil), "atomix.log.service.ClearRequest")
proto.RegisterType((*ClearResponse)(nil), "atomix.log.service.ClearResponse")
proto.RegisterType((*ListenRequest)(nil), "atomix.log.service.ListenRequest")
proto.RegisterType((*ListenResponse)(nil), "atomix.log.service.ListenResponse")
proto.RegisterType((*EntriesRequest)(nil), "atomix.log.service.EntriesRequest")
proto.RegisterType((*EntriesResponse)(nil), "atomix.log.service.EntriesResponse")
proto.RegisterType((*Listener)(nil), "atomix.log.service.Listener")
proto.RegisterType((*UnlistenRequest)(nil), "atomix.log.service.UnlistenRequest")
proto.RegisterType((*UnlistenResponse)(nil), "atomix.log.service.UnlistenResponse")
}
func init() { proto.RegisterFile("atomix/log/log.proto", fileDescriptor_dfa61300f829c393) }
var fileDescriptor_dfa61300f829c393 = []byte{
// 845 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x56, 0x4f, 0x6f, 0xe3, 0x44,
0x14, 0xcf, 0x24, 0x6e, 0xea, 0xbe, 0xc4, 0xae, 0x77, 0x36, 0x40, 0x28, 0x22, 0xcd, 0x8e, 0xb4,
0x22, 0x02, 0xe4, 0x4a, 0xe5, 0x82, 0x54, 0x09, 0xa9, 0x7f, 0xbc, 0xc8, 0xda, 0x10, 0x47, 0x6e,
0x37, 0x5c, 0x90, 0x82, 0xb7, 0x99, 0x06, 0x8b, 0xc4, 0x63, 0x3c, 0x93, 0xa8, 0x59, 0x09, 0x21,
0x04, 0x1f, 0x60, 0xaf, 0xdc, 0xf9, 0x30, 0x2b, 0x71, 0xd9, 0x23, 0x27, 0x40, 0xed, 0x17, 0x41,
0xf6, 0xd8, 0x8d, 0xbd, 0xbb, 0xa9, 0x50, 0x05, 0xe4, 0x10, 0x69, 0xde, 0x9b, 0xf7, 0xe7, 0xf7,
0x7e, 0xef, 0xcd, 0x8b, 0xa1, 0xe1, 0x09, 0x36, 0xf5, 0x2f, 0xf7, 0x26, 0x6c, 0x1c, 0xff, 0xcc,
0x30, 0x62, 0x82, 0x61, 0x2c, 0xb5, 0x66, 0xac, 0xe1, 0x34, 0x9a, 0xfb, 0xe7, 0x74, 0x67, 0x77,
0xcc, 0xd8, 0x78, 0x42, 0xf7, 0x12, 0x8b, 0xa7, 0xb3, 0x8b, 0x3d, 0xe1, 0x4f, 0x29, 0x17, 0xde,
0x34, 0x94, 0x4e, 0x3b, 0x8d, 0x31, 0x1b, 0xb3, 0xe4, 0xb8, 0x17, 0x9f, 0xa4, 0x96, 0x7c, 0x0d,
0xb5, 0x2e, 0x1b, 0x9f, 0x06, 0x5e, 0xc8, 0xbf, 0x61, 0x02, 0x37, 0x60, 0xc3, 0x0f, 0x46, 0xf4,
0xb2, 0x89, 0xda, 0xa8, 0xa3, 0xb8, 0x52, 0xc0, 0x07, 0xb0, 0x49, 0x03, 0x11, 0xf9, 0x94, 0x37,
0xcb, 0xed, 0x4a, 0xa7, 0xb6, 0xff, 0xc0, 0x7c, 0x1d, 0x81, 0xd9, 0x65, 0x63, 0x2b, 0x10, 0xd1,
0x62, 0xe0, 0x4d, 0x66, 0xd4, 0xcd, 0x3c, 0xc8, 0x0f, 0xa0, 0x15, 0x6e, 0x56, 0xe4, 0x68, 0xc0,
0xc6, 0x3c, 0xbe, 0x6e, 0x96, 0xdb, 0xa8, 0x53, 0x77, 0xa5, 0x80, 0x8f, 0x60, 0xeb, 0xa6, 0x8e,
0x66, 0xa5, 0x8d, 0x3a, 0xb5, 0xfd, 0x1d, 0x53, 0x56, 0x6a, 0x66, 0x95, 0x9a, 0x67, 0x99, 0xc5,
0x91, 0xfa, 0xe2, 0x8f, 0xdd, 0xd2, 0xf3, 0x3f, 0x77, 0x91, 0xbb, 0x74, 0x23, 0x1f, 0x43, 0xe3,
0x98, 0x05, 0xc2, 0xf3, 0x03, 0x6e, 0xc7, 0xa9, 0x5c, 0xfa, 0xdd, 0x8c, 0xf2, 0x15, 0xb5, 0x92,
0xcf, 0xe0, 0xad, 0x57, 0xac, 0x79, 0xc8, 0x02, 0x4e, 0xf1, 0x43, 0xd0, 0xcf, 0xd3, 0x8b, 0xe1,
0xd2, 0x4f, 0x75, 0xb5, 0xf3, 0xbc, 0x39, 0xd1, 0xa0, 0x76, 0xea, 0x3f, 0xa3, 0x69, 0x12, 0x42,
0xa0, 0x2e, 0xc5, 0x34, 0x0a, 0x06, 0x85, 0xfb, 0xcf, 0x68, 0xe2, 0xbb, 0xe1, 0x26, 0x67, 0xa2,
0x43, 0x3d, 0x0f, 0x8c, 0x3c, 0x00, 0xad, 0x98, 0xda, 0x80, 0xca, 0xb7, 0x74, 0x91, 0xe2, 0x8c,
0x8f, 0x64, 0x00, 0xda, 0x61, 0x18, 0xd2, 0x60, 0x74, 0x6b, 0x31, 0x2b, 0x48, 0x7d, 0x17, 0x54,
0xff, 0x62, 0x48, 0xa7, 0xa1, 0x58, 0x24, 0x9c, 0xaa, 0xee, 0xa6, 0x7f, 0x61, 0xc5, 0x22, 0xf9,
0x15, 0x81, 0x9e, 0x05, 0x4e, 0x93, 0x7f, 0x0a, 0x55, 0x2e, 0x3c, 0x31, 0xe3, 0x49, 0x68, 0x7d,
0xbf, 0xfd, 0xa6, 0xde, 0x3f, 0x09, 0x47, 0x9e, 0xa0, 0xa7, 0x89, 0x9d, 0x9b, 0xda, 0x2f, 0x31,
0x95, 0xf3, 0x98, 0xfe, 0x8d, 0x96, 0x12, 0x80, 0xcf, 0xa9, 0xb8, 0xbd, 0x91, 0xdf, 0x43, 0x2d,
0xb1, 0x49, 0xcb, 0xf8, 0xbf, 0xa7, 0xee, 0x3e, 0xdc, 0x7b, 0xe4, 0x47, 0x5c, 0x24, 0x83, 0x9f,
0x75, 0xf6, 0x67, 0x04, 0x38, 0xaf, 0x5d, 0x13, 0x36, 0x0c, 0x46, 0xd7, 0x7b, 0x05, 0xda, 0x4f,
0x08, 0xee, 0xe5, 0x94, 0x6b, 0x42, 0xd6, 0x01, 0xa3, 0x1f, 0xd1, 0x79, 0x1e, 0xd9, 0x8a, 0xf6,
0xc6, 0x78, 0x73, 0xa6, 0xeb, 0xc3, 0xdb, 0xa3, 0x97, 0xe2, 0x1f, 0xe2, 0xcd, 0x99, 0xae, 0x09,
0xef, 0x01, 0x68, 0x2e, 0x9d, 0xb2, 0x39, 0xbd, 0xc3, 0xde, 0x20, 0xbf, 0x21, 0xd0, 0x33, 0xef,
0xff, 0x68, 0x39, 0x3c, 0x04, 0x3d, 0x8c, 0xe8, 0xdc, 0x67, 0x33, 0x3e, 0x94, 0x08, 0x2a, 0x09,
0x02, 0x2d, 0xd3, 0x0e, 0x5e, 0xa7, 0x42, 0xb9, 0x1b, 0x15, 0x3a, 0xd4, 0x8f, 0x27, 0xd4, 0x8b,
0xb2, 0x07, 0xb0, 0x0d, 0x5a, 0x2a, 0xcb, 0xda, 0x88, 0x03, 0x5a, 0xd7, 0xe7, 0x82, 0x06, 0x19,
0x57, 0x6f, 0x43, 0x35, 0xa2, 0xe1, 0xc4, 0x5b, 0xa4, 0x9b, 0x3f, 0x95, 0xb2, 0xf5, 0x1c, 0x17,
0xb2, 0x95, 0xac, 0xe7, 0x65, 0x71, 0x95, 0xfc, 0x08, 0xfc, 0x52, 0x06, 0x3d, 0x8b, 0x98, 0xf2,
0x77, 0x00, 0x8a, 0x58, 0x84, 0x34, 0x65, 0xef, 0x83, 0x37, 0xfe, 0xad, 0x16, 0x3c, 0xcc, 0xb3,
0x45, 0x48, 0xdd, 0xc4, 0x69, 0x05, 0x85, 0x29, 0x9a, 0x4a, 0x01, 0x8d, 0xe4, 0x52, 0x59, 0x39,
0x4e, 0x1b, 0x77, 0xe2, 0x10, 0xbf, 0x07, 0x5b, 0x5c, 0x44, 0xd4, 0x9b, 0x0e, 0xfd, 0x51, 0xb3,
0xda, 0x46, 0x9d, 0x8a, 0xab, 0x4a, 0x85, 0x3d, 0x22, 0x1f, 0x81, 0x12, 0x83, 0xc5, 0x2a, 0x28,
0x3d, 0xa7, 0x67, 0x19, 0x25, 0x5c, 0x07, 0xf5, 0xb0, 0xdf, 0xb7, 0x7a, 0x27, 0xd6, 0x89, 0x81,
0x70, 0x0d, 0x36, 0x5d, 0xeb, 0x0b, 0x67, 0x60, 0x9d, 0x18, 0x15, 0x62, 0x80, 0x6e, 0xc9, 0x0f,
0x86, 0xac, 0x1f, 0x3f, 0x22, 0xd8, 0xbe, 0x51, 0xad, 0xe9, 0xb9, 0x7c, 0x05, 0xaa, 0xa4, 0x9f,
0x46, 0xf8, 0x7d, 0x00, 0x4e, 0x39, 0xf7, 0x59, 0x10, 0x17, 0x2b, 0x01, 0x6c, 0xa5, 0x1a, 0x7b,
0x54, 0xa4, 0x42, 0x36, 0xe4, 0x86, 0x8a, 0x25, 0x6e, 0x25, 0x3f, 0x0f, 0x26, 0x6c, 0x3f, 0x09,
0x26, 0x85, 0x11, 0x2b, 0x44, 0x41, 0xc5, 0x28, 0xf1, 0xda, 0x5e, 0xda, 0x4b, 0x46, 0x3e, 0xb4,
0xa1, 0x9e, 0x7f, 0x5e, 0xb8, 0x0a, 0x65, 0xe7, 0xb1, 0x51, 0x92, 0xa4, 0x3b, 0x7d, 0x03, 0x61,
0x1d, 0xe0, 0x4b, 0xd7, 0x3e, 0xb3, 0x86, 0x5d, 0xe7, 0xf8, 0xb1, 0x51, 0xc6, 0xef, 0xc0, 0xfd,
0xbe, 0x6b, 0x1d, 0x3b, 0xbd, 0x13, 0xfb, 0xcc, 0x76, 0x7a, 0xc3, 0x47, 0x87, 0x76, 0x37, 0x6e,
0xc1, 0x51, 0xf3, 0xc5, 0x55, 0x0b, 0xbd, 0xbc, 0x6a, 0xa1, 0xbf, 0xae, 0x5a, 0xe8, 0xf9, 0x75,
0xab, 0xf4, 0xf2, 0xba, 0x55, 0xfa, 0xfd, 0xba, 0x55, 0x7a, 0x5a, 0x4d, 0xf8, 0xfa, 0xe4, 0xef,
0x00, 0x00, 0x00, 0xff, 0xff, 0x54, 0x89, 0x99, 0x5b, 0x8e, 0x0a, 0x00, 0x00,
}
func (m *LogSnapshot) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LogSnapshot) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LogSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Entries) > 0 {
for iNdEx := len(m.Entries) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Entries[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintLog(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *LogEntryValue) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LogEntryValue) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LogEntryValue) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n1, err1 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err1 != nil {
return 0, err1
}
i -= n1
i = encodeVarintLog(dAtA, i, uint64(n1))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ContainsIndexRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ContainsIndexRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ContainsIndexRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ContainsIndexResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ContainsIndexResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ContainsIndexResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.ContainsIndex {
i--
if m.ContainsIndex {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *SizeRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SizeRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SizeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *SizeResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SizeResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SizeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Size_ != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Size_))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *IndexRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *IndexRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *IndexRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *IndexResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *IndexResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *IndexResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Key != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Key))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *AppendRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AppendRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AppendRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.IfEmpty {
i--
if m.IfEmpty {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x18
}
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *AppendResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AppendResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *AppendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n2, err2 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err2 != nil {
return 0, err2
}
i -= n2
i = encodeVarintLog(dAtA, i, uint64(n2))
i--
dAtA[i] = 0x1a
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x10
}
if m.Status != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Status))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *GetRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *GetResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *GetResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *GetResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n3, err3 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err3 != nil {
return 0, err3
}
i -= n3
i = encodeVarintLog(dAtA, i, uint64(n3))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *FirstEntryRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *FirstEntryRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *FirstEntryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *FirstEntryResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *FirstEntryResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *FirstEntryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n4, err4 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err4 != nil {
return 0, err4
}
i -= n4
i = encodeVarintLog(dAtA, i, uint64(n4))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *LastEntryRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LastEntryRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LastEntryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *LastEntryResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LastEntryResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *LastEntryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n5, err5 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err5 != nil {
return 0, err5
}
i -= n5
i = encodeVarintLog(dAtA, i, uint64(n5))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *PrevEntryRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PrevEntryRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PrevEntryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *PrevEntryResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PrevEntryResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *PrevEntryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n6, err6 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err6 != nil {
return 0, err6
}
i -= n6
i = encodeVarintLog(dAtA, i, uint64(n6))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *NextEntryRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *NextEntryRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *NextEntryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *NextEntryResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *NextEntryResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *NextEntryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n7, err7 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err7 != nil {
return 0, err7
}
i -= n7
i = encodeVarintLog(dAtA, i, uint64(n7))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *RemoveRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RemoveRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RemoveRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *RemoveResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RemoveResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *RemoveResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n8, err8 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err8 != nil {
return 0, err8
}
i -= n8
i = encodeVarintLog(dAtA, i, uint64(n8))
i--
dAtA[i] = 0x22
if len(m.PreviousValue) > 0 {
i -= len(m.PreviousValue)
copy(dAtA[i:], m.PreviousValue)
i = encodeVarintLog(dAtA, i, uint64(len(m.PreviousValue)))
i--
dAtA[i] = 0x1a
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x10
}
if m.Status != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Status))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ClearRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ClearRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ClearRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *ClearResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ClearResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ClearResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *ListenRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ListenRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ListenRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x18
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintLog(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0x12
}
if m.Replay {
i--
if m.Replay {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *ListenResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ListenResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ListenResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.StreamId != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.StreamId))
i--
dAtA[i] = 0x30
}
n9, err9 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err9 != nil {
return 0, err9
}
i -= n9
i = encodeVarintLog(dAtA, i, uint64(n9))
i--
dAtA[i] = 0x2a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x22
}
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintLog(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0x1a
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x10
}
if m.Type != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *EntriesRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *EntriesRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *EntriesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *EntriesResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *EntriesResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *EntriesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
n10, err10 := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp):])
if err10 != nil {
return 0, err10
}
i -= n10
i = encodeVarintLog(dAtA, i, uint64(n10))
i--
dAtA[i] = 0x1a
if len(m.Value) > 0 {
i -= len(m.Value)
copy(dAtA[i:], m.Value)
i = encodeVarintLog(dAtA, i, uint64(len(m.Value)))
i--
dAtA[i] = 0x12
}
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Listener) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Listener) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Listener) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.Index != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.Index))
i--
dAtA[i] = 0x20
}
if m.StreamId != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.StreamId))
i--
dAtA[i] = 0x10
}
if m.SessionId != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.SessionId))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *UnlistenRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *UnlistenRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *UnlistenRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.StreamId != 0 {
i = encodeVarintLog(dAtA, i, uint64(m.StreamId))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *UnlistenResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *UnlistenResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *UnlistenResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func encodeVarintLog(dAtA []byte, offset int, v uint64) int {
offset -= sovLog(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *LogSnapshot) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
if len(m.Entries) > 0 {
for _, e := range m.Entries {
l = e.Size()
n += 1 + l + sovLog(uint64(l))
}
}
return n
}
func (m *LogEntryValue) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *ContainsIndexRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *ContainsIndexResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.ContainsIndex {
n += 2
}
return n
}
func (m *SizeRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *SizeResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Size_ != 0 {
n += 1 + sovLog(uint64(m.Size_))
}
return n
}
func (m *IndexRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *IndexResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Key != 0 {
n += 1 + sovLog(uint64(m.Key))
}
return n
}
func (m *AppendRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
if m.IfEmpty {
n += 2
}
return n
}
func (m *AppendResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Status != 0 {
n += 1 + sovLog(uint64(m.Status))
}
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *GetRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *GetResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *FirstEntryRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *FirstEntryResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *LastEntryRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *LastEntryResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *PrevEntryRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *PrevEntryResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *NextEntryRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *NextEntryResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *RemoveRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
return n
}
func (m *RemoveResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Status != 0 {
n += 1 + sovLog(uint64(m.Status))
}
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.PreviousValue)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *ClearRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *ClearResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *ListenRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Replay {
n += 2
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *ListenResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovLog(uint64(m.Type))
}
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
if m.StreamId != 0 {
n += 1 + sovLog(uint64(m.StreamId))
}
return n
}
func (m *EntriesRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *EntriesResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
l = len(m.Value)
if l > 0 {
n += 1 + l + sovLog(uint64(l))
}
l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp)
n += 1 + l + sovLog(uint64(l))
return n
}
func (m *Listener) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.SessionId != 0 {
n += 1 + sovLog(uint64(m.SessionId))
}
if m.StreamId != 0 {
n += 1 + sovLog(uint64(m.StreamId))
}
if m.Index != 0 {
n += 1 + sovLog(uint64(m.Index))
}
return n
}
func (m *UnlistenRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.StreamId != 0 {
n += 1 + sovLog(uint64(m.StreamId))
}
return n
}
func (m *UnlistenResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func sovLog(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozLog(x uint64) (n int) {
return sovLog(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *LogSnapshot) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LogSnapshot: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LogSnapshot: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Entries = append(m.Entries, &LogEntryValue{})
if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LogEntryValue) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LogEntryValue: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LogEntryValue: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ContainsIndexRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ContainsIndexRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ContainsIndexRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ContainsIndexResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ContainsIndexResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ContainsIndexResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field ContainsIndex", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.ContainsIndex = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SizeRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SizeRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SizeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SizeResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SizeResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SizeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType)
}
m.Size_ = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Size_ |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *IndexRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: IndexRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: IndexRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *IndexResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: IndexResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: IndexResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
m.Key = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Key |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AppendRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AppendRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AppendRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field IfEmpty", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.IfEmpty = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *AppendResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AppendResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AppendResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
m.Status = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Status |= UpdateStatus(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *GetResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: GetResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: GetResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *FirstEntryRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FirstEntryRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FirstEntryRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *FirstEntryResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FirstEntryResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FirstEntryResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LastEntryRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LastEntryRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LastEntryRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LastEntryResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LastEntryResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LastEntryResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PrevEntryRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PrevEntryRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PrevEntryRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PrevEntryResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PrevEntryResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PrevEntryResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *NextEntryRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NextEntryRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NextEntryRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *NextEntryResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NextEntryResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NextEntryResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RemoveRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RemoveRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RemoveRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RemoveResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RemoveResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RemoveResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
m.Status = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Status |= UpdateStatus(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PreviousValue", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.PreviousValue = append(m.PreviousValue[:0], dAtA[iNdEx:postIndex]...)
if m.PreviousValue == nil {
m.PreviousValue = []byte{}
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ClearRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ClearRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ClearRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ClearResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ClearResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ClearResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ListenRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ListenRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ListenRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Replay", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Replay = bool(v != 0)
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ListenResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ListenResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ListenResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= ListenResponse_Type(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field StreamId", wireType)
}
m.StreamId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.StreamId |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *EntriesRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: EntriesRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: EntriesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *EntriesResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: EntriesResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: EntriesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthLog
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthLog
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.Timestamp, dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Listener) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Listener: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Listener: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field SessionId", wireType)
}
m.SessionId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.SessionId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field StreamId", wireType)
}
m.StreamId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.StreamId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
}
m.Index = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Index |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *UnlistenRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: UnlistenRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: UnlistenRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field StreamId", wireType)
}
m.StreamId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.StreamId |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *UnlistenResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLog
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: UnlistenResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: UnlistenResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipLog(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthLog
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipLog(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowLog
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowLog
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowLog
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthLog
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupLog
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthLog
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthLog = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowLog = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupLog = fmt.Errorf("proto: unexpected end of group")
)
|
Mattlk13/core
|
environments/se/core/src/test/java/org/jboss/weld/environment/se/test/container/provider/TestExtension.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.environment.se.test.container.provider;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicReference;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeBeanDiscovery;
import javax.enterprise.inject.spi.CDI;
import javax.enterprise.inject.spi.Extension;
import org.jboss.weld.environment.se.WeldContainer;
public class TestExtension implements Extension {
static AtomicReference<BeanManager> beanManagerReference = new AtomicReference<BeanManager>(null);
static AtomicReference<Bean<?>> fooBeanReference = new AtomicReference<Bean<?>>(null);
public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery event) {
CDI<Object> cdi = CDI.current();
@SuppressWarnings("resource")
WeldContainer container = (WeldContainer) cdi;
assertFalse(container.isRunning());
try {
cdi.select(Object.class);
fail();
} catch (IllegalStateException expected) {
}
beanManagerReference.set(cdi.getBeanManager());
}
public void afterBeanDiscovery(@Observes AfterBeanDiscovery event) {
try {
CDI.current().select(Foo.class);
fail();
} catch (IllegalStateException expected) {
}
BeanManager beanManager = beanManagerReference.get();
if (beanManager != null) {
fooBeanReference.set(beanManager.resolve(beanManager.getBeans(Foo.class)));
}
}
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event) {
CDI.current().select(Foo.class).get().getCurrent().equals(CDI.current());
}
static void reset() {
beanManagerReference.set(null);
fooBeanReference.set(null);
}
}
|
CiscoDevNet/Glance
|
public/glance/editor/EditorLoader.js
|
(function(nx) {
var EXPORT = nx.define("glance.editor.EditorLoader", nx.ui.Element, {
view: {
cssclass: "glance-editor-loading",
content: "Loading ..."
},
properties: {
session: null,
model: null,
view: nx.binding("model", true, function(async, model) {
var view;
if (!model) {
async.set(this);
} else {
view = new glance.editor.Editor();
view.model(model);
async.set(view);
return view;
}
})
},
methods: {
loadOld: function(mapUrl) {
var resources = new nx.Object();
resources.retain(glance.model.map.MapLoader.load(mapUrl, function(map) {
var emodel = EXPORT.getEditorModelByPerspectiveModel(map);
this.model(emodel);
}.bind(this)));
return resources;
},
load: function(url) {
return nx.util.ajax({
url: url,
success: function(resources, svg) {
svg = glance.common.Util.getRealSvg(svg);
var emodel = EXPORT.getEditorModelBySvg(svg);
this.model(emodel);
}.bind(this)
});
}
},
statics: {
getSvgByEditorModel: function(model) {
return nx.singleton(nx.lib.svg.Svg, {
view: {
cssclass: "mask-{mask}",
attributes: {
viewBox: nx.binding("model.width, model.height", function(width, height) {
if (width && height) {
return [0, 0, width, height].join(" ");
}
})
},
properties: {
width: "{model.width}",
height: "{model.height}"
},
content: [{
name: "style",
type: "nx.lib.svg.SvgStyle",
content: nx.util.csssheet.css({
"svg": {
"background": 'url(\'data:image/svg+xml;utf-8,<svg style="fill:white;" width="20" height="20" viewBox="0 0 20 20"><path d="M0,0L10,0L10,20L20,20L20,10L0,10Z" fill="#eee" stroke="none" /></svg>\')'
},
"svg.mask-true": {
"background": "black"
},
".boundary": {
"stroke": "none",
"fill": "rgba(255,255,255,1)"
},
".region": {
"stroke": "black",
"stroke-width": "1px",
"stroke-dasharray": "5,5",
"fill": "none"
},
"svg.mask-true .region": {
"stroke": "white"
},
".wall": {
"stroke": "rgba(0,0,0,1)",
"fill": "none"
},
".barrier": {
"stroke": "none",
"fill": "rgba(0,0,0,1)"
}
})
}, {
type: "nx.lib.svg.shape.Path",
cssclass: "boundary",
attributes: {
d: "{model.boundary.def}"
}
}, {
repeat: "{model.entities}",
type: "nx.lib.svg.shape.Path",
cssclass: nx.binding("scope.model", function(model) {
if (nx.is(model, "glance.editor.model.MapRegionModel")) {
return "region";
}
if (nx.is(model, "glance.editor.model.MapWallModel")) {
return "wall";
}
if (nx.is(model, "glance.editor.model.MapBarrierModel")) {
return "barrier";
}
}),
cssstyle: {
"stroke-width": nx.binding("scope.model.stroke.width", function(width) {
return (width * 1 ? width : "0") + "px";
})
},
attributes: {
d: "{scope.model.def}"
}
}]
},
properties: {
model: model,
mask: false
},
methods: {
getMaskDataUrl: function(callback) {
this.mask(true);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = this.width();
canvas.height = this.height();
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
// pull the entire image into an array of pixel data
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// examine every pixel, change any old rgb to the new-rgb
for (var i = 0; i < imageData.data.length; i += 4) {
// replace white to transparent
if (imageData.data[i] == 255 && imageData.data[i + 1] == 255 && imageData.data[i + 2] == 255 && imageData.data[i + 3] == 255) {
// change to your new rgb
imageData.data[i] = 0;
imageData.data[i + 1] = 0;
imageData.data[i + 2] = 0;
imageData.data[i + 3] = 0;
}
}
// put the altered data back on the canvas
ctx.putImageData(imageData, 0, 0);
var maskUrl = canvas.toDataURL();
this.mask(false);
callback(maskUrl);
}.bind(this);
img.src = nx.lib.svg.Svg.serialize(this.dom());
}
}
});
},
getSvgMapByEditoModel: function(model, callback) {
var svg = EXPORT.getSvgByEditorModel(model);
var svgUrl = nx.lib.svg.Svg.serialize(svg.dom());
return svg.getMaskDataUrl(function(maskUrl) {
callback([svgUrl, maskUrl]);
});
},
getEditorModelBySvg: function(svg) {
return glance.common.Util.withSvgAttaching(svg, function(svg, size) {
var emodel = new glance.editor.model.EditorModel();
emodel.width(size.width);
emodel.height(size.height);
var elements = svg.querySelectorAll("rect, polygon, path, circle, line, polyline, ellipse");
nx.each(elements, function(element) {
var model, id, name, icon, position, fill, stroke;
if (element.tagName.toLowerCase() === "circle" && element.getAttribute("type") === "facility") {
// facility
[name, icon] = ["id", "icon"].map(element.getAttribute.bind(element));
position = ["cx", "cy"].map(element.getAttribute.bind(element)).map(function(v) {
return v * 1 || 0;
});
position = new glance.editor.model.VertexModel(position[0], position[1]);
model = new glance.editor.model.MapFacilityModel();
nx.sets(model, {
name: name,
icon: icon,
position: position
});
emodel.facilities().push(model);
} else {
[fill, stroke] = [glance.editor.model.SvgColorModel.getFillColorByElement(element), glance.editor.model.SvgStrokeModel.getStrokeByElement(element)];
if (!fill || fill.a() == 0) {
// no fill or completely transparent
if (stroke && stroke.color() && stroke.color().a() > 0 && stroke.width() != 0) {
// and has stroke
if (stroke.dasharray() != "0px" && stroke.dasharray() !== "none") {
// dashed stroke: zone
model = new glance.editor.model.MapRegionModel(element);
emodel.regions().push(model);
} else {
// solid stroke: wall
model = new glance.editor.model.MapWallModel(element);
emodel.walls().push(model);
}
}
} else {
// filled, ignore stroke
if (fill.r() == 1 && fill.g() == 1 && fill.b() == 1) {
// completely white: boundary
model = new glance.editor.model.MapRegionModel(element);
emodel.boundary(model);
} else {
// other: barrier
model = new glance.editor.model.MapBarrierModel(element);
emodel.barriers().push(model);
}
}
}
});
return emodel;
});
},
getEditorModelByPerspectiveModel: function(map) {
var emodel = new glance.editor.model.EditorModel();
var areas = [
["boundary", map.shape()]
].concat(map.terrains().toArray().map(function(item) {
return [nx.path(item, "category"), nx.path(item, "shape")];
}));
nx.each(areas, function([category, shape]) {
var model, defs, segments;
switch (category) {
case "barrier":
case "furnish":
case "block":
model = new glance.editor.model.MapBarrierModel();
emodel.barriers().push(model);
break;
case "boundary":
model = new glance.editor.model.MapRegionModel();
emodel.boundary(model);
break;
case "region":
case "zone":
model = new glance.editor.model.MapRegionModel();
model.name(category + " " + nx.serial());
emodel.regions().push(model);
break;
case "wall":
model = new glance.editor.model.MapWallModel();
emodel.walls().push(model);
break;
}
// add points
defs = EXPORT.getDefsByCurves(shape.curves);
segments = glance.editor.model.SvgPathModel.getSegmentsByDefArray(defs);
model.segments().pushAll(segments);
});
emodel.width(map.width());
emodel.height(map.height());
return emodel;
},
getDefsByCurves: function(curves) {
var i, curve, v, vp, defs = [];
for (vp = [0, 0], i = 0; i < curves.length; i++) {
curve = curves[i];
switch (curve.constructor) {
// TODO other curve types
case THREE.LineCurve:
if (defs.length === 0 || curve.v1.x !== vp[0] || curve.v1.y !== vp[1]) {
defs.push(["M", [curve.v1.x, curve.v1.y]]);
}
defs.push(["L", [curve.v2.x, curve.v2.y]]);
vp = [curve.v2.x, curve.v2.y];
break;
}
}
return defs;
},
getDefaultEditorModel: function() {
var model = new glance.editor.model.EditorModel();
model.width(1024);
model.height(768);
return model;
},
CSS: nx.util.csssheet.create({
".glance-editor-loading": {
"position": "absolute",
"left": "0",
"right": "0",
"top": "0",
"bottom": "0",
"width": "200px",
"height": "200px",
"text-align": "center",
"line-height": "200px",
"margin": "auto"
}
})
}
});
})(nx);
|
andresilva1997/alohaAndes
|
isis2304-tutorial-arquitectura/src/vos/Vivienda.java
|
<gh_stars>0
package vos;
import org.codehaus.jackson.annotate.*;
public class Vivienda extends Operador {
////////////////////////////////////////////
//////////////// ATRIBUTOS///////////////////
////////////////////////////////////////////
/**
* Numero de habitaciones en la vivienda
*/
@JsonProperty(value = "numeroDeHabitaciones")
private Integer numeroDeHabitaciones;
/**
* donde esta ubicada
*/
@JsonProperty(value = "ubicacion")
private String ubicacion;
/**
* Tiene o no menaje
*/
@JsonProperty(value = "menaje")
private Boolean menaje;
/**
* costo de alquilar la vivienda.
*/
@JsonProperty(value = "costo")
private Double costo;
/**
* Descripcion del seguro con costos y terminos y condiciones
*/
@JsonProperty(value = "seguro")
private String seguro;
/**
* Conteo de las veces que la propiedad ha sido alquilada en el corrido del
* anho
*/
@JsonProperty(value = "diasAlquilada")
private Integer diasAlquilada;
////////////////////////////////////////////
//////////////// CONSTRUCTOR/////////////////
////////////////////////////////////////////
/**
* @param idOperador
* @param cupoTotal
* @param correo
* @param nombre
* @param numeroDeHabitaciones
* @param ubicacion
* @param menaje
* @param costo
* @param seguro
* @param diasAlquilada
*/
public Vivienda(@JsonProperty(value = "idOperador") Long idOperador,
@JsonProperty(value = "cupoTotal") Integer cupoTotal, @JsonProperty(value = "correo") String correo,
@JsonProperty(value = "nombre") String nombre, @JsonProperty(value="tipo") String tipo,@JsonProperty(value = "numeroDeHabitaciones") Integer numeroDeHabitaciones,
@JsonProperty(value = "ubicacion") String ubicacion,
@JsonProperty(value = "menaje") Boolean menaje, @JsonProperty(value = "costo") Double costo, @JsonProperty(value = "seguro") String seguro,
@JsonProperty(value = "diasAlquilada") Integer diasAlquilada) {
super(idOperador, cupoTotal, correo, nombre,tipo);
this.numeroDeHabitaciones = numeroDeHabitaciones;
this.ubicacion = ubicacion;
this.menaje = menaje;
this.costo = costo;
this.seguro = seguro;
this.diasAlquilada = diasAlquilada;
}
////////////////////////////////////////////
//////////// GETTERS AND SETTERS/////////////
////////////////////////////////////////////
/**
* @return the numeroDeHabitaciones
*/
public Integer getNumeroDeHabitaciones() {
return numeroDeHabitaciones;
}
/**
* @param numeroDeHabitaciones
* the numeroDeHabitaciones to set
*/
public void setNumeroDeHabitaciones(Integer numeroDeHabitaciones) {
this.numeroDeHabitaciones = numeroDeHabitaciones;
}
/**
* @return the ubicacion
*/
public String getUbicacion() {
return ubicacion;
}
/**
* @param ubicacion
* the ubicacion to set
*/
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
/**
* @return the menaje
*/
public Boolean getMenaje() {
return menaje;
}
/**
* @param menaje
* the menaje to set
*/
public void setMenaje(Boolean menaje) {
this.menaje = menaje;
}
/**
* @return the costo
*/
public Double getCosto() {
return costo;
}
/**
* @param costo
* the costo to set
*/
public void setCosto(Double costo) {
this.costo = costo;
}
/**
* @return the seguro
*/
public String getSeguro() {
return seguro;
}
/**
* @param seguro
* the seguro to set
*/
public void setSeguro(String seguro) {
this.seguro = seguro;
}
/**
* @return the diasAlquilada
*/
public Integer getDiasAlquilada() {
return diasAlquilada;
}
/**
* @param diasAlquilada
* the diasAlquilada to set
*/
public void setDiasAlquilada(Integer diasAlquilada) {
this.diasAlquilada = diasAlquilada;
}
}
|
kristofferlind/mean-projise
|
client/app/chatpanel/chatpanel.controller.js
|
<reponame>kristofferlind/mean-projise
//chatpanel.controller.js
/**
* @ngdoc object
* @name ChatPanelController
* @todo move most of sendMessage logic to a directive (on-enter, shift-key:true default:false..)
* @todo panelstate should be moved to directive
* @todo clear newMessage on send (needs to wait until post is sent)
* @description Viewlogic for Chatpanel, manages panelstate and sending messages
*/
angular.module('projiSeApp').controller('ChatpanelController', function($scope, PanelSwitch, $timeout, Chat) {
'use strict';
//Make Chat service available in view
$scope.Chat = Chat;
$scope.newMessage = {
message: ''
};
$scope.chatpanelActive = PanelSwitch.chatpanel.get();
$scope.$on('chatpanel:switched', function() {
$scope.chatpanelActive = PanelSwitch.chatpanel.get();
if ($scope.chatpanelActive !== PanelSwitch.chatpanel.get()) {
$timeout(function() {
$scope.chatpanelActive = PanelSwitch.chatpanel.get();
});
}
});
$scope.sendMessage = function($event) {
// if enter & shift
if ($event.keyCode === 13 && $event.shiftKey) {
return false;
} else {
//if enter & not shift
if ($event.keyCode === 13 && !$event.shiftKey) {
//empty messages are kind of useless
if ($scope.newMessage.message === '') {
$event.preventDefault(); //we dont want a newline in this case
return false;
}
$event.preventDefault(); //no newline
//add message to firebase
Chat.sendMessage($scope.newMessage);
//clear input field
// $scope.newMessage.message.focus(); //for some reason this sends an empty message.. need to make sure post is sent before emptying
}
}
};
});
|
yoshida-eth0/ruby-toji
|
lib/toji/progress/builder.rb
|
module Toji
module Progress
class Builder
def initialize(progress_cls, state_cls)
@progress_cls = progress_cls
@state_cls = state_cls
@states = []
@date_line = 0
@prefix_day_labels = nil
end
def <<(state)
@states += [state].flatten.map {|state|
if State===state
state
else
@state_cls.create(state)
end
}
self
end
alias_method :add, :<<
def date_line(val, unit=SECOND)
@date_line = (val * unit).to_i
self
end
def prefix_day_labels(val)
@prefix_day_labels = val
self
end
def build
progress = @progress_cls.new
states = @states.map{|s|
s.progress = progress
s
}.sort_by(&:time)
progress.states = states
progress.date_line = @date_line
if progress.respond_to?(:prefix_day_labels=)
progress.prefix_day_labels = @prefix_day_labels
end
progress
end
end
end
end
|
chriszh123/ruiyi
|
ruoyi-fac/src/main/java/com/ruoyi/fac/mapper/BuyerAddressMapper.java
|
<filename>ruoyi-fac/src/main/java/com/ruoyi/fac/mapper/BuyerAddressMapper.java
package com.ruoyi.fac.mapper;
import com.ruoyi.fac.domain.BuyerAddress;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 买者用户收货地址 数据层
*
* @author ruoyi
* @date 2019-01-28
*/
public interface BuyerAddressMapper {
/**
* 查询买者用户收货地址信息
*
* @param id 买者用户收货地址ID
* @return 买者用户收货地址信息
*/
BuyerAddress selectBuyerAddressById(Long id);
/**
* 查询买者用户收货地址列表
*
* @param buyerAddress 买者用户收货地址信息
* @return 买者用户收货地址集合
*/
List<BuyerAddress> selectBuyerAddressList(BuyerAddress buyerAddress);
/**
* 新增买者用户收货地址
*
* @param buyerAddress 买者用户收货地址信息
* @return 结果
*/
int insertBuyerAddress(BuyerAddress buyerAddress);
/**
* 修改买者用户收货地址
*
* @param buyerAddress 买者用户收货地址信息
* @return 结果
*/
int updateBuyerAddress(BuyerAddress buyerAddress);
/**
* 删除买者用户收货地址
*
* @param id 买者用户收货地址ID
* @return 结果
*/
int deleteBuyerAddressById(Long id);
/**
* 批量删除买者用户收货地址
*
* @param ids 需要删除的数据ID
* @return 结果
*/
int deleteBuyerAddressByIds(String[] ids);
BuyerAddress getDefaultAddress(String openId);
List<BuyerAddress> selectBuyerAddressByTokenId(String token);
BuyerAddress selectBuyerAddressByTokenAndId(@Param("token") String token, @Param("id") long id);
}
|
talkowski-lab/gnomad-sv-v3-qc
|
src/sv-pipeline/04_variant_resolution/scripts/merge_RdTest_genotypes.py
|
<filename>src/sv-pipeline/04_variant_resolution/scripts/merge_RdTest_genotypes.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2018 <NAME> <<EMAIL>>
# Distributed under terms of the MIT license.
"""
"""
import argparse
import pandas as pd
def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('genotypes')
parser.add_argument('GQ')
parser.add_argument('fout')
args = parser.parse_args()
# Load and melt genotypes
gt = pd.read_table(args.genotypes).drop_duplicates()
gt = pd.melt(gt, id_vars='chr start end cnvID'.split(),
var_name='sample', value_name='genotype')
# Round genotype copy states
# gt['genotype'] = gt['genotype'].round().astype(int)
# Pivot back out so input genotype matrix is all integers
# pivot = gt.pivot_table(index='chr start end cnvID'.split(),
# columns='sample', values='genotype').reset_index()
# samples = [c for c in pivot.columns if c not in 'chr start end cnvID'.split()]
# pivot[samples] = pivot[samples].astype(int)
# pivot.to_csv(args.genotypes, index=False, sep='\t')
# Load and melt GQ
gq = pd.read_table(args.GQ)
gq = pd.melt(gq, id_vars='chr start end cnvID'.split(),
var_name='sample', value_name='GQ')
# Merge genotypes with GQ
gt = pd.merge(gt, gq, on='chr start end cnvID sample'.split(), how='left')
gt.to_csv(args.fout, header=False, index=False, sep='\t')
if __name__ == '__main__':
main()
|
Suvradippaul/DSA-Bootcamp-Java
|
my work/MyJavaWork/src/oops/generics/CustomGenericArrayList.java
|
package oops.generics;
import java.util.Arrays;
public class CustomGenericArrayList<T> {
private Object[] arr;
private static int DEFAULT_SIZE = 10;
private int size = 0;
public CustomGenericArrayList() {
this.arr = new Object[DEFAULT_SIZE];
}
public void add(T num) {
if (this.isFull()) {
this.resize();
}
arr[size] = num;
size++;
}
public void resize() {
Object[] temp = new Object[DEFAULT_SIZE*2];
// copy the current into the new one
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
arr = temp;
}
public boolean isFull() {
// TODO Auto-generated method stub
return size == DEFAULT_SIZE;
}
public T get(int n) {
return (T)arr[n];
}
@Override
public String toString() {
// TODO Auto-generated method stub
return Arrays.toString(arr);
}
}
|
tianhengZhang/rtochius
|
lib/base/src/random.c
|
// SPDX-License-Identifier: GPL-2.0+
/*
* Simple xorshift PRNG
* see http://www.jstatsoft.org/v08/i14/paper
*
* Copyright (c) 2012 <NAME>
* <NAME> <<EMAIL>>
*/
#include <base/compiler.h>
#include <base/random.h>
static u64 y = 1;
static u64 random_r(u64 *seedp)
{
*seedp ^= (*seedp << 13);
*seedp ^= (*seedp >> 17);
*seedp ^= (*seedp << 5);
return *seedp;
}
u64 random(void)
{
return random_r(&y);
}
u64 random_range(u64 min, u64 max)
{
u64 temp;
if (unlikely(min > max))
return 0;
if (unlikely(min == max))
return min;
temp = max - min + 1;
return min + (random() % temp);
}
void srand(u64 seed)
{
y = seed;
}
|
791197071/arcgis-js-api
|
dijit/geoenrichment/ReportPlayer/core/conversion/portalToEditorUtils/parsers/MapParser.js
|
// COPYRIGHT © 201 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: <EMAIL>
//
// See http://js.arcgis.com/3.31/esri/copyright.txt for details.
define(["../../ConversionUtil","./AlignParser"],function(a,e){var t={getElement:function(t,n){var o=t.attributes,s={id:"map",isMap:!0,style:{top:a.ptToPx(o.top)||0,left:a.ptToPx(o.left)||0,width:a.ptToPx(o.width),height:a.ptToPx(o.height)}},p=n.templateJson.metadata.mapImageInfosHash[o.name];return s.webMapId=p?p.webMapId:o.webMapId,s.defaultBasemapId=p?p.defaultBasemapId:o.defaultBasemapId,s.mapScale=p?p.mapScale:null,s.calculatorFieldName=p&&p.fieldName,s.additionalLayerInfos=p&&p.additionalLayerInfos,s.pinSymbolJson=p&&p.pinSymbolJson,s.areaSymbolJsons=p&&p.areaSymbolJsons,s.areaSymbolRamp=p&&p.areaSymbolRamp,s.showMapLegend=o.showMapLegend,e.parseAlign(o,s.style),n.postProcessMapJson&&n.postProcessMapJson(t,s),s},parseMapImageDField:function(a,e){return t.getElement({name:"mapImage",attributes:{name:a}},e)}};return t});
|
igorsales/blekit
|
src/Classes/Ports/BLKI2CControlPort.h
|
<gh_stars>0
//
// BLKI2CControlPort.h
// BLEKit
//
// Created by <NAME> on 2014-10-03.
// Copyright (c) 2014 <EMAIL>. All rights reserved.
//
#import <BLEKit/BLKPort.h>
extern NSString* const kBLKPortTypeI2CControl;
@interface BLKI2CControlPort : BLKPort
@property (nonatomic, assign) BOOL useStopCondition;
- (void)readBytes:(NSInteger)length
fromSlaveAddress:(NSInteger)slaveAddress
andRegisterAddress:(NSInteger)regAddress
completion:(void(^)(NSData* data))completionBlock
failure:(void(^)(void))failureBlock;
- (void)writeBytes:(NSData*)data
toSlaveAddress:(NSInteger)slaveAddress
andRegisterAddress:(NSInteger)regAddress
completion:(void(^)(NSInteger written))completionBlock
failure:(void(^)(void))failureBlock;
@end
|
PieterSpruijt/Essentials
|
src/commands/info/mcname.js
|
const { MessageEmbed } = require('discord.js');
const axios = require('axios');
module.exports = {
name: "mcname",
description: "Get Minecraft user",
private: false,
commandOptions: [
{
type: 3,
name: `username`,
description: `The Minecraft username`,
required: true
}
],
run: async (bot, interaction, userinfo) => {
let username = interaction.data.options[0].value;
let url = `https://some-random-api.ml/mc?username=${encodeURIComponent(username)}`;
await axios
.get(url)
.catch(() => { return bot.error(`Something went wrong!`, bot, interaction) })
.then(async (embed) => {
if (!embed) return;
let { data } = embed;
if (data.error) return bot.error(`I can't find that user!`, bot, interaction);
let content = ``;
for (let i = 0; i < data.name_history.length; i++) {
if (i <= 9) {
if (data.name_history[i].changedToAt != `Original Name`) {
console.log(data)
content += `${data.name_history[i].name} - ${data.name_history[i].changedToAt}\n`
}
}
}
if (!content.length) { content = `No name history` }
let embed2 = new MessageEmbed()
.setTitle(`${username}'s profile`)
.addFields(
{ name: `Username:`, value: data.username },
{ name: `uuid:`, value: data.uuid },
{ name: `Names:`, value: content }
)
.setColor(userinfo.color);
await interaction.editReply({ embeds: [embed2] });
})
},
};
|
dasomel/egovframe-common-components
|
src/main/java/egovframework/com/uss/ion/rss/service/RssManage.java
|
<filename>src/main/java/egovframework/com/uss/ion/rss/service/RssManage.java
package egovframework.com.uss.ion.rss.service;
import java.io.Serializable;
import egovframework.com.cmm.ComDefaultVO;
/**
* RSS태그관리 Model and VO Class 구현
* @author 공통서비스 장동한
* @since 2010.06.16
* @version 1.0
* @see <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.07.03 장동한 최초 생성
*
* </pre>
*/
@SuppressWarnings("serial")
public class RssManage extends ComDefaultVO implements Serializable{
/** RSS태그관리 아이디 */
private String rssId;
/** 대상서비스명 */
private String trgetSvcNm;
/** 대상테이블명 */
private String trgetSvcTable;
/** 대상서비스목록갯수 */
private int trgetSvcListCo;
/** 헤더 TITLE */
private String hderTitle;
/** 헤더 LINK */
private String hderLink;
/** 헤더 DESCRIPTION */
private String hderDescription;
/** 헤더 TAG */
private String hderTag;
/** 헤더 ETC */
private String hderEtc;
/** 본문 TITLE */
private String bdtTitle;
/** 본문 LINK */
private String bdtLink;
/** 본문 DESCRIPTION */
private String bdtDescription;
/** 본문 TAG */
private String bdtTag;
/** 본문 ETC */
private String bdtEtc;
/** 최초등록시점 */
private String frstRegisterPnttm;
/** 최초등록아이디 */
private String frstRegisterId;
/** 최종수정일 */
private String lastUpdusrPnttm;
/** 최종수정자 아이디 */
private String lastUpdusrId;
/**
* @return the rssId
*/
public String getRssId() {
return rssId;
}
/**
* @param rssId the rssId to set
*/
public void setRssId(String rssId) {
this.rssId = rssId;
}
/**
* @return the trgetSvcNm
*/
public String getTrgetSvcNm() {
return trgetSvcNm;
}
/**
* @param trgetSvcNm the trgetSvcNm to set
*/
public void setTrgetSvcNm(String trgetSvcNm) {
this.trgetSvcNm = trgetSvcNm;
}
/**
* @return the trgetSvcTable
*/
public String getTrgetSvcTable() {
return trgetSvcTable;
}
/**
* @param trgetSvcTable the trgetSvcTable to set
*/
public void setTrgetSvcTable(String trgetSvcTable) {
this.trgetSvcTable = trgetSvcTable;
}
/**
* @return the trgetSvcListCo
*/
public int getTrgetSvcListCo() {
return trgetSvcListCo;
}
/**
* @param trgetSvcListCo the trgetSvcListCo to set
*/
public void setTrgetSvcListCo(int trgetSvcListCo) {
this.trgetSvcListCo = trgetSvcListCo;
}
/**
* @return the hderTitle
*/
public String getHderTitle() {
return hderTitle;
}
/**
* @param hderTitle the hderTitle to set
*/
public void setHderTitle(String hderTitle) {
this.hderTitle = hderTitle;
}
/**
* @return the hderLink
*/
public String getHderLink() {
return hderLink;
}
/**
* @param hderLink the hderLink to set
*/
public void setHderLink(String hderLink) {
this.hderLink = hderLink;
}
/**
* @return the hderDescription
*/
public String getHderDescription() {
return hderDescription;
}
/**
* @param hderDescription the hderDescription to set
*/
public void setHderDescription(String hderDescription) {
this.hderDescription = hderDescription;
}
/**
* @return the hderTag
*/
public String getHderTag() {
return hderTag;
}
/**
* @param hderTag the hderTag to set
*/
public void setHderTag(String hderTag) {
this.hderTag = hderTag;
}
/**
* @return the hderEtc
*/
public String getHderEtc() {
return hderEtc;
}
/**
* @param hderEtc the hderEtc to set
*/
public void setHderEtc(String hderEtc) {
this.hderEtc = hderEtc;
}
/**
* @return the bdtTitle
*/
public String getBdtTitle() {
return bdtTitle;
}
/**
* @param bdtTitle the bdtTitle to set
*/
public void setBdtTitle(String bdtTitle) {
this.bdtTitle = bdtTitle;
}
/**
* @return the bdtLink
*/
public String getBdtLink() {
return bdtLink;
}
/**
* @param bdtLink the bdtLink to set
*/
public void setBdtLink(String bdtLink) {
this.bdtLink = bdtLink;
}
/**
* @return the bdtDescription
*/
public String getBdtDescription() {
return bdtDescription;
}
/**
* @param bdtDescription the bdtDescription to set
*/
public void setBdtDescription(String bdtDescription) {
this.bdtDescription = bdtDescription;
}
/**
* @return the bdtTag
*/
public String getBdtTag() {
return bdtTag;
}
/**
* @param bdtTag the bdtTag to set
*/
public void setBdtTag(String bdtTag) {
this.bdtTag = bdtTag;
}
/**
* @return the bdtEtc
*/
public String getBdtEtc() {
return bdtEtc;
}
/**
* @param bdtEtc the bdtEtc to set
*/
public void setBdtEtc(String bdtEtc) {
this.bdtEtc = bdtEtc;
}
/**
* @return the frstRegisterPnttm
*/
public String getFrstRegisterPnttm() {
return frstRegisterPnttm;
}
/**
* @param frstRegisterPnttm the frstRegisterPnttm to set
*/
public void setFrstRegisterPnttm(String frstRegisterPnttm) {
this.frstRegisterPnttm = frstRegisterPnttm;
}
/**
* @return the frstRegisterId
*/
public String getFrstRegisterId() {
return frstRegisterId;
}
/**
* @param frstRegisterId the frstRegisterId to set
*/
public void setFrstRegisterId(String frstRegisterId) {
this.frstRegisterId = frstRegisterId;
}
/**
* @return the lastUpdusrPnttm
*/
public String getLastUpdusrPnttm() {
return lastUpdusrPnttm;
}
/**
* @param lastUpdusrPnttm the lastUpdusrPnttm to set
*/
public void setLastUpdusrPnttm(String lastUpdusrPnttm) {
this.lastUpdusrPnttm = lastUpdusrPnttm;
}
/**
* @return the lastUpdusrId
*/
public String getLastUpdusrId() {
return lastUpdusrId;
}
/**
* @param lastUpdusrId the lastUpdusrId to set
*/
public void setLastUpdusrId(String lastUpdusrId) {
this.lastUpdusrId = lastUpdusrId;
}
}
|
congthanh1910/next.js
|
test/integration/dynamic-optional-routing/pages/api/post/[[...slug]].js
|
<gh_stars>0
export default (req, res) => res.json({ slug: req.query.slug })
|
z669016/adventofcode-2019
|
src/main/java/com/putoet/day6/Day6.java
|
package com.putoet.day6;
import com.putoet.resources.ResourceLines;
public class Day6 {
public static void main(String[] args) {
final SpaceMap map = SpaceMapLoader.loadMap(ResourceLines.list("/day6.txt"));
part1(map);
part2(map);
}
private static void part1(SpaceMap map) {
System.out.println("Orbit count for the spacemap is " + map.orbits());
}
private static void part2(SpaceMap map) {
System.out.println("The distance from YOU to SAN is " + map.distance(map.get("YOU"), map.get("SAN")));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.